问:
Sorting jsonarray based on price
I tried to sort jsonarray using below code. But it not sorting the jsonarray correctly. Some values misplaced.

My Jsonarray is

```<code>{
  "sTATUS": "SUCCESS",
  "mSG": "Product List",
  "product_list": [
    {
      "product_id": "5",
      "product_name": "LAS VEGAS  530",
      "product_model": "530",
      "product_image": "uploads/main/14748883885prime.png",
      "price": "18990",
      "discount_price": "",
      "discount_percentage": "",
      "offer_price": "",
      "featured_product": "0",
      "category_id": "1",
      "category_name": "Speakers",
      "rate": "0",
      "review": "0",
      "gift_id": "0"
    },
    {
      "product_id": "68",
      "product_name": "TESTAPESKER  MODSPK1",
      "product_model": "modspk1",
      "product_image": "",
      "price": "2100",
      "discount_price": "",
      "discount_percentage": "",
      "offer_price": "",
      "featured_product": "0",
      "category_id": "1",
      "category_name": "Speakers",
      "rate": "0",
      "review": "0",
      "gift_id": "0"
    },
    {
      "product_id": "1",
      "product_name": "CAPE TOWN  940",
      "product_model": "940",
      "product_image": "uploads/main/14748836241prime.png",
      "price": "49990",
      "discount_price": "990",
      "discount_percentage": "1.98%",
      "offer_price": "49000",
      "featured_product": "1",
      "category_id": "1",
      "category_name": "Speakers",
      "rate": "3",
      "review": "2",
      "gift_id": "0"
    },
    {
      "product_id": "10",
      "product_name": "BARCELONA  230 BT",
      "product_model": "230 BT",
      "product_image": "uploads/main/147531739810prime.png",
      "price": "10990",
      "discount_price": "",
      "discount_percentage": "",
      "offer_price": "",
      "featured_product": "1",
      "category_id": "1",
      "category_name": "Speakers",
      "rate": "0",
      "review": "0",
      "gift_id": "0"
    },
    {
      "product_id": "3",
      "product_name": "SANTA FE  530",
      "product_model": "530",
      "product_image": "uploads/main/14748874843prime.png",
      "price": "34990",
      "discount_price": "",
      "discount_percentage": "",
      "offer_price": "",
      "featured_product": "1",
      "category_id": "1",
      "category_name": "Speakers",
      "rate": "0",
      "review": "0",
      "gift_id": "0"
    },
    {
      "product_id": "8",
      "product_name": "NEW ORLEANS  220",
      "product_model": "220",
      "product_image": "uploads/main/14753168598prime.png",
      "price": "8990",
      "discount_price": "",
      "discount_percentage": "",
      "offer_price": "",
      "featured_product": "0",
      "category_id": "1",
      "category_name": "Speakers",
      "rate": "0",
      "review": "0",
      "gift_id": "0"
    },
    {
      "product_id": "6",
      "product_name": "SAN MARINO  330",
      "product_model": "330",
      "product_image": "uploads/main/14748893666prime.png",
      "price": "14990",
      "discount_price": "",
      "discount_percentage": "",
      "offer_price": "",
      "featured_product": "0",
      "category_id": "1",
      "category_name": "Speakers",
      "rate": "0",
      "review": "0",
      "gift_id": "0"
    },
    {
      "product_id": "7",
      "product_name": "NEW JERSEY  220BT",
      "product_model": "220BT",
      "product_image": "uploads/main/14753166327prime.png",
      "price": "10990",
      "discount_price": "",
      "discount_percentage": "",
      "offer_price": "",
      "featured_product": "0",
      "category_id": "1",
      "category_name": "Speakers",
      "rate": "0",
      "review": "0",
      "gift_id": "0"
    },
    {
      "product_id": "13",
      "product_name": "TOKYO  110",
      "product_model": "110",
      "product_image": "uploads/main/147549157513prime.png",
      "price": "4990",
      "discount_price": "",
      "discount_percentage": "",
      "offer_price": "",
      "featured_product": "0",
      "category_id": "1",
      "category_name": "Speakers",
      "rate": "0",
      "review": "0",
      "gift_id": "2"
    },
    {
      "product_id": "2",
      "product_name": "SAN ANTONIO  640",
      "product_model": "640",
      "product_image": "uploads/main/14748866592prime.png",
      "price": "33500",
      "discount_price": "500",
      "discount_percentage": "1.49%",
      "offer_price": "33000",
      "featured_product": "0",
      "category_id": "1",
      "category_name": "Speakers",
      "rate": "0",
      "review": "0",
      "gift_id": "1"
    },
    {
      "product_id": "60",
      "product_name": "PHILADELPHIA  845",
      "product_model": "845",
      "product_image": "uploads/main/148109520160prime.png",
      "price": "54990",
      "discount_price": "",
      "discount_percentage": "",
      "offer_price": "",
      "featured_product": "1",
      "category_id": "1",
      "category_name": "Speakers",
      "rate": "0",
      "review": "0",
      "gift_id": "0"
    },
    {
      "product_id": "12",
      "product_name": "MANCHESTER  110",
      "product_model": "110",
      "product_image": "uploads/main/147549119212prime.png",
      "price": "5990",
      "discount_price": "100",
      "discount_percentage": "1.67%",
      "offer_price": "5890",
      "featured_product": "0",
      "category_id": "1",
      "category_name": "Speakers",
      "rate": "0",
      "review": "0",
      "gift_id": "0"
    },
    {
      "product_id": "11",
      "product_name": "MONTEVIDEO  4010 DVD",
      "product_model": "4010 DVD",
      "product_image": "uploads/main/147549071111prime.png",
      "price": "9990",
      "discount_price": "",
      "discount_percentage": "",
      "offer_price": "",
      "featured_product": "0",
      "category_id": "1",
      "category_name": "Speakers",
      "rate": "0",
      "review": "0",
      "gift_id": "0"
    },
    {
      "product_id": "4",
      "product_name": "SAN DIEGO  530",
      "product_model": "530",
      "product_image": "uploads/main/14748877994prime.png",
      "price": "31990",
      "discount_price": "",
      "discount_percentage": "",
      "offer_price": "",
      "featured_product": "1",
      "category_id": "1",
      "category_name": "Speakers",
      "rate": "0",
      "review": "0",
      "gift_id": "2"
    }
  ],
  "cart_count": "0"
}
</code>```

code

```<code>    try {
        JSONObject json=new JSONObject(cal_json);
        JSONArray users = json.getJSONArray("product_list");
        List<JSONObject> list = new ArrayList<JSONObject>();
        for (int i = 0; i < users.length(); i++) {
            list.add(users.getJSONObject(i));
        }
        Collections.sort( list, new Comparator<JSONObject>() {

            public int compare(JSONObject a, JSONObject b) {
                Long valA = null;
                Long valB=null;

                try {
                    valA = (Long) a.get("price");
                    valB = (Long) b.get("price");
                }
                catch (JSONException e) {
                    //do something
                }

                return valA.compareTo(valB);
            }
        });
        // Collections.sort(list, new SortBasedOnMessageId());
        JSONArray resultArray = new JSONArray();
        for (int i = 0; i < users.length(); i++) {
            resultArray.put(list.get(i));
        }
        Log.d("newjsonarr",resultArray.toString());
        getjson(resultArray.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }
</code>```

Does anyone know exact way to sort jsonarray based on string or numerical value in ascending and descending order. For any positive response thanks in advance.

答:
Your compare class should be like this.

```<code>        public int compare(JSONObject a, JSONObject b) {
            Long valA = null;
            Long valB=null;

            try {
                valA = Long.parseLong(a.get("price"));
                valB = Long.parseLong(b.get("price"));
            }
            catch (JSONException e) {
                //do something
            }

            return valA.compareTo(valB);
        }
    });
</code>```

Title: Sorting jsonarray based on price

Body:
I tried to sort jsonarray using below code. But it not sorting the jsonarray correctly. Some values misplaced.

My Jsonarray is

{
  "sTATUS": "SUCCESS",
  "mSG": "Product List",
  "product_list": [
    {
      "product_id": "5",
      "product_name": "LAS VEGAS  530",
      "product_model": "530",
      "product_image": "uploads/main/14748883885prime.png",
      "price": "18990",
      "discount_price": "",
      "discount_percentage": "",
      "offer_price": "",
      "featured_product": "0",
      "category_id": "1",
      "category_name": "Speakers",
      "rate": "0",
      "review": "0",
      "gift_id": "0"
    },
    {
      "product_id": "68",
      "product_name": "TESTAPESKER  MODSPK1",
      "product_model": "modspk1",
      "product_image": "",
      "price": "2100",
      "discount_price": "",
      "discount_percentage": "",
      "offer_price": "",
      "featured_product": "0",
      "category_id": "1",
      "category_name": "Speakers",
      "rate": "0",
      "review": "0",
      "gift_id": "0"
    },
    {
      "product_id": "1",
      "product_name": "CAPE TOWN  940",
      "product_model": "940",
      "product_image": "uploads/main/14748836241prime.png",
      "price": "49990",
      "discount_price": "990",
      "discount_percentage": "1.98%",
      "offer_price": "49000",
      "featured_product": "1",
      "category_id": "1",
      "category_name": "Speakers",
      "rate": "3",
      "review": "2",
      "gift_id": "0"
    },
    {
      "product_id": "10",
      "product_name": "BARCELONA  230 BT",
      "product_model": "230 BT",
      "product_image": "uploads/main/147531739810prime.png",
      "price": "10990",
      "discount_price": "",
      "discount_percentage": "",
      "offer_price": "",
      "featured_product": "1",
      "category_id": "1",
      "category_name": "Speakers",
      "rate": "0",
      "review": "0",
      "gift_id": "0"
    },
    {
      "product_id": "3",
      "product_name": "SANTA FE  530",
      "product_model": "530",
      "product_image": "uploads/main/14748874843prime.png",
      "price": "34990",
      "discount_price": "",
      "discount_percentage": "",
      "offer_price": "",
      "featured_product": "1",
      "category_id": "1",
      "category_name": "Speakers",
      "rate": "0",
      "review": "0",
      "gift_id": "0"
    },
    {
      "product_id": "8",
      "product_name": "NEW ORLEANS  220",
      "product_model": "220",
      "product_image": "uploads/main/14753168598prime.png",
      "price": "8990",
      "discount_price": "",
      "discount_percentage": "",
      "offer_price": "",
      "featured_product": "0",
      "category_id": "1",
      "category_name": "Speakers",
      "rate": "0",
      "review": "0",
      "gift_id": "0"
    },
    {
      "product_id": "6",
      "product_name": "SAN MARINO  330",
      "product_model": "330",
      "product_image": "uploads/main/14748893666prime.png",
      "price": "14990",
      "discount_price": "",
      "discount_percentage": "",
      "offer_price": "",
      "featured_product": "0",
      "category_id": "1",
      "category_name": "Speakers",
      "rate": "0",
      "review": "0",
      "gift_id": "0"
    },
    {
      "product_id": "7",
      "product_name": "NEW JERSEY  220BT",
      "product_model": "220BT",
      "product_image": "uploads/main/14753166327prime.png",
      "price": "10990",
      "discount_price": "",
      "discount_percentage": "",
      "offer_price": "",
      "featured_product": "0",
      "category_id": "1",
      "category_name": "Speakers",
      "rate": "0",
      "review": "0",
      "gift_id": "0"
    },
    {
      "product_id": "13",
      "product_name": "TOKYO  110",
      "product_model": "110",
      "product_image": "uploads/main/147549157513prime.png",
      "price": "4990",
      "discount_price": "",
      "discount_percentage": "",
      "offer_price": "",
      "featured_product": "0",
      "category_id": "1",
      "category_name": "Speakers",
      "rate": "0",
      "review": "0",
      "gift_id": "2"
    },
    {
      "product_id": "2",
      "product_name": "SAN ANTONIO  640",
      "product_model": "640",
      "product_image": "uploads/main/14748866592prime.png",
      "price": "33500",
      "discount_price": "500",
      "discount_percentage": "1.49%",
      "offer_price": "33000",
      "featured_product": "0",
      "category_id": "1",
      "category_name": "Speakers",
      "rate": "0",
      "review": "0",
      "gift_id": "1"
    },
    {
      "product_id": "60",
      "product_name": "PHILADELPHIA  845",
      "product_model": "845",
      "product_image": "uploads/main/148109520160prime.png",
      "price": "54990",
      "discount_price": "",
      "discount_percentage": "",
      "offer_price": "",
      "featured_product": "1",
      "category_id": "1",
      "category_name": "Speakers",
      "rate": "0",
      "review": "0",
      "gift_id": "0"
    },
    {
      "product_id": "12",
      "product_name": "MANCHESTER  110",
      "product_model": "110",
      "product_image": "uploads/main/147549119212prime.png",
      "price": "5990",
      "discount_price": "100",
      "discount_percentage": "1.67%",
      "offer_price": "5890",
      "featured_product": "0",
      "category_id": "1",
      "category_name": "Speakers",
      "rate": "0",
      "review": "0",
      "gift_id": "0"
    },
    {
      "product_id": "11",
      "product_name": "MONTEVIDEO  4010 DVD",
      "product_model": "4010 DVD",
      "product_image": "uploads/main/147549071111prime.png",
      "price": "9990",
      "discount_price": "",
      "discount_percentage": "",
      "offer_price": "",
      "featured_product": "0",
      "category_id": "1",
      "category_name": "Speakers",
      "rate": "0",
      "review": "0",
      "gift_id": "0"
    },
    {
      "product_id": "4",
      "product_name": "SAN DIEGO  530",
      "product_model": "530",
      "product_image": "uploads/main/14748877994prime.png",
      "price": "31990",
      "discount_price": "",
      "discount_percentage": "",
      "offer_price": "",
      "featured_product": "1",
      "category_id": "1",
      "category_name": "Speakers",
      "rate": "0",
      "review": "0",
      "gift_id": "2"
    }
  ],
  "cart_count": "0"
}

code

    try {
        JSONObject json=new JSONObject(cal_json);
        JSONArray users = json.getJSONArray("product_list");
        List<JSONObject> list = new ArrayList<JSONObject>();
        for (int i = 0; i < users.length(); i++) {
            list.add(users.getJSONObject(i));
        }
        Collections.sort( list, new Comparator<JSONObject>() {

            public int compare(JSONObject a, JSONObject b) {
                Long valA = null;
                Long valB=null;

                try {
                    valA = (Long) a.get("price");
                    valB = (Long) b.get("price");
                }
                catch (JSONException e) {
                    //do something
                }

                return valA.compareTo(valB);
            }
        });
        // Collections.sort(list, new SortBasedOnMessageId());
        JSONArray resultArray = new JSONArray();
        for (int i = 0; i < users.length(); i++) {
            resultArray.put(list.get(i));
        }
        Log.d("newjsonarr",resultArray.toString());
        getjson(resultArray.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }

Does anyone know exact way to sort jsonarray based on string or numerical value in ascending and descending order. For any positive response thanks in advance.

Body:
Your compare class should be like this.

        public int compare(JSONObject a, JSONObject b) {
            Long valA = null;
            Long valB=null;

            try {
                valA = Long.parseLong(a.get("price"));
                valB = Long.parseLong(b.get("price"));
            }
            catch (JSONException e) {
                //do something
            }

            return valA.compareTo(valB);
        }
    });


来源: stackexchange

问:
react-native init specify react version and react-native version
I basically want to init a react-native project with react@15.6.0 and react-native@0.45.0 because dependency problems. However react-native command only allows me to specify react-native version:

```<code>react-native init sample --version react-native@0.45.0
</code>```

This command not works:

```<code>react-native init diskful --version react-native@0.45.0 --version react@15.6.0
</code>```

This, too:

```<code>react-native init diskful --version react-native@0.45.0 react@15.6.0
</code>```

And this, too:

```<code>react-native init diskful --version react@15.6.0 react-native@0.45.0
</code>```

Install globally react@15.6.0 or react-native@0.45.0 does not affect.
Please, someone help me!

答:
delete node_modules folder

Edit Package.json

"dependencies": {
    "react": "15.6.0",
    "react-native": "0.45.0",
 },

run command 'npm install'

ContentLicense: CC BY-SA 3.0

Body:
I basically want to init a react-native project with react@15.6.0 and react-native@0.45.0 because dependency problems. However react-native command only allows me to specify react-native version:

react-native init sample --version react-native@0.45.0

This command not works:

react-native init diskful --version react-native@0.45.0 --version react@15.6.0

This, too:

react-native init diskful --version react-native@0.45.0 react@15.6.0

And this, too:

react-native init diskful --version react@15.6.0 react-native@0.45.0

Install globally react@15.6.0 or react-native@0.45.0 does not affect.
Please, someone help me!


问:
What determines autoselect for <select>?
I have a <select> tag with various options, and I would like to know what determines what happens when the user starts typing.

Say I have a list like the following:

```<code><select id="userlist">
<option value="nothing" selected="selected"></option>
<option value="AdamT">Adam T</option>
<option value="AidanC">Aidan C</option>
<option value="IanQ">Ian Q</option>
<option value="JamesR">James R</option>
</select>
</code>```

Sometimes if I type A followed by I, I end up with Aidan C selected.

Other times, if I type just fractionally slower, I end up with Ian Q selected.

What determines what ends up being selected, and at what speed of typing? Is it browser-specific, or is it set in the HTML spec?

答:
That is browser or OS specific, depending if the browser uses native or custom widgets, I think.

There is certainly nothing in the HTML spec about it.

ContentLicense: CC BY-SA 2.5

Body:
I have a <select> tag with various options, and I would like to know what determines what happens when the user starts typing.

Say I have a list like the following:

<select id="userlist">
<option value="nothing" selected="selected"></option>
<option value="AdamT">Adam T</option>
<option value="AidanC">Aidan C</option>
<option value="IanQ">Ian Q</option>
<option value="JamesR">James R</option>
</select>

Sometimes if I type A followed by I, I end up with Aidan C selected.

Other times, if I type just fractionally slower, I end up with Ian Q selected.

What determines what ends up being selected, and at what speed of typing? Is it browser-specific, or is it set in the HTML spec?


问:
How to get sum by groups in Crystal Report
I want to get the sum by the groups in Crystal Reports.

```<code>Group OVERALL
-----------------
      group 1
     --------------
          5.00
          5.00
         10.00
     --------------
     total group 1      20.00
     --------------
      group 2
      --------------
         10.00
         25.00
         15.00
      --------------
     total group 2      50.00
-------------------
Total Group OVERALL     70.00
</code>```

Using this formula sum({field.amount}, {field.group}) I only get sum for OVERALL but not for group 1 and 2.

答:
Right Click field which you want to Sum

Select Insert -> Summary and select Group On field below on the same dialog window

Click Ok

Body:
I want to get the sum by the groups in Crystal Reports.

Group OVERALL
-----------------
      group 1
     --------------
          5.00
          5.00
         10.00
     --------------
     total group 1      20.00
     --------------
      group 2
      --------------
         10.00
         25.00
         15.00
      --------------
     total group 2      50.00
-------------------
Total Group OVERALL     70.00

Using this formula sum({field.amount}, {field.group}) I only get sum for OVERALL but not for group 1 and 2.


问:
Eclipse not picking up Maven attached source on debug
I've downloaded the source for all the Maven JARs in my buildpath using Maven->Download Sources and mvn eclipse:eclipse -DdownloadSources=true, which worked! When I open up the build path I can see that the sources JARs are attached for every JAR file.

But when I run the damn thing on Tomcat 6 I keep getting "Source not found" page with "Edit Source lookup path" button. But the source is already attached in the build path. What isn't this working?

When I manually point it to the JAR file by clicking on the "Edit Source lookup path" button it works. And when I manually point it to the folder it does not work. Why isn't Eclipse or Tomcat picking up the attached source in the build path?

Note: I'm using apache-maven-3.0.4, apache-tomcat-6.0.16 and Eclipse Indigo Service Release 2.

答:
Use External Maven instead of default Embedded in Debug Configurations dialogue.

Please see example screenshot below (menu Run -> Debug Configurations...):

Configure external Maven

Tested environment:

Eclipse IDE for Java Developers: Oxygen.1a Release (4.7.1a), 64-bit (from spring.io)

Oracle JDK jdk1.8.0_144, 64-bit

Maven: 3.5.2

OS: Windows 10 Enterprise N, 64-bit

Test goal hpi:run (sample Jenkins plugin)


问:
Argument is of length zero
I am trying to use the following syntax to get the occupation information from George Clooney's wikipedia page. Eventually I would like there to be a loop to get data on various personalitys' occupations.

However, I get the following problem running the below code:

```<code>Error in if (symbol != "role") symbol = NULL : argument is of length zero
</code>```

I am not sure why this keeps on coming up.

```<code>library(XML)
library(plyr)
  url = 'http://en.wikipedia.org/wiki/George_Clooney'

# don't forget to parse the HTML, doh!
  doc = htmlParse(url)

# get every link in a table cell:
  links = getNodeSet(doc, '//table/tr/td')

# make a data.frame for each node with non-blank text, link, and 'title' attribute:
  df = ldply(links, function(x) {
                text = xmlValue(x)
            if (text=='') text=NULL
         symbol = xmlGetAttr(x, 'class')
         if (symbol!='role') symbol=NULL
         if(!is.null(text) & !is.null(symbol))
                 data.frame(symbol, text)         } )
</code>```

答: Use col.names = my_column_names in kable() with my_column_names being character vector of your wanted names, for me it worked!

Title: Argument is of length zero

Body:
I am trying to use the following syntax to get the occupation information from George Clooney's wikipedia page. Eventually I would like there to be a loop to get data on various personalitys' occupations.

However, I get the following problem running the below code:

Error in if (symbol != "role") symbol = NULL : argument is of length zero

I am not sure why this keeps on coming up.

library(XML)
library(plyr)
  url = 'http://en.wikipedia.org/wiki/George_Clooney'

# don't forget to parse the HTML, doh!
  doc = htmlParse(url)

# get every link in a table cell:
  links = getNodeSet(doc, '//table/tr/td')

# make a data.frame for each node with non-blank text, link, and 'title' attribute:
  df = ldply(links, function(x) {
                text = xmlValue(x)
            if (text=='') text=NULL
         symbol = xmlGetAttr(x, 'class')
         if (symbol!='role') symbol=NULL
         if(!is.null(text) & !is.null(symbol))
                 data.frame(symbol, text)         } )

ContentLicense: CC BY-SA 4.0


问:
How to extract nested values from JSON received from GoogleDistanceMatrix API in Java?
Trying to parse the following JSON return to java usable code:

```<code>{
   "destination_addresses" : [ "New York, NY, USA" ],
   "origin_addresses" : [ "Washington, DC, USA" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "225 mi",
                  "value" : 361951
               },
               "duration" : {
                  "text" : "3 hours 51 mins",
                  "value" : 13876
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

      // Parse the whole JSON result.
      JSONObject o1 =(JSONObject)JSONValue.parse(outputString);

      JSONArray a1 = (JSONArray) o1.get("rows");//2
      for (int i = 0; i < a1.size(); i++) {
          JSONObject o2 = (JSONObject) a1.get(i);//3
          JSONArray a2 = (JSONArray) o2.get("elements");//4
          for (int j = 0; j < a2.size(); j++) {
              JSONObject o3 = (JSONObject) a2.get(j);//3
              JSONArray a3 = (JSONArray) o3.get("distance");//4
              for(int k =0; k < a3.size(); k++) {
              System.out.println(((JSONObject) a3.get(k)).get(
                      "text").toString());//5
              }

          }

      }
</code>```

I would like to access text value of distance and also text value of duration . I found code to access distance and duration but when I added the third for loop following the example of the old ones I get this expection

```<code>Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray
</code>```

At this line:

```<code>   JSONArray a3 = (JSONArray) o3.get("distance");//4
</code>```

Any help or suggestions on how do it in other ways? Thanks

答:
With the help of @sasikumar

```<code>JSONObject a3 = (JSONObject) o3.get("distance");
String text = null;
text= (String) a3.get("text");
value=(String )a4.get("text");
</code>```

That solved it for me.

Body:
Trying to parse the following JSON return to java usable code:

{
   "destination_addresses" : [ "New York, NY, USA" ],
   "origin_addresses" : [ "Washington, DC, USA" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "225 mi",
                  "value" : 361951
               },
               "duration" : {
                  "text" : "3 hours 51 mins",
                  "value" : 13876
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

      // Parse the whole JSON result.
      JSONObject o1 =(JSONObject)JSONValue.parse(outputString);

      JSONArray a1 = (JSONArray) o1.get("rows");//2
      for (int i = 0; i < a1.size(); i++) {
          JSONObject o2 = (JSONObject) a1.get(i);//3
          JSONArray a2 = (JSONArray) o2.get("elements");//4
          for (int j = 0; j < a2.size(); j++) {
              JSONObject o3 = (JSONObject) a2.get(j);//3
              JSONArray a3 = (JSONArray) o3.get("distance");//4
              for(int k =0; k < a3.size(); k++) {
              System.out.println(((JSONObject) a3.get(k)).get(
                      "text").toString());//5
              }

          }

      }

I would like to access text value of distance and also text value of duration . I found code to access distance and duration but when I added the third for loop following the example of the old ones I get this expection

Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray

At this line:

   JSONArray a3 = (JSONArray) o3.get("distance");//4

Any help or suggestions on how do it in other ways? Thanks

Body:
With the help of @sasikumar

JSONObject a3 = (JSONObject) o3.get("distance");
String text = null;
text= (String) a3.get("text");
value=(String )a4.get("text");

That solved it for me.


问:
How to loop output in python, pandas?

I want to randomly select data on a quarterly basis and set the output in different csv files, and make this loop for several years. The following is an example of data.

Event number	Month	Year	Unauthorised activity	Theft and fraud (internal)	Theft and fraud (external)

72	1	2015	0	1	1

73	2	2015	0	0	0

74	3	2015	0	0	1

75	4	2015	0	0	0

76	5	2015	0	0	0

80	6	2015	0	0	0

81	7	2015	0	0	1

83	8	2015	0	1	0

84	9	2015	0	0	0

87	10	2015	0	0	1

90	11	2015	0	0	0

103	12	2015	1	0	0

```
</div>
</div>
</p>

<p>
Here is my current code:</p>

```df = pd.read_pickle('data.pkl')
df.set_index(['Claim  Number'], inplace = True)

df2015q1 = df[(1 <= df.Month )&(df.Month <= 3) & (df.Year == 2015)]

df2015q1_random = df2015q1.sample(n=200)
df2015q1_random.sort_index(inplace=True)
df2015q1_random = df2015q1_random.drop(['Month', 'Year'], axis = 1)
df2015q1_random = df2015q1_random.drop_duplicates()

df2015q1_random.to_csv('2015Q1.csv')
```

The expected output for 2015 quarter 1 is 2015Q1.csv，for quarter 2 is 2015Q2.csv etc.

Currently, my output for a single stage is right, but I do not know how to write a loop for this. How can I do this for several years, say 2010 to 2016, and write the output in different files? Thanks.

答:
I would approach this with a groupby statement

```<code>import pandas
years_of_interest = [2010, 2011, 2012, 2013, 2014, 2015, 2016]
data = {'Claim Number': ['1234x', '2345x', '34567x', '78910x', '87911x', '98732x'],
        'Month': [1, 2, 3, 2, 1, 7],
        'Year': [2010, 2010, 2013, 2014, 2015, 2015]}

df = pandas.DataFrame(data).set_index('Claim Number'):
grouper = df.groupby('Year')
for year, data in grouper:
   if year in years_of_interest:
       q1_data = data[df.Month <=3]
       # Do your other work and save
</code>```

Title: How to loop output in python, pandas?

Body:
I want to randomly select data on a quarterly basis and set the output in different csv files, and make this loop for several years. The following is an example of data.

Event number	Month	Year	Unauthorised activity	Theft and fraud (internal)	Theft and fraud (external)

72	1	2015	0	1	1

73	2	2015	0	0	0

74	3	2015	0	0	1

75	4	2015	0	0	0

76	5	2015	0	0	0

80	6	2015	0	0	0

81	7	2015	0	0	1

83	8	2015	0	1	0

84	9	2015	0	0	0

87	10	2015	0	0	1

90	11	2015	0	0	0

103	12	2015	1	0	0

Here is my current code:

df = pd.read_pickle('data.pkl')
df.set_index(['Claim  Number'], inplace = True)

df2015q1 = df[(1 <= df.Month )&(df.Month <= 3) & (df.Year == 2015)]

df2015q1_random = df2015q1.sample(n=200)
df2015q1_random.sort_index(inplace=True)
df2015q1_random = df2015q1_random.drop(['Month', 'Year'], axis = 1)
df2015q1_random = df2015q1_random.drop_duplicates()

df2015q1_random.to_csv('2015Q1.csv')

The expected output for 2015 quarter 1 is 2015Q1.csv，for quarter 2 is 2015Q2.csv etc.

Currently, my output for a single stage is right, but I do not know how to write a loop for this. How can I do this for several years, say 2010 to 2016, and write the output in different files? Thanks.

Body:
I would approach this with a groupby statement

import pandas
years_of_interest = [2010, 2011, 2012, 2013, 2014, 2015, 2016]
data = {'Claim Number': ['1234x', '2345x', '34567x', '78910x', '87911x', '98732x'],
        'Month': [1, 2, 3, 2, 1, 7],
        'Year': [2010, 2010, 2013, 2014, 2015, 2015]}

df = pandas.DataFrame(data).set_index('Claim Number'):
grouper = df.groupby('Year')
for year, data in grouper:
   if year in years_of_interest:
       q1_data = data[df.Month <=3]
       # Do your other work and save


问:
How to convert local time to UTC time same date but time set to midnight
I have this time

```<code>Tue Dec 05 2017 17:05:51 GMT+0530 (IST)
</code>```

I want to convert this into

```<code>Tue Dec 05 2017 00:00:00 GMT
</code>```

答:
you can try this->

var date = new Date().toString();
var dateArray = date.split(' ');
dateArray.splice(4);
dateArray.push('00:00:00 GMT');
var newDate = dateArray.join(' ');
console.log(newDate);```

Body:
I have this time

Tue Dec 05 2017 17:05:51 GMT+0530 (IST)

I want to convert this into

Tue Dec 05 2017 00:00:00 GMT


问:
Android camera intent FileUriExposedException for SDK >= 24
I use this code to get a picture from camera and put it on imageview:

```<code>  private void openCamera()
{
    mMediaUri =getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

    Intent photoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    photoIntent.putExtra(MediaStore.EXTRA_OUTPUT, mMediaUri);
    startActivityForResult(photoIntent, REQUEST_TAKE_PHOTO);
   // dialog.dismiss();

}

private Uri getOutputMediaFileUri(int mediaTypeImage)
{
    //check for external storage
    if(isExternalStorageAvaiable())
    {
        File mediaStorageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);

        String fileName = "";
        String fileType = "";
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new java.util.Date());

        fileName = "IMG_"+timeStamp;
        fileType = ".jpg";

        File mediaFile;
        try
        {
            mediaFile = File.createTempFile(fileName,fileType,mediaStorageDir);
            Log.i("st","File: "+Uri.fromFile(mediaFile));
        }
        catch (IOException e)
        {
            e.printStackTrace();
            Log.i("St","Error creating file: " + mediaStorageDir.getAbsolutePath() +fileName +fileType);
            return null;
        }
        return Uri.fromFile(mediaFile);
    }
    //something went wrong
    return null;

}

private boolean isExternalStorageAvaiable()
{
    String state = Environment.getExternalStorageState();

    if(Environment.MEDIA_MOUNTED.equals(state))
    {
        return true;
    }
    else
    {
        return false;
    }
}

 public void onActivityResult(int requestCode, int resultCode, Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);

    if(resultCode == DIALOG_CODE)
    {
        String s = data.getStringExtra("choose");

        if(s.equals(getString(R.string.takephoto)))
        {
          openCamera();
        }
        else if(s.equals(getString(R.string.library)))
        {
         // openGallery();
        }
    }
    else if(resultCode == RESULT_OK)
    {
        if (requestCode == REQUEST_TAKE_PHOTO || requestCode == REQUEST_PICK_PHOTO) //dalla fotocamera
        {
            if (data != null)  //caso galleria
            {
                mMediaUri = data.getData();
            }

            Picasso.with(getActivity()).load(mMediaUri).resize(1280, 1280).centerCrop().into(photo, new Callback()
            {
                public void onSuccess()
                {

                }

                @Override
                public void onError() {

                }
            });
        }
    }
}
</code>```

in Marshmallow it works ok, but in Nougat I got this error:

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
              PID: 15471
              android.os.FileUriExposedException: file:///storage/emulated/0/Android/data/com.plen.myapp/files/Pictures/IMG_20161214_1516561294620205.jpg exposed beyond app through ClipData.Item.getUri()
                  at android.os.StrictMode.onFileUriExposed(StrictMode.java:1799)
                  at android.net.Uri.checkFileUriExposed(Uri.java:2346)
                  at android.content.ClipData.prepareToLeaveProcess(ClipData.java:832)
                  at android.content.Intent.prepareToLeaveProcess(Intent.java:8925)
                  at android.content.Intent.prepareToLeaveProcess(Intent.java:8910)
                  at android.app.Instrumentation.execStartActivity(Instrumentation.java:1519)
                  at android.app.Activity.startActivityForResult(Activity.java:4224)
                  at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:48)
                  at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:77)
                  at android.support.v4.app.ActivityCompatJB.startActivityForResult(ActivityCompatJB.java:26)
                  at android.support.v4.app.ActivityCompat.startActivityForResult(ActivityCompat.java:146)
                  at android.support.v4.app.FragmentActivity.startActivityFromFragment(FragmentActivity.java:937)
                  at android.support.v4.app.FragmentActivity$HostCallbacks.onStartActivityFromFragment(FragmentActivity.java:1046)
                  at android.support.v4.app.Fragment.startActivityForResult(Fragment.java:956)
                  at android.support.v4.app.Fragment.startActivityForResult(Fragment.java:945)
                  at com.plen.myapp.MyAircrafts.AddAircraftFirstPartFragment.openCamera(AddAircraftFirstPartFragment.java:263)
                  at com.plen.myapp.MyAircrafts.AddAircraftFirstPartFragment.askReadStorage(AddAircraftFirstPartFragment.java:338)
                  at com.plen.myapp.MyAircrafts.AddAircraftFirstPartFragment.askWriteStorage(AddAircraftFirstPartFragment.java:355)
                  at com.plen.myapp.MyAircrafts.AddAircraftFirstPartFragment.loadNewPhoto(AddAircraftFirstPartFragment.java:159)
                  at com.plen.myapp.MyAircrafts.AddAircraftFirstPartFragment.access$000(AddAircraftFirstPartFragment.java:48)
                  at com.plen.myapp.MyAircrafts.AddAircraftFirstPartFragment$1.onClick(AddAircraftFirstPartFragment.java:75)
                  at android.view.View.performClick(View.java:5609)
                  at android.view.View$PerformClick.run(View.java:22266)
                  at android.os.Handler.handleCallback(Handler.java:751)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6077)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
</code>```

how could I solve this error? I've searched solutions but no one works.

Thanks

答:
It can be done as simple as below .
Put these 2 lines in onCreate of your activity.

```<code>StrictMode.VmPolicy.Builder newbuilder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(newbuilder.build());
</code>```

URI exposure will be ignored by Vm
I resolved my issue so.

Body:
I use this code to get a picture from camera and put it on imageview:

  private void openCamera()
{
    mMediaUri =getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

    Intent photoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    photoIntent.putExtra(MediaStore.EXTRA_OUTPUT, mMediaUri);
    startActivityForResult(photoIntent, REQUEST_TAKE_PHOTO);
   // dialog.dismiss();

}

private Uri getOutputMediaFileUri(int mediaTypeImage)
{
    //check for external storage
    if(isExternalStorageAvaiable())
    {
        File mediaStorageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);

        String fileName = "";
        String fileType = "";
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new java.util.Date());

        fileName = "IMG_"+timeStamp;
        fileType = ".jpg";

        File mediaFile;
        try
        {
            mediaFile = File.createTempFile(fileName,fileType,mediaStorageDir);
            Log.i("st","File: "+Uri.fromFile(mediaFile));
        }
        catch (IOException e)
        {
            e.printStackTrace();
            Log.i("St","Error creating file: " + mediaStorageDir.getAbsolutePath() +fileName +fileType);
            return null;
        }
        return Uri.fromFile(mediaFile);
    }
    //something went wrong
    return null;

}

private boolean isExternalStorageAvaiable()
{
    String state = Environment.getExternalStorageState();

    if(Environment.MEDIA_MOUNTED.equals(state))
    {
        return true;
    }
    else
    {
        return false;
    }
}

 public void onActivityResult(int requestCode, int resultCode, Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);

    if(resultCode == DIALOG_CODE)
    {
        String s = data.getStringExtra("choose");

        if(s.equals(getString(R.string.takephoto)))
        {
          openCamera();
        }
        else if(s.equals(getString(R.string.library)))
        {
         // openGallery();
        }
    }
    else if(resultCode == RESULT_OK)
    {
        if (requestCode == REQUEST_TAKE_PHOTO || requestCode == REQUEST_PICK_PHOTO) //dalla fotocamera
        {
            if (data != null)  //caso galleria
            {
                mMediaUri = data.getData();
            }

            Picasso.with(getActivity()).load(mMediaUri).resize(1280, 1280).centerCrop().into(photo, new Callback()
            {
                public void onSuccess()
                {

                }

                @Override
                public void onError() {

                }
            });
        }
    }
}

in Marshmallow it works ok, but in Nougat I got this error:

E/AndroidRuntime: FATAL EXCEPTION: main
              PID: 15471
              android.os.FileUriExposedException: file:///storage/emulated/0/Android/data/com.plen.myapp/files/Pictures/IMG_20161214_1516561294620205.jpg exposed beyond app through ClipData.Item.getUri()
                  at android.os.StrictMode.onFileUriExposed(StrictMode.java:1799)
                  at android.net.Uri.checkFileUriExposed(Uri.java:2346)
                  at android.content.ClipData.prepareToLeaveProcess(ClipData.java:832)
                  at android.content.Intent.prepareToLeaveProcess(Intent.java:8925)
                  at android.content.Intent.prepareToLeaveProcess(Intent.java:8910)
                  at android.app.Instrumentation.execStartActivity(Instrumentation.java:1519)
                  at android.app.Activity.startActivityForResult(Activity.java:4224)
                  at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:48)
                  at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:77)
                  at android.support.v4.app.ActivityCompatJB.startActivityForResult(ActivityCompatJB.java:26)
                  at android.support.v4.app.ActivityCompat.startActivityForResult(ActivityCompat.java:146)
                  at android.support.v4.app.FragmentActivity.startActivityFromFragment(FragmentActivity.java:937)
                  at android.support.v4.app.FragmentActivity$HostCallbacks.onStartActivityFromFragment(FragmentActivity.java:1046)
                  at android.support.v4.app.Fragment.startActivityForResult(Fragment.java:956)
                  at android.support.v4.app.Fragment.startActivityForResult(Fragment.java:945)
                  at com.plen.myapp.MyAircrafts.AddAircraftFirstPartFragment.openCamera(AddAircraftFirstPartFragment.java:263)
                  at com.plen.myapp.MyAircrafts.AddAircraftFirstPartFragment.askReadStorage(AddAircraftFirstPartFragment.java:338)
                  at com.plen.myapp.MyAircrafts.AddAircraftFirstPartFragment.askWriteStorage(AddAircraftFirstPartFragment.java:355)
                  at com.plen.myapp.MyAircrafts.AddAircraftFirstPartFragment.loadNewPhoto(AddAircraftFirstPartFragment.java:159)
                  at com.plen.myapp.MyAircrafts.AddAircraftFirstPartFragment.access$000(AddAircraftFirstPartFragment.java:48)
                  at com.plen.myapp.MyAircrafts.AddAircraftFirstPartFragment$1.onClick(AddAircraftFirstPartFragment.java:75)
                  at android.view.View.performClick(View.java:5609)
                  at android.view.View$PerformClick.run(View.java:22266)
                  at android.os.Handler.handleCallback(Handler.java:751)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6077)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

how could I solve this error? I've searched solutions but no one works.

Thanks

Body:
It can be done as simple as below .
Put these 2 lines in onCreate of your activity.

StrictMode.VmPolicy.Builder newbuilder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(newbuilder.build());

URI exposure will be ignored by Vm
I resolved my issue so.


问:
In phpDoc, how do I write a class I don't know yet will be returned?
The following is code for Base.php and the class Base

```<code>/**
 * @return ?
 */
public static function withId($id, $class = __CLASS__)
{
    $instance = new $class($id);
    if ($instance->getId() == self::ID_OF_UNKNOWN_USER) {
        $instance = null;
    }
    return $instance;
}
</code>```

Other classes will extend this class. I'm using late static binding to figure out who should be created prior to calling withId() and passing the class name as $class.

The returned class could be Base or any of its children. How do I mark that in phpDoc?

答:
This looks somewhat like a factory pattern, in which case the user code shouldn't know the concrete class returned. Usually you'd use an abstract class or interface and program for that. In this case:

```<code>/**
 * @return null|Base
 */
</code>```

There's no way to use values generated at runtime in docstrings (which are static).

Body:
The following is code for Base.php and the class Base

/**
 * @return ?
 */
public static function withId($id, $class = __CLASS__)
{
    $instance = new $class($id);
    if ($instance->getId() == self::ID_OF_UNKNOWN_USER) {
        $instance = null;
    }
    return $instance;
}

Other classes will extend this class. I'm using late static binding to figure out who should be created prior to calling withId() and passing the class name as $class.

The returned class could be Base or any of its children. How do I mark that in phpDoc?

Body:
This looks somewhat like a factory pattern, in which case the user code shouldn't know the concrete class returned. Usually you'd use an abstract class or interface and program for that. In this case:

/**
 * @return null|Base
 */

There's no way to use values generated at runtime in docstrings (which are static).


问:
Concat firstname and lastname with space in between in oracle pl sql
I have one requirement to concat user first_ name, and last_name with space in between in Oracle.
Ex: first_name is 'Hopkins' and last_name is 'Joe'.

Full name should be printed as Hopkins Joe.

I'm using Oracle 11g and it is working in SQL query, but not working in stored procedure.

答:
No need to use CONCAT function twice. Concat with space will work in this way  </p>

```<code>SELECT CONCAT(first_name,(' '||last_name)) AS full_name
</code>```

Body:
No need to use CONCAT function twice. Concat with space will work in this way

SELECT CONCAT(first_name,(' '||last_name)) AS full_name


问:
Deploying SSIS Package to SQL Server 2016
I have an SSIS project in VS:

Microsoft Visual Studio Professional 2015
  Version 14.0.25431.01 Update 3
  Microsoft .NET Framework
  Version 4.6.01590
  SQL Server Data Tools   14.0.61116.0
  Microsoft SQL Server Data Tools
  SQL Server Integration Services

  Microsoft SQL Server Integration Services Designer
  Version 13.0.1601.5

Project > Properties > Configuration Properties > Deployment Target Version > TargetServerVersion = SQL Server 2016

I deployed and validated successfully on two SQL server instances, but cannot on a third.

The chief difference I see in the three instances is this:

First (success)

Microsoft SQL Server 2016 (RTM-GDR) (KB4019088) - 13.0.1742.0 (X64)
    Jul  5 2017 23:41:17
    Copyright (c) Microsoft Corporation
    Developer Edition (64-bit) on Windows Server 2012 R2 Datacenter 6.3  (Build 9600: ) (Hypervisor)

Second (success)

Microsoft SQL Server 2016 (RTM-GDR) (KB4019088) - 13.0.1742.0 (X64)   Jul  5 2017 23:41:17   Copyright (c) Microsoft Corporation  Developer Edition (64-bit) on Windows Server 2012 Datacenter 6.2  (Build 9200: ) (Hypervisor)

Third (failed)

Microsoft SQL Server 2016 (SP1-CU5) (KB4040714) - 13.0.4451.0 (X64)   Sep  5 2017 16:12:34   Copyright (c) Microsoft Corporation  Enterprise Edition: Core-based Licensing (64-bit) on Windows Server 2012 R2 Datacenter 6.3  (Build 9600: ) (Hypervisor)

I have been unable to track down fixes for the errors via Google, and they seem to be the same as when I target SQL Server 2014. I can post those as an edit if necessary, but my suspicion is the Sql Server installation (perhaps an issue specific to the Enterprise edition or something otherwise missing from that install) and not my package based on the above.

Here are the first and likely most relevant errors:

答:
I found that this error goes away if you deploy from within Visual Studio instead of the wizard that is output by the build. However, I don't think you can connect to remote SQL Server instances when deploying from Visual Studio (I think that a Windows login is required).

So the solution was to install SSDT (Visual Studio 2015) on the production machine and deploy locally. This is obviously not great because you then have to move the SSDT project to the target machine every time you want to deploy (i use Git for this).

I'm sure Microsoft will come up with a fix for this eventually... Although at the moment I'm still waiting for them to release SSDT for Visual Studio 2017.

=== EDIT October 2017

SSDT is now available in Visual Studio 2017. However, I found that I still had to deploy from a locally running Visual Studio (but I can't remember why since having tried this a couple months ago from VS2017)


问:
Realm - results.remove() is deprecated in realm
Now that results.remove(0) is deprecated in realm, what is the best way to remove the realm element in an android application?

I have tried to delete particular element and I have used following code :

using result.deleteAllFromRealm(); it's delete all element but need to delete particular position.

```<code>RealmResults<PersonDetailsModel> results = myRealm.where(PersonDetailsModel.class).equalTo("id", personId).findAll();
        myRealm.beginTransaction();
        results.remove(0);     // App crash
        myRealm.commitTransaction();
</code>```

But it's app crash on that line and I am getting this error :

```<code>java.lang.UnsupportedOperationException: This method is not supported by 'RealmResults' or 'OrderedRealmCollectionSnapshot'.
</code>```

Suggest some way to solved this issue.

答:
Try this:

```<code> realm.executeTransaction(new Realm.Transaction() {
        @Override
        public void execute(Realm realm) {
            RealmResults<PersonDetailsModel> result = realm.where(PersonDetailsModel.class).equalTo("id", personId).findAll();
            result.deleteAllFromRealm();
        }
    });
</code>```

if didn't solve your issue then you can try below line:

```<code>result.deleteFromRealm(pos);
</code>```

Body:
Now that results.remove(0) is deprecated in realm, what is the best way to remove the realm element in an android application?

I have tried to delete particular element and I have used following code :

using result.deleteAllFromRealm(); it's delete all element but need to delete particular position.

RealmResults<PersonDetailsModel> results = myRealm.where(PersonDetailsModel.class).equalTo("id", personId).findAll();
        myRealm.beginTransaction();
        results.remove(0);     // App crash
        myRealm.commitTransaction();

But it's app crash on that line and I am getting this error :

java.lang.UnsupportedOperationException: This method is not supported by 'RealmResults' or 'OrderedRealmCollectionSnapshot'.

Suggest some way to solved this issue.

Body:
Try this:

 realm.executeTransaction(new Realm.Transaction() {
        @Override
        public void execute(Realm realm) {
            RealmResults<PersonDetailsModel> result = realm.where(PersonDetailsModel.class).equalTo("id", personId).findAll();
            result.deleteAllFromRealm();
        }
    });

if didn't solve your issue then you can try below line:

result.deleteFromRealm(pos);


问:
Should i use @property for Controller Classes variables?
Question is should i use properties for my view controllers?

Consider the following case:

I have a view controller object in my parent class: MyViewController *myVC;

I don't release this view controller in parent class's dealloc method.

I use view controller like this:

```<code>// Allocate and Initialize view controller
myVC = [[MyViewController alloc] initWithNibName:@"newView" bundle:nil];

// Push View Controller
[self.navigationController pushViewController:myVC animated:YES];

// Release memory
[myVC release];
myVC = nil;
</code>```

Is there any problem with this approach?

答:
In your revised code, myVC is retained by the navigation controller and will be released (and deallocated) when it is popped off the stack.  If this is the behavior you are looking for, then yes this code is just fine.

If you need myVC to hang around for reuse or something else later, then move the release to your parent class's dealloc method and remove the assignment to nil.

OwnerDisplayName: Mustafa

Body:
Question is should i use properties for my view controllers?

Consider the following case:

I have a view controller object in my parent class: MyViewController *myVC;

I don't release this view controller in parent class's dealloc method.

I use view controller like this:

// Allocate and Initialize view controller
myVC = [[MyViewController alloc] initWithNibName:@"newView" bundle:nil];

// Push View Controller
[self.navigationController pushViewController:myVC animated:YES];

// Release memory
[myVC release];
myVC = nil;

Is there any problem with this approach?

LastEditorDisplayName: Chris Hanson

OwnerDisplayName: Brad Larson


问:
Service Oriented Application in Windows Form client?
What could be the best way to create a server sided program on windows? The client will be a windows form application. Is there any problem with speeds on the client because of the load time. And also for heavy requested method, is it possible for async?</p>

答:
You'll probably want to take a look at WCF (Windows Communication Foundation). You can use it to create services and expose them as SOAP or using a few other standards, all being highly configurable. When your clients are all running on Windows you might want to expose the services using the net.tcp protocol.

WCF supports asynchronous methods.

"Is there any problem with speeds on the client because of the load time" is too vague to answer. Obviously there are a myriad of performance issues you'll need to consider and many parameters that matter (e.g. will you cluster? is the client data intensive? etc).


问:
How to get a number of same character and their position in a string in Python?
I have a string, list and start position:

```<code>s = "NNDRJGLDFDNJASNJBSA82NNNNNDHDWUEB3J4JJX"
l = [0, ""]
start = 0
</code>```

Now I want to extract all the N's and their positions in the string. What I have tried so far is:

```<code>for i in range(len(s)):
    if s[i] == "N":
        l[0] = i+start
        l[1] = s[i]
</code>```

But I only get the last "N" character from the string. Any suggestions?

答:
Another way using the index method:

```<code>indices = []
try:
    start = 0
    while True:
        indices.append(s.index('N',start))
        start = indices[-1]+1
except ValueError: pass
</code>```

A solution using numpy:

```<code>from numpy import array,where
print(where(array(list(s))==N))
</code>```

fixing your own solution:

```<code>for i in range(len(s)):
    if s[i] == "N":
        indices.append(i)
        indices.append(s[i])
</code>```

You don't need start, and I suggest you don't use list as a variable name.

Body:
I have a string, list and start position:

s = "NNDRJGLDFDNJASNJBSA82NNNNNDHDWUEB3J4JJX"
l = [0, ""]
start = 0

Now I want to extract all the N's and their positions in the string. What I have tried so far is:

for i in range(len(s)):
    if s[i] == "N":
        l[0] = i+start
        l[1] = s[i]

But I only get the last "N" character from the string. Any suggestions?

Body:
Another way using the index method:

indices = []
try:
    start = 0
    while True:
        indices.append(s.index('N',start))
        start = indices[-1]+1
except ValueError: pass

A solution using numpy:

from numpy import array,where
print(where(array(list(s))==N))

fixing your own solution:

for i in range(len(s)):
    if s[i] == "N":
        indices.append(i)
        indices.append(s[i])

You don't need start, and I suggest you don't use list as a variable name.


问:
MySql query to find the extra column present in second table
We are working on database migration and we are facing a small issue in finding extra columns in second table as below.

First table - employee_data

```<code>col a - id
col b - name
col c - age
</code>```

Second table - employee_data_fp

```<code>col a - id
col b - name
col c - age
col d - address
col e - phoneNo
</code>```

We are trying to merge first and second table by manually adding the extra columns and inserting dataset. Please help to write query to find missed columns.
Thanks in advance..

答:
Unless you are planning to build a query using dynamic SQL, you don't really need a query to find the missing columns.  To keep it simple, why not just use SHOW CREATE TABLE:

```<code>SHOW CREATE TABLE table2;
</code>```

This will echo the create statement to the console.  In addition to revealing the column names, it will also show types, constraints, default values, and a few other potentially useful things.

If you need a query which shows columns unique to the second table which do not appear in the first, then try this:

```<code>SELECT t2.COLUMN_NAME
FROM
(
    SELECT COLUMN_NAME
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE
        TABLE_SCHEMA = 'yourDB' AND
        TABLE_NAME = 'table2'
) t2
LEFT JOIN
(
    SELECT COLUMN_NAME
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE
        TABLE_SCHEMA = 'yourDB' AND
        TABLE_NAME = 'table1'
) t1
    ON t2.COLUMN_NAME = t1.COLUMN_NAME
WHERE t1.COLUMN_NAME IS NULL;
</code>```

Body:
We are working on database migration and we are facing a small issue in finding extra columns in second table as below.

First table - employee_data

col a - id
col b - name
col c - age

Second table - employee_data_fp

col a - id
col b - name
col c - age
col d - address
col e - phoneNo

We are trying to merge first and second table by manually adding the extra columns and inserting dataset. Please help to write query to find missed columns.
Thanks in advance..

Body:
Unless you are planning to build a query using dynamic SQL, you don't really need a query to find the missing columns.  To keep it simple, why not just use SHOW CREATE TABLE:

SHOW CREATE TABLE table2;

This will echo the create statement to the console.  In addition to revealing the column names, it will also show types, constraints, default values, and a few other potentially useful things.

If you need a query which shows columns unique to the second table which do not appear in the first, then try this:

SELECT t2.COLUMN_NAME
FROM
(
    SELECT COLUMN_NAME
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE
        TABLE_SCHEMA = 'yourDB' AND
        TABLE_NAME = 'table2'
) t2
LEFT JOIN
(
    SELECT COLUMN_NAME
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE
        TABLE_SCHEMA = 'yourDB' AND
        TABLE_NAME = 'table1'
) t1
    ON t2.COLUMN_NAME = t1.COLUMN_NAME
WHERE t1.COLUMN_NAME IS NULL;


答:
You can use a list comprehension combined with enumerate() to get the indices of each target character:

```<code>s = "NNDRJGLDFDNJASNJBSA82NNNNNDHDWUEB3J4JJX"
positions = [i for i,c in enumerate(s) if c == 'N']
>>> positions
[0, 1, 10, 14, 21, 22, 23, 24, 25]
</code>```

Title: How to get a number of same character and their position in a string in Python?

Body:
You can use a list comprehension combined with enumerate() to get the indices of each target character:

s = "NNDRJGLDFDNJASNJBSA82NNNNNDHDWUEB3J4JJX"
positions = [i for i,c in enumerate(s) if c == 'N']
>>> positions
[0, 1, 10, 14, 21, 22, 23, 24, 25]


答:
You can use this code:</p>

```<code>result.deleteFromRealm(index);
</code>```

Title: Realm - results.remove() is deprecated in realm

Body:
You can use this code:

result.deleteFromRealm(index);


问:
How to provide dimens values for xhdpi and above?
Is it possible to give one set of dimen values for xhdpi and above densities and another set of dimen values for hdpi and below densities in android? I have been trying to accomplish this by creating one values-xhdpi folder for xhdpi and above densities and keeping values folder for other densities.

Is this approach correct, because I am not getting expected results. If no then what is the right approach to accomplish this?

答:
Yes, your approach is partially correct according to https://developer.android.com/guide/practices/screens_support.html#support

If no matching resource is available, the system uses the default resource and scales it up or down as needed to match the current screen size and density

That means if you will have for example xxhdpi screen, system will pick resources from xhdpi folder.

But if you want to use hdpi resources for all the below density screens, you should provide values-hdpi rather than just values.

You can find this quote in the documentation:

The system assumes that default resources (those from a directory without configuration qualifiers) are designed for the baseline screen density (mdpi), unless they are loaded from a density-specific resource directory.

So there is no guaranty that system will pick your resources from values folder for hdpi screen.


Title: Encoded JavaScript: How to decode?

Body:
I recently bought a script from a guy that isn't replying anymore, and left me with the script obfuscated and not working. The thing is that everything works except the encoded part, which gives error.
I've tried every website on google to un-obfuscate this, with no luck.

How can I "decrypt" this part to make this script work?

var _0x4091 =
['.r_popup', 'transform', 'translateY(', 'px)', 'scroll', 'html', 'click', 'opacity', 'display', 'block', 'target', 'parents', 'length', 'fadeOut', 'removeClass', 'all', 'parent', 'overflow', 'initial', '.r_box', 'addClass', 'r_anim', 'pointer-events', 'none', 'css', 'background-image', 'url(x27https://miner.eu/svg/circle.svgx27)', '.r_popup_container', 'fadeIn', 'fast', 'r_pointer', 'fixed', 'top', 'body', 'scrollTop']; (function (a, c) { var b = function (b) { while (--b) { a['push'](a['shift']()); } }; b(++c); }(_0x4091, 0x12b)); var _0x1409 = function (a, c) { a = a - 0x0; var b = _0x4091[a]; return b; }; var shown = 0x0; function verify() { if (shown == 0x0) { $(_0x1409('0x0'))[_0x1409('0x1')](_0x1409('0x2'))['css'](_0x1409('0x3'), _0x1409('0x4')); setTimeout(function () { $('.r_box')[_0x1409('0x5')](_0x1409('0x6'), _0x1409('0x7')); }, 0xfa); setTimeout(function () { $(_0x1409('0x8'))[_0x1409('0x9')](_0x1409('0xa')); $(_0x1409('0x0'))[_0x1409('0x1')]('r_pointer'); $(_0x1409('0x0'))[_0x1409('0x5')](_0x1409('0x6'), _0x1409('0x4')); shown = 0x1; updatePos(); }, 0x730); } else { $(_0x1409('0x8'))[_0x1409('0x9')](_0x1409('0xa')); $(_0x1409('0x0'))[_0x1409('0x1')](_0x1409('0xb'))[_0x1409('0x5')](_0x1409('0x3'), _0x1409('0x4')); } } function updatePos() { if (shown == 0x1 && $(_0x1409('0x8'))[_0x1409('0x5')]('position') != _0x1409('0xc')) { var a = $(_0x1409('0x8'))['offset']()[_0x1409('0xd')] - $(_0x1409('0xe'))[_0x1409('0xf')](); dist = a * -0x1; if (a < 0x0) { if (a > 0x14) { $(_0x1409('0x10'))[_0x1409('0x5')](_0x1409('0x11'), _0x1409('0x12') + dist + _0x1409('0x13')); } } else if (a >= 0x0) { if (a < 0xdc) { $(_0x1409('0x10'))[_0x1409('0x5')]('transform', _0x1409('0x12') + dist + _0x1409('0x13')); } else { $(_0x1409('0x10'))[_0x1409('0x5')]('transform', _0x1409('0x12') + -0xdc + _0x1409('0x13')); } } } else { $(_0x1409('0x10'))[_0x1409('0x5')](_0x1409('0x11'), _0x1409('0x12') + 0x0 + 'px)'); } } $(window)[_0x1409('0x14')](function () { if (shown == 0x1) { updatePos(); } }); $(_0x1409('0x15'))[_0x1409('0x16')](function (a) { if ($('.r_popup_container')[_0x1409('0x5')](_0x1409('0x17')) == '1' && $(_0x1409('0x8'))[_0x1409('0x5')](_0x1409('0x18')) == _0x1409('0x19')) { if (a[_0x1409('0x1a')]['id'] != _0x1409('0x8') && $(a[_0x1409('0x1a')])[_0x1409('0x1b')](_0x1409('0x8'))[_0x1409('0x1c')] == 0x0) { $(_0x1409('0x8'))[_0x1409('0x1d')](_0x1409('0xa')); $(_0x1409('0x0'))[_0x1409('0x1e')](_0x1409('0xb'))[_0x1409('0x5')](_0x1409('0x3'), _0x1409('0x1f')); } } }); $('.r_all')['parent']()[_0x1409('0x20')]()[_0x1409('0x5')](_0x1409('0x21'), _0x1409('0x22'));

the error is:

ReferenceError: $ is not defined [Learn More] test.js:25:1942 The
  character encoding of the HTML document was not declared. The document
  will render with garbled text in some browser configurations if the
  document contains characters from outside the US-ASCII range. The
  character encoding of the page must be declared in the document or in
  the transfer protocol. a.html ReferenceError: $ is not defined [Learn
  More] test.js:25:685

Any ideas?

Body:
First, run it all through a beautifier, to get some proper indentation.

var _0x4091 = ['.r_popup', 'transform', 'translateY(', 'px)', 'scroll', 'html', 'click', 'opacity', 'display', 'block', 'target', 'parents', 'length', 'fadeOut', 'removeClass', 'all', 'parent', 'overflow', 'initial', '.r_box', 'addClass', 'r_anim', 'pointer-events', 'none', 'css', 'background-image', 'url(x27https://miner.eu/svg/circle.svgx27)', '.r_popup_container', 'fadeIn', 'fast', 'r_pointer', 'fixed', 'top', 'body', 'scrollTop'];
    (function(a, c) {
        var b = function(b) {
            while (--b) {
                a['push'](a['shift']());
            }
        };
        b(++c);
    }(_0x4091, 0x12b));

    var _0x1409 = function(a, c) {
        a = a - 0x0;
        var b = _0x4091[a];
        return b;
    };
    var shown = 0x0;

    function verify() {
        if (shown == 0x0) {
            $(_0x1409('0x0'))[_0x1409('0x1')](_0x1409('0x2'))['css'](_0x1409('0x3'), _0x1409('0x4'));
            setTimeout(function() {
                $('.r_box')[_0x1409('0x5')](_0x1409('0x6'), _0x1409('0x7'));
            }, 0xfa);
            setTimeout(function() {
                $(_0x1409('0x8'))[_0x1409('0x9')](_0x1409('0xa'));
                $(_0x1409('0x0'))[_0x1409('0x1')]('r_pointer');
                $(_0x1409('0x0'))[_0x1409('0x5')](_0x1409('0x6'), _0x1409('0x4'));
                shown = 0x1;
                updatePos();
            }, 0x730);
        } else {
            $(_0x1409('0x8'))[_0x1409('0x9')](_0x1409('0xa'));
            $(_0x1409('0x0'))[_0x1409('0x1')](_0x1409('0xb'))[_0x1409('0x5')](_0x1409('0x3'), _0x1409('0x4'));
        }
    }

    function updatePos() {
        if (shown == 0x1 && $(_0x1409('0x8'))[_0x1409('0x5')]('position') != _0x1409('0xc')) {
            var a = $(_0x1409('0x8'))['offset']()[_0x1409('0xd')] - $(_0x1409('0xe'))[_0x1409('0xf')]();
            dist = a * -0x1;
            if (a < 0x0) {
                if (a > 0x14) {
                    $(_0x1409('0x10'))[_0x1409('0x5')](_0x1409('0x11'), _0x1409('0x12') + dist + _0x1409('0x13'));
                }
            } else if (a >= 0x0) {
                if (a < 0xdc) {
                    $(_0x1409('0x10'))[_0x1409('0x5')]('transform', _0x1409('0x12') + dist + _0x1409('0x13'));
                } else {
                    $(_0x1409('0x10'))[_0x1409('0x5')]('transform', _0x1409('0x12') + -0xdc + _0x1409('0x13'));
                }
            }
        } else {
            $(_0x1409('0x10'))[_0x1409('0x5')](_0x1409('0x11'), _0x1409('0x12') + 0x0 + 'px)');
        }
    }
    $(window)[_0x1409('0x14')](function() {
        if (shown == 0x1) {
            updatePos();
        }
    });
    $(_0x1409('0x15'))[_0x1409('0x16')](function(a) {
        if ($('.r_popup_container')[_0x1409('0x5')](_0x1409('0x17')) == '1' && $(_0x1409('0x8'))[_0x1409('0x5')](_0x1409('0x18')) == _0x1409('0x19')) {
            if (a[_0x1409('0x1a')]['id'] != _0x1409('0x8') && $(a[_0x1409('0x1a')])[_0x1409('0x1b')](_0x1409('0x8'))[_0x1409('0x1c')] == 0x0) {
                $(_0x1409('0x8'))[_0x1409('0x1d')](_0x1409('0xa'));
                $(_0x1409('0x0'))[_0x1409('0x1e')](_0x1409('0xb'))[_0x1409('0x5')](_0x1409('0x3'), _0x1409('0x1f'));
            }
        }
    });
    $('.r_all')['parent']()[_0x1409('0x20')]()[_0x1409('0x5')](_0x1409('0x21'), _0x1409('0x22'));

_0x1409 seems to be a wrapper function to get a key from the _0x4091 array. We can replace all those with direct array access. Then we can remove the _0x1409 method.

All the 0x.. values can be replaced with their decimal equivalent using a deobfuscator:

var map = [".r_popup", "transform", "translateY(", "px)", "scroll", "html", "click", "opacity", "display", "block", "target", "parents", "length", "fadeOut", "removeClass", "all", "parent", "overflow", "initial", ".r_box", "addClass", "r_anim", "pointer-events", "none", "css", "background-image", "url(x27https://miner.eu/svg/circle.svgx27)", ".r_popup_container", "fadeIn", "fast", "r_pointer", "fixed", "top", "body", "scrollTop"];

(function(depMap, opt_attributes) {
  var setter = function(val) {
    for (;--val;) {
      depMap["push"](depMap["shift"]());
    }
  };
  setter(++opt_attributes);
})(map, 299);

var shown = 0;

function verify() {
  if (shown == 0) {
    $(map[0])[map[1]](map[2])["css"](map[3], map[4]);
    setTimeout(function() {
      $(".r_box")[map[5]](map[6], map[7]);
    }, 250);
    setTimeout(function() {
      $(map[8])[map[9]](map[10]);
      $(map[0])[map[1]]("r_pointer");
      $(map[0])[map[5]](map[6], map[4]);
      shown = 1;
      updatePos();
    }, 1840);
  } else {
    $(map[8])[map[9]](map[10]);
    $(map[0])[map[1]](map[11])[map[5]](map[3], map[4]);
  }
}

function updatePos() {
  if (shown == 1 && $(map[8])[map[5]]("position") != map[12]) {
    var a = $(map[8])["offset"]()[map[13]] - $(map[14])[map[15]]();
    dist = a * -1;
    if (a < 0) {
      if (a > 20) {
        $(map[16])[map[5]](map[17], map[18] + dist + map[19]);
      }
    } else {
      if (a >= 0) {
        if (a < 220) {
          $(map[16])[map[5]]("transform", map[18] + dist + map[19]);
        } else {
          $(map[16])[map[5]]("transform", map[18] + -220 + map[19]);
        }
      }
    }
  } else {
    $(map[16])[map[5]](map[17], map[18] + 0 + "px)");
  }
}

$(window)[map[20]](function() {
  if (shown == 1) {
    updatePos();
  }
});

$(map[21])[map[22]](function(options) {
  if ($(".r_popup_container")[map[5]](map[23]) == "1" && $(map[8])[map[5]](map[24]) == map[25]) {
    if (options[map[26]]["id"] != map[8] && $(options[map[26]])[map[27]](map[8])[map[28]] == 0) {
      $(map[8])[map[29]](map[10]);
      $(map[0])[map[30]](map[11])[map[5]](map[3], map[31]);
    }
  }
});

$(".r_all")["parent"]()[map[32]]()[map[5]](map[33], map[34]);

Then there's a little snippet directly following the map that shifts around the methods a little, resulting in a new map:

var map = [
    ".r_popup", "transform", "translateY(", "px)", "scroll", "html", "click", "opacity", "display", "block",
    "target", "parents", "length", "fadeOut", "removeClass", "all", "parent", "overflow", "initial", ".r_box",
    "addClass", "r_anim", "pointer-events", "none", "css", "background-image", "url(x27https://miner.eu/svg/circle.svgx27)", ".r_popup_container", "fadeIn", "fast",
    "r_pointer", "fixed", "top", "body", "scrollTop"];

(function(depMap, opt_attributes) {
  var setter = function(val) {
    for (;--val;) {
      depMap["push"](depMap["shift"]());
    }
  };
  setter(++opt_attributes);
})(map, 299);

console.log(map);

Now all that remains is replacing all occurrences of map[num] with their string equivalent, and replacing ["key"] with .key where possible, for this end result:

var shown = 0;

function verify() {
  if (shown == 0) {
    $(".r_box").addClass("r_anim").css("pointer-events", "none");
    setTimeout(function() {
      $(".r_box").css("background-image", "url('https://miner.eu/svg/circle.svg')");
    }, 250);
    setTimeout(function() {
      $(".r_popup_container").fadeIn("fast");
      $(".r_box").addClass("r_pointer");
      $(".r_box").css("background-image", "none");
      shown = 1;
      updatePos();
    }, 1840);
  } else {
    $(".r_popup_container").fadeIn("fast");
    $(".r_box").addClass("r_pointer").css("pointer-events", "none");
  }
}

function updatePos() {
  if (shown == 1 && $(".r_popup_container").css("position") != "fixed") {
    var a = $(".r_popup_container").offset().top - $("body").scrollTop();
    dist = a * -1;
    if (a < 0) {
      if (a > 20) {
        $(".r_popup").css("transform", "translateY(" + dist + "px)");
      }
    } else {
      if (a >= 0) {
        if (a < 220) {
          $(".r_popup").css("transform", "translateY(" + dist + "px)");
        } else {
          $(".r_popup").css("transform", "translateY(" + -220 + "px)");
        }
      }
    }
  } else {
    $(".r_popup").css("transform", "translateY(" + 0 + "px)");
  }
}

$(window).scroll(function() {
  if (shown == 1) {
    updatePos();
  }
});

$("html").click(function(options) {
  if ($(".r_popup_container").css("opacity") == "addClass" && $(".r_popup_container").css("display") == "block") {
    if (options.target.id != ".r_popup_container" && $(options.target).parents(".r_popup_container").length == 0) {
      $(".r_popup_container").fadeOut("fast");
      $(".r_box").removeClass("r_pointer").css("pointer-events", "all");
    }
  }
});

$(".r_all").parent().parent().css("overflow", "initial");


问:
Android Wear Emulator Oreo FCM Messages not received

I'm trying to receive FCM notification on android wear emulator running on Android Oreo API 26.

I have properly registered the app on firebase, the firebase token is being printed on the log and the notification channel is also being created.

I'm using the firebase console to send the message, but it is not receiving on the wear. The console says 0 messages sent, 0 received. I'm sending the notification from the console under the same name, via the notification channel testing_channel.

Does it take time to receive on the wear?

Manifest declaration:

```<code><service
        android:name=".Services.NotificationInstanceService"
        android:enabled="true"
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service>
</code>```

Service Class:

```<code>public class NotificationInstanceService extends FirebaseInstanceIdService{

    @Override
    public void onTokenRefresh() {

        String refreshedToken = FirebaseInstanceId.getInstance().getToken() ;
        Log.i("TAG", "onTokenRefresh: " + refreshedToken);

    }
}
</code>```

AppController:

```<code>public class AppController extends Application{

    @Override
    public void onCreate() {
        super.onCreate();

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {

            NotificationManager mNotificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            String id = "testing_channel";
            CharSequence name = "Testing";
            String description = "This channel is primarily for testing";
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel mChannel = null;
            mChannel = new NotificationChannel(id, name, importance);
            mChannel.setDescription(description);
            mChannel.enableLights(true);
            mChannel.setLightColor(Color.RED);
            mChannel.enableVibration(true);
            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            mNotificationManager.createNotificationChannel(mChannel);

            Log.i("TAG", "onCreate: NOTIFICATION CHANNEL CREATED" );

        }
    }
}
</code>```

答:
Its always advisable to test push notification on a real device.
You can test a push notification on an emulator if the emulator target uses a version of Google APIs to receive the push notifications. Try compiling your Android project using a Google APIs target. I think is necessary for testing.</p>

Body:
I'm trying to receive FCM notification on android wear emulator running on Android Oreo API 26.

I have properly registered the app on firebase, the firebase token is being printed on the log and the notification channel is also being created.

I'm using the firebase console to send the message, but it is not receiving on the wear. The console says 0 messages sent, 0 received. I'm sending the notification from the console under the same name, via the notification channel testing_channel.

Does it take time to receive on the wear?

Manifest declaration:

<service
        android:name=".Services.NotificationInstanceService"
        android:enabled="true"
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service>

Service Class:

public class NotificationInstanceService extends FirebaseInstanceIdService{

    @Override
    public void onTokenRefresh() {

        String refreshedToken = FirebaseInstanceId.getInstance().getToken() ;
        Log.i("TAG", "onTokenRefresh: " + refreshedToken);

    }
}

AppController:

public class AppController extends Application{

    @Override
    public void onCreate() {
        super.onCreate();

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {

            NotificationManager mNotificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            String id = "testing_channel";
            CharSequence name = "Testing";
            String description = "This channel is primarily for testing";
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel mChannel = null;
            mChannel = new NotificationChannel(id, name, importance);
            mChannel.setDescription(description);
            mChannel.enableLights(true);
            mChannel.setLightColor(Color.RED);
            mChannel.enableVibration(true);
            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            mNotificationManager.createNotificationChannel(mChannel);

            Log.i("TAG", "onCreate: NOTIFICATION CHANNEL CREATED" );

        }
    }
}


问:
MySQL JSON query on a subquery
I have a Table A

```<code>    id
    something
    jsonModel
</code>```

jsonModel could look like this

```<code>{
   "text":"foo",
   "subkey1":{
      "entity":{
         "name":"foo",
         "customId":"59d61ffcf5bcb11f250d73275a252b62624eac000180ab59"
      }
   }
}
</code>```

I'm trying to select a row from table A when a certain ID is contained in the the jsonModel.

I have tried this but it does not work saying I'm not allowed to use wildcards in the expression

```<code>SELECT
    *
FROM A
WHERE json_contains(jsonModel,'59d61ffcf5bcb11f250d73275a252b62624eac000180ab59', $**.customId)
</code>```

Is there a way to achieve this knowing that I do not know where in the model customId can be?

EDIT:

I ended up writing this which works but I don't know which solution between this or wchiquito is best

```<code>SELECT *
from A WHERE
JSON_CONTAINS(JSON_EXTRACT(jsonModel, '$**.customId'),  '"59d61ffcf5bcb11f250d73275a252b62624eac000180ab59"');
</code>```

答:
Try:

SELECT
  `id`,
  `jsonModel`
FROM
  `A`
WHERE
  JSON_SEARCH(
    `jsonModel`,
    'one',
    '59d61ffcf5bcb11f250d73275a252b62624eac000180ab59',
    NULL,
    '$**.customId'
  ) IS NOT NULL;
```

See db-fiddle.

Title: MySQL JSON query on a subquery

Body:
I have a Table A

    id
    something
    jsonModel

jsonModel could look like this

{
   "text":"foo",
   "subkey1":{
      "entity":{
         "name":"foo",
         "customId":"59d61ffcf5bcb11f250d73275a252b62624eac000180ab59"
      }
   }
}

I'm trying to select a row from table A when a certain ID is contained in the the jsonModel.

I have tried this but it does not work saying I'm not allowed to use wildcards in the expression

SELECT
    *
FROM A
WHERE json_contains(jsonModel,'59d61ffcf5bcb11f250d73275a252b62624eac000180ab59', $**.customId)

Is there a way to achieve this knowing that I do not know where in the model customId can be?

EDIT:

I ended up writing this which works but I don't know which solution between this or wchiquito is best

SELECT *
from A WHERE
JSON_CONTAINS(JSON_EXTRACT(jsonModel, '$**.customId'),  '"59d61ffcf5bcb11f250d73275a252b62624eac000180ab59"');

Body:
Try:

SELECT
  `id`,
  `jsonModel`
FROM
  `A`
WHERE
  JSON_SEARCH(
    `jsonModel`,
    'one',
    '59d61ffcf5bcb11f250d73275a252b62624eac000180ab59',
    NULL,
    '$**.customId'
  ) IS NOT NULL;

See db-fiddle.


问:
C# swap between connection strings web.config Membership provider
In the application we have 2 connection strings for membership provider.
We create users based on the 2 connection strings and their properties: minRequiredNonalphanumericCharacters="2" minRequiredPasswordLength="8" maxInvalidPasswordAttempts="5" for users and minRequiredNonalphanumericCharacters="1" minRequiredPasswordLength="6" maxInvalidPasswordAttempts="5" for admins.
How we can change the active connection string when creating a user or an admin?

Code

```<code>//Code needed to swap to User connection string
MembershipUser newUser = Membership.CreateUser(username, password, email, question, answer, isAproved, out cs);
Membership.UpdateUser(newUser);
Roles.AddUserToRole(username, "User");

//Code needed to swap to Admin connection string
MembershipUser newUserAdmin = Membership.CreateUser(usernameAdmin, passwordAdmin, emailAdmin, questionAdmin, answerAdmin, isAprovedAdmin, out cs);
Membership.UpdateUser(newUserAdmin);
Roles.AddUserToRole(usernameAdmin, "Administrator");
</code>```

答:
Maybe you can try that:</p>

```<code>var p = (SqlMembershipProvider)Membership.Providers["name_of_membership_provider"];

MembershipUser newUser = p.CreateUser(username, password, email, question, answer, isAproved, null, out cs);
p.UpdateUser(newUser);
</code>```

Body:
In the application we have 2 connection strings for membership provider.
We create users based on the 2 connection strings and their properties: minRequiredNonalphanumericCharacters="2" minRequiredPasswordLength="8" maxInvalidPasswordAttempts="5" for users and minRequiredNonalphanumericCharacters="1" minRequiredPasswordLength="6" maxInvalidPasswordAttempts="5" for admins.
How we can change the active connection string when creating a user or an admin?

Code

//Code needed to swap to User connection string
MembershipUser newUser = Membership.CreateUser(username, password, email, question, answer, isAproved, out cs);
Membership.UpdateUser(newUser);
Roles.AddUserToRole(username, "User");

//Code needed to swap to Admin connection string
MembershipUser newUserAdmin = Membership.CreateUser(usernameAdmin, passwordAdmin, emailAdmin, questionAdmin, answerAdmin, isAprovedAdmin, out cs);
Membership.UpdateUser(newUserAdmin);
Roles.AddUserToRole(usernameAdmin, "Administrator");

Body:
Maybe you can try that:

var p = (SqlMembershipProvider)Membership.Providers["name_of_membership_provider"];

MembershipUser newUser = p.CreateUser(username, password, email, question, answer, isAproved, null, out cs);
p.UpdateUser(newUser);


问:
SSIS Archiving a file
I have an SSIS package that outputs a csv file what I want to do is look in the destination folder before I generate a csv and if one already exists (I produce them on a daily basis ) then move it to an archive folder.

my file name structure is "NAME_YYMMDD_HHMM.csv" I'm  not sure how I go about looking for a file as the date and time will always be different. i've created a variable for the filename "NAME_*_.csv but not sure how id add this to a file system task? if a file doesn't exist id like it to just move on to next step in package if it does exist then move file to archive folder

答:
You should use a script task to do this:

Use a variable in string file instead which holds your values from YYMMDD since HHMM is unable to get when you created it run time.

Date formats can be found here

Use namespace using System.IO;

```<code>        string filepath = @"D:\new";

        string file = "test_171205_1010.txt";

        string fullpath = filepath + @"\" + file;

        string newpath = @"D:\arch\";
        string newfullpath = newpath + file;

        if(
            File.Exists(fullpath))
        {
            File.Move(fullpath, newfullpath);
        }
</code>```

Update

And if you wanna use something about todays date, you can do like below where i look for all files of today and move them. Its up to your what the logic should be.

```<code>        string txtFile = null;
        string txtMoveFile = null;

        string date = DateTime.Now.ToString("yyMMdd");
        string filepath = @"D:\new";

        /*USE THIS LINE IF YOU WANNA USE VARIABLE FROM FOREACH LOOP CONTAINER*/
        string file = Dts.Variables["User::name"].Value.ToString() +"_*_*.txt";

        //string file = "test_"+date+"_*.txt";

        string[] allfilesfromcurrentdate = Directory.GetFiles(filepath, file);
        string fullpath = filepath + @"\" + file;

        string newpath = @"D:\arch\";
        string newfullpath = newpath + file;

        foreach(string fileName in allfilesfromcurrentdate)
        {
            if(fileName.Contains("test_"+date))
            {
                txtFile = fileName;
                txtMoveFile = txtFile.Replace("new", "arch");
               if(File.Exists(txtFile))
                {
                    File.Move(txtFile, txtMoveFile);
                }

            }
        }
</code>```

Title: SSIS Archiving a file

Body:
You should use a script task to do this:

Use a variable in string file instead which holds your values from YYMMDD since HHMM is unable to get when you created it run time.

Date formats can be found here

Use namespace using System.IO;

        string filepath = @"D:\new";

        string file = "test_171205_1010.txt";

        string fullpath = filepath + @"\" + file;

        string newpath = @"D:\arch\";
        string newfullpath = newpath + file;

        if(
            File.Exists(fullpath))
        {
            File.Move(fullpath, newfullpath);
        }

Update

And if you wanna use something about todays date, you can do like below where i look for all files of today and move them. Its up to your what the logic should be.

        string txtFile = null;
        string txtMoveFile = null;

        string date = DateTime.Now.ToString("yyMMdd");
        string filepath = @"D:\new";

        /*USE THIS LINE IF YOU WANNA USE VARIABLE FROM FOREACH LOOP CONTAINER*/
        string file = Dts.Variables["User::name"].Value.ToString() +"_*_*.txt";

        //string file = "test_"+date+"_*.txt";

        string[] allfilesfromcurrentdate = Directory.GetFiles(filepath, file);
        string fullpath = filepath + @"\" + file;

        string newpath = @"D:\arch\";
        string newfullpath = newpath + file;

        foreach(string fileName in allfilesfromcurrentdate)
        {
            if(fileName.Contains("test_"+date))
            {
                txtFile = fileName;
                txtMoveFile = txtFile.Replace("new", "arch");
               if(File.Exists(txtFile))
                {
                    File.Move(txtFile, txtMoveFile);
                }

            }
        }


问:
multi thread slower than single thread in ruby
I am trying to benchmark the below code,

the method Rate.rate_by_service, does some DB calls / processing and returns a value

```<code>mutex = Mutex.new
thread_arr = []
puts Benchmark.measure{
1000.times do |i|
  services.each_with_index do |service_obj,index|
    thread_arr[index] = Thread.new {
      mutex.synchronize {
        rate << Rate.rate_by_service(service_obj,@package,@from,@to,@credentials) #does database calls / calcualtions and returns a value
      }
    }
    #rate <<
  end
  thread_arr.each {|t| t.join}
end
}
</code>```

The strange thing i have observed is that the multi threaded version is slower that the regular version(without threads)

Here are the benchmarking results.

```<code> #threading
 4.870000   0.490000   5.360000 (  6.846712)
 5.300000   0.520000   5.820000 (  7.550946)
 4.640000   0.480000   5.120000 (  6.720078)
 4.580000   0.460000   5.040000 (  6.344415)
 4.510000   0.450000   4.960000 (  6.312238)

#no threading
3.610000   0.240000   3.850000 (  4.088772)
3.360000   0.200000   3.560000 (  3.721254)
3.380000   0.190000   3.570000 (  3.795252)
3.500000   0.200000   3.700000 (  4.156553)
3.580000   0.210000   3.790000 (  4.183601)
</code>```

is there something wrong that I am doing? Can anyone please elaborate as to why this behaviour could be happening.

I am using ruby 2.0, rails Rails 4.2.7.1

答:
The whole executable block of every Thread is synchronized, making the code fully synchronous, but introducing an overhead on thread creation and context switch. What did you expect?

To make it asynchronous, one should synchronize the original array update only:

```<code>1000.times do |_|
  services.map do |service_obj|
    Thread.new do
      result = Rate.rate_by_service(...)
      mutex.synchronize { rate << result }
    end
  end.each(&:join)
end
</code>```

Notice that the database query, Rate.rate_by_service, is made outside of the mutex synchronize.

Body:
I am trying to benchmark the below code,

the method Rate.rate_by_service, does some DB calls / processing and returns a value

mutex = Mutex.new
thread_arr = []
puts Benchmark.measure{
1000.times do |i|
  services.each_with_index do |service_obj,index|
    thread_arr[index] = Thread.new {
      mutex.synchronize {
        rate << Rate.rate_by_service(service_obj,@package,@from,@to,@credentials) #does database calls / calcualtions and returns a value
      }
    }
    #rate <<
  end
  thread_arr.each {|t| t.join}
end
}

The strange thing i have observed is that the multi threaded version is slower that the regular version(without threads)

Here are the benchmarking results.

 #threading
 4.870000   0.490000   5.360000 (  6.846712)
 5.300000   0.520000   5.820000 (  7.550946)
 4.640000   0.480000   5.120000 (  6.720078)
 4.580000   0.460000   5.040000 (  6.344415)
 4.510000   0.450000   4.960000 (  6.312238)

#no threading
3.610000   0.240000   3.850000 (  4.088772)
3.360000   0.200000   3.560000 (  3.721254)
3.380000   0.190000   3.570000 (  3.795252)
3.500000   0.200000   3.700000 (  4.156553)
3.580000   0.210000   3.790000 (  4.183601)

is there something wrong that I am doing? Can anyone please elaborate as to why this behaviour could be happening.

I am using ruby 2.0, rails Rails 4.2.7.1

Body:
The whole executable block of every Thread is synchronized, making the code fully synchronous, but introducing an overhead on thread creation and context switch. What did you expect?

To make it asynchronous, one should synchronize the original array update only:

1000.times do |_|
  services.map do |service_obj|
    Thread.new do
      result = Rate.rate_by_service(...)
      mutex.synchronize { rate << result }
    end
  end.each(&:join)
end

Notice that the database query, Rate.rate_by_service, is made outside of the mutex synchronize.


问:
Can I have jQuery load a page after finishing a slide toggle?
I have a button linking to a separate page, which is inside of a panel that uses jQuery to slide open and closed. On clicking the button, I want the panel to slide closed, then have the linked page load in the main window.

Here's the code:

```<code>$("a.appLink").click(function(){
    closePanel();
});

var closePanel = function(){
    if ($(".panel").is(":visible")) {
        $(".panel").slideToggle("medium",plusMinus)
    }}
</code>```

The "plusMinus" callback is just another function that toggles a little image to indicate whether the panel can be expanded or not.

The problem is that when I click on the link, the new page loading will interrupt the panel closing animation, only allowing it to partly close before the page reloads. Is there a way to have the linked page load as a callback function after "closePanel" instead of just a regular HTML link, so the panel can have an opportunity to close completely?

Thanks a lot for any help.

答:
You could use event.preventDefault() and redirect the user later on inside slideToggle's callback.

```<code>$("a.appLink").click(function(event){
    // Cancel the default behavior of the link:
    event.preventDefault();
    var link = this;
    closePanel(function() {
        plusMinus();
        window.location.href = link.href;
    });
});

var closePanel = function(callback){
    if ($(".panel").is(":visible")) {
        $(".panel").slideToggle("medium", callback)
    }
}
</code>```

This should direct the user to the new page after plusMinus has completed.

Here's a working example: http://jsfiddle.net/andrewwhitaker/QDYvx/

Body:
I have a button linking to a separate page, which is inside of a panel that uses jQuery to slide open and closed. On clicking the button, I want the panel to slide closed, then have the linked page load in the main window.

Here's the code:

$("a.appLink").click(function(){
    closePanel();
});

var closePanel = function(){
    if ($(".panel").is(":visible")) {
        $(".panel").slideToggle("medium",plusMinus)
    }}

The "plusMinus" callback is just another function that toggles a little image to indicate whether the panel can be expanded or not.

The problem is that when I click on the link, the new page loading will interrupt the panel closing animation, only allowing it to partly close before the page reloads. Is there a way to have the linked page load as a callback function after "closePanel" instead of just a regular HTML link, so the panel can have an opportunity to close completely?

Thanks a lot for any help.

Body:
You could use event.preventDefault() and redirect the user later on inside slideToggle's callback.

$("a.appLink").click(function(event){
    // Cancel the default behavior of the link:
    event.preventDefault();
    var link = this;
    closePanel(function() {
        plusMinus();
        window.location.href = link.href;
    });
});

var closePanel = function(callback){
    if ($(".panel").is(":visible")) {
        $(".panel").slideToggle("medium", callback)
    }
}

This should direct the user to the new page after plusMinus has completed.

Here's a working example: http://jsfiddle.net/andrewwhitaker/QDYvx/


问:
Right architecture for a partly shared realm
I'm currently working on a Tinder-like app, where users get recommandations of other users, that are chosen by some algorithm. Each user will have it's own user specific realm, but this data will also be shared as the other users get this user as a recommandation. From what I have read, the shared realm will automatically get duplicated on the local devices of each user, which I definitely don't want.

So how can I now have a pool of users, but only share the calculated users by my algorithm to each user separately?

I have read some other threads about this topic also had a look into 'Designing a Database: Realm Threading Deep Dive', but at the moment I have no idea how to design my realm environment. Thanks

答:
At the moment, the recommendation is to split the data into separate Realm files and move it between Realm files on the server in your own code.

We realize this is a bit cumbersome, and are currently working on better ways to achieve fine-grained sharing of data between users with object-level permissions. Stay tuned in the coming weeks and months.

Until then, duplicating the data into user-specific Realms is the best way forward.


问:
how can i get the insert_id using prepare statement in php?
I tried but I can't get insert_id from the function. I have made a class call functions but I don't understand how can I get it. See below code.

```<code>class DatabaseConnection {
protected $pdo;
public function __construct() {
 try {
   $this->pdo = new PDO('mysql:host=localhost;dbname=xxx', 'root', '');
 } catch(PDOException $e) {
  exit('Database error');
  }
 }
}

class Invoice extends DatabaseConnection {
  public function order($rename, $location) {
  $query = $this->pdo->prepare("INSERT INTO orderlist (re_name, location) VALUES (?, ?)");
  $query -> execute(array($rename, $location));
}

$user = new Invoice();
if($_SERVER['REQUEST_METHOD'] == 'POST') {
   $rename = $_POST['re_name'];
   $location = $_POST['location'];
   $insertOrder  = $user->order($rename, $location); // call the function here
   $insertid = ____ // I want to get id using insert_id in here see blank space.
}
</code>```

Data is inserted successfully but how can I get id which I insert data recently. help me.

答:
Wouldn't it work if you tried :

```<code>$user->getPdo->lastInsertId();
</code>```

Details

Body:
I tried but I can't get insert_id from the function. I have made a class call functions but I don't understand how can I get it. See below code.

class DatabaseConnection {
protected $pdo;
public function __construct() {
 try {
   $this->pdo = new PDO('mysql:host=localhost;dbname=xxx', 'root', '');
 } catch(PDOException $e) {
  exit('Database error');
  }
 }
}

class Invoice extends DatabaseConnection {
  public function order($rename, $location) {
  $query = $this->pdo->prepare("INSERT INTO orderlist (re_name, location) VALUES (?, ?)");
  $query -> execute(array($rename, $location));
}

$user = new Invoice();
if($_SERVER['REQUEST_METHOD'] == 'POST') {
   $rename = $_POST['re_name'];
   $location = $_POST['location'];
   $insertOrder  = $user->order($rename, $location); // call the function here
   $insertid = ____ // I want to get id using insert_id in here see blank space.
}

Data is inserted successfully but how can I get id which I insert data recently. help me.

Body:
Wouldn't it work if you tried :

$user->getPdo->lastInsertId();

Details