问:
hazelcast open source cost?
I am new to hazelcast and want to use the replicated map to share data between two microservices. Using spring-boot-starter cache with following two modules. Is it open source/free ?

```<code>  `enter code here`<!-- Core hazelcast module -->
    <dependency>
        <groupId>com.hazelcast</groupId>
        <artifactId>hazelcast</artifactId>
    </dependency>

    <!-- hazelcast-spring -->
    <dependency>
        <groupId>com.hazelcast</groupId>
        <artifactId>hazelcast-spring</artifactId>
    </dependency>
</code>```

Please help

答:
Short answer: Yes, it is.

Long answer: It's Apache as the LICENSE file on GitHub clearly states.

Title: hazelcast open source cost?

Body:
I am new to hazelcast and want to use the replicated map to share data between two microservices. Using spring-boot-starter cache with following two modules. Is it open source/free ?

  `enter code here`
    <dependency>
        <groupId>com.hazelcast</groupId>
        <artifactId>hazelcast</artifactId>
    </dependency>

    <dependency>
        <groupId>com.hazelcast</groupId>
        <artifactId>hazelcast-spring</artifactId>
    </dependency>

Please help


来源: stackexchange

问:
Why is a pointer to int initialised with “*int” and not “&int”?
For example, when initialising a pointer to an int, we use:

```<code>var pointer *int
</code>```

Why is the syntax not instead:

```<code>var pointer &int
</code>```

To me, the second version would have made more sense as it would read like “variable ‘pointer’ is a memory address of an int”

Or to put it another way, I find it confusing that the “*” is used for both for defining a memory address type (as above), and for dereferencing, e.g.
*pointer = 123

Is this as confusing as it seems, or am I missing something here?

答:
& is an address operator, not a type.

For an operand x of type T, the address operation &x generates a pointer of type *T to x.

But it is true * is also used as a pointer indirection:

For an operand x of pointer type *T, the pointer indirection *x denotes the variable of type T pointed to by x

As seen in Tour of Go, * references both a type and an operator.

This thread from 2016 asks a similar question.

The pointer syntax is just copied from C, of course.

  See also Go's Declaration Syntax

  If we had used '&', then a Go pointer would look like a C++ reference.

And:

*int defines a pointer type and then can be used with or without the * on the variable.

With the * you access the value pointed to.

Without, you access the memory address pointed to.

& retrieves a memory address from a variable.

An address is not a pointer and vice versa.

  You define a pointer using a memory address.

```<code>var x int = 10    // declare an int variable `x` holding the value 10.
var y *int = &x  // Create a pointer `y` *using* the memory address of `x`.
</code>```

*y will have the value 10.

  y will be the memory address of x

See more in "Pointers in Go" from Dave Cheney:

Go pointers, like C pointers, are values that, uh, point to other values. This is a tremendously important concept and shouldn’t be considered dangerous or something to get hung up on.

A pointer is a value that points to the memory address of another variable.

But:

you cannot alter the address p points to unless you assign another address to it

  No: var p *int; p++ possible.

(See also "Go at Google: Language Design in the Service of Software Engineering")

Once a value is assigned to a pointer, with the exception of nil, Go guarantees that the thing being pointed to will continue to be valid for the lifetime of the pointer.

ContentLicense: CC BY-SA 4.0

Body:
For example, when initialising a pointer to an int, we use:

var pointer *int

Why is the syntax not instead:

var pointer &int

To me, the second version would have made more sense as it would read like “variable ‘pointer’ is a memory address of an int”

Or to put it another way, I find it confusing that the “*” is used for both for defining a memory address type (as above), and for dereferencing, e.g.
*pointer = 123

Is this as confusing as it seems, or am I missing something here?

Body:
& is an address operator, not a type.

For an operand x of type T, the address operation &x generates a pointer of type *T to x.

But it is true * is also used as a pointer indirection:

For an operand x of pointer type *T, the pointer indirection *x denotes the variable of type T pointed to by x

As seen in Tour of Go, * references both a type and an operator.

This thread from 2016 asks a similar question.

The pointer syntax is just copied from C, of course.

  See also Go's Declaration Syntax

  If we had used '&', then a Go pointer would look like a C++ reference.

And:

*int defines a pointer type and then can be used with or without the * on the variable.

With the * you access the value pointed to.

Without, you access the memory address pointed to.

& retrieves a memory address from a variable.

An address is not a pointer and vice versa.

  You define a pointer using a memory address.

var x int = 10    // declare an int variable `x` holding the value 10.
var y *int = &x  // Create a pointer `y` *using* the memory address of `x`.

*y will have the value 10.

  y will be the memory address of x

See more in "Pointers in Go" from Dave Cheney:

Go pointers, like C pointers, are values that, uh, point to other values. This is a tremendously important concept and shouldn’t be considered dangerous or something to get hung up on.

A pointer is a value that points to the memory address of another variable.

But:

you cannot alter the address p points to unless you assign another address to it

  No: var p *int; p++ possible.

(See also "Go at Google: Language Design in the Service of Software Engineering")

Once a value is assigned to a pointer, with the exception of nil, Go guarantees that the thing being pointed to will continue to be valid for the lifetime of the pointer.


问:
java.lang.NoClassDefFoundError: net/sf/hibernate/HibernateException
I am developing a JSF webapp with Hibernate. I tested with a main class and I can insert in database, but I can't deploy my webapp to Glassfish. It always errors with HTTP 500 error. Here is my code:

faces-config:

```<code><?xml version="1.0" encoding="UTF-8"?>
<faces-config version="1.2" xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xi="http://www.w3.org/2001/XInclude"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd">
 <application>
        <view-handler>com.sun.facelets.FaceletViewHandler</view-handler>
    </application>

 <managed-bean>
  <managed-bean-name>timesheetBean</managed-bean-name>
  <managed-bean-class>hibernate.timeBean.TimesheetBean</managed-bean-class>
  <managed-bean-scope>session</managed-bean-scope>
 </managed-bean>
 <navigation-rule>
  <from-view-id>/EditTimesheet.jsp</from-view-id>
 </navigation-rule>
</faces-config>
</code>```

web.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>test</display-name>

  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <context-param>
        <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
        <param-value>client</param-value>
    </context-param>

    <filter>
        <display-name>RichFaces Filter</display-name>
        <filter-name>richfaces</filter-name>
        <filter-class>org.ajax4jsf.Filter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>richfaces</filter-name>
        <servlet-name>Faces Servlet</servlet-name>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
        <dispatcher>INCLUDE</dispatcher>
    </filter-mapping>

    <context-param>
        <param-name>org.ajax4jsf.VIEW_HANDLERS</param-name>
        <param-value>com.sun.facelets.FaceletViewHandler</param-value>
    </context-param>
    <context-param>
        <param-name>javax.faces.DEFAULT_SUFFIX</param-name>
        <param-value>.xhtml</param-value>
    </context-param>

    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.jsf</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>
</code>```

EditTimesheet.jsp:

```<code><%@ page language="java" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <base href="<%=basePath%>">

    <title>My JSF 'EditDepartement.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

</head>

<body>
    <f:view>
        <h:form>
        <h:inputHidden id="id" value="#{timesheetBean.currentTimesheet.id}" />
        <h:panelGrid columns="2" border="1">
            <h:inputText value="#{timesheetBean.currentTimesheet.action}">
            </h:inputText>
            <h:outputText value="heure:" />
            <h:inputText value="#{timesheetBean.currentTimesheet.heure}">
            </h:inputText>
            <h:outputText value="date:" />
            <h:inputText value="#{timesheetBean.currentTimesheet.date}">
            </h:inputText>

</h:panelGrid>
        <h:commandButton value="Save" action="listeDepartements" actionListener="#{timesheetBean.saveTimesheet}" />
        <h:commandButton value="Annuler" action="listeTimesheet"/>
    </h:form>
    </f:view>
</body>
</html>
</code>```

The exeception is:

```<code>javax.servlet.ServletException: net/sf/hibernate/HibernateException

 root cause: java.lang.NoClassDefFoundError: net/sf/hibernate/HibernateException
</code>```

How is this caused and how can I solve it?

答:
It appears that you are utilizing Hibernate but don't have the Hibernate jar and dependencies built into your war. Make sure that all the dependencies you need are being built into the WEB-INF/lib directory inside your war.

The process for this would depend on how you are constructing your web application.

ContentLicense: CC BY-SA 3.0

Body:
I am developing a JSF webapp with Hibernate. I tested with a main class and I can insert in database, but I can't deploy my webapp to Glassfish. It always errors with HTTP 500 error. Here is my code:

faces-config:

<?xml version="1.0" encoding="UTF-8"?>
<faces-config version="1.2" xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xi="http://www.w3.org/2001/XInclude"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd">
 <application>
        <view-handler>com.sun.facelets.FaceletViewHandler</view-handler>
    </application>

 <managed-bean>
  <managed-bean-name>timesheetBean</managed-bean-name>
  <managed-bean-class>hibernate.timeBean.TimesheetBean</managed-bean-class>
  <managed-bean-scope>session</managed-bean-scope>
 </managed-bean>
 <navigation-rule>
  <from-view-id>/EditTimesheet.jsp</from-view-id>
 </navigation-rule>
</faces-config>

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>test</display-name>

  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <context-param>
        <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
        <param-value>client</param-value>
    </context-param>

    <filter>
        <display-name>RichFaces Filter</display-name>
        <filter-name>richfaces</filter-name>
        <filter-class>org.ajax4jsf.Filter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>richfaces</filter-name>
        <servlet-name>Faces Servlet</servlet-name>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
        <dispatcher>INCLUDE</dispatcher>
    </filter-mapping>

    <context-param>
        <param-name>org.ajax4jsf.VIEW_HANDLERS</param-name>
        <param-value>com.sun.facelets.FaceletViewHandler</param-value>
    </context-param>
    <context-param>
        <param-name>javax.faces.DEFAULT_SUFFIX</param-name>
        <param-value>.xhtml</param-value>
    </context-param>

    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.jsf</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

EditTimesheet.jsp:

<%@ page language="java" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

    <base href="<%=basePath%>">

    <title>My JSF 'EditDepartement.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">

    <f:view>
        <h:form>
        <h:inputHidden id="id" value="#{timesheetBean.currentTimesheet.id}" />
        <h:panelGrid columns="2" border="1">
            <h:inputText value="#{timesheetBean.currentTimesheet.action}">
            </h:inputText>
            <h:outputText value="heure:" />
            <h:inputText value="#{timesheetBean.currentTimesheet.heure}">
            </h:inputText>
            <h:outputText value="date:" />
            <h:inputText value="#{timesheetBean.currentTimesheet.date}">
            </h:inputText>

</h:panelGrid>
        <h:commandButton value="Save" action="listeDepartements" actionListener="#{timesheetBean.saveTimesheet}" />
        <h:commandButton value="Annuler" action="listeTimesheet"/>
    </h:form>
    </f:view>

The exeception is:

javax.servlet.ServletException: net/sf/hibernate/HibernateException

 root cause: java.lang.NoClassDefFoundError: net/sf/hibernate/HibernateException

How is this caused and how can I solve it?


问:
Idiom for handling size_t underflow in loop condition
In C and C++, size_t is an unsigned type that is used for expressing size. It expresses intent and somewhat simplifies range assertions (len < upper_bound vs len >= 0 && len < upper_bound for signed integers).

(In all the examples below len means the length of the array a).

The idiom for a for loop is: for (i = 0; i < len; i++). The idiom for  a backward for loop is for (i = len-1; i >= 0; i--). But having unsigned loop indices introduces subtle bugs, and every so often I mess up the edge cases.

First, the backwards for loop. This code underflows for len=0.

```<code>for (size_t i = len-1; i >= 0; i--) { // Bad: Underflows for len=0
    use(a[i]);
}
</code>```

There's the --> "operator" trick, which looks strange if you're not used to it.

```<code>for (size_t i = len; i--> 0;) {
    use(a[i]);
}
</code>```

You can use a signed type for the loop index variable, but that overflows if len > INT_MAX. Many people and organizations considers that risk so minimal that they just stick to int.

```<code>for (int i = len-1; i >= 0; i--) {  // BAD: overflows for len < INT_MAX
    use(a[i]);
}
</code>```

So I've settled for this construct, since it's closest to the canonical for-loop form and has the simplest expressions.

```<code>for (size_t i = len; i > 0; i--) {
    size_t pos = i-1;
    use(a[pos]);
}
</code>```

My problem iterating from 0 to len-1

That is, looping over the range [0, len-1). This loop underflows when len=0.

```<code>for (size_t i = 0; i < len-1; i++) {   // BAD: Underflows for len=0.
    use(a[i]);
}
</code>```

As for the iterating backwards case, you can use signed integers but that may cause overflows.

```<code>for (int i = 0; i < len-1; i++) {    // BAD: Will overflow if len > INT_MAX
    use(a[i]);
}
</code>```

I tend to add another expression to the loop condition, checking for len > 0, but that feels clumsy.

```<code>for (size_t i = 0; len > 0 && i < len-1; i++) {
    use(a[i]);
}
</code>```

I can add an if statement before the loop, but that also feels clumsy.

Is there a less bulky way of writing a for loop with unsigned index variables looping from 0 to len-1?

答:
In all these cases, you have one common theme: You have an index that has a start value. It gets incremented or decremented until it reaches the end value, which terminates the loop.

One thing that helps here is to make these two values explicit. In the simplest case, forward-iterating the whole range, the end value is simply len:

```<code>for (size_t i=0, end=len; i!=end; ++i) {
    ///...
}
</code>```

This follows the general advise given to people using iterators. In particular, pay attention to the comparison, which works here and which is actually required for some iterators.

Now, backward iterating:

```<code>for (size_t i=len-1, end=-1; i!=end; --i) {
    ///...
}
</code>```

Lastly, iterating a subset excluding the last n elements of the range backwards:

```<code>if (len > n) {
    for (size_t i=len-n-1, end=-1; i!=end; --i) {
        ///...
    }
}
</code>```

Actually, what you were fighting with was your attempt to put too much stuff into the loop logic. Just be explicit that this requires more than n elements in order to do anything at all. Yes, you could put len > n into the loop condition, but that wouldn't give you clear and simple code who's intention anyone understands.

Body:
In C and C++, size_t is an unsigned type that is used for expressing size. It expresses intent and somewhat simplifies range assertions (len < upper_bound vs len >= 0 && len < upper_bound for signed integers).

(In all the examples below len means the length of the array a).

The idiom for a for loop is: for (i = 0; i < len; i++). The idiom for  a backward for loop is for (i = len-1; i >= 0; i--). But having unsigned loop indices introduces subtle bugs, and every so often I mess up the edge cases.

First, the backwards for loop. This code underflows for len=0.

for (size_t i = len-1; i >= 0; i--) { // Bad: Underflows for len=0
    use(a[i]);
}

There's the --> "operator" trick, which looks strange if you're not used to it.

for (size_t i = len; i--> 0;) {
    use(a[i]);
}

You can use a signed type for the loop index variable, but that overflows if len > INT_MAX. Many people and organizations considers that risk so minimal that they just stick to int.

for (int i = len-1; i >= 0; i--) {  // BAD: overflows for len < INT_MAX
    use(a[i]);
}

So I've settled for this construct, since it's closest to the canonical for-loop form and has the simplest expressions.

for (size_t i = len; i > 0; i--) {
    size_t pos = i-1;
    use(a[pos]);
}

My problem iterating from 0 to len-1

That is, looping over the range [0, len-1). This loop underflows when len=0.

for (size_t i = 0; i < len-1; i++) {   // BAD: Underflows for len=0.
    use(a[i]);
}

As for the iterating backwards case, you can use signed integers but that may cause overflows.

for (int i = 0; i < len-1; i++) {    // BAD: Will overflow if len > INT_MAX
    use(a[i]);
}

I tend to add another expression to the loop condition, checking for len > 0, but that feels clumsy.

for (size_t i = 0; len > 0 && i < len-1; i++) {
    use(a[i]);
}

I can add an if statement before the loop, but that also feels clumsy.

Is there a less bulky way of writing a for loop with unsigned index variables looping from 0 to len-1?

Body:
In all these cases, you have one common theme: You have an index that has a start value. It gets incremented or decremented until it reaches the end value, which terminates the loop.

One thing that helps here is to make these two values explicit. In the simplest case, forward-iterating the whole range, the end value is simply len:

for (size_t i=0, end=len; i!=end; ++i) {
    ///...
}

This follows the general advise given to people using iterators. In particular, pay attention to the comparison, which works here and which is actually required for some iterators.

Now, backward iterating:

for (size_t i=len-1, end=-1; i!=end; --i) {
    ///...
}

Lastly, iterating a subset excluding the last n elements of the range backwards:

if (len > n) {
    for (size_t i=len-n-1, end=-1; i!=end; --i) {
        ///...
    }
}

Actually, what you were fighting with was your attempt to put too much stuff into the loop logic. Just be explicit that this requires more than n elements in order to do anything at all. Yes, you could put len > n into the loop condition, but that wouldn't give you clear and simple code who's intention anyone understands.


问:
Why Java synchronized threads printing out of order?
I am running this java thread example :

```<code>public class Locks1 extends Thread {
    private Object lock;
    private int myId;
    public Locks1( Object l, int id ) {
      lock = l; myId = id;
    }
    public void run() {
      synchronized( lock ) {
        for ( int i = 0; i < 3; i++ ) {
          System.out.println( "Thread #" + myId + " is tired" );
        try {
          Thread.currentThread().sleep( 10 );
        } catch ( InterruptedException e ){

        } System.out.println("Thread #" + myId + " is rested" );
      }
    }
  }
    public static void main( String args[] ) {
        Integer lock = new Integer( 0 );
        for ( int i = 0; i < 4; i++ ) {
          new Locks1( lock, i ).start();
        }
    }
}
</code>```

And I am having this result:

```<code>Thread #0 is tired
Thread #0 is rested
Thread #0 is tired
Thread #0 is rested
Thread #0 is tired
Thread #0 is rested
Thread #3 is tired
Thread #3 is rested
Thread #3 is tired
Thread #3 is rested
Thread #3 is tired
Thread #3 is rested
Thread #2 is tired
Thread #2 is rested
Thread #2 is tired
Thread #2 is rested
Thread #2 is tired
Thread #2 is rested
Thread #1 is tired
Thread #1 is rested
Thread #1 is tired
Thread #1 is rested
Thread #1 is tired
Thread #1 is rested
</code>```

I don't understand why it prints in this order. Can anyone please help me to understand why the sequence is 0321 instead of 0123?

Thanks

答: When several threads are waiting to acquire a lock and it finally becomes available, there is no guarantee what thread will be chosen. It can be any one. If you execute the test several times, you might get different results.</p>

Body:
I am running this java thread example :

public class Locks1 extends Thread {
    private Object lock;
    private int myId;
    public Locks1( Object l, int id ) {
      lock = l; myId = id;
    }
    public void run() {
      synchronized( lock ) {
        for ( int i = 0; i < 3; i++ ) {
          System.out.println( "Thread #" + myId + " is tired" );
        try {
          Thread.currentThread().sleep( 10 );
        } catch ( InterruptedException e ){

        } System.out.println("Thread #" + myId + " is rested" );
      }
    }
  }
    public static void main( String args[] ) {
        Integer lock = new Integer( 0 );
        for ( int i = 0; i < 4; i++ ) {
          new Locks1( lock, i ).start();
        }
    }
}

And I am having this result:

Thread #0 is tired
Thread #0 is rested
Thread #0 is tired
Thread #0 is rested
Thread #0 is tired
Thread #0 is rested
Thread #3 is tired
Thread #3 is rested
Thread #3 is tired
Thread #3 is rested
Thread #3 is tired
Thread #3 is rested
Thread #2 is tired
Thread #2 is rested
Thread #2 is tired
Thread #2 is rested
Thread #2 is tired
Thread #2 is rested
Thread #1 is tired
Thread #1 is rested
Thread #1 is tired
Thread #1 is rested
Thread #1 is tired
Thread #1 is rested

I don't understand why it prints in this order. Can anyone please help me to understand why the sequence is 0321 instead of 0123?

Thanks


问:
Ruby on Rails maintenance and RSpec
How are your experiences with RoR maintenance and RSpec.

Is RSpec good for real use, I mean do developers generally use it, or is it something you can live without?

How is with maintenance aspects of RoR, web hosting - is it cheap and abundant like say PHP hosting, gem dependencies and updates, changing the database model, etc.?

I'm researching couple of technologies for the next web project and RoR seems ok at a first glance, but wouldn't like to jump into something that requires a lot to maintain. Thanks.

答:
Rspec is definitely good for real use and most Rails developers use it a lot for their testing purposes. Generally speaking, Rails and testing are tied together. You can of course live without rspec, but testing is pretty important. You can always use test/unit, shoulda or other solutions, as long as you use something.

I would advice that you get a dedicated server for Rails or host it on Heroku. These are probably the best ways to go about it. Maintaining the projects is a whole easier than php or other choices.

Generally speaking, i highly recommend Rails :)

Title: Ruby on Rails maintenance and RSpec


问:
Exoplayer local path with Question Mark
I am developing music application. I have been using exoplayer to play music. I have lived a problem and couldn't find any solution. My problem is that ı have downloaded song file from internet. This song name contains "?" mark. I create path for this song file and use its name. After song downloaded successfully. I play with exoplayer. I create path for this song and set to exoplayer but it couldn't be played.

Song path = /storage/emulated/0/mymusic/downloads/How am I?_009.mp3

Uri uri = Uri.parse(path);

```<code>    MediaSource mediaSource = new ExtractorMediaSource.Factory(dataSourceFactory).createMediaSource(uri, null, null);

    exoPlayer.prepare(mediaSource);
</code>```

I don't want replace "?" with any character.
How can I play?
Anybody help?
Thanks

答:
you might also want to use something like this if youre planning on playing both offline and online music: </p>

```<code> MediaSource mediaSource = new ExtractorMediaSource
.Factory(dataSourceFactory)
.createMediaSource(
    isOnlinePath(path) ? Uri.parse(path) : Uri.fromFile(new File(path))
    , null, null);

exoPlayer.prepare(mediaSource);

boolean isOnlinePath(String path) {
     return path != null &&
      (path.contains("http") ||
       path.contains(".m3u") ||
       path.contains(".pls"));
}
</code>```

Title: Exoplayer local path with Question Mark

Body:
I am developing music application. I have been using exoplayer to play music. I have lived a problem and couldn't find any solution. My problem is that ı have downloaded song file from internet. This song name contains "?" mark. I create path for this song file and use its name. After song downloaded successfully. I play with exoplayer. I create path for this song and set to exoplayer but it couldn't be played.

Song path = /storage/emulated/0/mymusic/downloads/How am I?_009.mp3

Uri uri = Uri.parse(path);

    MediaSource mediaSource = new ExtractorMediaSource.Factory(dataSourceFactory).createMediaSource(uri, null, null);

    exoPlayer.prepare(mediaSource);

I don't want replace "?" with any character.
How can I play?
Anybody help?
Thanks

Body:
you might also want to use something like this if youre planning on playing both offline and online music:

 MediaSource mediaSource = new ExtractorMediaSource
.Factory(dataSourceFactory)
.createMediaSource(
    isOnlinePath(path) ? Uri.parse(path) : Uri.fromFile(new File(path))
    , null, null);

exoPlayer.prepare(mediaSource);

boolean isOnlinePath(String path) {
     return path != null &&
      (path.contains("http") ||
       path.contains(".m3u") ||
       path.contains(".pls"));
}


问:
delayed_job. Delete job from queue
```<code>class Radar
 include Mongoid::Document
 after_save :post_on_facebook

 private

 def post_on_facebook
  if self.user.settings.post_facebook
    Delayed::Job.enqueue(::FacebookJob.new(self.user,self.body,url,self.title),0,self.active_from)
  end
 end

end

class FacebookJob < Struct.new(:user,:body,:url,:title)
  include SocialPluginsHelper

  def perform
    facebook_client(user).publish_feed('', :message => body, :link => url, :name => title)
  end
end
</code>```

I want execute post_on_facebook method at specific date. I store this date at "active_from" field.

Code above is working and job is executed at correct date.

But in some cases I first create Radar object and send some job to Delayed Job queue. After that I update this object and send another job to Delayed Job.

This is wrong behavior because I wan't execute job only once at correct time. In this implementation I will have 2 jobs which will be executed. How I can delete previous job so only updated one will be executed ?

```<code>Rails 3.0.7
Delayed Job => 2.1.4 https://github.com/collectiveidea/delayed_job
</code>```

ps: sorry for my english I try do my best

答:
did you try storing the id from the delayed job and then store it for possible deletion:
e.g</p>

```<code>job_id = Delayed::Job.enqueue(::FacebookJob.new(self.user,self.body,url,self.title),0,self.active_from)
job = Delayed::Job.find(job_id)
job.delete
</code>```

Title: delayed_job. Delete job from queue

Body:
class Radar
 include Mongoid::Document
 after_save :post_on_facebook

 private

 def post_on_facebook
  if self.user.settings.post_facebook
    Delayed::Job.enqueue(::FacebookJob.new(self.user,self.body,url,self.title),0,self.active_from)
  end
 end

end

class FacebookJob < Struct.new(:user,:body,:url,:title)
  include SocialPluginsHelper

  def perform
    facebook_client(user).publish_feed('', :message => body, :link => url, :name => title)
  end
end

I want execute post_on_facebook method at specific date. I store this date at "active_from" field.

Code above is working and job is executed at correct date.

But in some cases I first create Radar object and send some job to Delayed Job queue. After that I update this object and send another job to Delayed Job.

This is wrong behavior because I wan't execute job only once at correct time. In this implementation I will have 2 jobs which will be executed. How I can delete previous job so only updated one will be executed ?

Rails 3.0.7
Delayed Job => 2.1.4 https://github.com/collectiveidea/delayed_job

ps: sorry for my english I try do my best

Body:
did you try storing the id from the delayed job and then store it for possible deletion:
e.g

job_id = Delayed::Job.enqueue(::FacebookJob.new(self.user,self.body,url,self.title),0,self.active_from)
job = Delayed::Job.find(job_id)
job.delete


问:
How to recieve messages for offline clients using QoS MQTT in eclipse-mosquitto?
My mosquitto.conf is (This is the entire conf file since everything else is just commented out)

```<code>log_dest file /mosquitto/log/mosquitto.log
log_type all
connection_messages true
log_timestamp true
log_timestamp_format [%H:%M:%S]
persistence true
persistence_location /mosquitto/data/
listener 1883
listener 9001
protocol websockets
</code>```

Then i run

docker exec -it  ecs-Eclipse_mosquitto_MQTT-11-Eclipse-mosquitto-MQTT-eafxxxxxxx mosquitto_pub -t presence -m hellothere -q qos=2

(NOTE I dont have any active subscribers yet online)

Navigated to /mosquitto/data and there was indeed a file called mosquitto.db

So i could deduce that my message hellothere is stored in mosquitto.db

Then i ran the command

docker exec -it  ecs-Eclipse_mosquitto_MQTT-11-Eclipse-mosquitto-MQTT-eafxxxxxxx mosquitto_sub -t presence -q qos=2

What i expect

For the MQTT broker to send the stored message since subscriber is now online

What actually happens

indefinite waiting for the message

Maybe i am missing something ?

答:
I think the relevant bit of the mqtt spec is:

When a Server takes ownership of an incoming Application Message it
  MUST add it to the Session state of those clients that have matching
  Subscriptions.

In your case when the message is published there are no clients with matching subscriptions (because you have not run mosquitto_sub at that point) so it does nothing further.

If you want messages to be stored for a client you must first connect, as that client, and subscribe to the relevant topic (with QOS>0 and CleanSession=0). After doing that any messages received whilst the client is offline will be stored and delivered when it reconnects (as long as CleanSession=0).

Note: To do the above with mosquitto_sub you will need to use the --id parameter to set the client id (messages will only be queued for the specific clients that have subscribed to the relevant topics). You will also need the -c flag to disable the 'clean session' flag.

So the steps will be as follows (I have removed the extra docker bits - you can add these back in):

mosquitto_sub -c --id subscriber1 -t presence -q 2

This will subscribe and then wait for any messages; you can safely close it (it's the subscription bit that needs to happen). Next publish your messgae:

mosquitto_pub -t presence -m hellothere -q 2

Now you can start mosquitto_sub again to retrieve the stored messages:

mosquitto_sub -c --id subscriber1 -t presence -q 2

Warning: When you subscribe like this the broker will store any messages received whilst you are offline. This can become an issue if you are testing a broker that processes a lot of messages (because storing all of the messages takes space). Probably not an issue here as you are only testing but something to bear in mind... Running mosquitto_sub without the -c will clear any subscriptions - there are also options in the mosquitto config that allow you to limit the number of messages held and how long they are held.

Body:
My mosquitto.conf is (This is the entire conf file since everything else is just commented out)

log_dest file /mosquitto/log/mosquitto.log
log_type all
connection_messages true
log_timestamp true
log_timestamp_format [%H:%M:%S]
persistence true
persistence_location /mosquitto/data/
listener 1883
listener 9001
protocol websockets

Then i run

docker exec -it  ecs-Eclipse_mosquitto_MQTT-11-Eclipse-mosquitto-MQTT-eafxxxxxxx mosquitto_pub -t presence -m hellothere -q qos=2

(NOTE I dont have any active subscribers yet online)

Navigated to /mosquitto/data and there was indeed a file called mosquitto.db

So i could deduce that my message hellothere is stored in mosquitto.db

Then i ran the command

docker exec -it  ecs-Eclipse_mosquitto_MQTT-11-Eclipse-mosquitto-MQTT-eafxxxxxxx mosquitto_sub -t presence -q qos=2

What i expect

For the MQTT broker to send the stored message since subscriber is now online

What actually happens

indefinite waiting for the message

Maybe i am missing something ?


答:
MQTT doesn't work that way.

Messages are only queued for clients that have previously been connected, it is a pub/sub system not a message queuing system.

A client needs to have been connected in the past and subscribed to the topic the message in question. It then needs to reconnect after the message has been published with the cleanSession flag set to false and using the same client id.

You can read more about this on the HiveMQ blog here

Title: How to recieve messages for offline clients using QoS MQTT in eclipse-mosquitto?


问:
Upload folder path for AWS Elastic Beanstalk
I have a Python Flask app that seems to be otherwise working on the AWS Elastic Beanstalk platform. The one thing I can't figure out is where to save files that my web app allows users to upload. When run locally, I simply provide a path where the files are to be saved but once deployed to AWS EB, I am confused what I should change this path to. I assume I am missing something in this process and if someone could provide some guidance, I would greatly appreciate it.</p>

答: Try using Amazon S3 to store files with your Flask Application. Explore Flask Boto3 Module. This module can be interface between your Flask Application and File Storage Service at Amazon.


问:
conda.exe: error while loading shared libraries: libz.so.1
Unable to install Anaconda3-2019.10-Linux-x86_64 in my RHEL machine; Getting the error -> conda.exe: error while loading shared libraries: libz.so.1: failed to map segment from shared object: Operation not permitted.

Anaconda or Miniconda version:  Anaconda3-2019.10-Linux-x86_64
Operating System:"Red Hat Enterprise Linux Server" VERSION="7.7 (Maipo)"

Steps to Reproduce

wget https://repo.anaconda.com/archive/Anaconda3-2019.10-Linux-x86_64.sh
bash ./Anaconda3-2019.10-Linux-x86_64.sh

I've followed the resolution steps mentioned in Github #11493, and #11154 by @davidlowryduda, @Pastthesun, but that doesn't fix my issue.  Have posted the issue in Github as #11587.

I tried with older version of Anaconda --> Anaconda3-2019.07-Linux-x86_64 and Anaconda3-2019.03-Linux-x86_64. Anaconda3-2019.07-Linux-x86_64 did not give the same issue related to libz.so.1, but gave another error. But I had a smooth installation with Anaconda3-2019.03-Linux-x86_64.

答:
I faced similar issue in Debian 10 and fixed the issue by exporting a writeable path to TMP environment variable.

Reference:
https://github.com/ContinuumIO/anaconda-issues/issues/11154


问:
How to split the number in js
I have only one number like "100000"

I wan't to  split this number same as [20000,20000,20000,20000,20000] in array

so if number is 138000 then it should be like [20000,20000,20000,20000,20000,20000,18000]

How to do this?

答:
let num = 118000,
  num_array = [];

while (num > 0) {
  if (num >= 20000) {
    num_array.push(20000);
    num -= 20000;
  } else {
    num_array.push(num);
    break;
  }
}

console.log(num_array);```

I think this is what you want, please post what you tried, so that it helps to understand where you failed.

Title: How to split the number in js

Body:
let num = 118000,
  num_array = [];

while (num > 0) {
  if (num >= 20000) {
    num_array.push(20000);
    num -= 20000;
  } else {
    num_array.push(num);
    break;
  }
}

console.log(num_array);

I think this is what you want, please post what you tried, so that it helps to understand where you failed.


问:
HIve: Data format changing while converting from ORC to TEXT
I have a hive table with the following schema:

```<code>CREATE EXTERNAL TABLE db_test.user_arry(
  cstid string,
  prdctsslctd array<string>,
  indvprc array<bigint>,
  dscntamt array<bigint>,
  prdctsrjctd array<string>)
ROW FORMAT DELIMITED
  FIELDS TERMINATED BY ','
  LINES TERMINATED BY '\n'
STORED AS INPUTFORMAT
  'org.apache.hadoop.mapred.TextInputFormat'
OUTPUTFORMAT
  'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'
LOCATION
   '/location/on/a/hadoop/'
</code>```

Data present in it, is in below format:

```<code>--------------------------------------------------------
 name | prdctsslctd | indvprc | dscntamt | prdctsrjctd
--------------------------------------------------------
 cctg65  ["m_jns","cbyht"]        ["23","6"]       ["1","1"] ["shs","jkt"]
 jju89o0 ["top","jeans_wmn"]      ["55","45"]      [NULL]         [NULL]
 ju34hd  ["laychps","candy","toy"]["3","5","67"]["12","8"]["candy"]
</code>```

Trying to pull this data into a table having the data type as string for all the columns

```<code>CREATE EXTERNAL TABLE db_test.user_strng(
  cstid string,
  prdctsslctd string,
  indvprc string,
  dscntamt string,
  prdctsrjctd string)
ROW FORMAT DELIMITED
 FIELDS TERMINATED BY ','
 LINES TERMINATED BY '\n'
STORED AS textfile
LOCATION
 '/location/on/a/hadoop/';
</code>```

Using:

```<code>insert into db_test.user_strng select * from db_test.user_arry;
</code>```

Actual O/P:

```<code>--------------------------------------------------------
 name | prdctsslctd | indvprc | dscntamt | prdctsrjctd
--------------------------------------------------------
 cctg65  m_jnscbyht        236       11     shsjkt
 jju89o0 topjeans_wmn      5545      NULL   NULL
 ju34hd  laychpscandytoy   3567      128    candy
</code>```

Expected O/P:

```<code>--------------------------------------------------------
 name | prdctsslctd | indvprc | dscntamt | prdctsrjctd
--------------------------------------------------------
 cctg65  "m_jns","cbyht"          "23","6"         "1","1"   "shs","jkt"
 jju89o0 "top","jeans_wmn"        "55","45"         NULL           NULL
 ju34hd  "laychps","candy","toy"  "3","5","67"     "12","8"  "candy"
</code>```

Not getting where the things are going wrong Or, missing out on something?

```<code>Update_1
</code>```

O/P from the table after performing the conversion array to array:

```<code>ALTER TABLE user_arry CHANGE indvprc indvprc array<string>;
ALTER TABLE user_arry CHANGE dscntamt dscntamt array<string>;

--------------------------------------------------------
 name | prdctsslctd | indvprc | dscntamt | prdctsrjctd
--------------------------------------------------------
 cctg65  ["m_jns","cbyht"]        ["23","6"]       ["1","1"] ["shs","jkt"]
 jju89o0 ["top","jeans_wmn"]      ["55","45"]      []         []
 ju34hd  ["laychps","candy","toy"]["3","5","67"]["12","8"]["candy"]
</code>```

Final O/P from the table where all datatypes are string:

```<code>--------------------------------------------------------
 name | prdctsslctd | indvprc | dscntamt | prdctsrjctd
--------------------------------------------------------
 cctg65  m_jns    cbyht      23   6    1      1      shs  jkt
 jju89o0 top      jeans_wmn  55   45
 ju34hd  laychps  candy      toy  3    5      67     12    8    candy
</code>```

Still not getting the desired o/p.

```<code>Update_2
</code>```

As suggested, did the change for FIELDS TERMINATED BY ',' to FIELDS TERMINATED BY '\t' . Getting the data in desired format.

答:
Change all arrays type to array <string>:

```<code>alter table ALTER TABLE user_arry CHANGE indvprc indvprc array<string>;
alter table ALTER TABLE user_arry CHANGE dscntamt dscntamt array<string>;
</code>```

And according to your data example, array<bigint> is not proper format for values like "23.45".  array<string> should work fine for your data file.

Use concat_ws to convert arrays to comma-delimited strings:

```<code>insert into db_test.user_strng
select  name,
        concat_ws(',',prdctsslctd)  as prdctsslctd,
        concat_ws(',',indvprc)      as indvprc,
        concat_ws(',',dscntamt)     as dscntamt,
        concat_ws(',',prdctsrjctd) as prdctsrjctd
  from db_test.user_arry;
</code>```

Body:
I have a hive table with the following schema:

CREATE EXTERNAL TABLE db_test.user_arry(
  cstid string,
  prdctsslctd array<string>,
  indvprc array<bigint>,
  dscntamt array<bigint>,
  prdctsrjctd array<string>)
ROW FORMAT DELIMITED
  FIELDS TERMINATED BY ','
  LINES TERMINATED BY '\n'
STORED AS INPUTFORMAT
  'org.apache.hadoop.mapred.TextInputFormat'
OUTPUTFORMAT
  'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'
LOCATION
   '/location/on/a/hadoop/'

Data present in it, is in below format:

--------------------------------------------------------
 name | prdctsslctd | indvprc | dscntamt | prdctsrjctd
--------------------------------------------------------
 cctg65  ["m_jns","cbyht"]        ["23","6"]       ["1","1"] ["shs","jkt"]
 jju89o0 ["top","jeans_wmn"]      ["55","45"]      [NULL]         [NULL]
 ju34hd  ["laychps","candy","toy"]["3","5","67"]["12","8"]["candy"]

Trying to pull this data into a table having the data type as string for all the columns

CREATE EXTERNAL TABLE db_test.user_strng(
  cstid string,
  prdctsslctd string,
  indvprc string,
  dscntamt string,
  prdctsrjctd string)
ROW FORMAT DELIMITED
 FIELDS TERMINATED BY ','
 LINES TERMINATED BY '\n'
STORED AS textfile
LOCATION
 '/location/on/a/hadoop/';

Using:

insert into db_test.user_strng select * from db_test.user_arry;

Actual O/P:

--------------------------------------------------------
 name | prdctsslctd | indvprc | dscntamt | prdctsrjctd
--------------------------------------------------------
 cctg65  m_jnscbyht        236       11     shsjkt
 jju89o0 topjeans_wmn      5545      NULL   NULL
 ju34hd  laychpscandytoy   3567      128    candy

Expected O/P:

--------------------------------------------------------
 name | prdctsslctd | indvprc | dscntamt | prdctsrjctd
--------------------------------------------------------
 cctg65  "m_jns","cbyht"          "23","6"         "1","1"   "shs","jkt"
 jju89o0 "top","jeans_wmn"        "55","45"         NULL           NULL
 ju34hd  "laychps","candy","toy"  "3","5","67"     "12","8"  "candy"

Not getting where the things are going wrong Or, missing out on something?

Update_1

O/P from the table after performing the conversion array to array:

ALTER TABLE user_arry CHANGE indvprc indvprc array<string>;
ALTER TABLE user_arry CHANGE dscntamt dscntamt array<string>;

--------------------------------------------------------
 name | prdctsslctd | indvprc | dscntamt | prdctsrjctd
--------------------------------------------------------
 cctg65  ["m_jns","cbyht"]        ["23","6"]       ["1","1"] ["shs","jkt"]
 jju89o0 ["top","jeans_wmn"]      ["55","45"]      []         []
 ju34hd  ["laychps","candy","toy"]["3","5","67"]["12","8"]["candy"]

Final O/P from the table where all datatypes are string:

--------------------------------------------------------
 name | prdctsslctd | indvprc | dscntamt | prdctsrjctd
--------------------------------------------------------
 cctg65  m_jns    cbyht      23   6    1      1      shs  jkt
 jju89o0 top      jeans_wmn  55   45
 ju34hd  laychps  candy      toy  3    5      67     12    8    candy

Still not getting the desired o/p.

Update_2

As suggested, did the change for FIELDS TERMINATED BY ',' to FIELDS TERMINATED BY '\t' . Getting the data in desired format.

Body:
Change all arrays type to array <string>:

alter table ALTER TABLE user_arry CHANGE indvprc indvprc array<string>;
alter table ALTER TABLE user_arry CHANGE dscntamt dscntamt array<string>;

And according to your data example, array<bigint> is not proper format for values like "23.45".  array<string> should work fine for your data file.

Use concat_ws to convert arrays to comma-delimited strings:

insert into db_test.user_strng
select  name,
        concat_ws(',',prdctsslctd)  as prdctsslctd,
        concat_ws(',',indvprc)      as indvprc,
        concat_ws(',',dscntamt)     as dscntamt,
        concat_ws(',',prdctsrjctd) as prdctsrjctd
  from db_test.user_arry;


问:
How can I change the vector of a ball in breakout game made using Java?
I'm using Java to make a breakout game. The independent parts are functioning: the paddle, the ball, the bricks.

However, the ball hits a wall and then instead of changing it's vector, the ball just travels up the x-axis in a straight line at the edge of the JFrame window until it hits the top of the window and bounces back down from this corner.

The ball then gets stuck in an infinite back and forth line from the top left corner until it touches the paddle (back and forth) and will never break any of the other bricks.

How can I change my code to fix this problem?

```<code>    import java.awt.Graphics;

    public class Ball extends Sprite {

    private int xVelocity = 1, yVelocity = -1;

    // Constructor
    public Ball() {
        setWidth(Settings.BALL_WIDTH);
        setHeight(Settings.BALL_HEIGHT);
        resetPosition();

    public void resetPosition() {
        setX(Settings.INITIAL_BALL_X);
        setY(Settings.INITIAL_BALL_Y);
    }

    public void update() {
        x += yVelocity;
        y += yVelocity;

        // Bounce off left side of screen
        if(x <= 0) {
            x = 0;
            setXVelocity(-1);

        }

        // Bounce off right side of screen
        if(x >= Settings.WINDOW_WIDTH - Settings.BALL_WIDTH) {
            x =Settings.WINDOW_WIDTH;
            setXVelocity(-1);
        }

        // Bounce off top of screen
        if(y <= 0) {
            y = 0;
            setYVelocity(1);
        }

    }

    public void setXVelocity(int x) {
        xVelocity = x;
    }
    public void setYVelocity(int y) {
        yVelocity = y;
    }

    public int getXVelocity() {
        return xVelocity;
    }
    public int getYVelocity() {
        return yVelocity;
    }

    public void paint(Graphics g) {
        g.fillOval(x, y, Settings.BALL_WIDTH, Settings.BALL_HEIGHT);
    }
}

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Paint;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JPanel;
import javax.swing.Timer;

public class BreakoutPanel extends JPanel implements ActionListener, KeyListener {

    static final long serialVersionUID = 2L;

    private boolean gameRunning = true;
    private int livesLeft = 3;
    private String screenMessage = "";
    private Ball ball;
    private Paddle paddle;
    private Brick bricks[];

    public BreakoutPanel(Breakout game) {

        addKeyListener(this);
        setFocusable(true);

        Timer timer = new Timer(5, this);
        timer.start();

        ball = new Ball();
        paddle = new Paddle();
        bricks = new Brick[Settings.TOTAL_BRICKS];
        createBricks();

    }

    private void createBricks() {
        int counter = 0;
        int x_space = 0;
        int y_space = 0;
        for(int x = 0; x < 4; x++) {
            for(int y = 0; y < 5; y++) {
                bricks[counter] = new Brick((x * Settings.BRICK_WIDTH) + Settings.BRICK_HORI_PADDING + x_space, (y * Settings.BRICK_HEIGHT) + Settings.BRICK_VERT_PADDING + y_space);
                counter++;
                y_space++;
            }
            x_space++;
            y_space = 0;
        }
    }

    private void paintBricks(Graphics g) {
        for(int x = 0; x < Settings.TOTAL_BRICKS; x++) {
            for(int y = 0; y < Settings.TOTAL_BRICKS; y++) {
                bricks[y].paint(g);
            }
        }
    }

    private void update() {
        if(gameRunning) {
            // TODO: Update the ball and paddle
            ball.update();
            paddle.update();
            collisions();
            repaint();
        }
    }

    private void gameOver() {
        stopGame();
        screenMessage = "Game Over!";
    }

    private void gameWon() {
        stopGame();
        screenMessage = "Congratulations! You have won!";
    }

    private void stopGame() {
        gameRunning = false;
    }

    private void collisions() {
        // Check for loss
        if(ball.y > 450) {
            // Game over
            livesLeft--;
            if(livesLeft <= 0) {
                gameOver();
                return;
            } else {
                ball.resetPosition();
                ball.setYVelocity(-1);
            }
        }

        // Check for win
        boolean bricksLeft = false;
        for(int i = 0; i < bricks.length; i++) {
            // Check if there are any bricks left
            if(!bricks[i].isBroken()) {
                // Brick was found, close loop
                bricksLeft = true;
                break;
            }
        }
        if(!bricksLeft) {
            gameWon();
            return;
        }

        // Check collisions
        if(ball.getRectangle().intersects(paddle.getRectangle())) {
            // Simplified touching of paddle
            ball.setYVelocity(-1);

        }

        for(int i = 0; i < bricks.length; i++) {
            if (ball.getRectangle().intersects(bricks[i].getRectangle())) {
                int ballLeft = (int) ball.getRectangle().getMinX();
                int ballHeight = (int) ball.getRectangle().getHeight();
                int ballWidth = (int) ball.getRectangle().getWidth();
                int ballTop = (int) ball.getRectangle().getMinY();

                Point pointRight = new Point(ballLeft + ballWidth + 1, ballTop);
                Point pointLeft = new Point(ballLeft - 1, ballTop);
                Point pointTop = new Point(ballLeft, ballTop - 1);
                Point pointBottom = new Point(ballLeft, ballTop + ballHeight + 1);

                if (!bricks[i].isBroken()) {
                    if (bricks[i].getRectangle().contains(pointRight)) {
                        ball.setXVelocity(-1);
                    } else if (bricks[i].getRectangle().contains(pointLeft)) {
                        ball.setXVelocity(1);
                    }

                    if (bricks[i].getRectangle().contains(pointTop)) {
                        ball.setYVelocity(1);
                    } else if (bricks[i].getRectangle().contains(pointBottom)) {
                        ball.setYVelocity(-1);
                    }
                    bricks[i].setBroken(true);
                }
            }
        }
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        ball.paint(g);
        paddle.paint(g);
        paintBricks(g);

        // Draw lives left
        // TODO: Draw lives left in the top left hand corner**
        if(livesLeft != 0) {
            String displayLives = Integer.toString(livesLeft);
            g.setFont(new Font("Arial", Font.BOLD, 18));
            g.drawString(displayLives, Settings.LIVES_POSITION_X, Settings.LIVES_POSITION_Y);
        }

        // Draw screen message*
        if(screenMessage != null) {
            g.setFont(new Font("Arial", Font.BOLD, 18));
            int messageWidth = g.getFontMetrics().stringWidth(screenMessage);
            g.drawString(screenMessage, (Settings.WINDOW_WIDTH / 2) - (messageWidth / 2),
     Settings.MESSAGE_POSITION);
        }
    }

    @Override
    public void keyPressed(KeyEvent e) {
        int key = e.getKeyCode();
        if (key == KeyEvent.VK_LEFT) {
            paddle.setXVelocity(-1);
        }
        if (key == KeyEvent.VK_RIGHT) {
        paddle.setXVelocity(1);
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_RIGHT) {
            paddle.setXVelocity(0);
        }
    }

    @Override
    public void keyTyped(KeyEvent arg0) {

    }

    @Override
    public void actionPerformed(ActionEvent arg0) {
        update();
    }

}
</code>```

答:
I made a similar game in python years ago. What I did to solve this problem was allow the player to control the direction of the ball by hitting it with different parts of the paddle.

If the player hit the ball with the absolute center of the paddle, then I would just reverse the vector as if it had hit off a wall. But if the absolute edge of the paddle hit the ball, then I would increase the x velocity in the same direction of the edge that it hit. You can make the effect continuous, so if the the ball hits the paddle halfway between the edge and the center, it increases the x velocity half as much as it would have if it had hit the absolute edge.

This way the vector will continuously change and the ball will bounce off of things in a more interesting way, as well as give the player more control so they don't have to just wait until the ball eventually hits every brick in a predefined pattern.

You can use a coefficient, or more complex function if you don't want the effect of where the ball hits the paddle to effect the x velocity in such a linear manner.

You can use a similar strategy for handling collisions with the bricks. For instance, if the ball hits the corner of a brick, you probably don't want it to react as if it had hit the bottom, or the side, but have a reaction that is somewhere in between.

Body:
I'm using Java to make a breakout game. The independent parts are functioning: the paddle, the ball, the bricks.

However, the ball hits a wall and then instead of changing it's vector, the ball just travels up the x-axis in a straight line at the edge of the JFrame window until it hits the top of the window and bounces back down from this corner.

The ball then gets stuck in an infinite back and forth line from the top left corner until it touches the paddle (back and forth) and will never break any of the other bricks.

How can I change my code to fix this problem?

    import java.awt.Graphics;

    public class Ball extends Sprite {

    private int xVelocity = 1, yVelocity = -1;

    // Constructor
    public Ball() {
        setWidth(Settings.BALL_WIDTH);
        setHeight(Settings.BALL_HEIGHT);
        resetPosition();

    public void resetPosition() {
        setX(Settings.INITIAL_BALL_X);
        setY(Settings.INITIAL_BALL_Y);
    }

    public void update() {
        x += yVelocity;
        y += yVelocity;

        // Bounce off left side of screen
        if(x <= 0) {
            x = 0;
            setXVelocity(-1);

        }

        // Bounce off right side of screen
        if(x >= Settings.WINDOW_WIDTH - Settings.BALL_WIDTH) {
            x =Settings.WINDOW_WIDTH;
            setXVelocity(-1);
        }

        // Bounce off top of screen
        if(y <= 0) {
            y = 0;
            setYVelocity(1);
        }

    }

    public void setXVelocity(int x) {
        xVelocity = x;
    }
    public void setYVelocity(int y) {
        yVelocity = y;
    }

    public int getXVelocity() {
        return xVelocity;
    }
    public int getYVelocity() {
        return yVelocity;
    }

    public void paint(Graphics g) {
        g.fillOval(x, y, Settings.BALL_WIDTH, Settings.BALL_HEIGHT);
    }
}

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Paint;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JPanel;
import javax.swing.Timer;

public class BreakoutPanel extends JPanel implements ActionListener, KeyListener {

    static final long serialVersionUID = 2L;

    private boolean gameRunning = true;
    private int livesLeft = 3;
    private String screenMessage = "";
    private Ball ball;
    private Paddle paddle;
    private Brick bricks[];

    public BreakoutPanel(Breakout game) {

        addKeyListener(this);
        setFocusable(true);

        Timer timer = new Timer(5, this);
        timer.start();

        ball = new Ball();
        paddle = new Paddle();
        bricks = new Brick[Settings.TOTAL_BRICKS];
        createBricks();

    }

    private void createBricks() {
        int counter = 0;
        int x_space = 0;
        int y_space = 0;
        for(int x = 0; x < 4; x++) {
            for(int y = 0; y < 5; y++) {
                bricks[counter] = new Brick((x * Settings.BRICK_WIDTH) + Settings.BRICK_HORI_PADDING + x_space, (y * Settings.BRICK_HEIGHT) + Settings.BRICK_VERT_PADDING + y_space);
                counter++;
                y_space++;
            }
            x_space++;
            y_space = 0;
        }
    }

    private void paintBricks(Graphics g) {
        for(int x = 0; x < Settings.TOTAL_BRICKS; x++) {
            for(int y = 0; y < Settings.TOTAL_BRICKS; y++) {
                bricks[y].paint(g);
            }
        }
    }

    private void update() {
        if(gameRunning) {
            // TODO: Update the ball and paddle
            ball.update();
            paddle.update();
            collisions();
            repaint();
        }
    }

    private void gameOver() {
        stopGame();
        screenMessage = "Game Over!";
    }

    private void gameWon() {
        stopGame();
        screenMessage = "Congratulations! You have won!";
    }

    private void stopGame() {
        gameRunning = false;
    }

    private void collisions() {
        // Check for loss
        if(ball.y > 450) {
            // Game over
            livesLeft--;
            if(livesLeft <= 0) {
                gameOver();
                return;
            } else {
                ball.resetPosition();
                ball.setYVelocity(-1);
            }
        }

        // Check for win
        boolean bricksLeft = false;
        for(int i = 0; i < bricks.length; i++) {
            // Check if there are any bricks left
            if(!bricks[i].isBroken()) {
                // Brick was found, close loop
                bricksLeft = true;
                break;
            }
        }
        if(!bricksLeft) {
            gameWon();
            return;
        }

        // Check collisions
        if(ball.getRectangle().intersects(paddle.getRectangle())) {
            // Simplified touching of paddle
            ball.setYVelocity(-1);

        }

        for(int i = 0; i < bricks.length; i++) {
            if (ball.getRectangle().intersects(bricks[i].getRectangle())) {
                int ballLeft = (int) ball.getRectangle().getMinX();
                int ballHeight = (int) ball.getRectangle().getHeight();
                int ballWidth = (int) ball.getRectangle().getWidth();
                int ballTop = (int) ball.getRectangle().getMinY();

                Point pointRight = new Point(ballLeft + ballWidth + 1, ballTop);
                Point pointLeft = new Point(ballLeft - 1, ballTop);
                Point pointTop = new Point(ballLeft, ballTop - 1);
                Point pointBottom = new Point(ballLeft, ballTop + ballHeight + 1);

                if (!bricks[i].isBroken()) {
                    if (bricks[i].getRectangle().contains(pointRight)) {
                        ball.setXVelocity(-1);
                    } else if (bricks[i].getRectangle().contains(pointLeft)) {
                        ball.setXVelocity(1);
                    }

                    if (bricks[i].getRectangle().contains(pointTop)) {
                        ball.setYVelocity(1);
                    } else if (bricks[i].getRectangle().contains(pointBottom)) {
                        ball.setYVelocity(-1);
                    }
                    bricks[i].setBroken(true);
                }
            }
        }
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        ball.paint(g);
        paddle.paint(g);
        paintBricks(g);

        // Draw lives left
        // TODO: Draw lives left in the top left hand corner**
        if(livesLeft != 0) {
            String displayLives = Integer.toString(livesLeft);
            g.setFont(new Font("Arial", Font.BOLD, 18));
            g.drawString(displayLives, Settings.LIVES_POSITION_X, Settings.LIVES_POSITION_Y);
        }

        // Draw screen message*
        if(screenMessage != null) {
            g.setFont(new Font("Arial", Font.BOLD, 18));
            int messageWidth = g.getFontMetrics().stringWidth(screenMessage);
            g.drawString(screenMessage, (Settings.WINDOW_WIDTH / 2) - (messageWidth / 2),
     Settings.MESSAGE_POSITION);
        }
    }

    @Override
    public void keyPressed(KeyEvent e) {
        int key = e.getKeyCode();
        if (key == KeyEvent.VK_LEFT) {
            paddle.setXVelocity(-1);
        }
        if (key == KeyEvent.VK_RIGHT) {
        paddle.setXVelocity(1);
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_RIGHT) {
            paddle.setXVelocity(0);
        }
    }

    @Override
    public void keyTyped(KeyEvent arg0) {

    }

    @Override
    public void actionPerformed(ActionEvent arg0) {
        update();
    }

}


问:
Why does Eclipse JFace's Window class create a resize listener only to then immediately remove it?
org.eclipse.jface.window.Window's create method calls createShell which during it's run creates a resizeListener, which sets a protected flag for any resize that may have occurred, which can then be used by subclasses to handle appropriately upon closure and such. However, then it calls initalizeBounds, which removes this very same listener.

I'm a bit confused as to why. I tried googling this, but I couldn't find anything even acknowledging this. Am I missing something?

答:
It looks like this flag is just intended for the Window class itself to handle a resize event happening before initializeBounds is called.

The flag was made protected to deal with a problem in ApplicationWindow (see bug 289181) where a resize event during Shell.setMenu was causing problems.


问:
powershell command to eject the device connected through usb does not work first time
I have a java application which interacts with a device connected through USB drive. I want to eject the device after processing. The below command works, but I have to try in a loop to make sure its ejected.

powershell.exe ((New-Object -comObject Shell.Application).NameSpace(17).ParseName('E:\').InvokeVerb('Eject'))

Not sure if any issue with the command. Sometimes it works after 3 or 4 times.

Can anyone help?

Added the screen shot here:
enter image description here

答:
I cannot reproduce the error, but it seems, that the type of the drive object changes from "USB Drive" to "Removable drive", when invoking the Eject verb.

You might want to add a short script to your routine. Something like:

$obj = (New-Object -comObject Shell.Application).namespace(17).ParseName('E:\')
$Type = $obj.Type
while ($Type-eq 'USB Drive'){
    $obj.InvokeVerb('Eject')
    $Type= $obj.Type
}

```

<p>Then you don't have to run the code several times and wait for PowerShell to spin up.</p>

<p>Here it is as a one-liner:</p>

<pre class="lang-bsh prettyprint-override"><code>powershell.exe -Command {$obj = (New-Object -comObject Shell.Application).namespace(17).ParseName('E:\');$Type = $obj.Type;while ($Type-eq 'USB Drive'){Write-Host 'Removing drive';$obj.InvokeVerb('Eject');$Type= $obj.Type}}
</code>```

If you want to run the command in cmd and not in PowerShell, you need to format it like this:

```<code>powershell.exe -Command $obj = (New-Object -comObject Shell.Application).namespace(17).ParseName('E:\');$Type = $obj.Type;while ($Type-eq 'USB Drive'){Write-Host 'Removing drive';$obj.InvokeVerb('Eject');$Type= $obj.Type}
</code>```

Body:
I cannot reproduce the error, but it seems, that the type of the drive object changes from "USB Drive" to "Removable drive", when invoking the Eject verb.

You might want to add a short script to your routine. Something like:

$obj = (New-Object -comObject Shell.Application).namespace(17).ParseName('E:\')
$Type = $obj.Type
while ($Type-eq 'USB Drive'){
    $obj.InvokeVerb('Eject')
    $Type= $obj.Type
}

Then you don't have to run the code several times and wait for PowerShell to spin up.

Here it is as a one-liner:

powershell.exe -Command {$obj = (New-Object -comObject Shell.Application).namespace(17).ParseName('E:\');$Type = $obj.Type;while ($Type-eq 'USB Drive'){Write-Host 'Removing drive';$obj.InvokeVerb('Eject');$Type= $obj.Type}}

If you want to run the command in cmd and not in PowerShell, you need to format it like this:

powershell.exe -Command $obj = (New-Object -comObject Shell.Application).namespace(17).ParseName('E:\');$Type = $obj.Type;while ($Type-eq 'USB Drive'){Write-Host 'Removing drive';$obj.InvokeVerb('Eject');$Type= $obj.Type}


问:
SQL query to get the latest price from the data?
I have this data in my Oracle table:

In this table, I have multiple products with having product_id and price at a particular time.

I want to write a SQL query to get latest price of each product based on the TIME column (Oracle - Long Type).

But here is the problem, for our table price monitoring for the product starts at 23:00 previous date.

Output required: when I passed 2-Dec-2019 as parameter into the SQL query

How can I do this with a SQL query? Or do I need to write a stored procedure for it, based on if and else condition?

Thanks in advance.

答:
We can try using ROW_NUMBER for this requirement:

```<code>WITH cte AS (
    SELECT t.*, ROW_NUMBER() OVER (PARTITION BY product_id ORDER BY time DESC) rn
    FROM yourTable t
    WHERE system_date = date '2019-12-19'
)

SELECT local_date, system_date, currency, product_id, time, current_price
FROM cte
WHERE rn = 1;
</code>```

Body:
We can try using ROW_NUMBER for this requirement:

WITH cte AS (
    SELECT t.*, ROW_NUMBER() OVER (PARTITION BY product_id ORDER BY time DESC) rn
    FROM yourTable t
    WHERE system_date = date '2019-12-19'
)

SELECT local_date, system_date, currency, product_id, time, current_price
FROM cte
WHERE rn = 1;


问:
Binding Dictionary to WPF toolkit Chart
Here is my code for binding a dictionary item to a Chart control. I keep getting the following error:

"Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index"

Here is my Code:

```<code>foreach (DataRow drow in objD0s.Tables[0].Rows)// Adding values from a dataset to dictionary
     {

         string strvalue = Convert.ToString(drow["Chemical Name"]);
         string doublevalue = Convert.ToString(drow["Global Warming"]);
         Cdata.Add(Convert.ToString(strvalue), Convert.ToDouble(doublevalue));

     }
     ColumnSeries colSeries = ChartChemImpact.Series[0] as ColumnSeries;

         ((ColumnSeries)ChartChemImpact.Series[0]).DataContext = Cdata;
         colSeries.ItemsSource = myDataTable0.DefaultView;
         colSeries.IndependentValueBinding = new Binding("[Chemical Name]");
         colSeries.DependentValueBinding = new Binding("[Global Warming]");

  }
</code>```

XAM

```<code> chartingToolkit:Chart Name="ChartChemImpact" Title="Chart Title"   Width="384"            Height="280">
   <chartingToolkit:ColumnSeries DependentValuePath="Key"  IndependentValuePath="Value" ItemsSource="{Binding}" Name="colSeries" />
  </chartingToolkit:Chart>
</code>```

Please help :(

答:
Ok, I have found the mistake. There are binding and value paths in the xaml, but they are replaced in the code.

I would remove those lines, so here is the result:

```<code>foreach (DataRow drow in objD0s.Tables[0].Rows)// Adding values from a dataset to dictionary
{
     string strvalue = Convert.ToString(drow["Chemical Name"]);
     string doublevalue = Convert.ToString(drow["Global Warming"]);
     Cdata.Add(Convert.ToString(strvalue), Convert.ToDouble(doublevalue));
}

((ColumnSeries)ChartChemImpact.Series[0]).DataContext = Cdata;
//And that's the end of the function, no more code
}
</code>```

Title: Binding Dictionary to WPF toolkit Chart

Body:
Here is my code for binding a dictionary item to a Chart control. I keep getting the following error:

"Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index"

Here is my Code:

foreach (DataRow drow in objD0s.Tables[0].Rows)// Adding values from a dataset to dictionary
     {

         string strvalue = Convert.ToString(drow["Chemical Name"]);
         string doublevalue = Convert.ToString(drow["Global Warming"]);
         Cdata.Add(Convert.ToString(strvalue), Convert.ToDouble(doublevalue));

     }
     ColumnSeries colSeries = ChartChemImpact.Series[0] as ColumnSeries;

         ((ColumnSeries)ChartChemImpact.Series[0]).DataContext = Cdata;
         colSeries.ItemsSource = myDataTable0.DefaultView;
         colSeries.IndependentValueBinding = new Binding("[Chemical Name]");
         colSeries.DependentValueBinding = new Binding("[Global Warming]");

  }

XAM

 chartingToolkit:Chart Name="ChartChemImpact" Title="Chart Title"   Width="384"            Height="280">
   <chartingToolkit:ColumnSeries DependentValuePath="Key"  IndependentValuePath="Value" ItemsSource="{Binding}" Name="colSeries" />
  </chartingToolkit:Chart>

Please help :(

Body:
Ok, I have found the mistake. There are binding and value paths in the xaml, but they are replaced in the code.

I would remove those lines, so here is the result:

foreach (DataRow drow in objD0s.Tables[0].Rows)// Adding values from a dataset to dictionary
{
     string strvalue = Convert.ToString(drow["Chemical Name"]);
     string doublevalue = Convert.ToString(drow["Global Warming"]);
     Cdata.Add(Convert.ToString(strvalue), Convert.ToDouble(doublevalue));
}

((ColumnSeries)ChartChemImpact.Series[0]).DataContext = Cdata;
//And that's the end of the function, no more code
}


问:
RegionCode in YouTube API v3
I can't seem to find any information on the implications of using/not using regionCode in the YouTube v3 API, for example the search/list resource.

In the specific, if the regionCode is not specified in the call to the API, will all the videos matching the criteria be returned?
If a video is allowed only in certain regions, not specifying the regionCode in the search request, will the API return it? Or only the unrestricted videos will be returned?

Where can I find some clarification on the topic?

答:
If you do not specify the Region Code then the API automatically determines the region based on your location. So, for example, if I queried the API on my laptop in New Zealand, then the region code would be NZ.

The API outputs the region code. In JSON it is under the tag regionCode.

Title: RegionCode in YouTube API v3


问:
I have imported Maven Project from Github to eclipse, inpom.xml dependencies showing underlined in red
When I run project facing an error, in pom.xml file artifact id showing underlined in red</p>

```<code>java.lang.NoSuchMethodError: org.testng.remote.AbstractRemoteTestNG.addListener(Lorg/testng/ISuiteListener;)V
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:111)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
</code>```

答:
Update your project and then try -

Right click on project -> Click Maven -> update project

Body:
When I run project facing an error, in pom.xml file artifact id showing underlined in red

java.lang.NoSuchMethodError: org.testng.remote.AbstractRemoteTestNG.addListener(Lorg/testng/ISuiteListener;)V
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:111)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)


问:
Searching an agile method to create tests
I'm actually testing web service of a web. Working with unit testers like Nunit and Gallio.

Actually, i have a problem. I want to test a service where i have to fill a lot of data in the html, like a formulary. And the problem is that i'm doing that editing an xml manually to do the tests... its too labored and heavy, and because this, i'm searching an agile method to do that.

My boss told me to do a formulary where i can fill all the fields, like the html, and then, create a xml with that. Is more efficient than editing a base xml manually.

There is a tool that can help me?

Sorry about my bad english.

答:
Maybe test data builders could work for you? You could write classes so that You can write in Your tests

```<code>var xml = new WebServiceCallBuilder()
             .WithDefaultValues()              // this sets most common options
             .WithParamX("something")          // which You can then modify
             .WithParamY("something other")
             .WithParamZ("another thing")
             .Build();

var result = webService.Call(xml);
</code>```

You can also implement test data builder so that it enables things like

```<code>
var xyzBuilder = new WebServiceCallBuilder()
                 .WithDefaultValues()
                 .WithParamX("x")
                 .WithParamY("y")
                 .WithParamZ("z");
var xyzXml = xyzBuilder.Build();

// let's say now You want similar builder but with different Z param
// then You can do this to not copy/paste/modify code above
var xyzzzBuilder = new WebServiceCallBuilder(xyzBuilder)
                      .WithParamZ("zzz");
var xyzzzXml = xyzzzBuilder.Build();
</code>```

I would probably use it.

Body:
Maybe test data builders could work for you? You could write classes so that You can write in Your tests

var xml = new WebServiceCallBuilder()
             .WithDefaultValues()              // this sets most common options
             .WithParamX("something")          // which You can then modify
             .WithParamY("something other")
             .WithParamZ("another thing")
             .Build();

var result = webService.Call(xml);

You can also implement test data builder so that it enables things like

var xyzBuilder = new WebServiceCallBuilder()
                 .WithDefaultValues()
                 .WithParamX("x")
                 .WithParamY("y")
                 .WithParamZ("z");
var xyzXml = xyzBuilder.Build();

// let's say now You want similar builder but with different Z param
// then You can do this to not copy/paste/modify code above
var xyzzzBuilder = new WebServiceCallBuilder(xyzBuilder)
                      .WithParamZ("zzz");
var xyzzzXml = xyzzzBuilder.Build();

I would probably use it.


问:
Object.assign() creates wierd properties when assigns mongoose doc
```<code>MessageThread.findById(req.body._id)
      .populate({ path: "messages" })
      .exec((err, foundMessageThread) => {
        var filtered = foundMessageThread.messages.map(message=>{
          return Object.assign({}, message, {isRead: true});
        })
        console.log("filtered", filtered);

      });
</code>```

console.log shows:

```<code>{ '$__':
 InternalCache {
   strictMode: true,
   selected: {},
   shardval: undefined,
   saveError: undefined,
   validationError: undefined,
   adhocPaths: undefined,
   removing: undefined,
   inserting: undefined,
   version: undefined,
   getters: {},
   _id: 5a4c7f2d8b49fc260c396f55,
   populate: undefined,
   populated: undefined,
   wasPopulated: true,
   scope: undefined,
   activePaths: [Object],
   pathsToScopes: {},
   ownerDocument: undefined,
   fullPath: undefined,
   emitter: [Object],
   '$options': true },
isNew: false,
errors: undefined,
_doc:
 { sentAt: 2018-01-03T06:58:53.188Z,
   isRead: false,
   _id: 5a4c7f2d8b49fc260c396f55,
   sender: 5a4b77767251b44cd870219f,
   reciever: 5a4b780a7251b44cd87021a1,
   text: 'qwe',
   __v: 0 },
'$init': true,
isRead: true },
......
</code>```

it repeats many times.
I suppose it (InternalCache { strictMode: true...) relates to message that is taken from foundMessageThread. And it reveals its metadata(in my term) while assigning. Because:

```<code>MessageThread.findById(req.body._id)
  .populate({ path: "messages" })
  .exec((err, foundMessageThread) => {
    var filtered = foundMessageThread.messages.map(message=>{
      console.log("message", message)
      return Object.assign({}, message, {isRead: true});
    })
    console.log("filtered", filtered);

  });
</code>```

console.log shows

```<code>{ sentAt: 2018-01-03T06:58:53.188Z,
  isRead: false,
  _id: 5a4c7f2d8b49fc260c396f55,
  sender: 5a4b77767251b44cd870219f,
  reciever: 5a4b780a7251b44cd87021a1,
  text: 'qwe',
  __v: 0 },
....
</code>```

My question:

Is it normal behavior?

If it is how to fix it? Because "metadata" prevents objects being assigned.

P.S. I've tried:

```<code>MessageThread.findById(req.body._id)
  .populate({ path: "messages" })
  .exec((err, foundMessageThread) => {
    var filtered = foundMessageThread.messages.map(message=>{
      return **Object.assign({}, message._doc, {isRead: true})**;
    })
    console.log("filtered", filtered);

  });
</code>```

答:
You can also use .lean() method with mongoose request. This allows to get less cumbersome response and process it easyly:

```<code>try {
    const assets = await myModel.Assets
      .find({ isActive: true }, { __v: 0, _id: 0 })
      .lean()
      .exec()
    // do something
}
catch(error) {
  throw error
}
</code>```

Body:
MessageThread.findById(req.body._id)
      .populate({ path: "messages" })
      .exec((err, foundMessageThread) => {
        var filtered = foundMessageThread.messages.map(message=>{
          return Object.assign({}, message, {isRead: true});
        })
        console.log("filtered", filtered);

      });

console.log shows:

{ '$__':
 InternalCache {
   strictMode: true,
   selected: {},
   shardval: undefined,
   saveError: undefined,
   validationError: undefined,
   adhocPaths: undefined,
   removing: undefined,
   inserting: undefined,
   version: undefined,
   getters: {},
   _id: 5a4c7f2d8b49fc260c396f55,
   populate: undefined,
   populated: undefined,
   wasPopulated: true,
   scope: undefined,
   activePaths: [Object],
   pathsToScopes: {},
   ownerDocument: undefined,
   fullPath: undefined,
   emitter: [Object],
   '$options': true },
isNew: false,
errors: undefined,
_doc:
 { sentAt: 2018-01-03T06:58:53.188Z,
   isRead: false,
   _id: 5a4c7f2d8b49fc260c396f55,
   sender: 5a4b77767251b44cd870219f,
   reciever: 5a4b780a7251b44cd87021a1,
   text: 'qwe',
   __v: 0 },
'$init': true,
isRead: true },
......

it repeats many times.
I suppose it (InternalCache { strictMode: true...) relates to message that is taken from foundMessageThread. And it reveals its metadata(in my term) while assigning. Because:

MessageThread.findById(req.body._id)
  .populate({ path: "messages" })
  .exec((err, foundMessageThread) => {
    var filtered = foundMessageThread.messages.map(message=>{
      console.log("message", message)
      return Object.assign({}, message, {isRead: true});
    })
    console.log("filtered", filtered);

  });

console.log shows

{ sentAt: 2018-01-03T06:58:53.188Z,
  isRead: false,
  _id: 5a4c7f2d8b49fc260c396f55,
  sender: 5a4b77767251b44cd870219f,
  reciever: 5a4b780a7251b44cd87021a1,
  text: 'qwe',
  __v: 0 },
....

My question:

Is it normal behavior?

If it is how to fix it? Because "metadata" prevents objects being assigned.

P.S. I've tried:

MessageThread.findById(req.body._id)
  .populate({ path: "messages" })
  .exec((err, foundMessageThread) => {
    var filtered = foundMessageThread.messages.map(message=>{
      return **Object.assign({}, message._doc, {isRead: true})**;
    })
    console.log("filtered", filtered);

  });

Body:
You can also use .lean() method with mongoose request. This allows to get less cumbersome response and process it easyly:

try {
    const assets = await myModel.Assets
      .find({ isActive: true }, { __v: 0, _id: 0 })
      .lean()
      .exec()
    // do something
}
catch(error) {
  throw error
}


问:
How to merge 2 rows into 1 row pandas
I currently have a dataframe that looks like this for the 1st few indexes:

But however as i scrolled down to look at the other indexes, i realise that some tax_type data were split into Individual Income Tax and Corporate Income Tax:

What i wanted to do is to combine the rows that are seperated into individual income tax and corporate income tax and rename them into Individual and Corporate Income Tax, and in the process, sum up the no_of_cases and tax_and_penalty_arising int they carry, together.

Can Anyone advice me on how to do it?

Here is my current source code that i have yet to complete(in fact i have no idea how to begin with):

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# import the csv file
dataname = 'Datasets\\tax-and-penalty-arising-from-audits-by-tax-type.csv'
data = pd.read_csv(dataname)
df = pd.DataFrame(data)
```

答:
Use Series.replace by dictionary and then aggregate sum:

```<code>d = {'Corporate Income Tax':'Individual and Corporate Income Tax',
     'Individual Income Tax':'Individual and Corporate Income Tax'}
df = df.groupby(['financial_year',df['tax_type'].replace(d)]).sum().reset_index()
</code>```

Title: How to merge 2 rows into 1 row pandas

Body:
Use Series.replace by dictionary and then aggregate sum:

d = {'Corporate Income Tax':'Individual and Corporate Income Tax',
     'Individual Income Tax':'Individual and Corporate Income Tax'}
df = df.groupby(['financial_year',df['tax_type'].replace(d)]).sum().reset_index()


问:
Insert columns value into hstore data type in postgres
I have a table in postgres which has this three columns id_0,turnr and tags. tags column data type is hstore.
currently i am using this query which is not working

```<code>INSERT INTO relation_15_02_2020 (tags)
VALUES
   (
   '
       "type"=>"restriction",
       "restriction"=>"(select distinct(turnr) from relation_15_02_2020  ) "
       '
   );
</code>```

How can i add

```<code>"type"=>"restriction",
"restriction"=>" turnr value for respective id
</code>```

desired output for id_0 =1 tags

```<code> {"type"=>"restriction","restriction"=>"NoRightTurn"}
</code>```

答:
You want to update the rows, not insert new ones:

```<code>update relation_15_02_2020
  set tags = hstore(array['type', 'restriction'], array['restriction', turnr])
where id_0 = 1;
</code>```

alternatively

```<code>update relation_15_02_2020
  set tags = hstore('type', 'restriction')||hstore('restriction', turnr)
where id_0 = 1;
</code>```

Body:
I have a table in postgres which has this three columns id_0,turnr and tags. tags column data type is hstore.
currently i am using this query which is not working

INSERT INTO relation_15_02_2020 (tags)
VALUES
   (
   '
       "type"=>"restriction",
       "restriction"=>"(select distinct(turnr) from relation_15_02_2020  ) "
       '
   );

How can i add

"type"=>"restriction",
"restriction"=>" turnr value for respective id

desired output for id_0 =1 tags

 {"type"=>"restriction","restriction"=>"NoRightTurn"}

Body:
You want to update the rows, not insert new ones:

update relation_15_02_2020
  set tags = hstore(array['type', 'restriction'], array['restriction', turnr])
where id_0 = 1;

alternatively

update relation_15_02_2020
  set tags = hstore('type', 'restriction')||hstore('restriction', turnr)
where id_0 = 1;


问:
Adjusting top axis title and labels plots of plotmo::plot_glmnet in R
I use r package plotmo to visualize coefficient shrinkage of LASSO regression. By default, it add a top axis with title 'Degrees of Freedom'. How could I delete the top title or change the content of it? Generally, how could I adjust top axis (including title and axis labels) ploted by plotmo::plot_glmnet  ?

library(glmnet)
library(plotmo)
fit = glmnet(as.matrix(mtcars[-1]), mtcars[,1])
plot_glmnet(fit,xvar='lambda',label=7)
```

<p><img src="https://i.stack.imgur.com/ywiVZ.png" alt="enter image description here"></p>

<p>I've tried to use <code>mtext</code> and <code>axis</code> function, but it didn't work:</p>

```plot_glmnet(fit,xvar='lambda',label=7)
mtext('new top title', side=3)
```

答:
There is a line in the code of plot_glmnet, mtext(toplabel...) that does this..
Unfortunately if you want to remove that, you have to create a new function with this line removed, and assign the namespace:

```<code>new_plot_glmnet = function (x = stop("no 'x' argument"), xvar = c("rlambda", "lambda",
    "norm", "dev"), label = 10, nresponse = NA, grid.col = NA,
    s = NA, ...)
{
    check.classname(x, "x", c("glmnet", "multnet"))
    obj <- x
    beta <- get.beta(obj$beta, nresponse)
    ibeta <- nonzeroCoef(beta)
    if (length(ibeta) == 0) {
        plot(0:1, 0:1, col = 0)
        legend("topleft", legend = "all glmnet coefficients are zero",
            bty = "n")
        return(invisible(NULL))
    }
    beta <- as.matrix(beta[ibeta, , drop = FALSE])
    xlim <- dota("xlim", ...)
    xvar <- match.arg1(xvar)
    switch(xvar, norm = {
        if (inherits(obj, "multnet") || inherits(obj, "mrelnet")) {
            stop0("xvar=\"norm\" is not supported by plot_gbm for ",
                "multiple responses (use plot.glmnet instead)")
        }
        x <- apply(abs(beta), 2, sum)
        if (!is.specified(xlim)) xlim <- c(min(x), max(x))
        xlab <- "L1 Norm"
        approx.f <- 1
    }, lambda = {
        x <- log(obj$lambda)
        if (!is.specified(xlim)) xlim <- c(min(x), max(x))
        xlab <- "Log Lambda"
        approx.f <- 0
    }, rlambda = {
        x <- log(obj$lambda)
        if (!is.specified(xlim)) xlim <- c(max(x), min(x))
        xlab <- "Log Lambda"
        approx.f <- 0
    }, dev = {
        x <- obj$dev.ratio
        if (!is.specified(xlim)) xlim <- c(min(x), max(x))
        xlab <- "Fraction Deviance Explained"
        approx.f <- 1
    })
    xlim <- fix.lim(xlim)
    if (xvar != "rlambda")
        stopifnot(xlim[1] < xlim[2])
    else if (xlim[2] >= xlim[1])
        stop0("xlim[1] must be bigger than xlim[2] for xvar=\"rlambda\"")
    iname <- get.iname(beta, ibeta, label)
    old.par <- par("mar", "mgp", "cex.axis", "cex.lab")
    on.exit(par(mar = old.par$mar, mgp = old.par$mgp, cex.axis = old.par$cex.axis,
        cex.lab = old.par$cex.lab))
    mar4 <- old.par$mar[4]
    if (length(iname)) {
        cex.names <- min(1, max(0.5, 2.5/sqrt(length(iname))))
        mar4 <- max(old.par$mar[4] + 1, 0.75 * cex.names * par("cex") *
            max(nchar(names(iname))))
    }
    main <- dota("main", ...)
    nlines.needed.for.main <- if (is.specified(main))
        nlines(main) + 0.5
    else 0
    par(mar = c(old.par$mar[1], old.par$mar[2], max(old.par$mar[3],
        nlines.needed.for.main + 2.6), mar4))
    par(mgp = c(1.5, 0.4, 0))
    par(cex.axis = 0.8)
    ylab <- "Coefficients"
    if (is.list(obj$beta))
        ylab <- paste0(ylab, ": Response ", rownames(obj$dfmat)[nresponse])
    coef.col <- get.coef.col(..., beta = beta)
    keep <- which((coef.col != "NA") & (coef.col != "0"))
    iname <- iname[iname %in% keep]
    beta[-keep, ] <- NA
    call.plot(graphics::matplot, force.x = x, force.y = t(beta),
        force.main = "", force.col = coef.col, def.xlim = xlim,
        def.xlab = xlab, def.ylab = ylab, def.lty = 1, def.lwd = 1,
        def.type = "l", ...)
    abline(h = 0, col = "gray", lty = 3)
    maybe.grid(x = x, beta = beta, grid.col = grid.col, coef.col = coef.col,
        ...)
    if (xvar == "rlambda") {
        annotate.rlambda(lambda = obj$lambda, x = x, beta = beta,
            s = s, grid.col = grid.col, coef.col = coef.col,
            ...)
        toplab <- "Lambda"
    }
    else {
        top.axis(obj, x, nresponse, approx.f)
        toplab <- "Degrees of Freedom"
    }
    #mtext(toplab, side = 3, line = 1.5, cex = par("cex") * par("cex.lab"))
    if (is.specified(main))
        mtext(main, side = 3, line = 3, , cex = par("cex"))
    if (length(iname))
        right.labs(beta, iname, cex.names, coef.col)
    invisible(NULL)
}

environment(new_plot_glmnet) <- asNamespace('plotmo')
</code>```

Then you plot:

```<code>new_plot_glmnet(fit,xvar='lambda',label=7)
mtext('new top title', side=3,padj=-2)
</code>```

Body:
I use r package plotmo to visualize coefficient shrinkage of LASSO regression. By default, it add a top axis with title 'Degrees of Freedom'. How could I delete the top title or change the content of it? Generally, how could I adjust top axis (including title and axis labels) ploted by plotmo::plot_glmnet  ?

library(glmnet)
library(plotmo)
fit = glmnet(as.matrix(mtcars[-1]), mtcars[,1])
plot_glmnet(fit,xvar='lambda',label=7)

I've tried to use mtext and axis function, but it didn't work:

plot_glmnet(fit,xvar='lambda',label=7)
mtext('new top title', side=3)

Body:
There is a line in the code of plot_glmnet, mtext(toplabel...) that does this..
Unfortunately if you want to remove that, you have to create a new function with this line removed, and assign the namespace:

new_plot_glmnet = function (x = stop("no 'x' argument"), xvar = c("rlambda", "lambda",
    "norm", "dev"), label = 10, nresponse = NA, grid.col = NA,
    s = NA, ...)
{
    check.classname(x, "x", c("glmnet", "multnet"))
    obj <- x
    beta <- get.beta(obj$beta, nresponse)
    ibeta <- nonzeroCoef(beta)
    if (length(ibeta) == 0) {
        plot(0:1, 0:1, col = 0)
        legend("topleft", legend = "all glmnet coefficients are zero",
            bty = "n")
        return(invisible(NULL))
    }
    beta <- as.matrix(beta[ibeta, , drop = FALSE])
    xlim <- dota("xlim", ...)
    xvar <- match.arg1(xvar)
    switch(xvar, norm = {
        if (inherits(obj, "multnet") || inherits(obj, "mrelnet")) {
            stop0("xvar=\"norm\" is not supported by plot_gbm for ",
                "multiple responses (use plot.glmnet instead)")
        }
        x <- apply(abs(beta), 2, sum)
        if (!is.specified(xlim)) xlim <- c(min(x), max(x))
        xlab <- "L1 Norm"
        approx.f <- 1
    }, lambda = {
        x <- log(obj$lambda)
        if (!is.specified(xlim)) xlim <- c(min(x), max(x))
        xlab <- "Log Lambda"
        approx.f <- 0
    }, rlambda = {
        x <- log(obj$lambda)
        if (!is.specified(xlim)) xlim <- c(max(x), min(x))
        xlab <- "Log Lambda"
        approx.f <- 0
    }, dev = {
        x <- obj$dev.ratio
        if (!is.specified(xlim)) xlim <- c(min(x), max(x))
        xlab <- "Fraction Deviance Explained"
        approx.f <- 1
    })
    xlim <- fix.lim(xlim)
    if (xvar != "rlambda")
        stopifnot(xlim[1] < xlim[2])
    else if (xlim[2] >= xlim[1])
        stop0("xlim[1] must be bigger than xlim[2] for xvar=\"rlambda\"")
    iname <- get.iname(beta, ibeta, label)
    old.par <- par("mar", "mgp", "cex.axis", "cex.lab")
    on.exit(par(mar = old.par$mar, mgp = old.par$mgp, cex.axis = old.par$cex.axis,
        cex.lab = old.par$cex.lab))
    mar4 <- old.par$mar[4]
    if (length(iname)) {
        cex.names <- min(1, max(0.5, 2.5/sqrt(length(iname))))
        mar4 <- max(old.par$mar[4] + 1, 0.75 * cex.names * par("cex") *
            max(nchar(names(iname))))
    }
    main <- dota("main", ...)
    nlines.needed.for.main <- if (is.specified(main))
        nlines(main) + 0.5
    else 0
    par(mar = c(old.par$mar[1], old.par$mar[2], max(old.par$mar[3],
        nlines.needed.for.main + 2.6), mar4))
    par(mgp = c(1.5, 0.4, 0))
    par(cex.axis = 0.8)
    ylab <- "Coefficients"
    if (is.list(obj$beta))
        ylab <- paste0(ylab, ": Response ", rownames(obj$dfmat)[nresponse])
    coef.col <- get.coef.col(..., beta = beta)
    keep <- which((coef.col != "NA") & (coef.col != "0"))
    iname <- iname[iname %in% keep]
    beta[-keep, ] <- NA
    call.plot(graphics::matplot, force.x = x, force.y = t(beta),
        force.main = "", force.col = coef.col, def.xlim = xlim,
        def.xlab = xlab, def.ylab = ylab, def.lty = 1, def.lwd = 1,
        def.type = "l", ...)
    abline(h = 0, col = "gray", lty = 3)
    maybe.grid(x = x, beta = beta, grid.col = grid.col, coef.col = coef.col,
        ...)
    if (xvar == "rlambda") {
        annotate.rlambda(lambda = obj$lambda, x = x, beta = beta,
            s = s, grid.col = grid.col, coef.col = coef.col,
            ...)
        toplab <- "Lambda"
    }
    else {
        top.axis(obj, x, nresponse, approx.f)
        toplab <- "Degrees of Freedom"
    }
    #mtext(toplab, side = 3, line = 1.5, cex = par("cex") * par("cex.lab"))
    if (is.specified(main))
        mtext(main, side = 3, line = 3, , cex = par("cex"))
    if (length(iname))
        right.labs(beta, iname, cex.names, coef.col)
    invisible(NULL)
}

environment(new_plot_glmnet) <- asNamespace('plotmo')

Then you plot:

new_plot_glmnet(fit,xvar='lambda',label=7)
mtext('new top title', side=3,padj=-2)