问:
Running a JAX-WS web service in development or production mode
I have a web service generated with wsimport (in an ANT task) for which I want to handle the javax.xml.bind.UnmarshalException exception that appears when I'm sending an invalid XML request.

In order to throw this exception I just send an unbalanced tag to the server and I get back:

```<code><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
 <S:Body>
      <S:Fault xmlns:ns4="http://www.w3.org/2003/05/soap-envelope">
         <faultcode>S:Server</faultcode>
         <faultstring>javax.xml.bind.UnmarshalException
 - with linked exception:
[com.ctc.wstx.exc.WstxParsingException: Unexpected close tag </m:BAR>; expected </m:BR>.
 at [row,col {unknown-source}]: [16,38]]</faultstring>
      </S:Fault>
   </S:Body>
</S:Envelope>
</code>```

Unfortunately in my code I see no way of catching this exception and sending back a standard message, instead of automatically sending some webservice-internal exception that the client might not be able to parse.

Is there a way to tell JAX-Ws to run in production or in development mode? Where in production mode it would allow me to override the message being sent in reply to an erroneous request?

Or at least implement some kind of hook that will call a method of mine when an exception happens in JAX-WS's code...

I am running the service on Glassfish 4.1.2.

My ANT script for building the webservice from the wsdl looks like this:

```<code><!DOCTYPE project>
<project name="WSDL to Java generator" default="wsimport">
    <path id="wsimport.classpath">
        <fileset dir="../../EAR/EarContent/lib">
            <include name="commons-beanutils-*.jar"/>
            <include name="commons-lang-*.jar"/>
            <include name="commons-logging-*.jar"/>
        </fileset>

        <fileset dir="../../Common/ant-libs">
            <include name="*.jar"/>
        </fileset>
    </path>

    <taskdef name="wsimport" classname="com.sun.tools.ws.ant.WsImport" classpathref="wsimport.classpath"/>

    <target name="wsimport">
        <wsimport verbose="true" wsdl="../schemas/WebService.wsdl"  wsdlLocation="../schemas/WebService.wsdl" binding="./ws-build-bindings.xjb">
            <xjcarg line="-Xannotate"/>
            <xjcarg line="-Xinheritance"/>

            <arg line="-keep"/>
            <arg line="-d ../src"/>
            <arg line="-p org.company.name.message"/>

            <arg line="-Xnocompile"/>
        </wsimport>
    </target>
</project>
</code>```

The generated interface looks like this:

```<code>import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.Holder;
/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.3.0
 * Generated source version: 2.2
 *
 */
@WebService(name = "WebService", targetNamespace = "http://company.com/foo/WebService/")
@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
@XmlSeeAlso({
    ObjectFactory.class
})
public interface WebService {

    @WebMethod(operationName = "PublishEvent", action = "PublishEvent")
    @WebResult(name = "ResponseMessage", targetNamespace = "http://foo.bar/schema/message", partName = "response")
    public ResponseMessageType publishEvent(
        @WebParam(name = "EventMessage", targetNamespace = "http://foo.bar/schema/message", partName = "event")
        EventMessageType event);

    @WebMethod(operationName = "Request", action = "Request")
    @WebResult(name = "ResponseMessage", targetNamespace = "http://foo.bar/schema/message", partName = "response")
    public ResponseMessageType request(
        @WebParam(name = "RequestMessage", targetNamespace = "http://foo.bar/schema/message", partName = "request")
        RequestMessageType request);

    @WebMethod(operationName = "Response", action = "Response")
    public void response(
        @WebParam(name = "ResponseMessage", targetNamespace = "http://foo.bar/schema/message", mode = WebParam.Mode.INOUT, partName = "response")
        Holder<ResponseMessageType> response);

}
</code>```

The generated class extending Service:

```<code>import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.WebServiceFeature;
/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.3.0
 * Generated source version: 2.2
 *
 */
@WebServiceClient(name = "WebService", targetNamespace = "http://company.com/foo/WebService/", wsdlLocation = "../schemas/WebService.wsdl")
public class WebService_Service
    extends Service
{

    private final static URL WebSERVICE_WSDL_LOCATION;
    private final static WebServiceException WebSERVICE_EXCEPTION;
    private final static QName WebSERVICE_QNAME = new QName("http://company.com/foo/WebService/", "WebService");

    static {
        WebSERVICE_WSDL_LOCATION = org.company.name.message.WebService_Service.class.getResource("../schemas/WebService.wsdl");
        WebServiceException e = null;
        if (WebSERVICE_WSDL_LOCATION == null) {
            e = new WebServiceException("Cannot find '../schemas/WebService.wsdl' wsdl. Place the resource correctly in the classpath.");
        }
        WebSERVICE_EXCEPTION = e;
    }

    public WebService_Service() {
        super(__getWsdlLocation(), WebSERVICE_QNAME);
    }

    public WebService_Service(WebServiceFeature... features) {
        super(__getWsdlLocation(), WebSERVICE_QNAME, features);
    }

    public WebService_Service(URL wsdlLocation) {
        super(wsdlLocation, WebSERVICE_QNAME);
    }

    public WebService_Service(URL wsdlLocation, WebServiceFeature... features) {
        super(wsdlLocation, WebSERVICE_QNAME, features);
    }

    public WebService_Service(URL wsdlLocation, QName serviceName) {
        super(wsdlLocation, serviceName);
    }

    public WebService_Service(URL wsdlLocation, QName serviceName, WebServiceFeature... features) {
        super(wsdlLocation, serviceName, features);
    }

    @WebEndpoint(name = "WebServiceSOAP")
    public WebService getWebServiceSOAP() {
        return super.getPort(new QName("http://company.com/foo/WebService/", "WebServiceSOAP"), WebService.class);
    }

    @WebEndpoint(name = "WebServiceSOAP")
    public WebService getWebServiceSOAP(WebServiceFeature... features) {
        return super.getPort(new QName("http://company.com/foo/WebService/", "WebServiceSOAP"), WebService.class, features);
    }

    private static URL __getWsdlLocation() {
        if (WebSERVICE_EXCEPTION!= null) {
            throw WebSERVICE_EXCEPTION;
        }
        return WebSERVICE_WSDL_LOCATION;
    }

}
</code>```

And here's my implementation of the interface (with the code doing the actual work omitted), when an invalid request is made, there's no way for me to catch it since my methods below are not called:

```<code>import javax.jws.WebService;
import javax.xml.ws.Holder;

import org.company.name.message.ErrorType.ErrorLevelEnum;
import org.company.name.message.EventMessageType;
import org.company.name.message.HeaderType;
import org.company.name.message.WebService;
import org.company.name.message.RequestMessageType;
import org.company.name.message.ResponseMessageType;

@WebService(endpointInterface = "org.company.name.message.WebService")
public class Web implements WebService {
    @Override
    public ResponseMessageType publishEvent(EventMessageType event) {
        ResponseMessageBuilder responseBuilder = new ResponseMessageBuilder();
        try
        {
            // build response here

        }
        catch (WebException exception) {
            // error building response
        }
        catch (Exception ex) {
            // general error
        }

        return responseBuilder.build();
    }

    @Override
    public ResponseMessageType request(RequestMessageType request) {
        ResponseMessageBuilder responseBuilder = new ResponseMessageBuilder();

        try
        {
            // build response here

        }
        catch (WebException exception) {
            // error building response
        }
        catch (Exception ex) {
            // general error
        }

        return responseBuilder.build();
    }

    @Override
    public void response(Holder<ResponseMessageType> response) {
        // TODO Auto-generated method stub
    }
}
</code>```

答:
Fixed this by using a SOAPHandler (https://docs.oracle.com/middleware/1213/wls/WSGET/jax-ws-soaphandlers.htm#WSGET3446).

The handler intercepts the request, tries to unmarshal it (via JAXB) and if an exception is thrown, I customize the response message (ie. fully replace it by doing messageContext.setMessage(soapFaultMessage); in the handleMessage method of yourSOAPHandler) and send it back (by returning false from the handleMessage method.

Also, it's worth looking into the SOAPFaultException class (https://docs.oracle.com/javase/7/docs/api/javax/xml/ws/soap/SOAPFaultException.html) which you can throw and the soap fault response message is customized to your liking.

Body:
I have a web service generated with wsimport (in an ANT task) for which I want to handle the javax.xml.bind.UnmarshalException exception that appears when I'm sending an invalid XML request.

In order to throw this exception I just send an unbalanced tag to the server and I get back:

<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
 <S:Body>
      <S:Fault xmlns:ns4="http://www.w3.org/2003/05/soap-envelope">
         <faultcode>S:Server</faultcode>
         <faultstring>javax.xml.bind.UnmarshalException
 - with linked exception:
[com.ctc.wstx.exc.WstxParsingException: Unexpected close tag </m:BAR>; expected </m:BR>.
 at [row,col {unknown-source}]: [16,38]]</faultstring>
      </S:Fault>
   </S:Body>
</S:Envelope>

Unfortunately in my code I see no way of catching this exception and sending back a standard message, instead of automatically sending some webservice-internal exception that the client might not be able to parse.

Is there a way to tell JAX-Ws to run in production or in development mode? Where in production mode it would allow me to override the message being sent in reply to an erroneous request?

Or at least implement some kind of hook that will call a method of mine when an exception happens in JAX-WS's code...

I am running the service on Glassfish 4.1.2.

My ANT script for building the webservice from the wsdl looks like this:

<!DOCTYPE project>
<project name="WSDL to Java generator" default="wsimport">
    <path id="wsimport.classpath">
        <fileset dir="../../EAR/EarContent/lib">
            <include name="commons-beanutils-*.jar"/>
            <include name="commons-lang-*.jar"/>
            <include name="commons-logging-*.jar"/>
        </fileset>

        <fileset dir="../../Common/ant-libs">
            <include name="*.jar"/>
        </fileset>
    </path>

    <taskdef name="wsimport" classname="com.sun.tools.ws.ant.WsImport" classpathref="wsimport.classpath"/>

    <target name="wsimport">
        <wsimport verbose="true" wsdl="../schemas/WebService.wsdl"  wsdlLocation="../schemas/WebService.wsdl" binding="./ws-build-bindings.xjb">
            <xjcarg line="-Xannotate"/>
            <xjcarg line="-Xinheritance"/>

            <arg line="-keep"/>
            <arg line="-d ../src"/>
            <arg line="-p org.company.name.message"/>

            <arg line="-Xnocompile"/>
        </wsimport>
    </target>
</project>

The generated interface looks like this:

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.Holder;
/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.3.0
 * Generated source version: 2.2
 *
 */
@WebService(name = "WebService", targetNamespace = "http://company.com/foo/WebService/")
@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
@XmlSeeAlso({
    ObjectFactory.class
})
public interface WebService {

    @WebMethod(operationName = "PublishEvent", action = "PublishEvent")
    @WebResult(name = "ResponseMessage", targetNamespace = "http://foo.bar/schema/message", partName = "response")
    public ResponseMessageType publishEvent(
        @WebParam(name = "EventMessage", targetNamespace = "http://foo.bar/schema/message", partName = "event")
        EventMessageType event);

    @WebMethod(operationName = "Request", action = "Request")
    @WebResult(name = "ResponseMessage", targetNamespace = "http://foo.bar/schema/message", partName = "response")
    public ResponseMessageType request(
        @WebParam(name = "RequestMessage", targetNamespace = "http://foo.bar/schema/message", partName = "request")
        RequestMessageType request);

    @WebMethod(operationName = "Response", action = "Response")
    public void response(
        @WebParam(name = "ResponseMessage", targetNamespace = "http://foo.bar/schema/message", mode = WebParam.Mode.INOUT, partName = "response")
        Holder<ResponseMessageType> response);

}

The generated class extending Service:

import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.WebServiceFeature;
/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.3.0
 * Generated source version: 2.2
 *
 */
@WebServiceClient(name = "WebService", targetNamespace = "http://company.com/foo/WebService/", wsdlLocation = "../schemas/WebService.wsdl")
public class WebService_Service
    extends Service
{

    private final static URL WebSERVICE_WSDL_LOCATION;
    private final static WebServiceException WebSERVICE_EXCEPTION;
    private final static QName WebSERVICE_QNAME = new QName("http://company.com/foo/WebService/", "WebService");

    static {
        WebSERVICE_WSDL_LOCATION = org.company.name.message.WebService_Service.class.getResource("../schemas/WebService.wsdl");
        WebServiceException e = null;
        if (WebSERVICE_WSDL_LOCATION == null) {
            e = new WebServiceException("Cannot find '../schemas/WebService.wsdl' wsdl. Place the resource correctly in the classpath.");
        }
        WebSERVICE_EXCEPTION = e;
    }

    public WebService_Service() {
        super(__getWsdlLocation(), WebSERVICE_QNAME);
    }

    public WebService_Service(WebServiceFeature... features) {
        super(__getWsdlLocation(), WebSERVICE_QNAME, features);
    }

    public WebService_Service(URL wsdlLocation) {
        super(wsdlLocation, WebSERVICE_QNAME);
    }

    public WebService_Service(URL wsdlLocation, WebServiceFeature... features) {
        super(wsdlLocation, WebSERVICE_QNAME, features);
    }

    public WebService_Service(URL wsdlLocation, QName serviceName) {
        super(wsdlLocation, serviceName);
    }

    public WebService_Service(URL wsdlLocation, QName serviceName, WebServiceFeature... features) {
        super(wsdlLocation, serviceName, features);
    }

    @WebEndpoint(name = "WebServiceSOAP")
    public WebService getWebServiceSOAP() {
        return super.getPort(new QName("http://company.com/foo/WebService/", "WebServiceSOAP"), WebService.class);
    }

    @WebEndpoint(name = "WebServiceSOAP")
    public WebService getWebServiceSOAP(WebServiceFeature... features) {
        return super.getPort(new QName("http://company.com/foo/WebService/", "WebServiceSOAP"), WebService.class, features);
    }

    private static URL __getWsdlLocation() {
        if (WebSERVICE_EXCEPTION!= null) {
            throw WebSERVICE_EXCEPTION;
        }
        return WebSERVICE_WSDL_LOCATION;
    }

}

And here's my implementation of the interface (with the code doing the actual work omitted), when an invalid request is made, there's no way for me to catch it since my methods below are not called:

import javax.jws.WebService;
import javax.xml.ws.Holder;

import org.company.name.message.ErrorType.ErrorLevelEnum;
import org.company.name.message.EventMessageType;
import org.company.name.message.HeaderType;
import org.company.name.message.WebService;
import org.company.name.message.RequestMessageType;
import org.company.name.message.ResponseMessageType;

@WebService(endpointInterface = "org.company.name.message.WebService")
public class Web implements WebService {
    @Override
    public ResponseMessageType publishEvent(EventMessageType event) {
        ResponseMessageBuilder responseBuilder = new ResponseMessageBuilder();
        try
        {
            // build response here

        }
        catch (WebException exception) {
            // error building response
        }
        catch (Exception ex) {
            // general error
        }

        return responseBuilder.build();
    }

    @Override
    public ResponseMessageType request(RequestMessageType request) {
        ResponseMessageBuilder responseBuilder = new ResponseMessageBuilder();

        try
        {
            // build response here

        }
        catch (WebException exception) {
            // error building response
        }
        catch (Exception ex) {
            // general error
        }

        return responseBuilder.build();
    }

    @Override
    public void response(Holder<ResponseMessageType> response) {
        // TODO Auto-generated method stub
    }
}


来源: stackexchange

问:
How do I send a cross-domain POST request via JavaScript?
How do I send a cross-domain POST request via JavaScript?

Notes - it shouldn't refresh the page, and I need to grab and parse the response afterwards.

答:
If you have access to all servers involved, put the following in the header of the reply for the page being requested in the other domain:

PHP:

```<code>header('Access-Control-Allow-Origin: *');
</code>```

For example, in Drupal's xmlrpc.php code you would do this:

```<code>function xmlrpc_server_output($xml) {
    $xml = '<?xml version="1.0"?>'."\n". $xml;
    header('Connection: close');
    header('Content-Length: '. strlen($xml));
    header('Access-Control-Allow-Origin: *');
    header('Content-Type: application/x-www-form-urlencoded');
    header('Date: '. date('r'));
    // $xml = str_replace("\n", " ", $xml);

    echo $xml;
    exit;
}
</code>```

This probably creates a security problem, and you should make sure that you take the appropriate measures to verify the request.

ContentLicense: CC BY-SA 4.0

LastEditorDisplayName: Ido Schacham

Body:
If you have access to all servers involved, put the following in the header of the reply for the page being requested in the other domain:

PHP:

header('Access-Control-Allow-Origin: *');

For example, in Drupal's xmlrpc.php code you would do this:

function xmlrpc_server_output($xml) {
    $xml = '<?xml version="1.0"?>'."\n". $xml;
    header('Connection: close');
    header('Content-Length: '. strlen($xml));
    header('Access-Control-Allow-Origin: *');
    header('Content-Type: application/x-www-form-urlencoded');
    header('Date: '. date('r'));
    // $xml = str_replace("\n", " ", $xml);

    echo $xml;
    exit;
}

This probably creates a security problem, and you should make sure that you take the appropriate measures to verify the request.

ContentLicense: CC BY-SA 3.0


问:
oracle compare a date with the current date
I have to convert a column to a date and then compare the month of the column with the current month.

The column looks like this :

```<code>Date
0117
0217
0317
..
</code>```

I know how to convert it but cant compare it.

```<code>select  date,to_date(date, 'mmyy')
from table
where ????
</code>```

any ideas?

答:
You can convert the value to a date using to_date():

```<code>select to_date(mmyy, 'MMYY')
from t;
</code>```

Note that I renamed the column mmyy to clarify what it contains.

This returns the first day of the month.

The result of to_date() can then be compared to the current date.  For instance, to match the first of date of the month:

```<code>where to_date(mmyy, 'MMYY') = trunc(sysdate)
</code>```

If you want to match everything in the month, just use an appropriate comparison:

```<code>where to_char(to_date(mmyy, 'MMYY'), 'YYYY-MM') = to_char(sysdate, 'YYYY-MM')
</code>```

or, more simply:

```<code> where mmyy = to_char(sysdate, 'MMYY')
</code>```

Body:
I have to convert a column to a date and then compare the month of the column with the current month.

The column looks like this :

Date
0117
0217
0317
..

I know how to convert it but cant compare it.

select  date,to_date(date, 'mmyy')
from table
where ????

any ideas?

Body:
You can convert the value to a date using to_date():

select to_date(mmyy, 'MMYY')
from t;

Note that I renamed the column mmyy to clarify what it contains.

This returns the first day of the month.

The result of to_date() can then be compared to the current date.  For instance, to match the first of date of the month:

where to_date(mmyy, 'MMYY') = trunc(sysdate)

If you want to match everything in the month, just use an appropriate comparison:

where to_char(to_date(mmyy, 'MMYY'), 'YYYY-MM') = to_char(sysdate, 'YYYY-MM')

or, more simply:

 where mmyy = to_char(sysdate, 'MMYY')


问:
Moving Folders in Laravel 5.5
Scenario

Im trying to allow users to move folders around in laravel 5.5, but Laravels site does not have example code for moving folders only files. I looked elsewhere and came across a couple other answers on stackoverflow and other places and tried them all.

Laravel move all files directory

https://laracasts.com/discuss/channels/laravel/laravel-cannot-use-movedirectory-and-copydirectory-problem

Laravel, unable to copyDirectory or moveDirectory

When I try to move a folder i get this response in Devtools:

```<code>0:"I want to move this /public/Gallery"
1:"To here /public/Images"
2:false
</code>```

From this code in the backend

```<code>$item ['path' => '/public/Gallery']
$path = '/public/Images'
$success = File::moveDirectory($item['path'], $path);
return [
    "I want to move this ".$item['path'],
    "To here $path",
    $success,
];
</code>```

Earlier i was getting a response that said the file already exists although it didnt but ive not since been able to replicate that.

EDIT

using Storage::move() i was able to replicate the 'already exists error'

```<code>exception:"League\Flysystem\FileExistsException"
file:"C:\Users\user.name\Desktop\electron-api\vendor\league\flysystem\src\Filesystem.php"
line:402
message:"File already exists at path: public/Images"
</code>```

Question

How to move folders around in laravel 5 storage, NOT FILES. Preferably using the Storage Facade.

答:
Files and directories are mostly the same thing and move will treat them as the same.
You can create a local disk that points to public so that it is easier to work with the public directory

```<code>Storage::move($item['path'], $path);
</code>```

The move function works like bash mv command which is essentially just a rename. 2 directories cannot have the same name. so either first delete public/Images/ or merge contents into public/Images and delete public/Gallery

if you wish to move the directory into $path then you have to place the directory name at the end of the path

```<code>Storage::move($item['path'], $path.'/Gallery');
</code>```

this will create '/public/Images/Gallery'

Title: Moving Folders in Laravel 5.5

Body:
Scenario

Im trying to allow users to move folders around in laravel 5.5, but Laravels site does not have example code for moving folders only files. I looked elsewhere and came across a couple other answers on stackoverflow and other places and tried them all.

Laravel move all files directory

https://laracasts.com/discuss/channels/laravel/laravel-cannot-use-movedirectory-and-copydirectory-problem

Laravel, unable to copyDirectory or moveDirectory

When I try to move a folder i get this response in Devtools:

0:"I want to move this /public/Gallery"
1:"To here /public/Images"
2:false

From this code in the backend

$item ['path' => '/public/Gallery']
$path = '/public/Images'
$success = File::moveDirectory($item['path'], $path);
return [
    "I want to move this ".$item['path'],
    "To here $path",
    $success,
];

Earlier i was getting a response that said the file already exists although it didnt but ive not since been able to replicate that.

EDIT

using Storage::move() i was able to replicate the 'already exists error'

exception:"League\Flysystem\FileExistsException"
file:"C:\Users\user.name\Desktop\electron-api\vendor\league\flysystem\src\Filesystem.php"
line:402
message:"File already exists at path: public/Images"

Question

How to move folders around in laravel 5 storage, NOT FILES. Preferably using the Storage Facade.

Body:
Files and directories are mostly the same thing and move will treat them as the same.
You can create a local disk that points to public so that it is easier to work with the public directory

Storage::move($item['path'], $path);

The move function works like bash mv command which is essentially just a rename. 2 directories cannot have the same name. so either first delete public/Images/ or merge contents into public/Images and delete public/Gallery

if you wish to move the directory into $path then you have to place the directory name at the end of the path

Storage::move($item['path'], $path.'/Gallery');

this will create '/public/Images/Gallery'


问:
Legend title pad in matplotlib
I would like the title in the legend of my matplotlib figure to be more distant from the content of the legend. Currently, I have the following:

I see the set_title function of the Legend class accepts a prop dictionary, which should be the one described in the text properties page. This one contains the field bbox, where a pad property could be added. But when I try something like the following

```<code>legend.set_title('Legend', prop={'bbox':{'pad':somepad}})
</code>```

python complains that bbox is not an accepted parameter.

I'm using matplotlib 2.1.0 under Python 3.6.3 on Arch Linux.

An obvious workaround would be add a linebreak, like this:

```<code>legend.set_title('Legend\n ')
</code>```

Although one might like the result, matplotlib has the great advantage that everything can be configured to the slightest detail, so I'm looking for a solution which gives me more fine-grained control over this spacing.

答:
Of course introducing a linebreak in the title text as legend.set_title('Legend\n ') is a valid option.

If you don't like that you can set the separation between title and legend handle box manually as

```<code>legend._legend_box.sep = 20
</code>```

Complete example:

```<code>import matplotlib.pyplot as plt

plt.plot([1,2], label="some")
plt.plot([1,3], label="label")

legend = plt.legend(title="Legend title", ncol=2)
legend._legend_box.sep = 20

plt.show()
</code>```

The default separation is labelspacing * fontsize, hence

```<code>plt.rcParams["legend.labelspacing"] * plt.rcParams["font.size"] == 0.5 * 10 == 5
</code>```

Title: Legend title pad in matplotlib

Body:
I would like the title in the legend of my matplotlib figure to be more distant from the content of the legend. Currently, I have the following:

I see the set_title function of the Legend class accepts a prop dictionary, which should be the one described in the text properties page. This one contains the field bbox, where a pad property could be added. But when I try something like the following

legend.set_title('Legend', prop={'bbox':{'pad':somepad}})

python complains that bbox is not an accepted parameter.

I'm using matplotlib 2.1.0 under Python 3.6.3 on Arch Linux.

An obvious workaround would be add a linebreak, like this:

legend.set_title('Legend\n ')

Although one might like the result, matplotlib has the great advantage that everything can be configured to the slightest detail, so I'm looking for a solution which gives me more fine-grained control over this spacing.

Body:
Of course introducing a linebreak in the title text as legend.set_title('Legend\n ') is a valid option.

If you don't like that you can set the separation between title and legend handle box manually as

legend._legend_box.sep = 20

Complete example:

import matplotlib.pyplot as plt

plt.plot([1,2], label="some")
plt.plot([1,3], label="label")

legend = plt.legend(title="Legend title", ncol=2)
legend._legend_box.sep = 20

plt.show()

The default separation is labelspacing * fontsize, hence

plt.rcParams["legend.labelspacing"] * plt.rcParams["font.size"] == 0.5 * 10 == 5


问:
Print 2 ArrayLists with specific format
I am trying to format the output of my program, so it looks easily readable by the user. I am not that good at formatting text and I would really welcome your help.

I am trying to print/display(in my JTextArea). I already have a method to display there:

```<code>public void display(String... lines){
     for(String line:lines){
          System.out.println(line);
     }
}
</code>```

Now, I have the 2 ArrayLists that contain some data which was added to them through the use of the program.

```<code>itemOrders = new ArrayList<CafeOrders>();
customers = new ArrayList<CafeCustomer>();
</code>```

The constructors, respectively:

```<code>public CafeOrders(String orderID, String itemName, double price){
    super();
    this.orderID = orderID;
    this.itemName = itemName;
    this.price = price;

}
</code>```

and

```<code>public CafeCustomer(int customerID, String customerName){
    super();
    this.customerID = customerID;
    this.customerName = customerName;
    this.orderNo = UUID.randomUUID().toString();

}
</code>```

I made it in such a way, that orderNo = orderID.

First the customer name is asked, then when he selects from a list of items, each item is added to the CafeOrders ArrayList along with the customer's ID.

I want to create a method that prints those 2 ArrayLists in the specific format, or something similar:

```<code>customerName "with id" orderID "has purchased" itemName1
                                               itemName2
                                               itemName3
                                               etc...
</code>```

Any help would be appreciated!

答:
```<code>for(CafeCustomer customer : customers ){
       for(CafeOrders order: itemOrders ){
           if(customer.getOrderNo.equals(order.getOrderId()) ){
               System.out.println(customer.getCustomerName() +"with Id " +
                customer.getCustomerId() + "has purchased "
                +order.getItemName());
           }
       }
   }
</code>```

Title: Print 2 ArrayLists with specific format

Body:
I am trying to format the output of my program, so it looks easily readable by the user. I am not that good at formatting text and I would really welcome your help.

I am trying to print/display(in my JTextArea). I already have a method to display there:

public void display(String... lines){
     for(String line:lines){
          System.out.println(line);
     }
}

Now, I have the 2 ArrayLists that contain some data which was added to them through the use of the program.

itemOrders = new ArrayList<CafeOrders>();
customers = new ArrayList<CafeCustomer>();

The constructors, respectively:

public CafeOrders(String orderID, String itemName, double price){
    super();
    this.orderID = orderID;
    this.itemName = itemName;
    this.price = price;

}

and

public CafeCustomer(int customerID, String customerName){
    super();
    this.customerID = customerID;
    this.customerName = customerName;
    this.orderNo = UUID.randomUUID().toString();

}

I made it in such a way, that orderNo = orderID.

First the customer name is asked, then when he selects from a list of items, each item is added to the CafeOrders ArrayList along with the customer's ID.

I want to create a method that prints those 2 ArrayLists in the specific format, or something similar:

customerName "with id" orderID "has purchased" itemName1
                                               itemName2
                                               itemName3
                                               etc...

Any help would be appreciated!


问:
Is optimize select max(date) sql query?
This query is too slow. Is it possible to optimize it?</p>

```<code>SELECT
    CONVERT(CHAR(10), MAX(dat), 101) AS MaxDate
FROM
    X_Prices price
INNER JOIN
    RMetal cat ON cat.SubCat = price.Subcat AND cat.Category = price.Category
WHERE
    cat.Country = 'India'
    AND cat.Section = 1
    AND cat.active = 1
    AND cat.inactive = 0
    AND price.Dat < GETDATE() - 60
</code>```

答:
if u can change the DB:
replace country with country code make sure SubCat & Category are numbers, & have index (as foreign key)

if this is the DB structure u should probably add indexes based on the execution plan, probably on the entire where clause

Title: Is optimize select max(date) sql query?

Body:
This query is too slow. Is it possible to optimize it?

SELECT
    CONVERT(CHAR(10), MAX(dat), 101) AS MaxDate
FROM
    X_Prices price
INNER JOIN
    RMetal cat ON cat.SubCat = price.Subcat AND cat.Category = price.Category
WHERE
    cat.Country = 'India'
    AND cat.Section = 1
    AND cat.active = 1
    AND cat.inactive = 0
    AND price.Dat < GETDATE() - 60


问:
How can I get the changeset ID of the base file when merging with mercurial?
I have a couple branches that I need to merge, but I don't know where some of the changes are coming from that are showing up in my merge tool. The change sets of local and other are obvious, but how can I find out which change set the base file came from? I'm working in a repository with dozens of branches, so viewing the graph and tracking it doesn't work very well.</p>

答:
Using revsets (Mercurial 1.6 and later), you can get the common ancestor of two changesets with:</p>

```<code>hg log -r ancestor(rev1,rev2)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Using revsets (Mercurial 1.6 and later), you can get the common ancestor of two changesets with:

hg log -r ancestor(rev1,rev2)


问:
How to split layer in After Effects using marker of markers and javascript, extendscript?
I am trying to split layer in After Effects using extendscript. First of all, i want get the time value of the marker. Then i want set the Timeline cursor on necessary point on the Timeline. And finally i'll split layer to pieces.

How did this in javascript? Maby you know how get time parameter from marker and then use this value to shift  Timeline cursor from necessary  position?

Or you know other way how do it?

答:
There is no need of markers for spliiting the layer.Just you have to duplicate the layers and make the use of intime and outtime and set them accordingily.For the splitting of between layer the original will be splitted to the required three layers or portions. So I have given the :

```<code>var portions =3;
</code>```

You can make the use of inPoints and outPoints to mark the interval for the layer for splitting :

```<code>var sliceTime = 15.0; //give the end time for the part of layer)
var origOutPoint = layer.outPoint;
comp.time = sliceTime;
while (portions > 1) {
    var d = layer.outPoint - sliceTime;
    dupeLayer = layer.duplicate();
    layer.outPoint = dupeLayer.inPoint = sliceTime;

    sliceTime = 20.0;
    portions--;
    layer = dupeLayer;
}
</code>```

Hope this might help you.

Body:
There is no need of markers for spliiting the layer.Just you have to duplicate the layers and make the use of intime and outtime and set them accordingily.For the splitting of between layer the original will be splitted to the required three layers or portions. So I have given the :

var portions =3;

You can make the use of inPoints and outPoints to mark the interval for the layer for splitting :

var sliceTime = 15.0; //give the end time for the part of layer)
var origOutPoint = layer.outPoint;
comp.time = sliceTime;
while (portions > 1) {
    var d = layer.outPoint - sliceTime;
    dupeLayer = layer.duplicate();
    layer.outPoint = dupeLayer.inPoint = sliceTime;

    sliceTime = 20.0;
    portions--;
    layer = dupeLayer;
}

Hope this might help you.


答:
As long as your customer can have multiple orders I would suggest using

Map<CafeCustomer, List<CafeOrder>>

And then what you can do:

```<code>public void display(Map<CafeCustomer, List<CafeOrder>> map)
{
     map.forEach( (customer, orderList) -> {
         System.out.println(customer.getCustomerName() + " has purchased:");
         for(CafeOrder order : orderList)
             System.out.println(order.getItemName());
});
}
</code>```

Title: Print 2 ArrayLists with specific format

Body:
As long as your customer can have multiple orders I would suggest using

Map<CafeCustomer, List<CafeOrder>>

And then what you can do:

public void display(Map<CafeCustomer, List<CafeOrder>> map)
{
     map.forEach( (customer, orderList) -> {
         System.out.println(customer.getCustomerName() + " has purchased:");
         for(CafeOrder order : orderList)
             System.out.println(order.getItemName());
});
}


问:
Using Mockito to unit test Guice based class
My application uses Google Guice dependency injection framework. Im now having trouble figuring out a way to write unit tests for my class.

```<code>private final Person aRecord;

@Inject
public MyClass(Venue venue, @Assisted("record") Record myRecord) {
    super(venue,myRecord);
    aRecord = (Person) myRecord;
}

public void build() throws Exception {
    super.build();
    super.getParentRecord().setJobType(aRecord.getJobType());
    super.getParentRecord().setHairColor(aRecord.getHairColor());
    super.getParentRecord().setEyeColor(aRecord.getEyeColor());
}
</code>```

I want to write a unit test for the build() method in the child class, it should

Ensure that when super.build() gets called all of the basic information on the super.getParentRecord() is populated e.g. age, gender etc.

Ensure an exception is thrown in the build() method if aRecord.getJobType() is null

Ensure an exception is thrown in the build() method if aRecord.getHairColor() is null

Ensure an exception is thrown in the build() method if aRecord.getEyeColor() is null

答:
You have two dependencies of MyClass (Venue and Record) so you have to mock those.

```<code>import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
...
Venue venueMock = mock(Venue.class);
Record recordMock = mock(Record.class);
</code>```

Then in your unit test you have to create an instance of MyClass and assert the expected result:

For example: "Ensure an exception is thrown in the build() method if aRecord.getJobType() is null"

```<code>@Test(expected=RuntimeException.class)// or whatever exception you expect
public void testIfExceptionIsThrownWhengetJobTypeReturnsNull() throws Throwable {
    Venue venueMock = mock(Venue.class);   //create the mocks
    Record recordMock = mock(Record.class);//create the mocks
    when(recordMock.getJobType()).thenReturn(null); //specify the behavior of the components that are not relevant to the tests

    MyClass myClass = new MyClass(venueMock, recordMock);
    myClass.build();
    //you can make some assertions here if you expect some result instead of exception
}
</code>```

Note that if you don't specify the return value of any of the mocked dependencies (with when()) it will return the default value for the return type - null for objects, 0 for primitive numbers, false for boolean, etc. So it will be best to stub all of the methods that are used in MyClass.

Body:
My application uses Google Guice dependency injection framework. Im now having trouble figuring out a way to write unit tests for my class.

private final Person aRecord;

@Inject
public MyClass(Venue venue, @Assisted("record") Record myRecord) {
    super(venue,myRecord);
    aRecord = (Person) myRecord;
}

public void build() throws Exception {
    super.build();
    super.getParentRecord().setJobType(aRecord.getJobType());
    super.getParentRecord().setHairColor(aRecord.getHairColor());
    super.getParentRecord().setEyeColor(aRecord.getEyeColor());
}

I want to write a unit test for the build() method in the child class, it should

Ensure that when super.build() gets called all of the basic information on the super.getParentRecord() is populated e.g. age, gender etc.

Ensure an exception is thrown in the build() method if aRecord.getJobType() is null

Ensure an exception is thrown in the build() method if aRecord.getHairColor() is null

Ensure an exception is thrown in the build() method if aRecord.getEyeColor() is null

Body:
You have two dependencies of MyClass (Venue and Record) so you have to mock those.

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
...
Venue venueMock = mock(Venue.class);
Record recordMock = mock(Record.class);

Then in your unit test you have to create an instance of MyClass and assert the expected result:

For example: "Ensure an exception is thrown in the build() method if aRecord.getJobType() is null"

@Test(expected=RuntimeException.class)// or whatever exception you expect
public void testIfExceptionIsThrownWhengetJobTypeReturnsNull() throws Throwable {
    Venue venueMock = mock(Venue.class);   //create the mocks
    Record recordMock = mock(Record.class);//create the mocks
    when(recordMock.getJobType()).thenReturn(null); //specify the behavior of the components that are not relevant to the tests

    MyClass myClass = new MyClass(venueMock, recordMock);
    myClass.build();
    //you can make some assertions here if you expect some result instead of exception
}

Note that if you don't specify the return value of any of the mocked dependencies (with when()) it will return the default value for the return type - null for objects, 0 for primitive numbers, false for boolean, etc. So it will be best to stub all of the methods that are used in MyClass.


问:
loading clips construct with clipspy
Just installed clipspy on a windows-10 64bit; and testing in a Jupyter notebook
I have;

```<code>from clips import Environment, Symbol
import os
env = Environment
env.load('D:\\Documents\\Clips\\clipspy\\Tree_Solve_Learn.clp')
</code>```

And get this

```<code>TypeError
Traceback (most recent call last)
<ipython-input-18-a08421f4802a> in <module>()
----> 1 env.load('D:\\Documents\\Clips\\clipspy\\Tree_Solve_Learn.clp')

TypeError: load() missing 1 required positional argument: 'path'
</code>```

So got an ls

```<code> Volume in drive D is DATA
 Volume Serial Number is 443F-982E

 Directory of D:\Documents\Clips\clipspy

12/04/2017  07:52 PM    <DIR>          .

12/04/2017  07:52 PM    <DIR>          ..

12/04/2017  07:44 PM    <DIR>          .ipynb_checkpoints

12/03/2017  07:03 PM                59 1stText.py

12/03/2017  01:32 PM               925 animal.dat

10/17/2017  06:43 PM    <DIR>          clipspy

10/17/2017  06:53 PM            20,766 clipspy-0.1.0.tar.gz

12/03/2017  01:30 PM             3,373 Tree_Solve_Learn.clp

12/03/2017  09:19 PM            19,311 Untitled.ipynb

12/03/2017  09:22 PM               555 Untitled1.ipynb

12/03/2017  09:19 PM                72 Untitled2.ipynb

12/04/2017  07:52 PM             1,972 Untitled3.ipynb

               8 File(s)         47,033 bytes

               4 Dir(s)  1,862,987,104,256 bytes free
</code>```

and the .clp file is there

struggling w/ the documentation - mostly cause I am not that experienced but not a total beginner

Anybody else trying 'clipspy' in a Window's environment?

Thanks
WJ

答:
From the example it seems you are not initializing the Environment object correctly.

```<code>from clips import Environment, Symbol
import os
env = Environment()  # <--- initialize the object like this
env.load('D:\\Documents\\Clips\\clipspy\\Tree_Solve_Learn.clp')
</code>```

Title: loading clips construct with clipspy

Body:
Just installed clipspy on a windows-10 64bit; and testing in a Jupyter notebook
I have;

from clips import Environment, Symbol
import os
env = Environment
env.load('D:\\Documents\\Clips\\clipspy\\Tree_Solve_Learn.clp')

And get this

TypeError
Traceback (most recent call last)
<ipython-input-18-a08421f4802a> in <module>()
----> 1 env.load('D:\\Documents\\Clips\\clipspy\\Tree_Solve_Learn.clp')

TypeError: load() missing 1 required positional argument: 'path'

So got an ls

 Volume in drive D is DATA
 Volume Serial Number is 443F-982E

 Directory of D:\Documents\Clips\clipspy

12/04/2017  07:52 PM    <DIR>          .

12/04/2017  07:52 PM    <DIR>          ..

12/04/2017  07:44 PM    <DIR>          .ipynb_checkpoints

12/03/2017  07:03 PM                59 1stText.py

12/03/2017  01:32 PM               925 animal.dat

10/17/2017  06:43 PM    <DIR>          clipspy

10/17/2017  06:53 PM            20,766 clipspy-0.1.0.tar.gz

12/03/2017  01:30 PM             3,373 Tree_Solve_Learn.clp

12/03/2017  09:19 PM            19,311 Untitled.ipynb

12/03/2017  09:22 PM               555 Untitled1.ipynb

12/03/2017  09:19 PM                72 Untitled2.ipynb

12/04/2017  07:52 PM             1,972 Untitled3.ipynb

               8 File(s)         47,033 bytes

               4 Dir(s)  1,862,987,104,256 bytes free

and the .clp file is there

struggling w/ the documentation - mostly cause I am not that experienced but not a total beginner

Anybody else trying 'clipspy' in a Window's environment?

Thanks
WJ

Body:
From the example it seems you are not initializing the Environment object correctly.

from clips import Environment, Symbol
import os
env = Environment()  # <--- initialize the object like this
env.load('D:\\Documents\\Clips\\clipspy\\Tree_Solve_Learn.clp')


问:
ASP.NET Core 2.0 Preview 2 on IIS error 502.5
I use asp.net core 2 Preview 2.

I opened stdoutLogEnabled = "true" in web.config but the system does not write logs.

Deploying on windows server 2012 r2 gives :

Error

HTTP Error 502.5 - Process Failure.

Web.config

```<code><aspNetCore processPath="dotnet" arguments=".\App.WebHost.dll" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false" />
</code>```

Logs

Please help me.

答:
I had this same problem, even after installing the hosting bundle. The solution was in the documentation -

Restart the system or execute net stop was /y followed by net start w3svc from a command prompt to pick up a change to the system PATH.

This is done after installing the .NET Core Windows server hosting bundle.

Body:
I use asp.net core 2 Preview 2.

I opened stdoutLogEnabled = "true" in web.config but the system does not write logs.

Deploying on windows server 2012 r2 gives :

Error

HTTP Error 502.5 - Process Failure.

Web.config

<aspNetCore processPath="dotnet" arguments=".\App.WebHost.dll" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false" />

Logs

Please help me.


问:
How can I make this code shorter? Is it possible to create this in one loop?
```<code>var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');

var rw = 50;
var rh = 50;
var x = 10;
var y = 10;

for (x=10, y=10; y<240; x=x+60, y=y+57) {
  ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}
  for (x=10, y=67; y<240; x=x+60, y=y+57) {
ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}

  for (x=10, y=124; y<240; x=x+60, y=y+57) {
ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}

  for (x=10, y=181; y<240; x=x+60, y=y+57) {
ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}

  for (x=10, y=238; y<240; x=x+60, y=y+57) {
ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}
</code>```

It's a javascript code. In my html is this

```<code><canvas id="myCanvas" height="300" width="450" style="border: 1px solid black"></canvas>
</code>```

My task is, come this code together below one loop.

Thank you so much for your help!

答:
You could move ctx.fillStyle outside of the loops and take a nested loop with just a count for each element/rectangle and take this value with a factor for the position for drawing.

You want 5 lines of dots, starting with one dot in the first line until you reach 5 dotes in the last line.

For this approach, you could take two nested loops, the outer for the lines/y-values and the inner for the columns/x-values.

For getting the right position, you could apply a factor and the given offset.

var canvas = document.getElementById('myCanvas'),
    ctx = canvas.getContext('2d'),
    rw = 50,
    rh = 50,
    x = 10,
    y = 10,
    i, j;

ctx.fillStyle = "orange";

for (j = 0; j < 5; j++) {
    for (i = 0; i <= j; i++) {
        ctx.fillRect(x + i * 60, y + j * 57, rw, rh);
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="myCanvas" height="300" width="450" style="border: 1px solid black"></canvas></code>```

Body:
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');

var rw = 50;
var rh = 50;
var x = 10;
var y = 10;

for (x=10, y=10; y<240; x=x+60, y=y+57) {
  ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}
  for (x=10, y=67; y<240; x=x+60, y=y+57) {
ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}

  for (x=10, y=124; y<240; x=x+60, y=y+57) {
ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}

  for (x=10, y=181; y<240; x=x+60, y=y+57) {
ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}

  for (x=10, y=238; y<240; x=x+60, y=y+57) {
ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}

It's a javascript code. In my html is this

<canvas id="myCanvas" height="300" width="450" style="border: 1px solid black"></canvas>

My task is, come this code together below one loop.

Thank you so much for your help!

Body:
You could move ctx.fillStyle outside of the loops and take a nested loop with just a count for each element/rectangle and take this value with a factor for the position for drawing.

You want 5 lines of dots, starting with one dot in the first line until you reach 5 dotes in the last line.

For this approach, you could take two nested loops, the outer for the lines/y-values and the inner for the columns/x-values.

For getting the right position, you could apply a factor and the given offset.

var canvas = document.getElementById('myCanvas'),
    ctx = canvas.getContext('2d'),
    rw = 50,
    rh = 50,
    x = 10,
    y = 10,
    i, j;

ctx.fillStyle = "orange";

for (j = 0; j < 5; j++) {
    for (i = 0; i <= j; i++) {
        ctx.fillRect(x + i * 60, y + j * 57, rw, rh);
    }
}

<canvas id="myCanvas" height="300" width="450" style="border: 1px solid black"></canvas>


问:
after a integer input, I want to concatenate two strings, one already initialize and another one is user input
```<code>int i = 4;
String s ="Hi ";

Scanner scan = new Scanner(System.in);

System.out.println("enter Integer");
int m=scan.nextInt();

System.out.println("enter string");
*String t = scan.next();
**String t = scan.nextLine();

System.out.println(i+m);
System.out.println(s+t);
</code>```

<p>when I use *scan.next() then it will only read a single word, another side when I use **scan.nextLine() it will directly show the output </p>

答:
Call nextLine() after nextint() to consume \n.

```<code>int a = scanner.nextInt()
scanner.nextLine() // to flush end of line
 ... // Then read string
String s = scanner.next()
</code>```

The whole story

After Entering a number, Say 5..
the stream looks like

5\n

When nextInt() is called,
the stream looks like

\n

After you enter string, say `hi

\nhi

After next() is called
the stream looks like

hi

The cause of problem: next() consume till \n.

When it is called \n was first character in the stream. so it read empty string "".

Body:
int i = 4;
String s ="Hi ";

Scanner scan = new Scanner(System.in);

System.out.println("enter Integer");
int m=scan.nextInt();

System.out.println("enter string");
*String t = scan.next();
**String t = scan.nextLine();

System.out.println(i+m);
System.out.println(s+t);

when I use *scan.next() then it will only read a single word, another side when I use **scan.nextLine() it will directly show the output

Body:
Call nextLine() after nextint() to consume \n.

int a = scanner.nextInt()
scanner.nextLine() // to flush end of line
 ... // Then read string
String s = scanner.next()

The whole story

After Entering a number, Say 5..
the stream looks like

5\n

When nextInt() is called,
the stream looks like

\n

After you enter string, say `hi

\nhi

After next() is called
the stream looks like

hi

The cause of problem: next() consume till \n.

When it is called \n was first character in the stream. so it read empty string "".


问:
MongoDB aggregate query to SpringDataMongoDB
I have below MongoDB aggregate query and would like to have it's equivalent SpringData Mongodb query.

MongoDB Aggregate Query :

```<code>db.response.aggregate(
        // Pipeline
        [
            // Stage 1 : Group by Emotion & Month
            {
                $group: {
                    _id: {
                        emotion: "$emotion",
                        category: "$category"
                    },
                    count: {
                        $sum: 1
                    },
                    point: {
                        $first: '$point'
                    }
                }
            },
            // Stage 2 : Total Points
            {
                $addFields: {
                    "totalPoint": {
                        $multiply: ["$point", "$count"]
                    }
                }
            },
                        // Stage3 : Group By Category - Overall Response Total & totalFeedbacks
            {
                $group: {
                    _id: '$_id.category',
                    totalFeedbacks: {
                        $sum: "$count"
                    },
                    overallResponseTotal: {
                        $sum: "$totalPoint"
                    }
                }
            },
                        // Stage4 - Overall Response Total & totalFeedbacks
            {
                $project: {
                    _id: 1,
                    overallResponseTotal: '$overallResponseTotal',
                    maxTotalFrom: {
                        "$multiply": ["$totalFeedbacks", 3.0]
                    },
                    percent: {
                        "$multiply": [{
                            "$divide": ["$overallResponseTotal", "$maxTotalFrom"]
                        }, 100.0]
                    }
                }
            },
                        // Stage4 - Percentage Monthwise
                {
                    $project: {
                        _id: 1,
                        overallResponseTotal: 1,
                        maxTotalFrom: 1,
                        percent: {
                            "$multiply": [{
                                "$divide": ["$overallResponseTotal", "$maxTotalFrom"]
                            }, 100.0]
                        }
                    }

                }
            ]
);
</code>```

I have tried it's equivalent in Spring Data but got stuck at Stage 2 on how to convert "$addFields" to java code. Though I search about it on multiple sites but couldn't find anything useful. Please see my equivalent java code for Stage 1.

```<code>//Stage 1 -Group By Emotion and Category and return it's count

GroupOperation groupEmotionAndCategory = Aggregation.group("emotion","category").count().as("count").first("point")
                        .as("point");

Aggregation aggregation = Aggregation.newAggregation(groupEmotionAndCategory);

AggregationResults<CategoryWiseEmotion> output = mongoTemplate.aggregate(aggregation, Response.class, CategoryWiseEmotion.class);
</code>```

Any helps will be highly appreciated.

答:
$addFields is not yet supported by Spring Data Mongodb.

One workaround is to pass the raw aggregation pipeline to Spring.

But since you have a limited number of fields after stage 1, you could also downgrade stage 2 to a projection:

```<code>{
    $project: {
        // _id is included by default
        "count" : 1, // include count
        "point" : 1, // include point
        "totalPoint": {
            $multiply: ["$point", "$count"] // compute totalPoint
        }
    }
}
</code>```

I haven't tested it myself, but this projection should translate to something like:

```<code>ProjectionOperation p = project("count", "point").and("point").multiply(Fields.field("count")).as("totalPoint");
</code>```

Then you can translate stage 3, 4 and 5 similarly and pass the whole pipeline to Aggregation.aggregate().

Body:
I have below MongoDB aggregate query and would like to have it's equivalent SpringData Mongodb query.

MongoDB Aggregate Query :

db.response.aggregate(
        // Pipeline
        [
            // Stage 1 : Group by Emotion & Month
            {
                $group: {
                    _id: {
                        emotion: "$emotion",
                        category: "$category"
                    },
                    count: {
                        $sum: 1
                    },
                    point: {
                        $first: '$point'
                    }
                }
            },
            // Stage 2 : Total Points
            {
                $addFields: {
                    "totalPoint": {
                        $multiply: ["$point", "$count"]
                    }
                }
            },
                        // Stage3 : Group By Category - Overall Response Total & totalFeedbacks
            {
                $group: {
                    _id: '$_id.category',
                    totalFeedbacks: {
                        $sum: "$count"
                    },
                    overallResponseTotal: {
                        $sum: "$totalPoint"
                    }
                }
            },
                        // Stage4 - Overall Response Total & totalFeedbacks
            {
                $project: {
                    _id: 1,
                    overallResponseTotal: '$overallResponseTotal',
                    maxTotalFrom: {
                        "$multiply": ["$totalFeedbacks", 3.0]
                    },
                    percent: {
                        "$multiply": [{
                            "$divide": ["$overallResponseTotal", "$maxTotalFrom"]
                        }, 100.0]
                    }
                }
            },
                        // Stage4 - Percentage Monthwise
                {
                    $project: {
                        _id: 1,
                        overallResponseTotal: 1,
                        maxTotalFrom: 1,
                        percent: {
                            "$multiply": [{
                                "$divide": ["$overallResponseTotal", "$maxTotalFrom"]
                            }, 100.0]
                        }
                    }

                }
            ]
);

I have tried it's equivalent in Spring Data but got stuck at Stage 2 on how to convert "$addFields" to java code. Though I search about it on multiple sites but couldn't find anything useful. Please see my equivalent java code for Stage 1.

//Stage 1 -Group By Emotion and Category and return it's count

GroupOperation groupEmotionAndCategory = Aggregation.group("emotion","category").count().as("count").first("point")
                        .as("point");

Aggregation aggregation = Aggregation.newAggregation(groupEmotionAndCategory);

AggregationResults<CategoryWiseEmotion> output = mongoTemplate.aggregate(aggregation, Response.class, CategoryWiseEmotion.class);

Any helps will be highly appreciated.

Body:
$addFields is not yet supported by Spring Data Mongodb.

One workaround is to pass the raw aggregation pipeline to Spring.

But since you have a limited number of fields after stage 1, you could also downgrade stage 2 to a projection:

{
    $project: {
        // _id is included by default
        "count" : 1, // include count
        "point" : 1, // include point
        "totalPoint": {
            $multiply: ["$point", "$count"] // compute totalPoint
        }
    }
}

I haven't tested it myself, but this projection should translate to something like:

ProjectionOperation p = project("count", "point").and("point").multiply(Fields.field("count")).as("totalPoint");

Then you can translate stage 3, 4 and 5 similarly and pass the whole pipeline to Aggregation.aggregate().


问:
HTML5 - SVG elements acting differently on Firefox and Chrome
My goal is to align a 'div' below a 'textarea' inside a 'svg' and 'g' element. On Firefox it works, on Chrome it does not.

Basically i apply a transform at the 'g' element and that element goes correctly to the position i wanted. However, having nested elements with the "class" property are incorrectly positioned, and what i mean is: having a single 'i' element without childs works fine, having a 'span' does not.

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<svg id="svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="display: inline; width: inherit; min-width: inherit; max-width: inherit; height: inherit; min-height: inherit; max-height: inherit; position: fixed;" version="1.1" >
 <g id="g1" transform="translate(130,30) ">
  <foreignObject x="0" y="0" width="150" height="150" overflow="visible" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
            <textarea style="background: white; color: black; border-radius:6px;border-style: solid; border-width: 3px;  width: 140px; font-size: 12px; resize: none; height: 50px">test</textarea>

  </foreignObject>
 </g>
</svg>```
</div>
</div>
</p>

```<svg id="svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="display: inline; width: inherit; min-width: inherit; max-width: inherit; height: inherit; min-height: inherit; max-height: inherit; position: fixed;" version="1.1" >
    <g id="g1" transform="translate(130,30) ">
        <foreignObject x="0" y="0" width="150" height="150" overflow="visible" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
            <textarea style="background: white; color: black; border-radius:6px;border-style: solid; border-width: 3px;  width: 140px; font-size: 12px; resize: none; height: 50px">test</textarea>

        </foreignObject>
    </g>
</svg>
```

Run the fiddle on both browsers to see the problem i referred:
Fiddle

Here are the images:

Firefox:
Chrome:

Thank you in advance o7

EDIT1:

Most likely a bug in chrome. You should open an issue on their bug-tracker. (when you do inspect the element, the bbox is drawn at the correct position, but the element itself is rendered completely off);

regarding Kaiido aswer, it really seems a issue with Chrome since there are multiple instances relating svg and chrome. another fun-fact is that the icon is rendered based on the height of the textarea, more precisely, if i put 200px as the textarea height, the icon would be further down aswell like and invisible textare was above.

答: try to remove this part from the code.

Body:
My goal is to align a 'div' below a 'textarea' inside a 'svg' and 'g' element. On Firefox it works, on Chrome it does not.

Basically i apply a transform at the 'g' element and that element goes correctly to the position i wanted. However, having nested elements with the "class" property are incorrectly positioned, and what i mean is: having a single 'i' element without childs works fine, having a 'span' does not.

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<svg id="svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="display: inline; width: inherit; min-width: inherit; max-width: inherit; height: inherit; min-height: inherit; max-height: inherit; position: fixed;" version="1.1" >
 <g id="g1" transform="translate(130,30) ">
  <foreignObject x="0" y="0" width="150" height="150" overflow="visible" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
            <textarea style="background: white; color: black; border-radius:6px;border-style: solid; border-width: 3px;  width: 140px; font-size: 12px; resize: none; height: 50px">test</textarea>

  </foreignObject>
 </g>
</svg>

<svg id="svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="display: inline; width: inherit; min-width: inherit; max-width: inherit; height: inherit; min-height: inherit; max-height: inherit; position: fixed;" version="1.1" >
    <g id="g1" transform="translate(130,30) ">
        <foreignObject x="0" y="0" width="150" height="150" overflow="visible" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
            <textarea style="background: white; color: black; border-radius:6px;border-style: solid; border-width: 3px;  width: 140px; font-size: 12px; resize: none; height: 50px">test</textarea>

        </foreignObject>
    </g>
</svg>

Run the fiddle on both browsers to see the problem i referred:
Fiddle

Here are the images:

Firefox:
Chrome:

Thank you in advance o7

EDIT1:

Most likely a bug in chrome. You should open an issue on their bug-tracker. (when you do inspect the element, the bbox is drawn at the correct position, but the element itself is rendered completely off);

regarding Kaiido aswer, it really seems a issue with Chrome since there are multiple instances relating svg and chrome. another fun-fact is that the icon is rendered based on the height of the textarea, more precisely, if i put 200px as the textarea height, the icon would be further down aswell like and invisible textare was above.

Body: try to remove this part from the code.


问:
Linux Device Driver Error for the Keyboard Interrupt Handling
During the way to learn how to program the Keyboard interrupt handling in Kernel mode, and following the example below, I get such an error after loading the driver in kernel space. </p>

```<code>#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/workqueue.h>
#include <linux/interrupt.h>
#include <asm/io.h>

MODULE_LICENSE("GPL");
irqreturn_t irq_handler(int irq, void *dev_id, struct pt_regs *regs) {
    static unsigned char scancode, status;
    status   = inb(0x64);
    scancode = inb(0x60);
    switch (scancode)
    {
    case 0x01:  printk (KERN_INFO "! You pressed Esc ...\n");
          break;
    case 0x3B:  printk (KERN_INFO "! You pressed F1 ...\n");
          break;
    case 0x3C:  printk (KERN_INFO "! You pressed F2 ...\n");
          break;
    default: break;
    }
    return IRQ_HANDLED;
}
static int __init irq_ex_init(void) {
    printk (KERN_INFO "DEVICE OPEN...\n");
    free_irq(1,NULL);
    return request_irq (1,(irq_handler_t)irq_handler,IRQF_SHARED,"test_keyboard_irq_handler",(void*)(irq_handler));
}
static void __exit irq_ex_exit(void) {
    printk (KERN_INFO "!DEVICE CLOSE...\n");
    free_irq(1,(void*)(irq_handler));
}
module_init(irq_ex_init);
module_exit(irq_ex_exit);
</code>```

<p>The unloading also work fine, but after loading by insmod, I get such an error. I was wondering if somebody can explain it.
I use Ubuntu 16.04.2 LTS. </p>

```<code>Dec  5 12:02:01 iman kernel: [  502.506500] ------------[ cut here ]------------
Dec  5 12:02:01 iman kernel: [  502.506510] WARNING: CPU: 1 PID: 4240 at /build/linux-hwe-zOpU13/linux-hwe-4.10.0/kernel/irq/manage.c:1484 __free_irq+0xa4/0x290
Dec  5 12:02:01 iman kernel: [  502.506511] Trying to free already-free IRQ 1
Dec  5 12:02:01 iman kernel: [  502.506512] Modules linked in: DDriver(OE+) Driver(OE) xt_CHECKSUM iptable_mangle ipt_MASQUERADE nf_nat_masquerade_ipv4 iptable_nat nf_nat_ipv4 nf_nat libcrc32c nf_conntrack_ipv4 nf_defrag_ipv4 xt_conntrack nf_conntrack ipt_REJECT nf_reject_ipv4 xt_tcpudp bridge stp llc ebtable_filter ebtables ip6table_filter ip6_tables iptable_filter ip_tables x_tables snd_hda_codec_hdmi eeepc_wmi asus_wmi sparse_keymap intel_rapl x86_pkg_temp_thermal intel_powerclamp coretemp crct10dif_pclmul crc32_pclmul ghash_clmulni_intel cryptd intel_cstate intel_rapl_perf joydev input_leds snd_seq_midi snd_seq_midi_event snd_hda_codec_realtek snd_hda_codec_generic snd_rawmidi snd_hda_intel snd_hda_codec lpc_ich snd_seq snd_hda_core snd_hwdep snd_seq_device snd_pcm snd_timer snd soundcore mei_me shpchp mei mac_hid kvm binfmt_misc
Dec  5 12:02:01 iman kernel: [  502.506560]  irqbypass parport_pc ppdev lp parport autofs4 hid_cherry hid_generic usbhid hid nouveau mxm_wmi i2c_algo_bit ttm drm_kms_helper ahci syscopyarea libahci sysfillrect r8169 sysimgblt mii fb_sys_fops drm wmi fjes video [last unloaded: DDriver]
Dec  5 12:02:01 iman kernel: [  502.506584] CPU: 1 PID: 4240 Comm: insmod Tainted: G        W  OE   4.10.0-40-generic #44~16.04.1-Ubuntu
Dec  5 12:02:01 iman kernel: [  502.506585] Hardware name: ASUSTeK Computer INC. V-P8H67E/V-P8H67E, BIOS 1401 12/12/2011
Dec  5 12:02:01 iman kernel: [  502.506586] Call Trace:
Dec  5 12:02:01 iman kernel: [  502.506593]  dump_stack+0x63/0x90
Dec  5 12:02:01 iman kernel: [  502.506596]  __warn+0xcb/0xf0
Dec  5 12:02:01 iman kernel: [  502.506598]  warn_slowpath_fmt+0x5f/0x80
Dec  5 12:02:01 iman kernel: [  502.506602]  __free_irq+0xa4/0x290
Dec  5 12:02:01 iman kernel: [  502.506604]  free_irq+0x39/0x90
Dec  5 12:02:01 iman kernel: [  502.506607]  ? 0xffffffffc0183000
Dec  5 12:02:01 iman kernel: [  502.506611]  irq_ex_init+0x26/0x1000 [DDriver]
Dec  5 12:02:01 iman kernel: [  502.506614]  do_one_initcall+0x53/0x1c0
Dec  5 12:02:01 iman kernel: [  502.506619]  ? kmem_cache_alloc_trace+0x152/0x1c0
Dec  5 12:02:01 iman kernel: [  502.506624]  do_init_module+0x5f/0x1ff
Dec  5 12:02:01 iman kernel: [  502.506629]  load_module+0x1825/0x1bf0
Dec  5 12:02:01 iman kernel: [  502.506632]  ? __symbol_put+0x60/0x60
Dec  5 12:02:01 iman kernel: [  502.506636]  ? ima_post_read_file+0x7d/0xa0
Dec  5 12:02:01 iman kernel: [  502.506640]  ? security_kernel_post_read_file+0x6b/0x80
Dec  5 12:02:01 iman kernel: [  502.506644]  SYSC_finit_module+0xdf/0x110
Dec  5 12:02:01 iman kernel: [  502.506648]  SyS_finit_module+0xe/0x10
Dec  5 12:02:01 iman kernel: [  502.506652]  entry_SYSCALL_64_fastpath+0x1e/0xad
Dec  5 12:02:01 iman kernel: [  502.506655] RIP: 0033:0x7f0f6a2a3499
Dec  5 12:02:01 iman kernel: [  502.506656] RSP: 002b:00007fff1b8c96f8 EFLAGS: 00000202 ORIG_RAX: 0000000000000139
Dec  5 12:02:01 iman kernel: [  502.506659] RAX: ffffffffffffffda RBX: 00007f0f6a566b20 RCX: 00007f0f6a2a3499
Dec  5 12:02:01 iman kernel: [  502.506661] RDX: 0000000000000000 RSI: 000055649bd65246 RDI: 0000000000000003
Dec  5 12:02:01 iman kernel: [  502.506663] RBP: 0000000000001011 R08: 0000000000000000 R09: 00007f0f6a568ea0
Dec  5 12:02:01 iman kernel: [  502.506664] R10: 0000000000000003 R11: 0000000000000202 R12: 00007f0f6a566b78
Dec  5 12:02:01 iman kernel: [  502.506665] R13: 00007f0f6a566b78 R14: 000000000000270f R15: 00007f0f6a5671a8
Dec  5 12:02:01 iman kernel: [  502.506668] ---[ end trace 4b89a13407b08cea ]---
</code>```

答:
free_irq() should never be called with NULL, you should pass the unique handler that you have used during registering the IRQ.

free_irq(1,(void*)(irq_handler)); //In your case

You should not free the IRQ in init function, free_irq() should be called after register_irq() call has been made in the same module.

Even if you call free_irq(1,(void*)(irq_handler)); in init function the kernel will taint as the handler was not previously registered.

You need to let the kernel know which handler you want to remove.

As you don't know which module has already registered the same IRQ so the logic is to use a shared IRQ in your module which you have already implemented in your code.

In short, do not free the IRQ in init function.

Body:
During the way to learn how to program the Keyboard interrupt handling in Kernel mode, and following the example below, I get such an error after loading the driver in kernel space.

#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/workqueue.h>
#include <linux/interrupt.h>
#include <asm/io.h>

MODULE_LICENSE("GPL");
irqreturn_t irq_handler(int irq, void *dev_id, struct pt_regs *regs) {
    static unsigned char scancode, status;
    status   = inb(0x64);
    scancode = inb(0x60);
    switch (scancode)
    {
    case 0x01:  printk (KERN_INFO "! You pressed Esc ...\n");
          break;
    case 0x3B:  printk (KERN_INFO "! You pressed F1 ...\n");
          break;
    case 0x3C:  printk (KERN_INFO "! You pressed F2 ...\n");
          break;
    default: break;
    }
    return IRQ_HANDLED;
}
static int __init irq_ex_init(void) {
    printk (KERN_INFO "DEVICE OPEN...\n");
    free_irq(1,NULL);
    return request_irq (1,(irq_handler_t)irq_handler,IRQF_SHARED,"test_keyboard_irq_handler",(void*)(irq_handler));
}
static void __exit irq_ex_exit(void) {
    printk (KERN_INFO "!DEVICE CLOSE...\n");
    free_irq(1,(void*)(irq_handler));
}
module_init(irq_ex_init);
module_exit(irq_ex_exit);

The unloading also work fine, but after loading by insmod, I get such an error. I was wondering if somebody can explain it.
I use Ubuntu 16.04.2 LTS.

Dec  5 12:02:01 iman kernel: [  502.506500] ------------[ cut here ]------------
Dec  5 12:02:01 iman kernel: [  502.506510] WARNING: CPU: 1 PID: 4240 at /build/linux-hwe-zOpU13/linux-hwe-4.10.0/kernel/irq/manage.c:1484 __free_irq+0xa4/0x290
Dec  5 12:02:01 iman kernel: [  502.506511] Trying to free already-free IRQ 1
Dec  5 12:02:01 iman kernel: [  502.506512] Modules linked in: DDriver(OE+) Driver(OE) xt_CHECKSUM iptable_mangle ipt_MASQUERADE nf_nat_masquerade_ipv4 iptable_nat nf_nat_ipv4 nf_nat libcrc32c nf_conntrack_ipv4 nf_defrag_ipv4 xt_conntrack nf_conntrack ipt_REJECT nf_reject_ipv4 xt_tcpudp bridge stp llc ebtable_filter ebtables ip6table_filter ip6_tables iptable_filter ip_tables x_tables snd_hda_codec_hdmi eeepc_wmi asus_wmi sparse_keymap intel_rapl x86_pkg_temp_thermal intel_powerclamp coretemp crct10dif_pclmul crc32_pclmul ghash_clmulni_intel cryptd intel_cstate intel_rapl_perf joydev input_leds snd_seq_midi snd_seq_midi_event snd_hda_codec_realtek snd_hda_codec_generic snd_rawmidi snd_hda_intel snd_hda_codec lpc_ich snd_seq snd_hda_core snd_hwdep snd_seq_device snd_pcm snd_timer snd soundcore mei_me shpchp mei mac_hid kvm binfmt_misc
Dec  5 12:02:01 iman kernel: [  502.506560]  irqbypass parport_pc ppdev lp parport autofs4 hid_cherry hid_generic usbhid hid nouveau mxm_wmi i2c_algo_bit ttm drm_kms_helper ahci syscopyarea libahci sysfillrect r8169 sysimgblt mii fb_sys_fops drm wmi fjes video [last unloaded: DDriver]
Dec  5 12:02:01 iman kernel: [  502.506584] CPU: 1 PID: 4240 Comm: insmod Tainted: G        W  OE   4.10.0-40-generic #44~16.04.1-Ubuntu
Dec  5 12:02:01 iman kernel: [  502.506585] Hardware name: ASUSTeK Computer INC. V-P8H67E/V-P8H67E, BIOS 1401 12/12/2011
Dec  5 12:02:01 iman kernel: [  502.506586] Call Trace:
Dec  5 12:02:01 iman kernel: [  502.506593]  dump_stack+0x63/0x90
Dec  5 12:02:01 iman kernel: [  502.506596]  __warn+0xcb/0xf0
Dec  5 12:02:01 iman kernel: [  502.506598]  warn_slowpath_fmt+0x5f/0x80
Dec  5 12:02:01 iman kernel: [  502.506602]  __free_irq+0xa4/0x290
Dec  5 12:02:01 iman kernel: [  502.506604]  free_irq+0x39/0x90
Dec  5 12:02:01 iman kernel: [  502.506607]  ? 0xffffffffc0183000
Dec  5 12:02:01 iman kernel: [  502.506611]  irq_ex_init+0x26/0x1000 [DDriver]
Dec  5 12:02:01 iman kernel: [  502.506614]  do_one_initcall+0x53/0x1c0
Dec  5 12:02:01 iman kernel: [  502.506619]  ? kmem_cache_alloc_trace+0x152/0x1c0
Dec  5 12:02:01 iman kernel: [  502.506624]  do_init_module+0x5f/0x1ff
Dec  5 12:02:01 iman kernel: [  502.506629]  load_module+0x1825/0x1bf0
Dec  5 12:02:01 iman kernel: [  502.506632]  ? __symbol_put+0x60/0x60
Dec  5 12:02:01 iman kernel: [  502.506636]  ? ima_post_read_file+0x7d/0xa0
Dec  5 12:02:01 iman kernel: [  502.506640]  ? security_kernel_post_read_file+0x6b/0x80
Dec  5 12:02:01 iman kernel: [  502.506644]  SYSC_finit_module+0xdf/0x110
Dec  5 12:02:01 iman kernel: [  502.506648]  SyS_finit_module+0xe/0x10
Dec  5 12:02:01 iman kernel: [  502.506652]  entry_SYSCALL_64_fastpath+0x1e/0xad
Dec  5 12:02:01 iman kernel: [  502.506655] RIP: 0033:0x7f0f6a2a3499
Dec  5 12:02:01 iman kernel: [  502.506656] RSP: 002b:00007fff1b8c96f8 EFLAGS: 00000202 ORIG_RAX: 0000000000000139
Dec  5 12:02:01 iman kernel: [  502.506659] RAX: ffffffffffffffda RBX: 00007f0f6a566b20 RCX: 00007f0f6a2a3499
Dec  5 12:02:01 iman kernel: [  502.506661] RDX: 0000000000000000 RSI: 000055649bd65246 RDI: 0000000000000003
Dec  5 12:02:01 iman kernel: [  502.506663] RBP: 0000000000001011 R08: 0000000000000000 R09: 00007f0f6a568ea0
Dec  5 12:02:01 iman kernel: [  502.506664] R10: 0000000000000003 R11: 0000000000000202 R12: 00007f0f6a566b78
Dec  5 12:02:01 iman kernel: [  502.506665] R13: 00007f0f6a566b78 R14: 000000000000270f R15: 00007f0f6a5671a8
Dec  5 12:02:01 iman kernel: [  502.506668] ---[ end trace 4b89a13407b08cea ]---


问:
How to hide or change the selection decorator on html buttons using bootstrap or css?
I am using arrows buttons like these ones:

```<code><button type="button" class="btn btn-default btn-arrow-left" > </button>
</code>```

```<code>body { /* just for this demo. */
    padding: 30px;
}
.btn { /* just for this demo. */
    margin-top: 5px;
}
.btn-arrow-right,
.btn-arrow-left {
    position: relative;
    padding-left: 18px;
    padding-right: 18px;
}
.btn-arrow-right {
    padding-left: 36px;
}
.btn-arrow-left {
    padding-right: 36px;
}
.btn-arrow-right:before,
.btn-arrow-right:after,
.btn-arrow-left:before,
.btn-arrow-left:after { /* make two squares (before and after), looking similar to the button */
    content:"";
    position: absolute;
    top: 5px; /* move it down because of rounded corners */
    width: 22px; /* same as height */
    height: 22px; /* button_outer_height / sqrt(2) */
    background: inherit; /* use parent background */
    border: inherit; /* use parent border */
    border-left-color: transparent; /* hide left border */
    border-bottom-color: transparent; /* hide bottom border */
    border-radius: 0px 4px 0px 0px; /* round arrow corner, the shorthand property doesn't accept "inherit" so it is set to 4px */
    -webkit-border-radius: 0px 4px 0px 0px;
    -moz-border-radius: 0px 4px 0px 0px;
}
.btn-arrow-right:before,
.btn-arrow-right:after {
    transform: rotate(45deg); /* rotate right arrow squares 45 deg to point right */
    -webkit-transform: rotate(45deg);
    -moz-transform: rotate(45deg);
    -o-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
}
.btn-arrow-left:before,
.btn-arrow-left:after {
    transform: rotate(225deg); /* rotate left arrow squares 225 deg to point left */
    -webkit-transform: rotate(225deg);
    -moz-transform: rotate(225deg);
    -o-transform: rotate(225deg);
    -ms-transform: rotate(225deg);
}
.btn-arrow-right:before,
.btn-arrow-left:before { /* align the "before" square to the left */
    left: -11px;
}
.btn-arrow-right:after,
.btn-arrow-left:after { /* align the "after" square to the right */
    right: -11px;
}
.btn-arrow-right:after,
.btn-arrow-left:before { /* bring arrow pointers to front */
    z-index: 1;
}
.btn-arrow-right:before,
.btn-a
</code>```

But I do not know how can I hide or change the yellow decorator when it is selected. Is it possible?

NOTE: I am working with Bootstrap v3.3.7

答:
You can set the outline property to none when on focus, like so:

```<code>.btn:focus, .btn:active{
    outline:none !important;
}
</code>```

Here is your updated code

Body:
I am using arrows buttons like these ones:

<button type="button" class="btn btn-default btn-arrow-left" > </button>

body { /* just for this demo. */
    padding: 30px;
}
.btn { /* just for this demo. */
    margin-top: 5px;
}
.btn-arrow-right,
.btn-arrow-left {
    position: relative;
    padding-left: 18px;
    padding-right: 18px;
}
.btn-arrow-right {
    padding-left: 36px;
}
.btn-arrow-left {
    padding-right: 36px;
}
.btn-arrow-right:before,
.btn-arrow-right:after,
.btn-arrow-left:before,
.btn-arrow-left:after { /* make two squares (before and after), looking similar to the button */
    content:"";
    position: absolute;
    top: 5px; /* move it down because of rounded corners */
    width: 22px; /* same as height */
    height: 22px; /* button_outer_height / sqrt(2) */
    background: inherit; /* use parent background */
    border: inherit; /* use parent border */
    border-left-color: transparent; /* hide left border */
    border-bottom-color: transparent; /* hide bottom border */
    border-radius: 0px 4px 0px 0px; /* round arrow corner, the shorthand property doesn't accept "inherit" so it is set to 4px */
    -webkit-border-radius: 0px 4px 0px 0px;
    -moz-border-radius: 0px 4px 0px 0px;
}
.btn-arrow-right:before,
.btn-arrow-right:after {
    transform: rotate(45deg); /* rotate right arrow squares 45 deg to point right */
    -webkit-transform: rotate(45deg);
    -moz-transform: rotate(45deg);
    -o-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
}
.btn-arrow-left:before,
.btn-arrow-left:after {
    transform: rotate(225deg); /* rotate left arrow squares 225 deg to point left */
    -webkit-transform: rotate(225deg);
    -moz-transform: rotate(225deg);
    -o-transform: rotate(225deg);
    -ms-transform: rotate(225deg);
}
.btn-arrow-right:before,
.btn-arrow-left:before { /* align the "before" square to the left */
    left: -11px;
}
.btn-arrow-right:after,
.btn-arrow-left:after { /* align the "after" square to the right */
    right: -11px;
}
.btn-arrow-right:after,
.btn-arrow-left:before { /* bring arrow pointers to front */
    z-index: 1;
}
.btn-arrow-right:before,
.btn-a

But I do not know how can I hide or change the yellow decorator when it is selected. Is it possible?

NOTE: I am working with Bootstrap v3.3.7

Body:
You can set the outline property to none when on focus, like so:

.btn:focus, .btn:active{
    outline:none !important;
}

Here is your updated code


问:
Converting a 24 khz mp3 audio to 16 khz wav using libmad library in C?
I m writing a small application in C that receives mp3 audio data from a cloud based voice engine and converts it to pcm data (wav format) at 16 khz sample rate. I m using libmad for decoding mp3 data but i m not finding an option to downsample it from 24 khz to 16 khz. Can we do this using libmad or do we need another separate library to achieve this ? Any information relevant to this would be helpful. Thanks,

~Reev

答:
The lamehelper library can be used for this...
Use this website to help you:
https://www.codeproject.com/Articles/656543/The-LAME-wrapper-An-audio-converter

Your code should look somewhat like this-

```<code>#include "lameHelper.h"
struct settings_t //make a struct to store settings
{
    char* title;
    char* artist;
    char* album;
    char* comment;
    char* year;
    char* track;
    char* genre;
    char* albumart;

    encode_channel_e channels;
    bitrate_e abr_bitrate;
    bitrate_e cbr_bitrate;
    int quality;
    encode_mode_e enc_mode;
    samplerate_e resample_frequency; // This is what you are going to need
    samplerate_e in_samplerate;

    //The constructor: used to set default values
    settings_t();
};

int main()
{
    settings_t settings;
    settings.enc_mode = EM_ABR;
    settings.abr_bitrate = BR_128kbps;//If you are going to use ABR encode mode @ 128kbps
    settings.album = "The Album";//Setting the album (id3 tag)
    settings.albumart = "c:/.../art.jpg";//Setting the albumart
    settings.track = "01";//Setting the track

    //..and various other settings

    lameHelper lhHandle;
    lhHandle.encode("c:/.../song.mp3", "c:/.../song.wav", settings);

    return 0;
}
</code>```

Body:
The lamehelper library can be used for this...
Use this website to help you:
https://www.codeproject.com/Articles/656543/The-LAME-wrapper-An-audio-converter

Your code should look somewhat like this-

#include "lameHelper.h"
struct settings_t //make a struct to store settings
{
    char* title;
    char* artist;
    char* album;
    char* comment;
    char* year;
    char* track;
    char* genre;
    char* albumart;

    encode_channel_e channels;
    bitrate_e abr_bitrate;
    bitrate_e cbr_bitrate;
    int quality;
    encode_mode_e enc_mode;
    samplerate_e resample_frequency; // This is what you are going to need
    samplerate_e in_samplerate;

    //The constructor: used to set default values
    settings_t();
};

int main()
{
    settings_t settings;
    settings.enc_mode = EM_ABR;
    settings.abr_bitrate = BR_128kbps;//If you are going to use ABR encode mode @ 128kbps
    settings.album = "The Album";//Setting the album (id3 tag)
    settings.albumart = "c:/.../art.jpg";//Setting the albumart
    settings.track = "01";//Setting the track

    //..and various other settings

    lameHelper lhHandle;
    lhHandle.encode("c:/.../song.mp3", "c:/.../song.wav", settings);

    return 0;
}


问:
Showing the actual value of complex type parameter with NUnit in the reports
I am stuck at finding one functionality that NUnit provides which I almost certain that I saw it before and I thought myself I will use it, but sadly I didn't pin it somewhere.

We are writing our tests like so:

```<code>[Test]
public void Post_StakeToDifferetnSelectionsViaBetsBetIdEndpoint_ReturnsCorrectData(
        [ValueSource(typeof(JsonContextCache), nameof(JsonContextCache.RandomThreeUniqueSelecionIds))] string[] selectionIds,
        [ValueSource(typeof(TestData), nameof(TestData.OddStyles))] OddStyle oddStyle,
        [Values(true, false)] bool logged)
</code>```

Problem with this approach is that when we supply ValueSource or TestCaseSource attributes with complex types (like string[], custom types) results in our CI environments from NUnit are like so:

```<code>Post_StakeToDifferetnSelectionsViaBetsBetIdEndpoint_ReturnsCorrectData(System.String[],European,True)
</code>```

What I want is, instead of this System.String[] to show the array values, but I don't know how can I make Nunit do that for me.

答:
Short answer:

It's not possible in your situation, because you are using [TestCaseSource], which leaves it entirely up to NUnit to assemble the test cases and name them. There are workarounds, but they are rather inconvenient.

Longer answer, edited from https:github.com/nunit/docs/issues/244:

You can change the naming of individual test cases in NUnit in certain circumstances:
1. When using the [TestCase] attribute, by specifying the SetName property.
2. When using the [TestCaseSource] attribute, provided the arguments are given by use of TestCaseData instances. Again, the property to use is SetName.

Two drawbacks to the above:
1. You have to do it one test at a time.
2. It isn't available at all when specifying arguments  using [Values] or [ValueSource].

The general solution that NUnit has always historically advised is to override ToString in the types you are using as arguments. Obviously, when the type is string[] that's not available to you as an option.

Unfortunately, unless we implement a fix to the above issue, there's no good alternative for your case. Workarounds to consider:

Use [TestCase] or [TestCaseSource], spelling out all the combinations yourself, and specify SetName on each case.

Wrap string[] with a type of your own for testing purposes, overriding ToString() to display the array contents.

Body:
I am stuck at finding one functionality that NUnit provides which I almost certain that I saw it before and I thought myself I will use it, but sadly I didn't pin it somewhere.

We are writing our tests like so:

[Test]
public void Post_StakeToDifferetnSelectionsViaBetsBetIdEndpoint_ReturnsCorrectData(
        [ValueSource(typeof(JsonContextCache), nameof(JsonContextCache.RandomThreeUniqueSelecionIds))] string[] selectionIds,
        [ValueSource(typeof(TestData), nameof(TestData.OddStyles))] OddStyle oddStyle,
        [Values(true, false)] bool logged)

Problem with this approach is that when we supply ValueSource or TestCaseSource attributes with complex types (like string[], custom types) results in our CI environments from NUnit are like so:

Post_StakeToDifferetnSelectionsViaBetsBetIdEndpoint_ReturnsCorrectData(System.String[],European,True)

What I want is, instead of this System.String[] to show the array values, but I don't know how can I make Nunit do that for me.


问:
date picker js didn't work?
I want to use date picker with js and it's work in some page with some code as same as this page but in this page it didn't work. i wish someone can help me with that

here is my code:

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/themes/base/jquery-ui.css"
        type="text/css" media="all" />

```
<pre class="snippet-code-html lang-html prettyprint-override"><code>          <label style="font-size:20px;">期間</label>
<form id="form1" runat="server" action="kasrapro.php">
    <input type="text" id="txtDate" name= "sdate" /></code>```

答:
Seems like it was a formatting error. Still there is one error in console that is because of your polyfiller.js, but DatePicker is working now.

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/themes/base/jquery-ui.css" type="text/css" media="all" />

期間
<form id="form1" runat="server" action="kasrapro.php">
  <input type="text" id="txtDate" name="sdate" />
</form>```

Title: date picker js didn't work?

Body:
I want to use date picker with js and it's work in some page with some code as same as this page but in this page it didn't work. i wish someone can help me with that

here is my code:

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/themes/base/jquery-ui.css"
        type="text/css" media="all" />

          期間
<form id="form1" runat="server" action="kasrapro.php">
    <input type="text" id="txtDate" name= "sdate" />

Body:
Seems like it was a formatting error. Still there is one error in console that is because of your polyfiller.js, but DatePicker is working now.

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/themes/base/jquery-ui.css" type="text/css" media="all" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
  $(function() {
$('#txtDate').datepicker({
  dateFormat: 'yy-mm-dd'
}).val();
$('#txtDate').datepicker();
  });
</script>
<script src="https://cdn.jsdelivr.net/webshim/1.12.4/extras/modernizr-custom.js"></script>
<!-- polyfiller file to detect and load polyfills -->
<script src="https://cdn.jsdelivr.net/webshim/1.12.4/polyfiller.js"></script>
<label style="font-size:20px;">期間</label>
<form id="form1" runat="server" action="kasrapro.php">
  <input type="text" id="txtDate" name="sdate" />
</form>


问:
Passing hash object as FCMP parameter
proc fcmp functions allow passing hash objects as parameters.  The documentation is a little vague and it doesn't mention whether or not this ability is restricted to calls from other fcmp functions or if it's allowed from a data step call as well.

I'm trying to define a hash in a data step and then pass that hash by reference to an fcmp function.  When I try the below code however, it's giving me: NOTE: Invalid type conversion and I'm not sure where I'm going wrong (or if this is even possible).

```<code>option cmplib=work.funcs;

proc fcmp outlib=work.funcs.funcs;
  function test(h hash);
    return (0);
  endsub;
run;

data _null_;
  format pos best.;

  if _n_ eq 1 then do;
    declare hash h();
    rc = h.definekey('pos');
    rc = h.definedone();
    call missing (pos);
  end;

  xx = test2(h);
  put _all_;
run;
</code>```

The reason I am trying to do this is because I would like to eventually have several functions that I can pass the same hash table to as a parameter.

答:
I don't believe this is possible from data step (be good to see that documentation link).

However - you CAN create a hash table within an fcmp function (or subroutine), and it will remain there for every subsequent call, until the end of the data step.

If you need to retain the state of that hash table across different fcmp function calls, then create a generic subroutine to contain the hash table, and call that subroutine from your different function calls.

Note that the implementation of hash tables within fcmp is limited (eg no attributes such as 'ordered' and you can't export them to datasets).

Title: Passing hash object as FCMP parameter

Body:
proc fcmp functions allow passing hash objects as parameters.  The documentation is a little vague and it doesn't mention whether or not this ability is restricted to calls from other fcmp functions or if it's allowed from a data step call as well.

I'm trying to define a hash in a data step and then pass that hash by reference to an fcmp function.  When I try the below code however, it's giving me: NOTE: Invalid type conversion and I'm not sure where I'm going wrong (or if this is even possible).

option cmplib=work.funcs;

proc fcmp outlib=work.funcs.funcs;
  function test(h hash);
    return (0);
  endsub;
run;

data _null_;
  format pos best.;

  if _n_ eq 1 then do;
    declare hash h();
    rc = h.definekey('pos');
    rc = h.definedone();
    call missing (pos);
  end;

  xx = test2(h);
  put _all_;
run;

The reason I am trying to do this is because I would like to eventually have several functions that I can pass the same hash table to as a parameter.