问:
Python 2.X : Regex to find all company names ending in ".inc"
I'm trying to extract the company names from press releases. As an example, below there is a snippet (in French) of a press release containing a list of seven companies ending in .inc.

En effet, Revenu Québec avait des motifs raisonnables de croire que ces entreprises avaient utilisé de fausses factures provenant de plusieurs sociétés, dont Asphalte Vrac Transport inc., 9163-6704 Québec inc., Entreprise Denis Dupré inc., Gestion Jean M. Machado inc., Impact Technologie Environnementale inc., Les entreprises Luc Clément inc. et Transport Vrac Globe International inc.

I'm trying to extract all the names using the following code:

```<code>aa = re.findall('inc\.,? (.*?inc\.)', text)
</code>```

I do manage to capture quite a few, but for some reason I can't figure, I can't extract them all. It seems trivial but it has stomped me for a few hours....

Any help is appreciated !

答:
This pattern appears to do the trick:

```<code>   >>> string = """En effet, Revenu Québec avait des motifs raisonnables de croire que ces entreprises avaient utilisé de fausses factures provenant de plusieurs sociétés, dont Asphalte Vrac Transport inc., 9163-6704 Québec inc., Entreprise Denis Dupré inc., Gestion Jean M. Machado inc., Impact Technologie Environnementale inc., Les entreprises Luc Clément inc. et Transport Vrac Globe International inc."""
   >>> pattern = r'((?:[A-Z0-9\-]\.?\w*\s?(?:[a-z0-9\-]\w*\s?)?)+ inc\.)'
   >>> m = re.findall(pattern, string)
   >>> print('\n'.join(m))

   Asphalte Vrac Transport inc.
   9163-6704 Québec inc.
   Entreprise Denis Dupré inc.
   Gestion Jean M. Machado inc.
   Impact Technologie Environnementale inc.
   Les entreprises Luc Clément inc.
   Transport Vrac Globe International inc.
</code>```

Explanation:

```<code>   [A-Z0-9\-] # match an uppercase letter or number or dash
   \.?        # match optional dot
   \w*        # match alpha-numeric chars 0 or more times
   \s?        # match optional white-space

   (?:[a-z0-9\-]\w*\s?)? # same again except with lowercase letters
                         # the ? means 0 or 1 times

    inc\.     # match ' inc.'
   (?: ... )  # non-capturing group
   ( ... )    # capturing group (whole thing)
   x?          # match x optional
   x*          # in this case match x 0 or more times
   x+          # match x 1 or more times
</code>```

Body:
I'm trying to extract the company names from press releases. As an example, below there is a snippet (in French) of a press release containing a list of seven companies ending in .inc.

En effet, Revenu Québec avait des motifs raisonnables de croire que ces entreprises avaient utilisé de fausses factures provenant de plusieurs sociétés, dont Asphalte Vrac Transport inc., 9163-6704 Québec inc., Entreprise Denis Dupré inc., Gestion Jean M. Machado inc., Impact Technologie Environnementale inc., Les entreprises Luc Clément inc. et Transport Vrac Globe International inc.

I'm trying to extract all the names using the following code:

aa = re.findall('inc\.,? (.*?inc\.)', text)

I do manage to capture quite a few, but for some reason I can't figure, I can't extract them all. It seems trivial but it has stomped me for a few hours....

Any help is appreciated !

Body:
This pattern appears to do the trick:

   >>> string = """En effet, Revenu Québec avait des motifs raisonnables de croire que ces entreprises avaient utilisé de fausses factures provenant de plusieurs sociétés, dont Asphalte Vrac Transport inc., 9163-6704 Québec inc., Entreprise Denis Dupré inc., Gestion Jean M. Machado inc., Impact Technologie Environnementale inc., Les entreprises Luc Clément inc. et Transport Vrac Globe International inc."""
   >>> pattern = r'((?:[A-Z0-9\-]\.?\w*\s?(?:[a-z0-9\-]\w*\s?)?)+ inc\.)'
   >>> m = re.findall(pattern, string)
   >>> print('\n'.join(m))

   Asphalte Vrac Transport inc.
   9163-6704 Québec inc.
   Entreprise Denis Dupré inc.
   Gestion Jean M. Machado inc.
   Impact Technologie Environnementale inc.
   Les entreprises Luc Clément inc.
   Transport Vrac Globe International inc.

Explanation:

   [A-Z0-9\-] # match an uppercase letter or number or dash
   \.?        # match optional dot
   \w*        # match alpha-numeric chars 0 or more times
   \s?        # match optional white-space

   (?:[a-z0-9\-]\w*\s?)? # same again except with lowercase letters
                         # the ? means 0 or 1 times

    inc\.     # match ' inc.'
   (?: ... )  # non-capturing group
   ( ... )    # capturing group (whole thing)
   x?          # match x optional
   x*          # in this case match x 0 or more times
   x+          # match x 1 or more times


来源: stackexchange

问:
Print range of numbers on same line
Using python I want to print a range of numbers on the same line. how can I do this using python, I can do it using C by not adding \n, but how can I do it using python.

```<code>for x in xrange(1,10):
    print x
</code>```

I am trying to get this result.

```<code>1 2 3 4 5 6 7 8 9 10
</code>```

答:
```<code>[print(i, end = ' ') for i in range(10)]
0 1 2 3 4 5 6 7 8 9
</code>```

This is a list comprehension method of answer same as @Anubhav

ContentLicense: CC BY-SA 3.0

Title: Print range of numbers on same line

Body:
Using python I want to print a range of numbers on the same line. how can I do this using python, I can do it using C by not adding \n, but how can I do it using python.

for x in xrange(1,10):
    print x

I am trying to get this result.

1 2 3 4 5 6 7 8 9 10

Body:
[print(i, end = ' ') for i in range(10)]
0 1 2 3 4 5 6 7 8 9

This is a list comprehension method of answer same as @Anubhav


问:
JavaFX - include fxml with an event in it
I'm currently trying to implements a very basic application with JavaFX just to do some tests. The final goal here is to implement an interface separated in severals parts, and each part will have its own .fxm and controller.

For the beginning, I've tried to develop a basic application with this architecture :

Project explorer

I have a main VueGlobale.fxml file which include another .fxml file clavier.fxml :

VueGlobale.fxml

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

<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>

<VBox
maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="529.0" xmlns="http://javafx.com/javafx/8.0.121" xmlns:fx="http://javafx.com/fxml/1">
   <children>
        <fx:include source="clavier.fxml" fx:id="clavier" />
   </children>
</VBox>
</code>```

clavier.fxml

```<code><?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.141" xmlns:fx="http://javafx.com/fxml/1" fx:controller="controllers.ClavierController">
   <children>
      <Button layoutX="274.0" layoutY="188.0" mnemonicParsing="false" onAction="#ajouterDo" text="Button" />
   </children>
</AnchorPane>
</code>```

An here's the ClavierController.fxml :
    package controllers;

```<code>import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import model.Model;

public class ClavierController  {

    private Model model;

    public ClavierController(Model m) {
        this.model = m;
    }

    @FXML
    public void ajouterDo(ActionEvent e){
        System.out.println("Click !");
        this.model.doSomething();
    }
}
</code>```

Model
package model;
public class Model {

```<code>public void doSomething() {
    System.out.println("Model !");
}
</code>```

}

Main

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

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(getClass().getResource("views/VueGlobale.fxml"));

        Parent root = loader.load();
        primaryStage.setTitle("Test");
        primaryStage.setScene(new Scene(root, 300, 275));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

The problem is : I don't know what to do in my main so that I can give to my clavier.fxml a ClavierController(Model m). (It's working with a controller without parameters, but what if I need to precise parameters ?)

Here's the StackTrace if it could help you :

```<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$155(LauncherImpl.java:182)
    at java.lang.Thread.run(Unknown Source)
Caused by: javafx.fxml.LoadException:
/J:/Programming/Telecom%20Nancy/S3/Test/bin/views/clavier.fxml:6
/J:/Programming/Telecom%20Nancy/S3/Test/bin/views/VueGlobale.fxml:9

    at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2601)
    at javafx.fxml.FXMLLoader.access$700(FXMLLoader.java:103)
    at javafx.fxml.FXMLLoader$ValueElement.processAttribute(FXMLLoader.java:932)
    at javafx.fxml.FXMLLoader$InstanceDeclarationElement.processAttribute(FXMLLoader.java:971)
    at javafx.fxml.FXMLLoader$Element.processStartElement(FXMLLoader.java:220)
    at javafx.fxml.FXMLLoader$ValueElement.processStartElement(FXMLLoader.java:744)
    at javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2707)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2527)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
    at javafx.fxml.FXMLLoader.access$2700(FXMLLoader.java:103)
    at javafx.fxml.FXMLLoader$IncludeElement.constructValue(FXMLLoader.java:1143)
    at javafx.fxml.FXMLLoader$ValueElement.processStartElement(FXMLLoader.java:746)
    at javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2707)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2527)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2409)
    at Main.start(Main.java:14)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(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$148(WinApplication.java:191)
    ... 1 more
Caused by: java.lang.InstantiationException: controllers.ClavierController
    at java.lang.Class.newInstance(Unknown Source)
    at sun.reflect.misc.ReflectUtil.newInstance(Unknown Source)
    at javafx.fxml.FXMLLoader$ValueElement.processAttribute(FXMLLoader.java:927)
    ... 23 more
Caused by: java.lang.NoSuchMethodException: controllers.ClavierController.<init>()
    at java.lang.Class.getConstructor0(Unknown Source)
    ... 26 more
Exception running application Main
</code>```

Thank you in advance for your help and for your time, have a good day.

EDIT :

By including several fxml, i mean this :

VueGlobale.fxml

```<code><?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>
<VBox
maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="529.0" xmlns="http://javafx.com/javafx/8.0.121" xmlns:fx="http://javafx.com/fxml/1">
   <children>
        <fx:include source="viewtop.fxml" fx:id="top" />
   </children>
<children>
        <fx:include source="clavier.fxml" fx:id="clavier" />
   </children>
<children>
        <fx:include source="viewbottom.fxml" fx:id="bottom" />
   </children>
</VBox>
</code>```

So I have three .fxml file included in my VueGlobale.fxml. Let us supposed that all this .fxml have their own controller (ClavierController.java, TopController.java, BottomController.java). All these controllers needs the model. What should I do in my main factory ? Something like this doesn't work :

```<code>import controllers.ClavierController;
import controllers.TopController;
import controllers.BottomController;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import model.Model;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Model m = new Model();

        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(getClass().getResource("views/VueGlobale.fxml"));
        loader.setControllerFactory(ic -> new ClavierController(m));
        loader.setControllerFactory(ic -> new TopController(m));
        loader.setControllerFactory(ic -> new BottomController(m));

        Parent root = loader.load();
        primaryStage.setTitle("Test");
        primaryStage.setScene(new Scene(root, 300, 275));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

答:
The controllerFactory is a property like any other property. If you set its value, it has that value, so it makes no sense to set its value to three different things in three consecutive lines of code.

You can create a controller factory that simply checks the parameter and returns the appropriate controller:

```<code>public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Model m = new Model();

        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(getClass().getResource("views/VueGlobale.fxml"));
        loader.setControllerFactory(ic -> {
            if (ic == ClavierController.class) {
                return new ClavierController(m);
            } else if (ic == TopController.class) {
                return new TopController(m);
            } else if (ic == BottomController.class) {
                return new BottomController(m) ;
            }
            throw new IllegalArgumentException("Unexpected controller type: "+ic.getName());
        });

        Parent root = loader.load();
        primaryStage.setTitle("Test");
        primaryStage.setScene(new Scene(root, 300, 275));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

You can also use reflection to implement logic like "If the supplied controller class has a constructor taking a model, call that constructor and pass the model in, otherwise call the default constructor":

```<code>loader.setControllerFactory(ic -> {
    try {
        for (Constructor<?> c : ic.getConstructors()) {
            if (c.getParameterCount() == 1 && c.getParameterTypes()[0]==Model.class) {
                return c.newInstance(m);
            }
        }
        return ic.newInstance();
    } catch (Exception e) {
        // fatal...
        throw new RuntimeException(e);
    }
});
</code>```

This is all a bit heavy-handed for what you are trying to achieve, though. You are merely trying to pass a model to the nested controllers (the controllers for the FXML files loaded via <fx:include>). The documentation explicitly provides an injection-based approach for this.

Specifically, if your "main" FXML adds fx:ids to the <fx:include>s, then the controllers can be injected into the main controller. So you can do something like:

<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>
<VBox
maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="529.0" xmlns="http://javafx.com/javafx/8.0.121" xmlns:fx="http://javafx.com/fxml/1">
   <children>
        <fx:include source="viewtop.fxml" fx:id="top" />
   </children>
<children>
        <fx:include source="clavier.fxml" fx:id="clavier" />
   </children>
<children>
        <fx:include source="viewbottom.fxml" fx:id="bottom" />
   </children>
</VBox>
```

<p>Now define a "main" controller for this FXML file:</p>

```public class MainController {

    @FXML
    private Parent top ;
    @FXML
    private Parent clavier ;
    @FXML
    private Parent bottom ;

    @FXML
    private TopController topController ;
    @FXML
    private ClavierController clavierController ;
    @FXML
    private BottomController bottomController ;

    private final Model model ;

    public MainController(Model model) {
        this.model = model ;
    }

    @FXML
    public void initialize() {
        topController.setModel(model);
        clavierController.setModel(model);
        bottomController.setModel(model);
    }

    // ...
}
```

<p>Just define the "nested" controllers with the appropriate methods for setting the model:</p>

```public class TopController {

    private Model model ;

    public void setModel(Model model) {
        this.model = model ;
    }

    @FXML
    private void someHandlerMethod(ActionEvent event) {
        model.doSomething();
    }
}
```

<p>And finally load your main fxml with:</p>

```Model model = new Model();
FXMLLoader loader = new FXMLLoader(getClass().getResource("/path/to/fxml"));
loader.setController(new MainController(model));
Parent root = loader.load();
```

and it should all be good to go.

Body:
I'm currently trying to implements a very basic application with JavaFX just to do some tests. The final goal here is to implement an interface separated in severals parts, and each part will have its own .fxm and controller.

For the beginning, I've tried to develop a basic application with this architecture :

Project explorer

I have a main VueGlobale.fxml file which include another .fxml file clavier.fxml :

VueGlobale.fxml

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

<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>

<VBox
maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="529.0" xmlns="http://javafx.com/javafx/8.0.121" xmlns:fx="http://javafx.com/fxml/1">
   <children>
        <fx:include source="clavier.fxml" fx:id="clavier" />
   </children>
</VBox>

clavier.fxml

<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.141" xmlns:fx="http://javafx.com/fxml/1" fx:controller="controllers.ClavierController">
   <children>
      <Button layoutX="274.0" layoutY="188.0" mnemonicParsing="false" onAction="#ajouterDo" text="Button" />
   </children>
</AnchorPane>

An here's the ClavierController.fxml :
    package controllers;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import model.Model;

public class ClavierController  {

    private Model model;

    public ClavierController(Model m) {
        this.model = m;
    }

    @FXML
    public void ajouterDo(ActionEvent e){
        System.out.println("Click !");
        this.model.doSomething();
    }
}

Model
package model;
public class Model {

public void doSomething() {
    System.out.println("Model !");
}

}

Main

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(getClass().getResource("views/VueGlobale.fxml"));

        Parent root = loader.load();
        primaryStage.setTitle("Test");
        primaryStage.setScene(new Scene(root, 300, 275));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

The problem is : I don't know what to do in my main so that I can give to my clavier.fxml a ClavierController(Model m). (It's working with a controller without parameters, but what if I need to precise parameters ?)

Here's the StackTrace if it could help you :

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$155(LauncherImpl.java:182)
    at java.lang.Thread.run(Unknown Source)
Caused by: javafx.fxml.LoadException:
/J:/Programming/Telecom%20Nancy/S3/Test/bin/views/clavier.fxml:6
/J:/Programming/Telecom%20Nancy/S3/Test/bin/views/VueGlobale.fxml:9

    at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2601)
    at javafx.fxml.FXMLLoader.access$700(FXMLLoader.java:103)
    at javafx.fxml.FXMLLoader$ValueElement.processAttribute(FXMLLoader.java:932)
    at javafx.fxml.FXMLLoader$InstanceDeclarationElement.processAttribute(FXMLLoader.java:971)
    at javafx.fxml.FXMLLoader$Element.processStartElement(FXMLLoader.java:220)
    at javafx.fxml.FXMLLoader$ValueElement.processStartElement(FXMLLoader.java:744)
    at javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2707)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2527)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
    at javafx.fxml.FXMLLoader.access$2700(FXMLLoader.java:103)
    at javafx.fxml.FXMLLoader$IncludeElement.constructValue(FXMLLoader.java:1143)
    at javafx.fxml.FXMLLoader$ValueElement.processStartElement(FXMLLoader.java:746)
    at javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2707)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2527)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2409)
    at Main.start(Main.java:14)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(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$148(WinApplication.java:191)
    ... 1 more
Caused by: java.lang.InstantiationException: controllers.ClavierController
    at java.lang.Class.newInstance(Unknown Source)
    at sun.reflect.misc.ReflectUtil.newInstance(Unknown Source)
    at javafx.fxml.FXMLLoader$ValueElement.processAttribute(FXMLLoader.java:927)
    ... 23 more
Caused by: java.lang.NoSuchMethodException: controllers.ClavierController.<init>()
    at java.lang.Class.getConstructor0(Unknown Source)
    ... 26 more
Exception running application Main

Thank you in advance for your help and for your time, have a good day.

EDIT :

By including several fxml, i mean this :

VueGlobale.fxml

<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>
<VBox
maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="529.0" xmlns="http://javafx.com/javafx/8.0.121" xmlns:fx="http://javafx.com/fxml/1">
   <children>
        <fx:include source="viewtop.fxml" fx:id="top" />
   </children>
<children>
        <fx:include source="clavier.fxml" fx:id="clavier" />
   </children>
<children>
        <fx:include source="viewbottom.fxml" fx:id="bottom" />
   </children>
</VBox>

So I have three .fxml file included in my VueGlobale.fxml. Let us supposed that all this .fxml have their own controller (ClavierController.java, TopController.java, BottomController.java). All these controllers needs the model. What should I do in my main factory ? Something like this doesn't work :

import controllers.ClavierController;
import controllers.TopController;
import controllers.BottomController;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import model.Model;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Model m = new Model();

        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(getClass().getResource("views/VueGlobale.fxml"));
        loader.setControllerFactory(ic -> new ClavierController(m));
        loader.setControllerFactory(ic -> new TopController(m));
        loader.setControllerFactory(ic -> new BottomController(m));

        Parent root = loader.load();
        primaryStage.setTitle("Test");
        primaryStage.setScene(new Scene(root, 300, 275));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Body:
The controllerFactory is a property like any other property. If you set its value, it has that value, so it makes no sense to set its value to three different things in three consecutive lines of code.

You can create a controller factory that simply checks the parameter and returns the appropriate controller:

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Model m = new Model();

        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(getClass().getResource("views/VueGlobale.fxml"));
        loader.setControllerFactory(ic -> {
            if (ic == ClavierController.class) {
                return new ClavierController(m);
            } else if (ic == TopController.class) {
                return new TopController(m);
            } else if (ic == BottomController.class) {
                return new BottomController(m) ;
            }
            throw new IllegalArgumentException("Unexpected controller type: "+ic.getName());
        });

        Parent root = loader.load();
        primaryStage.setTitle("Test");
        primaryStage.setScene(new Scene(root, 300, 275));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

You can also use reflection to implement logic like "If the supplied controller class has a constructor taking a model, call that constructor and pass the model in, otherwise call the default constructor":

loader.setControllerFactory(ic -> {
    try {
        for (Constructor<?> c : ic.getConstructors()) {
            if (c.getParameterCount() == 1 && c.getParameterTypes()[0]==Model.class) {
                return c.newInstance(m);
            }
        }
        return ic.newInstance();
    } catch (Exception e) {
        // fatal...
        throw new RuntimeException(e);
    }
});

This is all a bit heavy-handed for what you are trying to achieve, though. You are merely trying to pass a model to the nested controllers (the controllers for the FXML files loaded via <fx:include>). The documentation explicitly provides an injection-based approach for this.

Specifically, if your "main" FXML adds fx:ids to the <fx:include>s, then the controllers can be injected into the main controller. So you can do something like:

<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>
<VBox
maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="529.0" xmlns="http://javafx.com/javafx/8.0.121" xmlns:fx="http://javafx.com/fxml/1">
   <children>
        <fx:include source="viewtop.fxml" fx:id="top" />
   </children>
<children>
        <fx:include source="clavier.fxml" fx:id="clavier" />
   </children>
<children>
        <fx:include source="viewbottom.fxml" fx:id="bottom" />
   </children>
</VBox>

Now define a "main" controller for this FXML file:

public class MainController {

    @FXML
    private Parent top ;
    @FXML
    private Parent clavier ;
    @FXML
    private Parent bottom ;

    @FXML
    private TopController topController ;
    @FXML
    private ClavierController clavierController ;
    @FXML
    private BottomController bottomController ;

    private final Model model ;

    public MainController(Model model) {
        this.model = model ;
    }

    @FXML
    public void initialize() {
        topController.setModel(model);
        clavierController.setModel(model);
        bottomController.setModel(model);
    }

    // ...
}

Just define the "nested" controllers with the appropriate methods for setting the model:

public class TopController {

    private Model model ;

    public void setModel(Model model) {
        this.model = model ;
    }

    @FXML
    private void someHandlerMethod(ActionEvent event) {
        model.doSomething();
    }
}

And finally load your main fxml with:

Model model = new Model();
FXMLLoader loader = new FXMLLoader(getClass().getResource("/path/to/fxml"));
loader.setController(new MainController(model));
Parent root = loader.load();

and it should all be good to go.


问:
Argument separation in bash/command prompt
the other day I ran the following piece of code on the windows cmd:

```<code>$java -cp . myProgram > output.txt
</code>```

I could do the same in unix bash.

My question is the following:

How is it that > and output.txt are not passed as an argument to myProgram?

What if I wanted my program to receive > as an argument?

答:
The metacharacter > is processed by the shell, and this character and the following filename are not included in the arguments when running the program. If you want it to be passed literally to the program, you need to quote it.

```<code>java -cp . myProgram ">" output.txt
</code>```

Body:
the other day I ran the following piece of code on the windows cmd:

$java -cp . myProgram > output.txt

I could do the same in unix bash.

My question is the following:

How is it that > and output.txt are not passed as an argument to myProgram?

What if I wanted my program to receive > as an argument?

Body:
The metacharacter > is processed by the shell, and this character and the following filename are not included in the arguments when running the program. If you want it to be passed literally to the program, you need to quote it.

java -cp . myProgram ">" output.txt


问:
SQL, Select One row with min field value from subquery
I have following SQL query:

```<code> select count(t.id) from Tickets t
    where t.IsPaid = 1 and t.Price_id = (select price.Id from Prices price
            where price.Product_id = '7E67DAFB-C819-4715-830A-7C89EC986E4F' AND price.Quantity > (select count(t1.Id) from Tickets t1
                where t1.IsPaid = 1 AND t1.Price_id IN (select pr.Id from Prices pr
                    where price.Product_id = pr.Id)))
</code>```

The question is: how to get the row with min value of price.Price1 field from this part of my code?

```<code>(select price.Id from Prices price
            where price.Product_id = '7E67DAFB-C819-4715-830A-7C89EC986E4F' AND price.Quantity > (select count(t1.Id) from Tickets t1
                where t1.IsPaid = 1 AND t1.Price_id IN (select pr.Id from Prices pr
                    where price.Product_id = pr.Id)))
</code>```

I expect that as a result of second part of my code would be only Id of the ONE row. Right now this code always returning me all prices.
Here is relationships in main tables Database structure and relations

I was trying different methods like this:

```<code>(select price.Id, MIN(Price1) from Prices price
        where price.Product_id = '7E67DAFB-C819-4715-830A-7C89EC986E4F' AND price.Quantity > (select count(t1.Id) from Tickets t1
            where t1.IsPaid = 1 AND t1.Price_id IN (select pr.Id from Prices pr
                where price.Product_id = pr.Id)) Group by Id)
</code>```

But the result is: Result with MIN function

Example of data in Prices table: Prices table

Example of data in Tickets table: Tickets table

答:
The question is: how to get the row with min value of price.Price1
  field from this part of my code?

Simple:

```<code>(select TOP 1 price.Id
  from Prices price
  where price.Product_id = '7E67DAFB-C819-4715-830A-7C89EC986E4F'
  AND price.Quantity > (
    select count(t1.Id)
    from Tickets t1
    where t1.IsPaid = 1
    AND t1.Price_id IN (select pr.Id from Prices pr where price.Product_id = pr.Id)
  )
ORDER BY price.Price1 ASC
)
</code>```

Body:
I have following SQL query:

 select count(t.id) from Tickets t
    where t.IsPaid = 1 and t.Price_id = (select price.Id from Prices price
            where price.Product_id = '7E67DAFB-C819-4715-830A-7C89EC986E4F' AND price.Quantity > (select count(t1.Id) from Tickets t1
                where t1.IsPaid = 1 AND t1.Price_id IN (select pr.Id from Prices pr
                    where price.Product_id = pr.Id)))

The question is: how to get the row with min value of price.Price1 field from this part of my code?

(select price.Id from Prices price
            where price.Product_id = '7E67DAFB-C819-4715-830A-7C89EC986E4F' AND price.Quantity > (select count(t1.Id) from Tickets t1
                where t1.IsPaid = 1 AND t1.Price_id IN (select pr.Id from Prices pr
                    where price.Product_id = pr.Id)))

I expect that as a result of second part of my code would be only Id of the ONE row. Right now this code always returning me all prices.
Here is relationships in main tables Database structure and relations

I was trying different methods like this:

(select price.Id, MIN(Price1) from Prices price
        where price.Product_id = '7E67DAFB-C819-4715-830A-7C89EC986E4F' AND price.Quantity > (select count(t1.Id) from Tickets t1
            where t1.IsPaid = 1 AND t1.Price_id IN (select pr.Id from Prices pr
                where price.Product_id = pr.Id)) Group by Id)

But the result is: Result with MIN function

Example of data in Prices table: Prices table

Example of data in Tickets table: Tickets table

Body:
The question is: how to get the row with min value of price.Price1
  field from this part of my code?

Simple:

(select TOP 1 price.Id
  from Prices price
  where price.Product_id = '7E67DAFB-C819-4715-830A-7C89EC986E4F'
  AND price.Quantity > (
    select count(t1.Id)
    from Tickets t1
    where t1.IsPaid = 1
    AND t1.Price_id IN (select pr.Id from Prices pr where price.Product_id = pr.Id)
  )
ORDER BY price.Price1 ASC
)


问:
CMake add_jar with INCLUDE_JARS not working
I am using CMake to compile jar file with add_jar command. Problem is that when I try to add INCLUDE_JARS to specify dependency to external jar, the code will not run. Here is the code example:

```<code>add_jar(testJar
    SOURCES
        sources/com/test/Main.java
    INCLUDE_JARS
        ${CMAKE_SOURCE_DIR}/extern/org.json/json-20171018.jar
    ENTRY_POINT com.test.Main
)
</code>```

Running the testJar with "java -jar testJar.jar" gives me the following error:

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: org/json/JSONException
</code>```

The org.json jar should be in classpath, right? Adding manifest file with classpath solves the problem but is there way to do this without the manifest file?

And yes, I would use maven or gradle for building but as of restrictions in the project I cannot do that :)

答:
The option INCLUDE_JARS only makes sure that the given external jar is added to the class path upon compilation of the given Java source files. The jar file is neither copied to the build directory nor is it added to the jar file generated by add_jar.

If inclusion of the external jar in the Manifest file is not an option for you, manually add it to the class path upon running the testJar, i.e.:

```<code>java -cp path/to/json-20171018.jar -jar testJar.jar
</code>```

Body:
I am using CMake to compile jar file with add_jar command. Problem is that when I try to add INCLUDE_JARS to specify dependency to external jar, the code will not run. Here is the code example:

add_jar(testJar
    SOURCES
        sources/com/test/Main.java
    INCLUDE_JARS
        ${CMAKE_SOURCE_DIR}/extern/org.json/json-20171018.jar
    ENTRY_POINT com.test.Main
)

Running the testJar with "java -jar testJar.jar" gives me the following error:

Exception in thread "main" java.lang.NoClassDefFoundError: org/json/JSONException

The org.json jar should be in classpath, right? Adding manifest file with classpath solves the problem but is there way to do this without the manifest file?

And yes, I would use maven or gradle for building but as of restrictions in the project I cannot do that :)

Body:
The option INCLUDE_JARS only makes sure that the given external jar is added to the class path upon compilation of the given Java source files. The jar file is neither copied to the build directory nor is it added to the jar file generated by add_jar.

If inclusion of the external jar in the Manifest file is not an option for you, manually add it to the class path upon running the testJar, i.e.:

java -cp path/to/json-20171018.jar -jar testJar.jar


问:
Dictionary initialization syntax
```<code>def __init__(self, devices, queue):
    '''
    '''
    self.devices = devices
    self.queue = queue

    values = {k:0 for k in devices.keys()}
    values[0xbeef] = len(values) # the number of devices
    super(CallbackDataBlock, self).__init__(values)
</code>```

Can someone help me explain the following two lines:

values = {k:0 for k in devices.keys()}

What does k:0 do?

values[0xbeef] = len(values) # the number of devices

Does this mean that new item {0xbeef: length} is appended in the dict?

答:
The k is the field in the dictionary. The set of all fields is stored in the device.keys() which is most probably a list, we loop through the list, take names of fields and initialize them by zero.

Yes, you are right. The next statement is responsible for adding a new field and initializing it to the length of the array.

Title: Dictionary initialization syntax

Body:
def __init__(self, devices, queue):
    '''
    '''
    self.devices = devices
    self.queue = queue

    values = {k:0 for k in devices.keys()}
    values[0xbeef] = len(values) # the number of devices
    super(CallbackDataBlock, self).__init__(values)

Can someone help me explain the following two lines:

values = {k:0 for k in devices.keys()}

What does k:0 do?

values[0xbeef] = len(values) # the number of devices

Does this mean that new item {0xbeef: length} is appended in the dict?


问:
Transition time is only applied if target value changes

Note: I updated the question with a simpler example as I found that it is not an issue with transform in particular, but with how the transition timing is applied. You can still see the more complex example in the edit history.

Here is a simple example: when you mouse over the "Grow" button, the bar will grow to 400px in 5 seconds; and after exiting the "Grow" button, the bar will shrink automatically to 0px in 10 seconds. If you mouse over the "Shrink" button, the bar will shrink to 0px in 2 seconds.

Although it doesn't, it takes 10 seconds to go back to 0px even when mousing over "Shrink":

#bar {
  width:0;
  border-left:1px solid gray;
  height: 40px;
  transition: width 10s;
  background: green;
}

#grow,#shrink {
  display:inline-block;
  width: 60px;
  height: 60px;
  background: gray;
  margin-bottom: 10px;
  color: white;
  line-height: 60px;
  text-align: center;
  box-shadow: inset 0 0 0 1px black;
  margin-right: 20px;
}

#grow:hover ~ #bar {
  width: 400px;
  transition: width 5s;
}

#shrink:hover ~ #bar {
  width: 0px;
  transition: width 2s;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span id="grow">Grow</span>
<span id="shrink">Shrink</span>

<div id="bar"></div></code>```

At first I thought it could be a problem with specificity (even when #shrink:hover ~ #bar is more specific than just #bar), so I added an !important like this:

```<code>#shrink:hover ~ #bar {
  width: 0px;
  transition: width 2s !important;
}
</code>```

Still it didn't work. After some try-error, I found that changing the value actually makes the browser take the new transition time, even if the change is insignificant. So, for example, this will work:

#bar {
  width:0;
  border-left:1px solid gray;
  height: 40px;
  transition: width 10s;
  background: green;
}

#grow,#shrink {
  display:inline-block;
  width: 60px;
  height: 60px;
  background: gray;
  margin-bottom: 10px;
  color: white;
  line-height: 60px;
  text-align: center;
  box-shadow: inset 0 0 0 1px black;
  margin-right: 20px;
}

#grow:hover ~ #bar {
  width: 400px;
  transition: width 5s;
}

#shrink:hover ~ #bar {
  width: 0.000001px;
  transition: width 2s;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span id="grow">Grow</span>
<span id="shrink">Shrink</span>

<div id="bar"></div></code>```

That works. Also, I noticed another case in which it works: when it goes directly from "Grow" to "Shrink" without transitioning to anything else (you may be able to see it by moving from "Grow" to "Shrink" really fast or by removing the margin so they are together).

I have been able to replicate this issue in Chrome, Internet Explorer/Edge, Firefox, and Safari. So I don't know if it's a real issue or me misunderstanding how this should work (quite possible too).

Why does this happen? Is there a way to apply the new transition time without having to change the target value?

答:
I picked up this from the specs., saying

For each element with a before-change style and an after-change style,
  and each property (other than shorthands) for which the before-change
  style is different from the after-change style, implementations must
  start transitions based on the relevant item

which I interpret being the case here, where your #bar before-change value is not different from the #shrink:hover ~ #bar after-change value, hence no transition starts.

Src: https://www.w3.org/TR/css3-transitions/#starting

Body:
Note: I updated the question with a simpler example as I found that it is not an issue with transform in particular, but with how the transition timing is applied. You can still see the more complex example in the edit history.

Here is a simple example: when you mouse over the "Grow" button, the bar will grow to 400px in 5 seconds; and after exiting the "Grow" button, the bar will shrink automatically to 0px in 10 seconds. If you mouse over the "Shrink" button, the bar will shrink to 0px in 2 seconds.

Although it doesn't, it takes 10 seconds to go back to 0px even when mousing over "Shrink":

#bar {
  width:0;
  border-left:1px solid gray;
  height: 40px;
  transition: width 10s;
  background: green;
}

#grow,#shrink {
  display:inline-block;
  width: 60px;
  height: 60px;
  background: gray;
  margin-bottom: 10px;
  color: white;
  line-height: 60px;
  text-align: center;
  box-shadow: inset 0 0 0 1px black;
  margin-right: 20px;
}

#grow:hover ~ #bar {
  width: 400px;
  transition: width 5s;
}

#shrink:hover ~ #bar {
  width: 0px;
  transition: width 2s;
}

Grow
Shrink

At first I thought it could be a problem with specificity (even when #shrink:hover ~ #bar is more specific than just #bar), so I added an !important like this:

#shrink:hover ~ #bar {
  width: 0px;
  transition: width 2s !important;
}

Still it didn't work. After some try-error, I found that changing the value actually makes the browser take the new transition time, even if the change is insignificant. So, for example, this will work:

#bar {
  width:0;
  border-left:1px solid gray;
  height: 40px;
  transition: width 10s;
  background: green;
}

#grow,#shrink {
  display:inline-block;
  width: 60px;
  height: 60px;
  background: gray;
  margin-bottom: 10px;
  color: white;
  line-height: 60px;
  text-align: center;
  box-shadow: inset 0 0 0 1px black;
  margin-right: 20px;
}

#grow:hover ~ #bar {
  width: 400px;
  transition: width 5s;
}

#shrink:hover ~ #bar {
  width: 0.000001px;
  transition: width 2s;
}

Grow
Shrink

That works. Also, I noticed another case in which it works: when it goes directly from "Grow" to "Shrink" without transitioning to anything else (you may be able to see it by moving from "Grow" to "Shrink" really fast or by removing the margin so they are together).

I have been able to replicate this issue in Chrome, Internet Explorer/Edge, Firefox, and Safari. So I don't know if it's a real issue or me misunderstanding how this should work (quite possible too).

Why does this happen? Is there a way to apply the new transition time without having to change the target value?


答:
```<code>WITH cte as (
    select *,
           row_number() over (partition by TeamId
                              order by DateSubmitted ) as rn,
           count(*) over (partition by TeamId) as total_submission
    from [Kaggle].[dbo].[Submissions]
)
SELECT *
FROM cte
WHERE rn = 1
</code>```

Title: How to get the top 1 row when we order by date, for users grouped in one team

Body:
I have the following table

Id SubmittedUserId DateSubmitted TeamId PrivateScore PublicScore
2180 647.0 2010-04-29 22:32:08 496 56.21390151977539 55.76919937133789
2181 619.0 2010-04-30 09:38:29 497 50.0 47.11539840698242
2182 619.0 2010-04-30 09:48:50 497 65.60690307617188 61.057701110839844
2184 663.0 2010-05-01 11:02:52 499 50.0 47.11539840698242
2185 673.0 2010-05-02 08:04:38 500 62.283199310302734 61.057701110839844
2186 673.0 2010-05-02 08:13:43 500 62.86130142211914 60.576900482177734
2187 673.0 2010-05-02 08:25:09 500 65.75140380859375 62.5
2188 435.0 2010-05-03 17:48:39 501 50.0 47.11539840698242
2191 435.0 2010-05-04 15:39:56 501 56.502899169921875 55.28850173950195
2192 647.0 2010-05-04 18:56:15 496 56.3583984375 57.21149826049805
2193 652.0 2010-05-04 21:29:39 502 56.791900634765625 56.25
2194 435.0 2010-05-04 22:13:17 501 55.635799407958984 55.76919937133789
2195 652.0 2010-05-04 22:54:07 502 56.64739990234375 53.84619903564453
2196 652.0 2010-05-04 23:46:06 502 55.78030014038086 52.40380096435547
2197 435.0 2010-05-05 00:32:56 501 48.84389877319336 45.192298889160156
2198 435.0 2010-05-05 01:19:13 501 56.069400787353516 55.28850173950195

and I want to write a query to get the following table:

Id SubmittedUserId DateSubmitted TeamId PrivateScore PublicScore totalsubmissions
2180 647         5/4/2010 18:56 496     56.35839844 57.21149826 2
2182 619         4/30/2010 9:48 497     65.60690308 61.05770111 2
2184 663      5/1/2010 11:02 499     50         47.11539841 1
2187 673         5/2/2010 08:25 500     65.75140380 62.5     4
2198 435         5/5/2010 1:19 501   56.06940079 55.28850174 5

I wrote the following query which is wrong. I do not know how to write it.

select COUNT(*),
top 1 Id, SubmittedUserId, DateSubmitted, TeamId, PublicScore, PrivateScore
from [Kaggle].[dbo].[Submissions]
order by DateSubmitted desc
Group by  TeamId

I will appreciate any help.


问:
Extract time from JS Date object without offsetting the Time zone
So we have multiple clients, that are in multiple time zones. I'm pulling some dates from an API, and the dates/times that are in this string are exactly what I need to display. I've been researching this, and digging for some time, and still haven't come up with a clear answer. The string coming in is formatted as such:

```<code>"2017-12-29T20:00:00"
</code>```

What I'm wanting is to extract both the date and time as is, into two strings (no timezone offsetting, no matter where the viewer is located) but am having some issues doing so. Also hoping to format it in the correct fashion as well. Example:

```<code>"M/d/yyyy"
"hh:mm AM/PM" (12 hour)
</code>```

I've tried numerous ways to battle this, and don't really want to just grab substrings, but am half tempted to do so. Any help is appreciated.

答:
Use this code:

function formatAMPM(date) {
  var hours = date.getUTCHours();
  var minutes = date.getUTCMinutes();
  var ampm = hours >= 12 ? 'PM' : 'AM';
  hours = hours % 12;
  hours = hours ? hours : 12; // the hour '0' should be '12'
  minutes = minutes < 10 ? '0'+minutes : minutes;
  var strTime = hours + ':' + minutes + ' ' + ampm;
  return strTime;
}

var str = "2017-12-29T20:00:00";
var dt = new Date(str + "Z");
console.log("M/d/yyyy");
console.log((dt.getUTCMonth() + 1) + '/' + dt.getUTCDate() + '/' +  dt.getUTCFullYear());
console.log("hh:mm AM/PM");
console.log(formatAMPM(dt));```

Body:
So we have multiple clients, that are in multiple time zones. I'm pulling some dates from an API, and the dates/times that are in this string are exactly what I need to display. I've been researching this, and digging for some time, and still haven't come up with a clear answer. The string coming in is formatted as such:

"2017-12-29T20:00:00"

What I'm wanting is to extract both the date and time as is, into two strings (no timezone offsetting, no matter where the viewer is located) but am having some issues doing so. Also hoping to format it in the correct fashion as well. Example:

"M/d/yyyy"
"hh:mm AM/PM" (12 hour)

I've tried numerous ways to battle this, and don't really want to just grab substrings, but am half tempted to do so. Any help is appreciated.


问:
Create Azure Sql Database from Sql Compact sdf file
I need to create an Azure Sql Database from a Sql Compact sdf file.  I see that you can create a BACPAC file from a Sql Server database, upload the BACPAC to Azure blob storage, and then create the Azure Sql Database from the BACPAC, but I do not see how to do this via a Sql Compact database.  Is there a way to create a BACPAC from Sql Compact?  Ideally I would not want to convert the Sql Compact to Sql Server and then create the BACPAC.

If going the BACPAC route is not the best means of creating an Azure Sql Database from a Sql Compact file then what is the next best option?  I have also found some tools that will create the sql create/insert scripts from the sdf file, but running the script locally to create a populate an Azure Sql Database is extremely slow.

答:
The next best option is to use my SQL Server Compact Toolbox Visual Studio extension to script the SQL Compact database for Azure, which will generate scripts that are optimized for Azure (using batching of INSERTs)

If that is still too slow, boot up an Azure VM near your Azure database, and run the scripts from it.


问:
Writing cucumber feature/scenario for using a site (as an admin, user, and guest)
I'm new to cucumber and currently stuck trying to organize/structure some features/scenarios. The behavior I'm trying to capture is that of users, guests and admins using my website. The website is basically for creating private and public todo lists.

And these are the specific scenarios I want to test:

Registered users can view their private todo lists (but not someone else's private todo list)

Guests (anonymous users) can only view public todo lists

Admins can view all lists

Managing todo lists

Right now I'm going with something like this:

```<code>Feature: Managing Todo lists
  In order to be more productive
  As a user of the site
  I want to be able to manage todo lists

Background:
  Given a user named "user-one@email.com" with password "secret-one"
  Given a user named "user-two@email.com" with password "secret-two"
  Given an admin named "admin@email.com" with password "admin"

Scenario: user-one@email.com can view his own private todo lists
Scenario: user-one@email.com can not view user-two@email.com private todo lists
Scenario: admin@email.com can view user-one@email.com and user-two@email.com private todo lists
Scenario: user-one@email.com can create private todo lists
Scenario: user-one@email.com can delete todo lists they own
Scenario: admin@email.com can delete user-one@email todo list
Scenario: guests can view all public todo lists
</code>```

The problem I'm running into is the setup for each scenario. For example, in the first scenario I have to assume user-one@email.com is logged in. In the first admin@email.com scenario I have to assume the admin is logged in. In the last scenario I need to assume no one is logged in.

So how do I manage those Givens? Do I just add a

```<code>Given user-one@email.com is logged in
</code>```

To every single scenario? Or is there a better way to go about structuring all this? Please help! I'm sure this is a very common pattern that cucumber users need to test.

答:
Generally I try to list only the steps that are important.  In your case I would do something like:

```<code>Feature: Managing Todo lists
  In order to be more productive
  As a user of the site
  I want to be able to manage todo lists

Background:
  Given a user named "user-one@email.com" with password "secret-one"
  Given a user named "user-two@email.com" with password "secret-two"
  Given an admin named "admin@email.com" with password "admin"

Scenario: Users can see own private todo lists
  Given user "user-one" has a private todo list
  Then user "user-one" can see the private todo list of "user-one"

Scenario: Users cannot see others private todo lists
  Given user "user-one" has a private todo list
  Then user "user-two" cannot see the private todo list of "user-one"
</code>```

If you have a login step elsewhere you can re-use that step in the Then user "user-one" can see the private todo list of "user-one" step defintion, rather than in the feature.  Or your step could just share the same code directly.

See step re-use

ContentLicense: CC BY-SA 2.5

Body:
I'm new to cucumber and currently stuck trying to organize/structure some features/scenarios. The behavior I'm trying to capture is that of users, guests and admins using my website. The website is basically for creating private and public todo lists.

And these are the specific scenarios I want to test:

Registered users can view their private todo lists (but not someone else's private todo list)

Guests (anonymous users) can only view public todo lists

Admins can view all lists

Managing todo lists

Right now I'm going with something like this:

Feature: Managing Todo lists
  In order to be more productive
  As a user of the site
  I want to be able to manage todo lists

Background:
  Given a user named "user-one@email.com" with password "secret-one"
  Given a user named "user-two@email.com" with password "secret-two"
  Given an admin named "admin@email.com" with password "admin"

Scenario: user-one@email.com can view his own private todo lists
Scenario: user-one@email.com can not view user-two@email.com private todo lists
Scenario: admin@email.com can view user-one@email.com and user-two@email.com private todo lists
Scenario: user-one@email.com can create private todo lists
Scenario: user-one@email.com can delete todo lists they own
Scenario: admin@email.com can delete user-one@email todo list
Scenario: guests can view all public todo lists

The problem I'm running into is the setup for each scenario. For example, in the first scenario I have to assume user-one@email.com is logged in. In the first admin@email.com scenario I have to assume the admin is logged in. In the last scenario I need to assume no one is logged in.

So how do I manage those Givens? Do I just add a

Given user-one@email.com is logged in

To every single scenario? Or is there a better way to go about structuring all this? Please help! I'm sure this is a very common pattern that cucumber users need to test.

Body:
Generally I try to list only the steps that are important.  In your case I would do something like:

Feature: Managing Todo lists
  In order to be more productive
  As a user of the site
  I want to be able to manage todo lists

Background:
  Given a user named "user-one@email.com" with password "secret-one"
  Given a user named "user-two@email.com" with password "secret-two"
  Given an admin named "admin@email.com" with password "admin"

Scenario: Users can see own private todo lists
  Given user "user-one" has a private todo list
  Then user "user-one" can see the private todo list of "user-one"

Scenario: Users cannot see others private todo lists
  Given user "user-one" has a private todo list
  Then user "user-two" cannot see the private todo list of "user-one"

If you have a login step elsewhere you can re-use that step in the Then user "user-one" can see the private todo list of "user-one" step defintion, rather than in the feature.  Or your step could just share the same code directly.

See step re-use


问:
Is there any way to revert changes from a specific file to the latest commit?
I just did add>commit>push and everything worked fine. Then made many changes and made some more pushes. But now one file is buggy and I need to revert only that file to the latest commit not the whole project. How can I do that without losing rest of my changes? </p>

答:
this worked for me very well:

```<code>git status // showing all the files I changed after the commit.
</code>```

as you can see in the log, it says: (use "git checkout -- <file>..." to discard changes in working directory) so:

```<code>git checkout -- <filename as it shows in git status log>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
this worked for me very well:

git status // showing all the files I changed after the commit.

as you can see in the log, it says: (use "git checkout -- <file>..." to discard changes in working directory) so:

git checkout -- <filename as it shows in git status log>


问:
AudioKit FFT conversion to dB?
First time posting, thanks for the great community!

I am using AudioKit and trying to add frequency weighting filters to the microphone input and so I am trying to understand the values that are coming out of the AudioKit AKFFTTap.

Currently I am trying to just print the FFT buffer converted into dB values

```<code>for i in 0..<self.bufferSize {
    let db = 20 * log10((self.fft?.fftData[Int(i)])!)
    print(db)
}
</code>```

I was expecting values ranging in the range of about -128 to 0, but I am getting strange values of nearly -200dB and when I blow on the microphone to peg out the readings it only reaches about -60. Am I not approaching this correctly? I was assuming that the values being output from the EZAudioFFT engine would be plain amplitude values and that the normal dB conversion math would work. Anyone have any ideas?

Thanks in advance for any discussion about this issue!

答:
The values in the array correspond to the values of the bins in the FFT. Having a single bin contain a magnitude value close to 1 would mean that a great amount of energy is in that narrow frequency band e.g. a very loud sinusoid (a signal with a single frequency).

Normal sounds, such as the one caused by you blowing on the mic, spread their energy across the entire spectrum, that is, in many bins instead of just one. For this reason, usually the magnitudes get lower as the FFT size increases.

Magnitude of -40dB on a single bin is quite loud. If you try to play a tone, you should see a clear peak in one of the bins.

Title: AudioKit FFT conversion to dB?

Body:
First time posting, thanks for the great community!

I am using AudioKit and trying to add frequency weighting filters to the microphone input and so I am trying to understand the values that are coming out of the AudioKit AKFFTTap.

Currently I am trying to just print the FFT buffer converted into dB values

for i in 0..<self.bufferSize {
    let db = 20 * log10((self.fft?.fftData[Int(i)])!)
    print(db)
}

I was expecting values ranging in the range of about -128 to 0, but I am getting strange values of nearly -200dB and when I blow on the microphone to peg out the readings it only reaches about -60. Am I not approaching this correctly? I was assuming that the values being output from the EZAudioFFT engine would be plain amplitude values and that the normal dB conversion math would work. Anyone have any ideas?

Thanks in advance for any discussion about this issue!


问:
Visual Studio pre-link event triggers twice
Sorry the problem is probably not reproducible by others, but still maybe someone had it before or has a clue what might be going on...

I have a C++ solution in visual studio 2015, community edition.
There are 3 project: a lib, a test app for the lib and the actual application that uses the lib. The final app has a build dependency on the test app and custom pre-link step, so it executes unit tests on each build:

Both test app and the real app are console applications.
Once I press F7 to build the solution, I see the following:

the lib builds (as expected)

the test app builds and links (as expected)

the test app is triggered and I can see it running in a console window, with window title exactly as in the custom build step (this is not expected)

the test app runs again, this time without the console window, instead I see its console output in VS Output window. (expected)

the real application builds and links (expected)

What's even more weird, step #3 doesn't happen always. I cannot figure out why and what's the rule.

Any clues anyone?

答:
Ok, it was so annoying I've spent more time trying to figure out what's happening and finally noticed, that it's the antivirus....
This is the solution: getavast.net/support/disable-cybercapture</p>


问:
On Change navigate to url value from within an array
I have a select menu that is pulling all of its options from an array of objects. See below. I want to have the menu navigate to each's state's url value on change and open in a new tab, but what I have is not firing correctly. I have an if/else statement that keeps firing back 'false' as it is not recognizing a url value. </p>

```<code>let states = [
      {id: 1, state: "Alabama", district: "1st District", url:"www.google.com"},
      {id: 2, state: "Alabama", district: "2nd District", url:"www.google.com"},
      {id: 3, state: "Alabama", district: "3rd District", url:"www.google.com"},
      {id: 4, state: "Alabama", district: "4th District", url:"www.google.com"},
      {id: 5, state: "Alabama", district: "5th District", url:"www.google.com"},
      {id: 6, state: "Alabama", district: "6th District", url:"www.google.com"},
      {id: 7, state: "Alabama", district: "7th District", url:"www.google.com"},
      {id: 9, state: "Alaska", district: "Statewide District", url:"www.google.com"},
      {id: 10, state: "Arizona", district: "1st District", url:"www.google.com"},
      {id: 11, state: "Arizona", district: "2nd District", url:"www.google.com"},
      {id: 12, state: "Arizona", district: "3rd District", url:"www.google.com"},
</code>```

<p>There are more states but above is just a snippet. </p>

```<code><body>
    <div class="container55">
      <h2>Find Out How Tax Reform Will Impact Your District</h2>
        <select id="listed_states">
          <option>Find Your District Here</option>
        </select>
    </div>
  </body>

   <script>
    $(document).ready(function() {
  //Code block generating dropdown list from states object
      for (let i = 0; i < states.length; i++) {
       if (states[i].id > 0) {
        var option = $("<option>", {
         text: states[i].state + " " + states[i].district,
         value: states[i].id
       });
      $('#listed_states').append($(option));
    }
  }

  $('#listed_states').on('change', function(){
   if ($(this).url){
    window.open($(this).url, '_blank');
   } else {
    console.log('false');
   }
  })
 });
 </script>
</code>```

答:
option missing url  and you change $(this).url with $(this).find('option:selected').attr('url')

```<code>//Code block generating dropdown list from states object
          for (let i = 0; i < states.length; i++) {
           if (states[i].id > 0) {
            var option = $("<option>", {
             text: states[i].state + " " + states[i].district,
             value: states[i].id,
             url : states[i].url
           });
          $('#listed_states').append($(option));
        }
      }

      $('#listed_states').on('change', function(){
       if ($(this).find('option:selected').attr('url')){
        window.open($(this).find('option:selected').attr('url'), '_blank');
       } else {
        console.log('false');
       }
      })
     });
</code>```

https://codepen.io/piscu/pen/eeGzBP

Body:
I have a select menu that is pulling all of its options from an array of objects. See below. I want to have the menu navigate to each's state's url value on change and open in a new tab, but what I have is not firing correctly. I have an if/else statement that keeps firing back 'false' as it is not recognizing a url value.

let states = [
      {id: 1, state: "Alabama", district: "1st District", url:"www.google.com"},
      {id: 2, state: "Alabama", district: "2nd District", url:"www.google.com"},
      {id: 3, state: "Alabama", district: "3rd District", url:"www.google.com"},
      {id: 4, state: "Alabama", district: "4th District", url:"www.google.com"},
      {id: 5, state: "Alabama", district: "5th District", url:"www.google.com"},
      {id: 6, state: "Alabama", district: "6th District", url:"www.google.com"},
      {id: 7, state: "Alabama", district: "7th District", url:"www.google.com"},
      {id: 9, state: "Alaska", district: "Statewide District", url:"www.google.com"},
      {id: 10, state: "Arizona", district: "1st District", url:"www.google.com"},
      {id: 11, state: "Arizona", district: "2nd District", url:"www.google.com"},
      {id: 12, state: "Arizona", district: "3rd District", url:"www.google.com"},

There are more states but above is just a snippet.

Find Out How Tax Reform Will Impact Your District

        <select id="listed_states">
          <option>Find Your District Here</option>
        </select>

Body:
option missing url  and you change $(this).url with $(this).find('option:selected').attr('url')

//Code block generating dropdown list from states object
          for (let i = 0; i < states.length; i++) {
           if (states[i].id > 0) {
            var option = $("<option>", {
             text: states[i].state + " " + states[i].district,
             value: states[i].id,
             url : states[i].url
           });
          $('#listed_states').append($(option));
        }
      }

      $('#listed_states').on('change', function(){
       if ($(this).find('option:selected').attr('url')){
        window.open($(this).find('option:selected').attr('url'), '_blank');
       } else {
        console.log('false');
       }
      })
     });

https://codepen.io/piscu/pen/eeGzBP


问:
How do I parse Dict of {String, Dict of {String, Variant}} with QDBus?
I am querying NetworkManager's org.freedesktop.NetworkManager.Settings.Connection interface, calling "GetSettings" on it. It returns a Dict of {String, Dict of {String, Variant}} or a{sa{sv}} in Dbus type terms. I'm using QtCreator with Qt4 to build my application.

I cannot seem to get a piece of useable information out of this dictionary.
I cannot provide a MVE as it is heavily dependent if NetworkManager and DBus and Qt4 is installed on someone's system.

Here is the method I am developing to get information out of this Dictionary of Strings and Dictionary of Strings and Variants. I can see all the nice data that I want when piping it into qDebug(): qDebug()<<reply.

```<code>void GetInfo()
{
    //sysbus just means the system DBus.
    QDBusInterface connSettings("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings/1", "org.freedesktop.NetworkManager.Settings.Connection", sysbus);
    QDBusMessage reply = connections.call("GetSettings");
    if(reply.type() == QDBusMessage::ReplyMessage)
    {
        //I have tried everything I can imagine here,
        //QVariant g = reply.arguments().at(0).value<QVariant>(); did not work
        //g.canConvert<QMap>(); returns false, in contrast to what KDE says.
        //QDbusArgument g = query.arguments().at(0).value<QDBusArgument>();
        //g.beginMap(); and such don't work
    }
}
</code>```

It's very hard finding information on parsing a Dict type. The only source I found that provides some info is KDE. It says "The DBus Dict type should map to QMap, example to follow.." and no other hits on Google or examples exist. Maybe I am missing some fundemantal DBus knowledge, but I'm stumped.

I also checked out this excellent answer: How do I extract the returned data from QDBusMessage in a Qt DBus call? but I could not adapt it to parse a dict.

Would anyone know how to get to the last nested QVariant?

答:
Unfortunately, Qts DBUS API is not always the most straightforward to understand, so here's some tips.  Basically what I've found that works for me is that you will have to get the DBusArgument from the reply, and that is what is actually used in order to get the actual data.  Depending on what you are extracting, you can either override the operator<< and operator>> in your .cpp file(the documentation for QDBusArgument says how to do this), or you can define the type that you want to extract as.  The other important thing to note is that QDBusReply::arguments() contains either sending or receiving arguments, depending on if it a reply or a call.

Anyway, the following works for me(albeit in Qt5, but I expect that it should work in Qt4 as well)

```<code>QDBusInterface connSettings("org.freedesktop.NetworkManager",
                            "/org/freedesktop/NetworkManager/Settings/1",
                            "org.freedesktop.NetworkManager.Settings.Connection",
                            QDBusConnection::systemBus() );
QDBusMessage reply = connSettings.call("GetSettings");

qDebug() << "Reply below:";
qDebug() << reply;

qDebug() << "Extracted: ";

// Extract the argument from the reply
// In this case, we know that we get data back from the method call,
// but a range check is good here as well(also to ensure that the
// reply is a method reply, not an error)
const QDBusArgument &dbusArg = reply.arguments().at( 0 ).value<QDBusArgument>();

// The important part here: Define the structure type that we want to
// extract.  Since the DBus type is a{sa{sv}}, that corresponds to a
// Map with a key of QString, which maps to another map of
// QString,QVariant
QMap<QString,QMap<QString,QVariant> > map;
dbusArg >> map;
qDebug() << "Map is: " << map;

// We're just printing out the data in a more user-friendly way here
for( QString outer_key : map.keys() ){
    QMap<QString,QVariant> innerMap = map.value( outer_key );

    qDebug() << "Key: " << outer_key;
    for( QString inner_key : innerMap.keys() ){
        qDebug() << "    " << inner_key << ":" << innerMap.value( inner_key );
    }
}
</code>```

Body:
I am querying NetworkManager's org.freedesktop.NetworkManager.Settings.Connection interface, calling "GetSettings" on it. It returns a Dict of {String, Dict of {String, Variant}} or a{sa{sv}} in Dbus type terms. I'm using QtCreator with Qt4 to build my application.

I cannot seem to get a piece of useable information out of this dictionary.
I cannot provide a MVE as it is heavily dependent if NetworkManager and DBus and Qt4 is installed on someone's system.

Here is the method I am developing to get information out of this Dictionary of Strings and Dictionary of Strings and Variants. I can see all the nice data that I want when piping it into qDebug(): qDebug()<<reply.

void GetInfo()
{
    //sysbus just means the system DBus.
    QDBusInterface connSettings("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings/1", "org.freedesktop.NetworkManager.Settings.Connection", sysbus);
    QDBusMessage reply = connections.call("GetSettings");
    if(reply.type() == QDBusMessage::ReplyMessage)
    {
        //I have tried everything I can imagine here,
        //QVariant g = reply.arguments().at(0).value<QVariant>(); did not work
        //g.canConvert<QMap>(); returns false, in contrast to what KDE says.
        //QDbusArgument g = query.arguments().at(0).value<QDBusArgument>();
        //g.beginMap(); and such don't work
    }
}

It's very hard finding information on parsing a Dict type. The only source I found that provides some info is KDE. It says "The DBus Dict type should map to QMap, example to follow.." and no other hits on Google or examples exist. Maybe I am missing some fundemantal DBus knowledge, but I'm stumped.

I also checked out this excellent answer: How do I extract the returned data from QDBusMessage in a Qt DBus call? but I could not adapt it to parse a dict.

Would anyone know how to get to the last nested QVariant?

Body:
Unfortunately, Qts DBUS API is not always the most straightforward to understand, so here's some tips.  Basically what I've found that works for me is that you will have to get the DBusArgument from the reply, and that is what is actually used in order to get the actual data.  Depending on what you are extracting, you can either override the operator<< and operator>> in your .cpp file(the documentation for QDBusArgument says how to do this), or you can define the type that you want to extract as.  The other important thing to note is that QDBusReply::arguments() contains either sending or receiving arguments, depending on if it a reply or a call.

Anyway, the following works for me(albeit in Qt5, but I expect that it should work in Qt4 as well)

QDBusInterface connSettings("org.freedesktop.NetworkManager",
                            "/org/freedesktop/NetworkManager/Settings/1",
                            "org.freedesktop.NetworkManager.Settings.Connection",
                            QDBusConnection::systemBus() );
QDBusMessage reply = connSettings.call("GetSettings");

qDebug() << "Reply below:";
qDebug() << reply;

qDebug() << "Extracted: ";

// Extract the argument from the reply
// In this case, we know that we get data back from the method call,
// but a range check is good here as well(also to ensure that the
// reply is a method reply, not an error)
const QDBusArgument &dbusArg = reply.arguments().at( 0 ).value<QDBusArgument>();

// The important part here: Define the structure type that we want to
// extract.  Since the DBus type is a{sa{sv}}, that corresponds to a
// Map with a key of QString, which maps to another map of
// QString,QVariant
QMap<QString,QMap<QString,QVariant> > map;
dbusArg >> map;
qDebug() << "Map is: " << map;

// We're just printing out the data in a more user-friendly way here
for( QString outer_key : map.keys() ){
    QMap<QString,QVariant> innerMap = map.value( outer_key );

    qDebug() << "Key: " << outer_key;
    for( QString inner_key : innerMap.keys() ){
        qDebug() << "    " << inner_key << ":" << innerMap.value( inner_key );
    }
}


问:
Find a way in the java logging frameworks scene
Java has a lot of frameworks / APIs that help you do logging in your application:

The Java API has java.util.logging package.

Apache's Log4j.

Apache's Commons Logging.

SLF4J (logging Facade).

jLo.
and many many more...

I've always used the log4j library, i found it sufficient most of the time, and extensible when i needed more control.

Anyone who had experience with more than one framework can share his experience? when is it better to use one framework over the other and from application architecture point of view? Why would i prefer one over other?

Thanks

答:
Whatever the official position is "log4j" is the standard logging framework.

It works well and has been around for a while. Its the most deployed logging framework used by thousands of apps and packages. Its also the logging framework most likely to appear on a developers CV.

Stick with log4j there is no good reason to try anything else.

OwnerDisplayName: Alon

OwnerDisplayName: James Anderson


问:
Scope-resolution operator :: versus member-access operator . in C#
In C#, what's the difference between A::B and A.B? The only difference I've noticed is that only :: can be used with global, but other than that, what's the difference? Why do they both exist?

答:
the :: operator only works with aliases global is a special system provided alias.

so ... this works:

```<code>using Foo = System.ComponentModel;

public MyClass {

  private Foo::SomeClassFromSystemComponentModel X;

}
</code>```

but not this:

```<code>public MyClass {

  private System.ComponentModel::SomeClassFromSystemComponentModel X;

}
</code>```

This lets you escape from the hell of sub namespaces that can come about when you are integrating with a library where they have:

```<code>namespace MyAwesomeProduct.System
{

}
</code>```

And you in you code have

```<code>using MyAwesomeProduct;
</code>```

global:: lets you find the real System.

MSDN info here

Body:
the :: operator only works with aliases global is a special system provided alias.

so ... this works:

using Foo = System.ComponentModel;

public MyClass {

  private Foo::SomeClassFromSystemComponentModel X;

}

but not this:

public MyClass {

  private System.ComponentModel::SomeClassFromSystemComponentModel X;

}

This lets you escape from the hell of sub namespaces that can come about when you are integrating with a library where they have:

namespace MyAwesomeProduct.System
{

}

And you in you code have

using MyAwesomeProduct;

global:: lets you find the real System.

MSDN info here


问:
AngularJS and redirect within factory
I have a factory from where I want to redirect to another app location
'use strict';

```<code>myApp.factory('wizard', ['$rootScope', '$location', function ($rootScope, $location){

    return {

        doSteps: function(step){

            switch (step){
                case 1 :
                    $location.path('/');
                    $rootScope.$apply();
                    break;
                case 2 :
                    $location.path('start');
                    $rootScope.$apply();
                    break;
                case 3 :
                    $location.path('tutorial');
                    $rootScope.$apply();
                    break;
                case 4 :
                    $location.path('finish');
                    $rootScope.$apply()
                    break;
                default:
                    $location.path('/');
                    $rootScope.$apply();
            }
        }
    }

}]);
</code>```

which is suppose to be triggered by a button link in index.html file

```<code><a href="" ng-click="wizard.doSteps(1)" type="button" class="btn btn-circle" ng-class="{'btn-default': step !== 1, 'btn-primary': step === 1 }" id="step-1">1</a>
</code>```

and so on based on a step

Controller is loading wizard factory but somehow I'm not able to execute function from that factory on ng-click.

Question is if I'm doing this right or not?

答:
Try

```<code>ng-click="doStepts(1)"
</code>```

in html
and in your controller

```<code>$scope.doSteps=function(i){wizard.doSteps(i) }
</code>```

Title: AngularJS and redirect within factory

Body:
I have a factory from where I want to redirect to another app location
'use strict';

myApp.factory('wizard', ['$rootScope', '$location', function ($rootScope, $location){

    return {

        doSteps: function(step){

            switch (step){
                case 1 :
                    $location.path('/');
                    $rootScope.$apply();
                    break;
                case 2 :
                    $location.path('start');
                    $rootScope.$apply();
                    break;
                case 3 :
                    $location.path('tutorial');
                    $rootScope.$apply();
                    break;
                case 4 :
                    $location.path('finish');
                    $rootScope.$apply()
                    break;
                default:
                    $location.path('/');
                    $rootScope.$apply();
            }
        }
    }

}]);

which is suppose to be triggered by a button link in index.html file

1

and so on based on a step

Controller is loading wizard factory but somehow I'm not able to execute function from that factory on ng-click.

Question is if I'm doing this right or not?

Body:
Try

ng-click="doStepts(1)"

in html
and in your controller

$scope.doSteps=function(i){wizard.doSteps(i) }


问:
JS compare the order of SOME elements in two different arrays
I'm trying to figure out how to compare if certain elements in two arrays compare in the same order.

var compare = function (arr1, arr2) {
//........
}

compare ([f,t,r,m], [s,f,t,r,q,p,m]); //should return true

compare ([f,t,r,m], [f,a,t,,m,r]); //should return false```
</div>
</div>
</p>

<p>I proceeded with a for loop and then identifying when the values match, then I'm pretty sure you should compare the arrays but I feel I'm missing something.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var compare = function (a, b) {
  a.forEach(function(letter){
    for (i=0; i<b.length; i++) {
      if (letter===b[i]) {}
    }
  })
}</code>```

答:
You could take an index for array2 and check while iterating and return the comparison of the index and array2 and the element of array1.

function compare(array1, array2) {
    var i = 0;
    return array1.every(function (a) {
        while (i < array2.length && a !== array2[i]) {
            i++;
        }
        return a === array2[i++];
    });
}

console.log(compare(['f', 't', 'r', 'm'], ['s', 'f', 't', 'r', 'q', 'p', 'm'])); // true
console.log(compare(['f', 't', 'r', 'm'], ['f', 'a', 't', , 'm', 'r']));         // false```

Body:
I'm trying to figure out how to compare if certain elements in two arrays compare in the same order.

var compare = function (arr1, arr2) {
//........
}

compare ([f,t,r,m], [s,f,t,r,q,p,m]); //should return true

compare ([f,t,r,m], [f,a,t,,m,r]); //should return false

I proceeded with a for loop and then identifying when the values match, then I'm pretty sure you should compare the arrays but I feel I'm missing something.

var compare = function (a, b) {
  a.forEach(function(letter){
    for (i=0; i<b.length; i++) {
      if (letter===b[i]) {}
    }
  })
}


问:
Possible to use Math.min to get second smallest number from array?
I am using Math.min to get the smallest number out of an array of numbers. However, I also need to get the second smallest number as well. Wondering if there is a way to do this using Math.min as well, otherwise looking for the best way to get this number.

Here's what I have:

var arr = [15, 37, 9, 21, 55];
var min = Math.min.apply(null, arr.filter(Boolean));
var secondMin; // Get second smallest number from array here

console.log('Smallest number: ' + min);
console.log('Second smallest number: ' + secondMin);```

答:
If you are not worried about performance you could simply sort the array.</p>

```<code>arr.sort(function(a, b) {
  return a - b;
});
</code>```

Body:
If you are not worried about performance you could simply sort the array.

arr.sort(function(a, b) {
  return a - b;
});


问:
jQuery AJAX call to fetch web api data returns syntax error
I am trying to fetch this json object from this url:

https://test3.diavgeia.gov.gr/luminapi/opendata/dictionaries//KANONISTIKI_PRAXI_TYPE.json

You might not get much since it's in greek but you get the jsonformat.

Here's my code:

```<code>function getDicts() {
  api_url = 'https://test3.diavgeia.gov.gr/luminapi/opendata/dictionaries/KANONISTIKI_PRAXI_TYPE.json'
  $.ajax({
    headers: {
      'Access-Control-Allow-Origin': '*',
    },
    url: api_url,
    type: "GET",
    crossDomain: true,
    dataType: 'jsonp',
    success: function(api_data) {
      var obj = $.parseJSON(api_data);
      console.log(obj);
    },
    error: function(error) {
      console.log(error);
    },

  });
};
};
getDicts();
</code>```

If I use jsonas thedataType` I get the error:
 SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the json data

This is a screenshot from my call:

Here's a fiddle : https://jsfiddle.net/danee/sz7tLru8/

UPDATE!

I changed slightly the function, following some examples I found. Using the jsonp dataType, on the Network tab I do get a json object but on the console I get this:
SyntaxError: missing ; before statement[Learn More]  KANONISTIKI_PRAXI_TYPE.json:1:7

Here's a screenshot from the call with jsonp.

 That seems like an error on the json object? Haven't encountered that before.

I have updated the fiddle as well, but I get nothing there, no response.

答:
Your internet browser is blocking CORS Ajax calls. As a workaround one option is to deploy your own web application just for running web requests to target diavgeia.gov.gr external web api without this restriction.

Internet browser -(Ajax) -> Your web server -> Target web site

Another option is using reverse proxy websites that already provide this service for free. They will call the external web api for you from a server, not an Internet browser, so that CORS can be avoided.

Internet browser -(Ajax) -> Reverse proxy -> Target web site

```<code>let anonimizerUrl = 'https://allorigins.us';
var apiUrl = 'https://test3.diavgeia.gov.gr/luminapi/opendata/dictionaries/KANONISTIKI_PRAXI_TYPE.json';
$.ajax({
  url: anonimizerUrl + '/get?url=' + encodeURIComponent(apiUrl),
  success: function(response) {
    //Although response is an object, the field contents is a string and needs to be parsed here.
    var data = JSON.parse(response.contents);
    console.log(data);
  },
  error: function(request) {
    console.log(request.responseText);
  }
});
</code>```

If Allorigins is blocked by your internet provider (ISP), try another similar server from this list including.

https://cors-anywhere.herokuapp.com

http://www.whateverorigin.org

http://anyorigin.com

Note: Based on your post, I'm assuming you don't have access to make changes to the web api. Otherwise CORS can be enable from there or make changes for returning jsonp instead of json.

Body:
I am trying to fetch this json object from this url:

https://test3.diavgeia.gov.gr/luminapi/opendata/dictionaries//KANONISTIKI_PRAXI_TYPE.json

You might not get much since it's in greek but you get the jsonformat.

Here's my code:

function getDicts() {
  api_url = 'https://test3.diavgeia.gov.gr/luminapi/opendata/dictionaries/KANONISTIKI_PRAXI_TYPE.json'
  $.ajax({
    headers: {
      'Access-Control-Allow-Origin': '*',
    },
    url: api_url,
    type: "GET",
    crossDomain: true,
    dataType: 'jsonp',
    success: function(api_data) {
      var obj = $.parseJSON(api_data);
      console.log(obj);
    },
    error: function(error) {
      console.log(error);
    },

  });
};
};
getDicts();

If I use jsonas thedataType` I get the error:
 SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the json data

This is a screenshot from my call:

Here's a fiddle : https://jsfiddle.net/danee/sz7tLru8/

UPDATE!

I changed slightly the function, following some examples I found. Using the jsonp dataType, on the Network tab I do get a json object but on the console I get this:
SyntaxError: missing ; before statement[Learn More]  KANONISTIKI_PRAXI_TYPE.json:1:7

Here's a screenshot from the call with jsonp.

 That seems like an error on the json object? Haven't encountered that before.

I have updated the fiddle as well, but I get nothing there, no response.

Body:
Your internet browser is blocking CORS Ajax calls. As a workaround one option is to deploy your own web application just for running web requests to target diavgeia.gov.gr external web api without this restriction.

Internet browser -(Ajax) -> Your web server -> Target web site

Another option is using reverse proxy websites that already provide this service for free. They will call the external web api for you from a server, not an Internet browser, so that CORS can be avoided.

Internet browser -(Ajax) -> Reverse proxy -> Target web site

let anonimizerUrl = 'https://allorigins.us';
var apiUrl = 'https://test3.diavgeia.gov.gr/luminapi/opendata/dictionaries/KANONISTIKI_PRAXI_TYPE.json';
$.ajax({
  url: anonimizerUrl + '/get?url=' + encodeURIComponent(apiUrl),
  success: function(response) {
    //Although response is an object, the field contents is a string and needs to be parsed here.
    var data = JSON.parse(response.contents);
    console.log(data);
  },
  error: function(request) {
    console.log(request.responseText);
  }
});

If Allorigins is blocked by your internet provider (ISP), try another similar server from this list including.

https://cors-anywhere.herokuapp.com

http://www.whateverorigin.org

http://anyorigin.com

Note: Based on your post, I'm assuming you don't have access to make changes to the web api. Otherwise CORS can be enable from there or make changes for returning jsonp instead of json.


问:
Getting correct counts from Pandas Groupby
I have a Pandas DataFrame with the following:

```<code>Name   | Attended
Smith  | Y
Smith  | Y
Smith  | N
Adams  | N
Adams  | Y
Morgan | Y
Morgan | Y
</code>```

and I'd like to count the number of Y's and Ns for each Name.
so the output would be:

```<code>Name  | Attended| Count
Smith | Y       | 2
      | N       | 1
Adams | Y       | 1
      | N       | 1
Morgan| Y       | 3
      | N       | 0
</code>```

I tried df.groupby(["Name","Attended"]).count() and variations of it, but for some reason I don't get the right output. I get either the Name and simply the count (Smith 3, Adam 2, Morgan 3) or the same dataframe again. Help! Am I grouping by incorrectly? I looked for awhile over similar questions and my code matches with the answers there.

I'm using Python 3 and jupyter notebook.

答:
Or get the size of each group</p>

```<code>df = df.groupby(['Name', 'Attended']).size().to_frame(name = 'Count')

                Count
Name    Attended
Adams   N       1
        Y       1
Morgan  Y       2
Smith   N       1
        Y       2
</code>```

Body:
I have a Pandas DataFrame with the following:

Name   | Attended
Smith  | Y
Smith  | Y
Smith  | N
Adams  | N
Adams  | Y
Morgan | Y
Morgan | Y

and I'd like to count the number of Y's and Ns for each Name.
so the output would be:

Name  | Attended| Count
Smith | Y       | 2
      | N       | 1
Adams | Y       | 1
      | N       | 1
Morgan| Y       | 3
      | N       | 0

I tried df.groupby(["Name","Attended"]).count() and variations of it, but for some reason I don't get the right output. I get either the Name and simply the count (Smith 3, Adam 2, Morgan 3) or the same dataframe again. Help! Am I grouping by incorrectly? I looked for awhile over similar questions and my code matches with the answers there.

I'm using Python 3 and jupyter notebook.

Body:
Or get the size of each group

df = df.groupby(['Name', 'Attended']).size().to_frame(name = 'Count')

                Count
Name    Attended
Adams   N       1
        Y       1
Morgan  Y       2
Smith   N       1
        Y       2


问:
How to modify/add a new objectClass to an entry in OpenLDAP php
I have an entry in the AD(Active Directory) which has only person objectclass with attributes of cn and sn.
Now I want to add one more objectclass of organizationalPerson to insert postalCode attribute using LDAP.

I am new to LDAP, please help me.

Thanks in advance.

答:
Your question is not detailed enough to get any context. If your requirement is just to add an organizationalPerson objectClass to an existing object, you can do so through command line or using phpldapadmin/ Apache Directory Studio for GUI.

You can refer this site to get a basic understanding on how to configure and use openldap


问:
Internal Error 500 Apache, but nothing in the logs?
I'm getting 500 Internal Server errors when I try to make an HTTP POST to a specific address in my app.  I've looked into the server logs in the custom log directory specified in the virtual hosts file, but the error doesn't show up there so debugging this has been a pain in the ass.

How do I cause Apache to log Internal 500 errors into the error log?

答:
Please Note: The original poster was not specifically asking about PHP. All the php centric answers make large assumptions not relevant to the actual question.

The default error log as opposed to the scripts error logs usually has the (more) specific error. often it will be permissions denied or even an interpreter that can't be found.

This means the fault almost always lies with your script. e.g you uploaded a perl script but didnt give it execute permissions? or perhaps it was corrupted in a linux environment if you write the script in windows and then upload it to the server without the line endings being converted you will get this error.

in perl if you forget

```<code>print "content-type: text/html\r\n\r\n";
</code>```

you will get this error

There are many reasons for it. so please first check your error log and then provide some more information.

The default error log is often in /var/log/httpd/error_log or /var/log/apache2/error.log.

The reason you look at the default error logs (as indicated above) is because errors don't always get posted into the custom error log as defined in the virtual host.

Assumes linux and not necessarily perl

Body:
Please Note: The original poster was not specifically asking about PHP. All the php centric answers make large assumptions not relevant to the actual question.

The default error log as opposed to the scripts error logs usually has the (more) specific error. often it will be permissions denied or even an interpreter that can't be found.

This means the fault almost always lies with your script. e.g you uploaded a perl script but didnt give it execute permissions? or perhaps it was corrupted in a linux environment if you write the script in windows and then upload it to the server without the line endings being converted you will get this error.

in perl if you forget

print "content-type: text/html\r\n\r\n";

you will get this error

There are many reasons for it. so please first check your error log and then provide some more information.

The default error log is often in /var/log/httpd/error_log or /var/log/apache2/error.log.

The reason you look at the default error logs (as indicated above) is because errors don't always get posted into the custom error log as defined in the virtual host.

Assumes linux and not necessarily perl


问:
I'm testing wordpress, how do I make my own plugin editable after installation?
there are plugins that can be partially edited from the WordPress administrator panel. The plugin I developed does not allow editing the css files for example. I tried this without success

```<code>add_filter(‘wp_theme_editor_filetypes’, function ($types) {
$types[] = 'css';
$types[] = 'js';
return $types;
</code>```

});

答: Plugins can be edited by any user who can edit_plugins, as seen here. To adjust the editable plugin file extensions, you can use the editable_extensions filter.

Body:
there are plugins that can be partially edited from the WordPress administrator panel. The plugin I developed does not allow editing the css files for example. I tried this without success

add_filter(‘wp_theme_editor_filetypes’, function ($types) {
$types[] = 'css';
$types[] = 'js';
return $types;

});