问:
How to sort the latitude and longitude points so that when creating a polygon, lines do not intersect
I am working in the google map to show 4 markers and a polygon to join these 4 markers as a marker but the code I have tried giving me some kind of two triangle polygon(the lines are cross connected). How can I fix the code so that these lines do not cross connect.

function initMap() {
  var beaches = [
    ["a", 40.4476, -83.0767],
    ["b", 40.3655, -83.0441],
    ["d", 40.5943, -83.0128],
    ["e", 40.5113, -82.6063]
  ];
  var triangleCoords = [{
      lat: 40.4476,
      lng: -83.0767,
      'name': 'n'
    },
    {
      lat: 40.3655,
      lng: -83.0441,
      'name': 'n'
    },
    {
      lat: 40.5943,
      lng: -83.0128,
      'name': 'n'
    },
    {
      lat: 40.5113,
      lng: -82.6063,
      'name': 'n'
    }
  ];

  function SortByName(x, y) {
    return ((x.name == y.name) ? 0 : ((x.name > y.name) ? 1 : -1));
  }
  triangleCoords.sort(SortByName);
  var polygroups = {};
  for (var i = 0; i < triangleCoords.length; i++) {
    var groupName = triangleCoords[i].name;
    if (!polygroups[groupName]) {
      polygroups[groupName] = [];
    }
    polygroups[groupName].push({
      lat: triangleCoords[i].lat,
      lng: triangleCoords[i].lng
    });
  }
  var markers = [];
  var map;
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 10,
    center: {
      lat: 40.5943,
      lng: -83.0128
    },
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });
  var marker, i;
  var shape = {
    coords: [1, 1, 1, 20, 18, 20, 18, 1],
    type: 'poly'
  };
  var count = 0;
  $.each(polygroups, function(i, value) {
    var users = {
      0: {
        color: '#f45942'
      },
      1: {
        color: '#f4df41'
      },
      2: {
        color: '#58f441'
      }
    }
    var bermudaTriangle = new google.maps.Polygon({
      paths: value,
      strokeColor: users[count].color,
      strokeOpacity: 0.8,
      strokeWeight: 4,
      fillColor: users[count].color,
      fillOpacity: 0.0
    });
    bermudaTriangle.setMap(map);
    count++;
  });

  for (i = 0; i < beaches.length; i++) {
    marker = new google.maps.Marker({
      position: new google.maps.LatLng(beaches[i][1], beaches[i][2]),
      map: map
    });
    markers.push(marker);
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#map {
  height: 100%;
}

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}</code>```

```

答:
You have listed them in the wrong order...

```<code>  var triangleCoords = [{
    lat: 40.4476,
    lng: -83.0767,
    'name': 'n'
  }, {
    lat: 40.3655,
    lng: -83.0441,
    'name': 'n'
  }, {
    lat: 40.5113,
    lng: -82.6063,
    'name': 'n'
  }, {
    lat: 40.5943,
    lng: -83.0128,
    'name': 'n'
  }];
</code>```

Gives you a square...

JSfiddle: https://jsfiddle.net/cmjcs5eL/20/

Body:
I am working in the google map to show 4 markers and a polygon to join these 4 markers as a marker but the code I have tried giving me some kind of two triangle polygon(the lines are cross connected). How can I fix the code so that these lines do not cross connect.

function initMap() {
  var beaches = [
    ["a", 40.4476, -83.0767],
    ["b", 40.3655, -83.0441],
    ["d", 40.5943, -83.0128],
    ["e", 40.5113, -82.6063]
  ];
  var triangleCoords = [{
      lat: 40.4476,
      lng: -83.0767,
      'name': 'n'
    },
    {
      lat: 40.3655,
      lng: -83.0441,
      'name': 'n'
    },
    {
      lat: 40.5943,
      lng: -83.0128,
      'name': 'n'
    },
    {
      lat: 40.5113,
      lng: -82.6063,
      'name': 'n'
    }
  ];

  function SortByName(x, y) {
    return ((x.name == y.name) ? 0 : ((x.name > y.name) ? 1 : -1));
  }
  triangleCoords.sort(SortByName);
  var polygroups = {};
  for (var i = 0; i < triangleCoords.length; i++) {
    var groupName = triangleCoords[i].name;
    if (!polygroups[groupName]) {
      polygroups[groupName] = [];
    }
    polygroups[groupName].push({
      lat: triangleCoords[i].lat,
      lng: triangleCoords[i].lng
    });
  }
  var markers = [];
  var map;
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 10,
    center: {
      lat: 40.5943,
      lng: -83.0128
    },
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });
  var marker, i;
  var shape = {
    coords: [1, 1, 1, 20, 18, 20, 18, 1],
    type: 'poly'
  };
  var count = 0;
  $.each(polygroups, function(i, value) {
    var users = {
      0: {
        color: '#f45942'
      },
      1: {
        color: '#f4df41'
      },
      2: {
        color: '#58f441'
      }
    }
    var bermudaTriangle = new google.maps.Polygon({
      paths: value,
      strokeColor: users[count].color,
      strokeOpacity: 0.8,
      strokeWeight: 4,
      fillColor: users[count].color,
      fillOpacity: 0.0
    });
    bermudaTriangle.setMap(map);
    count++;
  });

  for (i = 0; i < beaches.length; i++) {
    marker = new google.maps.Marker({
      position: new google.maps.LatLng(beaches[i][1], beaches[i][2]),
      map: map
    });
    markers.push(marker);
  }
}

#map {
  height: 100%;
}

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

Body:
You have listed them in the wrong order...

  var triangleCoords = [{
    lat: 40.4476,
    lng: -83.0767,
    'name': 'n'
  }, {
    lat: 40.3655,
    lng: -83.0441,
    'name': 'n'
  }, {
    lat: 40.5113,
    lng: -82.6063,
    'name': 'n'
  }, {
    lat: 40.5943,
    lng: -83.0128,
    'name': 'n'
  }];

Gives you a square...

JSfiddle: https://jsfiddle.net/cmjcs5eL/20/


来源: stackexchange

问:
how to throw a 403 error in Apache CXF - Java
I am using the following code based on having an interceptor. When check returns true I want to throw a 403 error:

```<code>    @Override
    public void handleMessage(Message arg0) throws Fault {

        HttpServletRequest request = context.getHttpServletRequest();
        if(check(request)){
        // currently not working
                throw "Fault";
        }
</code>```

I want to throw a 403 error. How do I go about doing that from this situation?

I am a little confused about how "throws fault" works.

Any help is appreciated

答:
Have you considered throwing:

```<code>throw new javax.ws.rs.ForbiddenException();
</code>```

It returns http 403.

ContentLicense: CC BY-SA 3.0

Body:
I am using the following code based on having an interceptor. When check returns true I want to throw a 403 error:

    @Override
    public void handleMessage(Message arg0) throws Fault {

        HttpServletRequest request = context.getHttpServletRequest();
        if(check(request)){
        // currently not working
                throw "Fault";
        }

I want to throw a 403 error. How do I go about doing that from this situation?

I am a little confused about how "throws fault" works.

Any help is appreciated

Body:
Have you considered throwing:

throw new javax.ws.rs.ForbiddenException();

It returns http 403.


问:
How to extend the renderTable width in Shiny flexdashboard
I have the following self containing Shiny-Flexdashboard:

```<code>---
title: "FOO"
runtime: shiny
output:
  flexdashboard::flex_dashboard:
    vertical_layout: scroll
    orientation: rows
    theme:   default

---

```{r setup, include=FALSE}
library(flexdashboard)
library(tidyverse)
```

Rows
-------------------------------------

### Statistical Test Summary
```{r stat_test_table}
mainPanel(

  renderTable( {
      dat <- df <- structure(list(`Sample name` = structure(1:3, .Label = c("Sample1",
          "Sample2", "Sample3"), class = "factor"), `FDR correction (mean)` = c(5.93070861978308e-15,
         6.88632524238004e-13, 3.28339498763286e-16), `FDR correction (sd)` = c(2.00046170407461e-14,
        2.32019633515427e-12, 1.10782095003689e-15), `P-value (mean)` = c(5.55365134900322e-15,
        6.44757191496266e-13, 3.07475941705412e-16), `P-value (sd)` = c(1.98732517127302e-14,
        2.30494707691577e-12, 1.10054774779699e-15)), class = c("tbl_df",
        "tbl", "data.frame"), .Names = c("Sample name", "FDR correction (mean)",
        "FDR correction (sd)", "P-value (mean)", "P-value (sd)"), row.names = c(NA,  -3L))
  }
  , digits=-2, width = '100%'
  )
)
```
</code>```

It produces table like this:

As stated there how can I extend the column width?

答:
Using width = 12 in mainPanel and enclosing table inside div did the trick.

```<code>---
title: "FOO"
runtime: shiny
output:
  flexdashboard::flex_dashboard:
    vertical_layout: scroll
    orientation: columns
    theme:   default

---

```{r setup, include=FALSE}
library(flexdashboard)
library(tidyverse)
```

Columns
-------------------------------------

### Statistical Test Summary
```{r stat_test_table}

mainPanel(width = 12,
  div(style="height:570px",
  renderTable( {
      dat <- df <- structure(list(`Sample name` = structure(1:3, .Label = c("Sample1",
          "Sample2", "Sample3"), class = "factor"), `FDR correction (mean)` = c(5.93070861978308e-15,
         6.88632524238004e-13, 3.28339498763286e-16), `FDR correction (sd)` = c(2.00046170407461e-14,
        2.32019633515427e-12, 1.10782095003689e-15), `P-value (mean)` = c(5.55365134900322e-15,
        6.44757191496266e-13, 3.07475941705412e-16), `P-value (sd)` = c(1.98732517127302e-14,
        2.30494707691577e-12, 1.10054774779699e-15)), class = c("tbl_df",
        "tbl", "data.frame"), .Names = c("Sample name", "FDR correction (mean)",
        "FDR correction (sd)", "P-value (mean)", "P-value (sd)"), row.names = c(NA,  -3L))
  }
  , digits=-2, width = '100%'
  ))
)
```
</code>```

It produces the output as :

Body:
I have the following self containing Shiny-Flexdashboard:

---
title: "FOO"
runtime: shiny
output:
  flexdashboard::flex_dashboard:
    vertical_layout: scroll
    orientation: rows
    theme:   default

---

```{r setup, include=FALSE}
library(flexdashboard)
library(tidyverse)
```

Rows
-------------------------------------

### Statistical Test Summary
```{r stat_test_table}
mainPanel(

  renderTable( {
      dat <- df <- structure(list(`Sample name` = structure(1:3, .Label = c("Sample1",
          "Sample2", "Sample3"), class = "factor"), `FDR correction (mean)` = c(5.93070861978308e-15,
         6.88632524238004e-13, 3.28339498763286e-16), `FDR correction (sd)` = c(2.00046170407461e-14,
        2.32019633515427e-12, 1.10782095003689e-15), `P-value (mean)` = c(5.55365134900322e-15,
        6.44757191496266e-13, 3.07475941705412e-16), `P-value (sd)` = c(1.98732517127302e-14,
        2.30494707691577e-12, 1.10054774779699e-15)), class = c("tbl_df",
        "tbl", "data.frame"), .Names = c("Sample name", "FDR correction (mean)",
        "FDR correction (sd)", "P-value (mean)", "P-value (sd)"), row.names = c(NA,  -3L))
  }
  , digits=-2, width = '100%'
  )
)
```

It produces table like this:

As stated there how can I extend the column width?

Body:
Using width = 12 in mainPanel and enclosing table inside div did the trick.

---
title: "FOO"
runtime: shiny
output:
  flexdashboard::flex_dashboard:
    vertical_layout: scroll
    orientation: columns
    theme:   default

---

```{r setup, include=FALSE}
library(flexdashboard)
library(tidyverse)
```

Columns
-------------------------------------

### Statistical Test Summary
```{r stat_test_table}

mainPanel(width = 12,
  div(style="height:570px",
  renderTable( {
      dat <- df <- structure(list(`Sample name` = structure(1:3, .Label = c("Sample1",
          "Sample2", "Sample3"), class = "factor"), `FDR correction (mean)` = c(5.93070861978308e-15,
         6.88632524238004e-13, 3.28339498763286e-16), `FDR correction (sd)` = c(2.00046170407461e-14,
        2.32019633515427e-12, 1.10782095003689e-15), `P-value (mean)` = c(5.55365134900322e-15,
        6.44757191496266e-13, 3.07475941705412e-16), `P-value (sd)` = c(1.98732517127302e-14,
        2.30494707691577e-12, 1.10054774779699e-15)), class = c("tbl_df",
        "tbl", "data.frame"), .Names = c("Sample name", "FDR correction (mean)",
        "FDR correction (sd)", "P-value (mean)", "P-value (sd)"), row.names = c(NA,  -3L))
  }
  , digits=-2, width = '100%'
  ))
)
```

It produces the output as :


问:
bootstrap - make the page non-responsive and show desktop version to all devices
I have currently a website that is responsive but since its not very good in mobiles and tablets I want to make it like desktop (.col-md-x) on all smaller devices. I use bootstrap 3.

so if the resolution is more than 1200px it should show large version (.col-lg-x) and if not, it should always show the desktop version (.col-md-x).

to do this I deleted the

<meta name="viewport" content="width=device-width, initial-scale=1">

tag from the page head tag and replaced it with

<meta name="viewport" content="width=1024">

that do the trick but the page was very very zoomed out. so I changed the bootstrap break points in bootstrap customization page so that col-xs-x and col-sm-x and col-md-x breaks on 1px page width, and col-lg-x on 1200px.

its better now but the sidebars and some other elements will hide on small devices and full page is not shown there. what I want is a complete page like desktop with horizontal and vertical scrollbars and no breaking and no hiding and no collapsing navbar and other things. how can I achieve this?

答:
use Media Queries for Standard Devices
You should include the following <meta> viewport element in all your web pages:

<meta name="viewport" content="width=device-width, initial-scale=1.0">
you can learn

https://css-tricks.com/snippets/css/media-queries-for-standard-devices/

https://www.w3schools.com/css/css_rwd_mediaqueries.asp

https://www.w3schools.com/css/css3_mediaqueries_ex.asp

example

```<code>/*==========  Mobile First Method  ==========*/

    /* Custom, iPhone Retina */
    @media only screen and (min-width : 320px) {

    }

    /* Extra Small Devices, Phones */
    @media only screen and (min-width : 480px) {

    }

    /* Small Devices, Tablets */
    @media only screen and (min-width : 768px) {

    }

    /* Medium Devices, Desktops */
    @media only screen and (min-width : 992px) {

    }

    /* Large Devices, Wide Screens */
    @media only screen and (min-width : 1200px) {

    }

    /*==========  Non-Mobile First Method  ==========*/

    /* Large Devices, Wide Screens */
    @media only screen and (max-width : 1200px) {

    }

    /* Medium Devices, Desktops */
    @media only screen and (max-width : 992px) {

    }

    /* Small Devices, Tablets */
    @media only screen and (max-width : 768px) {

    }

    /* Extra Small Devices, Phones */
    @media only screen and (max-width : 480px) {

    }

    /* Custom, iPhone Retina */
    @media only screen and (max-width : 320px) {

    }
</code>```

Body:
use Media Queries for Standard Devices
You should include the following <meta> viewport element in all your web pages:

<meta name="viewport" content="width=device-width, initial-scale=1.0">
you can learn

https://css-tricks.com/snippets/css/media-queries-for-standard-devices/

https://www.w3schools.com/css/css_rwd_mediaqueries.asp

https://www.w3schools.com/css/css3_mediaqueries_ex.asp

example

/*==========  Mobile First Method  ==========*/

    /* Custom, iPhone Retina */
    @media only screen and (min-width : 320px) {

    }

    /* Extra Small Devices, Phones */
    @media only screen and (min-width : 480px) {

    }

    /* Small Devices, Tablets */
    @media only screen and (min-width : 768px) {

    }

    /* Medium Devices, Desktops */
    @media only screen and (min-width : 992px) {

    }

    /* Large Devices, Wide Screens */
    @media only screen and (min-width : 1200px) {

    }

    /*==========  Non-Mobile First Method  ==========*/

    /* Large Devices, Wide Screens */
    @media only screen and (max-width : 1200px) {

    }

    /* Medium Devices, Desktops */
    @media only screen and (max-width : 992px) {

    }

    /* Small Devices, Tablets */
    @media only screen and (max-width : 768px) {

    }

    /* Extra Small Devices, Phones */
    @media only screen and (max-width : 480px) {

    }

    /* Custom, iPhone Retina */
    @media only screen and (max-width : 320px) {

    }


问:
Firebase database query from multiple childs
I have some question regarding Firebase database structure. I am not familiar with it as I just started to learn it couple days ago. Basically 1 account can have many receipts, 1 receipt can have many items of different types, 1 receipt for 1 store and 1 receipt for 1 currency.

I have came up with the database design as below:

```<code>receipts {
    accountID1 : {
        receiptID1 : {
            date:
            store: {
                storeName: store1
                storeAddr: addr1
            }
            currency: {
                currencyName: currency1
                currentcySymbol: $
            }
            totalAmount: 50.00
        }
        receiptID2 : { ... }
    }
    accountID2 : { ... }
},
itemlists {
    receiptID1: {
        items: {
            itemID1 : {
                type: food
                name: snack
                price: 10.00
                quantity: 2
            }
            itemID2 : { ... }
        }
    }
    receiptID2: { ... }
},
receiptIDsByStore {
    storeID1: {
        receiptID1: true
        receiptID2: true
    }
},
receiptIDsByCurrency {
    currencyID1: {
        receiptID1: true
        receiptID2: true
    }
},
stores {
    storeID1: {
        storeName: store1
        storeAddress: addr1
    }
},
currencies {
    currencyID1: {
        currencyName: currency1
        currencySymbol: $
    }
}
itemIDsByType {
food: {
    itemID1: true,
    itemID2: true,
}
entertainment: {
    itemID3: true,
    itemID4: true,
}
}
</code>```

So my question is:

Is there any redundancy mistake I made for the design above?

I can get the total amount of spend by each user from receipts, am I right? I can just query like receipts/accountID1 to get all the receipts then sum up the total amount.

How can I actually sum up the total spend by each user for each type of items? For instance, I wanted to find for food. So I query itemIDsByType/food, then get list of itemIDs, then from there query itemlists and check if receiptID is belonged to that particular account, it it is then get the unit price?

EDIT

```<code>receipts {
    accountID1 : {
        receiptID1 : {
            date : "07/07/2017"
            store : {
                storeName : "store1"
                storeAddr : "addr1"
            }
            currency : {
                currencyName : "currency1"
                currentcySymbol : "$"
            }
            totalAmount : "50.00"
            items : {
                itemID1 : true,
                itemID2 : true,
            }
        }
        receiptID2 : {
            date : "08/07/2017"
                store : {
                    storeName : "store1"
                    storeAddr : "addr1"
                }
                currency : {
                    currencyName : "currency1"
                    currentcySymbol : "$"
                }
                totalAmount : "20.00"
                items : {
                    itemID3 : true,
                    itemID4 : true,
                }
        }
    }

    accountID2 : {
        receiptID3 : {
                date : "08/07/2017"
                    store : {
                        storeName : "store2"
                        storeAddr : "addr2"
                    }
                    currency : {
                        currencyName : "currency1"
                        currentcySymbol : "$"
                    }
                    totalAmount : "100.00"
                    items : {
                        itemID5 : true,
                        itemID6 : true,
                    }
            }
    }
},
items {
        itemID1 : {
            type : "food"
            name : "snack"
            unitprice : "10.00"
            quantity : "2"
        }
        itemID2 : {
            type : "entertainment"
            name : "gaming equipment"
            unitprice : "150.00"
            quantity : "1"
        }
        itemID3 : {
            type : "food"
            name : "fruit juice"
            unitprice : "4.00"
            quantity : "1"
        }
        itemID4 : {
            type : "entertainment"
            name : "new year clothes"
            unitprice : "100.00"
            quantity : "1"
        }
        itemID5 : {
            type : "healthcare"
            name : "fever meds"
            unitprice : "100.00"
            quantity : "1"
        }
        itemID6 : {
            type : "healthcare"
            name : "flu meds"
            unitprice : "100.00"
            quantity : "1"
        }
},
receiptIDsByStore {
    storeID1 : {
        receiptID1 : true,
        receiptID2 : true,
    }
    storeID2 : {
        receiptID3 : true,
    }
},
receiptIDsByCurrency {
    currencyID1 : {
        receiptID1 : true,
        receiptID2 : true,
        receiptID3 : true,
    }
},
stores {
    storeID1 : {
        storeName : "store1"
        storeAddress : "addr1"
    }
    storeID2 : {
        storeName : "store2"
        storeAddress : "addr2"
    }
},
currencies {
    currencyID1 : {
        currencyName : "currency1"
        currencySymbol : "$"
    }
},
itemIDsByType {
    food : {
        itemID1 : true,
        itemID3 : true,
    }
    entertainment: {
        itemID2 : true,
        itemID4 : true,
    }
    healthcare : {
        itemID5 : true,
        itemID6 : true,
    }
}
</code>```

答:
Your database is very well structured. One thing you need to remeber when it comes to Firebase database structuring a is to have the data as flatten as possible and to make everything for the view. If you want to learn more about Firebase database structure i recomand you reading this posts: NOSQL DATA MODELING TECHNIQUES and Structuring your Firebase Data correctly for a Complex App.

Regarding your questions, as you you'll probably see in those posts, having the same data in different location is not a mistake, actually it's the opposite, it's ca ommon practice in Firebase. Yes, you can just query like receipts/accountID1 and get all the receipts. If you need a count, you can just simply use getChildrenCount() method directly on the DataSnapshot. Nested queries are not prohibited in Firebase. You can query once, to get those ids and second to get the desired data according to those ids.

Not at least, if you have a SQL background i recomand you watching this youtube tutorial sesries, The Firebase Database For SQL Developers.

Hope it helps.

ContentLicense: CC BY-SA 4.0

Body:
I have some question regarding Firebase database structure. I am not familiar with it as I just started to learn it couple days ago. Basically 1 account can have many receipts, 1 receipt can have many items of different types, 1 receipt for 1 store and 1 receipt for 1 currency.

I have came up with the database design as below:

receipts {
    accountID1 : {
        receiptID1 : {
            date:
            store: {
                storeName: store1
                storeAddr: addr1
            }
            currency: {
                currencyName: currency1
                currentcySymbol: $
            }
            totalAmount: 50.00
        }
        receiptID2 : { ... }
    }
    accountID2 : { ... }
},
itemlists {
    receiptID1: {
        items: {
            itemID1 : {
                type: food
                name: snack
                price: 10.00
                quantity: 2
            }
            itemID2 : { ... }
        }
    }
    receiptID2: { ... }
},
receiptIDsByStore {
    storeID1: {
        receiptID1: true
        receiptID2: true
    }
},
receiptIDsByCurrency {
    currencyID1: {
        receiptID1: true
        receiptID2: true
    }
},
stores {
    storeID1: {
        storeName: store1
        storeAddress: addr1
    }
},
currencies {
    currencyID1: {
        currencyName: currency1
        currencySymbol: $
    }
}
itemIDsByType {
food: {
    itemID1: true,
    itemID2: true,
}
entertainment: {
    itemID3: true,
    itemID4: true,
}
}

So my question is:

Is there any redundancy mistake I made for the design above?

I can get the total amount of spend by each user from receipts, am I right? I can just query like receipts/accountID1 to get all the receipts then sum up the total amount.

How can I actually sum up the total spend by each user for each type of items? For instance, I wanted to find for food. So I query itemIDsByType/food, then get list of itemIDs, then from there query itemlists and check if receiptID is belonged to that particular account, it it is then get the unit price?

EDIT

receipts {
    accountID1 : {
        receiptID1 : {
            date : "07/07/2017"
            store : {
                storeName : "store1"
                storeAddr : "addr1"
            }
            currency : {
                currencyName : "currency1"
                currentcySymbol : "$"
            }
            totalAmount : "50.00"
            items : {
                itemID1 : true,
                itemID2 : true,
            }
        }
        receiptID2 : {
            date : "08/07/2017"
                store : {
                    storeName : "store1"
                    storeAddr : "addr1"
                }
                currency : {
                    currencyName : "currency1"
                    currentcySymbol : "$"
                }
                totalAmount : "20.00"
                items : {
                    itemID3 : true,
                    itemID4 : true,
                }
        }
    }

    accountID2 : {
        receiptID3 : {
                date : "08/07/2017"
                    store : {
                        storeName : "store2"
                        storeAddr : "addr2"
                    }
                    currency : {
                        currencyName : "currency1"
                        currentcySymbol : "$"
                    }
                    totalAmount : "100.00"
                    items : {
                        itemID5 : true,
                        itemID6 : true,
                    }
            }
    }
},
items {
        itemID1 : {
            type : "food"
            name : "snack"
            unitprice : "10.00"
            quantity : "2"
        }
        itemID2 : {
            type : "entertainment"
            name : "gaming equipment"
            unitprice : "150.00"
            quantity : "1"
        }
        itemID3 : {
            type : "food"
            name : "fruit juice"
            unitprice : "4.00"
            quantity : "1"
        }
        itemID4 : {
            type : "entertainment"
            name : "new year clothes"
            unitprice : "100.00"
            quantity : "1"
        }
        itemID5 : {
            type : "healthcare"
            name : "fever meds"
            unitprice : "100.00"
            quantity : "1"
        }
        itemID6 : {
            type : "healthcare"
            name : "flu meds"
            unitprice : "100.00"
            quantity : "1"
        }
},
receiptIDsByStore {
    storeID1 : {
        receiptID1 : true,
        receiptID2 : true,
    }
    storeID2 : {
        receiptID3 : true,
    }
},
receiptIDsByCurrency {
    currencyID1 : {
        receiptID1 : true,
        receiptID2 : true,
        receiptID3 : true,
    }
},
stores {
    storeID1 : {
        storeName : "store1"
        storeAddress : "addr1"
    }
    storeID2 : {
        storeName : "store2"
        storeAddress : "addr2"
    }
},
currencies {
    currencyID1 : {
        currencyName : "currency1"
        currencySymbol : "$"
    }
},
itemIDsByType {
    food : {
        itemID1 : true,
        itemID3 : true,
    }
    entertainment: {
        itemID2 : true,
        itemID4 : true,
    }
    healthcare : {
        itemID5 : true,
        itemID6 : true,
    }
}


问:
Pywinauto taking long time for operations
I'm having troubles with automating filtering in a certain window of a program, that i'm working on. A window consists of listview, few comboboxes and few edits. When i select certain position in the combobox2 and click "filter", then listview shows results matching with that checkbox.
  But here i have problem. After clicking filter manually, program loads results for a short time (~2 seconds), but if i do it with pywinauto, then it takes up to ~10 seconds before it moves to another function which should select another position in the combobox. (even then i can click it manualy and it works fine, so it's 100% not problem with the program)

Here's example of a code which causes troubles.

```<code>user_count = 0
while user_count < 5:
    self.app[kkvat].ComboBox2.Select(user_count)
    self.app[kkvat].Filter.Click()
    user_count += 1
</code>```

The problems shows up exactly at the second loop when the 2 position of combobox should be selected.

Sorry for my language, not native :(

答: The bug with timings is fixed in pywinauto 0.6.3. Please update it with pip install -U pywinauto and try your case again.

Body:
I'm having troubles with automating filtering in a certain window of a program, that i'm working on. A window consists of listview, few comboboxes and few edits. When i select certain position in the combobox2 and click "filter", then listview shows results matching with that checkbox.
  But here i have problem. After clicking filter manually, program loads results for a short time (~2 seconds), but if i do it with pywinauto, then it takes up to ~10 seconds before it moves to another function which should select another position in the combobox. (even then i can click it manualy and it works fine, so it's 100% not problem with the program)

Here's example of a code which causes troubles.

user_count = 0
while user_count < 5:
    self.app[kkvat].ComboBox2.Select(user_count)
    self.app[kkvat].Filter.Click()
    user_count += 1

The problems shows up exactly at the second loop when the 2 position of combobox should be selected.

Sorry for my language, not native :(


问:
"unable to locate Spring NamespaceHandler" error
I'm creating a stand-alone Sava application with Spring, to handle the JDBC access. The application works fine on every test and I decided that I need a jar to be deployed our clients.

They might not have spring in their classpath, so I used maven-assembly-plugin to handle the jar creation with dependencies.

However when I try to run the application:

```<code>java -jar target/myproject-0.0.1-SNAPSHOT-jar-with-dependencies.jar
</code>```

Which throws the following error:

```<code>Exception in thread "main" org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/p]
Offending resource: class path resource [applicationContext.xml]

at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68)
at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85)
at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:80)
...and so on to the database access class of this project.
</code>```

The applicationContext.xml file is in projectbase/src/main/resources. And its placed at target/packagename base.

The applicationContext.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:p="http://www.springframework.org/schema/p"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean id="dataSourceDesenv" class="org.apache.commons.dbcp.BasicDataSource"... />

    <bean id="simpleJdbcDaoSupport" class="org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport"
      p:dataSource-ref="dataSourceDesenv" />

    <bean id="simpleJdbcTemplate" class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
        <constructor-arg ref="dataSourceDesenv" />
    </bean>

</beans>
</code>```

答:
In addition to the solution posted by @GrampaJohn, I also had to make sure that I was packaging the required libraries into the generated JAR file instead of extracting them into the generated JAR.

In Eclipse Mars, after making changes to the pom.xml (added maven-shade plugin as suggested by @GrampaJohn), follow the steps:

File -> Export -> Select Java folder -> Runnable JAR File -> enter
  the Launch configuration (main file), export destination, and in
  Library Handling, select "Package required Libraries into generated
  JAR -> Click finish

.

Body:
I'm creating a stand-alone Sava application with Spring, to handle the JDBC access. The application works fine on every test and I decided that I need a jar to be deployed our clients.

They might not have spring in their classpath, so I used maven-assembly-plugin to handle the jar creation with dependencies.

However when I try to run the application:

java -jar target/myproject-0.0.1-SNAPSHOT-jar-with-dependencies.jar

Which throws the following error:

Exception in thread "main" org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/p]
Offending resource: class path resource [applicationContext.xml]

at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68)
at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85)
at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:80)
...and so on to the database access class of this project.

The applicationContext.xml file is in projectbase/src/main/resources. And its placed at target/packagename base.

The applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:p="http://www.springframework.org/schema/p"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean id="dataSourceDesenv" class="org.apache.commons.dbcp.BasicDataSource"... />

    <bean id="simpleJdbcDaoSupport" class="org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport"
      p:dataSource-ref="dataSourceDesenv" />

    <bean id="simpleJdbcTemplate" class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
        <constructor-arg ref="dataSourceDesenv" />
    </bean>

</beans>


问:
SetWindowPos() sometimes does not resize child-windows
First, I use Createprocess() to open all desired windows. (Not Listed)

After the successful opening of the processes I find with the FindWindow () and FindWindowEx() all available windows. (Listed)

Sometimes the function SetWindowPos() does not work properly. A few windows were sorted out a few not. But this case does not always occur!

For improvements I always have an open ear!

```<code>    //Some Variables comming from other code : numberOfWindows / numberOfStartedWindows
//Variables
        bool trigger = true;
        bool targetProcess = true;
        HWND hwnd, hwndChilds = NULL;
        int targetsFound = 0;
        int targetsFoundMath = 0;
        bool searchWindows = true;

        //Start targetProcess
        while (targetProcess) {

            //If targetsFround == numberOfWindows then exit targetProcess.
            if (targetsFound == numberOfWindows)
            {
                targetProcess = false;
            }

            //If all Windows are Started then start search loop
            if (numberOfStartedWindows == numberOfWindows)
            {
                trigger = false;
            }

            //We starting search loop...
            if (!trigger && targetProcess) {

                //Find the Main Window.
                hwnd = FindWindow(0, _T("World of Warcraft"));
                if (hwnd)
                {
                    targetsFound += 1;

                    //Set Window Foreground and call SetWindowPos to change Position
                    if (SetForegroundWindow(hwnd)) {
                        if (!SetWindowPos(hwnd, HWND_TOP, 0, 0, 1920, 800, SWP_SHOWWINDOW))
                        {
                            cout << "Error: HWND Failed with SETWINDOWPOS" << endl;
                        }
                    }
                    //Store HWND in StoreWindows
                    StoreWindows.emplace_back(hwnd);

                    //Now we search for child Windows
                    while (searchWindows)
                    {

                        //do it if targetsFound not numberOfWindows
                        if (targetsFound != numberOfWindows)
                        {
                            //Get Child Window
                            hwndChilds = FindWindowEx(NULL, hwnd, NULL, _T("World of Warcraft"));
                            if (hwndChilds != NULL)
                            {

                                //Little Math for Position
                                targetsFoundMath = (targetsFound - 1) * 384;

                                //if window in foreground SetWindowPos.
                                if(SetForegroundWindow(hwndChilds)){
                                    if (!SetWindowPos(hwndChilds, HWND_TOP, targetsFoundMath, 800, 384, 280, SWP_SHOWWINDOW))
                                    {
                                        cout << "Error: HWNDChilds Failed with SETWINDOWPOS" << endl;
                                    }
                                }

                                /*targetsFound += 1;
                                StoreWindows.emplace_back(hwndChilds);*/

                                //If all targetsFound then quit this loop after finish
                                if (targetsFound == numberOfWindows) {
                                    searchWindows = false;
                                    cout << "false" << targetsFound << endl;
                                }

                                //StoreChild Window and Add targetsfround +1
                                targetsFound += 1;
                                StoreWindows.emplace_back(hwndChilds);
                            }
                            else {
                                searchWindows = false;
                                cout << "no more child objects found!" << endl;
                            }
                        }
                        else
                        {
                            searchWindows = false;
                        }
                    }
                }
            }
        }
        cout << "Window Size: " << StoreWindows.size() << endl;
</code>```

Funny when I debugs:

```<code>RECT debugRect;
for (int x = 0; x < StoreWindows.size(); x++)
{
    GetClientRect(StoreWindows[x], &debugRect);

    cout << debugRect.left << " " << debugRect.right<< " " << debugRect.bottom<< " " << debugRect.top << endl;
    //debugRect.right = breite vom fenster // debugRect.bottom = Höhe
}
</code>```

The output from the Position looks good but the Window isnt on the right place :/
Debug:

Im out of ideas and hope you can help me! If you need more explanations, do not hesitate to ask.

With problems it looks so..

If everything goes without problems it looks like this:

答:
The problem was the duplicate (same) window partial to be found. Because the start process takes longer than the Find Func. Now i have Fixxed the loop. (Its wait now for all success windows.)</p>

```<code>bool mainWindow = false;
    bool searchHwndStrike = false;
    int targetResult = 0;
    while (true)
    {
        //Search first Window
        if (!mainWindow) {
            hwnd = FindWindow(0, _T("World of Warcraft"));
            if (hwnd != NULL)
            {

                if (SetForegroundWindow(hwnd)) {
                    if (!SetWindowPos(hwnd, HWND_TOP, 0, 0, 1920, 800, SWP_SHOWWINDOW))
                    {
                        cout << "Error: HWND Failed with SETWINDOWPOS" << endl;
                    }
                }

                cout << "Main window found." << endl;
                mainWindow = true;
                StoreWindows.emplace_back(hwnd);
            }
        }else {

            if (StoreWindows.size() < numberOfWindows) {
                hwnd = FindWindowEx(NULL, hwnd, NULL, _T("World of Warcraft"));
                if (hwnd != NULL)
                {
                    for (int x = 0; x < StoreWindows.size(); x++)
                    {
                        if (StoreWindows[x] == hwnd)
                        {
                            searchHwndStrike = true;
                        }
                    }
                    if (!searchHwndStrike)
                    {
                        cout << "Child window found." << endl;
                        cout << targetResult << endl;
                        targetResult = (StoreWindows.size()-1) * 384;

                        //if window in foreground SetWindowPos.
                        if (SetForegroundWindow(hwnd)) {
                            if (!SetWindowPos(hwnd, HWND_TOP, targetResult, 800, 384, 280, SWP_SHOWWINDOW))
                            {
                                cout << "Error: HWNDChilds Failed with SETWINDOWPOS" << endl;
                            }
                        }
                        StoreWindows.emplace_back(hwnd);

                    }
                    searchHwndStrike = false;
                }
            }
            else {
                break;
            }
        }
    }
    cout << StoreWindows.size() << endl;
</code>```

Body:
First, I use Createprocess() to open all desired windows. (Not Listed)

After the successful opening of the processes I find with the FindWindow () and FindWindowEx() all available windows. (Listed)

Sometimes the function SetWindowPos() does not work properly. A few windows were sorted out a few not. But this case does not always occur!

For improvements I always have an open ear!

    //Some Variables comming from other code : numberOfWindows / numberOfStartedWindows
//Variables
        bool trigger = true;
        bool targetProcess = true;
        HWND hwnd, hwndChilds = NULL;
        int targetsFound = 0;
        int targetsFoundMath = 0;
        bool searchWindows = true;

        //Start targetProcess
        while (targetProcess) {

            //If targetsFround == numberOfWindows then exit targetProcess.
            if (targetsFound == numberOfWindows)
            {
                targetProcess = false;
            }

            //If all Windows are Started then start search loop
            if (numberOfStartedWindows == numberOfWindows)
            {
                trigger = false;
            }

            //We starting search loop...
            if (!trigger && targetProcess) {

                //Find the Main Window.
                hwnd = FindWindow(0, _T("World of Warcraft"));
                if (hwnd)
                {
                    targetsFound += 1;

                    //Set Window Foreground and call SetWindowPos to change Position
                    if (SetForegroundWindow(hwnd)) {
                        if (!SetWindowPos(hwnd, HWND_TOP, 0, 0, 1920, 800, SWP_SHOWWINDOW))
                        {
                            cout << "Error: HWND Failed with SETWINDOWPOS" << endl;
                        }
                    }
                    //Store HWND in StoreWindows
                    StoreWindows.emplace_back(hwnd);

                    //Now we search for child Windows
                    while (searchWindows)
                    {

                        //do it if targetsFound not numberOfWindows
                        if (targetsFound != numberOfWindows)
                        {
                            //Get Child Window
                            hwndChilds = FindWindowEx(NULL, hwnd, NULL, _T("World of Warcraft"));
                            if (hwndChilds != NULL)
                            {

                                //Little Math for Position
                                targetsFoundMath = (targetsFound - 1) * 384;

                                //if window in foreground SetWindowPos.
                                if(SetForegroundWindow(hwndChilds)){
                                    if (!SetWindowPos(hwndChilds, HWND_TOP, targetsFoundMath, 800, 384, 280, SWP_SHOWWINDOW))
                                    {
                                        cout << "Error: HWNDChilds Failed with SETWINDOWPOS" << endl;
                                    }
                                }

                                /*targetsFound += 1;
                                StoreWindows.emplace_back(hwndChilds);*/

                                //If all targetsFound then quit this loop after finish
                                if (targetsFound == numberOfWindows) {
                                    searchWindows = false;
                                    cout << "false" << targetsFound << endl;
                                }

                                //StoreChild Window and Add targetsfround +1
                                targetsFound += 1;
                                StoreWindows.emplace_back(hwndChilds);
                            }
                            else {
                                searchWindows = false;
                                cout << "no more child objects found!" << endl;
                            }
                        }
                        else
                        {
                            searchWindows = false;
                        }
                    }
                }
            }
        }
        cout << "Window Size: " << StoreWindows.size() << endl;

Funny when I debugs:

RECT debugRect;
for (int x = 0; x < StoreWindows.size(); x++)
{
    GetClientRect(StoreWindows[x], &debugRect);

    cout << debugRect.left << " " << debugRect.right<< " " << debugRect.bottom<< " " << debugRect.top << endl;
    //debugRect.right = breite vom fenster // debugRect.bottom = Höhe
}

The output from the Position looks good but the Window isnt on the right place :/
Debug:

Im out of ideas and hope you can help me! If you need more explanations, do not hesitate to ask.

With problems it looks so..

If everything goes without problems it looks like this:

Body:
The problem was the duplicate (same) window partial to be found. Because the start process takes longer than the Find Func. Now i have Fixxed the loop. (Its wait now for all success windows.)

bool mainWindow = false;
    bool searchHwndStrike = false;
    int targetResult = 0;
    while (true)
    {
        //Search first Window
        if (!mainWindow) {
            hwnd = FindWindow(0, _T("World of Warcraft"));
            if (hwnd != NULL)
            {

                if (SetForegroundWindow(hwnd)) {
                    if (!SetWindowPos(hwnd, HWND_TOP, 0, 0, 1920, 800, SWP_SHOWWINDOW))
                    {
                        cout << "Error: HWND Failed with SETWINDOWPOS" << endl;
                    }
                }

                cout << "Main window found." << endl;
                mainWindow = true;
                StoreWindows.emplace_back(hwnd);
            }
        }else {

            if (StoreWindows.size() < numberOfWindows) {
                hwnd = FindWindowEx(NULL, hwnd, NULL, _T("World of Warcraft"));
                if (hwnd != NULL)
                {
                    for (int x = 0; x < StoreWindows.size(); x++)
                    {
                        if (StoreWindows[x] == hwnd)
                        {
                            searchHwndStrike = true;
                        }
                    }
                    if (!searchHwndStrike)
                    {
                        cout << "Child window found." << endl;
                        cout << targetResult << endl;
                        targetResult = (StoreWindows.size()-1) * 384;

                        //if window in foreground SetWindowPos.
                        if (SetForegroundWindow(hwnd)) {
                            if (!SetWindowPos(hwnd, HWND_TOP, targetResult, 800, 384, 280, SWP_SHOWWINDOW))
                            {
                                cout << "Error: HWNDChilds Failed with SETWINDOWPOS" << endl;
                            }
                        }
                        StoreWindows.emplace_back(hwnd);

                    }
                    searchHwndStrike = false;
                }
            }
            else {
                break;
            }
        }
    }
    cout << StoreWindows.size() << endl;


问:
How to rename properties of objects in array in javascript?
I have this javascript objects:

```<code>var arr = [{id:'124',name:'qqq'},
           {id:'589',name:'www'},
           {id:'45',name:'eee'},
           {id:'567',name:'rrr'}]
</code>```

I need to rename properties with name in arr1 to title:

```<code>var arr = [{id:'124',title:'qqq'},
           {id:'589',title:'www'},
           {id:'45',title:'eee'},
           {id:'567',title:'rrr'}]
</code>```

What is elegant way to implement it in Javascript?

答:
Use delete to remove a property from an object.
Use obj['newProperty'] to assign newProperty to an object.

var arr = [{id:'124',name:'qqq'},
           {id:'589',name:'www'},
           {id:'45',name:'eee'},
           {id:'567',name:'rrr'}];

arr.forEach( function(data) {
  data['title'] = data['name'];
  delete data['name'];
});

console.log(arr);```
</div>
</div>
</p>

<p>You can also use <code>array#map</code></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const arr = [{ id: '124', name: 'qqq' }, { id: '589', name: 'www' }, { id: '45', name: 'eee' }, { id: '567', name: 'rrr' } ],
      result = arr.map(({name, ...rest}) => ({...rest, title: name}));
console.log(result);</code>```

Body:
I have this javascript objects:

var arr = [{id:'124',name:'qqq'},
           {id:'589',name:'www'},
           {id:'45',name:'eee'},
           {id:'567',name:'rrr'}]

I need to rename properties with name in arr1 to title:

var arr = [{id:'124',title:'qqq'},
           {id:'589',title:'www'},
           {id:'45',title:'eee'},
           {id:'567',title:'rrr'}]

What is elegant way to implement it in Javascript?

Body:
Use delete to remove a property from an object.
Use obj['newProperty'] to assign newProperty to an object.

var arr = [{id:'124',name:'qqq'},
           {id:'589',name:'www'},
           {id:'45',name:'eee'},
           {id:'567',name:'rrr'}];

arr.forEach( function(data) {
  data['title'] = data['name'];
  delete data['name'];
});

console.log(arr);

You can also use array#map

const arr = [{ id: '124', name: 'qqq' }, { id: '589', name: 'www' }, { id: '45', name: 'eee' }, { id: '567', name: 'rrr' } ],
      result = arr.map(({name, ...rest}) => ({...rest, title: name}));
console.log(result);


答:
Use map :

var arr = [{
    id: '124',
    name: 'qqq'
  },
  {
    id: '589',
    name: 'www'
  },
  {
    id: '45',
    name: 'eee'
  },
  {
    id: '567',
    name: 'rrr'
  }
]

arr = arr.map((e) => {
  return {
    id: e.id,
    title: e.name
  }
});

console.log(arr);```

Title: How to rename properties of objects in array in javascript?


问:
C# How many times should I raise the PropertyChanged event
Say I have a method that removes a single child from a parent object and raises a PropertyChanged event to indicate that the list of children as changed. Now say that I have a second method that can delete multiple children in one call and that makes use of the first method in order not to write a piece of code a second time. In this case, should I let the second method call the first one N times and raise the PropertyChanged event N times, or should I only raise the event a single time at the end of my second method ? Thank you.</p>

答:
As a consumer of your component I would expect that the PropertyChanged event was raised only once per call I made, whether ultimately that call resulted in one or multiple items to be removed.

As you have stated in your comment, I may be doing complex or relatively long-running processing when I handle the changed event. If I am iterating and doing something with the remaining items and there are a lot of them (hundreds? Thousands?) then having to do that multiple times instead of just once could very quickly snowball and potentially become a serious performance problem.


问:
Removing duplicate string values in 2d array not working
I know this question has been asked many times before, however I am a complete beginner to C arrays and would like to avoid using pointers (if possible) and keep it as simple as possible.
I have used the input from the user for a char array and would like to remove any duplicate string values in my program

```<code>#include<string.h>
#include<stdio.h>

int main(){
    int N, i, j, k;
        int flag=1;
    scanf("%d", &N);
    if(1<=N<=10^6){
    char a[N][5];
        for(i=0; i<N; i++){
            scanf("%s", &a[i]);
        }
        for(i=0; i<N; i++){
            for(j=i+1;j<N;){
                if(strcmp(a[i],a[j])==0){
                    for(k=j+1; k<N; k++){
                        memcpy(a[k], a[k+1], 5);
                    }
                    N--;
                }else{
                    j++;
                }
            }
        }
        for(i=0; i<N; i++){
            printf("%s\n", a[i]);
        }
    }
    return 0;
}
</code>```

An input of 3 and {"abc", "abc", "as"} returns the value only {"abc"}.
I would like to get the array as {"abc", "as"}. I cannot understand where in the code or logic, I have gone wrong.

Update

I changed the code as mentioned below however for larger examples it is concatenating the strings

```<code>#include<string.h>
#include<stdio.h>

int main(){
    int N, i, j, k;

    scanf("%d", &N);
    if(1 <= N && N <= 1000000){
    char a[N][5];
        for(i=0; i<N; i++){
            scanf("%5s", a[i]);
        }
        for(i=0; i<N; i++){
            for(j=i+1;j<N;){
                if(strcmp(a[i],a[j])==0){
                    for(k=j+1; k<N; k++){
                        strcpy(a[k-1], a[k]);
                    }
                    N--;
                }else{
                    j++;
                }
            }
        }
        printf("%d\n", N);
        for(i=0; i<N; i++){
            printf("%s\n", a[i]);
        }
    }
    return 0;
}
</code>```

答:
Here's a description of all your errors in the comments:

```<code>#include<string.h>
#include<stdio.h>

int main(){
    int N, i, j, k;

    // check the return value!
    if (scanf("%d", &N) != 1) return 1;

    // if(1<=N<=10^6){
    // this is completely wrong:
    // 1. ^ doesn't mean "power" but bitwise exclusive or
    // 2. 1<=N evaluates to 0 (false) or 1 (true), this is ALWAYS <= 10
    // 3. so you have finally 1^6 = 7 -- ALWAYS true as a boolean
    //
    // what you want is:
    if(1 <= N && N <= 1000000){

        char a[N][5];
        for(i=0; i<N; i++){
            // scanf("%s", &a[i]);
            // at least limit the number of characters read (one less
            // than your buffer size because there's a 0 byte added)
            // then, taking a *pointer* of an array is wrong, the array
            // already decays as a pointer, so leave out the `&`
            scanf("%4s", a[i]);
        }
        for(i=0; i<N; i++){
            for(j=i+1;j<N;){
                if(strcmp(a[i],a[j])==0){
                    for (k=j+1; k<N; k++){
                        // memcpy(a[k], a[k+1], 6);
                        // two errors here:
                        // 1. You only have 5 bytes per element, so copy only 5
                        // 2. this is *off by one* for the array index
                        // correct version:
                        memcpy(a[k-1], a[k], 5);
                        // (or use strcpy())
                    }
                    N--;
                }else{
                    j++;
                }
            }
        }
        for(i=0; i<N; i++){
            printf("%s\n", a[i]);
        }
    }
    return 0;
}
</code>```

In general, always enable compiler warnings. Your compiler would have spotted most of these bugs for you, see what happens when you compile your original code with gcc and warnings enabled:

$ gcc -std=c11 -Wall -Wextra -pedantic -o2darr 2darr.c
2darr.c: In function 'main':
2darr.c:8:12: warning: comparison of constant '10' with boolean expression is always true [-Wbool-compare]
     if(1<=N<=10^6){
            ^~
2darr.c:8:9: warning: comparisons like 'X<=Y<=Z' do not have their mathematical meaning [-Wparentheses]
     if(1<=N<=10^6){
        ~^~~
2darr.c:8:12: warning: suggest parentheses around comparison in operand of '^' [-Wparentheses]
     if(1<=N<=10^6){
        ~~~~^~~~
2darr.c:11:21: warning: format '%s' expects argument of type 'char *', but argument 2 has type 'char (*)[5]' [-Wformat=]
             scanf("%s", &a[i]);
                     ^
2darr.c:11:21: warning: format '%s' expects argument of type 'char *', but argument 2 has type 'char (*)[5]' [-Wformat=]
2darr.c:6:13: warning: unused variable 'flag' [-Wunused-variable]
         int flag=1;
             ^~~~
```

Body:
I know this question has been asked many times before, however I am a complete beginner to C arrays and would like to avoid using pointers (if possible) and keep it as simple as possible.
I have used the input from the user for a char array and would like to remove any duplicate string values in my program

#include<string.h>
#include<stdio.h>

int main(){
    int N, i, j, k;
        int flag=1;
    scanf("%d", &N);
    if(1<=N<=10^6){
    char a[N][5];
        for(i=0; i<N; i++){
            scanf("%s", &a[i]);
        }
        for(i=0; i<N; i++){
            for(j=i+1;j<N;){
                if(strcmp(a[i],a[j])==0){
                    for(k=j+1; k<N; k++){
                        memcpy(a[k], a[k+1], 5);
                    }
                    N--;
                }else{
                    j++;
                }
            }
        }
        for(i=0; i<N; i++){
            printf("%s\n", a[i]);
        }
    }
    return 0;
}

An input of 3 and {"abc", "abc", "as"} returns the value only {"abc"}.
I would like to get the array as {"abc", "as"}. I cannot understand where in the code or logic, I have gone wrong.

Update

I changed the code as mentioned below however for larger examples it is concatenating the strings

#include<string.h>
#include<stdio.h>

int main(){
    int N, i, j, k;

    scanf("%d", &N);
    if(1 <= N && N <= 1000000){
    char a[N][5];
        for(i=0; i<N; i++){
            scanf("%5s", a[i]);
        }
        for(i=0; i<N; i++){
            for(j=i+1;j<N;){
                if(strcmp(a[i],a[j])==0){
                    for(k=j+1; k<N; k++){
                        strcpy(a[k-1], a[k]);
                    }
                    N--;
                }else{
                    j++;
                }
            }
        }
        printf("%d\n", N);
        for(i=0; i<N; i++){
            printf("%s\n", a[i]);
        }
    }
    return 0;
}

Body:
Here's a description of all your errors in the comments:

#include<string.h>
#include<stdio.h>

int main(){
    int N, i, j, k;

    // check the return value!
    if (scanf("%d", &N) != 1) return 1;

    // if(1<=N<=10^6){
    // this is completely wrong:
    // 1. ^ doesn't mean "power" but bitwise exclusive or
    // 2. 1<=N evaluates to 0 (false) or 1 (true), this is ALWAYS <= 10
    // 3. so you have finally 1^6 = 7 -- ALWAYS true as a boolean
    //
    // what you want is:
    if(1 <= N && N <= 1000000){

        char a[N][5];
        for(i=0; i<N; i++){
            // scanf("%s", &a[i]);
            // at least limit the number of characters read (one less
            // than your buffer size because there's a 0 byte added)
            // then, taking a *pointer* of an array is wrong, the array
            // already decays as a pointer, so leave out the `&`
            scanf("%4s", a[i]);
        }
        for(i=0; i<N; i++){
            for(j=i+1;j<N;){
                if(strcmp(a[i],a[j])==0){
                    for (k=j+1; k<N; k++){
                        // memcpy(a[k], a[k+1], 6);
                        // two errors here:
                        // 1. You only have 5 bytes per element, so copy only 5
                        // 2. this is *off by one* for the array index
                        // correct version:
                        memcpy(a[k-1], a[k], 5);
                        // (or use strcpy())
                    }
                    N--;
                }else{
                    j++;
                }
            }
        }
        for(i=0; i<N; i++){
            printf("%s\n", a[i]);
        }
    }
    return 0;
}

In general, always enable compiler warnings. Your compiler would have spotted most of these bugs for you, see what happens when you compile your original code with gcc and warnings enabled:

$ gcc -std=c11 -Wall -Wextra -pedantic -o2darr 2darr.c
2darr.c: In function 'main':
2darr.c:8:12: warning: comparison of constant '10' with boolean expression is always true [-Wbool-compare]
     if(1<=N<=10^6){
            ^~
2darr.c:8:9: warning: comparisons like 'X<=Y<=Z' do not have their mathematical meaning [-Wparentheses]
     if(1<=N<=10^6){
        ~^~~
2darr.c:8:12: warning: suggest parentheses around comparison in operand of '^' [-Wparentheses]
     if(1<=N<=10^6){
        ~~~~^~~~
2darr.c:11:21: warning: format '%s' expects argument of type 'char *', but argument 2 has type 'char (*)[5]' [-Wformat=]
             scanf("%s", &a[i]);
                     ^
2darr.c:11:21: warning: format '%s' expects argument of type 'char *', but argument 2 has type 'char (*)[5]' [-Wformat=]
2darr.c:6:13: warning: unused variable 'flag' [-Wunused-variable]
         int flag=1;
             ^~~~


问:
guestlist[j].getName() doesn't return name
I'm trying to modify a script I found online by daubejb to create a Google Doc from a Google Calendar event.

The reference on Google's website says that the getName() command should display the name of the guest or it's email if a name is not available. However, nothing is displayed when I try. When I use the getEmail() command instead I get the Email just fine but I would prefer to get the name.

```<code>function createMeetingNotesNextTimePeriod() {

 //------VARIABLES--
 // define a custom style for all data labels
 var labelStyle ={};
 labelStyle[DocumentApp.Attribute.BOLD] = true;
 labelStyle[DocumentApp.Attribute.FONT_SIZE] = 11;

 // get today's date
 var today = new Date();

 // create a formatted version of today's date
 var formatted_today = Utilities.formatDate(today, "EDT","yyyy-MM-dd");

 // number of hours from now to check for meetings
 var hours = 2

 // create variable for now
 var now = new Date();

 // create variable for number of hours from now in milliseconds
 var period_from_now = new Date(now.getTime() + (hours * 60 * 60 * 1000));

 //------GET EVENTS/ATTRIBUTES FOR TIME PERIOD FROM NOW--------------
 // retrieve all calendar events for time period
 var events = CalendarApp.getDefaultCalendar().getEvents(now, period_from_now, {search: '@notes'}) ;

 // loop through each event an get meeting attributes,
 for (var i=0;i<events.length;i++) {
   var title = events[i].getTitle();
   var description = events[i].getDescription();
   var eventstart = events[i].getStartTime();
   var eventend = events[i].getEndTime();
   var location = events[i].getLocation();
   var owner = events[i].getCreators();
   var guestlist = events[i].getGuestList();

   //----------CREATE MEETING NOTE DOC -------------
   // create a google doc with the meeting name as the title
   var file_exists = DriveApp.getFilesByName(title).hasNext();

   // check to see if file already exists, if does skip if loop
   if ((file_exists == false) && (guestlist.length >= 1)) {
    var doc = DocumentApp.create(title);

    // loop through event guests and get their emails and status
    for (var j=0;j<guestlist.length;j++) {
      var name = guestlist[j].getName();
      var guestStatus = guestlist[j].getGuestStatus();
      doc.getBody().appendParagraph(name + ': ' + guestStatus);
    }

    doc.getBody().editAsText()
    .insertText(0, 'Invités:\n')
    .setAttributes(0, 9, labelStyle);

    doc.getBody().editAsText()
    .insertText(0, 'Description:' + '\n\n' + description + '\n\n')
    .setAttributes(0, 11, labelStyle);

    doc.getBody().editAsText()
    .insertText(0, 'Organisateur:  ' + owner + '\n\n' )
    .setAttributes(0, 11, labelStyle);

    doc.getBody().editAsText()
    .insertText(0, 'Location:  ' + location + '\n\n')
    .setAttributes(0, 8, labelStyle);

    doc.getBody().editAsText()
    .insertText(0, 'Fin:  ' + eventend + '\n\n')
    .setAttributes(0, 3, labelStyle);

    doc.getBody().editAsText()
    .insertText(0, 'Début:  ' + eventstart + '\n')
    .setAttributes(0, 5, labelStyle);

    doc.getBody().editAsText()
    .insertText(0, title + '\n\n')
    .setFontSize(0, title.length, 14)
    .setBold(0, title.length, true)
    .setForegroundColor(0, title.length, '#cc0000');

   }  // if for file exists

  }  // for loop for each event

}  // functionCreateMeetingNotesNextTimePeriod
</code>```

Thanks in advance.

答:
If getEmail() is working, it only means that no name was provided hence getName() returns no results. The API is working fine.

I recommend trying this with your other calendars with valid guest names to see if your still getting no results.

Body:
I'm trying to modify a script I found online by daubejb to create a Google Doc from a Google Calendar event.

The reference on Google's website says that the getName() command should display the name of the guest or it's email if a name is not available. However, nothing is displayed when I try. When I use the getEmail() command instead I get the Email just fine but I would prefer to get the name.

function createMeetingNotesNextTimePeriod() {

 //------VARIABLES--
 // define a custom style for all data labels
 var labelStyle ={};
 labelStyle[DocumentApp.Attribute.BOLD] = true;
 labelStyle[DocumentApp.Attribute.FONT_SIZE] = 11;

 // get today's date
 var today = new Date();

 // create a formatted version of today's date
 var formatted_today = Utilities.formatDate(today, "EDT","yyyy-MM-dd");

 // number of hours from now to check for meetings
 var hours = 2

 // create variable for now
 var now = new Date();

 // create variable for number of hours from now in milliseconds
 var period_from_now = new Date(now.getTime() + (hours * 60 * 60 * 1000));

 //------GET EVENTS/ATTRIBUTES FOR TIME PERIOD FROM NOW--------------
 // retrieve all calendar events for time period
 var events = CalendarApp.getDefaultCalendar().getEvents(now, period_from_now, {search: '@notes'}) ;

 // loop through each event an get meeting attributes,
 for (var i=0;i<events.length;i++) {
   var title = events[i].getTitle();
   var description = events[i].getDescription();
   var eventstart = events[i].getStartTime();
   var eventend = events[i].getEndTime();
   var location = events[i].getLocation();
   var owner = events[i].getCreators();
   var guestlist = events[i].getGuestList();

   //----------CREATE MEETING NOTE DOC -------------
   // create a google doc with the meeting name as the title
   var file_exists = DriveApp.getFilesByName(title).hasNext();

   // check to see if file already exists, if does skip if loop
   if ((file_exists == false) && (guestlist.length >= 1)) {
    var doc = DocumentApp.create(title);

    // loop through event guests and get their emails and status
    for (var j=0;j<guestlist.length;j++) {
      var name = guestlist[j].getName();
      var guestStatus = guestlist[j].getGuestStatus();
      doc.getBody().appendParagraph(name + ': ' + guestStatus);
    }

    doc.getBody().editAsText()
    .insertText(0, 'Invités:\n')
    .setAttributes(0, 9, labelStyle);

    doc.getBody().editAsText()
    .insertText(0, 'Description:' + '\n\n' + description + '\n\n')
    .setAttributes(0, 11, labelStyle);

    doc.getBody().editAsText()
    .insertText(0, 'Organisateur:  ' + owner + '\n\n' )
    .setAttributes(0, 11, labelStyle);

    doc.getBody().editAsText()
    .insertText(0, 'Location:  ' + location + '\n\n')
    .setAttributes(0, 8, labelStyle);

    doc.getBody().editAsText()
    .insertText(0, 'Fin:  ' + eventend + '\n\n')
    .setAttributes(0, 3, labelStyle);

    doc.getBody().editAsText()
    .insertText(0, 'Début:  ' + eventstart + '\n')
    .setAttributes(0, 5, labelStyle);

    doc.getBody().editAsText()
    .insertText(0, title + '\n\n')
    .setFontSize(0, title.length, 14)
    .setBold(0, title.length, true)
    .setForegroundColor(0, title.length, '#cc0000');

   }  // if for file exists

  }  // for loop for each event

}  // functionCreateMeetingNotesNextTimePeriod

Thanks in advance.


答:
```<code>arr.map(e => { return { id: e.id, title: e.name }});
</code>```


问:
Add (Create) new sheet in spreadsheet using Google Sheet API
I have tried below code to create new sheet inside spreadsheet, but it’s not working.

```<code>    $service = new Google_Service_Sheets($client);

    //pr($service);
    $spreadsheetId = ‘You spredsheet id’;
    $json_request_string = ‘{“requests”:[{“addSheet”: {“properties”: {“title”: “Project tasks”}}}]}’;
    //$requests = json_decode($json_request_string);

    // TODO: Assign values to desired properties of `requestBody`:
    $requestBody = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest();
    $requestBody->setRequests($json_request_string);

    $response = $service->spreadsheets->batchUpdate($spreadsheetId, $requestBody);
</code>```

I get this error:

Request had invalid authentication credentials error

答:
```<code>$title = "my new sheet";

//Create New Sheet

$body = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest(array(
   'requests' => array('addSheet' => array('properties' => array('title' => $title )))));

$result = $service->spreadsheets->batchUpdate(SHEET_ID,$body);
</code>```

Body:
I have tried below code to create new sheet inside spreadsheet, but it’s not working.

    $service = new Google_Service_Sheets($client);

    //pr($service);
    $spreadsheetId = ‘You spredsheet id’;
    $json_request_string = ‘{“requests”:[{“addSheet”: {“properties”: {“title”: “Project tasks”}}}]}’;
    //$requests = json_decode($json_request_string);

    // TODO: Assign values to desired properties of `requestBody`:
    $requestBody = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest();
    $requestBody->setRequests($json_request_string);

    $response = $service->spreadsheets->batchUpdate($spreadsheetId, $requestBody);

I get this error:

Request had invalid authentication credentials error


问:
pywinauto change default timeout values
I am using Timings.Defaults() in my pywinauto/python code. However, for certain operations like

```<code>app.window_(title_re = windowTitle).Wait('visible', timeout=1)
</code>```

code waits for 5 seconds if the window is not visible. I have given timeout as 1 seconds but still it waits for 5 seconds. How do I change this 5 second wait to a shorter time?

答: The bug with timings is fixed in pywinauto 0.6.3. Please update it with pip install -U pywinauto.

Title: pywinauto change default timeout values

Body:
I am using Timings.Defaults() in my pywinauto/python code. However, for certain operations like

app.window_(title_re = windowTitle).Wait('visible', timeout=1)

code waits for 5 seconds if the window is not visible. I have given timeout as 1 seconds but still it waits for 5 seconds. How do I change this 5 second wait to a shorter time?


问:
DropSolve Cplex terminate after T time
I am using drop solve for a MIP optimization problem, to generate K solutions.

I would like to terminate after 60 seconds. I use cplex.params[1039] = 60; Also tried cplex.tilim = 60 in my .mod file

But the program doesn't stops.

Found this SO link to do the same in Java, but I am using DropSolve DoCplex Cloud. Using the Java API's
Terminate and retrieve solution in ILOG after a certain time limit

TIA

答:
I answered the question on the docplexcloud forum https://developer.ibm.com/answers/questions/385233/dropsolve-cplex-terminate-after-t-time.html.

The engine respects the parameter settings but the .mod file executes some scripting code after the solve. Execution of that code takes longer than expected but this is beyond the control of the engine and its parameters.

Title: DropSolve Cplex terminate after T time


问:
Different between keyword "new" and "default" in create instance of class
I have class like:

```<code> class foo
    {
        public foo(string Text)
        {
        }
    }
</code>```

After run this code for create instance of class the obj1 set to null:

```<code>foo obj1 = default(foo);
</code>```

And by blow code everything work fine:

```<code>foo obj2= new foo("bla bla");
</code>```

I have 2 Question :

Whats happen to default contractor when run default(foo);?

Is foo obj1 = default(foo); equal the foo obj1 = null?

Thanks in advance.

答:
It does not call the constructor just initializes with the default value.
Keep in mind that it is also relevant for value types such as int, double and structs.
Another use case is default a generic type.
Each type has a predetermined default value which specified at https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/default-values-table</p>

Body:
I have class like:

 class foo
    {
        public foo(string Text)
        {
        }
    }

After run this code for create instance of class the obj1 set to null:

foo obj1 = default(foo);

And by blow code everything work fine:

foo obj2= new foo("bla bla");

I have 2 Question :

Whats happen to default contractor when run default(foo);?

Is foo obj1 = default(foo); equal the foo obj1 = null?

Thanks in advance.


问:
NoSuchMethodError when using realm.io in a library
I transferred the model classes of my Android app inlcuding realm.io functions into a library following the advices described in the realm.io Java docs section Sharing schemas.
I'm facing a NoSuchMethodError when my app (indirectly) calls realm.io methods which are in the the library.

```<code>java.lang.NoSuchMethodError: No static method copyOrUpdate(Lio/realm/Realm;Lmy/package/structure/MyModelClass;ZLjava/util/Map;)Lmy/package/structure/MyModelClass; in class Lio/realm/MyModelClassRealmProxy; or its super classes (declaration of 'io.realm.MyModelClassRealmProxy' appears in /data/user/0/my.name.space/files/.jrebel/load-dexes/bundle3/classes.zip)
  at io.realm.MyModuleMediator.copyOrUpdate(MyModuleMediator.java:98)
  at io.realm.Realm.copyOrUpdate(Realm.java:1164)
  at io.realm.Realm.copyToRealmOrUpdate(Realm.java:757)
</code>```

Here is how my library looks like:

build.gradle (project)

```<code>buildscript {
  repositories {
      jcenter()
  }
  dependencies {
    classpath 'com.android.tools.build:gradle:2.1.2'
    classpath 'io.realm:realm-gradle-plugin:1.0.1'
  }
}
</code>```

build.gradle (library module)

```<code>apply plugin: 'com.android.library'
apply plugin: 'realm-android'
...
buildTypes {
    release {
        minifyEnabled false
        signingConfig signingConfigs.release
        proguardFile getDefaultProguardFile('proguard-rules.pro')
    }
}
...
</code>```

proguard-rules.pro

I used this snippet as a template

```<code>-keep class io.realm.annotations.RealmModule
-keep @io.realm.annotations.RealmModule class *
-keep class io.realm.internal.Keep
-keep @io.realm.internal.Keep class * { *; }
-keep my.package.MyModelClass
-dontwarn javax.**
-dontwarn io.realm.**
</code>```

MyModule.java

```<code>package my.package;

import io.realm.annotations.RealmModule;

@RealmModule(library = true, allClasses = true)
public class MyModule { }
</code>```

MyRealm.java

```<code>package my.package;

import ...

public class MyRealm {
    private final RealmConfiguration realmConfig;

    public MyRealm(Context context) {
        realmConfig = new RealmConfiguration.Builder(context)
                .name("name.of.my.config")
                .modules(new MyModule())
                .build();
    }

    public Realm getRealm() {
        return Realm.getInstance(realmConfig);
    }
}
</code>```

MyModelClass.class

```<code>package my.package;

import ...

public class MyModelClass extends RealmObject {

  public void save(Context context) {
    Realm realm = new MyRealm(context).getRealm();
    realm.executeTransaction(new Realm.Transaction() {
        @Override
        public void execute(Realm bgRealm) {
            bgRealm.copyToRealmOrUpdate(MyModelClass.this);
        }
    });
    realm.close();
  }
}
</code>```

In my actual app I call something like this which is causing the Exception:

MyActivity.java

```<code>// ...
MyModelClass c = new MyModelClass();
c.save(context);
</code>```

The code above was working well when everything was in the app project.

Am I missing something general?
Is there something more I need to consider regarding the proguard settings of the lib?
May JRebel cause this kind of problem?

答:
I think you might not be using it correctly, I will suggest that you see a full working example like the one they reference are the end of that Sharing Schemas link. The link is to this repository full working example of realm lib and app. I would suggest that you take a look at the Zoo class from the library, the methods are the only thing exposed to the application as you can see in the app's activity here (line 148 and downwards).

I think this was just a confusion on your part, because from what I understood you are calling your library class and using it like it was a Realm instance for that activity context which is not the case. Hope this can steer you in the right path!

Basically you simply create an instance based on you configuration so you don't need to pass a context there.

Body:
I transferred the model classes of my Android app inlcuding realm.io functions into a library following the advices described in the realm.io Java docs section Sharing schemas.
I'm facing a NoSuchMethodError when my app (indirectly) calls realm.io methods which are in the the library.

java.lang.NoSuchMethodError: No static method copyOrUpdate(Lio/realm/Realm;Lmy/package/structure/MyModelClass;ZLjava/util/Map;)Lmy/package/structure/MyModelClass; in class Lio/realm/MyModelClassRealmProxy; or its super classes (declaration of 'io.realm.MyModelClassRealmProxy' appears in /data/user/0/my.name.space/files/.jrebel/load-dexes/bundle3/classes.zip)
  at io.realm.MyModuleMediator.copyOrUpdate(MyModuleMediator.java:98)
  at io.realm.Realm.copyOrUpdate(Realm.java:1164)
  at io.realm.Realm.copyToRealmOrUpdate(Realm.java:757)

Here is how my library looks like:

build.gradle (project)

buildscript {
  repositories {
      jcenter()
  }
  dependencies {
    classpath 'com.android.tools.build:gradle:2.1.2'
    classpath 'io.realm:realm-gradle-plugin:1.0.1'
  }
}

build.gradle (library module)

apply plugin: 'com.android.library'
apply plugin: 'realm-android'
...
buildTypes {
    release {
        minifyEnabled false
        signingConfig signingConfigs.release
        proguardFile getDefaultProguardFile('proguard-rules.pro')
    }
}
...

proguard-rules.pro

I used this snippet as a template

-keep class io.realm.annotations.RealmModule
-keep @io.realm.annotations.RealmModule class *
-keep class io.realm.internal.Keep
-keep @io.realm.internal.Keep class * { *; }
-keep my.package.MyModelClass
-dontwarn javax.**
-dontwarn io.realm.**

MyModule.java

package my.package;

import io.realm.annotations.RealmModule;

@RealmModule(library = true, allClasses = true)
public class MyModule { }

MyRealm.java

package my.package;

import ...

public class MyRealm {
    private final RealmConfiguration realmConfig;

    public MyRealm(Context context) {
        realmConfig = new RealmConfiguration.Builder(context)
                .name("name.of.my.config")
                .modules(new MyModule())
                .build();
    }

    public Realm getRealm() {
        return Realm.getInstance(realmConfig);
    }
}

MyModelClass.class

package my.package;

import ...

public class MyModelClass extends RealmObject {

  public void save(Context context) {
    Realm realm = new MyRealm(context).getRealm();
    realm.executeTransaction(new Realm.Transaction() {
        @Override
        public void execute(Realm bgRealm) {
            bgRealm.copyToRealmOrUpdate(MyModelClass.this);
        }
    });
    realm.close();
  }
}

In my actual app I call something like this which is causing the Exception:

MyActivity.java

// ...
MyModelClass c = new MyModelClass();
c.save(context);

The code above was working well when everything was in the app project.

Am I missing something general?
Is there something more I need to consider regarding the proguard settings of the lib?
May JRebel cause this kind of problem?


问:
How can I make a UITextField move up when the keyboard is present - on starting to edit?
With the iOS SDK:

I have a UIView with UITextFields that bring up a keyboard. I need it to be able to:

Allow scrolling of the contents of the UIScrollView to see the other text fields once the keyboard is brought up

Automatically "jump" (by scrolling up) or shortening

I know that I need a UIScrollView.  I've tried changing the class of my UIView to a UIScrollView, but I'm still unable to scroll the textboxes up or down.

Do I need both a UIView and a UIScrollView? Does one go inside the other?

What needs to be implemented in order to automatically scroll to the active text field?

Ideally as much of the setup of the components as possible will be done in Interface Builder. I'd like to only write code for what needs it.

Note: the UIView (or UIScrollView) that I'm working with is brought up by a tabbar (UITabBar), which needs to function as normal.

I am adding the scroll bar just for when the keyboard comes up.  Even though it's not needed, I feel like it provides a better interface because then the user can scroll and change textboxes, for example.

I've got it working where I change the frame size of the UIScrollView when the keyboard goes up and down. I'm simply using:

```<code>-(void)textFieldDidBeginEditing:(UITextField *)textField {
    //Keyboard becomes visible
    scrollView.frame = CGRectMake(scrollView.frame.origin.x,
                                  scrollView.frame.origin.y,
    scrollView.frame.size.width,
    scrollView.frame.size.height - 215 + 50);   // Resize
}

-(void)textFieldDidEndEditing:(UITextField *)textField {
    // Keyboard will hide
    scrollView.frame = CGRectMake(scrollView.frame.origin.x,
                                  scrollView.frame.origin.y,
                                  scrollView.frame.size.width,
                                  scrollView.frame.size.height + 215 - 50); // Resize
}
</code>```

However, this doesn't automatically "move up" or center the lower text fields in the visible area, which is what I would really like.

答:
Simple Solution For Scrollview with TextFields is below, No need any Constraints or active textfield  etc...  </p>

```<code> override func viewWillAppear(_ animated: Bool){
        super.viewWillAppear(animated)
        registerForKeyboardNotifications();

    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        deregisterFromKeyboardNotifications();
    }
    //MARK:- KEYBOARD DELEGATE METHODS
        func registerForKeyboardNotifications(){
            //Adding notifies on keyboard appearing
            NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
            NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
        }
        func deregisterFromKeyboardNotifications(){
            //Removing notifies on keyboard appearing
            NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
            NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
        }
        func keyboardWasShown(notification: NSNotification){

            var info = notification.userInfo!
            let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
            var contentInset:UIEdgeInsets = self.scrRegister.contentInset
            contentInset.bottom = (keyboardSize?.height)!
            scrRegister.contentInset = contentInset

        }
        func keyboardWillBeHidden(notification: NSNotification)
        {
            var contentInset:UIEdgeInsets = self.scrRegister.contentInset
            contentInset.bottom = 0
            scrRegister.contentInset = contentInset

        }
</code>```

Body:
With the iOS SDK:

I have a UIView with UITextFields that bring up a keyboard. I need it to be able to:

Allow scrolling of the contents of the UIScrollView to see the other text fields once the keyboard is brought up

Automatically "jump" (by scrolling up) or shortening

I know that I need a UIScrollView.  I've tried changing the class of my UIView to a UIScrollView, but I'm still unable to scroll the textboxes up or down.

Do I need both a UIView and a UIScrollView? Does one go inside the other?

What needs to be implemented in order to automatically scroll to the active text field?

Ideally as much of the setup of the components as possible will be done in Interface Builder. I'd like to only write code for what needs it.

Note: the UIView (or UIScrollView) that I'm working with is brought up by a tabbar (UITabBar), which needs to function as normal.

I am adding the scroll bar just for when the keyboard comes up.  Even though it's not needed, I feel like it provides a better interface because then the user can scroll and change textboxes, for example.

I've got it working where I change the frame size of the UIScrollView when the keyboard goes up and down. I'm simply using:

-(void)textFieldDidBeginEditing:(UITextField *)textField {
    //Keyboard becomes visible
    scrollView.frame = CGRectMake(scrollView.frame.origin.x,
                                  scrollView.frame.origin.y,
    scrollView.frame.size.width,
    scrollView.frame.size.height - 215 + 50);   // Resize
}

-(void)textFieldDidEndEditing:(UITextField *)textField {
    // Keyboard will hide
    scrollView.frame = CGRectMake(scrollView.frame.origin.x,
                                  scrollView.frame.origin.y,
                                  scrollView.frame.size.width,
                                  scrollView.frame.size.height + 215 - 50); // Resize
}

However, this doesn't automatically "move up" or center the lower text fields in the visible area, which is what I would really like.

Body:
Simple Solution For Scrollview with TextFields is below, No need any Constraints or active textfield  etc...

 override func viewWillAppear(_ animated: Bool){
        super.viewWillAppear(animated)
        registerForKeyboardNotifications();

    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        deregisterFromKeyboardNotifications();
    }
    //MARK:- KEYBOARD DELEGATE METHODS
        func registerForKeyboardNotifications(){
            //Adding notifies on keyboard appearing
            NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
            NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
        }
        func deregisterFromKeyboardNotifications(){
            //Removing notifies on keyboard appearing
            NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
            NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
        }
        func keyboardWasShown(notification: NSNotification){

            var info = notification.userInfo!
            let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
            var contentInset:UIEdgeInsets = self.scrRegister.contentInset
            contentInset.bottom = (keyboardSize?.height)!
            scrRegister.contentInset = contentInset

        }
        func keyboardWillBeHidden(notification: NSNotification)
        {
            var contentInset:UIEdgeInsets = self.scrRegister.contentInset
            contentInset.bottom = 0
            scrRegister.contentInset = contentInset

        }


问:
Replace email string
So i want to replace an normal email for example: "teste123@test.com" to
 "teste123  null @test.com"`

until now I've got this:

```<code>  string expression = @"(([^<>()\[\]\\.,;:\s@']+(\.[^<>()\[\]\\.,;:\s@']+)*)|('.+'))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))";
            Regex rx = new Regex(expression);
            MatchCollection matches = rx.Matches(conteudo.PaginaConteudo);
            Console.WriteLine("{0} matches found in:\n   {1}",
                     matches.Count,
                     conteudo.PaginaConteudo);

            string email,
                   replacement = "<h5 style='display:none;'>null</h5>",
                   mailenc,
                   correctString;

            foreach (Match emails in matches)
            {
                email = emails.Value;
                mailenc = "<h5>"+email + replacement+"</h5>";
                correctString = conteudoOriginal.PaginaConteudo.Replace(email, mailenc);
                conteudoOriginal.PaginaConteudo = correctString;

            }
</code>```

答:
```<code>email = emails.Value.Replace("@","<b style='display:none;'>null</b>@");
</code>```

Title: Replace email string

Body:
So i want to replace an normal email for example: "teste123@test.com" to
 "teste123  null @test.com"`

until now I've got this:

  string expression = @"(([^<>()\[\]\\.,;:\s@']+(\.[^<>()\[\]\\.,;:\s@']+)*)|('.+'))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))";
            Regex rx = new Regex(expression);
            MatchCollection matches = rx.Matches(conteudo.PaginaConteudo);
            Console.WriteLine("{0} matches found in:\n   {1}",
                     matches.Count,
                     conteudo.PaginaConteudo);

            string email,
                   replacement = "
null
",
                   mailenc,
                   correctString;

            foreach (Match emails in matches)
            {
                email = emails.Value;
                mailenc = "
"+email + replacement+"
";
                correctString = conteudoOriginal.PaginaConteudo.Replace(email, mailenc);
                conteudoOriginal.PaginaConteudo = correctString;

            }


问:
Strongloop Loopback REST Query and/or combined with between
I have a simple model object with startDate and endDate properties.

I can not seem to query with both 'and/or' and 'between' using the REST api. I would like to query 'between' a startDate range 'or' an endDate range. I would have thought that the following query would have worked:

```<code>?filter[where][or][0][event.startDate][between][0]=2017-01-15&filter[where][or][0][event.startDate][between][1]=2017-01-22&filter[where][or][1][event.endDate][between][0]=2017-01-15&filter[where][or][1][event.endDate][between][1]=2017-01-22
</code>```

Ideally I would have liked to query between event.startDate and event.endDate but loopback does not like the following query:

```<code>?filter[where][event.startDate][between][0]=2017-01-15&filter[where][event.endDate][between][1]=2017-01-22
</code>```

The queries work independently just fine:

```<code>?filter[where][event.startDate][between][0]=2017-01-15&filter[where][event.startDate][between][1]=2017-01-22

?filter[where][event.endDate][between][0]=2017-01-15&filter[where][event.endDate][between][1]=2017-01-22
</code>```

Here is my model definition:

models/event.json

```<code>{
  "name": "event",
  "plural": "events",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "name": {
      "type": "string",
      "required": false
    },
    "startDate": {
      "type": "date",
      "required": false
    },
    "endDate": {
      "type": "date",
      "required": false
    }
  },
  "validations": [],
  "relations": {},
  "acls": [],
  "methods": {}
}
</code>```

答:
I could not make the REST query work in that case either.

Ultimately, we had to resort to building the query via stringified JSON, see the docs

So, something like this

let filter = {
  where: {
    or: [
      {
        'event.startDate': {
          between: ['2017-01-15', '2017-01-22']
        }
      },
      {
        'event.endDate': {
          between: ['2017-01-15', '2017-01-22']
        }
      }
    ]
  }
};

let url = `/api?filter=${JSON.stringify(filter)}`;
```

It also made query building a lot simpler, actually.

Body:
I have a simple model object with startDate and endDate properties.

I can not seem to query with both 'and/or' and 'between' using the REST api. I would like to query 'between' a startDate range 'or' an endDate range. I would have thought that the following query would have worked:

?filter[where][or][0][event.startDate][between][0]=2017-01-15&filter[where][or][0][event.startDate][between][1]=2017-01-22&filter[where][or][1][event.endDate][between][0]=2017-01-15&filter[where][or][1][event.endDate][between][1]=2017-01-22

Ideally I would have liked to query between event.startDate and event.endDate but loopback does not like the following query:

?filter[where][event.startDate][between][0]=2017-01-15&filter[where][event.endDate][between][1]=2017-01-22

The queries work independently just fine:

?filter[where][event.startDate][between][0]=2017-01-15&filter[where][event.startDate][between][1]=2017-01-22

?filter[where][event.endDate][between][0]=2017-01-15&filter[where][event.endDate][between][1]=2017-01-22

Here is my model definition:

models/event.json

{
  "name": "event",
  "plural": "events",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "name": {
      "type": "string",
      "required": false
    },
    "startDate": {
      "type": "date",
      "required": false
    },
    "endDate": {
      "type": "date",
      "required": false
    }
  },
  "validations": [],
  "relations": {},
  "acls": [],
  "methods": {}
}

Body:
I could not make the REST query work in that case either.

Ultimately, we had to resort to building the query via stringified JSON, see the docs

So, something like this

let filter = {
  where: {
    or: [
      {
        'event.startDate': {
          between: ['2017-01-15', '2017-01-22']
        }
      },
      {
        'event.endDate': {
          between: ['2017-01-15', '2017-01-22']
        }
      }
    ]
  }
};

let url = `/api?filter=${JSON.stringify(filter)}`;

It also made query building a lot simpler, actually.


问:
Install pymssql 2.1.3 in Pycharm
I'm working with Pycharm in a project to read SQL DBs ,I'm working in a windows 10 64bits workstation and I'm trying to install the module pymssql, I have already installed VS2015 to get all requirements but now each time that i try to install i got the message:

error: command 'C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\cl.exe' failed with exit status 2

I saw on message details the error in:
  _mssql.c(266): fatal error C1083: Cannot open include file: 'sqlfront.h': No such file or directory

How can i figured it out?  thanks

答:
Seems that your error is a known problem, check here.

As you can see from the last post from the link, they don't have wheels built for Python3.6, so when you try to install pymssql, the error is raised.

Still, as the post found suggests, you can try the following options:

Drop back to Python 3.5

Use the Python 3.6 wheels available here:

Try to build pymssql using the advice given in the forum link above.

If you were trying to install pymssql directly from PyCharm, I think that you should follow the options showed above but from command line

Title: Install pymssql 2.1.3 in Pycharm