问:
How to find first non-zero value in every column of a numpy array?
Suppose I have a numpy array of the form:

```<code>arr=numpy.array([[1,1,0],[1,1,0],[0,0,1],[0,0,0]])
</code>```

I want to find the indices of the first index (for every column) where the value is non-zero.

So in this instance, I would like the following to be returned:

```<code>[0,0,2]
</code>```

How do I go about this?

答:
Indices of first occurrences

Use np.argmax along that axis (zeroth axis for columns here) on the mask of non-zeros to get the indices of first matches (True values) -

```<code>(arr!=0).argmax(axis=0)
</code>```

Extending to cover generic axis specifier and for cases where no non-zeros are found along that axis for an element, we would have an implementation like so -

```<code>def first_nonzero(arr, axis, invalid_val=-1):
    mask = arr!=0
    return np.where(mask.any(axis=axis), mask.argmax(axis=axis), invalid_val)
</code>```

Note that since argmax() on all False values returns 0, so if the invalid_val needed is 0, we would have the final output directly with mask.argmax(axis=axis).

Sample runs -

```<code>In [296]: arr    # Different from given sample for variety
Out[296]:
array([[1, 0, 0],
       [1, 1, 0],
       [0, 1, 0],
       [0, 0, 0]])

In [297]: first_nonzero(arr, axis=0, invalid_val=-1)
Out[297]: array([ 0,  1, -1])

In [298]: first_nonzero(arr, axis=1, invalid_val=-1)
Out[298]: array([ 0,  0,  1, -1])
</code>```

Extending to cover all comparison operations

To find the first zeros, simply use arr==0 as mask for use in the function. For first ones equal to a certain value val, use arr == val and so on for all cases of comparisons possible here.

Indices of last occurrences

To find the last ones matching a certain comparison criteria, we need to flip along that axis and use the same idea of using argmax and then compensate for the flipping by offsetting from the axis length, as shown below -

```<code>def last_nonzero(arr, axis, invalid_val=-1):
    mask = arr!=0
    val = arr.shape[axis] - np.flip(mask, axis=axis).argmax(axis=axis) - 1
    return np.where(mask.any(axis=axis), val, invalid_val)
</code>```

Sample runs -

```<code>In [320]: arr
Out[320]:
array([[1, 0, 0],
       [1, 1, 0],
       [0, 1, 0],
       [0, 0, 0]])

In [321]: last_nonzero(arr, axis=0, invalid_val=-1)
Out[321]: array([ 1,  2, -1])

In [322]: last_nonzero(arr, axis=1, invalid_val=-1)
Out[322]: array([ 0,  1,  1, -1])
</code>```

Again, all cases of comparisons possible here are covered by using the corresponding comparator to get mask and then using within the listed function.

Body:
Suppose I have a numpy array of the form:

arr=numpy.array([[1,1,0],[1,1,0],[0,0,1],[0,0,0]])

I want to find the indices of the first index (for every column) where the value is non-zero.

So in this instance, I would like the following to be returned:

[0,0,2]

How do I go about this?

Body:
Indices of first occurrences

Use np.argmax along that axis (zeroth axis for columns here) on the mask of non-zeros to get the indices of first matches (True values) -

(arr!=0).argmax(axis=0)

Extending to cover generic axis specifier and for cases where no non-zeros are found along that axis for an element, we would have an implementation like so -

def first_nonzero(arr, axis, invalid_val=-1):
    mask = arr!=0
    return np.where(mask.any(axis=axis), mask.argmax(axis=axis), invalid_val)

Note that since argmax() on all False values returns 0, so if the invalid_val needed is 0, we would have the final output directly with mask.argmax(axis=axis).

Sample runs -

In [296]: arr    # Different from given sample for variety
Out[296]:
array([[1, 0, 0],
       [1, 1, 0],
       [0, 1, 0],
       [0, 0, 0]])

In [297]: first_nonzero(arr, axis=0, invalid_val=-1)
Out[297]: array([ 0,  1, -1])

In [298]: first_nonzero(arr, axis=1, invalid_val=-1)
Out[298]: array([ 0,  0,  1, -1])

Extending to cover all comparison operations

To find the first zeros, simply use arr==0 as mask for use in the function. For first ones equal to a certain value val, use arr == val and so on for all cases of comparisons possible here.

Indices of last occurrences

To find the last ones matching a certain comparison criteria, we need to flip along that axis and use the same idea of using argmax and then compensate for the flipping by offsetting from the axis length, as shown below -

def last_nonzero(arr, axis, invalid_val=-1):
    mask = arr!=0
    val = arr.shape[axis] - np.flip(mask, axis=axis).argmax(axis=axis) - 1
    return np.where(mask.any(axis=axis), val, invalid_val)

Sample runs -

In [320]: arr
Out[320]:
array([[1, 0, 0],
       [1, 1, 0],
       [0, 1, 0],
       [0, 0, 0]])

In [321]: last_nonzero(arr, axis=0, invalid_val=-1)
Out[321]: array([ 1,  2, -1])

In [322]: last_nonzero(arr, axis=1, invalid_val=-1)
Out[322]: array([ 0,  1,  1, -1])

Again, all cases of comparisons possible here are covered by using the corresponding comparator to get mask and then using within the listed function.


来源: stackexchange

问:
GetMapping and PostMapping annotations
I have  a doubr about this operation. Creating this class controller works:

```<code>@Controller
public class StudentController {
@RequestMapping(value = "/student", method = RequestMethod.GET)
public ModelAndView student() {
return new ModelAndView("student", "command", new Student());
}

@RequestMapping(value = "/addStudent", method = RequestMethod.POST)
public String addStudent(@ModelAttribute("SpringWeb")Student student,
ModelMap model) {
model.addAttribute("name", student.getName());
model.addAttribute("age", student.getAge());
model.addAttribute("id", student.getId());
return "result";
}
</code>```

But using GetMapping and PostMapping does not work, the project runs normally, but does not display the page call. Ie. :

```<code>@Controller
    public class StudentController {

    @GetMapping("/student")
    public ModelAndView student() {
    return new ModelAndView("student", "command", new Student());
    }

    @PostMapping("/addStudent")
    public String addStudent(@ModelAttribute("SpringWeb")Student student,
    ModelMap model) {
    model.addAttribute("name", student.getName());
    model.addAttribute("age", student.getAge());
    model.addAttribute("id", student.getId());
    return "result";
    }
}
</code>```

Code full, the way below works correctly :

Student.java

```<code>public class Student {

    private Integer age;
    private String name;
    private Integer id;

    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
}
</code>```

StudentController

```<code>import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class StudentController {

    @RequestMapping(value = "/student", method = RequestMethod.GET)
    public ModelAndView student() {
        return new ModelAndView("student", "command", new Student());
    }

    @RequestMapping(value = "/addStudent", method = RequestMethod.POST)
    public String addStudent(@ModelAttribute("SpringWeb") Student student, ModelMap model) {
        model.addAttribute("name", student.getName());
        model.addAttribute("age", student.getAge());
        model.addAttribute("id", student.getId());
        return "result";
    }
}
</code>```

result.jsp

```<code><%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <title>Spring MVC Form Handling</title>
 </head>
  <body>
     <h2>Submitted Student Information</h2>
      <table>
        <tr>
          <td>Name</td>
              <td>${name}</td>
          </tr>
            <tr>
              <td>Age</td>
                <td>${age}</td>
              </tr>
                 <tr>
                   <td>ID</td>
                    <td>${id}</td>
                     </tr>
                    </table>
    </body>
    </html>
</code>```

student.jsp

```<code><%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Spring MVC Form Handling</title>
</head>
<body>

    <h2>Student Information</h2>
    <form:form method="POST" action="/HelloForm/addStudent">

    <table>
    <tr>
    <td><form:label path="name">Name</form:label></td>
    <td><form:input path="name" /></td>
    </tr>

    <tr>
    <td><form:label path="age">Age</form:label></td>
    <td><form:input path="age"/></td>
     </tr>
    <tr>
  <td><form:label path="id">ID</form:label></td>
  <td><form:input path="id"/></td>
    </tr>

    <tr>
    <td colspan="2">
  <input type="submit" value="Submit" />
 </td>
   </tr>
        </table>
    </form:form>
</body>
</html>
</code>```

SpringContext.xml

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

<context:component-scan base-package="com" />

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp"/>

</bean>

</beans>
</code>```

web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>HelloForm</display-name>

  <servlet>
     <servlet-name>HelloForm</servlet-name>
     <servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
     <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>HelloForm</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

</web-app>
</code>```

答: You can change the @Controller to @RestController and then make use of @GetMapping and @PostMapping and run the code. This should work.</p>

ContentLicense: CC BY-SA 3.0

Title: GetMapping and PostMapping annotations

Body:
I have  a doubr about this operation. Creating this class controller works:

@Controller
public class StudentController {
@RequestMapping(value = "/student", method = RequestMethod.GET)
public ModelAndView student() {
return new ModelAndView("student", "command", new Student());
}

@RequestMapping(value = "/addStudent", method = RequestMethod.POST)
public String addStudent(@ModelAttribute("SpringWeb")Student student,
ModelMap model) {
model.addAttribute("name", student.getName());
model.addAttribute("age", student.getAge());
model.addAttribute("id", student.getId());
return "result";
}

But using GetMapping and PostMapping does not work, the project runs normally, but does not display the page call. Ie. :

@Controller
    public class StudentController {

    @GetMapping("/student")
    public ModelAndView student() {
    return new ModelAndView("student", "command", new Student());
    }

    @PostMapping("/addStudent")
    public String addStudent(@ModelAttribute("SpringWeb")Student student,
    ModelMap model) {
    model.addAttribute("name", student.getName());
    model.addAttribute("age", student.getAge());
    model.addAttribute("id", student.getId());
    return "result";
    }
}

Code full, the way below works correctly :

Student.java

public class Student {

    private Integer age;
    private String name;
    private Integer id;

    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
}

StudentController

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class StudentController {

    @RequestMapping(value = "/student", method = RequestMethod.GET)
    public ModelAndView student() {
        return new ModelAndView("student", "command", new Student());
    }

    @RequestMapping(value = "/addStudent", method = RequestMethod.POST)
    public String addStudent(@ModelAttribute("SpringWeb") Student student, ModelMap model) {
        model.addAttribute("name", student.getName());
        model.addAttribute("age", student.getAge());
        model.addAttribute("id", student.getId());
        return "result";
    }
}

result.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <title>Spring MVC Form Handling</title>

Submitted Student Information

          Name
              ${name}

              Age
                ${age}

                   ID
                    ${id}

student.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Spring MVC Form Handling</title>

Student Information

    <form:form method="POST" action="/HelloForm/addStudent">

    <form:label path="name">Name</form:label>
    <form:input path="name" />

    <form:label path="age">Age</form:label>
    <form:input path="age"/>

  <form:label path="id">ID</form:label>
  <form:input path="id"/>

  <input type="submit" value="Submit" />

    </form:form>

SpringContext.xml

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

<context:component-scan base-package="com" />

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp"/>

</bean>

</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>HelloForm</display-name>

  <servlet>
     <servlet-name>HelloForm</servlet-name>
     <servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
     <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>HelloForm</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

</web-app>


问:
What is the alternative of numpy.newaxis in tensorflow?
Hi I am new to tensorflow. I want to implement the following python code in tensorflow.</p>

```<code>import numpy as np
a = np.array([1,2,3,4,5,6,7,9,0])
print(a) ## [1 2 3 4 5 6 7 9 0]
print(a.shape) ## (9,)
b = a[:, np.newaxis] ### want to write this in tensorflow.
print(b.shape) ## (9,1)
</code>```

答:
If you're interested in exactly the same type(i.e. None) as in NumPy, then tf.newaxis is the exact alternative to np.newaxis.

Example:

```<code>In [71]: a1 = tf.constant([2,2], name="a1")

In [72]: a1
Out[72]: <tf.Tensor 'a1_5:0' shape=(2,) dtype=int32>

# add a new dimension
In [73]: a1_new = a1[tf.newaxis, :]

In [74]: a1_new
Out[74]: <tf.Tensor 'strided_slice_5:0' shape=(1, 2) dtype=int32>

# add one more dimension
In [75]: a1_new = a1[tf.newaxis, :, tf.newaxis]

In [76]: a1_new
Out[76]: <tf.Tensor 'strided_slice_6:0' shape=(1, 2, 1) dtype=int32>
</code>```

This is exactly the same kind of operations that you do in NumPy. Just use it exactly at the same dimension where you want it to be increased.

Body:
Hi I am new to tensorflow. I want to implement the following python code in tensorflow.

import numpy as np
a = np.array([1,2,3,4,5,6,7,9,0])
print(a) ## [1 2 3 4 5 6 7 9 0]
print(a.shape) ## (9,)
b = a[:, np.newaxis] ### want to write this in tensorflow.
print(b.shape) ## (9,1)

Body:
If you're interested in exactly the same type(i.e. None) as in NumPy, then tf.newaxis is the exact alternative to np.newaxis.

Example:

In [71]: a1 = tf.constant([2,2], name="a1")

In [72]: a1
Out[72]: <tf.Tensor 'a1_5:0' shape=(2,) dtype=int32>

# add a new dimension
In [73]: a1_new = a1[tf.newaxis, :]

In [74]: a1_new
Out[74]: <tf.Tensor 'strided_slice_5:0' shape=(1, 2) dtype=int32>

# add one more dimension
In [75]: a1_new = a1[tf.newaxis, :, tf.newaxis]

In [76]: a1_new
Out[76]: <tf.Tensor 'strided_slice_6:0' shape=(1, 2, 1) dtype=int32>

This is exactly the same kind of operations that you do in NumPy. Just use it exactly at the same dimension where you want it to be increased.


问:
Capturing Kafka offsets when writing with Spark Structured Streaming
I am using Spark Structured streaming on Spark 2.2 to Stream Files from an HDFS directory to a Kafka Topic.  I would like to capture the Kafka offsets for the data I am writing to the topic.

I am using

```<code>val write = jsonDF
.writeStream.format("kafka")
.option("checkpointLocation", Config().getString(domain + ".kafkaCheckpoint"))
.option("kafka.bootstrap.servers", Config().getString(domain + ".kafkaServer"))
.option("topic", Config().getString(domain + ".kafkaTopic"))
.start()
</code>```

To write to Kafka.

When I utilize

```<code>spark.streams.addListener(new StreamingQueryListener() {
  override def onQueryStarted(queryStarted: QueryStartedEvent): Unit = {
    println("Query started: " + queryStarted.id)
  }
  override def onQueryTerminated(queryTerminated: QueryTerminatedEvent): Unit = {
    println("Query terminated: " + queryTerminated.id)
  }
  override def onQueryProgress(queryProgress: QueryProgressEvent): Unit = {
    println("Query made progress: " + queryProgress.progress)
  }
})
</code>```

to capture the stream's progress information the information retrieved does not correlate with the offsets being created in Kafka.

I assume that this is because the information provided by the stream is really about the file stream I am utilizing and not related to what is written in Kafka.

Is there a way with Spark Structure Streaming to capture the offset information that is being generated when we write to Kafka?

Adding Example:
When I run data in from source 1 with three rows after just creating the topic I get:

Run 1:
      Start Offset: null, End offset: {"logOffset":0}
      Start Offset: {"logOffset":0}, End offset: {"logOffset":0}

```<code> Kafka Says:
 ruwe:2:1
 ruwe:1:1
 ruwe:0:1
</code>```

Run 2;

```<code>  Start Offset: {"logOffset":0}, End offset: {"logOffset":1}
  Start Offset: {"logOffset":1}, End offset: {"logOffset":1}

 Kafka Says:
 ruwe:2:2
 ruwe:1:2
 ruwe:0:2
</code>```

Run 3:

```<code>  Start Offset: {"logOffset":1}, End offset: {"logOffset":2}
  Start Offset: {"logOffset":2}, End offset: {"logOffset":2}

 Kafka Says:
 ruwe:2:3
 ruwe:1:3
 ruwe:0:3
</code>```

I then ran data in with the same program from a different source and received

```<code>  Start Offset: null, End offset: {"logOffset":0}
  Start Offset: {"logOffset":0}, End offset: {"logOffset":0}

  and of course Kafka continued to increment
</code>```

This indicates that Spark is reporting information that is based on the source

I would like to know what was created in the target.

答:
Is there a way with Spark Structure Streaming to capture the offset
  information that is being generated when we write to Kafka?

Yes, in onQueryProgress, you need to look at the StreamingQueryProgress.sources which is an Array[SourceProgress]. It has two strings, startOffset and endOffset, which are JSONs that you can parse:

```<code>sparkSession.streams.addListener(new StreamingQueryListener {override def onQueryStarted(event: StreamingQueryListener.QueryStartedEvent): Unit = ???

  override def onQueryProgress(event: StreamingQueryListener.QueryProgressEvent): Unit = {
    val source = event.progress.sources.headOption
    source.map(src => println(s"Start Offset: ${src.startOffset}, End offset: ${src.endOffset}"))
  }

  override def onQueryTerminated(event: StreamingQueryListener.QueryTerminatedEvent): Unit = ()
})
</code>```

The JSON has the following structure:

```<code>"startOffset" : {
  "topic-name" : {
    "0" : 1,
    "1" : 22,
    "2" : 419,
  }
},
"endOffset" : {
  "topic-name" : {
    "0" : 10,
    "1" : 100,
    "2" : 1000
  }
}
</code>```

Body:
I am using Spark Structured streaming on Spark 2.2 to Stream Files from an HDFS directory to a Kafka Topic.  I would like to capture the Kafka offsets for the data I am writing to the topic.

I am using

val write = jsonDF
.writeStream.format("kafka")
.option("checkpointLocation", Config().getString(domain + ".kafkaCheckpoint"))
.option("kafka.bootstrap.servers", Config().getString(domain + ".kafkaServer"))
.option("topic", Config().getString(domain + ".kafkaTopic"))
.start()

To write to Kafka.

When I utilize

spark.streams.addListener(new StreamingQueryListener() {
  override def onQueryStarted(queryStarted: QueryStartedEvent): Unit = {
    println("Query started: " + queryStarted.id)
  }
  override def onQueryTerminated(queryTerminated: QueryTerminatedEvent): Unit = {
    println("Query terminated: " + queryTerminated.id)
  }
  override def onQueryProgress(queryProgress: QueryProgressEvent): Unit = {
    println("Query made progress: " + queryProgress.progress)
  }
})

to capture the stream's progress information the information retrieved does not correlate with the offsets being created in Kafka.

I assume that this is because the information provided by the stream is really about the file stream I am utilizing and not related to what is written in Kafka.

Is there a way with Spark Structure Streaming to capture the offset information that is being generated when we write to Kafka?

Adding Example:
When I run data in from source 1 with three rows after just creating the topic I get:

Run 1:
      Start Offset: null, End offset: {"logOffset":0}
      Start Offset: {"logOffset":0}, End offset: {"logOffset":0}

 Kafka Says:
 ruwe:2:1
 ruwe:1:1
 ruwe:0:1

Run 2;

  Start Offset: {"logOffset":0}, End offset: {"logOffset":1}
  Start Offset: {"logOffset":1}, End offset: {"logOffset":1}

 Kafka Says:
 ruwe:2:2
 ruwe:1:2
 ruwe:0:2

Run 3:

  Start Offset: {"logOffset":1}, End offset: {"logOffset":2}
  Start Offset: {"logOffset":2}, End offset: {"logOffset":2}

 Kafka Says:
 ruwe:2:3
 ruwe:1:3
 ruwe:0:3

I then ran data in with the same program from a different source and received

  Start Offset: null, End offset: {"logOffset":0}
  Start Offset: {"logOffset":0}, End offset: {"logOffset":0}

  and of course Kafka continued to increment

This indicates that Spark is reporting information that is based on the source

I would like to know what was created in the target.

Body:
Is there a way with Spark Structure Streaming to capture the offset
  information that is being generated when we write to Kafka?

Yes, in onQueryProgress, you need to look at the StreamingQueryProgress.sources which is an Array[SourceProgress]. It has two strings, startOffset and endOffset, which are JSONs that you can parse:

sparkSession.streams.addListener(new StreamingQueryListener {override def onQueryStarted(event: StreamingQueryListener.QueryStartedEvent): Unit = ???

  override def onQueryProgress(event: StreamingQueryListener.QueryProgressEvent): Unit = {
    val source = event.progress.sources.headOption
    source.map(src => println(s"Start Offset: ${src.startOffset}, End offset: ${src.endOffset}"))
  }

  override def onQueryTerminated(event: StreamingQueryListener.QueryTerminatedEvent): Unit = ()
})

The JSON has the following structure:

"startOffset" : {
  "topic-name" : {
    "0" : 1,
    "1" : 22,
    "2" : 419,
  }
},
"endOffset" : {
  "topic-name" : {
    "0" : 10,
    "1" : 100,
    "2" : 1000
  }
}


问:
What happens when a React app, which contains Flow annotations, is launched?
I'm relatively new to web development. I have a react app which makes use of the usual JSX components. These get compiled to regular html and JavaScript, presumably by a react script created when I first ran create-react-app MyApp.

My package.json file contains the following:

```<code>"scripts": {
    "start": "react-scripts start",
    ...
}
</code>```

and I run npm start to launch the app.

I have recently been exploring the flow static analysis tool, as this seems to be gaining ground over the older React PropTypes in the React community. I have seen StackOverflow questions alluding to the fact that JavaScript code with Flow annotations is no longer valid JavaScript and answers that say in order to use such JavaScript it needs to be transpiled to remove the Flow annotations. The Flow website lists Babel and flow-remove-types as two transpile tools.

My confusion is, my project works fine without me explicitly transpiling the code. E.g. the following JavaScript and Flow code in MyApp/src/index.js:

```<code>const someSillyConst: any = this;
console.log(`test: ${someSillyConst}`);
</code>```

Becomes this:

```<code>var someSillyConst = this;
console.log('test: ' + someSillyConst);
</code>```

when I examine a file called static/js/bundle.js in Chrome's dev tools.

Yet I can still view the original version in Users/barry/MyApp/src/index.js, again in Chrome's dev tools.

So, what is happening between me running npm start and the app rendering in Chrome that removes non-valid JavaScript, in this case Flow annotations?

答:
The reason it works is – create-react-app supports flow out of the box since it's using babel-preset-react which in turn includes babel-flow.

So, your code actually gets transpiled. The transpilation in your case also converts the template literal to plain old string concatenation (and the const to var).

preset-react: https://babeljs.io/docs/plugins/preset-react/
babel-preset-react-app: https://github.com/facebookincubator/create-react-app/blob/master/packages/babel-preset-react-app/index.js

If you want to explore all the config stuff which is hidden by create react app, you may use npm eject – although you probably want to do this for another project since this is a one way operation. This command is going to copy over all the config files for you to edit.

Body:
I'm relatively new to web development. I have a react app which makes use of the usual JSX components. These get compiled to regular html and JavaScript, presumably by a react script created when I first ran create-react-app MyApp.

My package.json file contains the following:

"scripts": {
    "start": "react-scripts start",
    ...
}

and I run npm start to launch the app.

I have recently been exploring the flow static analysis tool, as this seems to be gaining ground over the older React PropTypes in the React community. I have seen StackOverflow questions alluding to the fact that JavaScript code with Flow annotations is no longer valid JavaScript and answers that say in order to use such JavaScript it needs to be transpiled to remove the Flow annotations. The Flow website lists Babel and flow-remove-types as two transpile tools.

My confusion is, my project works fine without me explicitly transpiling the code. E.g. the following JavaScript and Flow code in MyApp/src/index.js:

const someSillyConst: any = this;
console.log(`test: ${someSillyConst}`);

Becomes this:

var someSillyConst = this;
console.log('test: ' + someSillyConst);

when I examine a file called static/js/bundle.js in Chrome's dev tools.

Yet I can still view the original version in Users/barry/MyApp/src/index.js, again in Chrome's dev tools.

So, what is happening between me running npm start and the app rendering in Chrome that removes non-valid JavaScript, in this case Flow annotations?


问:
SQL Server JSON Join Many to Many
I am exploring the concept of using SQL Server to be more like a document database and in an average relational database model I would use a third table to join the many to many relationship between two objects say Products and Categories.

In SQL Server 2016 I have the following tables...

```<code>CREATE TABLE [dbo].[Products]
(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](250) NOT NULL,
    [Categories] [nvarchar](max) NULL

    CONSTRAINT [PK_Products]
        PRIMARY KEY CLUSTERED ([ID] ASC)
)

CREATE TABLE [dbo].[Categories]
(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](250) NOT NULL,
    [ParentID] [int] NULL,

    CONSTRAINT [PK_Categories]
        PRIMARY KEY CLUSTERED ([ID] ASC)
)
</code>```

The Categories column in the Products table would hold a JSON array of IDs.

Is there a single query to select products and include a new column (JSON) of the related categories. CROSS APPLY duplicates each product row.

Something like this (but this doesn't work)...

```<code>SELECT
    p.ID, p.Name,
    ((SELECT * FROM Categories
      WHERE ID in (SELECT [value] FROM OPENJSON(p.Categories)))
      FOR JSON PATH) AS Categories
FROM Products p
</code>```

Some demo data

```<code>TRUNCATE TABLE Categories;

INSERT INTO Categories ([Name]) VALUES ('PC Systems');
INSERT INTO Categories ([Name], [ParentID]) VALUES ('Custom PC', 1);
INSERT INTO Categories ([Name], [ParentID]) VALUES ('Gaming PC', 1);
INSERT INTO Categories ([Name], [ParentID]) VALUES ('Small Form Factor', 1);
INSERT INTO Categories ([Name], [ParentID]) VALUES ('Business PCs', 1);
INSERT INTO Categories ([Name], [ParentID]) VALUES ('Mac', 1);

INSERT INTO Categories ([Name]) VALUES ('Speakers');
INSERT INTO Categories ([Name]) VALUES ('Monitors');

TRUNCATE TABLE Products;
DECLARE @jsonCategories NVARCHAR(MAX)

SET @jsonCategories = N'[7]';
INSERT INTO Products ([Name], [Categories]) VALUES ('HomePod', @jsonCategories);

SET @jsonCategories = N'[5, 4]';
INSERT INTO Products ([Name], [Categories]) VALUES ('Surface Pro', @jsonCategories);
</code>```

Thanks for any help

答:
Sorry, found my own answer</p>

```<code>SELECT p.ID, p.Name,
    (
        SELECT * FROM Categories WHERE ID in (SELECT [value] FROM OPENJSON(p.Categories)) FOR JSON PATH
    ) as Categories
FROM Products p
</code>```

Title: SQL Server JSON Join Many to Many

Body:
I am exploring the concept of using SQL Server to be more like a document database and in an average relational database model I would use a third table to join the many to many relationship between two objects say Products and Categories.

In SQL Server 2016 I have the following tables...

CREATE TABLE [dbo].[Products]
(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](250) NOT NULL,
    [Categories] [nvarchar](max) NULL

    CONSTRAINT [PK_Products]
        PRIMARY KEY CLUSTERED ([ID] ASC)
)

CREATE TABLE [dbo].[Categories]
(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](250) NOT NULL,
    [ParentID] [int] NULL,

    CONSTRAINT [PK_Categories]
        PRIMARY KEY CLUSTERED ([ID] ASC)
)

The Categories column in the Products table would hold a JSON array of IDs.

Is there a single query to select products and include a new column (JSON) of the related categories. CROSS APPLY duplicates each product row.

Something like this (but this doesn't work)...

SELECT
    p.ID, p.Name,
    ((SELECT * FROM Categories
      WHERE ID in (SELECT [value] FROM OPENJSON(p.Categories)))
      FOR JSON PATH) AS Categories
FROM Products p

Some demo data

TRUNCATE TABLE Categories;

INSERT INTO Categories ([Name]) VALUES ('PC Systems');
INSERT INTO Categories ([Name], [ParentID]) VALUES ('Custom PC', 1);
INSERT INTO Categories ([Name], [ParentID]) VALUES ('Gaming PC', 1);
INSERT INTO Categories ([Name], [ParentID]) VALUES ('Small Form Factor', 1);
INSERT INTO Categories ([Name], [ParentID]) VALUES ('Business PCs', 1);
INSERT INTO Categories ([Name], [ParentID]) VALUES ('Mac', 1);

INSERT INTO Categories ([Name]) VALUES ('Speakers');
INSERT INTO Categories ([Name]) VALUES ('Monitors');

TRUNCATE TABLE Products;
DECLARE @jsonCategories NVARCHAR(MAX)

SET @jsonCategories = N'[7]';
INSERT INTO Products ([Name], [Categories]) VALUES ('HomePod', @jsonCategories);

SET @jsonCategories = N'[5, 4]';
INSERT INTO Products ([Name], [Categories]) VALUES ('Surface Pro', @jsonCategories);

Thanks for any help

Body:
Sorry, found my own answer

SELECT p.ID, p.Name,
    (
        SELECT * FROM Categories WHERE ID in (SELECT [value] FROM OPENJSON(p.Categories)) FOR JSON PATH
    ) as Categories
FROM Products p


问:
setInterval that takes into account function time of run
I need function that execute some payload functions once in a while but takes into account that

a) payload function can takes some time to finish (like axaj request with timeout)

b) payload function can be Promise

c) I might wanna stop it some time later

答:
To easy, just use the new ESnext async / await syntax to make it easy. At first we need a small helper timer:

```<code>const time = ms => new Promise(res => setTimeout(res, ms));
</code>```

To be used like this:

```<code>(async function(){
   while(true){
       await whatever(); // whatever shall be a promise
       //wait some time:
       await time(1000);
   }
})()
</code>```

Body:
To easy, just use the new ESnext async / await syntax to make it easy. At first we need a small helper timer:

const time = ms => new Promise(res => setTimeout(res, ms));

To be used like this:

(async function(){
   while(true){
       await whatever(); // whatever shall be a promise
       //wait some time:
       await time(1000);
   }
})()


问:
make WKWebview "real" fullscreen on iPhone X (remove safe area from WKWebView
I'm trying to implement a "real" fullscreen in App WebView, meaning I want the webcontent to fully go under the notch no matter what.

This is the current situation I am facing, when framing the WebView to the superviews bounds:

The red border is the border of the webView (Also the size of the screen). Twitter has 100% height and width on the body.

I understand that websites can't have 100% width in Safari and that its the default behaviour for the in App Browser to respect the safearea but especially in my case, where the webpages are somewhat designed for the app, I need to use the full space.

I couldn't figure out how to set the webview to give its content the full size. Is there a way to change the safearea?

Code Snippet:

```<code>private var webView : WKWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    self.webView = WKWebView(frame: .zero)

    self.webView.layer.borderColor = UIColor.red.cgColor
    self.webView.layer.borderWidth = 2

    self.webView.load(URLRequest(url: URL(string: "https://www.twitter.com")!))

    self.view.addSubview(self.webView)
}

override func viewDidLayoutSubviews() {
    self.webView.frame = self.view.bounds
}
</code>```

答:
After a little try and error, this is the solution I came up with.
Subclass WKWebView and create a custom class. Overwrite safeAreaInsets:

```<code>import Foundation
import WebKit

class FullScreenWKWebView: WKWebView {
    override var safeAreaInsets: UIEdgeInsets {
        return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    }
}
</code>```

Body:
I'm trying to implement a "real" fullscreen in App WebView, meaning I want the webcontent to fully go under the notch no matter what.

This is the current situation I am facing, when framing the WebView to the superviews bounds:

The red border is the border of the webView (Also the size of the screen). Twitter has 100% height and width on the body.

I understand that websites can't have 100% width in Safari and that its the default behaviour for the in App Browser to respect the safearea but especially in my case, where the webpages are somewhat designed for the app, I need to use the full space.

I couldn't figure out how to set the webview to give its content the full size. Is there a way to change the safearea?

Code Snippet:

private var webView : WKWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    self.webView = WKWebView(frame: .zero)

    self.webView.layer.borderColor = UIColor.red.cgColor
    self.webView.layer.borderWidth = 2

    self.webView.load(URLRequest(url: URL(string: "https://www.twitter.com")!))

    self.view.addSubview(self.webView)
}

override func viewDidLayoutSubviews() {
    self.webView.frame = self.view.bounds
}

Body:
After a little try and error, this is the solution I came up with.
Subclass WKWebView and create a custom class. Overwrite safeAreaInsets:

import Foundation
import WebKit

class FullScreenWKWebView: WKWebView {
    override var safeAreaInsets: UIEdgeInsets {
        return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    }
}


问:
Convert data.frame columns from factors to characters
I have a data frame. Let's call him bob:

```<code>> head(bob)
                 phenotype                         exclusion
GSM399350 3- 4- 8- 25- 44+ 11b- 11c- 19- NK1.1- Gr1- TER119-
GSM399351 3- 4- 8- 25- 44+ 11b- 11c- 19- NK1.1- Gr1- TER119-
GSM399352 3- 4- 8- 25- 44+ 11b- 11c- 19- NK1.1- Gr1- TER119-
GSM399353 3- 4- 8- 25+ 44+ 11b- 11c- 19- NK1.1- Gr1- TER119-
GSM399354 3- 4- 8- 25+ 44+ 11b- 11c- 19- NK1.1- Gr1- TER119-
GSM399355 3- 4- 8- 25+ 44+ 11b- 11c- 19- NK1.1- Gr1- TER119-
</code>```

I'd like to concatenate the rows of this data frame (this will be another question). But look:

```<code>> class(bob$phenotype)
[1] "factor"
</code>```

Bob's columns are factors. So, for example:

```<code>> as.character(head(bob))
[1] "c(3, 3, 3, 6, 6, 6)"       "c(3, 3, 3, 3, 3, 3)"
[3] "c(29, 29, 29, 30, 30, 30)"
</code>```

I don't begin to understand this, but I guess these are indices into the levels of the factors of the columns (of the court of king caractacus) of bob? Not what I need.

Strangely I can go through the columns of bob by hand, and do

```<code>bob$phenotype <- as.character(bob$phenotype)
</code>```

which works fine. And, after some typing, I can get a data.frame whose columns are characters rather than factors. So my question is: how can I do this automatically? How do I convert a data.frame with factor columns into a data.frame with character columns without having to manually go through each column?

Bonus question: why does the manual approach work?

答:
This function does the trick</p>

```<code>df <- stacomirtools::killfactor(df)
</code>```

Body:
I have a data frame. Let's call him bob:

> head(bob)
                 phenotype                         exclusion
GSM399350 3- 4- 8- 25- 44+ 11b- 11c- 19- NK1.1- Gr1- TER119-
GSM399351 3- 4- 8- 25- 44+ 11b- 11c- 19- NK1.1- Gr1- TER119-
GSM399352 3- 4- 8- 25- 44+ 11b- 11c- 19- NK1.1- Gr1- TER119-
GSM399353 3- 4- 8- 25+ 44+ 11b- 11c- 19- NK1.1- Gr1- TER119-
GSM399354 3- 4- 8- 25+ 44+ 11b- 11c- 19- NK1.1- Gr1- TER119-
GSM399355 3- 4- 8- 25+ 44+ 11b- 11c- 19- NK1.1- Gr1- TER119-

I'd like to concatenate the rows of this data frame (this will be another question). But look:

> class(bob$phenotype)
[1] "factor"

Bob's columns are factors. So, for example:

> as.character(head(bob))
[1] "c(3, 3, 3, 6, 6, 6)"       "c(3, 3, 3, 3, 3, 3)"
[3] "c(29, 29, 29, 30, 30, 30)"

I don't begin to understand this, but I guess these are indices into the levels of the factors of the columns (of the court of king caractacus) of bob? Not what I need.

Strangely I can go through the columns of bob by hand, and do

bob$phenotype <- as.character(bob$phenotype)

which works fine. And, after some typing, I can get a data.frame whose columns are characters rather than factors. So my question is: how can I do this automatically? How do I convert a data.frame with factor columns into a data.frame with character columns without having to manually go through each column?

Bonus question: why does the manual approach work?

Body:
This function does the trick

df <- stacomirtools::killfactor(df)


问:
JSP custom tag for displaying a large event type calendar
This is probably a simple question, but what is everyone using to display a simple event calendar in jsp. I was looking for an existing taglib but didn't really find anything other than calendarTag.

I'm using Spring MVC 3.0, JodaTime. and basically just want a large calendar on a jsp where I can include links to another pager  based on some logic. Not really anything fancy.

Any Thoughts?

答:
I would create the calendar in the controller, for example like this:

```<code>@Controller
public class CalendarController{

    private static final int START_OF_WEEK = DateTimeConstants.MONDAY;

    @RequestMapping("drawCalendar")
    public ModelAndView drawCalendar(@RequestParam("month") final int month,
        @RequestParam("year") final int year){
        final LocalDate monthStart = new LocalDate(year, month, 1);
        boolean endReached = false;
        LocalDate today = null;
        final List<List<LocalDate>> weeks1 = new ArrayList<List<LocalDate>>();
        while(!endReached){
            final List<LocalDate> thisWeek = new ArrayList<LocalDate>();
            for(int weekOffset = 0; weekOffset < 7; weekOffset++){
                if(today == null){
                    if(!endReached
                        && weekOffset == monthStart.getDayOfWeek()
                            - START_OF_WEEK){
                        today = monthStart;
                    }
                } else{
                    today = today.plusDays(1);
                    if(today.getMonthOfYear() != month){
                        today = null;
                        endReached = true;
                    }
                }
                thisWeek.add(today);
            }
            weeks1.add(thisWeek);
        }
        final List<List<LocalDate>> weeks = weeks1;

        final Map<String, Object> model = new HashMap<String, Object>();
        model.put("calendar", weeks);
        final ModelAndView modelAndView = new ModelAndView("calendar", model);
        return modelAndView;
    }
}
</code>```

and in the JSP I would iterate over the weeks:

```<code><c:forEach items="${calendar}" var="week">
    <tr>
        <td>Mon</td>
        <td>Tue</td>
        <td>Wed</td>
        <td>Thu</td>
        <td>Fri</td>
        <td>Sat</td>
        <td>Sun</td>
    </tr>
    <tr>
        <c:forEach items="${week}" var="date">
            <td><c:out value="${date==null ? '' : date.dayOfWeek}"</td>
        </c:forEach>
    </tr>
</c:forEach>
</code>```

(of course I haven't written any JSP code in about 3 years, so sorry if something is wrong)

ContentLicense: CC BY-SA 2.5

Body:
I would create the calendar in the controller, for example like this:

@Controller
public class CalendarController{

    private static final int START_OF_WEEK = DateTimeConstants.MONDAY;

    @RequestMapping("drawCalendar")
    public ModelAndView drawCalendar(@RequestParam("month") final int month,
        @RequestParam("year") final int year){
        final LocalDate monthStart = new LocalDate(year, month, 1);
        boolean endReached = false;
        LocalDate today = null;
        final List<List<LocalDate>> weeks1 = new ArrayList<List<LocalDate>>();
        while(!endReached){
            final List<LocalDate> thisWeek = new ArrayList<LocalDate>();
            for(int weekOffset = 0; weekOffset < 7; weekOffset++){
                if(today == null){
                    if(!endReached
                        && weekOffset == monthStart.getDayOfWeek()
                            - START_OF_WEEK){
                        today = monthStart;
                    }
                } else{
                    today = today.plusDays(1);
                    if(today.getMonthOfYear() != month){
                        today = null;
                        endReached = true;
                    }
                }
                thisWeek.add(today);
            }
            weeks1.add(thisWeek);
        }
        final List<List<LocalDate>> weeks = weeks1;

        final Map<String, Object> model = new HashMap<String, Object>();
        model.put("calendar", weeks);
        final ModelAndView modelAndView = new ModelAndView("calendar", model);
        return modelAndView;
    }
}

and in the JSP I would iterate over the weeks:

<c:forEach items="${calendar}" var="week">
    <tr>
        <td>Mon</td>
        <td>Tue</td>
        <td>Wed</td>
        <td>Thu</td>
        <td>Fri</td>
        <td>Sat</td>
        <td>Sun</td>
    </tr>
    <tr>
        <c:forEach items="${week}" var="date">
            <td><c:out value="${date==null ? '' : date.dayOfWeek}"</td>
        </c:forEach>
    </tr>
</c:forEach>

(of course I haven't written any JSP code in about 3 years, so sorry if something is wrong)


问:
How to add index to label in DSE graph?
I turned off the auto scan for dse graph and add index for properties of vertices and edges. All my query failed with the following error message,

```<code>g.V().hasLabel("PERMISSIONS").valueMap()
</code>```

yields,

```<code>Could not find an index on vertices labelled 'PERMISSIONS' to answer the condition: '((label = PERMISSIONS))'. Current indexes are: byName(Secondary)->name. Alternatively if in development enable graph scan by using graph.allow_scan. Graph scan is NOT suitable for anything other than toy graphs.
</code>```

How to add index to lable?

答:
The docs have a section on indexing which will show you how to create an index - http://docs.datastax.com/en/dse/5.1/dse-dev/datastax_enterprise/graph/using/indexingTOC.html

It looks like though that you are trying to return all data for the Permissions Vertex Label.  That would cause a cluster scan.  Are you able to filter your query by a property, instead of trying to return all data?

Title: How to add index to label in DSE graph?

Body:
I turned off the auto scan for dse graph and add index for properties of vertices and edges. All my query failed with the following error message,

g.V().hasLabel("PERMISSIONS").valueMap()

yields,

Could not find an index on vertices labelled 'PERMISSIONS' to answer the condition: '((label = PERMISSIONS))'. Current indexes are: byName(Secondary)->name. Alternatively if in development enable graph scan by using graph.allow_scan. Graph scan is NOT suitable for anything other than toy graphs.

How to add index to lable?


问:
SQL Finding most spoken language in a country
I am trying to get the most spoken language in a country based on percentage. I am joining 2 tables:

```<code>Country(NAME,CODE)
CountryLanguage(Percentage, CountryCode, Language)
</code>```

Joining those 2 gives me

```<code>Aruba           Dutch       5.3
Aruba           English     9.5
Aruba           Papiamento  76.7
Aruba           Spanish     7.4
Afghanistan     Balochi     0.9
Afghanistan     Dari        32.1
Afghanistan     Pashto      52.4
Afghanistan     Turkmenian  1.9
Afghanistan     Uzbek       8.8
</code>```

I tried to get the most spoken language by saying

```<code>SELECT co.Name, cl.language, max(cl.Percentage)
from Country co, CountryLanguage cl
where co.Code = cl.CountryCode
group by co.Name
</code>```

This gives me the right percentage but wrong language, where did I go wrong?

```<code>Afghanistan  Balochi    52.4
Aruba        Dutch      76.7
</code>```

答:
Simply adding group by both columns</p>

```<code>SELECT co.Name, cl.language, max(cl.Percentage)
from Country co, CountryLanguage cl
where co.Code = cl.CountryCode
group by co.Name,cl.language
</code>```

Body:
I am trying to get the most spoken language in a country based on percentage. I am joining 2 tables:

Country(NAME,CODE)
CountryLanguage(Percentage, CountryCode, Language)

Joining those 2 gives me

Aruba           Dutch       5.3
Aruba           English     9.5
Aruba           Papiamento  76.7
Aruba           Spanish     7.4
Afghanistan     Balochi     0.9
Afghanistan     Dari        32.1
Afghanistan     Pashto      52.4
Afghanistan     Turkmenian  1.9
Afghanistan     Uzbek       8.8

I tried to get the most spoken language by saying

SELECT co.Name, cl.language, max(cl.Percentage)
from Country co, CountryLanguage cl
where co.Code = cl.CountryCode
group by co.Name

This gives me the right percentage but wrong language, where did I go wrong?

Afghanistan  Balochi    52.4
Aruba        Dutch      76.7

Body:
Simply adding group by both columns

SELECT co.Name, cl.language, max(cl.Percentage)
from Country co, CountryLanguage cl
where co.Code = cl.CountryCode
group by co.Name,cl.language


问:
Select only elements that don't have a parent with defined class
How do I select only children that don't have a parent with a certain class in their parent tree?

This didn't work:

```<code>div:not(.dontSelect) .child
</code>```

div {
  background-color: red;
  padding: 5px;
}

div:not(.dontSelect) .child {
  background-color: green;
  padding: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <div class="child">
    Select this
  </div>
  <div class="dontSelect">
    <div>
      <div class="child">
        Don't select this
      </div>
    </div>
  </div>
</div></code>```

答:
If you can use a id for main div:

div#content {
  background-color: red;
  padding: 5px;
}

div#content > div:not(.dontSelect).child {
  background-color: green;
  padding: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="content">
  <div class="child">
    Select this
  </div>
  <div class="dontSelect">
    <div>
      <div class="child">
        Don't select this
      </div>
    </div>
  </div>
</div></code>```

Body:
How do I select only children that don't have a parent with a certain class in their parent tree?

This didn't work:

div:not(.dontSelect) .child

div {
  background-color: red;
  padding: 5px;
}

div:not(.dontSelect) .child {
  background-color: green;
  padding: 5px;
}

    Select this

        Don't select this

Body:
If you can use a id for main div:

div#content {
  background-color: red;
  padding: 5px;
}

div#content > div:not(.dontSelect).child {
  background-color: green;
  padding: 5px;
}

<div id="content">
  <div class="child">
    Select this
  </div>
  <div class="dontSelect">
    <div>
      <div class="child">
        Don't select this
      </div>
    </div>
  </div>
</div>


问:
how to hide scroll bar for one div if two divs in one page of html
HTML:

```<code><div class="container">
    <div class="mainContent"></div>
    <div class="sidebar"></div>
</div>
</code>```

CSS:

```<code>#container {
    min-width: 1170px;
    width: 95%;
    margin-left: auto;
    margin-right: auto;
}

#mainContent {
    min-width: 1200px;
    width: 85%;
    float: left;
}

#sidebar {
    min-width: 200px;
    position: fixed;
    width: 15%;
    display: inline-block;
    margin: 0px 0px 5px 5px;
    vertical-align: middle;
    max-height: 810px;
    overflow: auto;
}
</code>```

Here mainContent is scrolling with fixed sidebar.

I am trying to give scrolling property for sidebar separately using overflow: auto.
But I wish to hide sidebar's scrollbar.Just hide not disabling scrolling.

Can you to tell me how to do this with above properties?

答:
You can try this:</p>

```<code>    #mySidenav {
        overflow-x: hidden;
        -webkit-scrollbar{
        width: 0px;
        background: transparent;
    }
</code>```

Body:
HTML:

CSS:

#container {
    min-width: 1170px;
    width: 95%;
    margin-left: auto;
    margin-right: auto;
}

#mainContent {
    min-width: 1200px;
    width: 85%;
    float: left;
}

#sidebar {
    min-width: 200px;
    position: fixed;
    width: 15%;
    display: inline-block;
    margin: 0px 0px 5px 5px;
    vertical-align: middle;
    max-height: 810px;
    overflow: auto;
}

Here mainContent is scrolling with fixed sidebar.

I am trying to give scrolling property for sidebar separately using overflow: auto.
But I wish to hide sidebar's scrollbar.Just hide not disabling scrolling.

Can you to tell me how to do this with above properties?

Body:
You can try this:

    #mySidenav {
        overflow-x: hidden;
        -webkit-scrollbar{
        width: 0px;
        background: transparent;
    }


问:
How to properly set a network timeout before showing an animation on iOS?
as the title says I have a problem with my app. Let me explain a little more in detail what I'm trying to achieve using a bulleted list:

The app loads the main menù and connect to firebase in order to see if there's some product to show

Download the product image

Animate the content in order to show the product info and image

I created functions to handle the case the connection doesn't work or the product doesn't exist. The problem is when the connection is too slow to load the image before the animation starts (about 2 seconds). In this case, the app stuck a little and the product will be shown before the animation ends.

Load code

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    // The view where the product will be shown
    self.productView.alpha = 0.0

    // Checks the internet connection
    if (ConnectionService.isConnectedToNetwork()) {
        fetchDataFromDatabase(downloadCompleted: { (productToShow) in
            self.fillPromoView(usingProduct: productToShow)
        })
    } else {
        fillPromoView(nil)
    }
}
</code>```

Appear code

```<code>override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    UIView.animate(withDuration: 0.5, delay: 2.0, options: UIViewAnimationOptions.curveEaseInOut, animations: {
          ...
    }
}
</code>```

Here the code to download the product image:

```<code>func fetchDataFromDatabase(downloadCompleted: @escaping ((Product?) -> Void)) {
    FirebaseService.instance.getProductList { (productList) in
        if (productList.count != 0) {
            do {
                let productImage = try Data(contentsOf: productList.productImage as URL)

                // Fill the IBOutlet with the downloaded image
                self.promoProductImg.image = UIImage(data: productImage)

                downloadCompleted(productList)
            } catch {
                downloadCompleted(nil)
            }
        } else {
            downloadCompleted(nil)
        }
    }
}
</code>```

My aim is to launch the animation once I have a response from the download status or because the connection takes more than 2 seconds to download the image. Any advice?

答:
Your code in viewDidAppear will fire irregardless of whether you have a response from FireBase.

At an abstract level you need to allow your application to know when you have loaded data (or not)

The simpliest way of doing this would be;

Have a "skeleton" template for the product details page (here is an example of Facebooks version of it, see the first gif)

Move your view animation code out of viewDidAppear and into its own dedicated function.

Call this function via NSNotificationCenter inside the success portion offetchDataFromDatabase (via this notification paradigm, you will "fire" a notification in your fetchDataFromDatabase function, and your viewController will "listen" for this notification and respond accordingly (in this instance, by animating and presenting the data in a view"))

Body:
as the title says I have a problem with my app. Let me explain a little more in detail what I'm trying to achieve using a bulleted list:

The app loads the main menù and connect to firebase in order to see if there's some product to show

Download the product image

Animate the content in order to show the product info and image

I created functions to handle the case the connection doesn't work or the product doesn't exist. The problem is when the connection is too slow to load the image before the animation starts (about 2 seconds). In this case, the app stuck a little and the product will be shown before the animation ends.

Load code

override func viewDidLoad() {
    super.viewDidLoad()

    // The view where the product will be shown
    self.productView.alpha = 0.0

    // Checks the internet connection
    if (ConnectionService.isConnectedToNetwork()) {
        fetchDataFromDatabase(downloadCompleted: { (productToShow) in
            self.fillPromoView(usingProduct: productToShow)
        })
    } else {
        fillPromoView(nil)
    }
}

Appear code

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    UIView.animate(withDuration: 0.5, delay: 2.0, options: UIViewAnimationOptions.curveEaseInOut, animations: {
          ...
    }
}

Here the code to download the product image:

func fetchDataFromDatabase(downloadCompleted: @escaping ((Product?) -> Void)) {
    FirebaseService.instance.getProductList { (productList) in
        if (productList.count != 0) {
            do {
                let productImage = try Data(contentsOf: productList.productImage as URL)

                // Fill the IBOutlet with the downloaded image
                self.promoProductImg.image = UIImage(data: productImage)

                downloadCompleted(productList)
            } catch {
                downloadCompleted(nil)
            }
        } else {
            downloadCompleted(nil)
        }
    }
}

My aim is to launch the animation once I have a response from the download status or because the connection takes more than 2 seconds to download the image. Any advice?


问:
Visual studio equivalent of java System.out
What do I use in Visual Studio (C#) to perform the equivalent of Java's System.out.println( /*stuff*/ ) ?

Does the output from the command show in the Output window in the IDE?

I have a button on a webpage that calls a service which returns a string. I want to see what's in the string and have tried all the variations below and nothing ever shows up in the output. It also doesn't stop on the breakpoint so I can check if there are any results.

```<code>var service = new OTest.TylerAPI.APIWebServiceSoapClient();
results = service.OdysseyMsgExecution("<Message MessageType='FindCaseByCaseNumber' Source='APIMessage' ReferenceNumber='1' NodeID='1' UserID='1'> <CaseNumber>T4CV0043212010</CaseNumber></Message>", "NMODYSSEYMETRO");
System.Diagnostics.Debug.Write(results);
</code>```

答: Or, if you want to see output in the Output window of Visual Studio, System.Diagnostics.Debug.WriteLine(stuff)

Body:
What do I use in Visual Studio (C#) to perform the equivalent of Java's System.out.println( /*stuff*/ ) ?

Does the output from the command show in the Output window in the IDE?

I have a button on a webpage that calls a service which returns a string. I want to see what's in the string and have tried all the variations below and nothing ever shows up in the output. It also doesn't stop on the breakpoint so I can check if there are any results.

var service = new OTest.TylerAPI.APIWebServiceSoapClient();
results = service.OdysseyMsgExecution("<Message MessageType='FindCaseByCaseNumber' Source='APIMessage' ReferenceNumber='1' NodeID='1' UserID='1'> <CaseNumber>T4CV0043212010</CaseNumber></Message>", "NMODYSSEYMETRO");
System.Diagnostics.Debug.Write(results);


问:
How to add a set on numbers on a two dimensional array based on the results of first row in javascript
I have a two dimensional array:

```<code>var array = [["Alex", 10], ["Sam", 15], ["Alex", 20], ["Rob", 20], ["Sam", 10]];
</code>```

How can I make a new array where in the result would be something like this.

```<code>newArray = [["Alex", 30], ["Sam", 25], ["Rob", 20]];
</code>```

So basically what I want is to get the sum of the numbers for a particular individual.

Any help would be appreciated. I don't know if I have been able to explain the problem properly.

答:
Do you have access to the original data source to edit the structure?
Converting it in to an Array of Objects like this would be much neater and easier to deal with:

```<code>var array = [
    {name: "Alex", age: 10},
    {name: "Sam", age: 15},
    {name: "Alex", age: 20},
    {name: "Rob", age: 20},
    {name: "Sam", age: 10},
];
</code>```

then you could use an Array.filter inside an Array.forEach to extract the uniques like so:

```<code>var newArray = [];
array.forEach(person => {
    if (newArray.filter(item => item.name === person.name).length < 1) newArray.push(person);
});
</code>```

Super clean and utilises the ES6 Arrow Functions and shorthand :D

NOTE: If you can't change the original data source, you could re-format the data before the forEach using Array.map:

```<code>array.map(item => {name: item[0], age: item[1]});
</code>```

This will manipulate the original Array, replacing all entries with their Object equivalent.

NOTE #2: If you need legacy support, replacing the arrow functions with their anonymous function older brother e.g. function(item) { return {name: item[0], age: item[1]} } will make this code supported down to IE 9

Body:
I have a two dimensional array:

var array = [["Alex", 10], ["Sam", 15], ["Alex", 20], ["Rob", 20], ["Sam", 10]];

How can I make a new array where in the result would be something like this.

newArray = [["Alex", 30], ["Sam", 25], ["Rob", 20]];

So basically what I want is to get the sum of the numbers for a particular individual.

Any help would be appreciated. I don't know if I have been able to explain the problem properly.

Body:
Do you have access to the original data source to edit the structure?
Converting it in to an Array of Objects like this would be much neater and easier to deal with:

var array = [
    {name: "Alex", age: 10},
    {name: "Sam", age: 15},
    {name: "Alex", age: 20},
    {name: "Rob", age: 20},
    {name: "Sam", age: 10},
];

then you could use an Array.filter inside an Array.forEach to extract the uniques like so:

var newArray = [];
array.forEach(person => {
    if (newArray.filter(item => item.name === person.name).length < 1) newArray.push(person);
});

Super clean and utilises the ES6 Arrow Functions and shorthand :D

NOTE: If you can't change the original data source, you could re-format the data before the forEach using Array.map:

array.map(item => {name: item[0], age: item[1]});

This will manipulate the original Array, replacing all entries with their Object equivalent.

NOTE #2: If you need legacy support, replacing the arrow functions with their anonymous function older brother e.g. function(item) { return {name: item[0], age: item[1]} } will make this code supported down to IE 9


问:
MySQL charset=UTF-8 with ConnectionReset=True is not working
I've a connection string like below

"Server=localhost;Uid=root;Pwd='abcd';Database=testdb;charset=utf8;ConnectionReset=True;"

Any insertion to a database table column with unicode character is inserted as special characters. Everything works fine if i remove "ConnectionReset=True;" from my connection string.
Any idea whats going on here?

Note: I believe my code is fine because insertion of unicode is fine when I remove ConnectionReset=True; part from the connection string.

答:
You are encountering MySQL Bug #85185: "ConnectionReset pooling option does not preserve CharSet option value".

It's a good idea to use ConnectionReset=true; however, this has the side-effect of resetting the connection character set to the server default, which isn't what you want. I can think of two workarounds:

Use MySqlConnector, a replacement ADO.NET MySQL connector library that fixes this (and many other) Connector/NET bugs

Execute connection.ExecuteNonQuery("SET NAMES utf8mb4"); after each call to connection.Open(). This will fix the connection character set after a connection is reset when it's returned from the pool.

Finally, the MySQL utf8 character set is not actually UTF-8, so use utf8mb4 instead.


问:
Toggle the div with a button and hide the div when click outside of that div
I have a menu which I'm trying to toggle with a button (Which I've been able to do quit easily). But I also want menu to hide when clicked outside of it, And after lot of Googling I came across this solution. It works well i.e If you click outside the div, it hides it. But now I can't toggle the div with toggle button.

$('.toggle').click(function() {
  $(this).siblings('div').toggle();
});

$(document).mouseup(function(e) {
  var container = $(".menu");

  // if the target of the click isn't the container nor a descendant of the container
  if (!container.is(e.target) && container.has(e.target).length === 0) {
    container.hide();
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.toggle {
  border: 1px solid gray;
  padding: 3px;
  width: 50px;
  border-radius: 3px;
  cursor: pointer;
}

.menu {
  border: 1px solid gray;
  width: 150px;
  border-radius: 5px;
  margin-top: 8px;
}

.list,
{
  list-style: none;
}</code>```

  Toggle

Friends

Family

College

Colleague

Acquaintances

Unsorted

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

<p>I would really be greatful if alteast any one could explain to me what this line of code is actually doing.</p>

```container.has(e.target).length === 0
```

答:
I think you are looking for this, hope it helps:

$('.toggle').click(function(e) {
    $('.menu').toggle();
});
$('body :not(.menu, ul.list, li, .toggle)').click(function(e) {
    $(".menu").hide();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.toggle {
  border: 1px solid gray;
  padding: 3px;
  width: 50px;
  border-radius: 3px;
  cursor: pointer;
}

.menu {
  border: 1px solid gray;
  width: 150px;
  border-radius: 5px;
  margin-top: 8px;
}

.list,
{
  list-style: none;
}</code>```

  Toggle

Click

any

element

to

test

only

affect

toggle and menu classes

Friends

Family

College

Colleague

Acquaintances

Unsorted

```

Body:
I have a menu which I'm trying to toggle with a button (Which I've been able to do quit easily). But I also want menu to hide when clicked outside of it, And after lot of Googling I came across this solution. It works well i.e If you click outside the div, it hides it. But now I can't toggle the div with toggle button.

$('.toggle').click(function() {
  $(this).siblings('div').toggle();
});

$(document).mouseup(function(e) {
  var container = $(".menu");

  // if the target of the click isn't the container nor a descendant of the container
  if (!container.is(e.target) && container.has(e.target).length === 0) {
    container.hide();
  }
});

.toggle {
  border: 1px solid gray;
  padding: 3px;
  width: 50px;
  border-radius: 3px;
  cursor: pointer;
}

.menu {
  border: 1px solid gray;
  width: 150px;
  border-radius: 5px;
  margin-top: 8px;
}

.list,
{
  list-style: none;
}

  Toggle

Friends

Family

College

Colleague

Acquaintances

Unsorted

I would really be greatful if alteast any one could explain to me what this line of code is actually doing.

container.has(e.target).length === 0

Body:
I think you are looking for this, hope it helps:

$('.toggle').click(function(e) {
    $('.menu').toggle();
});
$('body :not(.menu, ul.list, li, .toggle)').click(function(e) {
    $(".menu").hide();
});

.toggle {
  border: 1px solid gray;
  padding: 3px;
  width: 50px;
  border-radius: 3px;
  cursor: pointer;
}

.menu {
  border: 1px solid gray;
  width: 150px;
  border-radius: 5px;
  margin-top: 8px;
}

.list,
{
  list-style: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="toggle">
  Toggle
</div>
<div>Click</div>
<div>any</div>
<div>element</div>
<div>to</div>
<div>test</div>
<div>only</div>
<div>affect</div>
<div>toggle and menu classes</div>
<div class="menu">
  <ul class="list">
    <li>Friends</li>
    <li>Family</li>
    <li>College</li>
    <li>Colleague</li>
    <li>Acquaintances</li>
    <li>Unsorted</li>
  </ul>
</div>


问:
Variables value gets lost in subshell
This bash script concatenates the names for jar files to a classpath (variable CP), in the while loop the value is correct but is lost in the subshell as descibed in this related question Bash variable scope

```<code>#!/bin/bash
CP="AAA"
func() {
        ls -1 | while read JAR
        do
                if [ ! -z "$CP" ]; then
                        CP=${CP}':'
                fi
                CP=${CP}${JAR}
        done
        echo $CP # <-- prints AAA
}

func
</code>```

My question is, since I can't figure out which element will be the last one, how can the value be saved.

Do I actually have to save the current value (repeatedly in the loop) to a file?

EDIT:

A colleague came up with this command sequence which works well

```<code>ls | xargs echo|tr ' ' :
</code>```

答:
None of these answers seem to get into actually returning the value properly, echoing out the answer is fine with a very simple routine, but say you want output of the script in action, this is useless. I don't have the best answer but I don't have much time to figure it out either, so I'm just going to suggest to output exactly what you want to a temp file and read that (surprised it hasn't been mentioned to date) :

```<code>#!/bin/bash
CP="AAA"
func() {
  ls -1 | (
    while read JAR
    do
      if [ ! -z "$CP" ]; then
        CP=${CP}':'
      fi
      CP=${CP}${JAR}
    done
    echo "$CP" > /tmp/cp-value-file
  )
}

func
CP=$(cat /tmp/cp-value-file)
echo $CP
</code>```

Downside: will in some cases need to write to the disk every iteration of the loop.

Title: Variables value gets lost in subshell

Body:
This bash script concatenates the names for jar files to a classpath (variable CP), in the while loop the value is correct but is lost in the subshell as descibed in this related question Bash variable scope

#!/bin/bash
CP="AAA"
func() {
        ls -1 | while read JAR
        do
                if [ ! -z "$CP" ]; then
                        CP=${CP}':'
                fi
                CP=${CP}${JAR}
        done
        echo $CP # <-- prints AAA
}

func

My question is, since I can't figure out which element will be the last one, how can the value be saved.

Do I actually have to save the current value (repeatedly in the loop) to a file?

EDIT:

A colleague came up with this command sequence which works well

ls | xargs echo|tr ' ' :

Body:
None of these answers seem to get into actually returning the value properly, echoing out the answer is fine with a very simple routine, but say you want output of the script in action, this is useless. I don't have the best answer but I don't have much time to figure it out either, so I'm just going to suggest to output exactly what you want to a temp file and read that (surprised it hasn't been mentioned to date) :

#!/bin/bash
CP="AAA"
func() {
  ls -1 | (
    while read JAR
    do
      if [ ! -z "$CP" ]; then
        CP=${CP}':'
      fi
      CP=${CP}${JAR}
    done
    echo "$CP" > /tmp/cp-value-file
  )
}

func
CP=$(cat /tmp/cp-value-file)
echo $CP

Downside: will in some cases need to write to the disk every iteration of the loop.


问:
Include files in Maven JAR package
I have a maven project with the following structure:

```<code>project

-src
--main
---java
----(All my .java files are here in their packages)
---resource
----(All my resources are here)

-database (HSQLDB files)
--db.script
--db.properties
--db.data

-target
--Maven build directory

pom.xml
</code>```

I want the maven jar plugin to package in the database folder when it builds a JAR file. I've tried including as outlined here: https://maven.apache.org/plugins/maven-jar-plugin/examples/include-exclude.html, but it doesn't find the directory "../database" (or ../../database OR ../../../database!), and also it now doesn't include any of the classes or resources (It was including them before).

So what should I have in the configuration of the maven jar plugin?
Which is the correct path to include and how do I keep the files it was including before?

Thanks

答:
By default, only resources located in src/main/resources are added in the JAR.

What you tried to do by configuring the maven-jar-plugin defines only the filetset to exclude or include in the built JAR.

But these files still have to be located in a resources folder where Maven looks for resources.

So, you have two ways to solve your requirement:

move database  in the standard directory : src/main/resources.

specifies two resource folders for resources :

To do the latter, in the pom.xml add in the build tag :

```<code><resources>
     <resource>
       <directory>src/main/resources</directory>
     </resource>
     <resource>
       <directory>database-resources</directory>
     </resource>
</resources>
</code>```

Then add the database folder that you want package inside the database-resources.

Title: Include files in Maven JAR package

Body:
I have a maven project with the following structure:

project

-src
--main
---java
----(All my .java files are here in their packages)
---resource
----(All my resources are here)

-database (HSQLDB files)
--db.script
--db.properties
--db.data

-target
--Maven build directory

pom.xml

I want the maven jar plugin to package in the database folder when it builds a JAR file. I've tried including as outlined here: https://maven.apache.org/plugins/maven-jar-plugin/examples/include-exclude.html, but it doesn't find the directory "../database" (or ../../database OR ../../../database!), and also it now doesn't include any of the classes or resources (It was including them before).

So what should I have in the configuration of the maven jar plugin?
Which is the correct path to include and how do I keep the files it was including before?

Thanks

Body:
By default, only resources located in src/main/resources are added in the JAR.

What you tried to do by configuring the maven-jar-plugin defines only the filetset to exclude or include in the built JAR.

But these files still have to be located in a resources folder where Maven looks for resources.

So, you have two ways to solve your requirement:

move database  in the standard directory : src/main/resources.

specifies two resource folders for resources :

To do the latter, in the pom.xml add in the build tag :

<resources>
     <resource>
       <directory>src/main/resources</directory>
     </resource>
     <resource>
       <directory>database-resources</directory>
     </resource>
</resources>

Then add the database folder that you want package inside the database-resources.


问:
Issues with gridview
I created a gridview with filter and everything fine but when I do gridview.databind(); nothing happen and with I change the page index nothing happen too.

I used scriptmanger,updatepanel and a little of javascript markup code:

```<code><asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"/>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
<asp:GridView ID="GridView1" ClientIDMode="Static" runat="server" AllowPaging="True" AutoGenerateColumns="False"
    onload="GridView1_Load" OnRowCreated="OnRowCreated" Width="614px" CellPadding="4" ForeColor="#333333"
    GridLines="Both" EmptyDataText="No Data To Show">
    <Columns>
        <asp:BoundField DataField="areacode" HeaderText="areacode"
            SortExpression="areacode" />
        <asp:BoundField DataField="areaename" HeaderText="areaename"
            SortExpression="areaename" />
        <asp:BoundField DataField="areaaname" HeaderText="areaaname"
            SortExpression="areaaname" />
        <asp:BoundField DataField="areazipcode" HeaderText="areazipcode"
            SortExpression="areazipcode" />
        <asp:BoundField DataField="districtcode" HeaderText="districtcode"
            SortExpression="districtcode" />
    </Columns>
    <EditRowStyle BackColor="#999999" />
    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"/>
    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
    <RowStyle BackColor="#ffffff" ForeColor="#333333" />
</asp:GridView>
    </ContentTemplate>
</asp:UpdatePanel>

<asp:SqlDataSource ID="SqlDataSource1" runat="server"
    ConnectionString="<%$ ConnectionStrings:NetCareConnectionString %>"
    SelectCommand="SELECT * FROM [areadata]"></asp:SqlDataSource>

<script language="javascript" type="text/javascript">
    var gridViewCtlId = '<%=GridView1.ClientID%>';
    var gridViewCtl = null;
    var curSelRow = null;

    function onchange(evt) {
        PageMethods.getControlData(evt.target.id, document.getElementById(evt.target.id).value);
    }
    function getGridViewControl() {
        if (null == gridViewCtl) {
            gridViewCtl = document.getElementById(gridViewCtlId);
        }
    }

    function onGridViewRowSelected(rowIdx, isfiltered) {
        var selRow;
        //filter one
        if (rowIdx == '1' & isfiltered == 'True')
            selRow = null;
        else
            selRow = getSelectedRow(rowIdx);

        if (curSelRow != null) {
            curSelRow.style.backgroundColor = '#ffffff';
        }

        if (selRow != null) {
            curSelRow = selRow;
            curSelRow.style.backgroundColor = '#8098B3';
        }

    }

    function getSelectedRow(rowIdx) {
        getGridViewControl();
        PageMethods.getRowSelected(rowIdx - 1);
        if (null != gridViewCtl) {
            return gridViewCtl.rows[rowIdx];
        }
        return null;
    }
</code>```

code behind:

```<code>    using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    static string controlID, controlValue, selectedRowIndex;
    #region WebMethods
    [System.Web.Services.WebMethod]
    public static void getControlData(string controlIDP, string controlValueP)
    {
        controlID = controlIDP;
        controlValue = controlValueP;
        _Default d = new _Default();
        d.textboxes_TextChanged();
    }
    [System.Web.Services.WebMethod]
    public static void getRowSelected(string rowIndex)
    {
        selectedRowIndex = rowIndex;
    }
    #endregion
    private void SetInitialRow(GridView inputGridView,SqlDataSource inputSqlDataSource)
    {
        if (inputGridView != null)
        {
            DataView dv = (DataView)inputSqlDataSource.Select(DataSourceSelectArguments.Empty);
            object [] session=new object[2];
            session[0]=dv;
            session[1] = inputGridView;
            Session["GridView"] = session;
            TextBox[] tb = new TextBox[inputGridView.Columns.Count];
            DataTable dt = dv.Table.Clone();
            dt.Rows.Add(dt.NewRow());
            for (int row = 0; row < dv.Table.Rows.Count; row++)
            {
                DataRow newRow = dt.NewRow();
                newRow = dv.Table.Rows[row];
                dt.ImportRow(newRow);
            }
            inputGridView.DataSource = dt;
            inputGridView.DataBind();
            for (int i = 0; i < inputGridView.Columns.Count; i++)
            {
                tb[i] = new TextBox();
                tb[i].Attributes.Add("id", i.ToString());
                if (!inputGridView.Rows[0].Cells[i].HasControls())
                    inputGridView.Rows[0].Cells[i].Controls.Add(tb[i]);
                else
                    inputGridView.Rows[0].Cells[i].Controls.Clear();
            }
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        SetInitialRow(GridView1, SqlDataSource1);
    }
    public void textboxes_TextChanged()
    {
        if (!string.IsNullOrWhiteSpace(controlValue))
        {
            object[] session = (object[])Session["GridView"];
            DataView dv = (DataView)session[0];
            GridView1 = (GridView)session[1];
            String strexpr = string.Format("{0}={1}", dv.Table.Columns[int.Parse(controlID)], controlValue);
            DataRow[] rows = dv.Table.Select(strexpr);
            DataTable dt = dv.Table.Clone();
            foreach (DataRow row in rows)
                dt.ImportRow(row);
            System.Windows.Forms.MessageBox.Show(dt.Rows.Count.ToString());
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }
    protected void OnRowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes.Add("onclick", "onGridViewRowSelected('" + (e.Row.RowIndex + 1).ToString() + "','" + true + "')");
        }
    }
    protected void GridView1_Load(object sender, EventArgs e)
    {

    }
}
</code>```

答:
I'm not sure which DataBind() is causing you problems.

When you execute:

```<code>    protected void Page_Load(object sender, EventArgs e)
{
         SetInitialRow(GridView1, SqlDataSource1);
}
</code>```

You are passing the GridView1 by value so when you bind to it in the SetInitialValue function, so are binding to a copy, NOT the gridview on the WebForm. You could try passing the GridView1 by reference. The same would apply to SqlDataSource1.

Edit
See ref (C# Reference) for more on the ref keyword in c#. If passing by reference, your code would look something like:

```<code>   protected void Page_Load(object sender, EventArgs e)
{
         SetInitialRow(ref GridView1, ref SqlDataSource1);
}
</code>```

and

```<code>private void SetInitialRow(ref GridView inputGridView,ref SqlDataSource inputSqlDataSource)
{
</code>```

Title: Issues with gridview

Body:
I created a gridview with filter and everything fine but when I do gridview.databind(); nothing happen and with I change the page index nothing happen too.

I used scriptmanger,updatepanel and a little of javascript markup code:

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"/>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
<asp:GridView ID="GridView1" ClientIDMode="Static" runat="server" AllowPaging="True" AutoGenerateColumns="False"
    onload="GridView1_Load" OnRowCreated="OnRowCreated" Width="614px" CellPadding="4" ForeColor="#333333"
    GridLines="Both" EmptyDataText="No Data To Show">
    <Columns>
        <asp:BoundField DataField="areacode" HeaderText="areacode"
            SortExpression="areacode" />
        <asp:BoundField DataField="areaename" HeaderText="areaename"
            SortExpression="areaename" />
        <asp:BoundField DataField="areaaname" HeaderText="areaaname"
            SortExpression="areaaname" />
        <asp:BoundField DataField="areazipcode" HeaderText="areazipcode"
            SortExpression="areazipcode" />
        <asp:BoundField DataField="districtcode" HeaderText="districtcode"
            SortExpression="districtcode" />
    </Columns>
    <EditRowStyle BackColor="#999999" />
    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"/>
    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
    <RowStyle BackColor="#ffffff" ForeColor="#333333" />
</asp:GridView>
    </ContentTemplate>
</asp:UpdatePanel>

<asp:SqlDataSource ID="SqlDataSource1" runat="server"
    ConnectionString="<%$ ConnectionStrings:NetCareConnectionString %>"
    SelectCommand="SELECT * FROM [areadata]"></asp:SqlDataSource>

Body:
I'm not sure which DataBind() is causing you problems.

When you execute:

    protected void Page_Load(object sender, EventArgs e)
{
         SetInitialRow(GridView1, SqlDataSource1);
}

You are passing the GridView1 by value so when you bind to it in the SetInitialValue function, so are binding to a copy, NOT the gridview on the WebForm. You could try passing the GridView1 by reference. The same would apply to SqlDataSource1.

Edit
See ref (C# Reference) for more on the ref keyword in c#. If passing by reference, your code would look something like:

   protected void Page_Load(object sender, EventArgs e)
{
         SetInitialRow(ref GridView1, ref SqlDataSource1);
}

and

private void SetInitialRow(ref GridView inputGridView,ref SqlDataSource inputSqlDataSource)
{


问:
Java EWS- how to identify if attachment is sender signature image
I need to identify if an attachment is signature image of the sender and ignore it as I want to skip that kind of attachments, but I'm not able to identify if that particular attachment is signature image.

Or can a user add a custom property while adding the signature image, so I can look for that property in the program?

```<code>if (emailMessage.getHasAttachments() || emailMessage.getAttachments().getItems().size() > 0) {

//get all the attachments
AttachmentCollection attachmentsCol = emailMessage.getAttachments();

log.info("File Count: " + attachmentsCol.getCount());

    Attachment attachment = attachmentsCol.getPropertyAtIndex(i);
    //log.debug("Starting to process attachment "+ attachment.getName());

    //do we need to skip this attachment

        FileAttachment fileAttachment = (FileAttachment) attachment;
        // if we don't call this, the Content property may be null.
        fileAttachment.load();
        booelan isSignatureImage = fileAttachment.isContactPhoto(); // this is false
}
</code>```

}

答:
I figured out a way to do this. Run the code once, determine a hash of the attachment you want to ignore and then make a local string of this hash. Then, each attachment you process, compare it to this local hash string and if they match, you can just ignore it and move to the next (if you are processing attachments in a loop like I am).  </p>

```<code>            // you must first load your attachment to be able to call .getContent() on it
            fileAttachment.load();

            // load content
            byte[] b = fileAttachment.getContent();

            // get the hash of your attachment
            byte[] hash = MessageDigest.getInstance("MD5").digest(b);

            // after you run this on the attachment you do not want, take the string from 'actual' below and put it here
            String expected = "YOUR HASHED STRING";

            String actual = DatatypeConverter.printHexBinary(hash);
            System.out.println(actual);

            // some conditional to check if your current hash matches expected
            if(actual.equals(expected)){
                continue;
            }
</code>```

Body:
I need to identify if an attachment is signature image of the sender and ignore it as I want to skip that kind of attachments, but I'm not able to identify if that particular attachment is signature image.

Or can a user add a custom property while adding the signature image, so I can look for that property in the program?

if (emailMessage.getHasAttachments() || emailMessage.getAttachments().getItems().size() > 0) {

//get all the attachments
AttachmentCollection attachmentsCol = emailMessage.getAttachments();

log.info("File Count: " + attachmentsCol.getCount());

    Attachment attachment = attachmentsCol.getPropertyAtIndex(i);
    //log.debug("Starting to process attachment "+ attachment.getName());

    //do we need to skip this attachment

        FileAttachment fileAttachment = (FileAttachment) attachment;
        // if we don't call this, the Content property may be null.
        fileAttachment.load();
        booelan isSignatureImage = fileAttachment.isContactPhoto(); // this is false
}

}

Body:
I figured out a way to do this. Run the code once, determine a hash of the attachment you want to ignore and then make a local string of this hash. Then, each attachment you process, compare it to this local hash string and if they match, you can just ignore it and move to the next (if you are processing attachments in a loop like I am).

            // you must first load your attachment to be able to call .getContent() on it
            fileAttachment.load();

            // load content
            byte[] b = fileAttachment.getContent();

            // get the hash of your attachment
            byte[] hash = MessageDigest.getInstance("MD5").digest(b);

            // after you run this on the attachment you do not want, take the string from 'actual' below and put it here
            String expected = "YOUR HASHED STRING";

            String actual = DatatypeConverter.printHexBinary(hash);
            System.out.println(actual);

            // some conditional to check if your current hash matches expected
            if(actual.equals(expected)){
                continue;
            }


问:
Can I disable the bootstrap checks in Elasticsearch 5.4?
I'm running Elasticsearch on a non-production RHEL6 server. I only have a regular user account with no root access. I'm in a very locked-down corporate environment so getting root will be time-consuming and I need a work-around.

When I start the process I get these errors:

```<code>max file descriptors [8192] for elasticsearch process is too low, increase to at least [65536]
max number of threads [1024] for user [salimfadhley] is too low, increase to at least [2048]
max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144]
</code>```

Is there a way to make ElasticSearch ignore this error condition and just start up.

I'm fully aware that ignoring errors is normally considered unwise, however on this occasion I just need to get ES up and running so that I can devote my attention to other aspects of this project: Getting the system limits raised will take more time than I currently have available.

答:
Yes you can!

(I found) this is very dirty, but if you configure discovery.type as single-node, no bootstrap check will run.

Yes, that means you cannot test a cluster in your laptop.

See https://github.com/elastic/elasticsearch/issues/21655

Body:
I'm running Elasticsearch on a non-production RHEL6 server. I only have a regular user account with no root access. I'm in a very locked-down corporate environment so getting root will be time-consuming and I need a work-around.

When I start the process I get these errors:

max file descriptors [8192] for elasticsearch process is too low, increase to at least [65536]
max number of threads [1024] for user [salimfadhley] is too low, increase to at least [2048]
max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144]

Is there a way to make ElasticSearch ignore this error condition and just start up.

I'm fully aware that ignoring errors is normally considered unwise, however on this occasion I just need to get ES up and running so that I can devote my attention to other aspects of this project: Getting the system limits raised will take more time than I currently have available.


答:
You need to first gather by the columns you want to spread, and combine the Period column with the variable column, then spread the resulting variable column:

```<code>library(dplyr)
library(tidyr)

test %>%
  gather(variable, value, count:SumTotal) %>%
  unite("variable", Period, variable, sep = ".") %>%
  spread(variable, value)
</code>```

Result:

```<code>   SR Area First.count First.countTotal First.SumTotal Second.count Second.countTotal
1   1  TSC           4               10        1520.00            6                10
2  15   FH           3                3       29346.78           NA                NA
3  20   FH           6               12       13316.89            6                12
4  96   FH           3                3       10173.05           NA                NA
5 110   MO           6               12       13243.50            6                12
6 121   FH           6               12      111189.07            6                12
7 130  WMB           6               12       79463.10            6                12
8 143   MO           5               11        7035.88            6                11
  Second.SumTotal
1         5769.02
2              NA
3        11932.68
4              NA
5        17131.94
6        84123.52
7       120010.57
8        11520.00
</code>```

Title: Convert some rows to columns in r

Body:
I have a dataset like the one below:

test <- structure(list(SR = c(1L, 1L, 15L, 20L, 20L, 96L, 110L, 110L,
121L, 121L, 130L, 130L, 143L, 143L), Area = structure(c(3L, 3L,
1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 4L, 4L, 2L, 2L), .Label = c("FH",
"MO", "TSC", "WMB"), class = "factor"), Period = structure(c(1L,
2L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L), .Label = c("First",
"Second"), class = "factor"), count = c(4L, 6L, 3L, 6L, 6L, 3L,
6L, 6L, 6L, 6L, 6L, 6L, 5L, 6L), countTotal = c(10L, 10L, 3L,
12L, 12L, 3L, 12L, 12L, 12L, 12L, 12L, 12L, 11L, 11L), SumTotal = c(1520,
5769.02, 29346.78, 13316.89, 11932.68, 10173.05, 13243.5, 17131.94,
111189.07, 84123.52, 79463.1, 120010.57, 7035.88, 11520)), .Names = c("SR",
"Area", "Period", "count", "countTotal", "SumTotal"), class = "data.frame", row.names = c(NA,
-14L))

 SR Area Period count countTotal  SumTotal
  1  TSC  First     4         10   1520.00
  1  TSC Second     6         10   5769.02
 15   FH  First     3          3  29346.78
 20   FH  First     6         12  13316.89
 20   FH Second     6         12  11932.68
 96   FH  First     3          3  10173.05
110   MO  First     6         12  13243.50
110   MO Second     6         12  17131.94
121   FH  First     6         12 111189.07
121   FH Second     6         12  84123.52
130  WMB  First     6         12  79463.10
130  WMB Second     6         12 120010.57
143   MO  First     5         11   7035.88
143   MO Second     6         11  11520.00

I want to convert some of the rows to columns to make the dataset look like this:

 SR Area countTotal First.Count Second.Count First.SumTotal Second.SumTotal
  1  TSC         10           4            6        1520.00         5769.02
 15   FH          3           3           NA       29346.78              NA
 20   FH         12           6            6       13316.89        11932.68
 96   FH          3           3           NA       10173.05              NA
110   MO         12           6            6       13243.50        17131.94
121   FH         12           6            6      111189.07        84123.52
130  WMB         12           6            6       79463.10       120010.57
143   MO         11           5            6        7035.88        11520.00

I was trying to use spread from tidyr with this code
test %>% spread(Period, SumTotal) but I still get two lines for each SR and Area.
Can someone help?

Body:
You need to first gather by the columns you want to spread, and combine the Period column with the variable column, then spread the resulting variable column:

library(dplyr)
library(tidyr)

test %>%
  gather(variable, value, count:SumTotal) %>%
  unite("variable", Period, variable, sep = ".") %>%
  spread(variable, value)

Result:

   SR Area First.count First.countTotal First.SumTotal Second.count Second.countTotal
1   1  TSC           4               10        1520.00            6                10
2  15   FH           3                3       29346.78           NA                NA
3  20   FH           6               12       13316.89            6                12
4  96   FH           3                3       10173.05           NA                NA
5 110   MO           6               12       13243.50            6                12
6 121   FH           6               12      111189.07            6                12
7 130  WMB           6               12       79463.10            6                12
8 143   MO           5               11        7035.88            6                11
  Second.SumTotal
1         5769.02
2              NA
3        11932.68
4              NA
5        17131.94
6        84123.52
7       120010.57
8        11520.00


问:
Add new objects after using "new"
after I call new, how can I add more objects to the pointer? (I need it for a class)
this is what I mean:

```<code>int *a;
a = new int;
a = new int;
</code>```

Thank you very much!

答: You should probably use a vector or list.</p>

Title: Add new objects after using "new"

Body:
after I call new, how can I add more objects to the pointer? (I need it for a class)
this is what I mean:

int *a;
a = new int;
a = new int;

Thank you very much!


问:
Android studio uses 100% CPU while just coding (no builiding)
Android Studio uses 100% CPU when I'm just coding, even if I type a single word CPU use raises to the 100% and comes to back normal, and if I keep typing it takes 100% CPU all the time.

What I have tried is :

File > Invalidate cache and Restart

Change max heap size for android studio by editing VM options

"Power Save Mode" it runs perfectly when it is turned on. but it also disables some useful features of IDE and I don't want to disable it.

removed .android and .AndroidStudio3.0 folder from c:\users\username\

Android Studio plugins are set to default. no extra plugins are added. I tried disabling a plugin that can be disabled like Git and SVN but it's still same

I'm running windows 7 64-bit OS and Android Studio 3.0 and OS which I re-installed yesterday. I did not install the JDK - Android Studio is using default OpenJDK.

I've searched on internet but it did not help. any help would be appreciated.

答: Try to add more Heap memory for Android Studio, go to Help -> Edit Custom VM Options... and set -Xmx2g (depends on your project size), after restart AS.</p>

ContentLicense: CC BY-SA 4.0