问:
Import doc and docx files in .Net and C#
I'm writing a text editor and I want to add the possibility to import .doc and .docx files. I know that I could use OLE Automation, but if I use a recent OLE library, it won't work with those people with an older version of Word, and if instead I use an older version, it won't be able to read .docx files.
Any ideas?
Thanks

EDIT: Another solution would be that, like my application works with HTML and RTF, convert .doc and .docx files with command line to one of these formats, something like this: http://www.snee.com/bobdc.blog/ 2007/09/using-word-for-command-line-co.html

答: You should be able to use the OpenXML libraries or xpath in .NET to read / import the contents of a docx file.</p>


来源: stackexchange

问:
JavaPoet - Exception unexpected
So, I'm making a program that takes a Class Diagram and, using JavaPoet, converts it in Java code.

The class Diagram is not written in UML, it's already modelled inside the program with java.

Here is the code portion giving me problems:
(parsing all the attributes inside a class, to add them to the new source code, and to add Setters/Getters if missing)

```<code>for (Attribute a : classe.attributes) { //Parse all the attribute inside the class

    TypeName aClass = stringToType(a.getType()); //the attribute tipe

    FieldSpec aField = FieldSpec.builder(aClass, a.getName()) //the attribute
            .addModifiers(javax.lang.model.element.Modifier.valueOf(a.getProtection().toUpperCase()), a.isStatic() ? Modifier.STATIC : null)
            .build();
    fields.add(aField);

    MethodSpec aMethod = MethodSpec.methodBuilder("set" + upperFirst(a.getName()))
            .addModifiers(Modifier.PUBLIC, a.isStatic() ? Modifier.STATIC : null)
            .returns(TypeName.VOID)
            .addParameter(aClass, a.getName())
            .addStatement("this." + a.getName() + " = " + a.getName())
            .build();
    if (!methods.contains(aMethod)) //if not present, add the set method
        methods.add(aMethod);

    MethodSpec bMethod = MethodSpec.methodBuilder("get" + upperFirst(a.getName()))
            .addModifiers(Modifier.PUBLIC, a.isStatic() ? Modifier.STATIC : null)
            .addStatement("return " + a.getName())
            .returns(aClass)
            .build();

    if (!methods.contains(bMethod)) methods.add(bMethod); //if not present, add the get method

}
</code>```

I get the following exception right on the last line:

```<code>Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
    at java.util.EnumSet.typeCheck(EnumSet.java:396)
    at java.util.RegularEnumSet.add(RegularEnumSet.java:161)
    at java.util.RegularEnumSet.add(RegularEnumSet.java:36)
    at java.util.EnumSet.copyOf(EnumSet.java:179)
    at com.squareup.javapoet.CodeWriter.emitModifiers(CodeWriter.java:172)
    at com.squareup.javapoet.MethodSpec.emit(MethodSpec.java:86)
    at com.squareup.javapoet.MethodSpec.toString(MethodSpec.java:164)
    at com.squareup.javapoet.MethodSpec.equals(MethodSpec.java:153)
    at java.util.ArrayList.indexOf(ArrayList.java:317)
    at java.util.ArrayList.contains(ArrayList.java:300)
</code>```

HERE IS THE CODE I POSTED ->

```<code>    at base.controller.commands.ExportModelCommand.execute(ExportModelCommand.java:224)
    at base.Main.executeCommand(Main.java:113)
    at base.controller.menu.menuitem.ItemExport.lambda$new$0(ItemExport.java:17)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.control.MenuItem.fire(MenuItem.java:462)
    at com.sun.javafx.scene.control.skin.ContextMenuContent$MenuItemContainer.doSelect(ContextMenuContent.java:1405)
    at com.sun.javafx.scene.control.skin.ContextMenuContent$MenuItemContainer.lambda$createChildren$343(ContextMenuContent.java:1358)
    at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
    at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:380)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:294)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(GlassViewEventHandler.java:416)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:415)
    at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
    at com.sun.glass.ui.View.notifyMouse(View.java:937)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
    at java.lang.Thread.run(Thread.java:745)
</code>```

And I really cannot understand why.

I tried to debug, I couldn't find anything at NULL. How do I find the problem?

WHOLE CODE - CLASS MODEL (the omitted part is getters/setters)

```<code>public class ClassModel {

    private String name = "";
    private String parent = null;
    public ArrayList<Attribute> attributes = new ArrayList<Attribute>();
    public ArrayList<Method> methods = new ArrayList<Method>();
    public boolean isInterface;
    private boolean isFinal;
    private ProtectionLevel prote;
    private String genericText="";
    private String stereotype="";

    public ClassModel() {
        }

    public ClassModel(ClassModel original) {
        this.name = original.name;
        this.parent = original.parent;
        this.isInterface = original.isInterface;

        /*
        for (Map.Entry<String, Relation> e : original.relations.entrySet()) {
            this.relations.put(e.getKey(), new Relation(e.getValue()));
        }
        */
        for (Attribute a : original.attributes) {
            this.attributes.add(new Attribute(a));
        }
        for (Method m : original.methods) {
            this.methods.add(new Method(m));
        }
    }
</code>```

WHOLE CODE - EXPORT COMMAND :

```<code>public Message execute() {
    ///////////////////
        /*    Save As    */
    ///////////////////

    // Set tab flag to saved and remove '*' from tab name

    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new File("./"));
    chooser.setDialogTitle("Choose your folder");
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    chooser.setAcceptAllFileFilterUsed(false);

    if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
        for (Tab tab : Main.project.getTabContainer().getTabs()) {
            BaseDiagramModel currentModel = ((UMLTab) tab).getModel();
            if (currentModel.getDiagramPosition() == 2) {

                for (UMLElement e : currentModel) {
                    if (e instanceof UMLClassElementImage) {
                        //prepare content for new file java

                        ClassModel classe = ((UMLClassElementImage) e).modelClass;

                        ArrayList<MethodSpec> methods = new ArrayList<MethodSpec>();
                        ArrayList<FieldSpec> fields = new ArrayList<FieldSpec>();
                        ArrayList<UMLElement> composition = new ArrayList<UMLElement>();
                        ArrayList<UMLElement> aggregation = new ArrayList<UMLElement>();
                        ArrayList<UMLElement> inheritance = new ArrayList<UMLElement>();
                        for (UMLElement x : ((UMLNode<UMLElement>) e).getChildren()) {
                            if (x instanceof UMLArrowAggregation) {
                                aggregation.add(x);

                            } else if (x instanceof UMLArrowComposition) {
                                composition.add(x);

                            } else if (x instanceof UMLArrowEreditarieta) {
                                inheritance.add(x);

                            }
                            //else if (x instanceof UMLArrowDashedLineWithCentralLabelAndApexOnHead) {
                             //   implementation.add(x);
                            //}
                        }

                        for (UMLElement aggregated : aggregation) {
                            UMLElement whatIsAfterTheArrow = ((UMLNode<UMLElement>) aggregated).getChildren().get(0);
                            ClassModel classeAgg = ((UMLClassElementImage) whatIsAfterTheArrow).modelClass;

                            FieldSpec aField = FieldSpec.builder(ClassName.get("", classeAgg.getName()), classeAgg.getName())
                                    .addModifiers(Modifier.PROTECTED)
                                    .build();
                            fields.add(aField);

                            MethodSpec aMethod = MethodSpec.methodBuilder("set" + upperFirst(classeAgg.getName()))
                                    .addModifiers(Modifier.PUBLIC)
                                    .returns(TypeName.VOID)
                                    .addParameter(ClassName.get("", classeAgg.getName()), classeAgg.getName())
                                    .addStatement("this." + classeAgg.getName() + " = " + classeAgg.getName())
                                    .build();
                            if (!methods.contains(aMethod)) methods.add(aMethod);
                            MethodSpec bMethod = MethodSpec.methodBuilder("get" + upperFirst(classeAgg.getName()))
                                    .addModifiers(Modifier.PUBLIC)
                                    .addStatement("return " + classeAgg.getName())
                                    .returns(ClassName.get("", classeAgg.getName()))
                                    .build();
                            if (!methods.contains(bMethod)) methods.add(bMethod);

                        }

                        for (UMLElement composed : composition) {
                            UMLElement whatIsAfterTheArrow = ((UMLNode<UMLElement>) composed).getChildren().get(0);
                            ClassModel classeComp = ((UMLClassElementImage) whatIsAfterTheArrow).modelClass;

                            FieldSpec aField = FieldSpec.builder(ClassName.get("", classeComp.getName()), classeComp.getName())
                                    .addModifiers(Modifier.PROTECTED, Modifier.FINAL)
                                    .build();
                            fields.add(aField);

                            MethodSpec aMethod = MethodSpec.methodBuilder("set" + upperFirst(classeComp.getName()))
                                    .addModifiers(Modifier.PUBLIC)
                                    .returns(TypeName.VOID)
                                    .addParameter(ClassName.get("", classeComp.getName()), classeComp.getName())
                                    .addStatement("this." + classeComp.getName() + " = " + classeComp.getName())
                                    .build();
                            if (!methods.contains(aMethod)) methods.add(aMethod);
                            MethodSpec bMethod = MethodSpec.methodBuilder("get" + upperFirst(classeComp.getName()))
                                    .addModifiers(Modifier.PUBLIC)
                                    .addStatement("return " + classeComp.getName())
                                    .returns(ClassName.get("", classeComp.getName()))
                                    .build();
                            if (!methods.contains(bMethod)) methods.add(bMethod);

                        }

                        for (Attribute a : classe.attributes) {

                            TypeName aClass = stringToType(a.getType());

                            FieldSpec aField = FieldSpec.builder(aClass, a.getName())
                                    .addModifiers(javax.lang.model.element.Modifier.valueOf(a.getProtection().toUpperCase()), a.isStatic() ? Modifier.STATIC : null)
                                    .build();
                            fields.add(aField);

                            MethodSpec aMethod = MethodSpec.methodBuilder("set" + upperFirst(a.getName()))
                                    .addModifiers(Modifier.PUBLIC, a.isStatic() ? Modifier.STATIC : null)
                                    .returns(TypeName.VOID)
                                    .addParameter(aClass, a.getName())
                                    .addStatement("this." + a.getName() + " = " + a.getName())
                                    .build();
                            if (!methods.contains(aMethod))
                                methods.add(aMethod);

                            MethodSpec bMethod = MethodSpec.methodBuilder("get" + upperFirst(a.getName()))
                                    .addModifiers(Modifier.PUBLIC, a.isStatic() ? Modifier.STATIC : null)
                                    .addStatement("return " + a.getName())
                                    .returns(aClass)
                                    .build();

                            if (!methods.contains(bMethod)) methods.add(bMethod);

                        }

                        for (Method m : classe.methods) {

                            ArrayList<ParameterSpec> parametriSpec = new ArrayList<>();
                            Set<Attribute> parametri = m.getParameters();

                            for (Attribute singleParam : parametri) {
                                TypeName attClass = stringToType(singleParam.getType());

                                ParameterSpec test = ParameterSpec.builder(attClass, singleParam.getName())
                                        // .addModifiers(Modifier.FINAL)
                                        .build();
                                parametriSpec.add(test);
                            }

                            TypeName aClass = stringToType(m.getReturnType());

                            MethodSpec aMethod = MethodSpec.methodBuilder(m.getName())

                                    .addModifiers(javax.lang.model.element.Modifier.valueOf(m.getProtection().toUpperCase()), m.isStatic() ? Modifier.STATIC : null)
                                    .returns(aClass)
                                    .addParameters(parametriSpec)
                                    .build();

                            methods.add(aMethod);
                        }
                        TypeSpec theClass = null;

                        TypeName father = null;
                        if (!inheritance.isEmpty())
                            father = ClassName.get("", ((UMLClassElementImage) ((UMLNode<UMLElement>) inheritance.get(0)).getChildren().get(0)).modelClass.getName());
                        try {

                            theClass = TypeSpec.classBuilder(classe.getName())
                                    .addModifiers(((UMLClassElementImage) e).modelClass.getFinal() ? new Modifier[] { javax.lang.model.element.Modifier.valueOf(classe.getProte().toString().toUpperCase()), Modifier.FINAL} : new Modifier[] { javax.lang.model.element.Modifier.valueOf(classe.getProte().toString().toUpperCase()) })
                                    .addModifiers(javax.lang.model.element.Modifier.valueOf(classe.getProte().toString().toUpperCase()), Modifier.FINAL)
                                    .superclass(father == null ? ClassName.OBJECT : father)
                                    .addMethods(methods)
                                    .addFields(fields)
                                    .build();

                            // Create object to choose and create new file

                        } catch (Exception exc) {

                            getFailureMessage("Il nome della classe potrebbe essere sbagliato?");

                        }

                        try {
                            JavaFile javaFile = JavaFile.builder(currentModel.getTitle(), theClass)
                                    .build();
                            Path javaPath = Paths.get(chooser.getSelectedFile().getPath());
                            javaFile.writeTo(javaPath);

                        } catch (Exception exc) {
                            exc.printStackTrace();
                            return getFailureMessage();

                        }

                    }
                    //Else is not a class
                }

            }

        }
    else if (chooser.showOpenDialog(null) == JFileChooser.CANCEL_OPTION)
        return getFailureMessage("Esportazione annullata");

    // Save jsonArray into a file
    // JsonFileManager jsonFileManager = new JsonFileManager();
    // jsonFileManager.save(jsonArray, Main.project.getName() + ".citro");

    return getSuccessMessage();

}
</code>```

答:
The problem were the lines like this one:

```<code>.addModifiers(Modifier.PUBLIC, a.isStatic() ? Modifier.STATIC : null)
</code>```

I discovered it later, but addModifiers(null), instead of doing nothing, makes the whole thing explode

ContentLicense: CC BY-SA 3.0

Title: JavaPoet - Exception unexpected

Body:
So, I'm making a program that takes a Class Diagram and, using JavaPoet, converts it in Java code.

The class Diagram is not written in UML, it's already modelled inside the program with java.

Here is the code portion giving me problems:
(parsing all the attributes inside a class, to add them to the new source code, and to add Setters/Getters if missing)

for (Attribute a : classe.attributes) { //Parse all the attribute inside the class

    TypeName aClass = stringToType(a.getType()); //the attribute tipe

    FieldSpec aField = FieldSpec.builder(aClass, a.getName()) //the attribute
            .addModifiers(javax.lang.model.element.Modifier.valueOf(a.getProtection().toUpperCase()), a.isStatic() ? Modifier.STATIC : null)
            .build();
    fields.add(aField);

    MethodSpec aMethod = MethodSpec.methodBuilder("set" + upperFirst(a.getName()))
            .addModifiers(Modifier.PUBLIC, a.isStatic() ? Modifier.STATIC : null)
            .returns(TypeName.VOID)
            .addParameter(aClass, a.getName())
            .addStatement("this." + a.getName() + " = " + a.getName())
            .build();
    if (!methods.contains(aMethod)) //if not present, add the set method
        methods.add(aMethod);

    MethodSpec bMethod = MethodSpec.methodBuilder("get" + upperFirst(a.getName()))
            .addModifiers(Modifier.PUBLIC, a.isStatic() ? Modifier.STATIC : null)
            .addStatement("return " + a.getName())
            .returns(aClass)
            .build();

    if (!methods.contains(bMethod)) methods.add(bMethod); //if not present, add the get method

}

I get the following exception right on the last line:

Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
    at java.util.EnumSet.typeCheck(EnumSet.java:396)
    at java.util.RegularEnumSet.add(RegularEnumSet.java:161)
    at java.util.RegularEnumSet.add(RegularEnumSet.java:36)
    at java.util.EnumSet.copyOf(EnumSet.java:179)
    at com.squareup.javapoet.CodeWriter.emitModifiers(CodeWriter.java:172)
    at com.squareup.javapoet.MethodSpec.emit(MethodSpec.java:86)
    at com.squareup.javapoet.MethodSpec.toString(MethodSpec.java:164)
    at com.squareup.javapoet.MethodSpec.equals(MethodSpec.java:153)
    at java.util.ArrayList.indexOf(ArrayList.java:317)
    at java.util.ArrayList.contains(ArrayList.java:300)

HERE IS THE CODE I POSTED ->

    at base.controller.commands.ExportModelCommand.execute(ExportModelCommand.java:224)
    at base.Main.executeCommand(Main.java:113)
    at base.controller.menu.menuitem.ItemExport.lambda$new$0(ItemExport.java:17)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.control.MenuItem.fire(MenuItem.java:462)
    at com.sun.javafx.scene.control.skin.ContextMenuContent$MenuItemContainer.doSelect(ContextMenuContent.java:1405)
    at com.sun.javafx.scene.control.skin.ContextMenuContent$MenuItemContainer.lambda$createChildren$343(ContextMenuContent.java:1358)
    at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
    at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:380)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:294)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(GlassViewEventHandler.java:416)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:415)
    at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
    at com.sun.glass.ui.View.notifyMouse(View.java:937)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
    at java.lang.Thread.run(Thread.java:745)

And I really cannot understand why.

I tried to debug, I couldn't find anything at NULL. How do I find the problem?

WHOLE CODE - CLASS MODEL (the omitted part is getters/setters)

public class ClassModel {

    private String name = "";
    private String parent = null;
    public ArrayList<Attribute> attributes = new ArrayList<Attribute>();
    public ArrayList<Method> methods = new ArrayList<Method>();
    public boolean isInterface;
    private boolean isFinal;
    private ProtectionLevel prote;
    private String genericText="";
    private String stereotype="";

    public ClassModel() {
        }

    public ClassModel(ClassModel original) {
        this.name = original.name;
        this.parent = original.parent;
        this.isInterface = original.isInterface;

        /*
        for (Map.Entry<String, Relation> e : original.relations.entrySet()) {
            this.relations.put(e.getKey(), new Relation(e.getValue()));
        }
        */
        for (Attribute a : original.attributes) {
            this.attributes.add(new Attribute(a));
        }
        for (Method m : original.methods) {
            this.methods.add(new Method(m));
        }
    }

WHOLE CODE - EXPORT COMMAND :

public Message execute() {
    ///////////////////
        /*    Save As    */
    ///////////////////

    // Set tab flag to saved and remove '*' from tab name

    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new File("./"));
    chooser.setDialogTitle("Choose your folder");
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    chooser.setAcceptAllFileFilterUsed(false);

    if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
        for (Tab tab : Main.project.getTabContainer().getTabs()) {
            BaseDiagramModel currentModel = ((UMLTab) tab).getModel();
            if (currentModel.getDiagramPosition() == 2) {

                for (UMLElement e : currentModel) {
                    if (e instanceof UMLClassElementImage) {
                        //prepare content for new file java

                        ClassModel classe = ((UMLClassElementImage) e).modelClass;

                        ArrayList<MethodSpec> methods = new ArrayList<MethodSpec>();
                        ArrayList<FieldSpec> fields = new ArrayList<FieldSpec>();
                        ArrayList<UMLElement> composition = new ArrayList<UMLElement>();
                        ArrayList<UMLElement> aggregation = new ArrayList<UMLElement>();
                        ArrayList<UMLElement> inheritance = new ArrayList<UMLElement>();
                        for (UMLElement x : ((UMLNode<UMLElement>) e).getChildren()) {
                            if (x instanceof UMLArrowAggregation) {
                                aggregation.add(x);

                            } else if (x instanceof UMLArrowComposition) {
                                composition.add(x);

                            } else if (x instanceof UMLArrowEreditarieta) {
                                inheritance.add(x);

                            }
                            //else if (x instanceof UMLArrowDashedLineWithCentralLabelAndApexOnHead) {
                             //   implementation.add(x);
                            //}
                        }

                        for (UMLElement aggregated : aggregation) {
                            UMLElement whatIsAfterTheArrow = ((UMLNode<UMLElement>) aggregated).getChildren().get(0);
                            ClassModel classeAgg = ((UMLClassElementImage) whatIsAfterTheArrow).modelClass;

                            FieldSpec aField = FieldSpec.builder(ClassName.get("", classeAgg.getName()), classeAgg.getName())
                                    .addModifiers(Modifier.PROTECTED)
                                    .build();
                            fields.add(aField);

                            MethodSpec aMethod = MethodSpec.methodBuilder("set" + upperFirst(classeAgg.getName()))
                                    .addModifiers(Modifier.PUBLIC)
                                    .returns(TypeName.VOID)
                                    .addParameter(ClassName.get("", classeAgg.getName()), classeAgg.getName())
                                    .addStatement("this." + classeAgg.getName() + " = " + classeAgg.getName())
                                    .build();
                            if (!methods.contains(aMethod)) methods.add(aMethod);
                            MethodSpec bMethod = MethodSpec.methodBuilder("get" + upperFirst(classeAgg.getName()))
                                    .addModifiers(Modifier.PUBLIC)
                                    .addStatement("return " + classeAgg.getName())
                                    .returns(ClassName.get("", classeAgg.getName()))
                                    .build();
                            if (!methods.contains(bMethod)) methods.add(bMethod);

                        }

                        for (UMLElement composed : composition) {
                            UMLElement whatIsAfterTheArrow = ((UMLNode<UMLElement>) composed).getChildren().get(0);
                            ClassModel classeComp = ((UMLClassElementImage) whatIsAfterTheArrow).modelClass;

                            FieldSpec aField = FieldSpec.builder(ClassName.get("", classeComp.getName()), classeComp.getName())
                                    .addModifiers(Modifier.PROTECTED, Modifier.FINAL)
                                    .build();
                            fields.add(aField);

                            MethodSpec aMethod = MethodSpec.methodBuilder("set" + upperFirst(classeComp.getName()))
                                    .addModifiers(Modifier.PUBLIC)
                                    .returns(TypeName.VOID)
                                    .addParameter(ClassName.get("", classeComp.getName()), classeComp.getName())
                                    .addStatement("this." + classeComp.getName() + " = " + classeComp.getName())
                                    .build();
                            if (!methods.contains(aMethod)) methods.add(aMethod);
                            MethodSpec bMethod = MethodSpec.methodBuilder("get" + upperFirst(classeComp.getName()))
                                    .addModifiers(Modifier.PUBLIC)
                                    .addStatement("return " + classeComp.getName())
                                    .returns(ClassName.get("", classeComp.getName()))
                                    .build();
                            if (!methods.contains(bMethod)) methods.add(bMethod);

                        }

                        for (Attribute a : classe.attributes) {

                            TypeName aClass = stringToType(a.getType());

                            FieldSpec aField = FieldSpec.builder(aClass, a.getName())
                                    .addModifiers(javax.lang.model.element.Modifier.valueOf(a.getProtection().toUpperCase()), a.isStatic() ? Modifier.STATIC : null)
                                    .build();
                            fields.add(aField);

                            MethodSpec aMethod = MethodSpec.methodBuilder("set" + upperFirst(a.getName()))
                                    .addModifiers(Modifier.PUBLIC, a.isStatic() ? Modifier.STATIC : null)
                                    .returns(TypeName.VOID)
                                    .addParameter(aClass, a.getName())
                                    .addStatement("this." + a.getName() + " = " + a.getName())
                                    .build();
                            if (!methods.contains(aMethod))
                                methods.add(aMethod);

                            MethodSpec bMethod = MethodSpec.methodBuilder("get" + upperFirst(a.getName()))
                                    .addModifiers(Modifier.PUBLIC, a.isStatic() ? Modifier.STATIC : null)
                                    .addStatement("return " + a.getName())
                                    .returns(aClass)
                                    .build();

                            if (!methods.contains(bMethod)) methods.add(bMethod);

                        }

                        for (Method m : classe.methods) {

                            ArrayList<ParameterSpec> parametriSpec = new ArrayList<>();
                            Set<Attribute> parametri = m.getParameters();

                            for (Attribute singleParam : parametri) {
                                TypeName attClass = stringToType(singleParam.getType());

                                ParameterSpec test = ParameterSpec.builder(attClass, singleParam.getName())
                                        // .addModifiers(Modifier.FINAL)
                                        .build();
                                parametriSpec.add(test);
                            }

                            TypeName aClass = stringToType(m.getReturnType());

                            MethodSpec aMethod = MethodSpec.methodBuilder(m.getName())

                                    .addModifiers(javax.lang.model.element.Modifier.valueOf(m.getProtection().toUpperCase()), m.isStatic() ? Modifier.STATIC : null)
                                    .returns(aClass)
                                    .addParameters(parametriSpec)
                                    .build();

                            methods.add(aMethod);
                        }
                        TypeSpec theClass = null;

                        TypeName father = null;
                        if (!inheritance.isEmpty())
                            father = ClassName.get("", ((UMLClassElementImage) ((UMLNode<UMLElement>) inheritance.get(0)).getChildren().get(0)).modelClass.getName());
                        try {

                            theClass = TypeSpec.classBuilder(classe.getName())
                                    .addModifiers(((UMLClassElementImage) e).modelClass.getFinal() ? new Modifier[] { javax.lang.model.element.Modifier.valueOf(classe.getProte().toString().toUpperCase()), Modifier.FINAL} : new Modifier[] { javax.lang.model.element.Modifier.valueOf(classe.getProte().toString().toUpperCase()) })
                                    .addModifiers(javax.lang.model.element.Modifier.valueOf(classe.getProte().toString().toUpperCase()), Modifier.FINAL)
                                    .superclass(father == null ? ClassName.OBJECT : father)
                                    .addMethods(methods)
                                    .addFields(fields)
                                    .build();

                            // Create object to choose and create new file

                        } catch (Exception exc) {

                            getFailureMessage("Il nome della classe potrebbe essere sbagliato?");

                        }

                        try {
                            JavaFile javaFile = JavaFile.builder(currentModel.getTitle(), theClass)
                                    .build();
                            Path javaPath = Paths.get(chooser.getSelectedFile().getPath());
                            javaFile.writeTo(javaPath);

                        } catch (Exception exc) {
                            exc.printStackTrace();
                            return getFailureMessage();

                        }

                    }
                    //Else is not a class
                }

            }

        }
    else if (chooser.showOpenDialog(null) == JFileChooser.CANCEL_OPTION)
        return getFailureMessage("Esportazione annullata");

    // Save jsonArray into a file
    // JsonFileManager jsonFileManager = new JsonFileManager();
    // jsonFileManager.save(jsonArray, Main.project.getName() + ".citro");

    return getSuccessMessage();

}

Body:
The problem were the lines like this one:

.addModifiers(Modifier.PUBLIC, a.isStatic() ? Modifier.STATIC : null)

I discovered it later, but addModifiers(null), instead of doing nothing, makes the whole thing explode


问:
Is it possible to predefine the avaible values of a functions's parameter?
I would like to set the avaible values of a functions parameter something like this:

```<code>let valueList = [
   'val1',
   'val2',
   'val3',
];

let getSomething = (parameter: valueList) => {
    // do something
}
</code>```

And i want to get error on console if parameter value other than what are in the valueList variable.

And it would be good, if IDE showup the possible values when I call the function as follow:

```<code>getSomething(| <- cursor ) // when cursor here, the IDE show the possible values from valueList
</code>```

答:
You can define an enum as mentioned in other answers or if you want your parameter to be a string, you can use a string literal type combined with union types:

```<code>type valueList = 'val1' | 'val2' | 'val3';

let getSomething = (parameter: valueList) => {
    // do something
}

getSomething("val1") // OK
getSomething("val1-wrong") // Error
</code>```

Body:
I would like to set the avaible values of a functions parameter something like this:

let valueList = [
   'val1',
   'val2',
   'val3',
];

let getSomething = (parameter: valueList) => {
    // do something
}

And i want to get error on console if parameter value other than what are in the valueList variable.

And it would be good, if IDE showup the possible values when I call the function as follow:

getSomething(| <- cursor ) // when cursor here, the IDE show the possible values from valueList

Body:
You can define an enum as mentioned in other answers or if you want your parameter to be a string, you can use a string literal type combined with union types:

type valueList = 'val1' | 'val2' | 'val3';

let getSomething = (parameter: valueList) => {
    // do something
}

getSomething("val1") // OK
getSomething("val1-wrong") // Error


问:
AsyncTask : return from interface callback in doInBackground
I would need some help to figure out how to return a doInBackground() value in AsyncTask which code is an interface. Here is an example

```<code>         private class MyAsyncTask extends AsyncTask<Void, Void, Boolean> {

                    public MyAsyncTask() {
                        super();
                        // do stuff
                    }

                    @Override
                    protected Boolean doInBackground(Void... void) {

                     checkIfContentAvailable(new interfaceMediaAvailableToDownload() {
                            @Override
                            public void onComplete(boolean resutl) {
                                    return result; //This must be doInBackground return value, not onSuccess which is Void
                            }

                            @Override
                            public void onInternetError() {
                                return false; //This must be doInBackground return value, not onSuccess which is Void
                            }
                        };
                    }

                @Override
                protected void onPostExecute(Boolean result) {
                     if (result){
                        //Do stuff
                     }else{
                        //Do stuff
                     }

                }
        }
</code>```

Obviously, this above code can't work because I don't know how to return onSuccess() value to doInBackground().

I hope this is clear enough....

EDIT

Okay my bad, I thought it would have been more readable to hide MyInterface usage, but I realize through your answers it is not. So I completed the code to add more details.

Any idea please?
Thank you in advance.

答:
Create the object of the Mynterface in the place where you execute the AsyncTask.

Create a object reference of the MyInterface inside the AsyncTask ans set your interface object.

Then call the onSuccess method like below

```<code>`
    private class MyAsyncTask extends AsyncTask<Void, Void, Boolean> {

     MyInteface myInterface;
     setMyInterface(MyInterface interface){this.myInterface = interface;}

                public MyAsyncTask() {
                    super();
                    // do stuff
                }

                @Override
                protected Boolean doInBackground(Void... void) {
                 this.myInterface.onSuccess(); // or call on failure if failure happened

                }

      @Override
            protected void onPostExecute(Boolean result) {
    //Do stuff with result

            }
    }
</code>```

`

Use it like ...

```<code>MyAsyncTask async = new MyAsyncTask();
async.setMyInterface(this);
async.execute();
</code>```

Implement the interface in the place where your are executing.

This how you can do it.

Body:
I would need some help to figure out how to return a doInBackground() value in AsyncTask which code is an interface. Here is an example

         private class MyAsyncTask extends AsyncTask<Void, Void, Boolean> {

                    public MyAsyncTask() {
                        super();
                        // do stuff
                    }

                    @Override
                    protected Boolean doInBackground(Void... void) {

                     checkIfContentAvailable(new interfaceMediaAvailableToDownload() {
                            @Override
                            public void onComplete(boolean resutl) {
                                    return result; //This must be doInBackground return value, not onSuccess which is Void
                            }

                            @Override
                            public void onInternetError() {
                                return false; //This must be doInBackground return value, not onSuccess which is Void
                            }
                        };
                    }

                @Override
                protected void onPostExecute(Boolean result) {
                     if (result){
                        //Do stuff
                     }else{
                        //Do stuff
                     }

                }
        }

Obviously, this above code can't work because I don't know how to return onSuccess() value to doInBackground().

I hope this is clear enough....

EDIT

Okay my bad, I thought it would have been more readable to hide MyInterface usage, but I realize through your answers it is not. So I completed the code to add more details.

Any idea please?
Thank you in advance.

Body:
Create the object of the Mynterface in the place where you execute the AsyncTask.

Create a object reference of the MyInterface inside the AsyncTask ans set your interface object.

Then call the onSuccess method like below

`
    private class MyAsyncTask extends AsyncTask<Void, Void, Boolean> {

     MyInteface myInterface;
     setMyInterface(MyInterface interface){this.myInterface = interface;}

                public MyAsyncTask() {
                    super();
                    // do stuff
                }

                @Override
                protected Boolean doInBackground(Void... void) {
                 this.myInterface.onSuccess(); // or call on failure if failure happened

                }

      @Override
            protected void onPostExecute(Boolean result) {
    //Do stuff with result

            }
    }

`

Use it like ...

MyAsyncTask async = new MyAsyncTask();
async.setMyInterface(this);
async.execute();

Implement the interface in the place where your are executing.

This how you can do it.


问:
Facebook webhook making multiple calls for the same message?
I made and echo bot on AWS with Python and serverless.

I keep getting the same request again and again.
I read the faq where it says u have to deliver a status code 200 else it will keep retrying the webhook.

I'm not sure How I do this.

I have noticed that the sequence number is always the same for the calls so I assume the reply I sent was not acknowledged.
my code is here

```<code>import os
import json
import requests
import random
from datetime import datetime
######################
# helper functions
######################
##recursively look/return for an item in dict given key
def find_item(obj, key):
    item = None
    if key in obj: return obj[key]
    for k, v in obj.items():
        if isinstance(v,dict):
            item = find_item(v, key)
            if item is not None:
                return item

##recursivley check for items in a dict given key
def keys_exist(obj, keys):
    for key in keys:
        if find_item(obj, key) is None:
            return(False)
    return(True)

##send txt via messenger to id
def send_message(send_id, msg_txt):
    print("Send message called")
    print (datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
    params  = {"statusCode": 200,"access_token": os.environment['accesstoken']}
    headers = {"statusCode": "200","Content-Type": "application/json"}
    data = json.dumps({"statusCode": "200","recipient": {"id": send_id},
                       "message": {"text": msg_txt}})

    r = requests.post("https://graph.facebook.com/v2.9/me/messages", params=params, headers=headers, data=data)
    print (r.text)

    if r.status_code != 200:
        print(r.status_code)
        print(r.text)

#-----------------------------------------------------------

def hello(event, context):
    #debug
    event=json.loads(json.dumps(event))
    print("event:" )
    print(event)
    # print("context")
    # print(context)

    #handle webhook challenge
    try:

        if keys_exist(event, ["queryStringParameters","hub.verify_token","hub.challenge"]):
            print("subscribe to webhook invoked")
            v_token   = str(find_item(event, 'hub.verify_token'))
            challenge = find_item(event, 'hub.challenge')
            if ("strongtoken" == v_token):
                response = {
                    "statusCode": 200,
                    "body": str(challenge)
                }
                print(challenge)
                return response

        #handle messaging events
        if keys_exist(event, ['body']):
            event_entry=json.loads(event['body'])
            if ((len(event_entry['entry'])>0) & (keys_exist(event_entry['entry'][0],['messaging'])) ):
                messaging_event = event_entry['entry'][0]['messaging'][0]
                if (keys_exist(messaging_event,['message'])):
                    msg_txt   = messaging_event['message']['text']
                    sender_id = messaging_event['sender']['id']
                    print(sender_id)
                    first_word = msg_txt.split(" ")[0]
                    send_message(sender_id, msg_txt)
                else:
                    print("Did not send message")
                    pass
            else:
                print("Did not send message")
                pass

        else:
            pass
    except:
        pass
</code>```

I have given the status code 200 in soo many places and I'm not sure y I still keep getting the same problem.

答:
Your webhook callback should always return a 200 OK HTTP response when invoked by Facebook. Failing to do so may cause your webhook to be unsubscribed by the Messenger Platform. (copied from messenger docs.)
You have to search problem from your returning response. It is not with the sending data.

```
response = requests.post(POST_MESSAGE_URL, headers={
            'Content-Type': 'application/json'
        }, params={
            'access_token': ACCESS_TOKEN
        }, data=json.dumps(DATA_JSON)
```

this code working fine for me

Body:
I made and echo bot on AWS with Python and serverless.

I keep getting the same request again and again.
I read the faq where it says u have to deliver a status code 200 else it will keep retrying the webhook.

I'm not sure How I do this.

I have noticed that the sequence number is always the same for the calls so I assume the reply I sent was not acknowledged.
my code is here

import os
import json
import requests
import random
from datetime import datetime
######################
# helper functions
######################
##recursively look/return for an item in dict given key
def find_item(obj, key):
    item = None
    if key in obj: return obj[key]
    for k, v in obj.items():
        if isinstance(v,dict):
            item = find_item(v, key)
            if item is not None:
                return item

##recursivley check for items in a dict given key
def keys_exist(obj, keys):
    for key in keys:
        if find_item(obj, key) is None:
            return(False)
    return(True)

##send txt via messenger to id
def send_message(send_id, msg_txt):
    print("Send message called")
    print (datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
    params  = {"statusCode": 200,"access_token": os.environment['accesstoken']}
    headers = {"statusCode": "200","Content-Type": "application/json"}
    data = json.dumps({"statusCode": "200","recipient": {"id": send_id},
                       "message": {"text": msg_txt}})

    r = requests.post("https://graph.facebook.com/v2.9/me/messages", params=params, headers=headers, data=data)
    print (r.text)

    if r.status_code != 200:
        print(r.status_code)
        print(r.text)

#-----------------------------------------------------------

def hello(event, context):
    #debug
    event=json.loads(json.dumps(event))
    print("event:" )
    print(event)
    # print("context")
    # print(context)

    #handle webhook challenge
    try:

        if keys_exist(event, ["queryStringParameters","hub.verify_token","hub.challenge"]):
            print("subscribe to webhook invoked")
            v_token   = str(find_item(event, 'hub.verify_token'))
            challenge = find_item(event, 'hub.challenge')
            if ("strongtoken" == v_token):
                response = {
                    "statusCode": 200,
                    "body": str(challenge)
                }
                print(challenge)
                return response

        #handle messaging events
        if keys_exist(event, ['body']):
            event_entry=json.loads(event['body'])
            if ((len(event_entry['entry'])>0) & (keys_exist(event_entry['entry'][0],['messaging'])) ):
                messaging_event = event_entry['entry'][0]['messaging'][0]
                if (keys_exist(messaging_event,['message'])):
                    msg_txt   = messaging_event['message']['text']
                    sender_id = messaging_event['sender']['id']
                    print(sender_id)
                    first_word = msg_txt.split(" ")[0]
                    send_message(sender_id, msg_txt)
                else:
                    print("Did not send message")
                    pass
            else:
                print("Did not send message")
                pass

        else:
            pass
    except:
        pass

I have given the status code 200 in soo many places and I'm not sure y I still keep getting the same problem.

Body:
Your webhook callback should always return a 200 OK HTTP response when invoked by Facebook. Failing to do so may cause your webhook to be unsubscribed by the Messenger Platform. (copied from messenger docs.)
You have to search problem from your returning response. It is not with the sending data.

response = requests.post(POST_MESSAGE_URL, headers={
            'Content-Type': 'application/json'
        }, params={
            'access_token': ACCESS_TOKEN
        }, data=json.dumps(DATA_JSON)

this code working fine for me


问:
textbox with numbers only but also pasting, copying, and selecting
I'm quite new in VB and got stuck on (i think) easy problem. I have a text box thats allows only numbers:

```<code>    Private Sub TextBox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress

    If Asc(e.KeyChar) <> 8 Then
        If Asc(e.KeyChar) < 49 Or Asc(e.KeyChar) > 57 Then
            e.Handled = True
        End If
    End If

End Sub
</code>```

from 1 to 9. But this box doesnt allows me to paste, copy, and select text...how can i change it? I know that KeyCode for Control is 17, and for 'V' is 86, but have no idea how to use it...
thanks for any help

答:
If you necessarily want a TextBox you could combine the KeyDown and KeyPress events in order to block anything that isn't numbers while manually allowing Copy, Paste, Cut, etc.

```<code>Imports System.Text.RegularExpressions

Private Sub TextBox2_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox2.KeyPress
    e.Handled = Char.IsNumber(e.KeyChar) = False AndAlso Char.IsControl(e.KeyChar) = False 'Verify if input is a number or a control character (such as Backspace).
End Sub

Private Sub TextBox2_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox2.KeyDown
    Dim TargetTextBox As TextBox = DirectCast(sender, TextBox)
    e.SuppressKeyPress = True 'Start by blocking all key presses.

    Select Case e.KeyData 'In order to not block some standard keyboard shortcuts.
        Case Keys.Control Or Keys.C 'Copy
            TargetTextBox.Copy()
        Case Keys.Control Or Keys.X 'Cut
            TargetTextBox.Cut()
        Case Keys.Control Or Keys.V 'Paste
            TargetTextBox.Paste()
            TargetTextBox.Text = Regex.Replace(TextBox2.Text, "[^\d]", "")
        Case Keys.Control Or Keys.A 'Select all.
            TargetTextBox.SelectAll()
        Case Else
            e.SuppressKeyPress = False 'Allow all other key presses to be passed on to the KeyPress event.
    End Select
End Sub
</code>```

EDIT: Pardon the unintentional similar Regex, Arun Kumar.

Body:
I'm quite new in VB and got stuck on (i think) easy problem. I have a text box thats allows only numbers:

    Private Sub TextBox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress

    If Asc(e.KeyChar) <> 8 Then
        If Asc(e.KeyChar) < 49 Or Asc(e.KeyChar) > 57 Then
            e.Handled = True
        End If
    End If

End Sub

from 1 to 9. But this box doesnt allows me to paste, copy, and select text...how can i change it? I know that KeyCode for Control is 17, and for 'V' is 86, but have no idea how to use it...
thanks for any help

Body:
If you necessarily want a TextBox you could combine the KeyDown and KeyPress events in order to block anything that isn't numbers while manually allowing Copy, Paste, Cut, etc.

Imports System.Text.RegularExpressions

Private Sub TextBox2_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox2.KeyPress
    e.Handled = Char.IsNumber(e.KeyChar) = False AndAlso Char.IsControl(e.KeyChar) = False 'Verify if input is a number or a control character (such as Backspace).
End Sub

Private Sub TextBox2_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox2.KeyDown
    Dim TargetTextBox As TextBox = DirectCast(sender, TextBox)
    e.SuppressKeyPress = True 'Start by blocking all key presses.

    Select Case e.KeyData 'In order to not block some standard keyboard shortcuts.
        Case Keys.Control Or Keys.C 'Copy
            TargetTextBox.Copy()
        Case Keys.Control Or Keys.X 'Cut
            TargetTextBox.Cut()
        Case Keys.Control Or Keys.V 'Paste
            TargetTextBox.Paste()
            TargetTextBox.Text = Regex.Replace(TextBox2.Text, "[^\d]", "")
        Case Keys.Control Or Keys.A 'Select all.
            TargetTextBox.SelectAll()
        Case Else
            e.SuppressKeyPress = False 'Allow all other key presses to be passed on to the KeyPress event.
    End Select
End Sub

EDIT: Pardon the unintentional similar Regex, Arun Kumar.


问:
AngularJS Dynamically Adding Control In Repeater to Form Causes Submit
I have a form which represents an object and an array of sub-objects contained in a repeater. I want to dynamically add sub-objects to the array. When I add a sub-object the form gets submitted unexpectedly.

See this example:

http://plnkr.co/edit/TUblgmb7N710nPL7s5tU?p=preview

My form looks like this:

```<code><form ng-submit="handleSubmit()" ng-controller="TestController">
  <div>Some Input: <input type="text"></div>

  <div ng-repeat="obj in model.children">
    <input type="text" ng-model="obj.text" />
  </div>

  <button ng-click="addChild()"> Add Child</button>

</form>
</code>```

The controller looks like this...

```<code>Controllers.controller('TestController', ["$scope", function($scope) {

  $scope.model = {
    name: "Some Text",
    children: []
  };

  $scope.handleSubmit = function() {
    alert("Form Submitted!");
  }

  $scope.addChild = function() {
    $scope.model.children.push({text:"Foo"});
  }

}]);
</code>```

Click the "Add Child" buttton. The UI is updated as expected but the form gets submitted.

I can work around this by putting the submit function in ng-click on the Save button instead of ng-submit on the form but this seems like unexpected behaviour. Can anyone explain?

答:
The default attribute type The HTML button tag <button>My Button</button> triggers the submit event as <input type = "submit"...> does.

Now, following the idea of @GruffBunny, I have added a pInputType parameter to your method to show what button was clicked:

```<code>$scope.addChild = function(pInputType) {
    $scope.model.children.push({text:"Foo", inputType : pInputType });
}
</code>```

Then in the HTML block, the attribute inputTypewas added within the loop as follow:

```<code><div ng-repeat="obj in model.children">
   <hr />
   <h3>{{obj.inputType}}</h3>
   <div>New Input: <input type="text" ng-model="obj.text" /></div>
</div>
</code>```

Finally, here are the buttons for testing the code:

```<code><!-- With Input Type -->
<h2>Input type Button</h2>
<input type="button" ng-click="addChild('Input type Button')" value="Btn Add Child" />
<hr />
<!-- With Normal Anchor -->
<h2>HTML Anchor</h2>
<a href="#" ng-click="addChild('HTML Anchor')">Add Child Link</a>
<hr />
<!-- Adding Bootstrap -->
<h2>HTML Bootstrap Anchor</h2>
<a href="#" ng-click="addChild('HTML Bootstrap Anchor')" class="btn btn-info"> Add Child Link</a>
<hr />
<!-- Button Tag -->
<h2>HTML Button Tag (Triggers SUbmit Events)</h2>
<button ng-click="addChild('Triggers Submit Events')">Add Child</button>
<hr />
</code>```

Here is the complete plunker: http://plnkr.co/edit/N4hSjG

For further information about this behavior, you can read this Stack Overflow question: <button> vs. <input type="button" />. Which to use?

I hope it could be useful this explanation for anyone.

Body:
I have a form which represents an object and an array of sub-objects contained in a repeater. I want to dynamically add sub-objects to the array. When I add a sub-object the form gets submitted unexpectedly.

See this example:

http://plnkr.co/edit/TUblgmb7N710nPL7s5tU?p=preview

My form looks like this:

<form ng-submit="handleSubmit()" ng-controller="TestController">

Some Input: <input type="text">

    <input type="text" ng-model="obj.text" />

  <button ng-click="addChild()"> Add Child</button>

</form>

The controller looks like this...

Controllers.controller('TestController', ["$scope", function($scope) {

  $scope.model = {
    name: "Some Text",
    children: []
  };

  $scope.handleSubmit = function() {
    alert("Form Submitted!");
  }

  $scope.addChild = function() {
    $scope.model.children.push({text:"Foo"});
  }

}]);

Click the "Add Child" buttton. The UI is updated as expected but the form gets submitted.

I can work around this by putting the submit function in ng-click on the Save button instead of ng-submit on the form but this seems like unexpected behaviour. Can anyone explain?

Body:
The default attribute type The HTML button tag <button>My Button</button> triggers the submit event as <input type = "submit"...> does.

Now, following the idea of @GruffBunny, I have added a pInputType parameter to your method to show what button was clicked:

$scope.addChild = function(pInputType) {
    $scope.model.children.push({text:"Foo", inputType : pInputType });
}

Then in the HTML block, the attribute inputTypewas added within the loop as follow:

<div ng-repeat="obj in model.children">
   <hr />
   <h3>{{obj.inputType}}</h3>
   <div>New Input: <input type="text" ng-model="obj.text" /></div>
</div>

Finally, here are the buttons for testing the code:

<!-- With Input Type -->
<h2>Input type Button</h2>
<input type="button" ng-click="addChild('Input type Button')" value="Btn Add Child" />
<hr />
<!-- With Normal Anchor -->
<h2>HTML Anchor</h2>
<a href="#" ng-click="addChild('HTML Anchor')">Add Child Link</a>
<hr />
<!-- Adding Bootstrap -->
<h2>HTML Bootstrap Anchor</h2>
<a href="#" ng-click="addChild('HTML Bootstrap Anchor')" class="btn btn-info"> Add Child Link</a>
<hr />
<!-- Button Tag -->
<h2>HTML Button Tag (Triggers SUbmit Events)</h2>
<button ng-click="addChild('Triggers Submit Events')">Add Child</button>
<hr />

Here is the complete plunker: http://plnkr.co/edit/N4hSjG

For further information about this behavior, you can read this Stack Overflow question: <button> vs. <input type="button" />. Which to use?

I hope it could be useful this explanation for anyone.


问:
SQL: Fill column from other table with different identifier/key and different number of data set
Assuming the dataTarget column is empty, how do I fill it with data from the dataSource like shown below?

Source

```<code>id      otherSubId  dataSource
------------------------------
4000    10          DataA
4000    20          DataB
4000    30          DataC
4000    40          DataD
6000    1000        DataAA
6000    2000        DataBB
6000    3000        DataCC
6000    4000        DataDD
</code>```

Target

```<code>id      subId   dataTarget
--------------------------
4000    100     DataA
4000    200     DataB
4000    300     DataC
6000    100     DataAA
6000    300     DataCC
6000    400     DataDD
6000    500
6000    200     DataBB
</code>```

Please note that -

DataD from dataSource is not used

dataTarget with an id value of 6000 and a subId value of 500 is left empty because no more data for the last set.

I am thinking creating a tempId column filled with sequential number needed (1, 2, 3, ...) for each unique id ordered by otherSubId on both tables and combine it with id to create something to connect between both tables, but I want to know if someone has a better approach without altering the table.

答:
For PostgreSQL, you can use ROW_NUMBER() to basically mimic the plan you have for a tempid, but all within one query:

```<code>SELECT *
FROM (SELECT id, subID, dataTarget,
      ROW_NUMBER() OVER (PARTITION BY id ORDER BY subID asc) RN
      FROM target
     ) T
JOIN (SELECT id, othersubID, dataSource,
      ROW_NUMBER() OVER (PARTITION BY id ORDER BY othersubID asc) RN
      FROM source
     ) S ON S.id = T.id
        AND S.RN = T.RN
</code>```

The update would be:

```<code>UPDATE T
SET T.dataTarget = S.dataSource
FROM (SELECT id, subID, dataTarget,
      ROW_NUMBER() OVER (PARTITION BY id ORDER BY subID asc) RN
      FROM target
     ) T
JOIN (SELECT id, othersubID, dataSource,
      ROW_NUMBER() OVER (PARTITION BY id ORDER BY othersubID asc) RN
      FROM source
     ) S ON S.id = T.id
        AND S.RN = T.RN
</code>```

I'm also curious how representative your example data is of the actual table.  If it really looks just like that, you can add or remove a 0 in your join predicate:

```<code>SELECT *
FROM Target T
JOIN Source S ON T.id = S.id
             AND (t.subId * 10 = s.othersubID OR
                  t.subId / 10 = s.othersubID)
</code>```

This should work in any RDBMS, assuming subID is not a string.  If it is, you have to concatenate or remove a 0 instead of doing math.

Body:
Assuming the dataTarget column is empty, how do I fill it with data from the dataSource like shown below?

Source

id      otherSubId  dataSource
------------------------------
4000    10          DataA
4000    20          DataB
4000    30          DataC
4000    40          DataD
6000    1000        DataAA
6000    2000        DataBB
6000    3000        DataCC
6000    4000        DataDD

Target

id      subId   dataTarget
--------------------------
4000    100     DataA
4000    200     DataB
4000    300     DataC
6000    100     DataAA
6000    300     DataCC
6000    400     DataDD
6000    500
6000    200     DataBB

Please note that -

DataD from dataSource is not used

dataTarget with an id value of 6000 and a subId value of 500 is left empty because no more data for the last set.

I am thinking creating a tempId column filled with sequential number needed (1, 2, 3, ...) for each unique id ordered by otherSubId on both tables and combine it with id to create something to connect between both tables, but I want to know if someone has a better approach without altering the table.

Body:
For PostgreSQL, you can use ROW_NUMBER() to basically mimic the plan you have for a tempid, but all within one query:

SELECT *
FROM (SELECT id, subID, dataTarget,
      ROW_NUMBER() OVER (PARTITION BY id ORDER BY subID asc) RN
      FROM target
     ) T
JOIN (SELECT id, othersubID, dataSource,
      ROW_NUMBER() OVER (PARTITION BY id ORDER BY othersubID asc) RN
      FROM source
     ) S ON S.id = T.id
        AND S.RN = T.RN

The update would be:

UPDATE T
SET T.dataTarget = S.dataSource
FROM (SELECT id, subID, dataTarget,
      ROW_NUMBER() OVER (PARTITION BY id ORDER BY subID asc) RN
      FROM target
     ) T
JOIN (SELECT id, othersubID, dataSource,
      ROW_NUMBER() OVER (PARTITION BY id ORDER BY othersubID asc) RN
      FROM source
     ) S ON S.id = T.id
        AND S.RN = T.RN

I'm also curious how representative your example data is of the actual table.  If it really looks just like that, you can add or remove a 0 in your join predicate:

SELECT *
FROM Target T
JOIN Source S ON T.id = S.id
             AND (t.subId * 10 = s.othersubID OR
                  t.subId / 10 = s.othersubID)

This should work in any RDBMS, assuming subID is not a string.  If it is, you have to concatenate or remove a 0 instead of doing math.


问:
Problems sending TCP socket from localhost to localhost with rammbock library of Robotframework
I'm using Robotframework and I need to send a JSON message to a program that listens on port 80. Since I'm sending this JSON from my computer to a program that is also installed on my computer I assume (with my little Networks knowledge) that the sending and the receiving IP would be 127.0.0.1.

In this particular piece of code I send a integer to a template that creates a JSON structure with this argument and sends it to localhost port 80, the socket needs to be TCP.

This is my code:

```<code>*** Test Cases ***
      Set Simulator CDC
      [Tags]    cdc
      [Template]    Set Simulator CDC Template
      #${cdc}
      3120

*** Keywords ***
      Set Simulator CDC Template
      [Arguments]    ${cdc}    ${status}=0    ${connection}=${SIMULATOR_CONNECTION}
      ${cdc}=    Convert to Integer    ${cdc}
      ${json_cdc}=    Create Dictionary    command=cdc    cdc=${cdc}
      ${json_cdc}=    json.Dumps    ${json_cdc}
      Log    ${json_cdc}
      New Protocol    simpleRequest
      Chars    *    ${json_cdc}
      End Protocol
      Start TCP server    127.0.0.1    12454    protocol=simpleRequest
      Start TCP client    protocol=simpleRequest
      Connect    127.0.0.1    80
      New Message    ${json_cdc}    simpleRequest
      u32    status
      Client Sends message
      ${msg}=    Server Receives Message
      Should be equal    ${msg.status.hex}    ${status}
</code>```

I'm not sure if you can create the protocol with variable type 'Chars' being a JSON but when converting the JSON to string the result is the same. Log file only gives error on keyword 'Server Receives Message' but I installed Wireshark and I don't see any packet goint to 127.0.0.1 and the program that should receive the JSON won't receive a thing.

Thanks in advance;

Manuel González García

答:
It seems you are starting your server on port 12454 instead of 80, you should change this line :

```<code>Start TCP server    127.0.0.1    12454    protocol=simpleRequest
</code>```

to

```<code>Start TCP server    127.0.0.1    80    protocol=simpleRequest
</code>```

It also seems that your code is missing indentation, which seems required by rammbock

Body:
I'm using Robotframework and I need to send a JSON message to a program that listens on port 80. Since I'm sending this JSON from my computer to a program that is also installed on my computer I assume (with my little Networks knowledge) that the sending and the receiving IP would be 127.0.0.1.

In this particular piece of code I send a integer to a template that creates a JSON structure with this argument and sends it to localhost port 80, the socket needs to be TCP.

This is my code:

*** Test Cases ***
      Set Simulator CDC
      [Tags]    cdc
      [Template]    Set Simulator CDC Template
      #${cdc}
      3120

*** Keywords ***
      Set Simulator CDC Template
      [Arguments]    ${cdc}    ${status}=0    ${connection}=${SIMULATOR_CONNECTION}
      ${cdc}=    Convert to Integer    ${cdc}
      ${json_cdc}=    Create Dictionary    command=cdc    cdc=${cdc}
      ${json_cdc}=    json.Dumps    ${json_cdc}
      Log    ${json_cdc}
      New Protocol    simpleRequest
      Chars    *    ${json_cdc}
      End Protocol
      Start TCP server    127.0.0.1    12454    protocol=simpleRequest
      Start TCP client    protocol=simpleRequest
      Connect    127.0.0.1    80
      New Message    ${json_cdc}    simpleRequest
      u32    status
      Client Sends message
      ${msg}=    Server Receives Message
      Should be equal    ${msg.status.hex}    ${status}

I'm not sure if you can create the protocol with variable type 'Chars' being a JSON but when converting the JSON to string the result is the same. Log file only gives error on keyword 'Server Receives Message' but I installed Wireshark and I don't see any packet goint to 127.0.0.1 and the program that should receive the JSON won't receive a thing.

Thanks in advance;

Manuel González García

Body:
It seems you are starting your server on port 12454 instead of 80, you should change this line :

Start TCP server    127.0.0.1    12454    protocol=simpleRequest

to

Start TCP server    127.0.0.1    80    protocol=simpleRequest

It also seems that your code is missing indentation, which seems required by rammbock


问:
Cascade remove relation without cascade remove target
I have a ManyToMany-relation between student and teacher in a Student_Teacher-table (Entityless).

```<code>Student:       Teacher(owning-side):   Student_Teacher
1= Tim         50= Mrs. Foo            1=   1   50
2= Ann         51= Mr. Bar             2=   1   51
                                       3=   2   50
                                       4=   2   51
</code>```

As you see above every Student is currently related to every Teacher.

Now I like to remove Ann and I like to use the database's cascading techique to remove entries from the Student_Teacher-table but I do neither like to remove other Students, nor Teacher, nor other relationship.

This is what I have in the Student-Entity:

```<code>@ManyToMany(mappedBy="students")
public Set<Teacher> getTeachers() {
    return teachers;
}
</code>```

This is what I have in the Teacher-Entity:

```<code>@ManyToMany
@JoinTable(name="Student_Teacher", joinColumns = {
    @JoinColumn(name="StudentID", referencedColumnName = "TeacherID", nullable = false)
}, inverseJoinColumns = {
    @JoinColumn(name="TeacherID", referencedColumnName = "StudentID", nullable = false)
})
public Set<Student> getStudents() {
    return students;
}
</code>```

Now I like to use the database's delete cascade functionality. I repeat: The database's delete cascade functionality targeting the Student_Teacher-table only!

The problem:

```<code>org.h2.jdbc.JdbcSQLException: Referentielle Integrität verletzt: "FK_43PMYXR2NU005M2VNEB99VX0X: PUBLIC.Student_Teacher FOREIGN KEY(StudentID) REFERENCES PUBLIC.Student(StudentID) (2)"
Referential integrity constraint violation: "FK_43PMYXR2NU005M2VNEB99VX0X: PUBLIC.Student_Teacher FOREIGN KEY(StudentID) REFERENCES PUBLIC.Student(StudentID) (2)"; SQL statement:
delete from "Student" where name='Ann'
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
    at org.h2.message.DbException.get(DbException.java:179)
    at org.h2.message.DbException.get(DbException.java:155)
    at org.h2.constraint.ConstraintReferential.checkRow(ConstraintReferential.java:425)
</code>```

What i can not use is the

```<code>@ManyToMany(cascade={CascadeType.REMOVE})
</code>```

Because of the documetation tells me:

(Optional) The operations that must be cascaded to the target of the association.

The "target" is the Teacher, so this cascade would remove the Teacher (what I do not like to remove).

Question:

How to configure the entitys to remove Ann and the relation only using the database's cascade functionality?

Proof of Concept:

I tried another feature, I have noticed the possibility to configure the foreign-key nativly like this:

```<code>@ManyToMany(cascade = { CascadeType.REMOVE })
@JoinTable(name="Student_Teacher", joinColumns = {
    @JoinColumn(name="StudentID", referencedColumnName = "TeacherID", nullable = false, foreignKey=@ForeignKey(foreignKeyDefinition="FOREIGN KEY (StudentID) REFERENCES Student ON DELETE NO ACTION"))
}, inverseJoinColumns = {
    @JoinColumn(name="TeacherID", referencedColumnName = "StudentID", nullable = false, foreignKey=@ForeignKey(foreignKeyDefinition="FOREIGN KEY (TeacherID) REFERENCES Teacher ON DELETE NO ACTION"))
})
public Set<Student> getStudents() {
    return students;
}
</code>```

The problem is: This works fine but to trigger the removal of the entries in Student_Teacher I have to specify @ManyToMany(cascade = { CascadeType.REMOVE }) on both sides. Hibernate do not parse the foreignKeyDefinition and only see the CascadeType.REMOVE and drops the target-entitys (and the referenced Student Tim) out of the cache, but they are still in the database!!! So I have to clear the hibernate-session immendentelly after drop to re-read the existence of the Teachers Mrs. Foo and Mr. Bar and the Student Tim.

答:
You may create a new entity TeacherStudent for the relationship, and then use CascadeType.REMOVE safely:

```<code>@Entity
public class Student {
    @OneToMany(mappedBy="student",cascade={CascadeType.REMOVE})
    public Set<TeacherStudent> teacherStudents;
}

@Entity
public class Teacher {
    @OneToMany(mappedBy="teacher",cascade={CascadeType.REMOVE})
    public Set<TeacherStudent> teacherStudents;
}

@Entity
public class TeacherStudent {
    @ManyToOne
    public Teacher teacher;

    @ManyToOne
    public Student student;
}
</code>```

You'll have to take care of the composite foreign key for TeacherStudent. You may take a look at https://stackoverflow.com/a/29116687/3670143 for that.

Another relevant thread about ON DELETE CASCADE is JPA + Hibernate: How to define a constraint having ON DELETE CASCADE

Body:
I have a ManyToMany-relation between student and teacher in a Student_Teacher-table (Entityless).

Student:       Teacher(owning-side):   Student_Teacher
1= Tim         50= Mrs. Foo            1=   1   50
2= Ann         51= Mr. Bar             2=   1   51
                                       3=   2   50
                                       4=   2   51

As you see above every Student is currently related to every Teacher.

Now I like to remove Ann and I like to use the database's cascading techique to remove entries from the Student_Teacher-table but I do neither like to remove other Students, nor Teacher, nor other relationship.

This is what I have in the Student-Entity:

@ManyToMany(mappedBy="students")
public Set<Teacher> getTeachers() {
    return teachers;
}

This is what I have in the Teacher-Entity:

@ManyToMany
@JoinTable(name="Student_Teacher", joinColumns = {
    @JoinColumn(name="StudentID", referencedColumnName = "TeacherID", nullable = false)
}, inverseJoinColumns = {
    @JoinColumn(name="TeacherID", referencedColumnName = "StudentID", nullable = false)
})
public Set<Student> getStudents() {
    return students;
}

Now I like to use the database's delete cascade functionality. I repeat: The database's delete cascade functionality targeting the Student_Teacher-table only!

The problem:

org.h2.jdbc.JdbcSQLException: Referentielle Integrität verletzt: "FK_43PMYXR2NU005M2VNEB99VX0X: PUBLIC.Student_Teacher FOREIGN KEY(StudentID) REFERENCES PUBLIC.Student(StudentID) (2)"
Referential integrity constraint violation: "FK_43PMYXR2NU005M2VNEB99VX0X: PUBLIC.Student_Teacher FOREIGN KEY(StudentID) REFERENCES PUBLIC.Student(StudentID) (2)"; SQL statement:
delete from "Student" where name='Ann'
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
    at org.h2.message.DbException.get(DbException.java:179)
    at org.h2.message.DbException.get(DbException.java:155)
    at org.h2.constraint.ConstraintReferential.checkRow(ConstraintReferential.java:425)

What i can not use is the

@ManyToMany(cascade={CascadeType.REMOVE})

Because of the documetation tells me:

(Optional) The operations that must be cascaded to the target of the association.

The "target" is the Teacher, so this cascade would remove the Teacher (what I do not like to remove).

Question:

How to configure the entitys to remove Ann and the relation only using the database's cascade functionality?

Proof of Concept:

I tried another feature, I have noticed the possibility to configure the foreign-key nativly like this:

@ManyToMany(cascade = { CascadeType.REMOVE })
@JoinTable(name="Student_Teacher", joinColumns = {
    @JoinColumn(name="StudentID", referencedColumnName = "TeacherID", nullable = false, foreignKey=@ForeignKey(foreignKeyDefinition="FOREIGN KEY (StudentID) REFERENCES Student ON DELETE NO ACTION"))
}, inverseJoinColumns = {
    @JoinColumn(name="TeacherID", referencedColumnName = "StudentID", nullable = false, foreignKey=@ForeignKey(foreignKeyDefinition="FOREIGN KEY (TeacherID) REFERENCES Teacher ON DELETE NO ACTION"))
})
public Set<Student> getStudents() {
    return students;
}

The problem is: This works fine but to trigger the removal of the entries in Student_Teacher I have to specify @ManyToMany(cascade = { CascadeType.REMOVE }) on both sides. Hibernate do not parse the foreignKeyDefinition and only see the CascadeType.REMOVE and drops the target-entitys (and the referenced Student Tim) out of the cache, but they are still in the database!!! So I have to clear the hibernate-session immendentelly after drop to re-read the existence of the Teachers Mrs. Foo and Mr. Bar and the Student Tim.

Body:
You may create a new entity TeacherStudent for the relationship, and then use CascadeType.REMOVE safely:

@Entity
public class Student {
    @OneToMany(mappedBy="student",cascade={CascadeType.REMOVE})
    public Set<TeacherStudent> teacherStudents;
}

@Entity
public class Teacher {
    @OneToMany(mappedBy="teacher",cascade={CascadeType.REMOVE})
    public Set<TeacherStudent> teacherStudents;
}

@Entity
public class TeacherStudent {
    @ManyToOne
    public Teacher teacher;

    @ManyToOne
    public Student student;
}

You'll have to take care of the composite foreign key for TeacherStudent. You may take a look at https://stackoverflow.com/a/29116687/3670143 for that.

Another relevant thread about ON DELETE CASCADE is JPA + Hibernate: How to define a constraint having ON DELETE CASCADE


问:
do I need multiple tables or single?
I developing a tool which may got more than a million data to fill in.

current i have designed single table with 36 coloumns. my question is do I need to divide these into multiple tables or single??

If single what is the advantage and disadvantage

if multiple then what is the advantage and disadvantage

and what will be the engine to use for speed...

my concern is a large database which will have atleast 50000 queries perday..

any help??

答:
If you want to store a million rows of the same kind, go for it. Any decent database will cope even with much bigger tables.

Design your database to best fit the data (as seen from your application), get it up, and optimize later. You will probably find that performance is not a problem.

ContentLicense: CC BY-SA 2.5

Title: do I need multiple tables or single?


问:
How to get active browser info along with active session ID using java\command line
I've to get all active browsers that are opened in the local machine along with corresponding session ids.

I've made little research and i do find the below link.

It's giving the active browser name which is not enough though

I know there is some plugin's available to get the sessions but i need to do it programmatically.

Thanks in advance!!

答:
Short answer: it's impossible.

Long answer: Nothing distinguish browser from any other program. In fact many programs have browser functionality embedded in it.

If you define browser as one of known program such as "Firefox", "Chrome", "IE" etc. than you can do something to achieve some result.

First of all: forget about Java, you need to work with Win-API and Java is not best solution to do it.

You can enumerate process and find browsers by executable name.

Then you can check each browser documentation to find if there any integration API. Each browser will have its own API (or do not have).

Then using this API you can extract what is available.

So it will be hard if even possible to get what you want.


问:
How can I get a single marker to update it's position as the user moves in GMap.net
```<code>string lat = "40.682640,40.682671,40.682701,40.682732,40.682763,40.682794";
string lng = "-73.868470,-73.868359,-73.868247,-73.868136,-73.868025,-73.867913";
int index = 0;
private void Form1_Load(object sender, EventArgs e)
{
    Timer MyTimer = new Timer();
    MyTimer.Interval = (2000);
    MyTimer.Tick += new EventHandler(MyTimer_Tick);
    MyTimer.Start();
}
private void MyTimer_Tick(object sender, EventArgs e)
{

    string[] Latitude = lat.Split(',');
    string[] Longitude = lng.Split(',');

    gmap.MapProvider = GMap.NET.MapProviders.BingMapProvider.Instance;
    GMap.NET.GMaps.Instance.Mode = GMap.NET.AccessMode.ServerOnly;
    GMapProvider.WebProxy = null;
    gmap.SetPositionByKeywords("Atlantic Ave,USA");
    gmap.Position = new GMap.NET.PointLatLng(40.683377, -73.865798);
    gmap.ShowCenter = false;
    GMapOverlay markers = new GMapOverlay("markers");
    GMapMarker marker = new GMarkerGoogle(new PointLatLng(float.Parse(Latitude[index]), float.Parse(Longitude[index])), GMarkerGoogleType.blue);

    gmap.Overlays.Add(markers);
    markers.Markers.Add(marker);
    index++;

    GMapMarker marker1 = new GMarkerGoogle(new PointLatLng(40.684175, -73.862904), GMarkerGoogleType.green);

    markers.Markers.Add(marker1);
}
</code>```

I need to get a single marker update its position (blue marker) as the user moves while the other marker remains stationary. I've tried  markers.Markers.remove(marker); but all markers are being removed.

答:
According to the source code, something like the following should update the position:

```<code>marker.Position = new PointLatLng(lat, lng);
</code>```

GMarkerGoogle inherits from GMapMarker which has a public PointLatLng Position. The setter of Position is like so:

```<code>set
{
    if(position != value)
    {
        position = value;
        if(IsVisible)
        {
            if(Overlay != null && Overlay.Control != null)
            {
                Overlay.Control.UpdateMarkerLocalPosition(this);
            }
        }
    }
}
</code>```

Notice the Overlay.Control.UpdateMarkerLocalPosition(this);

Body:
string lat = "40.682640,40.682671,40.682701,40.682732,40.682763,40.682794";
string lng = "-73.868470,-73.868359,-73.868247,-73.868136,-73.868025,-73.867913";
int index = 0;
private void Form1_Load(object sender, EventArgs e)
{
    Timer MyTimer = new Timer();
    MyTimer.Interval = (2000);
    MyTimer.Tick += new EventHandler(MyTimer_Tick);
    MyTimer.Start();
}
private void MyTimer_Tick(object sender, EventArgs e)
{

    string[] Latitude = lat.Split(',');
    string[] Longitude = lng.Split(',');

    gmap.MapProvider = GMap.NET.MapProviders.BingMapProvider.Instance;
    GMap.NET.GMaps.Instance.Mode = GMap.NET.AccessMode.ServerOnly;
    GMapProvider.WebProxy = null;
    gmap.SetPositionByKeywords("Atlantic Ave,USA");
    gmap.Position = new GMap.NET.PointLatLng(40.683377, -73.865798);
    gmap.ShowCenter = false;
    GMapOverlay markers = new GMapOverlay("markers");
    GMapMarker marker = new GMarkerGoogle(new PointLatLng(float.Parse(Latitude[index]), float.Parse(Longitude[index])), GMarkerGoogleType.blue);

    gmap.Overlays.Add(markers);
    markers.Markers.Add(marker);
    index++;

    GMapMarker marker1 = new GMarkerGoogle(new PointLatLng(40.684175, -73.862904), GMarkerGoogleType.green);

    markers.Markers.Add(marker1);
}

I need to get a single marker update its position (blue marker) as the user moves while the other marker remains stationary. I've tried  markers.Markers.remove(marker); but all markers are being removed.

Body:
According to the source code, something like the following should update the position:

marker.Position = new PointLatLng(lat, lng);

GMarkerGoogle inherits from GMapMarker which has a public PointLatLng Position. The setter of Position is like so:

set
{
    if(position != value)
    {
        position = value;
        if(IsVisible)
        {
            if(Overlay != null && Overlay.Control != null)
            {
                Overlay.Control.UpdateMarkerLocalPosition(this);
            }
        }
    }
}

Notice the Overlay.Control.UpdateMarkerLocalPosition(this);


问:
Can't show result as select option Codeigniter 3
My Model name mymodel.php

```<code>.....
function all($table,$order)
        {
            $this->db->select('*');
            $this->db->from($table);
            $this->db->order_by($order);
            $query = $this->db->get();
            if ($query->num_rows() == 0) {
                return FALSE;
            } else {
                return $query->result();
            }
        } .....
</code>```

My controller name donate.php

```<code>.....
    function index()
    {
      $data = array(
                        'rekening' => $this->mymodel->all('rekening', 'id_rekening ASC'),
                        );
                    $this->load->view('client/donate/index', $data);
                } .....
</code>```

And this My View in path view/client/donate/index

```<code><?php foreach ($rekening as $rek): ?>
                <option value="<?php echo $rek->id_rekening; ?>" <?php echo set_select('ke_rekening', $rek->id_rekening); ?>><?php echo $rek->bank .' - '. $rek->atas_nama_rekening; ?></option>
              <?php endforeach ?>
</code>```

But why cant show in select option? I use codeigniter 3,
Show image

答:
controller donate.php

```<code>function index()
{
  $data = array('rekening' => $this->mymodel->all('rekening', 'id_rekening'));
  $this->load->view('client/donate/index', $data);
}
</code>```

Model donate.php

```<code>function all($table,$order)
{
   $this->db->select('*');
   $this->db->from($table);
   $this->db->order_by($order, 'asc');
   $query = $this->db->get();
   if ($query->num_rows() == 0) {
      return FALSE;
   } else {
      return $query->result();
   }
}
</code>```

Body:
My Model name mymodel.php

.....
function all($table,$order)
        {
            $this->db->select('*');
            $this->db->from($table);
            $this->db->order_by($order);
            $query = $this->db->get();
            if ($query->num_rows() == 0) {
                return FALSE;
            } else {
                return $query->result();
            }
        } .....

My controller name donate.php

.....
    function index()
    {
      $data = array(
                        'rekening' => $this->mymodel->all('rekening', 'id_rekening ASC'),
                        );
                    $this->load->view('client/donate/index', $data);
                } .....

And this My View in path view/client/donate/index

<?php foreach ($rekening as $rek): ?>
                <option value="<?php echo $rek->id_rekening; ?>" <?php echo set_select('ke_rekening', $rek->id_rekening); ?>><?php echo $rek->bank .' - '. $rek->atas_nama_rekening; ?></option>
              <?php endforeach ?>

But why cant show in select option? I use codeigniter 3,
Show image

Body:
controller donate.php

function index()
{
  $data = array('rekening' => $this->mymodel->all('rekening', 'id_rekening'));
  $this->load->view('client/donate/index', $data);
}

Model donate.php

function all($table,$order)
{
   $this->db->select('*');
   $this->db->from($table);
   $this->db->order_by($order, 'asc');
   $query = $this->db->get();
   if ($query->num_rows() == 0) {
      return FALSE;
   } else {
      return $query->result();
   }
}


问:
create fixed size List of non-repeating permutations from list of elements
I have a list of objects M := [A, B, C, ... Z] and I want to create a new list N containing non-repeating fixed size "f" permutations of these objects.

So N would be (for f = 2) [[A, B], [A, C], ...] but should not contain repetitions like [A, A] and if [A, B] is set [B, A] should be ignored.

I have found things like Guavas "PowerSet" but this wont help me as it can not be "cropped" to a fixed size.

I hope i have stated my problem correctly.

f should always be 2

Based on http://algorithms.tutorialhorizon.com/print-all-combinations-of-subset-of-size-k-from-given-array/ i've done the following:

```<code>private Set<List<Object>> combineObjects(List<Object> M) {
    boolean[] used = new boolean[M.size()];
    return generateObjectCombinations(M, 0, 0, used);
}

private Set<List<Object>> generateObjectCombinations(
    List<Object> M,
    int start,
    int curLen,
    boolean[] used
) {
    Set<List<Object>> returnSet = new HashSet<>();
    if (curLen == 2) {
        List<Object> data = newArrayList();
        for (int i = 0; i < M.size(); i++) {
            if (used[i]) {
                data.add(M.get(i));
            }
        }
        returnSet.add(data);
        return returnSet;
    }
    if (start == M.size()) {
        return Collections.emptySet();
    }
    used[start] = true;
    returnSet.addAll(generateObjectCombinations(M, start + 1, curLen + 1, used));
    used[start] = false;
    returnSet.addAll(generateObjectCombinations(M, start + 1, curLen, used));
    return returnSet;
}
</code>```

It is working but I wonder if there is a "cleaner" solution. I want to eliminate the bool-array.

And no, it's not my homework. Maybe i am just to tired and should take vacation.

EDIT
Based on @azro's answer i restructured the code like this:

```<code>List<List<Object>> combinations = new ArrayList<>();
List<Object> M = new ArrayList<>();

for (int i = 0; i < M.size(); i++) {
    Object outerM = M.get(i);

    for (int j = i; j < M.size(); j++) {
        Object innerM = M.get(j);
        if (innerM.equals(outerM)) {
            continue;
        }
        combinations.add(Lists.newArrayList(outerM, innerM));
    }
}
</code>```

or even better

```<code>List<List<Object>> combinations = new ArrayList<>();
List<Object> M = new ArrayList<>();

for (int i = 0; i < M.size(); i++) {
    Object outerM = M.get(i);

    for (int j = (i + 1); j < M.size(); j++) {
        Object innerM = M.get(j);
        combinations.add(Lists.newArrayList(outerM, innerM));
    }
}
</code>```

I should really take a loooong vacation. Thanks @azro!!

答:
As you didn't wrote "f should always be 2" as the beginning I wrote a solution which works for f>=1, so here is the method and how to use it :

```<code>public static void main(String[] args) {
        List<String> letter = Arrays.asList("A", "B", "C", "D", "E");
        List<String> res = new ArrayList<>();
        res.addAll(letter);
        int size = 2;

        for (int i = 1; i < size ; i++) {
            res = addLetter(res, letter);   //add a letter to all
        }

        res.forEach(p -> System.out.println(p));
}

public static List<String> addLetter(List<String> already, List<String> letters) {
    List<String> res = new ArrayList<>();

    for (String al : already) {
        for (String let : letters) {
            if (!al.contains(let)) {
                res.add(al + let);
            }
        }
    }
    return res;
}
</code>```

If "f should always be 2" you need only :

```<code>public static void main(String[] args) {
    List<String> letters = Arrays.asList("A", "B", "C", "D", "E");
    List<String> res = new ArrayList<>();

    for (String al : letters) {
        for (String let : letters) {
            if (!al.contains(let)) {
                res.add(al + let);
            }
        }
    }
    res.forEach(p -> System.out.println(p));
}
</code>```

Body:
I have a list of objects M := [A, B, C, ... Z] and I want to create a new list N containing non-repeating fixed size "f" permutations of these objects.

So N would be (for f = 2) [[A, B], [A, C], ...] but should not contain repetitions like [A, A] and if [A, B] is set [B, A] should be ignored.

I have found things like Guavas "PowerSet" but this wont help me as it can not be "cropped" to a fixed size.

I hope i have stated my problem correctly.

f should always be 2

Based on http://algorithms.tutorialhorizon.com/print-all-combinations-of-subset-of-size-k-from-given-array/ i've done the following:

private Set<List<Object>> combineObjects(List<Object> M) {
    boolean[] used = new boolean[M.size()];
    return generateObjectCombinations(M, 0, 0, used);
}

private Set<List<Object>> generateObjectCombinations(
    List<Object> M,
    int start,
    int curLen,
    boolean[] used
) {
    Set<List<Object>> returnSet = new HashSet<>();
    if (curLen == 2) {
        List<Object> data = newArrayList();
        for (int i = 0; i < M.size(); i++) {
            if (used[i]) {
                data.add(M.get(i));
            }
        }
        returnSet.add(data);
        return returnSet;
    }
    if (start == M.size()) {
        return Collections.emptySet();
    }
    used[start] = true;
    returnSet.addAll(generateObjectCombinations(M, start + 1, curLen + 1, used));
    used[start] = false;
    returnSet.addAll(generateObjectCombinations(M, start + 1, curLen, used));
    return returnSet;
}

It is working but I wonder if there is a "cleaner" solution. I want to eliminate the bool-array.

And no, it's not my homework. Maybe i am just to tired and should take vacation.

EDIT
Based on @azro's answer i restructured the code like this:

List<List<Object>> combinations = new ArrayList<>();
List<Object> M = new ArrayList<>();

for (int i = 0; i < M.size(); i++) {
    Object outerM = M.get(i);

    for (int j = i; j < M.size(); j++) {
        Object innerM = M.get(j);
        if (innerM.equals(outerM)) {
            continue;
        }
        combinations.add(Lists.newArrayList(outerM, innerM));
    }
}

or even better

List<List<Object>> combinations = new ArrayList<>();
List<Object> M = new ArrayList<>();

for (int i = 0; i < M.size(); i++) {
    Object outerM = M.get(i);

    for (int j = (i + 1); j < M.size(); j++) {
        Object innerM = M.get(j);
        combinations.add(Lists.newArrayList(outerM, innerM));
    }
}

I should really take a loooong vacation. Thanks @azro!!

Body:
As you didn't wrote "f should always be 2" as the beginning I wrote a solution which works for f>=1, so here is the method and how to use it :

public static void main(String[] args) {
        List<String> letter = Arrays.asList("A", "B", "C", "D", "E");
        List<String> res = new ArrayList<>();
        res.addAll(letter);
        int size = 2;

        for (int i = 1; i < size ; i++) {
            res = addLetter(res, letter);   //add a letter to all
        }

        res.forEach(p -> System.out.println(p));
}

public static List<String> addLetter(List<String> already, List<String> letters) {
    List<String> res = new ArrayList<>();

    for (String al : already) {
        for (String let : letters) {
            if (!al.contains(let)) {
                res.add(al + let);
            }
        }
    }
    return res;
}

If "f should always be 2" you need only :

public static void main(String[] args) {
    List<String> letters = Arrays.asList("A", "B", "C", "D", "E");
    List<String> res = new ArrayList<>();

    for (String al : letters) {
        for (String let : letters) {
            if (!al.contains(let)) {
                res.add(al + let);
            }
        }
    }
    res.forEach(p -> System.out.println(p));
}