问:
Sending STOMP messages from other layers of an application
I am building an application using Spring Websockets on a clustered tomcat environment with a RabbitMQ broker. I have an API module which needs to register the endpoint to listen to. I followed the normal examples and came up with this config:

```<code>@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer
{
    @Override
    public void configureMessageBroker(final MessageBrokerRegistry config)
    {
        config.enableStompBrokerRelay("/topic/")
            .setRelayHost("localhost")
            .setRelayPort(61613)
            .setClientLogin("guest")
            .setClientPasscode("guest");
    }

    @Override
    public void registerStompEndpoints(final StompEndpointRegistry registry)
    {
        registry.addEndpoint("/updates")
            .setAllowedOrigins("*")
            .withSockJS();
    }
}
</code>```

While this works, it doesn't solve my issue as it appears the WebSocket and relay config are all bundled into the API module therefore leaving other layers unable to reuse the broker. I need the stomp message broker relay configuration to happen at the service layer so that other modules of our app can push messages to topics in RabbitMQ which then turn around and notify the API module to update all open websockets.

Below is a sample diagram of the relevant layers in our application and what I am trying to accomplish. I need to allow the module "Cron Message Sender" to push messages to everyone who is subscribed to a message topic through our other API modules.

答:
So the second approach did in fact work. I configured the websockets to be run independently (no relay) and then I made a separate AMQP message broker connection at the service layer to allow communication between services. In the API module, I simply listened to the AMQP message broker and then manually forwarded those messages to the SimpMessagingTemplate which notified the websocket subscribers. I am not sure if this is technically the "right" way to do it but it seems to be working great and I do not yet see any issues with the implementation. In fact, I actually think I may prefer this approach as I now just gave all my services the ability to talk to each other with more types of messages than what I originally needed for the websockets.

Here is the new configuration:

```<code>@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer
{
    @Override
    public void configureMessageBroker(final MessageBrokerRegistry config)
    {
        config.enableSimpleBroker("/topic");
    }

    @Override
    public void registerStompEndpoints(final StompEndpointRegistry registry)
    {
        registry.addEndpoint("/updates")
            .setAllowedOrigins("*")
            .withSockJS();
    }
}
</code>```

And here is where I listen to the message broker and forward the messages to the websocket subscribers:

```<code>@Component
public class SendWebSocketUpdates
{
    private static final Logger logger = LoggerFactory.getLogger(SendWebSocketUpdates.class);

    private final Gson gson;

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @Autowired
    private MessageBrokerConsumer<String> messageBrokerConsumer;

    public SendWebSocketUpdates()
    {
        this.gson = new Gson();
    }

    @PostConstruct
    public void init()
    {
        //listen for incoming AMQP messages from the rabbitmq server and forward them to the websocket subscribers
        messageBrokerConsumer.addListener((message, topicName) -> {
            final String destination = "/topic/" + topicName;
            final String messageJson = gson.toJson(message.getBody());

            //check to see if trace logging is enabled
            if (logger.isTraceEnabled())
            {
                logger.trace("Sending Message to \"{}\": {}", destination, messageJson);
            }

            //broadcast the via a STOMP message to subscribers of this topic
            messagingTemplate.convertAndSend(destination, messageJson);
        });
    }
}
</code>```

Body:
I am building an application using Spring Websockets on a clustered tomcat environment with a RabbitMQ broker. I have an API module which needs to register the endpoint to listen to. I followed the normal examples and came up with this config:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer
{
    @Override
    public void configureMessageBroker(final MessageBrokerRegistry config)
    {
        config.enableStompBrokerRelay("/topic/")
            .setRelayHost("localhost")
            .setRelayPort(61613)
            .setClientLogin("guest")
            .setClientPasscode("guest");
    }

    @Override
    public void registerStompEndpoints(final StompEndpointRegistry registry)
    {
        registry.addEndpoint("/updates")
            .setAllowedOrigins("*")
            .withSockJS();
    }
}

While this works, it doesn't solve my issue as it appears the WebSocket and relay config are all bundled into the API module therefore leaving other layers unable to reuse the broker. I need the stomp message broker relay configuration to happen at the service layer so that other modules of our app can push messages to topics in RabbitMQ which then turn around and notify the API module to update all open websockets.

Below is a sample diagram of the relevant layers in our application and what I am trying to accomplish. I need to allow the module "Cron Message Sender" to push messages to everyone who is subscribed to a message topic through our other API modules.

Body:
So the second approach did in fact work. I configured the websockets to be run independently (no relay) and then I made a separate AMQP message broker connection at the service layer to allow communication between services. In the API module, I simply listened to the AMQP message broker and then manually forwarded those messages to the SimpMessagingTemplate which notified the websocket subscribers. I am not sure if this is technically the "right" way to do it but it seems to be working great and I do not yet see any issues with the implementation. In fact, I actually think I may prefer this approach as I now just gave all my services the ability to talk to each other with more types of messages than what I originally needed for the websockets.

Here is the new configuration:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer
{
    @Override
    public void configureMessageBroker(final MessageBrokerRegistry config)
    {
        config.enableSimpleBroker("/topic");
    }

    @Override
    public void registerStompEndpoints(final StompEndpointRegistry registry)
    {
        registry.addEndpoint("/updates")
            .setAllowedOrigins("*")
            .withSockJS();
    }
}

And here is where I listen to the message broker and forward the messages to the websocket subscribers:

@Component
public class SendWebSocketUpdates
{
    private static final Logger logger = LoggerFactory.getLogger(SendWebSocketUpdates.class);

    private final Gson gson;

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @Autowired
    private MessageBrokerConsumer<String> messageBrokerConsumer;

    public SendWebSocketUpdates()
    {
        this.gson = new Gson();
    }

    @PostConstruct
    public void init()
    {
        //listen for incoming AMQP messages from the rabbitmq server and forward them to the websocket subscribers
        messageBrokerConsumer.addListener((message, topicName) -> {
            final String destination = "/topic/" + topicName;
            final String messageJson = gson.toJson(message.getBody());

            //check to see if trace logging is enabled
            if (logger.isTraceEnabled())
            {
                logger.trace("Sending Message to \"{}\": {}", destination, messageJson);
            }

            //broadcast the via a STOMP message to subscribers of this topic
            messagingTemplate.convertAndSend(destination, messageJson);
        });
    }
}


来源: stackexchange

问:
InvocationTargetException when using JavaFX
I am trying to use Gluon/JavaFX for the first time, but I am receiving an InvocationTargetException at run-time. I have searched for answers on this site and others, but have received the same problem after trying each suggestion.

Main:

```<code>package Scenes;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

public class Main extends Application{

    public void start(Stage stage) throws Exception{

        Parent root = FXMLLoader.load(getClass().getResource("test.fxml"));
        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.setTitle("asdf");
        stage.show();
    }

    public static void main(String[] args) {

        launch(args);
    }

}
</code>```

Controller:

```<code>package Scenes;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JFileChooser;

import javafx.scene.control.Button;

public class Controller {

    Button kButton;
    Button bpButton;

    public void initialize() {

    }

    public static void browseFileK() {
        JFileChooser jfc = new JFileChooser();
        int returnValue = jfc.showOpenDialog(null);
        if(returnValue == JFileChooser.APPROVE_OPTION)
        {
            File selectedFile = jfc.getSelectedFile();
        }
    }

        public static void browseFileBP() {
            JFileChooser jfc = new JFileChooser();
            int returnValue = jfc.showOpenDialog(null);
            if(returnValue == JFileChooser.APPROVE_OPTION)
            {
                File selectedFile = jfc.getSelectedFile();
            }
        }

}
</code>```

FXML file:

```<code><?xml version="1.0" encoding="UTF-8"?>

<?import com.gluonhq.charm.glisten.control.TextField?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.text.Font?>

<VBox prefHeight="400.0" prefWidth="640.0" xmlns="http://javafx.com/javafx/8.0.151" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
  <children>
    <AnchorPane cache="true" maxHeight="-1.0" maxWidth="-1.0" prefHeight="-1.0" prefWidth="-1.0" VBox.vgrow="ALWAYS">
      <children>
        <Label alignment="CENTER" layoutX="155.0" layoutY="177.0" style="
" textAlignment="CENTER" textFill="#9f9f9f" wrapText="false">
          <font>
            <Font size="18.0" />
          </font>
        </Label>
            <TextField layoutX="21.0" layoutY="47.0" prefHeight="26.0" prefWidth="237.0" text="Select location of Kasasa accounts file" />
            <TextField layoutX="21.0" layoutY="118.0" prefHeight="26.0" prefWidth="237.0" text="Select location of Bill Pay accounts file" />
            <Button layoutX="294.0" layoutY="48.0" mnemonicParsing="false" text="Browse..." />
            <Button layoutX="294.0" layoutY="115.0" mnemonicParsing="false" text="Browse..." />
            <Button layoutX="168.0" layoutY="269.0" mnemonicParsing="false" prefHeight="32.0" prefWidth="253.0" text="Generate refund document" />
      </children>
    </AnchorPane>
  </children>
</VBox>
</code>```

Stacktrace:

```<code>Exception in Application start method
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
    at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$154(LauncherImpl.java:182)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException: Location is required.
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3207)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
    at Scenes.Main.start(Main.java:14)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$161(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$174(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
    ... 1 more
</code>```

It seems the most popular suggestions have been to add the fxml file to the same package as main, add "/" in front of the fxml file, or to change the file name to "Scenes/test.fxml", none of which have worked for me.

答:
Your FXML file says :

```<code>fx:controller="sample.Controller"
</code>```

but your Controller is in

```<code> package Scenes;
</code>```

So your FXML should be

```<code>fx:controller="Scenes.Controller"
</code>```

You are using Swing components.

```<code>import javax.swing.JButton;
import javax.swing.JFileChooser;
</code>```

You need to use JavaFx components.

```<code>import javafx.scene.control.Button;
import javafx.stage.FileChooser;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to use Gluon/JavaFX for the first time, but I am receiving an InvocationTargetException at run-time. I have searched for answers on this site and others, but have received the same problem after trying each suggestion.

Main:

package Scenes;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

public class Main extends Application{

    public void start(Stage stage) throws Exception{

        Parent root = FXMLLoader.load(getClass().getResource("test.fxml"));
        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.setTitle("asdf");
        stage.show();
    }

    public static void main(String[] args) {

        launch(args);
    }

}

Controller:

package Scenes;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JFileChooser;

import javafx.scene.control.Button;

public class Controller {

    Button kButton;
    Button bpButton;

    public void initialize() {

    }

    public static void browseFileK() {
        JFileChooser jfc = new JFileChooser();
        int returnValue = jfc.showOpenDialog(null);
        if(returnValue == JFileChooser.APPROVE_OPTION)
        {
            File selectedFile = jfc.getSelectedFile();
        }
    }

        public static void browseFileBP() {
            JFileChooser jfc = new JFileChooser();
            int returnValue = jfc.showOpenDialog(null);
            if(returnValue == JFileChooser.APPROVE_OPTION)
            {
                File selectedFile = jfc.getSelectedFile();
            }
        }

}

FXML file:

<?xml version="1.0" encoding="UTF-8"?>

<?import com.gluonhq.charm.glisten.control.TextField?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.text.Font?>

<VBox prefHeight="400.0" prefWidth="640.0" xmlns="http://javafx.com/javafx/8.0.151" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
  <children>
    <AnchorPane cache="true" maxHeight="-1.0" maxWidth="-1.0" prefHeight="-1.0" prefWidth="-1.0" VBox.vgrow="ALWAYS">
      <children>

            <TextField layoutX="21.0" layoutY="47.0" prefHeight="26.0" prefWidth="237.0" text="Select location of Kasasa accounts file" />
            <TextField layoutX="21.0" layoutY="118.0" prefHeight="26.0" prefWidth="237.0" text="Select location of Bill Pay accounts file" />
            <Button layoutX="294.0" layoutY="48.0" mnemonicParsing="false" text="Browse..." />
            <Button layoutX="294.0" layoutY="115.0" mnemonicParsing="false" text="Browse..." />
            <Button layoutX="168.0" layoutY="269.0" mnemonicParsing="false" prefHeight="32.0" prefWidth="253.0" text="Generate refund document" />
      </children>
    </AnchorPane>
  </children>
</VBox>

Stacktrace:

Exception in Application start method
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
    at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$154(LauncherImpl.java:182)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException: Location is required.
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3207)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
    at Scenes.Main.start(Main.java:14)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$161(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$174(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
    ... 1 more

It seems the most popular suggestions have been to add the fxml file to the same package as main, add "/" in front of the fxml file, or to change the file name to "Scenes/test.fxml", none of which have worked for me.

Body:
Your FXML file says :

fx:controller="sample.Controller"

but your Controller is in

 package Scenes;

So your FXML should be

fx:controller="Scenes.Controller"

You are using Swing components.

import javax.swing.JButton;
import javax.swing.JFileChooser;

You need to use JavaFx components.

import javafx.scene.control.Button;
import javafx.stage.FileChooser;


问:
Scheme (DrRacket) - read-line doesn't stop for input at second attempt
I have prompt user for 2 values to be stored in 2 different variables as follows:

```<code>(define (promptUser)
  (define varA 'a)
  (define varB 0)

  (display "Value or hit q/Q to terminate: ")
  (set! varA  (read-line))

  (cond
       ((or (string=? varA  "q") (string=? varA  "Q")))
       (else
           (display "Value for b: ")
           (set! varB (read))
           (promptUser)
       )
   )
)
</code>```

As you can see, when I call (promptUser) the first time, it actually stops at (read-line) to wait for user input, but for some reason the call at (promptUser) actually skips through for the first user input and jumps directly into else case under cond

Example of error as below:

It doesn't stop for varA's input.

Can someone please explain this to me?

答:
There is some problem with:

```<code>(set! varB (read))
</code>```

When testing in drracket 'read' gets everything until separator, that is space or new line. I can guess that the new line char is consumed in next cycle in:

```<code>(set! varA  (read-line))
</code>```

This can be seen when you in B enter eg: 'aaa bbb' and if you display content of varA in next cycle. bbb will be there.
If you replace your read with read-line,

```<code>(set! varB (read-line))
</code>```

everything works as expected.

Body:
I have prompt user for 2 values to be stored in 2 different variables as follows:

(define (promptUser)
  (define varA 'a)
  (define varB 0)

  (display "Value or hit q/Q to terminate: ")
  (set! varA  (read-line))

  (cond
       ((or (string=? varA  "q") (string=? varA  "Q")))
       (else
           (display "Value for b: ")
           (set! varB (read))
           (promptUser)
       )
   )
)

As you can see, when I call (promptUser) the first time, it actually stops at (read-line) to wait for user input, but for some reason the call at (promptUser) actually skips through for the first user input and jumps directly into else case under cond

Example of error as below:

It doesn't stop for varA's input.

Can someone please explain this to me?

Body:
There is some problem with:

(set! varB (read))

When testing in drracket 'read' gets everything until separator, that is space or new line. I can guess that the new line char is consumed in next cycle in:

(set! varA  (read-line))

This can be seen when you in B enter eg: 'aaa bbb' and if you display content of varA in next cycle. bbb will be there.
If you replace your read with read-line,

(set! varB (read-line))

everything works as expected.


问:
How to serialize(JSON) FileField in Django
I am new to Django and trying to build an app to test out few things for my project. I want to read the form - do some validation and then send the input to another module (say a scheduler running separately). The scheduler rest api will be called with the form data (which is file) and the scheduler will load the data into the models. I am using python requests and serializing data into json before calling the rest api. This is where I am getting error. Django on request.FILES create a InMemoryUploadedFile class which has the data loaded somewhere in memory and serializing this to Json is not straightforward. I tried looking other ways (like image serializers example) but not able to resolve this issue.

forms.py

```<code>class UploadDatasetForm(forms.Form):
    docfile = forms.FileField(label='Choose file')
</code>```

views.py

```<code>def test_upload(request):
    if request.method == 'POST':
        form = UploadDatasetForm(request.POST, request.FILES)
        if form.is_valid():
            in_file = request.FILES['docfile']
            payload = {'doc_file': in_file}
            msg = json.dumps(payload)
            URL = 'http://localhost:8880/form'
            r = requests.post(URL, data=msg)
    return HttpResponse(json.dumps(r.text), content_type="application/json")
</code>```

Error:

```<code>raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <InMemoryUploadedFile: A_test.csv (text/csv)> is not JSON serializable
</code>```

Any help here will be appreciated. Thanks a lot.

答:
By default python only supports of converting a hand full of default datatypes (str, int, float, dict, list, etc.). You try to convert InMemoryUploadedFile, the dumps function doesn't know how to handle that. What you need to do is provide a method to convert the data into one of the data types that python does supports.</p>

```<code>class MyJsonEncoder(DjangoJSONEncoder):
    def default(self, o):
        if isinstance(o, InMemoryUploadedFile):
           return o.read()
        return str(o)

msg = json.dumps(payload, cls=MyJsonEncoder)
</code>```

Body:
I am new to Django and trying to build an app to test out few things for my project. I want to read the form - do some validation and then send the input to another module (say a scheduler running separately). The scheduler rest api will be called with the form data (which is file) and the scheduler will load the data into the models. I am using python requests and serializing data into json before calling the rest api. This is where I am getting error. Django on request.FILES create a InMemoryUploadedFile class which has the data loaded somewhere in memory and serializing this to Json is not straightforward. I tried looking other ways (like image serializers example) but not able to resolve this issue.

forms.py

class UploadDatasetForm(forms.Form):
    docfile = forms.FileField(label='Choose file')

views.py

def test_upload(request):
    if request.method == 'POST':
        form = UploadDatasetForm(request.POST, request.FILES)
        if form.is_valid():
            in_file = request.FILES['docfile']
            payload = {'doc_file': in_file}
            msg = json.dumps(payload)
            URL = 'http://localhost:8880/form'
            r = requests.post(URL, data=msg)
    return HttpResponse(json.dumps(r.text), content_type="application/json")

Error:

raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <InMemoryUploadedFile: A_test.csv (text/csv)> is not JSON serializable

Any help here will be appreciated. Thanks a lot.

Body:
By default python only supports of converting a hand full of default datatypes (str, int, float, dict, list, etc.). You try to convert InMemoryUploadedFile, the dumps function doesn't know how to handle that. What you need to do is provide a method to convert the data into one of the data types that python does supports.

class MyJsonEncoder(DjangoJSONEncoder):
    def default(self, o):
        if isinstance(o, InMemoryUploadedFile):
           return o.read()
        return str(o)

msg = json.dumps(payload, cls=MyJsonEncoder)


问:
Incremental search in Idea the word under cursor
I would like to search in current file the word under cursor like Alt+F3, except manually selecting current word? Is there alike keyboard shortcut?

答:
Ctrl+F3 - Find Next

Unfortunately, I have failed to find any keyboard shortcut for Find Previous shortcut.


问:
Spring Batch - restartable process with memory DB
Spring Batch with memory DB - I have Spring Batch process using H2 memory DB (for  performance purposes).

It is multistep and multithread process working pretty well so far but one of requirements is to make it restartable (and recoverable) on failure.

Now the process is designed to terminate Spring Boot apliction when finished (or crashed).

My question is how can I add restart functionality without changing DB for file based or without compromising the performance in general?

One of ideas is to add another step executed on failure dumping db to files but what then? How to make process to recover out of that?

答:
You just can configure your H2 instance to being persisted in file:

```<code>jdbc:h2:[file:][<path>]<databaseName>
jdbc:h2:~/test
jdbc:h2:file:/data/sample
jdbc:h2:file:C:/data/sample (Windows only)
</code>```

Please check h2 documentation

Body:
You just can configure your H2 instance to being persisted in file:

jdbc:h2:[file:][<path>]<databaseName>
jdbc:h2:~/test
jdbc:h2:file:/data/sample
jdbc:h2:file:C:/data/sample (Windows only)

Please check h2 documentation


问:
Python re.sub(): how to substitute all 'u' or 'U's with 'you'
I am doing some text normalization using python and regular expressions. I would like to substitute all 'u'or 'U's with 'you'.
Here is what I have done so far:

```<code>import re
text = 'how are u? umberella u! u. U. U@ U# u '
print re.sub (' [u|U][s,.,?,!,W,#,@ (^a-zA-Z)]', ' you ', text)
</code>```

The output I get is:

```<code>how are you  you berella you  you  you  you  you  you
</code>```

As you can see the problem is that 'umberella' is changed to 'berella'. Also I want to keep the character that appears after a 'u'. For example I want 'u!' to be changed to 'you!'. Can anyone tell me what I am doing wrong and what is the best way to write the regular expression?

答:
Another possible solution I came up with was: </p>

```<code>re.sub(r'([uU]+(.)?\s)',' you ', text)
</code>```

Body:
I am doing some text normalization using python and regular expressions. I would like to substitute all 'u'or 'U's with 'you'.
Here is what I have done so far:

import re
text = 'how are u? umberella u! u. U. U@ U# u '
print re.sub (' [u|U][s,.,?,!,W,#,@ (^a-zA-Z)]', ' you ', text)

The output I get is:

how are you  you berella you  you  you  you  you  you

As you can see the problem is that 'umberella' is changed to 'berella'. Also I want to keep the character that appears after a 'u'. For example I want 'u!' to be changed to 'you!'. Can anyone tell me what I am doing wrong and what is the best way to write the regular expression?

Body:
Another possible solution I came up with was:

re.sub(r'([uU]+(.)?\s)',' you ', text)


问:
VBA: Multiplying by a fraction within a loop
My code works below works but I'd like to add one function.  I've got a large data sheet with each line repeated three times.  Within each set of three I've added a month twice.  The purpose is to smooth out forecasted sales into one month and two months beyond the estimated shipping date.  Now I'd like to multiply my the values in column E by factors into column F.  The original line in each set of three will =50%*E:E  in column F, the second line will have =30%*E:E in column F, and the third line will have =20%*E:E in Column F.   This process should be repeated continually for every set of three lines. Problem: My current code does give me the correct value, however the values are two cells lower than they need to be. Thanks for any help in advance! My current code is below:

```<code>Public Sub DateAdd()

Dim r As Long
Dim l As Long
Dim Quant As Long
Dim dttTemp As Date
Dim ws As Worksheet

Set ws = ThisWorkbook.Worksheets("SalesForce Projects")

Application.ScreenUpdating = False

For r = ws.Range("A" & ws.Rows.Count).End(xlUp).Row To 1 Step -1
With ws.Cells(r, 1).EntireRow
    .Copy
    .Resize(2).Offset(1, 0).Insert Shift:=xlDown
End With
dttTemp = ws.Cells(r, "S").Value
ws.Cells(r + 1, "S").Value = DateSerial(Year(dttTemp), Month(dttTemp) + 1,
Day(dttTemp))
ws.Cells(r + 2, "S").Value = DateSerial(Year(dttTemp), Month(dttTemp) + 2,
Day(dttTemp))
Next r

Application.ScreenUpdating = True
</code>```

' This is where my code is bad

```<code>For l = ws.Range("A" & ws.Rows.Count).End(xlUp).Row To 1 Step -3

Quant = ws.Cells(l, "E").Value
ws.Cells(l, "F").Value = Cells(l, "E") * 0.5
ws.Cells(l + 1, "F").Value = Cells(l, "E") * 0.3
ws.Cells(l + 2, "F").Value = Cells(l, "E") * 0.2
Next l

End Sub
</code>```

答:
When you say "50% of the value in column E," you could mean the entire value of all 90 in column E or just the value of the three cells in a set. If you mean the first then (I assume that row 1 is headings, so your values start at row 2.) In cell F2 enter the formula

```<code> =Sum(E:E)*.5
</code>```

In cell F3 enter

```<code> =SUM(E:E)*.3
</code>```

In cell F4 enter

```<code>=SUM(E:E)*.2
</code>```

If you mean the other option then enter:

```<code>In F2   =Sum(E2:E4)*.5
in F3  =Sum(E2:E4)*.3
In F4   =Sum(E2:e4)*.2
</code>```

Now select f2:f4. Place your mouse on the bottom right corner and you should see the cursor change to a small black cross. Double-click and the formulas will be replicated down the sheet. If you have more than one sheet to fill then control click on the tab names before starting this process to similtainoiusly copy to all selected sheets.

Body:
My code works below works but I'd like to add one function.  I've got a large data sheet with each line repeated three times.  Within each set of three I've added a month twice.  The purpose is to smooth out forecasted sales into one month and two months beyond the estimated shipping date.  Now I'd like to multiply my the values in column E by factors into column F.  The original line in each set of three will =50%*E:E  in column F, the second line will have =30%*E:E in column F, and the third line will have =20%*E:E in Column F.   This process should be repeated continually for every set of three lines. Problem: My current code does give me the correct value, however the values are two cells lower than they need to be. Thanks for any help in advance! My current code is below:

Public Sub DateAdd()

Dim r As Long
Dim l As Long
Dim Quant As Long
Dim dttTemp As Date
Dim ws As Worksheet

Set ws = ThisWorkbook.Worksheets("SalesForce Projects")

Application.ScreenUpdating = False

For r = ws.Range("A" & ws.Rows.Count).End(xlUp).Row To 1 Step -1
With ws.Cells(r, 1).EntireRow
    .Copy
    .Resize(2).Offset(1, 0).Insert Shift:=xlDown
End With
dttTemp = ws.Cells(r, "S").Value
ws.Cells(r + 1, "S").Value = DateSerial(Year(dttTemp), Month(dttTemp) + 1,
Day(dttTemp))
ws.Cells(r + 2, "S").Value = DateSerial(Year(dttTemp), Month(dttTemp) + 2,
Day(dttTemp))
Next r

Application.ScreenUpdating = True

' This is where my code is bad

For l = ws.Range("A" & ws.Rows.Count).End(xlUp).Row To 1 Step -3

Quant = ws.Cells(l, "E").Value
ws.Cells(l, "F").Value = Cells(l, "E") * 0.5
ws.Cells(l + 1, "F").Value = Cells(l, "E") * 0.3
ws.Cells(l + 2, "F").Value = Cells(l, "E") * 0.2
Next l

End Sub

Body:
When you say "50% of the value in column E," you could mean the entire value of all 90 in column E or just the value of the three cells in a set. If you mean the first then (I assume that row 1 is headings, so your values start at row 2.) In cell F2 enter the formula

 =Sum(E:E)*.5

In cell F3 enter

 =SUM(E:E)*.3

In cell F4 enter

=SUM(E:E)*.2

If you mean the other option then enter:

In F2   =Sum(E2:E4)*.5
in F3  =Sum(E2:E4)*.3
In F4   =Sum(E2:e4)*.2

Now select f2:f4. Place your mouse on the bottom right corner and you should see the cursor change to a small black cross. Double-click and the formulas will be replicated down the sheet. If you have more than one sheet to fill then control click on the tab names before starting this process to similtainoiusly copy to all selected sheets.


问:
C# LINQ to Entities One-To-Many relationship: Problem displaying last log entry data
I have a web application with two tables to track user shares.  Shares must be approved and so they go through a series of status changes.  Each status change is recorded in the log and timestamped. The current status is always the last entry in the log for that particular share.

Here are the entities (with brevity):

Shares:
ShareID
UserName

ShareLogs:
LogID
ShareID
CreatedDate
Status

I'm trying to get a list of Shares with their current status based on the last log entry.
Here is the SQL query that returns the correct result, but I'd like to do this using LINQ.

```<code>SELECT s.ShareID, s.UserName, sl.Code, sl.CreatedDate
FROM Shares s
INNER JOIN
(
SELECT s.ShareID, s.Code, s.CreatedDate
    FROM ShareLogs sl
    INNER JOIN (SELECT ShareID, MAX(CreatedDate) logDate FROM ShareLogs GROUP BY ShareID) sl2
        ON sl.ShareID = sl2.ShareID AND sl.CreatedDate = sl2.logDate) psl1
ON s.ShareID = sl1.ShareID
ORDER BY s.ShareID
</code>```

I have written one LINQ query that seems to work, but I feel like there should be a better way, as this query looks pretty terrible.

```<code>var query = from list in
(from s in context.Shares
join sl in context.ShareLogs on s.ShareID equals sl.ShareID
where sl.CreatedDate == s.ShareLogs.Max(e => e.CreatedDate)
select new
{
 share = s
 status = sl.Code,
 processDate = sl.CreatedDate
}).Where(e => e.status == 2 || e.status == 3)
select list;
</code>```

答:
You could try doing a join, then grouping on all rows except the ShareID, then just get the share with the greatest date. eg:

```<code>var shareList = context.Shares;
var shareLogList = context.ShareLogs;
var join = shareList.Join(shareLogList, o=>o.ShareID, i=>i.ShareID, s=>new{o.ShareID, o.UserName,i.LogID, i.CreatedDate, i.Status});
var query = join.GroupBy(g=>new{g.ShareID,g.UserName}, (key,lines)=>new{key.ShareID, Status = lines.Max(m=>m.CreatedDate).Status});
</code>```

That should do it! You can combine it into one statement if you'd like, I just separated them for clarity.

ContentLicense: CC BY-SA 2.5

Body:
I have a web application with two tables to track user shares.  Shares must be approved and so they go through a series of status changes.  Each status change is recorded in the log and timestamped. The current status is always the last entry in the log for that particular share.

Here are the entities (with brevity):

Shares:
ShareID
UserName

ShareLogs:
LogID
ShareID
CreatedDate
Status

I'm trying to get a list of Shares with their current status based on the last log entry.
Here is the SQL query that returns the correct result, but I'd like to do this using LINQ.

SELECT s.ShareID, s.UserName, sl.Code, sl.CreatedDate
FROM Shares s
INNER JOIN
(
SELECT s.ShareID, s.Code, s.CreatedDate
    FROM ShareLogs sl
    INNER JOIN (SELECT ShareID, MAX(CreatedDate) logDate FROM ShareLogs GROUP BY ShareID) sl2
        ON sl.ShareID = sl2.ShareID AND sl.CreatedDate = sl2.logDate) psl1
ON s.ShareID = sl1.ShareID
ORDER BY s.ShareID

I have written one LINQ query that seems to work, but I feel like there should be a better way, as this query looks pretty terrible.

var query = from list in
(from s in context.Shares
join sl in context.ShareLogs on s.ShareID equals sl.ShareID
where sl.CreatedDate == s.ShareLogs.Max(e => e.CreatedDate)
select new
{
 share = s
 status = sl.Code,
 processDate = sl.CreatedDate
}).Where(e => e.status == 2 || e.status == 3)
select list;

Body:
You could try doing a join, then grouping on all rows except the ShareID, then just get the share with the greatest date. eg:

var shareList = context.Shares;
var shareLogList = context.ShareLogs;
var join = shareList.Join(shareLogList, o=>o.ShareID, i=>i.ShareID, s=>new{o.ShareID, o.UserName,i.LogID, i.CreatedDate, i.Status});
var query = join.GroupBy(g=>new{g.ShareID,g.UserName}, (key,lines)=>new{key.ShareID, Status = lines.Max(m=>m.CreatedDate).Status});

That should do it! You can combine it into one statement if you'd like, I just separated them for clarity.


问:
How to remove a specific key from Firebase in Swift 3
How can I get the marked key then remove it from UITableView swift 3 ?

```<code>override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

        if editingStyle == .delete {

            self.grocery.remove(at: indexPath.row)
            self.tableView.deleteRows(at: [indexPath], with: .automatic)
        }
    }
</code>```

答:
You can remove any data from Firebase as following: </p>

```<code>let ref = Database.database().reference()
let groceryRef = ref.child("Users").child(userKey).child("Grocery")
groceryRef.removeValue()
</code>```

Body:
How can I get the marked key then remove it from UITableView swift 3 ?

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

        if editingStyle == .delete {

            self.grocery.remove(at: indexPath.row)
            self.tableView.deleteRows(at: [indexPath], with: .automatic)
        }
    }

Body:
You can remove any data from Firebase as following:

let ref = Database.database().reference()
let groceryRef = ref.child("Users").child(userKey).child("Grocery")
groceryRef.removeValue()


问:
Callback on CNContactViewController
How to get a callBack when user successfully saves or dismiss the CNContactViewController

```<code>func addContact(contactDetails: ContactDetails) {
    let store = CNContactStore()
    let contact = CNMutableContact()
    let comp = contactDetails.name.components(separatedBy: " ")
    contact.givenName = comp.first ?? ""
    contact.familyName = comp.count > 1 ? comp[1] : ""
    let homePhone = CNLabeledValue(label: CNLabelHome, value: CNPhoneNumber(stringValue :contactDetails.phone ))
    contact.phoneNumbers = [homePhone]
    let workEmail = CNLabeledValue(label:CNLabelWork, value:contactDetails.email as NSString)
    contact.emailAddresses = [workEmail]
    let controller = CNContactViewController(forUnknownContact : contact)// .viewControllerForUnknownContact(contact)
    controller.contactStore = store
    controller.delegate = self
    //self.navigationController?.setNavigationBarHidden(false, animated: true)
    self.navigationController?.pushViewController(controller, animated: true)
}
</code>```

答:
You can declare a delegate / protocol for communicate between controllers. Check below link for simple code example;

Simple Protocol Example

Title: Callback on CNContactViewController

Body:
How to get a callBack when user successfully saves or dismiss the CNContactViewController

func addContact(contactDetails: ContactDetails) {
    let store = CNContactStore()
    let contact = CNMutableContact()
    let comp = contactDetails.name.components(separatedBy: " ")
    contact.givenName = comp.first ?? ""
    contact.familyName = comp.count > 1 ? comp[1] : ""
    let homePhone = CNLabeledValue(label: CNLabelHome, value: CNPhoneNumber(stringValue :contactDetails.phone ))
    contact.phoneNumbers = [homePhone]
    let workEmail = CNLabeledValue(label:CNLabelWork, value:contactDetails.email as NSString)
    contact.emailAddresses = [workEmail]
    let controller = CNContactViewController(forUnknownContact : contact)// .viewControllerForUnknownContact(contact)
    controller.contactStore = store
    controller.delegate = self
    //self.navigationController?.setNavigationBarHidden(false, animated: true)
    self.navigationController?.pushViewController(controller, animated: true)
}


问:
Search for key by vector in map
So, we have a school-project in creating a phonebook where you should be able to look up phone numbers by searching for the name. I decided to use a map with a string for the phone number and and a vector of strings for the name, due associated number should be able to have multiple names in it.

However, due to us jumping straight from Python to C++ without any explanation of the syntax or the language, I am having a hard time coming up with a way to look for the number by searching for names.

The class I am using looks like this

```<code>class Telefonbok
{
    public:
        void add(string namn, string nummer)
        {
            map<string, vector<string>>::iterator it = boken.find(nummer);
            if (it != boken.end())
            {
                cout << "This number already exists, please choose another";
            }
            else
            {
                namn_alias.push_back(namn);
                boken[nummer] = namn_alias;
            }
        }
        void lookup(string name)
        {
            for (map<string, vector<string>>::iterator sokning = boken.begin(); sokning != boken.end(); sokning++)
                cout << "Hello!";
        }
    private:
        vector<string> namn_alias;
        string nummer;
        map<string, vector<string>> boken;
};
</code>```

What I am trying to do in lookup function is to search for a phone number by the names in the vector, but I am stumped on how to proceed with looking through the vector inside the for-loop.

The plan was to go through the Map keys one by one to find the vector that contains the searched-for name. Any tips on how to proceed or some functions I have missed that can be used for this?

答:
Algirdas is correct, you should read up on C++.

Assuming you are mapping name to 1-or-more numbers, but only 1 number per name...

```<code>#include <cstddef>
#include <iostream>
#include <map>
#include <string>
#include <vector>

using std::cout;
using std::endl;
using std::map;
using std::string;
using std::vector;

class Telefonbok
{
public:
  void add(string namn, string nummer) {
    auto it = nummer_namn.find(nummer);
    if (it != nummer_namn.end()) {
      cout << "This number already exists, please choose another" << endl;
    }
    else {
      nummer_namn[nummer] = namn;
      namn_nummer[namn].push_back(nummer);
    }
  }

  void lookup(string name) {
    auto it = namn_nummer.find(name);
    if (it == namn_nummer.end()) {
      cout << "Unable to find any numbers for " << name << ", sorry." << endl;
      return;
    }

    for (auto const& sokning : it->second)
      cout << name << " : " << sokning << endl;
  }
private:
  map<string, vector<string>> namn_nummer;
  map<string, string> nummer_namn;
};

int main() {
  Telefonbok bok;
  bok.add("Eljay", "789");
  bok.add("Eljay", "456");
  bok.add("Beaker", "123");

  bok.lookup("Eljay");
  bok.lookup("Beaker");
  bok.lookup("Bunsen Honeydew");

  return EXIT_SUCCESS;
}
</code>```

Title: Search for key by vector in map

Body:
So, we have a school-project in creating a phonebook where you should be able to look up phone numbers by searching for the name. I decided to use a map with a string for the phone number and and a vector of strings for the name, due associated number should be able to have multiple names in it.

However, due to us jumping straight from Python to C++ without any explanation of the syntax or the language, I am having a hard time coming up with a way to look for the number by searching for names.

The class I am using looks like this

class Telefonbok
{
    public:
        void add(string namn, string nummer)
        {
            map<string, vector<string>>::iterator it = boken.find(nummer);
            if (it != boken.end())
            {
                cout << "This number already exists, please choose another";
            }
            else
            {
                namn_alias.push_back(namn);
                boken[nummer] = namn_alias;
            }
        }
        void lookup(string name)
        {
            for (map<string, vector<string>>::iterator sokning = boken.begin(); sokning != boken.end(); sokning++)
                cout << "Hello!";
        }
    private:
        vector<string> namn_alias;
        string nummer;
        map<string, vector<string>> boken;
};

What I am trying to do in lookup function is to search for a phone number by the names in the vector, but I am stumped on how to proceed with looking through the vector inside the for-loop.

The plan was to go through the Map keys one by one to find the vector that contains the searched-for name. Any tips on how to proceed or some functions I have missed that can be used for this?

Body:
Algirdas is correct, you should read up on C++.

Assuming you are mapping name to 1-or-more numbers, but only 1 number per name...

#include <cstddef>
#include <iostream>
#include <map>
#include <string>
#include <vector>

using std::cout;
using std::endl;
using std::map;
using std::string;
using std::vector;

class Telefonbok
{
public:
  void add(string namn, string nummer) {
    auto it = nummer_namn.find(nummer);
    if (it != nummer_namn.end()) {
      cout << "This number already exists, please choose another" << endl;
    }
    else {
      nummer_namn[nummer] = namn;
      namn_nummer[namn].push_back(nummer);
    }
  }

  void lookup(string name) {
    auto it = namn_nummer.find(name);
    if (it == namn_nummer.end()) {
      cout << "Unable to find any numbers for " << name << ", sorry." << endl;
      return;
    }

    for (auto const& sokning : it->second)
      cout << name << " : " << sokning << endl;
  }
private:
  map<string, vector<string>> namn_nummer;
  map<string, string> nummer_namn;
};

int main() {
  Telefonbok bok;
  bok.add("Eljay", "789");
  bok.add("Eljay", "456");
  bok.add("Beaker", "123");

  bok.lookup("Eljay");
  bok.lookup("Beaker");
  bok.lookup("Bunsen Honeydew");

  return EXIT_SUCCESS;
}


问:
How to test Messenger Bots offline? Local webhooks
I'm starting with Messenger Platform API. I want to make simple Messenger Chatbot. Here is tutorial I follow.

As you see, to start I need to set up webhook (step 2). So basically: web server that provides some REST API and posts some data back. The problem is: facebook requires me to provide some real, existing app URL that works currently in internet. So, do I need to upload my code to server each time I change something? Can I somehow test it locally (on my localhost)? How can I test behavior of my bot?

答:
If you can't use ngrok for some reason (like routing webhook to multiples dev machines). please try this emulator i have created for developing / debugging webhooks locally. this provides emulation of send api and a messenger ui

I have created an emulator for send api and messenger which i use for debugging web hooks locally

https://github.com/SonOfSardaar/facebook-send-api-emulator

I also came across this (i have not tried this one yet but looks good)

https://learn.microsoft.com/en-us/bot-framework/debug-bots-emulator


问:
Mutable and Immutable Strings in python
I was just going through mutable and immutable structures in python.
It was written that "Strings are immutable" in Python i.e We cannot alter them
Consider the code:

```<code>str1='Rohit'
str1.replace('R','M')
</code>```

This gives the output:

```<code>'Mohit'
</code>```

Now, somebody said that it is the variable str1 which is pointing to the string 'Rohit' and after str1.replace() it points to 'Mohit'
Consider this code:

```<code>'Rohit'.replace('R','M')
</code>```

This also gives me the output:

```<code>'Mohit'
</code>```

Then what is meant by 'Strings are immutable'?

答: You are getting such output because that line of code does nothing to the string but creates a new string with R replaced with M (you can think it returned a variable), and in python when you simply type the name of a variale it is printed on the console. That's what created the confusion, I think.</p>

Title: Mutable and Immutable Strings in python

Body:
I was just going through mutable and immutable structures in python.
It was written that "Strings are immutable" in Python i.e We cannot alter them
Consider the code:

str1='Rohit'
str1.replace('R','M')

This gives the output:

'Mohit'

Now, somebody said that it is the variable str1 which is pointing to the string 'Rohit' and after str1.replace() it points to 'Mohit'
Consider this code:

'Rohit'.replace('R','M')

This also gives me the output:

'Mohit'

Then what is meant by 'Strings are immutable'?


问:
May the compiler silently convert from const to const& and vice versa?
The thought behind this is that the value won't be changed so that we don't need to care about the memory adress.

Of course there are special cases like (maybe only) polymorphism where this is not possible.

答:
A value copy of an object might not be taken if const& is substituted for const.

If that has a side effect then the compiler is not allowed to make the substitution.

In this respect, the rule differs from return value optimisation where a value copy is allowed to be dropped even if there are side effects.


问:
Ignore part of a string when splitting using regular expression in R
I'm trying to split a string in R (using strsplit) at some specific points (dash, -) however not if the dash are within a string in brackets ([).

Example:

```<code>xx <- c("Radio Stations-Listened to Past Week-Toronto [FM-CFXJ-93.5 (93.5 The Move)]","Total Internet-Time Spent Online-Past 7 Days")
xx
  [1] "Radio Stations-Listened to Past Week-Toronto [FM-CFXJ-93.5 (93.5 The Move)]"
  [2] "Total Internet-Time Spent Online-Past 7 Days"
</code>```

should give me something like:

```<code>list(c("Radio Stations","Listened to Past Week","Toronto [FM-CFXJ-93.5 (93.5 The Move)]"), c("Total Internet","Time Spent Online","Past 7 Days"))
  [[1]]
  [1] "Radio Stations"                         "Listened to Past Week"
  [3] "Toronto [FM-CFXJ-93.5 (93.5 The Move)]"

  [[2]]
  [1] "Total Internet"    "Time Spent Online" "Past 7 Days"
</code>```

Is there a way with regular expression to do this?  The position and the number of dashs change within each elements of the vector, and there is not always brackets.  However, when there are brackets, they are always at the end.

I've tried different things, but none are working:

```<code>## Trying to match "-" before "[" in Perl
strsplit(xx, split = "-(?=\\[)", perl=T)
# does nothing

## trying to first extract what follow "[" then splitting what is preceding that
temp <- strsplit(xx, "[", fixed = T)
temp <- lapply(temp, function(yy) substr(head(yy, -1),"-"))
# doesn't work as there are some elements with no brackets...
</code>```

Any help would be appreciated.

答:
To match a - that is not inside [ and ] you must match a part of the string that is enclosed with [ and ] and omit it, and match - in all other contexts. In abc-def], the - is not in between [ and ] and acc. to the specs should not be split against.

It is done with this regex:

```<code>\[[^][]*](*SKIP)(*FAIL)|-
</code>```

Here,

\[ - matches a [

[^][]* -  zero or more chars other than [ and ] (if you use [^]] it will match any char but ])

] - a literal ]

(*SKIP)(*FAIL)- PCRE verbs that omit the match and make the engine go on looking for the match after the end of the omitted one

| - or

- - a hyphen in other contexts.

Or, to match [...[...] like substrings (demo):

```<code>\[[^]]*](*SKIP)(*FAIL)|-
</code>```

Or, to account for nested square brackets (demo):

```<code>(\[(?:[^][]++|(?1))*])(*SKIP)(*FAIL)|-
</code>```

Here, (\[(?:[^][]++|(?1))*]) matches and captures [, then 1+ chars other than [ and ] (with [^][]++) or (|) (?1) recurses the whole capturing group 1 pattern (the whole part between (...)).

See the R demo:

```<code>xx <- c("abc-def]", "Radio Stations-Listened to Past Week-Toronto [FM-CFXJ-93.5 (93.5 The Move)]","Total Internet-Time Spent Online-Past 7 Days")
pattern <- "\\[[^][]*](*SKIP)(*FAIL)|-"
strsplit(xx, pattern, perl=TRUE)
# [[1]]
# [1] "abc"  "def]"
# [[2]]
# [1] "Radio Stations"
# [2] "Listened to Past Week"
# [3] "Toronto [FM-CFXJ-93.5 (93.5 The Move)]"
# [[3]]
# [1] "Total Internet"    "Time Spent Online" "Past 7 Days"

pattern_recursive <- "(\\[(?:[^][]++|(?1))*])(*SKIP)(*FAIL)|-"
xx2 <- c("Radio Stations-Listened to Past Week-Toronto [[F[M]]-CFXJ-93.5 (93.5 The Move)]","Total Internet-Time Spent Online-Past 7 Days")
strsplit(xx2, pattern_recursive, perl=TRUE)
# [[1]]
# [1] "Radio Stations"
# [2] "Listened to Past Week"
# [3] "Toronto [[F[M]]-CFXJ-93.5 (93.5 The Move)]"

# [[2]]
# [1] "Total Internet"    "Time Spent Online" "Past 7 Days"
</code>```

Body:
I'm trying to split a string in R (using strsplit) at some specific points (dash, -) however not if the dash are within a string in brackets ([).

Example:

xx <- c("Radio Stations-Listened to Past Week-Toronto [FM-CFXJ-93.5 (93.5 The Move)]","Total Internet-Time Spent Online-Past 7 Days")
xx
  [1] "Radio Stations-Listened to Past Week-Toronto [FM-CFXJ-93.5 (93.5 The Move)]"
  [2] "Total Internet-Time Spent Online-Past 7 Days"

should give me something like:

list(c("Radio Stations","Listened to Past Week","Toronto [FM-CFXJ-93.5 (93.5 The Move)]"), c("Total Internet","Time Spent Online","Past 7 Days"))
  [[1]]
  [1] "Radio Stations"                         "Listened to Past Week"
  [3] "Toronto [FM-CFXJ-93.5 (93.5 The Move)]"

  [[2]]
  [1] "Total Internet"    "Time Spent Online" "Past 7 Days"

Is there a way with regular expression to do this?  The position and the number of dashs change within each elements of the vector, and there is not always brackets.  However, when there are brackets, they are always at the end.

I've tried different things, but none are working:

## Trying to match "-" before "[" in Perl
strsplit(xx, split = "-(?=\\[)", perl=T)
# does nothing

## trying to first extract what follow "[" then splitting what is preceding that
temp <- strsplit(xx, "[", fixed = T)
temp <- lapply(temp, function(yy) substr(head(yy, -1),"-"))
# doesn't work as there are some elements with no brackets...

Any help would be appreciated.

Body:
To match a - that is not inside [ and ] you must match a part of the string that is enclosed with [ and ] and omit it, and match - in all other contexts. In abc-def], the - is not in between [ and ] and acc. to the specs should not be split against.

It is done with this regex:

\[[^][]*](*SKIP)(*FAIL)|-

Here,

\[ - matches a [

[^][]* -  zero or more chars other than [ and ] (if you use [^]] it will match any char but ])

] - a literal ]

(*SKIP)(*FAIL)- PCRE verbs that omit the match and make the engine go on looking for the match after the end of the omitted one

| - or

- - a hyphen in other contexts.

Or, to match [...[...] like substrings (demo):

\[[^]]*](*SKIP)(*FAIL)|-

Or, to account for nested square brackets (demo):

(\[(?:[^][]++|(?1))*])(*SKIP)(*FAIL)|-

Here, (\[(?:[^][]++|(?1))*]) matches and captures [, then 1+ chars other than [ and ] (with [^][]++) or (|) (?1) recurses the whole capturing group 1 pattern (the whole part between (...)).

See the R demo:

xx <- c("abc-def]", "Radio Stations-Listened to Past Week-Toronto [FM-CFXJ-93.5 (93.5 The Move)]","Total Internet-Time Spent Online-Past 7 Days")
pattern <- "\\[[^][]*](*SKIP)(*FAIL)|-"
strsplit(xx, pattern, perl=TRUE)
# [[1]]
# [1] "abc"  "def]"
# [[2]]
# [1] "Radio Stations"
# [2] "Listened to Past Week"
# [3] "Toronto [FM-CFXJ-93.5 (93.5 The Move)]"
# [[3]]
# [1] "Total Internet"    "Time Spent Online" "Past 7 Days"

pattern_recursive <- "(\\[(?:[^][]++|(?1))*])(*SKIP)(*FAIL)|-"
xx2 <- c("Radio Stations-Listened to Past Week-Toronto [[F[M]]-CFXJ-93.5 (93.5 The Move)]","Total Internet-Time Spent Online-Past 7 Days")
strsplit(xx2, pattern_recursive, perl=TRUE)
# [[1]]
# [1] "Radio Stations"
# [2] "Listened to Past Week"
# [3] "Toronto [[F[M]]-CFXJ-93.5 (93.5 The Move)]"

# [[2]]
# [1] "Total Internet"    "Time Spent Online" "Past 7 Days"


问:
SEGMENTATION FAULT (11) for one of my 2d arrays?
I have 2x 2D arrays as a pointer.
one is "int ** field" and the other one "char **mask".
I want to create 2 2D arrays and initialise them.
The code I have works for the int array but not for the char array, although the code is the same... why?

```<code>Minesweeper * createField(int n, int m){

    Minesweeper *ms = (Minesweeper *) malloc(sizeof(Minesweeper *));

    ms->m = m;
    ms->n = n;

    ms->field = (int **) malloc(sizeof(int *) * n);
    ms->mask  = (char **) malloc(sizeof(char *) * n);
    for(int i=0; i<n; i++){
        ms->field[i] = (int *) malloc(sizeof(int *) * m);
        ms->mask[i] = (char *) malloc(sizeof(char *) * m);
    }

    for(int k=0; k<n; k++){
        for(int j=0; j<m; j++){
            ms->field[k][j] = 0;
            ms->mask[k][j] = 'x';
        }
    }

    return ms;
}
</code>```

By the way:

Minesweeper is a typedef struct with 4 attributes: int** field, char** mask, int m and int n.

I always get Segmentation fault when I want to initialize my mask array...

答:
Be careful when you allocate like

```<code>malloc(sizeof(Minesweeper *));
</code>```

you get memory for a single pointer allocated - (Minesweeper *). To allocate memory for the whole structure you have to use sizeof(Minesweeper) - without the asterisk.

So replace with:

```<code>Minesweeper *ms = (Minesweeper *) malloc(sizeof(Minesweeper));
</code>```

and

```<code>ms->field[i] = (int *) malloc(sizeof(int) * m);
ms->mask[i] = (char *) malloc(sizeof(char) * m);
</code>```

Body:
I have 2x 2D arrays as a pointer.
one is "int ** field" and the other one "char **mask".
I want to create 2 2D arrays and initialise them.
The code I have works for the int array but not for the char array, although the code is the same... why?

Minesweeper * createField(int n, int m){

    Minesweeper *ms = (Minesweeper *) malloc(sizeof(Minesweeper *));

    ms->m = m;
    ms->n = n;

    ms->field = (int **) malloc(sizeof(int *) * n);
    ms->mask  = (char **) malloc(sizeof(char *) * n);
    for(int i=0; i<n; i++){
        ms->field[i] = (int *) malloc(sizeof(int *) * m);
        ms->mask[i] = (char *) malloc(sizeof(char *) * m);
    }

    for(int k=0; k<n; k++){
        for(int j=0; j<m; j++){
            ms->field[k][j] = 0;
            ms->mask[k][j] = 'x';
        }
    }

    return ms;
}

By the way:

Minesweeper is a typedef struct with 4 attributes: int** field, char** mask, int m and int n.

I always get Segmentation fault when I want to initialize my mask array...

Body:
Be careful when you allocate like

malloc(sizeof(Minesweeper *));

you get memory for a single pointer allocated - (Minesweeper *). To allocate memory for the whole structure you have to use sizeof(Minesweeper) - without the asterisk.

So replace with:

Minesweeper *ms = (Minesweeper *) malloc(sizeof(Minesweeper));

and

ms->field[i] = (int *) malloc(sizeof(int) * m);
ms->mask[i] = (char *) malloc(sizeof(char) * m);


问:
View specific css in Razor Pages with _Layout.cshtml
I have a _Layout.cshtml file with a  section that looks like so:

```<code><head>
    <title>Dashboard</title>
    <link rel="stylesheet" href="css/bootstrap.min.css"/>
    <link rel="stylesheet" href="css/layout.css"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
</code>```

I have a View called Index.cshtml (that is using _Layout.cshtml as a layout) with a  section that looks like so:

```<code><head>
    <link rel="stylesheet" href="css/Home/Index.css"/>
    <script src="https://cdn.datatables.net/v/bs/jq-3.2.1/dt-1.10.16/datatables.min.js"></script>
    <link href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap.min.css" rel="stylesheet" />
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
</head>
</code>```

Now this line in Index.cshtml is styling my DataTables correctly, but it is messing up my layout page even though it is located in the Index.cshtml and not the _Layout.cshtml:

```<code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
</code>```

I must be getting a bit messed up with how my css is working throughout my web app. I have tried using @section but I couldn't get that to work either.

So my question is how can I make the css in Index.cshtml only apply to that page rather than also affecting the css in _Layout.cshtml?

答:
In your _Layout.cshtml use the RenderSection method with the required argument set to false:

```<code><head>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
    ....
    @RenderSection("head",false)
</head>
</code>```

Then in your view that requires additional css:

```<code>@section head {
  <link href="my_view_specific_css.css" rel="stylesheet" />
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a _Layout.cshtml file with a  section that looks like so:

    <title>Dashboard</title>
    <link rel="stylesheet" href="css/bootstrap.min.css"/>
    <link rel="stylesheet" href="css/layout.css"/>

I have a View called Index.cshtml (that is using _Layout.cshtml as a layout) with a  section that looks like so:

    <link rel="stylesheet" href="css/Home/Index.css"/>

    <link href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap.min.css" rel="stylesheet" />
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

Now this line in Index.cshtml is styling my DataTables correctly, but it is messing up my layout page even though it is located in the Index.cshtml and not the _Layout.cshtml:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

I must be getting a bit messed up with how my css is working throughout my web app. I have tried using @section but I couldn't get that to work either.

So my question is how can I make the css in Index.cshtml only apply to that page rather than also affecting the css in _Layout.cshtml?

Body:
In your _Layout.cshtml use the RenderSection method with the required argument set to false:

<head>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
    ....
    @RenderSection("head",false)
</head>

Then in your view that requires additional css:

@section head {
  <link href="my_view_specific_css.css" rel="stylesheet" />
}


问:
Is there an equivalent to __MODULE__ for named functions in Elixir/ Erlang?
Is there an equivalent for retrieving the name of a function just like like __MODULE__ retrieves the name of a Module in Elixir/Erlang?

Example:

```<code>defmodule Demo do
  def home_menu do
    module_name = __MODULE__
    func_name = :home_menu
    # is there a __FUNCTION__
  end
End
</code>```

EDITED

The selected answer works,

but calling the returned function name with apply/3 yields this error:

```<code>[error] %UndefinedFunctionError{arity: 4, exports: nil, function: :public_home, module: Demo, reason: nil}
</code>```

I have a function :

```<code>defp public_home(u, m, msg, reset) do

end
</code>```

The function in question will strictly be called within its module.

Is there a way to dynamically call a private function by name within its own module?

答:
Yes, there is. In Erlang there are several predefined macros that should be able to provide the information you need:

```<code>% The name of the current function
?FUNCTION_NAME

% The arity of the current function (remember name alone isn't enough to identify a function in Erlang/Elixir)
?FUNCTION_ARITY

% The file name of the current module
?FILE

% The line number of the current line
?LINE
</code>```

Source: http://erlang.org/doc/reference_manual/macros.html#id85926

Body:
Is there an equivalent for retrieving the name of a function just like like __MODULE__ retrieves the name of a Module in Elixir/Erlang?

Example:

defmodule Demo do
  def home_menu do
    module_name = __MODULE__
    func_name = :home_menu
    # is there a __FUNCTION__
  end
End

EDITED

The selected answer works,

but calling the returned function name with apply/3 yields this error:

[error] %UndefinedFunctionError{arity: 4, exports: nil, function: :public_home, module: Demo, reason: nil}

I have a function :

defp public_home(u, m, msg, reset) do

end

The function in question will strictly be called within its module.

Is there a way to dynamically call a private function by name within its own module?

Body:
Yes, there is. In Erlang there are several predefined macros that should be able to provide the information you need:

% The name of the current function
?FUNCTION_NAME

% The arity of the current function (remember name alone isn't enough to identify a function in Erlang/Elixir)
?FUNCTION_ARITY

% The file name of the current module
?FILE

% The line number of the current line
?LINE

Source: http://erlang.org/doc/reference_manual/macros.html#id85926


问:
phpunit / Symfony: BadMethodCallException
I want to test the http status code of URLs from my project.

By some tests I got the following error message from phpunit:

```<code>1) pp\TheBundle\Tests\UrlTests\UrlTests::test18Url
PHPUnit_Framework_Exception: PHP Fatal error:  Uncaught exception 'BadMethodCallException' with message 'A Crawler cannot be serialized.' in /var/www/viasenso/muttersystem/vendor/symfony/symfony/src/Symfony/Component/DomCrawler/Crawler.php:315
Stack trace:
#0 [internal function]: Symfony\Component\DomCrawler\Crawler->serialize()
#1 -(364): serialize(Array)
#2 -(513): __phpunit_run_isolated_test()
#3 {main}
  thrown in /var/www/viasenso/muttersystem/vendor/symfony/symfony/src/Symfony/Component/DomCrawler/Crawler.php on line 315

Fatal error: Uncaught exception 'BadMethodCallException' with message 'A Crawler cannot be serialized.' in /var/www/viasenso/muttersystem/vendor/symfony/symfony/src/Symfony/Component/DomCrawler/Crawler.php on line 315

BadMethodCallException: A Crawler cannot be serialized. in /var/www/viasenso/muttersystem/vendor/symfony/symfony/src/Symfony/Component/DomCrawler/Crawler.php on line 315

Call Stack:
    0.0022     441400   1. {main}() -:0
    0.0400    4434840   2. __phpunit_run_isolated_test() -:513
    0.6232   30949432   3. serialize() -:364
    0.6235   31024280   4. Symfony\Component\DomCrawler\Crawler->serialize() -:364
</code>```

This is the content of the test function:

```<code>$crawler = $this->helper->getCrawler('/de/profil/the-profile/123/veroeffentlichen', [
    'user' => $this->helper->getParameter('testing')['user']['admin']['username'],
    'pwd' => $this->helper->getParameter('testing')['user']['admin']['password'],
]);

$this->assertEquals(Response::HTTP_OK, $this->client->getResponse()->getStatusCode(),
    'Status-Code ' . $this->client->getResponse()->getStatusCode() . ' on URL ' . $this->client->getRequest()->getUri() . '');
</code>```

Any ideas, why this error happens? The debugging informations from phpunit are not really helpfull...

答: Change config processIsolation to false, you should get a more clear test failed message

Body:
I want to test the http status code of URLs from my project.

By some tests I got the following error message from phpunit:

1) pp\TheBundle\Tests\UrlTests\UrlTests::test18Url
PHPUnit_Framework_Exception: PHP Fatal error:  Uncaught exception 'BadMethodCallException' with message 'A Crawler cannot be serialized.' in /var/www/viasenso/muttersystem/vendor/symfony/symfony/src/Symfony/Component/DomCrawler/Crawler.php:315
Stack trace:
#0 [internal function]: Symfony\Component\DomCrawler\Crawler->serialize()
#1 -(364): serialize(Array)
#2 -(513): __phpunit_run_isolated_test()
#3 {main}
  thrown in /var/www/viasenso/muttersystem/vendor/symfony/symfony/src/Symfony/Component/DomCrawler/Crawler.php on line 315

Fatal error: Uncaught exception 'BadMethodCallException' with message 'A Crawler cannot be serialized.' in /var/www/viasenso/muttersystem/vendor/symfony/symfony/src/Symfony/Component/DomCrawler/Crawler.php on line 315

BadMethodCallException: A Crawler cannot be serialized. in /var/www/viasenso/muttersystem/vendor/symfony/symfony/src/Symfony/Component/DomCrawler/Crawler.php on line 315

Call Stack:
    0.0022     441400   1. {main}() -:0
    0.0400    4434840   2. __phpunit_run_isolated_test() -:513
    0.6232   30949432   3. serialize() -:364
    0.6235   31024280   4. Symfony\Component\DomCrawler\Crawler->serialize() -:364

This is the content of the test function:

$crawler = $this->helper->getCrawler('/de/profil/the-profile/123/veroeffentlichen', [
    'user' => $this->helper->getParameter('testing')['user']['admin']['username'],
    'pwd' => $this->helper->getParameter('testing')['user']['admin']['password'],
]);

$this->assertEquals(Response::HTTP_OK, $this->client->getResponse()->getStatusCode(),
    'Status-Code ' . $this->client->getResponse()->getStatusCode() . ' on URL ' . $this->client->getRequest()->getUri() . '');

Any ideas, why this error happens? The debugging informations from phpunit are not really helpfull...


问:
firebase functions push Notifications to specific user
i want to send Push notification via firebase functions to the user who posted the post when some other user likes his/her post.

i want to get the highlighted user-id in the image to get fcm token of this user id stored in other tree.

here is my firebase function code below.

```<code>    const functions = require('firebase-functions');

    const admin = require('firebase-admin');
    admin.initializeApp(functions.config().firebase);

exports.sendNotification = functions.database.ref('/user-posts/{userID}/{pushId}/stars/')
        .onWrite(event=> {
            var request = event.data.val();

            console.log("request",request);
            console.log("key",Object.keys(request)[0]);
            var key = Object.keys(request)[0];
            var token;

            const payload = {
          notification: {
            title: 'You have a new follower!',
            body: 'is now following you.'
          }
        };

             const getDeviceTokensPromise = admin.database()
             .ref(`/users-notifications/${key}`)
             .once('value').then(function(snapshot) {
                    console.log("val",snapshot.val());
                        token= snapshot.val();

                        admin.messaging().sendToDevice(token,payload)
            .then(response=>{
                console.log("Successfully sent message:", response);

            })
            .catch(function(error){
                console.log("error sending message",error);
            })
        })

                    }, function(error) {
                        // The Promise was rejected.
                    console.error(error);
                    });
</code>```

答:
You can backwards traverse the DB tree by using the event ref's parent property.

```<code>userID = event.data.ref.parent.parent.parent.key
</code>```

parent of event.data.ref is "stars"
parent of "stars" is your pushID
parent of pushID is userID

Body:
i want to send Push notification via firebase functions to the user who posted the post when some other user likes his/her post.

i want to get the highlighted user-id in the image to get fcm token of this user id stored in other tree.

here is my firebase function code below.

    const functions = require('firebase-functions');

    const admin = require('firebase-admin');
    admin.initializeApp(functions.config().firebase);

exports.sendNotification = functions.database.ref('/user-posts/{userID}/{pushId}/stars/')
        .onWrite(event=> {
            var request = event.data.val();

            console.log("request",request);
            console.log("key",Object.keys(request)[0]);
            var key = Object.keys(request)[0];
            var token;

            const payload = {
          notification: {
            title: 'You have a new follower!',
            body: 'is now following you.'
          }
        };

             const getDeviceTokensPromise = admin.database()
             .ref(`/users-notifications/${key}`)
             .once('value').then(function(snapshot) {
                    console.log("val",snapshot.val());
                        token= snapshot.val();

                        admin.messaging().sendToDevice(token,payload)
            .then(response=>{
                console.log("Successfully sent message:", response);

            })
            .catch(function(error){
                console.log("error sending message",error);
            })
        })

                    }, function(error) {
                        // The Promise was rejected.
                    console.error(error);
                    });

Body:
You can backwards traverse the DB tree by using the event ref's parent property.

userID = event.data.ref.parent.parent.parent.key

parent of event.data.ref is "stars"
parent of "stars" is your pushID
parent of pushID is userID


问:
Vagrant won't forward ONLY port 80
I have port forwarding set up for vagrant

```<code>Vagrant.configure("2") do |config|
  config.vm.box = "centOS"
  config.vm.network :forwarded_port, guest: 80, host: 80
  config.vm.network :forwarded_port, guest: 8443, host: 8443
  config.vm.network :forwarded_port, guest: 8443, host: 9443
  config.vm.network :forwarded_port, guest: 8445, host: 8445
  config.vm.network :forwarded_port, guest: 8000, host: 8000
  config.vm.hostname = "www.vagrant.com"
end
</code>```

Port 80 is open from my vagrant virtual box

```<code>[vagrant@www ~]$ nmap -sT 0.0.0.0 -p 80

Starting Nmap 5.51 ( http://nmap.org ) at 2013-07-02 22:25 UTC
Nmap scan report for 0.0.0.0
Host is up (0.000063s latency).
PORT   STATE SERVICE
80/tcp open  http
</code>```

But it is closed from my host machine

```<code>Ben-Fischer:~ bfischer$ nmap -sT 0.0.0.0 -p 80

Starting Nmap 6.25 ( http://nmap.org ) at 2013-07-02 17:38 CDT
Nmap scan report for 0.0.0.0
Host is up (0.000086s latency).
PORT   STATE  SERVICE
80/tcp closed http
</code>```

Nothing else is listening on port 80 on my host machine

```<code>Ben-Fischer:~ bfischer$ sudo lsof -n -i4TCP:80 | grep LISTEN
[no output]
</code>```

Iptables are off and so is my mac firewall

```<code>[vagrant@www ~]$ sudo service iptables stop
</code>```

And all of the other forwarded ports work fine (8443,9443,8445,8000)

The box is an image from vagrant, centOS 6.3 with chef.

So... why can't I connect to port 80 from my local machine?

答:
You can config port forwarding into VirtualBox:

Your VM -> Settings -> Network -> Advanced -> ports forwarding

Here you can add ports that you need.

Title: Vagrant won't forward ONLY port 80

Body:
I have port forwarding set up for vagrant

Vagrant.configure("2") do |config|
  config.vm.box = "centOS"
  config.vm.network :forwarded_port, guest: 80, host: 80
  config.vm.network :forwarded_port, guest: 8443, host: 8443
  config.vm.network :forwarded_port, guest: 8443, host: 9443
  config.vm.network :forwarded_port, guest: 8445, host: 8445
  config.vm.network :forwarded_port, guest: 8000, host: 8000
  config.vm.hostname = "www.vagrant.com"
end

Port 80 is open from my vagrant virtual box

[vagrant@www ~]$ nmap -sT 0.0.0.0 -p 80

Starting Nmap 5.51 ( http://nmap.org ) at 2013-07-02 22:25 UTC
Nmap scan report for 0.0.0.0
Host is up (0.000063s latency).
PORT   STATE SERVICE
80/tcp open  http

But it is closed from my host machine

Ben-Fischer:~ bfischer$ nmap -sT 0.0.0.0 -p 80

Starting Nmap 6.25 ( http://nmap.org ) at 2013-07-02 17:38 CDT
Nmap scan report for 0.0.0.0
Host is up (0.000086s latency).
PORT   STATE  SERVICE
80/tcp closed http

Nothing else is listening on port 80 on my host machine

Ben-Fischer:~ bfischer$ sudo lsof -n -i4TCP:80 | grep LISTEN
[no output]

Iptables are off and so is my mac firewall

[vagrant@www ~]$ sudo service iptables stop

And all of the other forwarded ports work fine (8443,9443,8445,8000)

The box is an image from vagrant, centOS 6.3 with chef.

So... why can't I connect to port 80 from my local machine?


问:
Python's threading and multiprocess lock not working
I have a toy example that demonstrates multithreading and locks. Without locks, I obviously get a bad value for the global counter variable. However, when I put in the threading.Lock in, it leads to even more inconsistencies. Also, multiprocessing.Lock() doesn't completely fix the problem either.

```<code>import threading
from multiprocessing import Process, Lock

num_experiments = 200
num_threads = 5
iterations_in_one_thread = 500

def f():

    global counter
    for i in range(iterations_in_one_thread):
        with lock:
            counter += 1

bad_count = 0
# lock = threading.Lock()
lock = Lock()

for x in range(num_experiments):

    counter = 0
    threads = []
    for i in range(num_threads):
        t = threading.Thread(target=f)
        threads.append(t)
        t.start()

    for i in threads:
        t.join()

    if counter != num_threads * iterations_in_one_thread:
        bad_count += 1
        print counter

print "Bad count:", bad_count
print "Total runs:", num_experiments
</code>```

Output I expect: Bad count: 0
Output I get: Bad count: 3 (or sometimes upto 6)

I'm on python 2.7.3

```<code>Python 2.7.13 |Anaconda custom (x86_64)| (default, Dec 20 2016, 23:05:08)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin
</code>```

答:
I think that you just made a simple typo.

```<code>for i in threads:
    t.join()
</code>```

should be

```<code>for i in threads:
    i.join()
</code>```

Otherwise, you're only joining on the last thread. Also, you probably shouldn't mix the multiprocessing library with the threading library. Stick with threading.Lock.

Body:
I have a toy example that demonstrates multithreading and locks. Without locks, I obviously get a bad value for the global counter variable. However, when I put in the threading.Lock in, it leads to even more inconsistencies. Also, multiprocessing.Lock() doesn't completely fix the problem either.

import threading
from multiprocessing import Process, Lock

num_experiments = 200
num_threads = 5
iterations_in_one_thread = 500

def f():

    global counter
    for i in range(iterations_in_one_thread):
        with lock:
            counter += 1

bad_count = 0
# lock = threading.Lock()
lock = Lock()

for x in range(num_experiments):

    counter = 0
    threads = []
    for i in range(num_threads):
        t = threading.Thread(target=f)
        threads.append(t)
        t.start()

    for i in threads:
        t.join()

    if counter != num_threads * iterations_in_one_thread:
        bad_count += 1
        print counter

print "Bad count:", bad_count
print "Total runs:", num_experiments

Output I expect: Bad count: 0
Output I get: Bad count: 3 (or sometimes upto 6)

I'm on python 2.7.3

Python 2.7.13 |Anaconda custom (x86_64)| (default, Dec 20 2016, 23:05:08)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin

Body:
I think that you just made a simple typo.

for i in threads:
    t.join()

should be

for i in threads:
    i.join()

Otherwise, you're only joining on the last thread. Also, you probably shouldn't mix the multiprocessing library with the threading library. Stick with threading.Lock.


问:
For high scalability & performance needs, is it preferable to have C++ or Java implementation at the backend of a PHP application?
For high scalability & performance needs for a social portal, is it advisable to have C++ or Java implementation at the backend of an PHP application ?

What are the benefits & trade-offs of the same ?

答:
First of all PHP is already a backend. PHP itself is implemented in C or C++.

For scalability language doesn't matter, because scalability is about parallel handling of multiple requests.

For performance as in "get a single request processed as soon as possible", language usually matters that's why Facebook wrote PHP to C++ compiler.


问:
MATLAB Using a single figure frame for chasePlot used inside a loop
I have a while loop inside of which I have to use a plot and a chasePlot function.

The problem is, it comes up with a new window figure each time the loop runs. I somehow want a single frame which can be updated rather than each time making a new window and figure for it.

Anybody knows how to prevent a new figure in each loop so that one figure is there and that keeps on updating.

答:
Don't use 'figure' before the 'plot' command and the code will keep overwriting every time on the same figure. You can also use the 'drawnow limitrate' command for better visualization. See an example below:</p>

```<code>    clc; close all; clear all;

    x = 0 :100 :1e5;

    y = zeros(size(x));

    for n = 1:numel(x)

        y(n) = sin(x(n));

        plot(x(1:n), y(1:n));

        drawnow limitrate;

    end
</code>```

Body:
Don't use 'figure' before the 'plot' command and the code will keep overwriting every time on the same figure. You can also use the 'drawnow limitrate' command for better visualization. See an example below:

    clc; close all; clear all;

    x = 0 :100 :1e5;

    y = zeros(size(x));

    for n = 1:numel(x)

        y(n) = sin(x(n));

        plot(x(1:n), y(1:n));

        drawnow limitrate;

    end


问:
How I can I unit test that a function inside another function was called?
How I can I unit test that a function inside another function was called? I can't change the source code, so I need to test this as-is.

How can I do this? Here's my code:

```<code>function B(){ console.log('function b'); }

function A(){
    B();
}
</code>```

Jasmine test:

```<code>it('should check function B in function A was called', function () {
    spyOn(window, 'B');
    A();
    expect(B).toHaveBeenCalled();
});
</code>```

答:
Spies

Jasmine has test double functions called spies. A spy can stub any
  function and tracks calls to it and all arguments. A spy only exists
  in the describe or it block in which it is defined, and will be
  removed after each spec. There are special matchers for interacting
  with spies. This syntax has changed for Jasmine 2.0. The
  toHaveBeenCalled matcher will return true if the spy was called. The
  toHaveBeenCalledWith matcher will return true if the argument list
  matches any of the recorded calls to the spy.

```<code> describe("A spy", function() {
  var foo, bar = null;

  beforeEach(function() {
    foo = {
      setBar: function(value) {
        bar = value;
      }
    };

    spyOn(foo, 'setBar');

    foo.setBar(123);
    foo.setBar(456, 'another param');
  });

  it("tracks that the spy was called", function() {
    expect(foo.setBar).toHaveBeenCalled();
  });

  it("tracks all the arguments of its calls", function() {
    expect(foo.setBar).toHaveBeenCalledWith(123);
    expect(foo.setBar).toHaveBeenCalledWith(456, 'another param');
  });

  it("stops all execution on a function", function() {
    expect(bar).toBeNull();
  });
});
</code>```

Body:
How I can I unit test that a function inside another function was called? I can't change the source code, so I need to test this as-is.

How can I do this? Here's my code:

function B(){ console.log('function b'); }

function A(){
    B();
}

Jasmine test:

it('should check function B in function A was called', function () {
    spyOn(window, 'B');
    A();
    expect(B).toHaveBeenCalled();
});

Body:
Spies

Jasmine has test double functions called spies. A spy can stub any
  function and tracks calls to it and all arguments. A spy only exists
  in the describe or it block in which it is defined, and will be
  removed after each spec. There are special matchers for interacting
  with spies. This syntax has changed for Jasmine 2.0. The
  toHaveBeenCalled matcher will return true if the spy was called. The
  toHaveBeenCalledWith matcher will return true if the argument list
  matches any of the recorded calls to the spy.

 describe("A spy", function() {
  var foo, bar = null;

  beforeEach(function() {
    foo = {
      setBar: function(value) {
        bar = value;
      }
    };

    spyOn(foo, 'setBar');

    foo.setBar(123);
    foo.setBar(456, 'another param');
  });

  it("tracks that the spy was called", function() {
    expect(foo.setBar).toHaveBeenCalled();
  });

  it("tracks all the arguments of its calls", function() {
    expect(foo.setBar).toHaveBeenCalledWith(123);
    expect(foo.setBar).toHaveBeenCalledWith(456, 'another param');
  });

  it("stops all execution on a function", function() {
    expect(bar).toBeNull();
  });
});


问:
Wicket: Setting value of DropDownChoice with CompoundPropertyModel
I'm filling a form with data from a CompoundPropertyModel. My TextArea and DateTextField get their value by using the name of the field of the Model as the Id so it will look for a Model in it's parents and find the value through reflection, as described in https://ci.apache.org/projects/wicket/guide/6.x/guide/modelsforms.html.
But I fail to get this working for my DropDownChoice. The value stays null.

Would love to hear if someone knows what I'm doing wrong. Currently have a workarround in place where I give a PropertyModel of the FotoGroep to my DropDownChoice constructor.

Class:

```<code>public class ImageControlForm<T extends Foto> extends StatelessForm<Foto> {

    private TextArea<String> beschrijving;
    private DateTextField datum;
    private DropDownChoice<FotoGroep> groep;

    public ImageControlForm(String id, CompoundPropertyModel<Foto> fotoModel) {
        super(id, fotoModel);

        setMultiPart(true);
        setDefaultModel(fotoModel);

        add(maakBeschrijvingField());
        add(maakDatumField());
        add(maakGroepField());
    }

    private TextArea<?> maakBeschrijvingField() {
        beschrijving = new TextArea<>("beschrijving");
        return beschrijving;
    }

    private DateTextField maakDatumField() {
        datum = new DateTextField("datum", "d/M/yy");
        datum.add(new DatumPicker());
        return datum;
    }

    private DropDownChoice<FotoGroep> maakGroepField() {
        Order sortOrder = Helper.createOrder("naam", SortOrder.ASC);
        List<FotoGroep> fotoGroepen = databaseService.getPictureGroups(sortOrder);
        groep = new DropDownChoice<>("fotoGroep", fotoGroepen, new ChoiceRenderer<FotoGroep>("naam", "fotoGroepId"));
        groep.isRequired();
        return groep;
    }
</code>```

Foto:

```<code>@Entity
@Table(name = "XS_FOTO")
public class Foto extends BasisModel implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "FOTO_ID")
    private Long fotoId;

    @Column(name = "BESCHRIJVING", nullable = true)
    private String beschrijving;

    @Column(name = "DATUM", nullable = true)
    @Temporal(TemporalType.DATE)
    private Date datum;

    @ManyToOne
    @JoinColumn(name = "FOTO_GROEP_ID", nullable = false)
    private FotoGroep fotoGroep = new FotoGroep(Long.valueOf(12));

    (getters and setters)
</code>```

FotoGroep:

```<code>@Entity
@Table(name = "XS_FOTO_GROEP")
public class FotoGroep extends BasisModel implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "FOTO_GROEP_ID")
    private Long fotoGroepId;

    @Column(name = "NAAM", nullable = false)
    private String naam;

    @Override
    public boolean equals(Object object) {
        return (this.getFotoGroepId().equals(((FotoGroep)object).getFotoGroepId()));
    }

    @Override
    public int hashCode() {
        return Objects.hash(fotoGroepId, naam, beschrijving, datum);
    }

    (getters and setters)
</code>```

As requested, I tried overriding equals and hashCode but without succes. I debugged and the foto.fotoGroep.fotoGroepId is the same as the only fotoGroep.fotoGroepId in the List<FotoGroepen>. Both FotoGroep even are the same bean at runtime. My unit test put's the same FotoGroep in the list as in the Model.

Edit, possible bad unit test(?):
I was testing the value of my DropDownChoice with:

```<code>assertEquals("456", formTester.getTextComponentValue("fotoGroep"));
</code>```

The value kept returning Null. BUT when I check the HTML, I can see that the right option is selected:

```<code><select wicket:id="fotoGroep" name="fotoGroep" disabled="disabled">
    <option value="123">naam</option>
    <option value="123">naam</option>
    <option value="123">naam</option>
    <option value="123">naam</option>
    <option value="123">naam</option>
    <option value="123">naam</option>
    <option selected="selected" value="456">naam</option>
</select>
</code>```

Could someone explain this behavior? When using a PropertyModel inside my DropDownChoice it also sets the value, but not when using the Model inheritance.

答:
I was testing DropDownChoice wrong.

I was testing the value of the DropDownChoice:

```<code>assertEquals("456", formTester.getTextComponentValue("fotoGroep"));
</code>```

But in my case, this value was never set, BUT the right option was selected! I've changed my test to:

```<code>DropDownChoice<FotoGroep> dropDownChoice = (DropDownChoice)tester.getComponentFromLastRenderedPage("imageControlPanel:imageControlForm:fotoGroep");
dropDownChoice.setModelObject(createFotoGroep);
tester.assertModelValue("imageControlPanel:imageControlForm:fotoGroep", dropDownChoice.getModelObject());
</code>```

The test will take the DropDownChoice, set the value you are expecting and then compare the Models of both.

Body:
I'm filling a form with data from a CompoundPropertyModel. My TextArea and DateTextField get their value by using the name of the field of the Model as the Id so it will look for a Model in it's parents and find the value through reflection, as described in https://ci.apache.org/projects/wicket/guide/6.x/guide/modelsforms.html.
But I fail to get this working for my DropDownChoice. The value stays null.

Would love to hear if someone knows what I'm doing wrong. Currently have a workarround in place where I give a PropertyModel of the FotoGroep to my DropDownChoice constructor.

Class:

public class ImageControlForm<T extends Foto> extends StatelessForm<Foto> {

    private TextArea<String> beschrijving;
    private DateTextField datum;
    private DropDownChoice<FotoGroep> groep;

    public ImageControlForm(String id, CompoundPropertyModel<Foto> fotoModel) {
        super(id, fotoModel);

        setMultiPart(true);
        setDefaultModel(fotoModel);

        add(maakBeschrijvingField());
        add(maakDatumField());
        add(maakGroepField());
    }

    private TextArea<?> maakBeschrijvingField() {
        beschrijving = new TextArea<>("beschrijving");
        return beschrijving;
    }

    private DateTextField maakDatumField() {
        datum = new DateTextField("datum", "d/M/yy");
        datum.add(new DatumPicker());
        return datum;
    }

    private DropDownChoice<FotoGroep> maakGroepField() {
        Order sortOrder = Helper.createOrder("naam", SortOrder.ASC);
        List<FotoGroep> fotoGroepen = databaseService.getPictureGroups(sortOrder);
        groep = new DropDownChoice<>("fotoGroep", fotoGroepen, new ChoiceRenderer<FotoGroep>("naam", "fotoGroepId"));
        groep.isRequired();
        return groep;
    }

Foto:

@Entity
@Table(name = "XS_FOTO")
public class Foto extends BasisModel implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "FOTO_ID")
    private Long fotoId;

    @Column(name = "BESCHRIJVING", nullable = true)
    private String beschrijving;

    @Column(name = "DATUM", nullable = true)
    @Temporal(TemporalType.DATE)
    private Date datum;

    @ManyToOne
    @JoinColumn(name = "FOTO_GROEP_ID", nullable = false)
    private FotoGroep fotoGroep = new FotoGroep(Long.valueOf(12));

    (getters and setters)

FotoGroep:

@Entity
@Table(name = "XS_FOTO_GROEP")
public class FotoGroep extends BasisModel implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "FOTO_GROEP_ID")
    private Long fotoGroepId;

    @Column(name = "NAAM", nullable = false)
    private String naam;

    @Override
    public boolean equals(Object object) {
        return (this.getFotoGroepId().equals(((FotoGroep)object).getFotoGroepId()));
    }

    @Override
    public int hashCode() {
        return Objects.hash(fotoGroepId, naam, beschrijving, datum);
    }

    (getters and setters)

As requested, I tried overriding equals and hashCode but without succes. I debugged and the foto.fotoGroep.fotoGroepId is the same as the only fotoGroep.fotoGroepId in the List<FotoGroepen>. Both FotoGroep even are the same bean at runtime. My unit test put's the same FotoGroep in the list as in the Model.

Edit, possible bad unit test(?):
I was testing the value of my DropDownChoice with:

assertEquals("456", formTester.getTextComponentValue("fotoGroep"));

The value kept returning Null. BUT when I check the HTML, I can see that the right option is selected:

<select wicket:id="fotoGroep" name="fotoGroep" disabled="disabled">
    <option value="123">naam</option>
    <option value="123">naam</option>
    <option value="123">naam</option>
    <option value="123">naam</option>
    <option value="123">naam</option>
    <option value="123">naam</option>
    <option selected="selected" value="456">naam</option>
</select>

Could someone explain this behavior? When using a PropertyModel inside my DropDownChoice it also sets the value, but not when using the Model inheritance.

Body:
I was testing DropDownChoice wrong.

I was testing the value of the DropDownChoice:

assertEquals("456", formTester.getTextComponentValue("fotoGroep"));

But in my case, this value was never set, BUT the right option was selected! I've changed my test to:

DropDownChoice<FotoGroep> dropDownChoice = (DropDownChoice)tester.getComponentFromLastRenderedPage("imageControlPanel:imageControlForm:fotoGroep");
dropDownChoice.setModelObject(createFotoGroep);
tester.assertModelValue("imageControlPanel:imageControlForm:fotoGroep", dropDownChoice.getModelObject());

The test will take the DropDownChoice, set the value you are expecting and then compare the Models of both.


问:
Different results for string iteration in Go
Just used two simple ways to iterate a string in Go. The first one seems right but the second way got minus numbers starting with -97. Could somebody knows why?

```<code>func main() {
    str := "abc"

    for i := 0; i < len(str) ; i++ {
        println(str[i] - 'a')
    }

    for x := range str {
        println(x - 'a')
    }
}
</code>```

The result is -

```<code>0
1
2
-97
-96
-95
</code>```

答:
```<code>for x := range str {
    println(x - 'a')
}
</code>```

x contains the index of the letter

what you want to do is take the second value returned by the range and ignore the first

```<code>for _, x := range str {
    println(x - 'a')
}
</code>```

Body:
Just used two simple ways to iterate a string in Go. The first one seems right but the second way got minus numbers starting with -97. Could somebody knows why?

func main() {
    str := "abc"

    for i := 0; i < len(str) ; i++ {
        println(str[i] - 'a')
    }

    for x := range str {
        println(x - 'a')
    }
}

The result is -

0
1
2
-97
-96
-95

Body:
for x := range str {
    println(x - 'a')
}

x contains the index of the letter

what you want to do is take the second value returned by the range and ignore the first

for _, x := range str {
    println(x - 'a')
}