问:
Convert XML to Json Object using Javascript,Jquery
I need to convert xml to json.

My XML data is:

```<code><fl val="A_Value">AAAAAAAAAA</fl>
<fl val="B_Value">
  <![CDATA["BBBBBBBB"]]>
</fl>
<fl val="C_Value">CCCCCCCCCC</fl>
<fl val="D_Value">DDDDDDDDDD</fl>
</code>```

I would like to convert this to json:

```<code>{
   AAAAAAAAAA : A_Value,
   BBBBBBBB   : B_Value,
   CCCCCCCCCC : C_Value,
   DDDDDDDDDD : D_Value
}
</code>```

Can anyone please help me. Thanks.

答:
We start with the XML Data in a string:

```<code>var xmlStr =
  '<root><fl val="A_Value">AAAAAAAAAA</fl>' +
  '<fl val="B_Value">' +
  '  <![CDATA["BBBBBBBB"]]>' +
  '</fl>' +
  '<fl val="C_Value">CCCCCCCCCC</fl>' +
  '<fl val="D_Value">DDDDDDDDDD</fl></root>';
</code>```

Convert the string to an XML doc object:

```<code>var parseXml;

if (window.DOMParser) {
    parseXml = function(xmlStr) {
        return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
    };
} else if (typeof window.ActiveXObject != "undefined" && new window.ActiveXObject("Microsoft.XMLDOM")) {
    parseXml = function(xmlStr) {
        var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(xmlStr);
        return xmlDoc;
    };
} else {
    parseXml = function() { return null; }
}

var xmlDoc = parseXml(xmlStr);
</code>```

Then convert the XML doc object to JSON:

```<code>function xmlToJson(xml) {
    // Create the return object
    var obj = {};

    // console.log(xml.nodeType, xml.nodeName );

    if (xml.nodeType == 1) { // element
        // do attributes
        if (xml.attributes.length > 0) {
        obj["@attributes"] = {};
            for (var j = 0; j < xml.attributes.length; j++) {
                var attribute = xml.attributes.item(j);
                obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
            }
        }
    }
    else if (xml.nodeType == 3 ||
             xml.nodeType == 4) { // text and cdata section
        obj = xml.nodeValue
    }

    // do children
    if (xml.hasChildNodes()) {
        for(var i = 0; i < xml.childNodes.length; i++) {
            var item = xml.childNodes.item(i);
            var nodeName = item.nodeName;
            if (typeof(obj[nodeName]) == "undefined") {
                obj[nodeName] = xmlToJson(item);
            } else {
                if (typeof(obj[nodeName].length) == "undefined") {
                    var old = obj[nodeName];
                    obj[nodeName] = [];
                    obj[nodeName].push(old);
                }
                if (typeof(obj[nodeName]) === 'object') {
                    obj[nodeName].push(xmlToJson(item));
                }
            }
        }
    }
    return obj;
}

var theJson = xmlToJson(xmlDoc);
console.log(JSON.stringify(theJson));
/*
"{"root":{"fl":[{"@attributes":{"val":"A_Value"},"#text":{}},{"@attributes":{"val":"B_Value"},"#text":{},"#cdata-section":"\"BBBBBBBB\""},{"@attributes":{"val":"C_Value"},"#text":{}},{"@attributes":{"val":"D_Value"},"#text":{}}]}}"
*/
</code>```

Then transform the object to your desired structure:

```<code>var transformed = {};
var elements = theJson.root.fl;
for(var i=0; i<elements.length; i++) {
    var element = elements[i];
    transformed[element["#text"].trim().length > 0 ?
        element["#text"] :
        element["#cdata-section"]] = element["@attributes"]["val"];
}
console.log(JSON.stringify(transformed));
//{"AAAAAAAAAA":"A_Value","\"BBBBBBBB\"":"B_Value","CCCCCCCCCC":"C_Value","DDDDDDDDDD":"D_Value"}
</code>```

Body:
I need to convert xml to json.

My XML data is:

<fl val="A_Value">AAAAAAAAAA</fl>
<fl val="B_Value">
  <![CDATA["BBBBBBBB"]]>
</fl>
<fl val="C_Value">CCCCCCCCCC</fl>
<fl val="D_Value">DDDDDDDDDD</fl>

I would like to convert this to json:

{
   AAAAAAAAAA : A_Value,
   BBBBBBBB   : B_Value,
   CCCCCCCCCC : C_Value,
   DDDDDDDDDD : D_Value
}

Can anyone please help me. Thanks.

Body:
We start with the XML Data in a string:

var xmlStr =
  '<root><fl val="A_Value">AAAAAAAAAA</fl>' +
  '<fl val="B_Value">' +
  '  <![CDATA["BBBBBBBB"]]>' +
  '</fl>' +
  '<fl val="C_Value">CCCCCCCCCC</fl>' +
  '<fl val="D_Value">DDDDDDDDDD</fl></root>';

Convert the string to an XML doc object:

var parseXml;

if (window.DOMParser) {
    parseXml = function(xmlStr) {
        return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
    };
} else if (typeof window.ActiveXObject != "undefined" && new window.ActiveXObject("Microsoft.XMLDOM")) {
    parseXml = function(xmlStr) {
        var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(xmlStr);
        return xmlDoc;
    };
} else {
    parseXml = function() { return null; }
}

var xmlDoc = parseXml(xmlStr);

Then convert the XML doc object to JSON:

function xmlToJson(xml) {
    // Create the return object
    var obj = {};

    // console.log(xml.nodeType, xml.nodeName );

    if (xml.nodeType == 1) { // element
        // do attributes
        if (xml.attributes.length > 0) {
        obj["@attributes"] = {};
            for (var j = 0; j < xml.attributes.length; j++) {
                var attribute = xml.attributes.item(j);
                obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
            }
        }
    }
    else if (xml.nodeType == 3 ||
             xml.nodeType == 4) { // text and cdata section
        obj = xml.nodeValue
    }

    // do children
    if (xml.hasChildNodes()) {
        for(var i = 0; i < xml.childNodes.length; i++) {
            var item = xml.childNodes.item(i);
            var nodeName = item.nodeName;
            if (typeof(obj[nodeName]) == "undefined") {
                obj[nodeName] = xmlToJson(item);
            } else {
                if (typeof(obj[nodeName].length) == "undefined") {
                    var old = obj[nodeName];
                    obj[nodeName] = [];
                    obj[nodeName].push(old);
                }
                if (typeof(obj[nodeName]) === 'object') {
                    obj[nodeName].push(xmlToJson(item));
                }
            }
        }
    }
    return obj;
}

var theJson = xmlToJson(xmlDoc);
console.log(JSON.stringify(theJson));
/*
"{"root":{"fl":[{"@attributes":{"val":"A_Value"},"#text":{}},{"@attributes":{"val":"B_Value"},"#text":{},"#cdata-section":"\"BBBBBBBB\""},{"@attributes":{"val":"C_Value"},"#text":{}},{"@attributes":{"val":"D_Value"},"#text":{}}]}}"
*/

Then transform the object to your desired structure:

var transformed = {};
var elements = theJson.root.fl;
for(var i=0; i<elements.length; i++) {
    var element = elements[i];
    transformed[element["#text"].trim().length > 0 ?
        element["#text"] :
        element["#cdata-section"]] = element["@attributes"]["val"];
}
console.log(JSON.stringify(transformed));
//{"AAAAAAAAAA":"A_Value","\"BBBBBBBB\"":"B_Value","CCCCCCCCCC":"C_Value","DDDDDDDDDD":"D_Value"}


来源: stackexchange

问:
app_remove event in Firebase
I am using Firebase Analytics for my Xamarin Forms mobile app. The Firebase documentation says it can track the event "app_remove" . But I cant find that in firebase events dashboard .

Can someone help !

答: For Android app, please note that the app should be linked to Google Play to report app_remove event on Firebase.</p>

ContentLicense: CC BY-SA 3.0

Title: app_remove event in Firebase


问:
Spring MVC returning 406 to controller test
I have the following project tree:

```<code>├── app
│   ├── build.gradle
│   └── src
│       ├── main
│       │   ├── java
│       │   │   └── child
│       │   │       └── app
│       │   │           └── Application.java
│       │   └── resources
│       │       └── application-default.yaml
│       └── test
│           └── java
│               └── child
│                   └── app
│                       └── ApplicationTest.java
├── build.gradle
└── childA
    ├── build.gradle
    └── src
        ├── main
        │   └── java
        │       └── child
        │           └── a
        │               ├── CoreConfig.java
        │               ├── PingController.java
        │               └── SpringWebMvcInitializer.java
        └── test
            └── java
            │   └── child
            │       └── a
            │           └── PingControllerTest.java
            └── resources
                └── application-core.yml
</code>```

I have the following test class :

```<code>@RunWith(SpringRunner.class)
@ContextConfiguration(classes = { PingController.class, SpringWebMvcInitializer.class }, initializers = ConfigFileApplicationContextInitializer.class)
@WebAppConfiguration
@ActiveProfiles({ "core" })
public class PingControllerTest {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Before
    public void setUp() {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

    @Test
    public void testPing() throws Exception {
this.mockMvc.perform(get(CoreHttpPathStore.PING)).andDo(print());
this.mockMvc.perform(get(CoreHttpPathStore.PING).accept(MediaType.APPLICATION_JSON_UTF8_VALUE).contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)).andExpect(status().isOk());
    }

}
</code>```

I have the following PingController.java:

```<code>@RestController
public class PingController {

    @RequestMapping(value = CoreHttpPathStore.PING, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<Map<String, Object>> ping() throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        map.put("message", "Welcome to our API");
        map.put("date", new Date());
        map.put("status", HttpStatus.OK);
        return new ResponseEntity<>(map, HttpStatus.OK);
    }

}
</code>```

I have the following SpringWebMvcInitializer.java:

```<code>@ComponentScan
public class SpringWebMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[]{};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[]{};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{ "/" };
    }

}
</code>```

Expected

I expect test to pass with http code 200.

Result

I get 406 and the following print():

```<code>04:29:47.488 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Successfully completed request

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /ping
       Parameters = {}
          Headers = {}

Handler:
             Type = com.kopaxgroup.api.core.controller.PingController

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = org.springframework.web.HttpMediaTypeNotAcceptableException

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 406
    Error message = null
          Headers = {}
     Content type = null
             Body =
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
</code>```

Question

So here are my questions :

I have done some googling and most of the answers says that the context needs to be loaded with @ContextConfiguration("/test-context.xml"), I use JAVA configuration and I have no XML. Is my SpringWebMvcInitializer.java replacing that file and is it replacing it correctly ?

Why do I get 406 error ?

答:
I think the easy way is to create TestApplication class and put it in /childA/test/java/a:

```<code>import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class TestApplication {
}
</code>```

and I think it is better to use the following annotation for tests if you use Spring Boot:

```<code>@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles({"core"})
public class PingControllerTest {
...
}
</code>```

Body:
I have the following project tree:

├── app
│   ├── build.gradle
│   └── src
│       ├── main
│       │   ├── java
│       │   │   └── child
│       │   │       └── app
│       │   │           └── Application.java
│       │   └── resources
│       │       └── application-default.yaml
│       └── test
│           └── java
│               └── child
│                   └── app
│                       └── ApplicationTest.java
├── build.gradle
└── childA
    ├── build.gradle
    └── src
        ├── main
        │   └── java
        │       └── child
        │           └── a
        │               ├── CoreConfig.java
        │               ├── PingController.java
        │               └── SpringWebMvcInitializer.java
        └── test
            └── java
            │   └── child
            │       └── a
            │           └── PingControllerTest.java
            └── resources
                └── application-core.yml

I have the following test class :

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = { PingController.class, SpringWebMvcInitializer.class }, initializers = ConfigFileApplicationContextInitializer.class)
@WebAppConfiguration
@ActiveProfiles({ "core" })
public class PingControllerTest {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Before
    public void setUp() {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

    @Test
    public void testPing() throws Exception {
this.mockMvc.perform(get(CoreHttpPathStore.PING)).andDo(print());
this.mockMvc.perform(get(CoreHttpPathStore.PING).accept(MediaType.APPLICATION_JSON_UTF8_VALUE).contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)).andExpect(status().isOk());
    }

}

I have the following PingController.java:

@RestController
public class PingController {

    @RequestMapping(value = CoreHttpPathStore.PING, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<Map<String, Object>> ping() throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        map.put("message", "Welcome to our API");
        map.put("date", new Date());
        map.put("status", HttpStatus.OK);
        return new ResponseEntity<>(map, HttpStatus.OK);
    }

}

I have the following SpringWebMvcInitializer.java:

@ComponentScan
public class SpringWebMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[]{};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[]{};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{ "/" };
    }

}

Expected

I expect test to pass with http code 200.

Result

I get 406 and the following print():

04:29:47.488 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Successfully completed request

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /ping
       Parameters = {}
          Headers = {}

Handler:
             Type = com.kopaxgroup.api.core.controller.PingController

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = org.springframework.web.HttpMediaTypeNotAcceptableException

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 406
    Error message = null
          Headers = {}
     Content type = null
             Body =
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

Question

So here are my questions :

I have done some googling and most of the answers says that the context needs to be loaded with @ContextConfiguration("/test-context.xml"), I use JAVA configuration and I have no XML. Is my SpringWebMvcInitializer.java replacing that file and is it replacing it correctly ?

Why do I get 406 error ?

Body:
I think the easy way is to create TestApplication class and put it in /childA/test/java/a:

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class TestApplication {
}

and I think it is better to use the following annotation for tests if you use Spring Boot:

@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles({"core"})
public class PingControllerTest {
...
}


问:
SQL-Identify and fix criss cross records
I have a table of program members with incorrect data I am trying to fix programmatically.
The following query exposes the records that need to be fixed.

```<code>select a.*
from Table a
join Table b
on a.BillingMemberID = b.MemberID
where a.MemberID = b.BillingMemberID
and a.MemberID != a.BillingMemberID
</code>```

Example data would be:

```<code>MemberID | BillingMemberID
1        | 1
2        | 7               <== MemberID and BillingMemberID of 2 & 7 criss cross
3        | 4               <== MemberID and BillingMemberID of 3 & 4 criss cross
4        | 3
5        | 6               <== MemberID and BillingMemberID of 5 & 6 criss cross
6        | 5
7        | 2
8        | 8
</code>```

The fixed data would look like:

```<code>MemberID | BillingMemberID
1        | 1
2        | 2
3        | 3
4        | 3
5        | 5
6        | 5
7        | 2
8        | 8
</code>```

Taking the lowest ID number of the crossed pairs and changing the BillingMemberID of the other record.
How would I write a SQL script to go through a table of 5K+ records, find these crossed pairs and fix them as shown?

答:
I assume your query is wrong in that in your where clause a.MemberID probably equals b.MemberID, but the second part is correct - finding the mismatches.  I assume neither example you gave actually results from your query either.

I've simplified the example to be a single table - you can extrapolate to something more complex, but it'd just be the following.  Note that it gives the full table, not just the items need fixing (you could add a clause of a.BillingMemberID != b.BillingMemberId to filter).

select a.MemberId, case when a.BillingMemberID > b.BillingMemberID then
b.BillingMemberID else a.BillingMemberID end newval from @t1 a
inner join @t1 b
on a.BillingMemberID = b.MemberID
```

Body:
I have a table of program members with incorrect data I am trying to fix programmatically.
The following query exposes the records that need to be fixed.

select a.*
from Table a
join Table b
on a.BillingMemberID = b.MemberID
where a.MemberID = b.BillingMemberID
and a.MemberID != a.BillingMemberID

Example data would be:

MemberID | BillingMemberID
1        | 1
2        | 7               <== MemberID and BillingMemberID of 2 & 7 criss cross
3        | 4               <== MemberID and BillingMemberID of 3 & 4 criss cross
4        | 3
5        | 6               <== MemberID and BillingMemberID of 5 & 6 criss cross
6        | 5
7        | 2
8        | 8

The fixed data would look like:

MemberID | BillingMemberID
1        | 1
2        | 2
3        | 3
4        | 3
5        | 5
6        | 5
7        | 2
8        | 8

Taking the lowest ID number of the crossed pairs and changing the BillingMemberID of the other record.
How would I write a SQL script to go through a table of 5K+ records, find these crossed pairs and fix them as shown?


问:
How to extract just part of this string in C?
I have a version file I need to parse to get certain versions in C99. For example purposes, say one of the strings looks like this:

```<code>FILE: EXAMPLE ABC123459876-001 REV 1.IMG
</code>```

The 12345 numbers can be any arbitrary numbers, but always followed by 4 digits and a hyphen + a rev and an extension. I just want to return the middle of this string, that is, the file name + main version so: "EXAMPLE 9876-001 REV 1". I got it to work in the regex101 tester online with something like:

```<code>"(?<=EXAMPLE ABC.....)(....-... REV .)(?=.IMG)"
</code>```

... but C99 regex does not support positive lookahead / lookbehind operators so this does not work for me. Should I be using strstr() or strtok() instead? Just looking for some ideas as to the best way to be doing this in C, thanks.

答:
Do you really need regex for this? Could you not just split this string into substrings and work with that?

You can remove the extension with finding the dot with strchr

Substring the file name

Use regex to get the rest with ([0-9]{4}.*$)

Body:
I have a version file I need to parse to get certain versions in C99. For example purposes, say one of the strings looks like this:

FILE: EXAMPLE ABC123459876-001 REV 1.IMG

The 12345 numbers can be any arbitrary numbers, but always followed by 4 digits and a hyphen + a rev and an extension. I just want to return the middle of this string, that is, the file name + main version so: "EXAMPLE 9876-001 REV 1". I got it to work in the regex101 tester online with something like:

"(?<=EXAMPLE ABC.....)(....-... REV .)(?=.IMG)"

... but C99 regex does not support positive lookahead / lookbehind operators so this does not work for me. Should I be using strstr() or strtok() instead? Just looking for some ideas as to the best way to be doing this in C, thanks.


问:
How to create a dictionary of arrays to strings in Python?
I'm trying to create a dictionary that maps a specific array like [1,1,0,0] to a string 'Car' but the dictionary does not accept arrays or lists

```<code>a={(1,1,0,0):'Car',
(0,0,0,1):'Pedestrian',
(1,0,0,0):'Traffic Light'}

b=np.array([[1,1,0,0],[1,0,0,0],[0,0,0,1]])
</code>```

Both codes are free of errors but obviously they don't match. Here is my idea:

```<code>b.map(a)

Out[3]=['Car','Traffic Light','Pedestrian']
</code>```

Thanks in advance.

答:
A simple list comprehension will do, converting each inner array to a tuple before passing it to the dict for lookup:

```<code>>>> out = [a[tuple(x)] for x in b]
>>> out
['Car', 'Traffic Light', 'Pedestrian']
</code>```

Body:
I'm trying to create a dictionary that maps a specific array like [1,1,0,0] to a string 'Car' but the dictionary does not accept arrays or lists

a={(1,1,0,0):'Car',
(0,0,0,1):'Pedestrian',
(1,0,0,0):'Traffic Light'}

b=np.array([[1,1,0,0],[1,0,0,0],[0,0,0,1]])

Both codes are free of errors but obviously they don't match. Here is my idea:

b.map(a)

Out[3]=['Car','Traffic Light','Pedestrian']

Thanks in advance.

Body:
A simple list comprehension will do, converting each inner array to a tuple before passing it to the dict for lookup:

>>> out = [a[tuple(x)] for x in b]
>>> out
['Car', 'Traffic Light', 'Pedestrian']


问:
WebRequest MVC HttpPost DateTime Format
I have an MVC Action.....

```<code>[HttpPost]
public ActionResult DoStuff(string myString, DateTime myDateTime)
</code>```

...and I'm calling the action from a compact framework application like so.....

```<code> WebRequest request = WebRequest.Create(url);

        // Set the Method property of the request to POST.
        request.Method = "POST";
        request.Proxy = null;

        // Create POST data and convert it to a byte array.
        string postData = "myString=Bonjour&myDateTime=" + DateTime.Now.ToString();

        byte[] byteArray = Encoding.UTF8.GetBytes(jsonPostData);

        // Set the ContentType property of the WebRequest.
        request.ContentType = "application/x-www-form-urlencoded";

        // Set the ContentLength property of the WebRequest.
        request.ContentLength = byteArray.Length;

        // Get the request stream.
        using (Stream dataStream = request.GetRequestStream())
        {
            dataStream.Write(byteArray, 0, byteArray.Length);
        }

        // Get the response.
        using (WebResponse response = request.GetResponse())
        {
            // Display the status.
            // Console.WriteLine(((HttpWebResponse)response).StatusDescription);

            // Get the stream containing content returned by the server.
            using (Stream responseStream = response.GetResponseStream())
            {
                // Read the response...
                using (StreamReader reader = new StreamReader(responseStream))
                {
                    Console.WriteLine(reader.ReadToEnd());
                }
            }
        }
</code>```

Problem is the "myDateTime" parameter is always null?   What format should the postData string be in for this to work (i've tried quite a few!)?

Many thanks,

ETFairfax

答:
First of all a DateTime parameter cannot be null. This is a value type. Second of all you are writing too much code for such a simple task:

```<code>using (var client = new WebClient())
{
    var values = new NameValueCollection
    {
        { "myString", "Bonjour" },
        { "myDateTime", DateTime.Now.ToString("yyyy-MM-dd") },
    };
    byte[] result = client.UploadValues(url, values);
    string strResult = Encoding.UTF8.GetString(result);
}
</code>```

Also notice that the parameter is called myDateTime in your controller action so you must send exactly this parameter name.

ContentLicense: CC BY-SA 2.5

Title: WebRequest MVC HttpPost DateTime Format

Body:
I have an MVC Action.....

[HttpPost]
public ActionResult DoStuff(string myString, DateTime myDateTime)

...and I'm calling the action from a compact framework application like so.....

 WebRequest request = WebRequest.Create(url);

        // Set the Method property of the request to POST.
        request.Method = "POST";
        request.Proxy = null;

        // Create POST data and convert it to a byte array.
        string postData = "myString=Bonjour&myDateTime=" + DateTime.Now.ToString();

        byte[] byteArray = Encoding.UTF8.GetBytes(jsonPostData);

        // Set the ContentType property of the WebRequest.
        request.ContentType = "application/x-www-form-urlencoded";

        // Set the ContentLength property of the WebRequest.
        request.ContentLength = byteArray.Length;

        // Get the request stream.
        using (Stream dataStream = request.GetRequestStream())
        {
            dataStream.Write(byteArray, 0, byteArray.Length);
        }

        // Get the response.
        using (WebResponse response = request.GetResponse())
        {
            // Display the status.
            // Console.WriteLine(((HttpWebResponse)response).StatusDescription);

            // Get the stream containing content returned by the server.
            using (Stream responseStream = response.GetResponseStream())
            {
                // Read the response...
                using (StreamReader reader = new StreamReader(responseStream))
                {
                    Console.WriteLine(reader.ReadToEnd());
                }
            }
        }

Problem is the "myDateTime" parameter is always null?   What format should the postData string be in for this to work (i've tried quite a few!)?

Many thanks,

ETFairfax

Body:
First of all a DateTime parameter cannot be null. This is a value type. Second of all you are writing too much code for such a simple task:

using (var client = new WebClient())
{
    var values = new NameValueCollection
    {
        { "myString", "Bonjour" },
        { "myDateTime", DateTime.Now.ToString("yyyy-MM-dd") },
    };
    byte[] result = client.UploadValues(url, values);
    string strResult = Encoding.UTF8.GetString(result);
}

Also notice that the parameter is called myDateTime in your controller action so you must send exactly this parameter name.


问:
Response from Foursquare Api is undefined- Node.js
I want to get a photo from a foursquare venue using request in Node.js platform.
My id and secret are of course valid,and with this code i have the below result.However i want to get the prefix and suffix of the image in order to create the image as shown in Foursquare api https://developer.foursquare.com/docs/api/venues/photos

The result as shown in the second image keeps being undefined,no matter if i try to reach meta or response or anything.What am i doing wrong?

const request = require('request');
request({
  url: 'https://api.foursquare.com/v2/venues/59aa0677e17910245d942204/photos',
  method: 'GET',
  qs: {
    client_id: 'my_id',
    client_secret: 'my_secret',
    ll: '40.7243,-74.0018',
    query: 'coffee',
    v: '20171114',
    limit: 1
  }
}, function(err, res, body) {
  if (err) {
    console.error(err);
  } else {
    console.log(body);
  }
});```

答:
You have to parse json. Try the following code:

```<code>console.log(JSON.parse(body).meta);
console.log(JSON.parse(body).response);
</code>```

output:

{ code: 200, requestId: 'xxxxx' }
  { photos: { count: 1, items: [ [Object] ], dupesRemoved: 0 } }

Body:
You have to parse json. Try the following code:

console.log(JSON.parse(body).meta);
console.log(JSON.parse(body).response);

output:

{ code: 200, requestId: 'xxxxx' }
  { photos: { count: 1, items: [ [Object] ], dupesRemoved: 0 } }


问:
grpc c++ called CompletionQueue shutdown but CompletionQueue.next blocked forever when there is pending event
There are two threads, one calls shutdown on a CompletionQueue

```<code>    debug_log("cq shutdown start\n");
    cq.Shutdown();
    debug_log("cq shutdown success\n");
</code>```

And in another theads, cq.next blocked forever.

I can see there is one pending event in cq,
but from documentation I expect that once I call shutdown, cq.next will start return false.

I don't know what goes wrong here.

Here is the call stack for cq.next

```<code>grpc_iocp_work(grpc_exec_ctx * exec_ctx, gpr_timespec deadline) Line 83 C
grpc_pollset_work(grpc_exec_ctx * exec_ctx, grpc_pollset * pollset, grpc_pollset_worker * * worker_hdl, gpr_timespec now, gpr_timespec deadline) Line 143   C
cq_next(grpc_completion_queue * cc, gpr_timespec deadline, void * reserved) Line 844    C
grpc_completion_queue_next(grpc_completion_queue * cc, gpr_timespec deadline, void * reserved) Line 873 C
grpc::CompletionQueue::AsyncNextInternal(void * * tag, bool * ok, gpr_timespec deadline) Line 71    C++
grpc::CompletionQueue::Next(void * * tag, bool * ok) Line 151   C++
</code>```

答: The API means cq.Next will return false once you have drained the cq. I am not sure what you meant by having one pending event, but if it is not the shutdown event, your cq.Next will still wait for that event to return before returning false (in the next call).</p>

Body:
There are two threads, one calls shutdown on a CompletionQueue

    debug_log("cq shutdown start\n");
    cq.Shutdown();
    debug_log("cq shutdown success\n");

And in another theads, cq.next blocked forever.

I can see there is one pending event in cq,
but from documentation I expect that once I call shutdown, cq.next will start return false.

I don't know what goes wrong here.

Here is the call stack for cq.next

grpc_iocp_work(grpc_exec_ctx * exec_ctx, gpr_timespec deadline) Line 83 C
grpc_pollset_work(grpc_exec_ctx * exec_ctx, grpc_pollset * pollset, grpc_pollset_worker * * worker_hdl, gpr_timespec now, gpr_timespec deadline) Line 143   C
cq_next(grpc_completion_queue * cc, gpr_timespec deadline, void * reserved) Line 844    C
grpc_completion_queue_next(grpc_completion_queue * cc, gpr_timespec deadline, void * reserved) Line 873 C
grpc::CompletionQueue::AsyncNextInternal(void * * tag, bool * ok, gpr_timespec deadline) Line 71    C++
grpc::CompletionQueue::Next(void * * tag, bool * ok) Line 151   C++


问:
Codepen jquery code works fine but when I move it to my wordpress site it no longer works
Alright so here is a link to my Codepen code

https://codepen.io/Kegster/pen/aVJVqW?editors=1111#code-area

and here is a link to the WordPress site that I put my code on

http://www.blackbearlodge.com.php7-34.lan3-1.websitetestlink.com/activities/

The code is exactly the same on my WordPress site.
I would be happy to know either what I can do to fix this or what the animation type is and just find a plugin that could put that exact animation in for me.  Currently just getting fed up with the fact that jQuery is not working properly for me on the site at all.

I tried to update jQuery to the most updated version and that breaks my site (just gets me stuck at a loading screen). I tried to use .stop(true, true) to see if it was queuing something up and that didn't work either. I tried a bunch of other things like making the code I built match the proper version. Just can't seem to figure out why nothing will work.  Been at this for 3 days to fix a simple animation.

The theme I am using is i-max (non-pro version)but I am using a child theme that I set up. Which is why there are 2 style.css files. The second one is overwriting the first one so I can make my own style changes.

答:
You have a max-width with set on the img

```<code>.entry-content img,
.entry-summary img,
.comment-content img,
.widget img,
.wp-caption {
    max-width: 100%;
}
</code>```

To remove, add this into your child theme CSS

```<code>.entry-content #img-container123 img {
    max-width: none;
}
</code>```

Body:
You have a max-width with set on the img

.entry-content img,
.entry-summary img,
.comment-content img,
.widget img,
.wp-caption {
    max-width: 100%;
}

To remove, add this into your child theme CSS

.entry-content #img-container123 img {
    max-width: none;
}


问:
How to correctly add map to raster image in R
I'm trying to plot sea surface temperature data and add a colored image of land so that data isn't confused with NAs. I've tried multiple methods to do so, but as you'll see in the images below, the maps do not line up properly relative to the data.

To make this issue reproducible, here is a link to a dropbox with the file I'm working with: https://www.dropbox.com/s/e8pwgmnhvw4s0nf/sst.nc4?dl=0

Here is the code I've developed thus far;

```<code>library(ncdf4)
library(raster)
library(mapdata)
library(mapproj)
library(rgeos)
library(ggplot2)
</code>```

Via ncdf4, rasterToPoints, map_data, and ggplot2

```<code>eight = nc_open("Downloads/sst.nc4")
sst = ncvar_get(eight, "sst")
sst = raster(sst)
sst = t(flip(sst, 1)) # have to orient the data properly

# extract the dimensions and set the extent
lat.min = min(eight$dim$lat$vals)
lat.max = max(eight$dim$lat$vals)
lon.min = min(eight$dim$lon$vals)
lon.max = max(eight$dim$lon$vals)
sst = setExtent(sst, ext = c(lon.min, lon.max, lat.min, lat.max))

# provide proper projection
crs(sst) = "+init=epsg:4326"

# convert raster to points
sst.p <- rasterToPoints(sst)
df <- data.frame(sst.p)
colnames(df) <- c("Longitude", "Latitude", "sst")
usa = map_data("usa")
ggplot(data=df, aes(y=Latitude, x=Longitude)) +
  geom_raster(aes(fill=sst)) +
  theme_bw() +
  coord_equal() +
  scale_fill_gradient("SST (Celsius)", limits=c(0,35)) +
  geom_polygon(data = usa, aes(x=long, y = lat, group = group)) +

  theme(axis.title.x = element_text(size=16),
        axis.title.y = element_text(size=16, angle=90),
        axis.text.x = element_text(size=14),
        axis.text.y = element_text(size=14),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        legend.position = "right",
        legend.key = element_blank()
  )
</code>```

Via Raster, maptools data, SP Transform and base plotting

```<code>#read in the data
sst = raster("Downloads/sst.nc4",  varname = "sst", stopIfNotEqualSpaced=FALSE)

# get world map data
data("wrld_simpl", package="maptools")

## Crop to the desired extent, then plot
newext <- c(lon.min, lon.max, lat.min, lat.max)
out <- crop(wrld_simpl, newext)

#transform to proper CRS
out = spTransform(out, "+init=epsg:4326")

#plot
plot(out, col="khaki", bg="azure2")
plot(sst, add = T)
</code>```

-The projection I'm using for this spatial data is EPSG:4326

-Here is the XML snippet dictating the sst.nc4 output projection

```<code><crs>PROJCS["Mercator_1SP / World Geodetic System 1984",
         GEOGCS["World Geodetic System 1984",
         DATUM["World Geodetic System 1984",
         SPHEROID["WGS 84", 6378135.0, 298.257223563, AUTHORITY["EPSG","7030"]],
         AUTHORITY["EPSG","6326"]],
         PRIMEM["Greenwich", 0.0, AUTHORITY["EPSG","8901"]],
         UNIT["degree", 0.017453292519943295],
         AXIS["Geodetic longitude", EAST],
         AXIS["Geodetic latitude", NORTH]],
         PROJECTION["Mercator_1SP"],
         PARAMETER["latitude_of_origin", 0.0],
         PARAMETER["central_meridian", 0.0],
         PARAMETER["scale_factor", 1.0],
         PARAMETER["false_easting", 0.0],
         PARAMETER["false_northing", 0.0],
         UNIT["m", 1.0],
         AXIS["Easting", EAST],
         AXIS["Northing", NORTH]]</crs>
</code>```

I've also attempted to use the map() function with mapproj's projection argument but it doesn't seem to have a pseudo-mercator projection as an option.

答:
This one is a bit confusing. The generally easiest approach would be

```<code>sst = raster("sst.nc4",  varname = "sst")
</code>```

but, for this file, that gives this error:

```<code>"cells are not equally spaced; you should extract values as points"
</code>```

So let's do that:

```<code>library(ncdf4)
library(raster)
library(maptools)

d <- nc_open("sst.nc4")
sst <- ncvar_get(d, "sst")
lon <- ncvar_get(d, "lon")
lat <- ncvar_get(d, "lat")
nc_close(d)

xy <- cbind(rep(lon, length(lat)), rep(lat, each=length(lon)))
</code>```

Combine and remove NA values (about half the cells...

```<code>xyv <- na.omit(cbind(xy, as.vector(sst)))
</code>```

Set up a RasterLayer with a resolution that is sufficient for your purposes, and rasterize the points

```<code> r <- raster(extent(range(lon), range(lat)), res=1/6)
 r <- rasterize(xyv[, 1:2], r, xyv[,3], fun=mean)
</code>```

Plot

```<code>data(wrld_simpl)
w <- crop(wrld_simpl, r)

plot(r)
plot(w, col='gray', add=TRUE)
</code>```

Body:
I'm trying to plot sea surface temperature data and add a colored image of land so that data isn't confused with NAs. I've tried multiple methods to do so, but as you'll see in the images below, the maps do not line up properly relative to the data.

To make this issue reproducible, here is a link to a dropbox with the file I'm working with: https://www.dropbox.com/s/e8pwgmnhvw4s0nf/sst.nc4?dl=0

Here is the code I've developed thus far;

library(ncdf4)
library(raster)
library(mapdata)
library(mapproj)
library(rgeos)
library(ggplot2)

Via ncdf4, rasterToPoints, map_data, and ggplot2

eight = nc_open("Downloads/sst.nc4")
sst = ncvar_get(eight, "sst")
sst = raster(sst)
sst = t(flip(sst, 1)) # have to orient the data properly

# extract the dimensions and set the extent
lat.min = min(eight$dim$lat$vals)
lat.max = max(eight$dim$lat$vals)
lon.min = min(eight$dim$lon$vals)
lon.max = max(eight$dim$lon$vals)
sst = setExtent(sst, ext = c(lon.min, lon.max, lat.min, lat.max))

# provide proper projection
crs(sst) = "+init=epsg:4326"

# convert raster to points
sst.p <- rasterToPoints(sst)
df <- data.frame(sst.p)
colnames(df) <- c("Longitude", "Latitude", "sst")
usa = map_data("usa")
ggplot(data=df, aes(y=Latitude, x=Longitude)) +
  geom_raster(aes(fill=sst)) +
  theme_bw() +
  coord_equal() +
  scale_fill_gradient("SST (Celsius)", limits=c(0,35)) +
  geom_polygon(data = usa, aes(x=long, y = lat, group = group)) +

  theme(axis.title.x = element_text(size=16),
        axis.title.y = element_text(size=16, angle=90),
        axis.text.x = element_text(size=14),
        axis.text.y = element_text(size=14),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        legend.position = "right",
        legend.key = element_blank()
  )

Via Raster, maptools data, SP Transform and base plotting

#read in the data
sst = raster("Downloads/sst.nc4",  varname = "sst", stopIfNotEqualSpaced=FALSE)

# get world map data
data("wrld_simpl", package="maptools")

## Crop to the desired extent, then plot
newext <- c(lon.min, lon.max, lat.min, lat.max)
out <- crop(wrld_simpl, newext)

#transform to proper CRS
out = spTransform(out, "+init=epsg:4326")

#plot
plot(out, col="khaki", bg="azure2")
plot(sst, add = T)

-The projection I'm using for this spatial data is EPSG:4326

-Here is the XML snippet dictating the sst.nc4 output projection

<crs>PROJCS["Mercator_1SP / World Geodetic System 1984",
         GEOGCS["World Geodetic System 1984",
         DATUM["World Geodetic System 1984",
         SPHEROID["WGS 84", 6378135.0, 298.257223563, AUTHORITY["EPSG","7030"]],
         AUTHORITY["EPSG","6326"]],
         PRIMEM["Greenwich", 0.0, AUTHORITY["EPSG","8901"]],
         UNIT["degree", 0.017453292519943295],
         AXIS["Geodetic longitude", EAST],
         AXIS["Geodetic latitude", NORTH]],
         PROJECTION["Mercator_1SP"],
         PARAMETER["latitude_of_origin", 0.0],
         PARAMETER["central_meridian", 0.0],
         PARAMETER["scale_factor", 1.0],
         PARAMETER["false_easting", 0.0],
         PARAMETER["false_northing", 0.0],
         UNIT["m", 1.0],
         AXIS["Easting", EAST],
         AXIS["Northing", NORTH]]</crs>

I've also attempted to use the map() function with mapproj's projection argument but it doesn't seem to have a pseudo-mercator projection as an option.

Body:
This one is a bit confusing. The generally easiest approach would be

sst = raster("sst.nc4",  varname = "sst")

but, for this file, that gives this error:

"cells are not equally spaced; you should extract values as points"

So let's do that:

library(ncdf4)
library(raster)
library(maptools)

d <- nc_open("sst.nc4")
sst <- ncvar_get(d, "sst")
lon <- ncvar_get(d, "lon")
lat <- ncvar_get(d, "lat")
nc_close(d)

xy <- cbind(rep(lon, length(lat)), rep(lat, each=length(lon)))

Combine and remove NA values (about half the cells...

xyv <- na.omit(cbind(xy, as.vector(sst)))

Set up a RasterLayer with a resolution that is sufficient for your purposes, and rasterize the points

 r <- raster(extent(range(lon), range(lat)), res=1/6)
 r <- rasterize(xyv[, 1:2], r, xyv[,3], fun=mean)

Plot

data(wrld_simpl)
w <- crop(wrld_simpl, r)

plot(r)
plot(w, col='gray', add=TRUE)


问:
ANT & MSBUILD - build process won't fail if errors
When running msbuild.exe with ANT's exec task, errors in the .net code do not result in the build process failing.

Why would this be?

答: I arrived at a solution and used Exec's failonerror, works like a charm.

OwnerDisplayName: Bert Vandamme


问:
android WIFI state when phone is locked
when android phone is in SLEEP State 0r Locked State What is the state of WIFI ?
is it active or not?</p>

答: Must be active, I've downloaded stuff from the Market place whilst my phone (HTC Desire) has gone to sleep, and the download has finished the next time I unlock (wake) it.</p>

Title: android WIFI state when phone is locked


问:
How to get X and Y position of Image inside a ListView in Xamarin.Forms?
I need to show a tooltip popup when the images inside a listview is tapped. For that i'm creating a absolute layout page and adding the listview and the popup layout inside the absolute layout. I'm then trying to use the Position of the Image inside a listview to place the popup layout just below the image.

But the image X position is returning some value but the Y value returns 0 always.

答: There's a handy NuGet package called MR.Gestures that provides (among other things) X- and Y- screen coordinates of a tap location.</p>


问:
Whats the difference between these two classes
Hi I have a question about these two class's , •    The bus (i.e., what values does it need to store and what actions can it take)
•   The command (i.e., what type of command has been issued to what bus and what values) I'm confused as to what the difference would be, the bus class will have the function where it moves it self. But then what is the command class for? I need to use to different classes for this one has been called bus and other command.

Guidlines---
You are running a bus company with four buses.  These buses will move around based on commands provided from keyboard input.  To move a bus, you will issue a command from the keyboard with the bus identification, direction, and number of spaces to move.  For example:
B W 3
Would move Bus “B” three spaces to the West.  All buses will start at the bus station at coordinates (0,0).  A “N”orth command would increment the y-coordinate; “S”outh decrement the y-coordinate.  A “E”ast command increments the x-coordinate and a “W”est command decrements the x-coordinate.
You will also accept commands to pick up and drop off people:
D P 5
A D 2

答:
In trying to understand your question, I see a bus class also known as a bus object.

It is just like a physical bus with attributes like:

License plate number
Capacity

And whatever other attributes make up that bus.

The command class if I am reading correctly is a class that can be inherited by bus, but it could also be inherited by other objects. If you had a bus object and a car object, they both have a license plate.

If a bus and a car had some different attributes, they would be different.

They could both inherit the command class however, and if the command class were to have a go function, they would both be able to go.

Abstraction and polymorphism can be tricky, but it is key to object oriented programming.

I hope this helps.


问:
Create woocommerce order with gravity forms metadata
I have a interesting and bit complicated task to do with gravity forms and Woocommerce.

On our website, we offer free sample to every new customer registered. We tried to build something like as soon as new user fill their details like email, name and address as well as the free sample they want to get and submit, it should create an order in Woocommerce. Is it possible with gravity forms or its not possible at all?

I tried myself, it didn't work for me.

答:
It's possible, but there are a lot of variables that need to be taken into consideration, so it's really hard to help without you doing an attempt first.

This will only show you where to start, you need to figure out the rest:

```<code>add_action( 'gform_after_submission', 'post_to_third_party', 10, 2 );
function post_to_third_party( $entry, $form ) {
    global $woocommerce;
    // use this to find out $entry output
    var_dump($entry);

    // Make sure to add hidden field somewhere in the form with product id and define it here, If you have some other way of defining products in the form you need to make sure product id is returned in the variable below somehow
    $product_id = rgar( $entry, '12' );

    $address = array(
      'first_name' => rgar( $entry, '5' ),
      'last_name'  => rgar( $entry, '2' ),
      'company'    => rgar( $entry, '3' ),
      'email'      => rgar( $entry, '4' ),
      'phone'      => rgar( $entry, '5' ),
      'address_1'  => rgar( $entry, '6' ),
      'address_2'  => rgar( $entry, '7' ),
      'city'       => rgar( $entry, '8' ),
      'state'      => rgar( $entry, '9' ),
      'postcode'   => rgar( $entry, '10' ),
      'country'    => rgar( $entry, '11' ),
    );

    $prices = array( 'totals' => array(
            'subtotal' => 0,
            'total' => 0,
        ) );

    $order = wc_create_order();

    $order->add_product( wc_get_product($product_id), 1, $prices);
    $order->set_address( $address, 'billing' );
    $order->calculate_totals();
    $order->update_status("processing", 'Sample Order', TRUE);

}
</code>```

Body:
It's possible, but there are a lot of variables that need to be taken into consideration, so it's really hard to help without you doing an attempt first.

This will only show you where to start, you need to figure out the rest:

add_action( 'gform_after_submission', 'post_to_third_party', 10, 2 );
function post_to_third_party( $entry, $form ) {
    global $woocommerce;
    // use this to find out $entry output
    var_dump($entry);

    // Make sure to add hidden field somewhere in the form with product id and define it here, If you have some other way of defining products in the form you need to make sure product id is returned in the variable below somehow
    $product_id = rgar( $entry, '12' );

    $address = array(
      'first_name' => rgar( $entry, '5' ),
      'last_name'  => rgar( $entry, '2' ),
      'company'    => rgar( $entry, '3' ),
      'email'      => rgar( $entry, '4' ),
      'phone'      => rgar( $entry, '5' ),
      'address_1'  => rgar( $entry, '6' ),
      'address_2'  => rgar( $entry, '7' ),
      'city'       => rgar( $entry, '8' ),
      'state'      => rgar( $entry, '9' ),
      'postcode'   => rgar( $entry, '10' ),
      'country'    => rgar( $entry, '11' ),
    );

    $prices = array( 'totals' => array(
            'subtotal' => 0,
            'total' => 0,
        ) );

    $order = wc_create_order();

    $order->add_product( wc_get_product($product_id), 1, $prices);
    $order->set_address( $address, 'billing' );
    $order->calculate_totals();
    $order->update_status("processing", 'Sample Order', TRUE);

}


问:
how to git log amendments
So basically, I know that to see past git commits, you do git log. But at my company we work with gerrit on one commit and you make amendments to that commits. How do I see all the past amendments to that specific commit, so I see each of their commit message and I can diff between the amendments? THANKS!</p>

答:
Assuming all "amendments" have the same Change-ID,

(which is how Gerrit associates a set of commits to the same Gerrit-Change,

you can choose which versions of a change you would like to compare to each-other.

The default behavior is to compare the Base (first commit in the set) to the latest one.

In your local (git-)branch, you could also see the different versions of your change

by using the git reflog command.

(git reflog shows the history of your work like breadcrumbs,

and you can even show and cherry-pick any of those revisions)

Title: how to git log amendments


问:
which aws instance types need subnet id specified?
Cloud formation says:

The specified instance type can only be used in a VPC. A subnet ID or
  network interface ID is required to carry out the request. Launching
  EC2 instance failed.

Which instance types do not need a subnet ID or network interface ID?

答:
Which instance types do not need a subnet ID or network interface ID?

There is no instance type that does not require those things. EC2 Instance is a Virtual Cloud Compute so you need them to define where the instance will be deployed on and how network can connect to that instance.

If you use AWS console wizard, it sopports you to run quickly so you don't need to specify those information, wizard will create them for you.

But if you use CloudFormation, you must define manually.


答:
So you want everything except the File:-prefix and the file ending? Since File sounds static, this regex should work:

```<code>File: ([^\.]*)\..*
</code>```

You can than get that group using regexec

Title: How to extract just part of this string in C?

Body:
So you want everything except the File:-prefix and the file ending? Since File sounds static, this regex should work:

File: ([^\.]*)\..*

You can than get that group using regexec


问:
Json with '@attr' in name to java POJO
I have the following json schema. The schema has a @ character in the schema. How does this translate to a java pojo?

Sample json

```<code>{
"@type":"employee",
"name":"John Doe"
}
</code>```

答:
Gson is another alternative:

```<code>public class Person{
  @SerializedName("@type")
  public String type;

  public String name;
}
</code>```

then you can use it as :

```<code>Person person = new Gson().fromJson(YOURJSON,Person.class);
</code>```

Title: Json with '@attr' in name to java POJO

Body:
I have the following json schema. The schema has a @ character in the schema. How does this translate to a java pojo?

Sample json

{
"@type":"employee",
"name":"John Doe"
}

Body:
Gson is another alternative:

public class Person{
  @SerializedName("@type")
  public String type;

  public String name;
}

then you can use it as :

Person person = new Gson().fromJson(YOURJSON,Person.class);


问:
Joining on Is Null MS Access SQL
How do I join 2 tables in MS Access that may have NULL values in the join fields?  For instance I have 2 tables, Table1 and Table2.  I would like to join them on Table1.[Test Field 1] = Table2.[Test Field 1].  Also if the field in both tables is NULL I would like them to join.  I have tried a couple different ways of going about this, including the SQL below.  When I try to run that I get the error message: "Missing ),], or Item in Query expression..."  I've tried inserting more brackets etc but nothing has worked.  </p>

```<code>SELECT Table1.[Test Field 1], Table1.[Test Field 2], Table2.[Test Field 1], Table2.[Test Field 2]
FROM Table1 INNER JOIN Table2 ON Table1.[Test Field 1] = Table2.[Test Field 1]
OR (ISNULL(table1.[test field 1]) AND ISNULL(table2.[Test Field 1]));
</code>```

答:
IS NULL with a space checks if a column is actually null.  This may be what you're looking to use.  Here is your query using IS NULL after the column names:

```<code>SELECT Table1.[Test Field 1], Table1.[Test Field 2], Table2.[Test Field 1], Table2.[Test Field 2]
FROM Table1
INNER JOIN Table2 ON (Table1.[Test Field 1] = Table2.[Test Field 1]
   OR (table1.[test field 1] IS NULL AND table2.[Test Field 1] IS NULL));
</code>```

Title: Joining on Is Null MS Access SQL

Body:
How do I join 2 tables in MS Access that may have NULL values in the join fields?  For instance I have 2 tables, Table1 and Table2.  I would like to join them on Table1.[Test Field 1] = Table2.[Test Field 1].  Also if the field in both tables is NULL I would like them to join.  I have tried a couple different ways of going about this, including the SQL below.  When I try to run that I get the error message: "Missing ),], or Item in Query expression..."  I've tried inserting more brackets etc but nothing has worked.

SELECT Table1.[Test Field 1], Table1.[Test Field 2], Table2.[Test Field 1], Table2.[Test Field 2]
FROM Table1 INNER JOIN Table2 ON Table1.[Test Field 1] = Table2.[Test Field 1]
OR (ISNULL(table1.[test field 1]) AND ISNULL(table2.[Test Field 1]));

Body:
IS NULL with a space checks if a column is actually null.  This may be what you're looking to use.  Here is your query using IS NULL after the column names:

SELECT Table1.[Test Field 1], Table1.[Test Field 2], Table2.[Test Field 1], Table2.[Test Field 2]
FROM Table1
INNER JOIN Table2 ON (Table1.[Test Field 1] = Table2.[Test Field 1]
   OR (table1.[test field 1] IS NULL AND table2.[Test Field 1] IS NULL));


问:
Sharing getter method across classes
I have 2 classes (A & B) as below. How to share Class A getter method value to Class B ?  Pls suggest.

Class A has id getter & setter:

```<code>public class A {

@Id
public Integer id;

public A() {
}

public A(Integer id) {
    this.id = id;
}

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}
}
</code>```

Class B has value getter & setter.  Inside value getter method, I need to access Class A getId() value.  Currently, I am getting null.

```<code>public class B {

private Double value;

public B() {
}

public B(Double value) {
    this.value = value;
}

public Double getValue()  {

A a = new A();
System.out.println("class A id value:" + a.getId());

    return value;
}

public void setValue(Double value) {
    this.value = value;
}
}
</code>```

答:
You are getting null because you are initialising a = new A();
You are not passing the Id value eg: new A(123);</p>

Title: Sharing getter method across classes

Body:
I have 2 classes (A & B) as below. How to share Class A getter method value to Class B ?  Pls suggest.

Class A has id getter & setter:

public class A {

@Id
public Integer id;

public A() {
}

public A(Integer id) {
    this.id = id;
}

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}
}

Class B has value getter & setter.  Inside value getter method, I need to access Class A getId() value.  Currently, I am getting null.

public class B {

private Double value;

public B() {
}

public B(Double value) {
    this.value = value;
}

public Double getValue()  {

A a = new A();
System.out.println("class A id value:" + a.getId());

    return value;
}

public void setValue(Double value) {
    this.value = value;
}
}


问:
regex remove 3 characters before and after /
looking for a simple regular expression for this,

This is the input:

This is a sample text

```<code>eiwen34EDJ/VUFercsFIR/GRSnrr
</code>```

Output:

```<code>eiwen34 ercs nrr
</code>```

I want to remove 3 characters before and after '/'. i.e. In terms of my example, EDJ/VUF and FIR/GRS should be removed.

I was searched for many questions in here but didn't find the solution for it, please help me.

答:
You can use:

```<code>/[a-z]{3}\/[a-z]{3}/gi
</code>```

This checks for 3 characters before and after the slash and replaces with a space:

var string = 'eiwen34EDJ/VUFercsFIR/GRSnrr';

var newString = string.replace(/[a-z]{3}\/[a-z]{3}/gi, ' ');

console.log(newString);```

Body:
looking for a simple regular expression for this,

This is the input:

This is a sample text

eiwen34EDJ/VUFercsFIR/GRSnrr

Output:

eiwen34 ercs nrr

I want to remove 3 characters before and after '/'. i.e. In terms of my example, EDJ/VUF and FIR/GRS should be removed.

I was searched for many questions in here but didn't find the solution for it, please help me.

Body:
You can use:

/[a-z]{3}\/[a-z]{3}/gi

This checks for 3 characters before and after the slash and replaces with a space:

var string = 'eiwen34EDJ/VUFercsFIR/GRSnrr';

var newString = string.replace(/[a-z]{3}\/[a-z]{3}/gi, ' ');

console.log(newString);


问:
sh: scripts/image_to_code.py: /usr/bin/python^M: bad interpreter: No such file or directory
I'm running pod install for a project and am running into this error:

```<code>Installing Facebook-iOS-SDK (3.21.1)
[!] /bin/bash
set -e
find src -name \*.png | grep -v @ | grep -v '/tests/' | grep -v 'Tests/' | grep -v -- - | sed -e 's|\(.*\)/\([a-zA-Z0-9]*\).png|scripts/image_to_code.py -i \1/\2.png -c \2 -o src|' | sh && find src -name \*.wav | grep -v @ | grep -v -- - | sed -e 's|\(.*\)/\([a-zA-Z0-9]*\).wav|scripts/audio_to_code.py -i \1/\2.wav -c \2 -o src|' | sh

sh: scripts/image_to_code.py: /usr/bin/python^M: bad interpreter: No such file or directory
</code>```

I've seen fixes like this: How to solve "bad interpreter: No such file or directory" but surely I don't have to modify pod source files before running pod install.

I've seen a fix here:
https://github.com/CocoaPods/CocoaPods/issues/2418 that suggests doing:

```<code>sudo ln -s /usr/bin/python /usr/local/bin/python^M
</code>```

which seems crazy.

Any better suggestions?

答:
I had a similar error with the Ruby interpreter. The solution for me was to just re-run the cocoapods installer a la

```<code>sudo gem install cocoapods
</code>```

https://github.com/CocoaPods/CocoaPods/issues/6778 lead me to trying this

Body:
I'm running pod install for a project and am running into this error:

Installing Facebook-iOS-SDK (3.21.1)
[!] /bin/bash
set -e
find src -name \*.png | grep -v @ | grep -v '/tests/' | grep -v 'Tests/' | grep -v -- - | sed -e 's|\(.*\)/\([a-zA-Z0-9]*\).png|scripts/image_to_code.py -i \1/\2.png -c \2 -o src|' | sh && find src -name \*.wav | grep -v @ | grep -v -- - | sed -e 's|\(.*\)/\([a-zA-Z0-9]*\).wav|scripts/audio_to_code.py -i \1/\2.wav -c \2 -o src|' | sh

sh: scripts/image_to_code.py: /usr/bin/python^M: bad interpreter: No such file or directory

I've seen fixes like this: How to solve "bad interpreter: No such file or directory" but surely I don't have to modify pod source files before running pod install.

I've seen a fix here:
https://github.com/CocoaPods/CocoaPods/issues/2418 that suggests doing:

sudo ln -s /usr/bin/python /usr/local/bin/python^M

which seems crazy.

Any better suggestions?

Body:
I had a similar error with the Ruby interpreter. The solution for me was to just re-run the cocoapods installer a la

sudo gem install cocoapods

https://github.com/CocoaPods/CocoaPods/issues/6778 lead me to trying this


问:
Modifying part of the url from a  tag in Jinja2
I am using Jinja2, and I have an url:

```<code>http://mywebsite/blog/en/
</code>```

Just below the header I have three buttons, which are intended to send to the current url, but replacing the last part with the current language. This buttons are rendered by a macro:

```<code>{% macro Languages(name='', value='', abbreviation='') %}
<button class="Languages">
    <a href="{{name}}">{{name}}</a>
</button>
{{ caller() }}
{% endmacro %}
</code>```

So at the end I have something like:

```<code><button class="Languages">
    <a href="en">English</a>
</button>
<button class="Languages">
    <a href="de">Deutsch</a>
</button>
<button class="Languages">
    <a href="es">Español</a>
</button>
</code>```

My question is about how to do this. Is it possible to use some kind of regex to say something like «go to the current url but replacing the text between the last / and / for an «en» or an «es» or a «de»? I imagine that it should look like \/\w\w\/, but I can't imagine how set this in the href=''.

Thanks in advance!

答:
Do you really need a fully-qualified URL in your ? If not, then this should do the trick.

```<code><a href="../{{abbreviation}}">{{name}}</a>
</code>```

Here it is in a runnable example:

```<code>#!/usr/bin/env python

from flask import Flask, request, render_template_string
app = Flask(__name__)

@app.route('/blog/<lang>/')
def blog(lang):
    return render_template_string('''
        {% macro Languages(name='', value='', abbreviation='') %}
        <button class="Languages">
            <a href="../{{abbreviation}}/">{{name}}</a>
        </button>
        {% endmacro %}
        <html><body><form method="post">
            {{Languages('English', '1', 'en')}}
            {{Languages('Spanish', '1', 'es')}}
            {{Languages('French', '1', 'fr')}}
            </form>

            <br>{{lang}} {{ {"en": "hello", "fr": "bon jour", "es": "hola"}[lang] }}
        </body></html>''', lang=lang)

if __name__=='__main__':
    app.run(debug=True, port=8080)
</code>```

Title: Modifying part of the url from a <a> tag in Jinja2

Body:
I am using Jinja2, and I have an url:

http://mywebsite/blog/en/

Just below the header I have three buttons, which are intended to send to the current url, but replacing the last part with the current language. This buttons are rendered by a macro:

{% macro Languages(name='', value='', abbreviation='') %}
<button class="Languages">
    {{name}}
</button>
{{ caller() }}
{% endmacro %}

So at the end I have something like:

<button class="Languages">
    English
</button>
<button class="Languages">
    Deutsch
</button>
<button class="Languages">
    Español
</button>

My question is about how to do this. Is it possible to use some kind of regex to say something like «go to the current url but replacing the text between the last / and / for an «en» or an «es» or a «de»? I imagine that it should look like \/\w\w\/, but I can't imagine how set this in the href=''.

Thanks in advance!

Body:
Do you really need a fully-qualified URL in your <a>? If not, then this should do the trick.

<a href="../{{abbreviation}}">{{name}}</a>

Here it is in a runnable example:

#!/usr/bin/env python

from flask import Flask, request, render_template_string
app = Flask(__name__)

@app.route('/blog/<lang>/')
def blog(lang):
    return render_template_string('''
        {% macro Languages(name='', value='', abbreviation='') %}
        <button class="Languages">
            <a href="../{{abbreviation}}/">{{name}}</a>
        </button>
        {% endmacro %}
        <html><body><form method="post">
            {{Languages('English', '1', 'en')}}
            {{Languages('Spanish', '1', 'es')}}
            {{Languages('French', '1', 'fr')}}
            </form>

            <br>{{lang}} {{ {"en": "hello", "fr": "bon jour", "es": "hola"}[lang] }}
        </body></html>''', lang=lang)

if __name__=='__main__':
    app.run(debug=True, port=8080)


问:
Animation Code Being Ignored
I'm having a problem with JQuery animations, I've written a basic webpage that has a login box and when clicking login, the following function is executed.

```<code>function buttonClick() {
    $('div.login').animate({bottom: '500px'});
    window.location.href = 'home.html'
}
</code>```

When the only code in the function is the animation it works fine but as soon as I introduce the window.location.href code is won't execute in time and the page changes before the animation has even started. Any ideas how to delay the execution of the window line?

Thanks!

答:
Use the complete callback of animate()

```<code>function buttonClick() {
    $('div.login').animate({bottom: '500px'}, function(){
       // animation has completed here
       window.location.href = 'home.html'
    });
}
</code>```

Title: Animation Code Being Ignored

Body:
I'm having a problem with JQuery animations, I've written a basic webpage that has a login box and when clicking login, the following function is executed.

function buttonClick() {
    $('div.login').animate({bottom: '500px'});
    window.location.href = 'home.html'
}

When the only code in the function is the animation it works fine but as soon as I introduce the window.location.href code is won't execute in time and the page changes before the animation has even started. Any ideas how to delay the execution of the window line?

Thanks!

Body:
Use the complete callback of animate()

function buttonClick() {
    $('div.login').animate({bottom: '500px'}, function(){
       // animation has completed here
       window.location.href = 'home.html'
    });
}


问:
d3 Pie chart with one object key /value
Hello I am quite new with d3 and javascript. I am trying to display a pie chart with one object filled with mutiple keys and values.

Here my object :

```<code>dataset Object { $Allied Health Professions, Dentistry, Nursing and Pharmacy: 4, $Psychology, Psychiatry and Neuroscience: 4, $Biological Sciences: 4, $General Engineering: 4, $Architecture, Built Environment and Planning: 4, $Geography, Environmental Studies and Archaeology: 4, $Business and Management Studies: 4, $Law: 4, $Social Work and Social Policy: 4, $Education: 4, 5 de plus… }
</code>```

My code is quite long and in mutiple files so I don't think it's relevant to link it.

I succeed to load a pie chart with a simple array but I do not know how to access the values here.

答:
D3 data method accepts 3 things:

An array;

A function;

Nothing;

Therefore, you have to convert that object in an array of objects, with a specific property for the category and a property for the value. For instance:

var obj = {
  "Allied Health Professions, Dentistry, Nursing and Pharmacy": 4,
  "Psychology, Psychiatry and Neuroscience": 4,
  "Biological Sciences": 4,
  "General Engineering": 4,
  "Architecture, Built Environment and Planning": 4
};
var data = [];
for (var key in obj) {
  data.push({
    name: key,
    value: obj[key]
  })
};
console.log(data)```
</div>
</div>
</p>

<p>Here is a basic demo with a portion of your object:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var obj = {
  "Allied Health Professions, Dentistry, Nursing and Pharmacy": 4,
  "Psychology, Psychiatry and Neuroscience": 4,
  "Biological Sciences": 4,
  "General Engineering": 4,
  "Architecture, Built Environment and Planning": 4
};
var data = [];
for (var key in obj) {
  data.push({
    name: key,
    value: obj[key]
  })
};
var arc = d3.arc().outerRadius(100).innerRadius(0);
var pie = d3.pie().value(function(d) {
  return d.value
});
var colors = d3.scaleOrdinal(d3.schemeCategory10)
var svg = d3.select("svg")
  .append("g")
  .attr("transform", "translate(100,100)")
svg.selectAll(null)
  .data(pie(data))
  .enter()
  .append("path")
  .attr("d", arc)
  .style("fill", function(d, i) {
    return colors(i)
  })</code>```

<svg width="200" height="200"></svg>```

Title: d3 Pie chart with one object key /value

Body:
Hello I am quite new with d3 and javascript. I am trying to display a pie chart with one object filled with mutiple keys and values.

Here my object :

dataset Object { $Allied Health Professions, Dentistry, Nursing and Pharmacy: 4, $Psychology, Psychiatry and Neuroscience: 4, $Biological Sciences: 4, $General Engineering: 4, $Architecture, Built Environment and Planning: 4, $Geography, Environmental Studies and Archaeology: 4, $Business and Management Studies: 4, $Law: 4, $Social Work and Social Policy: 4, $Education: 4, 5 de plus… }

My code is quite long and in mutiple files so I don't think it's relevant to link it.

I succeed to load a pie chart with a simple array but I do not know how to access the values here.

Body:
D3 data method accepts 3 things:

An array;

A function;

Nothing;

Therefore, you have to convert that object in an array of objects, with a specific property for the category and a property for the value. For instance:

var obj = {
  "Allied Health Professions, Dentistry, Nursing and Pharmacy": 4,
  "Psychology, Psychiatry and Neuroscience": 4,
  "Biological Sciences": 4,
  "General Engineering": 4,
  "Architecture, Built Environment and Planning": 4
};
var data = [];
for (var key in obj) {
  data.push({
    name: key,
    value: obj[key]
  })
};
console.log(data)

Here is a basic demo with a portion of your object:

var obj = {
  "Allied Health Professions, Dentistry, Nursing and Pharmacy": 4,
  "Psychology, Psychiatry and Neuroscience": 4,
  "Biological Sciences": 4,
  "General Engineering": 4,
  "Architecture, Built Environment and Planning": 4
};
var data = [];
for (var key in obj) {
  data.push({
    name: key,
    value: obj[key]
  })
};
var arc = d3.arc().outerRadius(100).innerRadius(0);
var pie = d3.pie().value(function(d) {
  return d.value
});
var colors = d3.scaleOrdinal(d3.schemeCategory10)
var svg = d3.select("svg")
  .append("g")
  .attr("transform", "translate(100,100)")
svg.selectAll(null)
  .data(pie(data))
  .enter()
  .append("path")
  .attr("d", arc)
  .style("fill", function(d, i) {
    return colors(i)
  })

<script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="200" height="200"></svg>


问:
Trying to prevent the opening of an angular material dialog while opening another one
I'm using the Angular Material Dialogs for events management in a grid calendar.

```<code><td *ngFor="let member of members | async" (click)="openDialogNewEvent(time,member)">
    <div *ngFor="let event of events">
        <span *ngIf="event.time===member.time" (click)="openDialogSeeEvent(event)">.</span>
    </div></td>
</code>```

The clickable span launching the second dialog :

```<code>openDialogSeeEvent(event)
</code>```

is in the clickable td cell that launch the first dialog :

```<code>openDialogNewEvent(time,member)
</code>```

It used to work like that but with the last angular material update, it seems that the two dialogs open when there is a click on the span.

I'm trying to find a way to prevent opening the openDialogNewEvent when clicking on the openDialogSeeEvent but I can't find it.

答:
Try this:

```<code>openDialogSeeEvent(event1, event2) {
  event1.stopPropagation();
  // more code
}
</code>```

And in html page:

```<code>(click)="openDialogSeeEvent($event, event)"
</code>```

Body:
I'm using the Angular Material Dialogs for events management in a grid calendar.

        .

The clickable span launching the second dialog :

openDialogSeeEvent(event)

is in the clickable td cell that launch the first dialog :

openDialogNewEvent(time,member)

It used to work like that but with the last angular material update, it seems that the two dialogs open when there is a click on the span.

I'm trying to find a way to prevent opening the openDialogNewEvent when clicking on the openDialogSeeEvent but I can't find it.

Body:
Try this:

openDialogSeeEvent(event1, event2) {
  event1.stopPropagation();
  // more code
}

And in html page:

(click)="openDialogSeeEvent($event, event)"


问:
EXCEL VBA: Condensing multiple ranges with a SUMIF formula to one line
I have the following lines of code to fill specific ranges with SUMIF formulas:

```<code>Range("B7").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B8").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B9").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B12").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B13").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B17").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B21").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B22").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B23").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B24").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B25").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B29").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B30").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B31").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B32").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B33").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B37").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
</code>```

I'm having a hard time turning the above lines of code into something shorter like the code below. I receive the same answer but I am unsure how to code it with multiple ranges.

```<code>Dim Sumact As Range

Set Sumact = Sheets("IS Branch 12").Range("B7")

Sumact = Application.sumif(Range("M2:M500"),Range("A7"),Range("L2:L500"))
</code>```

答:
Why not try it this way?</p>

```<code>Dim Rng As Range
Set Rng = Range("B7:B9,B12:B13,B17,B21:B25,B29:B33,B37")
Rng.Formula = "=SUMIF($M$2:$M$500,A7,$L$2:$L$500)"
Rng.Value = Rng.Value
</code>```

Body:
I have the following lines of code to fill specific ranges with SUMIF formulas:

Range("B7").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B8").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B9").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B12").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B13").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B17").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B21").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B22").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B23").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B24").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B25").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B29").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B30").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B31").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B32").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B33").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B37").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"

I'm having a hard time turning the above lines of code into something shorter like the code below. I receive the same answer but I am unsure how to code it with multiple ranges.

Dim Sumact As Range

Set Sumact = Sheets("IS Branch 12").Range("B7")

Sumact = Application.sumif(Range("M2:M500"),Range("A7"),Range("L2:L500"))

Body:
Why not try it this way?

Dim Rng As Range
Set Rng = Range("B7:B9,B12:B13,B17,B21:B25,B29:B33,B37")
Rng.Formula = "=SUMIF($M$2:$M$500,A7,$L$2:$L$500)"
Rng.Value = Rng.Value


问:
socket.io - hundreds of requests instead of one connection
I created simple app to start with socket.io, but when I run it, Chrome(tested in other browsers, result same) eats all of my CPU and makes many requests:

I'm new to sockets, but I'm sure this is not how it should work. The code running in browser is really simple, it should just connect to socket and log all received data to console:

index.html

```<code><!DOCTYPE html>
<html>
<head>
    <script src="https://cdn.socket.io/socket.io-1.2.0.js" charset="UTF-8"></script>
</head>
<body>
<script type="application/javascript">
    var Sockets = io.connect('http://localhost:4000');
    Sockets.on('Test', function (data) {
        console.log(data);
    });
</script>

</body>
</html>
</code>```

Also, my server file looks like this:

server.js

```<code>var app = require('express')();
var http = require('http').Server(app);
var bodyParser = require("body-parser");
var io = require('socket.io')(http);
var port = 4000;

http.listen(port, function () {
    console.log('Server running at port ' + port);
});

var urlencodedParser = bodyParser.urlencoded({extended: false});
app.post('/', urlencodedParser, function (req, res) {
    if (!req.body) return res.sendStatus(400);
    var post = req.body;
    io.emit("Test", post.data);
    console.log(post.data);
    res.send('true');
});

io.on('connection', function(socket){
    console.log('a user connected');
    socket.on('disconnect', function(){
        console.log('user disconnected');
    });
});
</code>```

When I run the server node server.js, I got the Server running at port 4000 message and everything seems fine. But when I open the index.html in my browser, the node console is spammed by a user connected messages. Instead of connecting one client, the browser makes dozens of requests every second. When I close the browser, there is no output for some time, and then the node console is spammed by user disconnected messages.

This server should redirect all data sent via POST to connected sockets. When I make this POST request, the node server receives it (I know because it print's it into node console). But it's not received by the socket client, as there is no output in browser console (but the browser still makes dozens of new connections every second.

What is wrong here? First I thought I just messed up, so I went back and copy-pasted code from tutorial I found (not in English, but in Czech), but nothing changed. The tutorial has a lot of positive feedback, so there is propably something wrong with my computer. But what?

答:
Your configuration of running that page from a different web server than your socket.io server is on won't work as you have it.  It will take one of three changes to make it work:

You can use the "same origin" for the web page and the socket.io connection by loading the web page from the same server that your socket.io.  That means you need to load the web page directly from your socket.io web server.

You can configure your socket.io web server to accept cross origin connections (CORS connections).

You can configure your socket.io client to connect directly using webSocket without doing socket.io's usual preview with a regular http request.

If you're testing something you intend to deploy for real, you may as well just make your existing socket.io web server server your web page and load the web page directly from that.

Another possible cause of a situation like this is an incompatible client and server version of socket.io.  You should make absolutely sure that you have the same version of socket.io on client and server.  If you get the client socket.io library from /socket.io/socket.io.js from your socket.io web server, the the client version will automatically always match the server version.  The way you are loading it from a CDN, you have to manually make sure you have identical versions.

Body:
I created simple app to start with socket.io, but when I run it, Chrome(tested in other browsers, result same) eats all of my CPU and makes many requests:

I'm new to sockets, but I'm sure this is not how it should work. The code running in browser is really simple, it should just connect to socket and log all received data to console:

index.html

<!DOCTYPE html>

Also, my server file looks like this:

server.js

var app = require('express')();
var http = require('http').Server(app);
var bodyParser = require("body-parser");
var io = require('socket.io')(http);
var port = 4000;

http.listen(port, function () {
    console.log('Server running at port ' + port);
});

var urlencodedParser = bodyParser.urlencoded({extended: false});
app.post('/', urlencodedParser, function (req, res) {
    if (!req.body) return res.sendStatus(400);
    var post = req.body;
    io.emit("Test", post.data);
    console.log(post.data);
    res.send('true');
});

io.on('connection', function(socket){
    console.log('a user connected');
    socket.on('disconnect', function(){
        console.log('user disconnected');
    });
});

When I run the server node server.js, I got the Server running at port 4000 message and everything seems fine. But when I open the index.html in my browser, the node console is spammed by a user connected messages. Instead of connecting one client, the browser makes dozens of requests every second. When I close the browser, there is no output for some time, and then the node console is spammed by user disconnected messages.

This server should redirect all data sent via POST to connected sockets. When I make this POST request, the node server receives it (I know because it print's it into node console). But it's not received by the socket client, as there is no output in browser console (but the browser still makes dozens of new connections every second.

What is wrong here? First I thought I just messed up, so I went back and copy-pasted code from tutorial I found (not in English, but in Czech), but nothing changed. The tutorial has a lot of positive feedback, so there is propably something wrong with my computer. But what?


问:
Python Popen().stdout.read() hang

I'm trying to get output of another script, using Python's subprocess.Popen like follows

```<code>process = Popen(command, stdout=PIPE, shell=True)
exitcode = process.wait()
output = process.stdout.read()   # hangs here
</code>```

It hangs at the third line, only when I run it as a python script and I cannot reproduce this in the python shell.

The other script prints just a few words and I am assuming that it's not a buffer issue.

Does anyone has idea about what I am doing wrong here?

答:
read() waits for EOF before returning.

You can:

wait for the subprocess to die, then read() will return.

use readline() if your output is broken into lines (will still hang if no output lines).

use os.read(F,N) which returns at most N bytes from F, but will still block if the pipe is empty (unless O_NONBLOCK is set on the fd).

Title: Python Popen().stdout.read() hang

Body:
I'm trying to get output of another script, using Python's subprocess.Popen like follows

process = Popen(command, stdout=PIPE, shell=True)
exitcode = process.wait()
output = process.stdout.read()   # hangs here

It hangs at the third line, only when I run it as a python script and I cannot reproduce this in the python shell.

The other script prints just a few words and I am assuming that it's not a buffer issue.

Does anyone has idea about what I am doing wrong here?


问:
How to use Azure Function as endpoint for IoTHub
I have connected a Function App to an IoTHub and it triggers on the incoming events. The messages show as expected in the log window.
How can I direct the messages to an http endpoint as a REST interface? </p>

答: You can also refer to this blog post: https://azure.microsoft.com/en-us/blog/how-to-use-azure-functions-with-iot-hub-message-routing/</p>


问:
How can I export issues from IBM Cloud's Git Repos and Issue Tracking
I have a project on IBM Cloud's Git Repos and Issue Tracking service (built on GitLab CE) at https://git.ng.bluemix.net.  I'd like to export the issues in my project for reporting purposes, but I don't see any option provided in the project UI.  Is there some way to export my project's issues into a spreadsheet?</p>

答:
At the moment, exporting GitHub issues to CSV appear to only be supported in Enterprise editions of GitLab.

However, there appear to be third party options for Community Edition. See the thread here for more details.


问:
Uncaught SyntaxError: Unexpected token } (For my friend it works fine.)
For my friend the code works fine.</p>

```<code>function saveProfession(profession)
{

    fetch('/game/saveProfession/' + profession).then(function(response)
    {
        if(response.status !== 200)
        {
            console.log('problem with ajax call!' + response.status + " msg: " +
                response.value);
            return;
        }
        response.text().then(function(data)

    }
};
</code>```

答:
Shouldn't work fine for your friend.

```<code>response.text().then(function(data)
</code>```

It's missing the closing ) to the then statement.

Body:
For my friend the code works fine.

function saveProfession(profession)
{

    fetch('/game/saveProfession/' + profession).then(function(response)
    {
        if(response.status !== 200)
        {
            console.log('problem with ajax call!' + response.status + " msg: " +
                response.value);
            return;
        }
        response.text().then(function(data)

    }
};

Body:
Shouldn't work fine for your friend.

response.text().then(function(data)

It's missing the closing ) to the then statement.


问:
how to run snmpRequest.java in snmp4j?
I am actually using Snmp4j libraries..
But I am not getting how to run  org/snmp4j/tools/console/SnmpRequest.java

I wanted to know how to run snmpRequest.java in snmp4j?

答:
Assuming that you have the two jars in libs directory that's present in current directory, try the following syntax:

java  -classpath  ./libs/snmp4j-2.5.0.jar:./libs/log4j-1.2.17.jar org.snmp4j.tools.console.SnmpRequest -h

java  -classpath  ./libs/snmp4j-2.5.0.jar:./libs/log4j-1.2.17.jar org.snmp4j.tools.console.SnmpRequest -c public -v 2c -d OFF 10.1.1.1 1.3.6.1.2.1.1.1.0 1.3.6.1.2.1.1.2.0

java  -classpath  ./libs/snmp4j-2.5.0.jar:./libs/log4j-1.2.17.jar org.snmp4j.tools.console.SnmpRequest -d OFF -p GETNEXT -c public -v 2c  10.1.1.1 1.3.6.1.2.1.1.1-5

java  -classpath  ./libs/snmp4j-2.5.0.jar:./libs/log4j-1.2.17.jar org.snmp4j.tools.console.SnmpRequest -d OFF -p GETBULK -c public -v 2c -Ow 10.1.1.1 1.0.8802.1.1.2.1.4

java  -classpath  ./libs/snmp4j-2.5.0.jar:./libs/log4j-1.2.17.jar org.snmp4j.tools.console.SnmpRequest -d OFF -p GETBULK -c public -v 2c -Ot 10.1.1.1 1.0.8802.1.1.2.1.4

It works for me.

Title: how to run snmpRequest.java in snmp4j?


问:
Django ajax jQuery autocomplete only works on one page
I've added a working search field to a navigation bar that use jQuery autocomplete.  The problem is it only works on the main page.  On the other pages it tries to add the source url to the end of the page url.

For instance, on the home page it points to ajax_call/search, but on a company page (it's app that gathers internal data on companies) it points to company/847/ajax_call/search and obviously fails.

What do I need to do so the jQuery autocomplete functionality works across the entire site (without rewriting it in every template)?

Template

```<code>$(function() {
    $("#tags").autocomplete({
        minLength:2,
        source: "ajax_call/search/",
        select: function(event, ui){
            window.location.href = ui.item.href;
        }
    });
});
</code>```

URL

```<code>url(r'^ajax_call/search/$', views.ajax_company_search, name='search-field'),
</code>```

View

```<code>def ajax_company_search(request):
    if request.is_ajax():
        query = request.GET.get('term', '')
        company_names = Company.objects.filter(company_name__icontains=query).values('company_name', 'pk')

        results = []
        for name in company_names:
            name_json = dict()
            name_json['label'] = name['company_name']
            name_json['value'] = name['company_name']
            name_json['href'] = "company/" + str(name['pk']) + "/"

            results.append(name_json)

        data = json.dumps(results)
    else:
        data = 'fail'
    mimetype = 'application/json'
return HttpResponse(data, mimetype)
</code>```

答:
You specified a relative URL in your JavaScript function. That's why it changes when you visit another page (with a different URL). In this case you want to use an absolute URL, like this: /ajax_call/search/.

Also, it is best practice to not hard-code your URLs in templates but to use reverse resolution:

```<code>$(function() {
    $("#tags").autocomplete({
        minLength:2,
        source: {% url 'search-field' %},
        select: function(event, ui){
            window.location.href = ui.item.href;
        }
    });
});
</code>```

Body:
I've added a working search field to a navigation bar that use jQuery autocomplete.  The problem is it only works on the main page.  On the other pages it tries to add the source url to the end of the page url.

For instance, on the home page it points to ajax_call/search, but on a company page (it's app that gathers internal data on companies) it points to company/847/ajax_call/search and obviously fails.

What do I need to do so the jQuery autocomplete functionality works across the entire site (without rewriting it in every template)?

Template

$(function() {
    $("#tags").autocomplete({
        minLength:2,
        source: "ajax_call/search/",
        select: function(event, ui){
            window.location.href = ui.item.href;
        }
    });
});

URL

url(r'^ajax_call/search/$', views.ajax_company_search, name='search-field'),

View

def ajax_company_search(request):
    if request.is_ajax():
        query = request.GET.get('term', '')
        company_names = Company.objects.filter(company_name__icontains=query).values('company_name', 'pk')

        results = []
        for name in company_names:
            name_json = dict()
            name_json['label'] = name['company_name']
            name_json['value'] = name['company_name']
            name_json['href'] = "company/" + str(name['pk']) + "/"

            results.append(name_json)

        data = json.dumps(results)
    else:
        data = 'fail'
    mimetype = 'application/json'
return HttpResponse(data, mimetype)

Body:
You specified a relative URL in your JavaScript function. That's why it changes when you visit another page (with a different URL). In this case you want to use an absolute URL, like this: /ajax_call/search/.

Also, it is best practice to not hard-code your URLs in templates but to use reverse resolution:

$(function() {
    $("#tags").autocomplete({
        minLength:2,
        source: {% url 'search-field' %},
        select: function(event, ui){
            window.location.href = ui.item.href;
        }
    });
});


问:
Timing issue in map / forEach while waiting for promise
So I have the a timing issue. What's going on is toDataUrl doesn't complete before chrome.storage.local.get is called. How can I refactor to have map or some other loop move on once the dataUrl is ready? I've tried async await, changing forEach to maps and vice versa. I've also tried while loops and counters but maybe I'm not implementing it correctly?

To clarify: what needs to happen is the chrome.storage.local.get needs to be called once all the loops have fully completed which doesn't currently happen.

To Data Url:

```<code>    const toDataURL = url => fetch(url)
      .then(response => response.blob())
      .then(blob => new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.onloadend = () => resolve(reader.result)
        reader.onerror = reject
        reader.readAsDataURL(blob)
  }))
</code>```

Main Body:

```<code>app.checkOfflineStorage = function(quotes) {

  let nQuotes = quotes;

  nQuotes.data.map(function(e, idx) {

    if(e.attachments) {
      e.attachments.data.forEach(function(el) {

        if(el.type === 'quote-picture') {

           toDataURL(`https://quotecatalog.imgix.net${el.value}?w=110`).then(function(res) {

          el.dataURI = res;

        })
    }

  })
}

if(e.title) {
  if(typeof e.title.data.attachments !== 'undefined') {
    var title_attachments = e.title.data.attachments.data;

    title_attachments.forEach(function(el) {

 toDataURL(`https://quotecatalog.imgix.net${el.value}?w=110`).then(function(res) {

        el.dataURI = res;
      })
    })
  }
}
  })

   chrome.storage.local.get('offlineCache',

  if (Object.keys(storedQuoteArray).length === 0) {

    console.log(nQuotes)
    chrome.storage.local.set({"offlineCache": nQuotes}, function(res) {});

  } else {

    console.log(nQuotes)
    var combinedArray = storedQuoteArray.offlineCache.data.concat(nQuotes.data)

    combinedArray = combinedArray.slice(0, 100)
    console.log('100', combinedArray)

    chrome.storage.local.set({"offlineCache": {"data": combinedArray}}, function(res) {});
  }

   })
   }
</code>```

答:
A quick example of Promise.all:

```<code>Promise.all(e.attachments.data.map(function(el) {
    if(el.type === 'quote-picture') {
       return toDataURL(`https://quotecatalog.imgix.net${el.value}?w=110`)
    }
);)
.then(function (resultArray) {
// Handle results array
});
</code>```

Body:
So I have the a timing issue. What's going on is toDataUrl doesn't complete before chrome.storage.local.get is called. How can I refactor to have map or some other loop move on once the dataUrl is ready? I've tried async await, changing forEach to maps and vice versa. I've also tried while loops and counters but maybe I'm not implementing it correctly?

To clarify: what needs to happen is the chrome.storage.local.get needs to be called once all the loops have fully completed which doesn't currently happen.

To Data Url:

    const toDataURL = url => fetch(url)
      .then(response => response.blob())
      .then(blob => new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.onloadend = () => resolve(reader.result)
        reader.onerror = reject
        reader.readAsDataURL(blob)
  }))

Main Body:

app.checkOfflineStorage = function(quotes) {

  let nQuotes = quotes;

  nQuotes.data.map(function(e, idx) {

    if(e.attachments) {
      e.attachments.data.forEach(function(el) {

        if(el.type === 'quote-picture') {

           toDataURL(`https://quotecatalog.imgix.net${el.value}?w=110`).then(function(res) {

          el.dataURI = res;

        })
    }

  })
}

if(e.title) {
  if(typeof e.title.data.attachments !== 'undefined') {
    var title_attachments = e.title.data.attachments.data;

    title_attachments.forEach(function(el) {

 toDataURL(`https://quotecatalog.imgix.net${el.value}?w=110`).then(function(res) {

        el.dataURI = res;
      })
    })
  }
}
  })

   chrome.storage.local.get('offlineCache',

  if (Object.keys(storedQuoteArray).length === 0) {

    console.log(nQuotes)
    chrome.storage.local.set({"offlineCache": nQuotes}, function(res) {});

  } else {

    console.log(nQuotes)
    var combinedArray = storedQuoteArray.offlineCache.data.concat(nQuotes.data)

    combinedArray = combinedArray.slice(0, 100)
    console.log('100', combinedArray)

    chrome.storage.local.set({"offlineCache": {"data": combinedArray}}, function(res) {});
  }

   })
   }

Body:
A quick example of Promise.all:

Promise.all(e.attachments.data.map(function(el) {
    if(el.type === 'quote-picture') {
       return toDataURL(`https://quotecatalog.imgix.net${el.value}?w=110`)
    }
);)
.then(function (resultArray) {
// Handle results array
});


问:
Docker can't start because docker container with id exists?
My docker container can't restart after I upgrade the docker to Docker version 17.06.2-ce. The error message and my compose file are following:

```<code>Starting wordpress ... error
Starting mysql     ... error

ERROR: for wordpress  Cannot start service wordpress: oci runtime error: container with id exists:
b3951fd8b599c273f39d3b29085d525828a92dabe518f42860ba6535d5edad6e

ERROR: for mysql  Cannot start service mysql: oci runtime error: container with id exists: be9c3682bb66720c8015cfe9e9025c68a917204444e9b77f68b63d84f0469b71

======================
</code>```

the docker compose file  is:

```<code>services:
  wordpress:
    image: wordpress
    restart: always
    ports:
      - 80:80
    environment:
      WORDPRESS_DB_PASSWORD: xxx

  mysql:
    image: mysql:5.7
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: xxx
</code>```

I have reboot the instance but not working.
Need your help!

答:
There is a documented bug for that specific version upgrade. The fix would be at https://github.com/docker/docker-ce/pull/117/files.

I haven't found the proper way to upgrade to 17.06+ under my environment, but you can get your containers running again. Try this:

See if you can downgrade to 17.03.

Start the containers again under that version. The first time it might fail, but starting them a second time might just work if your environment is like mine. For instance:

$ docker start wp
Error response from daemon: oci runtime error: container with id exists: dc9c6a17c102747d81fbad674e93257a5b31f15e0837ed64b39c63eda5e6f46a
Error: failed to start containers: wp
$ docker start wp
wp
$ docker ps | grep wp
dc9c6a17c102        wordpress           "docker-entrypoint..."   2 months ago        Up 2 minutes       80/tcp     wp

I've written about that on the Gentoo Forums (for my case) and on Github.

Body:
My docker container can't restart after I upgrade the docker to Docker version 17.06.2-ce. The error message and my compose file are following:

Starting wordpress ... error
Starting mysql     ... error

ERROR: for wordpress  Cannot start service wordpress: oci runtime error: container with id exists:
b3951fd8b599c273f39d3b29085d525828a92dabe518f42860ba6535d5edad6e

ERROR: for mysql  Cannot start service mysql: oci runtime error: container with id exists: be9c3682bb66720c8015cfe9e9025c68a917204444e9b77f68b63d84f0469b71

======================

the docker compose file  is:

services:
  wordpress:
    image: wordpress
    restart: always
    ports:
      - 80:80
    environment:
      WORDPRESS_DB_PASSWORD: xxx

  mysql:
    image: mysql:5.7
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: xxx

I have reboot the instance but not working.
Need your help!


答:
You're probably missing some code after your last "then":</p>

```<code>function saveProfession(profession)
{

    fetch('/game/saveProfession/' + profession).then(function(response)
    {
        if(response.status !== 200)
        {
            console.log('problem with ajax call!' + response.status + " msg: " + response.value);
            return;
        }
        response.text().then(function(data) { /* do something with data */ });
    });
};
</code>```

Title: Uncaught SyntaxError: Unexpected token } (For my friend it works fine.)

Body:
You're probably missing some code after your last "then":

function saveProfession(profession)
{

    fetch('/game/saveProfession/' + profession).then(function(response)
    {
        if(response.status !== 200)
        {
            console.log('problem with ajax call!' + response.status + " msg: " + response.value);
            return;
        }
        response.text().then(function(data) { /* do something with data */ });
    });
};