text:
Q: Exception loading simple GWT view I have a simple entrypoint class that just loads a Panel
    public class TestUI implements EntryPoint
    {
        PanelA panelA = new PanelA();

        public void onModuleLoad()
        {
            final RootPanel rootPanel = RootPanel.get();

            rootPanel.add( panelA );
        }
    }

Here is PanelB
        public class PanelB extends HTMLPanel
    {
        public PanelB()
        {
            super("Panel B");
            final PanelA panelA = new PanelA();
            Button btnNewButton = new Button("Go to panel A");
            btnNewButton.addClickHandler(new ClickHandler() {
                public void onClick(ClickEvent event) {
                    final RootPanel rootPanel = RootPanel.get();
                    rootPanel.clear();
                    rootPanel.add( panelA );
                }
            });
            add(btnNewButton);
        }

    }

and here is panel A
        public class PanelA extends HTMLPanel
    {
        public PanelA( )
        {
            super("Panel A");
            final PanelB panelB = new PanelB();
            Button btnNewButton = new Button("Go to panel B");
            btnNewButton.addClickHandler(new ClickHandler() {
                public void onClick(ClickEvent event) {
                    final RootPanel rootPanel = RootPanel.get();
                    rootPanel.clear();
                    rootPanel.add( panelB );
                }
            });
            add(btnNewButton);
        }
    }

However when I try to load the page containing this entry point it fails with the exception trace below.
If I replace the reference to Panel A in the entrypoint with a plain HTML panel then it loads fine.  What is wrong with my simple panels?
I'm basically trying to create a GUI where I can click back and forth between pages and I figured this would be the first step towards that goal.
Exception in thread "Code server for stockwatcher from Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/20100101 com.google.gwt.dev.shell.BrowserChannel$RemoteDeathError: Remote connection lost
    at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:536)
    at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:363)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.net.SocketException: Software caused connection abort: socket write error
    at java.net.SocketOutputStream.socketWrite0(Native Method)
    at java.net.SocketOutputStream.socketWrite(Unknown Source)
    at java.net.SocketOutputStream.write(Unknown Source)
    at java.io.BufferedOutputStream.flushBuffer(Unknown Source)
    at java.io.BufferedOutputStream.flush(Unknown Source)
    at java.io.DataOutputStream.flush(Unknown Source)
    at com.google.gwt.dev.shell.BrowserChannel$ReturnMessage.send(BrowserChannel.java:1310)
    at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:533)
    ... 2 more

A: You are causing a mutual recursion or cyclic dependency call... Here is the detailed analysis...
In the TestUI  you are creating an instance of PanelA. What happen when you create an instance of a class? Its constructor gets called. In this case PanelA's constructor gets called. In there you are creating an instance of PanelB and hence PanelB's constructor gets called. Now again in PanelB you are creating an instance of PanelA and hence its constructor gets called and the process repeats infinitely. A better programming technique should avoid these kind of cyclic dependencies. Avoid this and it will solve your problem.

A: With every Panel A you are creating, you create a new Panel B, which is itself creating a new Panel A, which is creating a new Panel B, which is infinitely continuing. Maybe that's the problem.
I think you should call the constructor of panel B/panel A only in the onClick-Event.


text:
Q: How to Drag and Drop a text file in new tab using swing I want Drag and Drop a file that particular file must opened in new/separate tab.I wrote the code for DragAndDrop.But It has worked when I taken Newfile then I Drag and Drop the text File from the Computer.It has copied or override the contents of a file. But,when I Drag and drop a file,It should open in a separate tab.How can I do this.Please give me suggestions.Thank you.I have post my original application.It has two classes.
Main class:
public class OpenDemo extends javax.swing.JFrame implements ChangeListener{
  private ArrayList<OInternalFrame> frames = new ArrayList<OInternalFrame>();
  private OInternalFrame currentFrame;
  int i=0;
  JTabbedPane tabbedPane2;
  public OpenDemo() {
    initComponents();
}
@SuppressWarnings("unchecked")
private void initComponents() {
    tabbedPane2=new JTabbedPane();
    this.add(tabbedPane2);
    enableDragAndDrop();
    tp = new javax.swing.JTabbedPane();
    jMenuBar1 = new javax.swing.JMenuBar();
    jMenu1 = new javax.swing.JMenu();
    open = new javax.swing.JMenuItem();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jMenu1.setText("File");
    open.setText("Open");
    open.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            openActionPerformed(evt);
        }
    });
    jMenu1.add(open);
    jMenuBar1.add(jMenu1);
    setJMenuBar(jMenuBar1);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(tp, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(tp, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE));
    pack();
}

private void openActionPerformed(java.awt.event.ActionEvent evt) {
    FileDialog fd = new FileDialog(OpenDemo.this, "Select File", FileDialog.LOAD);
    fd.setVisible(true);
    String sts;
    if (fd.getFile() != null) {
        sts = fd.getDirectory() + fd.getFile();
        System.out.println(sts);
        BufferedReader br = null;
        StringBuffer str = new StringBuffer("");
        try {
            br = new BufferedReader(new FileReader(sts));
            String line;
            try {
                while ((line = br.readLine()) != null) {
                    str.append(line + "\n");
                }
            } catch (IOException ex) {
                Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex);
              }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex);
          }
        String t = str.toString();
        OInternalFrame internalFrame = new OInternalFrame("",true,true);
        i++;
        internalFrame.setName("Doc "+i);
        try {
            internalFrame.setSelected(true);
        } catch (PropertyVetoException ex) {
            Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex);
          }
        internalFrame.addInternalFrameListener(new InternalFrameAdapter() {
            @Override
            public void internalFrameClosing(InternalFrameEvent e) {
                i--;
                frames.remove(currentFrame);
                tp.remove(currentFrame);
            }
        });
        tp.add(internalFrame);
        tp.setSelectedIndex(i-1);
        tp.addChangeListener(this);
        frames.add(internalFrame);
        currentFrame=internalFrame;

        currentFrame.setText(t);
        currentFrame.setVisible(true);
    }
}
@Override
public void stateChanged(ChangeEvent ce) {
    JTabbedPane sourceTabbedPane = (JTabbedPane) ce.getSource();
    int index = sourceTabbedPane.getSelectedIndex();
    try {
        currentFrame =frames.get(index);
    }
    catch(IndexOutOfBoundsException e1){
    }
}
public static void main(String args[]) {
try {
    for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
        if ("Nimbus".equals(info.getName())) {
            javax.swing.UIManager.setLookAndFeel(info.getClassName());
            break;
        }
    }
} catch (ClassNotFoundException ex) {
    java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
    java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
    java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
    java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
        new OpenDemo().setVisible(true);
    }
  });
  }
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem open;
private javax.swing.JTabbedPane tp;
private void enableDragAndDrop() {
    OInternalFrame iFrame=new OInternalFrame("",true,true);
    DropTarget target=new DropTarget(currentFrame.textArea,new DropTargetListener(){
    public void dragEnter(DropTargetDragEvent e) {
    }
    public void dragExit(DropTargetEvent e) {
    }
    public void dragOver(DropTargetDragEvent e) {
    }
    public void dropActionChanged(DropTargetDragEvent e) {
    }
    public void drop(DropTargetDropEvent e) {
        try {
            e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
            java.util.List list=(java.util.List)e.getTransferable().getTransferData(DataFlavor.javaFileListFlavor);
            File file=(File)list.get(0);
            //JTextArea newTabTextArea=new JTextArea();
            //DropTarget target=new DropTarget(newTabTextArea,this);
            DropTarget target=new DropTarget(currentFrame.textArea,this);
            //newTabTextArea.read(new FileReader(file),null);
            currentFrame.textArea.read(new FileReader(file),null);
            //newTabTextArea.setCaretPosition(0);
            currentFrame.textArea.setCaretPosition(0);
            //tabbedPane2.add(add(newTabTextArea));
            tp.add(currentFrame.textArea);
            int tabIndex=tp.indexOfComponent(currentFrame.textArea);
            tp.setSelectedIndex(tabIndex);
            tp.setTitleAt(tabIndex,file.getName());
            add(tp);
        }
        catch(Exception ex){}
    }
 });
}
}

OInternalFrame :
public class OInternalFrame extends JInternalFrame
{
public JTextArea textArea;
private JScrollPane scrollPane;
JTabbedPane tabbedPane2;
public OInternalFrame(String title,boolean resizable,boolean closable)
{
    super(title,resizable,closable);
    initComponents();
}
private void initComponents() {
    textArea = new JTextArea();
    tabbedPane2=new JTabbedPane();
    scrollPane = new JScrollPane();
    textArea.setFont(new java.awt.Font("Miriam Fixed", 0, 13));
    add(scrollPane);
    scrollPane.getViewport().add(textArea);
    setVisible(true);
    scrollPane.setVisible(true);
}
public void setText(String t) {
    textArea.setText(t);
    textArea.setCaretPosition(0);
    textArea.setVisible(true);
    textArea.repaint();
}
}

A: Use below code to open file in new tab. I have added code in Method:drop(DropTargetDropEvent e) and constructor. please use according to your need , change jframe hight and width .Reply if need any help.
import javax.swing.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.dnd.*;
import java.io.File;
import java.io.FileReader;

public class DragAndDropFile extends javax.swing.JFrame {
JScrollPane scrollPane;
JTextArea textArea;
private JTabbedPane tabbedPane2;

public DragAndDropFile() {

    //initComponents();
    textArea=new JTextArea();
    scrollPane=new JScrollPane(textArea);
    tabbedPane2=new JTabbedPane();
    this.add(tabbedPane2);
    enableDragAndDrop();

}

private void newFileActionPerformed(java.awt.event.ActionEvent evt) {

    //tabbedPane.add(scrollPane);
}

private void enableDragAndDrop() {

        DropTarget target=new DropTarget(this,new DropTargetListener(){
        public void dragEnter(DropTargetDragEvent e) {
        }
        public void dragExit(DropTargetEvent e) {
        }
        public void dragOver(DropTargetDragEvent e) {
        }
        public void dropActionChanged(DropTargetDragEvent e) {
        }
        public void drop(DropTargetDropEvent e) {
            try {
                e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
                java.util.List list=(java.util.List) e.getTransferable().getTransferData(DataFlavor.javaFileListFlavor);
                File file=(File)list.get(0);

                JTextArea newTabTextArea=new JTextArea();
                DropTarget target=new DropTarget(newTabTextArea,this);
                newTabTextArea.read(new FileReader(file),null);
                newTabTextArea.setCaretPosition(0);
                tabbedPane2.add(newTabTextArea);
                int tabIndex=tabbedPane2.indexOfComponent(newTabTextArea);
                tabbedPane2.setSelectedIndex(tabIndex);
                tabbedPane2.setTitleAt(tabIndex,file.getName());

            }
            catch(Exception ex){}
        }
    });
}

public static void main(String args[]) {
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info :  javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(DragAndDropFile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(DragAndDropFile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(DragAndDropFile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(DragAndDropFile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }

    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new DragAndDropFile().setVisible(true);
        }
    });
}
private javax.swing.JMenu file;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem newFile;
private javax.swing.JTabbedPane tabbedPane;

}

A: Answer to your integration issue.

*

*You have to create new text area each time you drap a file because you want them in separate tab so change your drop method drop  in OInternalFrame with below
public void drop(DropTargetDropEvent e) {
try {
    e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
    java.util.List list=(java.util.List)e.getTransferable().getTransferData(DataFlavor.javaFileListFlavor);
    File file=(File)list.get(0);
    JTextArea newTabTextArea=new JTextArea();
    DropTarget target=new DropTarget(newTabTextArea,this);
    newTabTextArea.read(new FileReader(file),null);
    newTabTextArea.setCaretPosition(0);
    tabbedPane2.add(add(newTabTextArea));
    int tabIndex=tabbedPane2.indexOfComponent(newTabTextArea);
    tabbedPane2.setSelectedIndex(tabIndex);
    tabbedPane2.setTitleAt(tabIndex,file.getName());
}
catch(Exception ex){}

}

*You have not add tabbedpane2 in you frames . According to your code it look like your are planning to add in Internal frame. But i suggest to add drop listener in OpenDemo frame it will look good but depends on your requirement.add below line in initComponents method
this.add(tabbedPane2);

*After this it will work when you add file from menu item (first file is not visible you should work on that). then once internal frame is added you can drag and drop file you needed.
4.I suggest to have tabbedpane2 and drop listener in main frame ie openDemo and remove internal frame but depends on your design.
see screen shot.

A: Repalce Your OpenDemo file with this code :
   Changes are

*

*Added New internal frame for each Drop Event

*Added Drop event listner in main frame which was missing.

*Added Drop Listner in internal frame when it is added through Open menu item

*Added New Internal Class for DropListner instead of anonymous class to have code reuse.

*some minor chagnes

*You should Debug step by step ,and you can found these issue easily.
public class OpenDemo extends javax.swing.JFrame implements ChangeListener
{
private ArrayList<OInternalFrame> frames = new ArrayList<OInternalFrame>();
private OInternalFrame currentFrame;
private DropTargetListener dropListner;
int i=0;
JTabbedPane tabbedPane2;
public OpenDemo() {
  initComponents();
}
@SuppressWarnings("unchecked")
private void initComponents() {
dropListner=new DropTargetListener();
currentFrame=new OInternalFrame("doc1",true,true);
tabbedPane2=new JTabbedPane();
this.add(tabbedPane2);
enableDragAndDrop();
tp = new javax.swing.JTabbedPane();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
open = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jMenu1.setText("File");
open.setText("Open");
open.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
        openActionPerformed(evt);
    }
});
jMenu1.add(open);
jMenuBar1.add(jMenu1);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(tp, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(tp, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE));
pack();
 }

private void openActionPerformed(java.awt.event.ActionEvent evt) {
FileDialog fd = new FileDialog(OpenDemo.this, "Select File", FileDialog.LOAD);
fd.setVisible(true);
String sts;
if (fd.getFile() != null) {
    sts = fd.getDirectory() + fd.getFile();
    System.out.println(sts);
    BufferedReader br = null;
    StringBuffer str = new StringBuffer("");
    try {
        br = new BufferedReader(new FileReader(sts));
        String line;
        try {
            while ((line = br.readLine()) != null) {
                str.append(line + "\n");
            }
        } catch (IOException ex) {
            Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex);
        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex);
    }
    String t = str.toString();
    OInternalFrame internalFrame = new OInternalFrame("",true,true);
    i++;
    internalFrame.setName("Doc "+i);
    // Should file name here
    internalFrame.setName(fd.getFile());
    DropTarget target=new DropTarget(internalFrame.textArea,dropListner);
    try {
        internalFrame.setSelected(true);
    } catch (PropertyVetoException ex) {
        Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex);
    }
    internalFrame.addInternalFrameListener(new InternalFrameAdapter() {
        @Override
        public void internalFrameClosing(InternalFrameEvent e) {
            i--;
            frames.remove(currentFrame);
            tp.remove(currentFrame);
        }
    });
    tp.add(internalFrame);
    tp.setSelectedIndex(i-1);
    tp.addChangeListener(this);
    frames.add(internalFrame);
    currentFrame=internalFrame;

    currentFrame.setText(t);
    currentFrame.setVisible(true);
}
}
@Override
public void stateChanged(ChangeEvent ce) {
JTabbedPane sourceTabbedPane = (JTabbedPane) ce.getSource();
int index = sourceTabbedPane.getSelectedIndex();
try {
    currentFrame =frames.get(index);
}
catch(IndexOutOfBoundsException e1){
}
}
public static void main(String args[]) {
try {
    for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
        if ("Nimbus".equals(info.getName())) {
            javax.swing.UIManager.setLookAndFeel(info.getClassName());
            break;
        }
    }
 } catch (ClassNotFoundException ex) {
    java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
    java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
    java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
    java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
        new OpenDemo().setVisible(true);
    }
});
}
 private javax.swing.JMenu jMenu1;
 private javax.swing.JMenuBar jMenuBar1;
 private javax.swing.JMenuItem open;
 private javax.swing.JTabbedPane tp;
 private void enableDragAndDrop() {
 DropTarget target=new DropTarget(this,dropListner);
 }

 private class DropTargetListener implements java.awt.dnd.DropTargetListener
 {
 public void dragEnter(DropTargetDragEvent e) {
 }
 public void dragExit(DropTargetEvent e) {
 }
 public void dragOver(DropTargetDragEvent e) {
 }
 public void dropActionChanged(DropTargetDragEvent e) {
 }
 public void drop(DropTargetDropEvent e) {
 try {
    e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
    java.util.List list=(java.util.List)e.getTransferable().getTransferData(DataFlavor.javaFileListFlavor);
    File file=(File)list.get(0);
    OInternalFrame newOInternalFrame=new OInternalFrame(file.getName(),true,true);
    DropTarget target=new DropTarget(newOInternalFrame.textArea,dropListner);
    newOInternalFrame.textArea.read(new FileReader(file),null);
    // currentFrame.textArea.read(new FileReader(file),null);
    newOInternalFrame.textArea.setCaretPosition(0);
    // currentFrame.textArea.setCaretPosition(0);
    //tabbedPane2.add(add(newTabTextArea));
    tp.add(newOInternalFrame);
    int tabIndex=tp.indexOfComponent(newOInternalFrame);
    tp.setSelectedIndex(tabIndex);
    tp.setTitleAt(tabIndex,file.getName());
    add(tp);
}
catch(Exception ex){}
}
}
}

Image:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Loop though object for jsx I am have a problem displaying the images as a list. was wondering why?
I don't have any errors so i am not sure how to solve this
import React from 'react'
import ReactDOM from 'react-dom'

const friends = [
  {
    title: "Yummmmmmm",
    src: "https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-monkeyweirdo.jpg"
  },
  {
    title: "Hey Guys!  Wait Up!",
    src: "https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-earnestfrog.jpg"
  },
  {
    title: "Yikes",
    src: "https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-alpaca.jpg"
  }
];

// New component class starts here:

I used a map function to loop though the above array of object datatypes.
i injected to extract the key's values.
 class Friend extends React.Component{
  render(){
    let flist = friends.map((friend, i) =>{

{friend[i].title}

    })
    return (

{flist}

);
  }
}

ReactDOM.render(<Friend />, document.getElementById('app'));

A: You are not returning anything from your map function. Try:
class Friend extends React.Component{
  render(){
    let flist = friends.map((friend) => (

{friend.title}

    ))
    return (

{flist}

    );
  }
}

You also don't need to select the object like: friend[i], because you are already iterating over every element of the list.


text:
Q: Как получить результатом одно из двух? Мне нужно сделать, чтобы после нажатия кнопки "проверка" с вероятностью в 50% отображался текст "Да" или "Нет"
 Как это реализовать?

A: Если вам рандом нужен, то так:

btn.addEventListener('click', () => {
  let answers = ['Да', 'Нет'];
  alert(answers[Math.floor(Math.random()*answers.length)]);
});
<button id="btn">Click</button>


text:
Q: JS - how to remove image with JavaScript? I faced a problem as to remove image with JS
code like a...
<img src="image.png" id='image_X'>
...
document.getElementById('image_X').src=''

Image stays unchanged :( So my question is how to remove image with JS?
To be more detailed... How to modify the image src attribute value dynamically?
Any useful comment is appreciated

A: You could just hide it. In vanilla JS that would be:
document.getElementById("image_X").style.display='none';

In jQuery:
$("#image_X").css('display', 'none');

If you really want to remove it from DOM, there is removeChild method you could invoke on the parentNode of your image element.

A: This should do it:
var el = document.getElementById('image_X');
el.parentNode.removeChild(el);

You can try it here.
You can neatly wrap that into a function like so:
function removeElement(ele) {
    ele.parentNode.removeChild(ele);
}

removeElement(document.getElementById("image_X"));

A: Gets its parent and use removeChild.
var parent = getElementById('parentid');
var child = document.getElementById('imagex');
parent.removeChild(child);

A: To delete an image in JavaScript (or generally to delete anything), first you should grab the element, then traverse to its parent element, then you can delete the child using removeChild method.

A: var image_x = document.getElementById('image_X');
image_x.parentNode.removeChild(image_x);

http://jsfiddle.net/5DdyL/

A: Try using:
document.getElementByID("").style.visibilty="hidden";
when you do not want to show the image and
document.getElementById("").style.visibility="visible";
when you want to show the image.

A: I want to share some additional tips...
@Marecky, Thank to Jared Farrish answer I could figure out some helpful points concerning JS...
But next I had to make my own additional research as well... It is not a super fact, but a little theory tip... So, as a result, I could find that browsers, as a any desktop app, of course, are created with some kind of GUI framework... As a rule, most GUI (for example Swing) frameworks, of course, may using double buffered objects to display graphics... So when it (FF for example) re-translates script to graphic objects the GUI sync rules come to life...
...OK... Coming from GUI re-painting problems to scripting itself...
So my question was about playing around DOM objects... The fact was the img tag doesn't update UI event if the code like document.getEelementById('image_X').src='' is activated; So the <body> tag space (for some reason) , I am not sure but, is keeping some kind of 'cached' state... And maybe that makes img (if it is in body) become 'static'; So I had to find some helpful additional object which supports dynamic UI update. As a test, I used div instead of the pure body tag to keep img in it; So not to update body but div inner content only and that helped. So using JS + HTML in my case was helpful...
I hope the tip saves ones day

A: Try
 document.getEelementById('image_X').src="''";

but it will display a broken image

A: 1) remove img element using parent node.
2) Then, Store that parent node.
3) Then, create new img element in that parent node.


text:
Q: Ogg audio served from PHP-file unseekable on Chrome I'm developing a basic audio player using HTML5 audio element. All served files are .ogg coming from another system as a binary string through an API and printed out by a simple PHP handler (which includes some basic security checking) and there's really nothing I can do about it.
However, while everything works nicely on Firefox, Chrome has some issues regarding seeking, skipping or replaying (simply put: it can't be done). Getting audio duration from the audio element returns Infinity, and while currentTime returns correct value, it can't be manipulated.
I started fiddling with headers and response codes and nothing seems to work properly. Using response code 206 for partial content or declaring Accept-Ranges in header causes audio element to go disabled as it does when the source file doesn't exist.
Searching for proper headers didn't yield much results, since it always was about partial content and X-Content-Duration (which is a PITA to calculate because of VBR), which did absolutely nothing on Chrome.
Here are the relevant headers which work just fine on FF. Did I make a major mistake on something, or is there just some issue with Chrome?
HTTP/1.1 200 OK (changing this to 206 makes the file unplayable in Chrome)
Cache-Control: public, no-store
Content-Disposition: attachment; filename="redacted.ogg"
Content-Length: 123456
X-Content-Duration: 12 (this does nothing on Chrome, works on FF)
Content-Range: bytes 0-123455/123456
Accept-Ranges: bytes (...as does including this)
Content-Transfer-Encoding: binary
Content-Type: audio/ogg
Expires: 0
Pragma: public

Edit: some kind of behaviour on Opera, probably on all Webkit browsers. Also doesn't work in fread/file_get_contents type of situations.

A: Alright, dumb me, it really was due the partial content. Chrome didn't really like the idea of taking the whole file at once (and caching it like FF), so to enable seeking and whatnot it needed Accept-Ranges: bytes, a bit of incoming header parsing to get the requested byte range and couple of lines which return that aforementioned byte range with correct partial content status (206), not just "bytes 0-(filesize-1)/filesize" (whole file), even if the first request asks for it (bytes=0-).
Hope this helps someone else as well.


text:
Q: Turn URL encoded string into UTF-8 Yesterday I faced problem about getting some Unicode strings from URL. Actually I use CodeIgniter and the URL segments will be passed into controller/function(parameters). I don't know is it the CI changes the encoding or it's something else. I have the right encoding in my HTML page in the content and in the address bar till I get those Unicode segments.
For example:
localhost/df-gamez/news/افتتاح-جدید-سایت-تیم-دریم-فکتوری

The last segment is perisan characters which is under UTF-8. It's present correctly in everywhere but when I get it in my code It will turn to something like this:
%d8%a7%d9%81%d8%aa%d8%aa%d8%a7%d8%ad-%d8%b3%d8%a7%db%8c%d8%aa-%d8%ac%d8%af%db%8c%d8%af-
%d8%aa%db%8c%d9%85-%d8%af%d8%b1%db%8c%d9%85-%d9%81%da%a9%d8%aa%d9%88%d8%b1%db%8c

I tried to change it to UTF-8 with mb_encode but it didn't. Both my HTML page and Controller file are formatted as UTF-8 Without BOM.
Peace Out!

A: Use urldecode function to decode.
echo urldecode("%d8%a7%d9%81%d8%aa%d8%aa%d8%a7%d8%ad-%d8%b3%d8%a7%db%8c%d8%aa-%d8%ac%d8%af%db%8c%d8%af-%d8%aa%db%8c%d9%85-%d8%af%d8%b1%db%8c%d9%85-%d9%81%da%a9%d8%aa%d9%88%d8%b1%db%8c");

will give you افتتاح-سایت-جدید-تیم-دریم-فکتوری


text:
Q: coloring text in a time when condition is fulfilled I am trying to coloring text on green or red when condition ( if ) is fulfilled.
There is my function getAll()
            function getAllTasks() {
                $http.get('db_files/tasksDB.php').then(function (response) {
                    $scope.tasks = response.data;
                    $scope.tasks = response.data.map(function (item) {
                        var millisDiff = (new Date(item.deadline) - new Date(item.task_start));
                        item.dayDiff = Math.floor(millisDiff / (1000 * 60 * 60 * 24));
                        $scope.color = function () {
                            return (item.dayDiff < 1) ? 'red' : 'green';
                        };
                        return item;
                    });
                });
            }

And there is part of my table where I want to color text.
Example below don't works.
{{ task.dayDiff }}

I also tried like that but it always coloring on green or on red.
{{ task.dayDiff }}

I want to do something like that: If one day left then color text on red else color on green.

A: Use ng-style directive to assign styles from the controller. here is sample demo

angular.module("app",[])
.controller("ctrl",function($scope){

  $scope.itemArr = [{
     "id":"521",
     "username":"defus",
     "task":"test",
     "dept":"test",
     "status":"Otwarte",
     "task_start":"2017-02-26 11:47:29",
     "task_end":"0000-00-00 00:00:00",
     "task_time":null,
     "deadline":"2017-02-28"
  }]

 $scope.itemArr =   $scope.itemArr.map(function(item) {
    var millisDiff = (new Date(item.deadline) - new Date(item.task_start));
    item.dayDiff = Math.floor(millisDiff / (1000 * 60 * 60 * 24));
    $scope.color = (item.dayDiff > 1) ? 'red' : 'green';
    return item;
  });
   console.log($scope.itemArr)
   console.log($scope.color)
})

working

A: Add the color function to item object, so you could call it in the view.
{{ task.dayDiff }}

function getAllTasks() {
  $http.get('db_files/tasksDB.php').then(function(response) {
    $scope.tasks = response.data;
    $scope.tasks = response.data.map(function(item) {
      var millisDiff = (new Date(item.deadline) - new Date(item.task_start));
      item.dayDiff = Math.floor(millisDiff / (1000 * 60 * 60 * 24));
      item.color = function() {
        return (item.dayDiff < 1) ? 'red' : 'green';
      };
      return item;
    });
  });
}


text:
Q: How to position Horizontal Ray text from PDH & PDL to bottom right I am trying to position my text label to far right of screen like you would do if you clicked on a horizontal ray and went to settings and positioned text to bottom right.
This is my code so far but text is in center and moves when I zoom in and out
//@version=5
indicator('PRIOR D/W/M LEVELS', shorttitle='D/W/M', overlay=true)

preDayData = input(defval=true, title='Previous Day High/Low?', tooltip='Select to show previous days high and low values across all timeframes')
preWeekData = input(defval=true, title='Previous Week High/Low?', tooltip='Select to show previous weeks high and low values across all timeframes')
preMonthData = input(defval=true, title='Previous Month High/Low?', tooltip='Select to show previous month high and low values across all timeframes')

PDH = request.security(syminfo.tickerid, 'D', high[1])
PDL = request.security(syminfo.tickerid, 'D', low[1])
PWH = request.security(syminfo.tickerid, 'W', high[1])
PWL = request.security(syminfo.tickerid, 'W', low[1])
PMH = request.security(syminfo.tickerid, 'M', high[1])
PML = request.security(syminfo.tickerid, 'M', low[1])

is_new_day = ta.change(time('1W'))
bar_idx_prev_day = bar_index - ta.valuewhen(is_new_day, bar_index+5, 1)
is_new_week = ta.change(time('1W'))
bar_idx_prev_week = bar_index - ta.valuewhen(is_new_week, bar_index+5, 1)
is_new_month = ta.change(time('1M'))
bar_idx_prev_month = bar_index - ta.valuewhen(is_new_month, bar_index+5, 1)

var line l_pdh = na
var line l_pdl = na
var line l_pwh = na
var line l_pwl = na
var line l_pmh = na
var line l_pml = na

// if barstate.islast
if preDayData == true
    l_pdh := line.new(bar_index - bar_idx_prev_day, PDH, bar_index, PDH, extend=extend.right, color=color.blue)
    l_pdl := line.new(bar_index - bar_idx_prev_day, PDL, bar_index, PDL, extend=extend.right, color=color.blue)

if preWeekData == true
    l_pwh := line.new(bar_index - bar_idx_prev_week, PWH, bar_index, PWH, extend=extend.right, color=color.yellow)
    l_pwl := line.new(bar_index - bar_idx_prev_week, PWL, bar_index, PWL, extend=extend.right, color=color.yellow)

if preMonthData == true
    l_pmh := line.new(bar_index - bar_idx_prev_month, PMH, bar_index, PMH, extend=extend.right, color=color.fuchsia)
    l_pml := line.new(bar_index - bar_idx_prev_month, PML, bar_index, PML, extend=extend.right, color=color.fuchsia)

plotshape(preDayData ? PDH : na, location=location.absolute, style=shape.labeldown, textcolor=color.new(color.blue,0), color=color.new(color.blue,100), text="Daily High", show_last=1, offset=5)
plotshape(preDayData ? PDL : na, location=location.absolute, style=shape.labelup, textcolor=color.new(color.blue,0), color=color.new(color.blue,100), text="Daily Low", show_last=1, offset=5)
plotshape(preWeekData ? PWH : na, location=location.absolute, style=shape.labeldown, textcolor=color.new(color.yellow,0), color=color.new(color.yellow,100), text="Weekly High", show_last=1, offset=15)
plotshape(preWeekData ? PWL : na, location=location.absolute, style=shape.labelup, textcolor=color.new(color.yellow,0), color=color.new(color.yellow,100), text="Weekly Low", show_last=1, offset=15)
plotshape(preMonthData ? PMH : na, location=location.absolute, style=shape.labeldown, textcolor=color.new(color.fuchsia,0), color=color.new(color.fuchsia,100), text="Monthly High", show_last=1, offset=25)
plotshape(preMonthData ? PML : na, location=location.absolute, style=shape.labelup, textcolor=color.new(color.fuchsia,0), color=color.new(color.fuchsia,100), text="Monthly Low", show_last=1, offset=25)

line.delete(l_pdh[1])
line.delete(l_pdl[1])
line.delete(l_pwh[1])
line.delete(l_pwl[1])
line.delete(l_pmh[1])
line.delete(l_pml[1])

I would like it to look more like this

A: That is not quite possible.
As a workaround, you can plot the values instead of using lines with show_last=1 and trackprice=true, and turn on the option to display the plot name and values on the price scale.
Here is an example for the daily high.
//@version=5
indicator('PRIOR D/W/M LEVELS', shorttitle='D/W/M', overlay=true)

preDayData = input(defval=true, title='Previous Day High/Low?', tooltip='Select to show previous days high and low values across all timeframes')
PDH = request.security(syminfo.tickerid, 'D', high[1])
plot(preDayData ? PDH : na, " Daily High", color.blue, show_last=1, trackprice=true)


text:
Q: Enzyme don't work with script "yarn test --coverage" I tried to test my react project with enzyme and jest, when run my project with yarn test all be right, but when I tried to run the coverage report with the script yarn test --coverage and all test with enzyme has been failed.
import '@testing-library/jest-dom/extend-expect';

import {configure} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import 'jest-enzyme';

configure({adapter: new Adapter()});

This is my test.
it("should render Form", () => {
    console.log(wrapper.debug());
    expect(wrapper.exists(FormSignup)).toBe(true);
  });

When I run with yarn test and y try to log wrapper.debug()
Console.log src/pages/patient-auth/patient-auth.test.js:99

Authorización de paciente

<form autoComplete="off" class="sc-fKgIGh fFDhjo">

Nombre: test test test

Correo : test@test.com

<input type="date" name="expiration_date" min="1980-01-01" max="2021-01-19" class="sc-dlnjPT lbPlE"/>
Fecha de expiración

 Autorización

<input type="checkbox" name="auth" id="auth" class="sc-jrsJCI iFWYuj"/>

<button type="submit" class="sc-bdnylx jqdcFs">"Actualizar Paciente"</button>

{"expiration_date":"","auth":null}

</form>

and the test is right
When I run with yarn test --coverage and y try to log wrapper.debug()
console.log src/pages/patient-auth/patient-auth.test.js:99
      null

 expect(received).toBe(expected) // Object.is equality

    Expected: true
    Received: false

      103 |
      104 |   it("should render Form", () => {
    > 105 |     expect(wrapper.exists(FormSignup)).toBe(true);
          |                                        ^
      106 |   });

Thanks a lot


text:
Q: Sharepoint 2010 Managed Metadata Service not there When I try to turn on the Managed Metadata Service in central admin, I don't see an option here  http://mycentraladmin:5555/_admin/ServiceApplications.aspx
I just see
Application Discovery and Load Balancer Service Application
Security Token Service Application
I also can't click on new

A: I was using firefox, I should have been using IE.


text:
Q: MYSQL using CASE statement to create a column based on dates There is a column in a table with dates called 'date_activated'. I would like to add a column and use the information from the 'date_activated' to produce a datetime format that sets to the first day of the year.
For example:

id
date_activated
datetime

1.
2016-05-12
2016-01-01 0:00:00

2.
2019-05-16
2019-01-01 0:00:00

A: Here is the query:
select
    *,
    cast(concat(year(date_activated), '-1-1') as datetime) 'datetime'
from
    t;

and matching output:

id
date_activated
datetime

1
2016-05-12
2016-01-01 00:00:00

2
2019-05-16
2019-01-01 00:00:00

If you want to alter the table you do that, then update the column with the cast expression.

A: First, ALTER your table to add your additional column:
ALTER TABLE sample_table
ADD COLUMN `datetime` timestamp AFTER date_activated;

Note: your newly created column named datetime is a Keyword in MySQL. It is not advised to name things after Keywords or Reserved Words.

Next, UPDATE your column using an INNER JOIN to self-join your tables in order to get the year from the date_activated column:
UPDATE sample_table a
INNER JOIN sample_table b ON a.id = b.id
SET b.datetime = CONCAT(YEAR(b.date_activated), '-01-01 00:00:00')

Using YEAR(), you can extract the year from date_activated then CONCAT it with '-01-01 00:00:00' to fit your new timestamp columns format.

If you're just trying to add it to your SELECT statement without altering or updating your table:
SELECT id,
       date_activated,
       CONCAT(YEAR(date_activated), '-01-01 00:00:00') AS datetime
FROM sample_table

Input:

id
date_activated

1
2016-05-12

2
2019-05-16

Output:

id
date_activated
datetime

1
2016-05-12
2016-01-01 00:00:00

2
2019-05-16
2019-01-01 00:00:00

db<>fiddle here.


text:
Q: When cloning ext4 partition with the "dd" command to a bigger partition free space doesn't increase
Possible Duplicate:
Drive reporting incorrect free space

Recently I've been trying to clone my hd using dd tool.
Everything was ok, as cloning ntfs partitions but when it comes to ext4 - dd does a strange thing. Eg. Having 12GB partition with 4GB of free space, when im trying to clone it on the new 25GB partition it does clone it, but the data that previously was 12GB, now are 21GB with 4GB(the same amount of free space still as it was on the old partition). It happens everytime im cloning my home and root partitions (ext4).
I was also trying to lower the size of the new partition, to the size of the old one, but then dd ends with error saying that there's not enough of space, which should be enough...
Anyone? What's going on?

A: I assume you are doing something like:
sudo dd if=/dev/sda98 of=/dev/sda99

where /dev/sda98 has a size of 12GB and /dev/sda99 is 25GB in size.
Obviously these names are wrong, but you get the idea.
What you have done is to move not just the data but the entire file system, including all of its metadata describing what's free and what's used, to the new partition. It has lot's of free space but that free space hasn't been incorporated into the file system on /dev/sda99 so its hidden at the end of the partition and completely unusable.
The solution is to resize the file system located in the partition:
sudo resize2fs /dev/sda99

it works on EXT2, EXT3, and EXT4 file systems.
I'd encourage you to make a backup first, but I assume you still have the data in the original partition.
This will tell the file system to expand into all available space on the partition, incorporating the new space into the file systems's metadata so files can be stored in it.
You can't copy a bigger partition to a smaller partition with dd unless you tell it to only copy so much with the count parameter. dd does a bit for bit copy of everything in the source partition to the target partition, in this case it tries to copy all of the hidden/invisible space to the smaller partition along with the original contents. It has no idea or care about what it is copying--it needn't be a valid file system at all.


text:
Q: An error was encountered performing the requested operation:ORA-00604: I am trying connection to the Oracle database but this error display :
 An error was encountered performing the requested operation:ORA-00604: error occurred at recursive SQL level 1ORA-01756: quoted string not properly terminated00604. 00000 - "error occurred at recursive SQL level %s"*Cause: An error occurred while processing a recursive SQL statement(a statement applying to internal dictionary tables).*Action: If the situation described in the next error on the stackcan be corrected, do so; otherwise contact Oracle Support.
what is the wrong and how can I solve it ?


text:
Q: Css/C# Make element "disappear" on print I have a pretty simple View which Renders a Child View for each Object handed over by the Controler. Information for each Object is than printet on a seperate page. All of this works fine. However i would like to have a headline on top of the page which is not printed. Using the Css I use this works, however the first printed page will be a blank one. If I just outcomment the headline the blank page disappears again. Is there any way of having the Headline there without printing a blank page?
View:
@model IQueryable<Event>

@{
    ViewBag.Title = "Druckansicht";
}

@section Scripts {

}

Deine Druckansicht vom @ViewBag.StartDate bis zum @ViewBag.EndDate

@foreach (Event evnt in Model)
{

        @{Html.RenderAction("PrintChild", "Events", new { ID = evnt.EventID });}

}

Css:
@media print
{
    .no-print
    {
        display: none !important;
    }

    .page-break
    {
        page-break-before: always;
    }
}

Linking to the Stylesheet etc. is done in a _Layout View.
This is the Solution I ended up using:
CSS:
@media print
{
    .no-print
    {
        display: none !important;
    }

    .page-break
    {
        page-break-after: always;
    }

    .page-break-last
    {
         page-break-after: avoid;
    }
}

View:
@{
        int i = Model.Count();
        foreach (Musa.Models.Event evnt in Model)
        {
            if (i == 1)
            {

                    @{Html.RenderAction("PrintChild", "Events", new { ID = evnt.EventID });}

            }
            else
            {

                    @{Html.RenderAction("PrintChild", "Events", new { ID = evnt.EventID });}

            }
            i--;

        }
    }

A: The following would work:
@media print
{
    .no-print
    {
        display: none !important;
    }

    .page-break
    {
        page-break-after: always;
    }

    .last-page{
        page-break-after: avoid;
    }
}

With the following html:

Header

Test 1

Test 2

Test 3

So make sure the last item get's an additonal class tag otherwise you will get a blank page at the end.


text:
Q: What does this stacktrace mean? I've got an exception I don't understand:
[2012-10-09 08:59:56:152 CEST] 000000a0 SystemOut     O 08:59:56,151  INFO ArendesokningActionHandler:84 - i search
[2012-10-09 08:59:56:152 CEST] 000000a0 SystemOut     O 08:59:56,152 DEBUG AnsokanDAOImpl:36 - 0. sökning utförs
[2012-10-09 08:59:56:152 CEST] 000000a0 SystemOut     O 08:59:56,152 DEBUG AnsokanDAOImpl:38 - 1. sökning utförs
[2012-10-09 08:59:56:160 CEST] 000000a0 SystemOut     O 08:59:56,160 DEBUG AnsokanDAOImpl:40 - 2. sökning utförs
[2012-10-09 08:59:56:160 CEST] 000000a0 SystemOut     O 08:59:56,160 DEBUG AnsokanDAOImpl:42 - 3. sökning utförs
[2012-10-09 08:59:56:160 CEST] 000000a0 SystemOut     O 08:59:56,160  INFO AnsokanDAOImpl:44 - sökning utförs
[2012-10-09 08:59:56:167 CEST] 000000a0 SystemOut     O 08:59:56,165 ERROR AnsokanDAOImpl:48 - Kunde inte söka på: 1201322-3
<openjpa-2.1.1-SNAPSHOT-r422266:1141200 nonfatal user error> org.apache.openjpa.persistence.ArgumentException: No metadata was found for type "class java.lang.String". The class is not enhanced.

Code is
@Stateless
public class AnsokanDAOImpl implements AnsokanDAO {

    @PersistenceContext(unitName = EJBConstants.PERSISTENCE_UNIT_NAME)
    private EntityManager em;

    private final static Logger logger = Logger.getLogger(AnsokanDAOImpl.class);

    @SuppressWarnings("unchecked")
    public List<Ansokan> search(String search) {
        List<Ansokan> ansokningar = new ArrayList<Ansokan>();
        logger.debug("0. sökning utförs");
        try {
            logger.debug("1. sökning utförs");
            Query query = em.createNamedQuery("search");
            logger.debug("2. sökning utförs");
            query.setParameter("search", search);
            logger.debug("3. sökning utförs");

            logger.info("sökning utförs");
            ansokningar = (List<Ansokan>) query.getResultList();
            logger.info("antal träffar i sökning: "+ansokningar.size());
        } catch(Exception e){
            logger.error("Kunde inte söka på: "+search, e);
        }

        return ansokningar;
    }

Can you help me?
Here's the namedquery:
/**
 * Entity implementation class for Entity: Ansokan
 *
 */
@Entity(name = "Ansokan")
@Table(name="TP003_ANSOKAN")
@NamedQueries({
    @NamedQuery(name = "search", query = "SELECT a FROM Ansokan a WHERE a.prvnummer LIKE :search"),
    @NamedQuery(name = "findAnsokanByNumId", query = "SELECT a FROM Ansokan a WHERE a.prvnummer.numId = :numId"),
})

This is the complete Ansokan entity:
package se.prv.pandora.arendeprocess.entity;

/**
 * @author Fredrik Gunnfors (adbfgu)
 *
 */

import java.io.Serializable;
import java.sql.Timestamp;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

import javax.persistence.CascadeType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

/**
 * Entity implementation class for Entity: Ansokan
 *
 */
@Entity(name = "Ansokan")
@Table(name="TP003_ANSOKAN")
@NamedQueries({
    @NamedQuery(name = "search", query = "SELECT a FROM Ansokan a WHERE a.prvnummer LIKE :search"),
    @NamedQuery(name = "findAnsokanByNumId", query = "SELECT a FROM Ansokan a WHERE a.prvnummer.numId = :numId"),
})

public class Ansokan implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="Seq_ansokan_id")
    @SequenceGenerator(name="Seq_ansokan_id", sequenceName="SEQ_TP003_ANSID", allocationSize=1)
    @Column(name = "ANSID", nullable = false)
    private int ansId;

    @ManyToOne
    @JoinColumn(name="numId")
    PRVNummer prvnummer;

    private Integer systemTypId;
    private Integer systemTypDelId;

    private Timestamp loggTid;

    @Column(name = "INGDATUM", length = 10)
    private Date ingivningsDatum;

    @Column(name = "STATUSID")
    private Integer statusId;

    @Column(name = "BENAMNING", length = 500)
    private String benamning; //ASTATUS

    @Column(name = "ANKDATUM", length = 10)
    private Date ankomstDatum;

    @Column(name = "INKDATUM", length = 10)
    private Date inkomDatum;

    @Column(name = "BESLUTSDATUM", length = 10)
    private Date beslutsDatum;

    @Column(name = "ANSVARIG_HANDLID")
    private Integer ansvarigHandlaggareId;

    @Column(name = "SKAPAD_HANDLID")
    private Integer skapadHandlaggareId;

    @Column(name = "EGENSKAPID")
    private Integer egenskapId;

    @Column(name = "PRIORITET", length = 1)
    private String prioritet;

    @OneToMany(mappedBy="ansokan", cascade=CascadeType.ALL)
    private List<ArbetsMomentLog> arbetsuppgifter = new ArrayList<ArbetsMomentLog>();

    // Konstruktor
    public Ansokan() {
        super();
    }

    public int getAnsId() {
        return ansId;
    }

    public void setAnsId(int ansId) {
        this.ansId = ansId;
    }

    public PRVNummer getPrvnummer() {
        return prvnummer;
    }

    public void setPrvnummer(PRVNummer prvnummer) {
        this.prvnummer = prvnummer;
    }

    public Integer getSystemTypId() {
        return systemTypId;
    }

    public void setSystemTypId(Integer systemTypId) {
        this.systemTypId = systemTypId;
    }

    public Integer getSystemTypDelId() {
        return systemTypDelId;
    }

    public void setSystemTypDelId(Integer systemTypDelId) {
        this.systemTypDelId = systemTypDelId;
    }

    public Timestamp getLoggTid() {
        return loggTid;
    }

    public void setLoggTid(Timestamp loggTid) {
        this.loggTid = loggTid;
    }

    public Integer getStatusId() {
        return statusId;
    }

    public void setStatusId(Integer statusId) {
        this.statusId = statusId;
    }

    public String getBenamning() {
        return benamning;
    }

    public void setBenamning(String benamning) {
        this.benamning = benamning;
    }

    public Date getIngivningsDatum() {
        return ingivningsDatum;
    }

    public void setIngivningsDatum(Date ingivningsDatum) {
        this.ingivningsDatum = ingivningsDatum;
    }

    public Date getAnkomstDatum() {
        return ankomstDatum;
    }

    public void setAnkomstDatum(Date ankomstDatum) {
        this.ankomstDatum = ankomstDatum;
    }

    public Date getInkomDatum() {
        return inkomDatum;
    }

    public void setInkomDatum(Date inkomDatum) {
        this.inkomDatum = inkomDatum;
    }

    public Date getBeslutsDatum() {
        return beslutsDatum;
    }

    public void setBeslutsDatum(Date beslutsDatum) {
        this.beslutsDatum = beslutsDatum;
    }

    public Integer getAnsvarigHandlaggareId() {
        return ansvarigHandlaggareId;
    }

    public void setAnsvarigHandlaggareId(Integer ansvarigHandlaggareId) {
        this.ansvarigHandlaggareId = ansvarigHandlaggareId;
    }

    public Integer getSkapadHandlaggareId() {
        return skapadHandlaggareId;
    }

    public void setSkapadHandlaggareId(Integer skapadHandlaggareId) {
        this.skapadHandlaggareId = skapadHandlaggareId;
    }

    public Integer getEgenskapId() {
        return egenskapId;
    }

    public void setEgenskapId(Integer egenskapId) {
        this.egenskapId = egenskapId;
    }

    public String getPrioritet() {
        return prioritet;
    }

    public void setPrioritet(String prioritet) {
        this.prioritet = prioritet;
    }

    public List<ArbetsMomentLog> getArbetsuppgifter() {
        return arbetsuppgifter;
    }

    public void setArbetsuppgifter(List<ArbetsMomentLog> arbetsuppgifter) {
        this.arbetsuppgifter = arbetsuppgifter;
    }

    public void addArbetsuppgifter(List<ArbetsMomentLog> arbetsuppgifter) {
        if(this.arbetsuppgifter!=null)
            this.arbetsuppgifter.addAll(arbetsuppgifter);
        else {
            this.arbetsuppgifter = arbetsuppgifter;
        }
    }

    public ArbetsMomentLog getArbetsuppgiftByTyp(int arbMomTyp) {
        ArbetsMomentLog amlog = null;
        for(ArbetsMomentLog aml: this.arbetsuppgifter) {
            if(aml.getArbetsMomentId()==arbMomTyp) {
                amlog = aml;
                break;
            }

        }
        return amlog;
    }

}

A: You're binding a String value to search the Field prvnummer from the type PRVNummer.
Change public List<Ansokan> search(String search) to public List<Ansokan> search(PRVNummer search)


text:
Q: Asymptotic integration of $\int_0^\infty\frac{x^{-\frac{1}{2}+a}J_{-\frac{1}{2}+a}(x\alpha)}{e^x-1}{\rm d}x$ when $\alpha \gg 1$ What is the asymptotic integration of
$$\int_0^\infty\frac{x^{-\frac{1}{2}+a}J_{-\frac{1}{2}+a}(x\alpha)}{e^x-1}{\rm d}x$$
when $\alpha\rightarrow\infty$. How to compute that using standard identities? Please give a general expression and then consider a special case where $a=\frac{5}{2}$.

A: We assume that $a>\frac{1}{2}$ is fixed. Note that
$$
\frac{{x^{a - 1/2} }}{{e^x  - 1}} \sim \sum\limits_{n = 0}^\infty  {\frac{{B_n }}{{n!}}x^{n + a - 3/2} }
$$
as $x\to 0+$, where $B_n$ denotes the Bernoulli numbers. Then, by Theorem 2 in https://doi.org/10.1137/0507061, we find
\begin{align*}
\int_0^{ + \infty } {\frac{{x^{a - 1/2} }}{{e^x  - 1}}J_{a - 1/2} (\alpha x)dx}  & \sim \frac{1}{{2}}\sum\limits_{n = 0}^\infty  {\frac{{B_n }}{{n!}}\frac{\Gamma\! \left( {\frac{n}{2} + a - \frac{1}{2}} \right)}{\Gamma\! \left( {1-\frac{n}{2}} \right)}\!\left( {\frac{2}{\alpha }} \right)^{n + a - 1/2} }
\\ &
 = \frac{1}{2}\Gamma \!\left( {a - \frac{1}{2}} \right)\!\left( {\frac{2}{\alpha }} \right)^{a - 1/2}  - \frac{{\Gamma (a)}}{{4\sqrt \pi  }}\left( {\frac{2}{\alpha }} \right)^{a + 1/2}
\end{align*}
as $\alpha \to +\infty$. Note that the Bernoulli numbers of odd index $n\geq 3$ or the reciprocal gamma function eliminate all terms in the asymptotic expansion except the first two. The absolute error of this two-term approximation decays to zero faster in $\alpha$ than any negative power of $\alpha$. Thus, this asymptotics is rather accurate for large $\alpha$.
In the special case $a=\frac{5}{2}$, the aproximation is
$$
\int_0^{ + \infty } {\frac{{x^2 }}{{e^x  - 1}}J_2 (\alpha x)dx}  \sim \frac{2}{{\alpha ^2 }} - \frac{3}{{2\alpha ^3 }}.
$$
The right-hand side apporaches $0$ from above for large positive values of $\alpha$.
A different type of expansion may be obtained as follows. We can expand the denominator of the integrand and integrate term-by-term using http://dlmf.nist.gov/10.22.E49, to deduce
\begin{align*}
\int_0^{ + \infty } {\frac{{x^{a - 1/2} }}{{e^x  - 1}}J_{a - 1/2} (\alpha x)dx} & = \int_0^{ + \infty } {x^{a - 1/2} \left( {\sum\limits_{n = 1}^\infty  {e^{ - nx} } } \right)J_{a - 1/2} (\alpha x)dx}
\\ &
 = \sum\limits_{n = 1}^\infty  {\int_0^{ + \infty } {x^{a - 1/2} e^{ - nx} J_{a - 1/2} (\alpha x)dx} }
\\ &
 = \left( {\frac{\alpha }{2}} \right)^{a - 1/2} \Gamma (2a)\sum\limits_{n = 1}^\infty  {\frac{1}{{n^{2a} }}{\bf F}\!\left( {a,a + \frac{1}{2};a + \frac{1}{2}; - \left( {\frac{\alpha }{n}} \right)^2 } \right)}
\\ & = \left( {\frac{\alpha }{2}} \right)^{a - 1/2} \frac{{\Gamma (2a)}}{{\Gamma \!\left( {a + \frac{1}{2}} \right)}}\sum\limits_{n = 1}^\infty  {\frac{1}{{(n^2  + \alpha ^2 )^a }}}
\\ &
 = (2\alpha )^{a - 1/2} \frac{{\Gamma (a)}}{{\sqrt \pi  }}\sum\limits_{n = 1}^\infty  {\frac{1}{{(n^2  + \alpha ^2 )^a }}}
\end{align*}
for $a>\frac{1}{2}$ and $\alpha>0$. Here $\mathbf F$ stands for the regularised hypergeometric function. The last series is a generalised Mathieu series. Thus applying Theorem 1 in https://arxiv.org/abs/1601.07751v1, we obtain
\begin{align*}
\int_0^{ + \infty } {\frac{{x^{a - 1/2} }}{{e^x  - 1}}J_{a - 1/2} (\alpha x)dx}  = & \;\frac{1}{2}\Gamma\! \left( {a - \frac{1}{2}} \right)\!\left( {\frac{2}{\alpha }} \right)^{a - 1/2}  - \frac{{\Gamma (a)}}{{4\sqrt \pi  }}\left( {\frac{2}{\alpha }} \right)^{a + 1/2}  \\ & +(2\pi )^{a - 1/2} \frac{{e^{ - 2\pi \alpha } }}{{\sqrt \alpha  }}\left( {1 + \mathcal{O}\!\left( {\frac{1}{\alpha }} \right)} \right)
\end{align*}
as $\alpha \to +\infty$, with $a>\frac{1}{2}$ being fixed. This shows the exponential accuracy of our original two-term asymptotics.


text:
Q: How to run Office Web Add in automatically on opening/closing Excel I am using 'Office Web Add In' to add some functionality into the office applications like excel,word etc.I want to trigger this functionality on opening/closing of excel.
Problem is the Office Web Add In runs only on user-interaction, when the user clicks on the menu in the ribbons option.
I am not able to trigger this add-in functionality automatically.
This is achievable in other type of add-ins such as Excel- VBA or VSTO Add In.
How can I trigger the add-in functionality automatically on opening excel ?
Have searched for a solution online, but could not find so.
Found something called as 'Auto Open Task Pane' feature which still does not works properly.

A: I am assuming you are addin is built through office yeoman generator or may be on your own with proper manifest file.
Please see the official docs
https://learn.microsoft.com/en-us/office/dev/add-ins/develop/automatically-open-a-task-pane-with-a-document
Please note: Auto open will only work on the below applications.

Also in your manifest file you can add
<Action xsi:type="ShowTaskpane">
    <TaskpaneId>Office.AutoShowTaskpaneWithDocument</TaskpaneId>
    <SourceLocation resid="Contoso.Taskpane.Url" />
</Action>

More clear documentation is available on the official link.
Hope it helps.


text:
Q: Accessing a managed CacheBean in other Java Classes I have written a Java Managed cache bean. One of the uses of this bean is to allow other parts of my app to set various databases. My template will be used by other apps, so I want to be able to set the path of the data database (my programming is in one app and my data is in another) in one place in the cache Bean and then be able to use it through out my app.
My solution seems to work, but I wonder if this is the best way to approach the problem.
My Faces-Config is:
<?xml version="1.0" encoding="UTF-8"?>
<faces-config>
  <managed-bean>
    <managed-bean-name>CacheBean</managed-bean-name>
    <managed-bean-class>com.scoular.cache.CacheBean</managed-bean-class>
    <managed-bean-scope>application</managed-bean-scope>
  </managed-bean>
</faces-config>

I have paired down both the CacheBean and the other Java Class so only the relevant classes show:
CacheBean:
package com.xxxx.cache;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Vector;
import javax.faces.context.FacesContext;

public class CacheBean implements Serializable {

    // Constants
    private static final String BEAN_NAME = "CacheBean";

    private static final long serialVersionUID = -2665922853615670023L;

    private String serverPath;
    private String pcAppDBpathJava;

    public static CacheBean getCurrentInstance() {

        // This is a neat way to get a handle on the instance of this bean in the scope from other Java code...
        FacesContext context = FacesContext.getCurrentInstance();
        return (CacheBean) context.getApplication().getVariableResolver().resolveVariable(context, BEAN_NAME);
     }

    public CacheBean() throws NotesException, Exception {
        loadDBPaths();
    }

    public void loadDBPaths() {
        Session session = Factory.getSession();
        Database tmpDB = session.getCurrentDatabase();
        String tmpStr = tmpDB.getServer();
        pcAppDBpathJava =  tmpStr + "!!" + "scoApps\\PC\\PCApp.nsf";
    }

    public String getServerPath() {
        Session session = Factory.getSession();
        Database tmpDB = session.getCurrentDatabase();
        serverPath = tmpDB.getServer();
        return serverPath;
    }

    public void setServerPath(String serverPath) {
        this.serverPath = serverPath;
    }

    public String getPcAppDBpathJava() {
        return pcAppDBpathJava;
    }

    public void setPcAppDBpathJava(String pcAppDBpathJava) {
        this.pcAppDBpathJava = pcAppDBpathJava;
    }

}

And the other Java class is:
package com.xxxx.model;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import javax.faces.context.FacesContext;
import org.openntf.domino.*;
import org.openntf.domino.utils.Factory;
import org.openntf.domino.xsp.XspOpenLogUtil;
import com.scoular.cache.CacheBean;

public class PC implements Serializable {

    private static final long serialVersionUID = -928898373594997220L;

    @SuppressWarnings("unused")
    private Database appData;

    public PC() {
    }

    public void loadByUnid(String unid) {
        try {

            Database PCDataDB = this.getAppData();
            Document doc = PCDataDB.getDocumentByUNID(unid);
            if (null == doc) {
                System.out.println("Document not found");
            } else {
                loadValues(doc);
            }
        } catch (Exception e) {
            XspOpenLogUtil.logError(e);
        }
    }

    public Database getAppData() {
        CacheBean cache = CacheBean.getCurrentInstance();
        Session session = Factory.getSession();
            Database PCDataDB = session.getDatabase(cache.getPcDataDBpathJava());
        return PCDataDB;
    }

    public void setAppData(Database appData) {
        this.appData = appData;
    }
}

Any suggestions would be much appreciated.

A: You can get your bean as "variable" from JSF engine. Take a look here: https://www.mindoo.com/web/blog.nsf/dx/18.07.2009191738KLENAL.htm?opendocument&comments
Simply call helper class for bound value and you will get either object reference or return value of some method - based on EL you use.
Update, missed actual question:

My solution seems to work, but I wonder if this is the best way to
  approach the problem.

Yes, I think that's the best option.


text:
Q: React Redux using many smart containers and structuring components I've been used to writing code where I had a giant smart container and would pass some props down to the children who need it. However, I've been starting to try a different approach of just creating more containers that grab whatever info they need from the store.
Let's say I have a parent div and three children divs. Parent div is connected and has whatever props it needs. Some child divs also have some functionality and props that it needs.
Basically, is this a normal/good way of approaching things? Just wanted to make sure I'm not doing this the wrong way or creating too many smart containers is a bad thing.
<ConnectedParent>
  <ConnectedChild>
  <ConnectedChild>
  <PresentationalChild>
</ConnectedParent>

A: This is covered in the Redux FAQ entry on "Should I only connect my top component, or can I connect multiple components in my tree?".
Basically, feel free to connect as many components as you want, and connecting more components usually leads to better performance.


text:
Q: Trying to change my code to include loops and listed variables to make more streamline and expandable code I made a prior discussion where I was unable to properly explain myself. This is my most up to date code that does what I want with 3 items. I would like to turn this into a function using a list so that it can ask how many items you want to use and then run the code that I have so it is not manually inputted 3 separate times but is instead expandable to however many items are needed.

unit = "pounds"
pounds = 0.00220462

weightA = float(input("What is the weight of Specimen A? "))

converted_weightA = float(weightA * pounds)
formatted_floatA = "{:.2f}".format(converted_weightA)
#print('Specimen A is ' + formatted_floatA + ' ' + unit)

weightB = float(input("What is the weight of Specimen B? "))

converted_weightB = float(weightB * pounds)
formatted_floatB = "{:.2f}".format(converted_weightB)
#print('Specimen B is ' + formatted_floatB + ' ' + unit)

weightC = float(input("What is the weight of Specimen C? "))

converted_weightC = float(weightC * pounds)
formatted_floatC = "{:.2f}".format(converted_weightC)
#print('Specimen C is ' + formatted_floatC + ' ' + unit)

totalcost = float(input("What is the total price of the lot?:    "))
totalweight = converted_weightA + converted_weightB + converted_weightC

IndividualPriceA = (converted_weightA / totalweight) * (totalcost * 3)
IndividualPriceB = (converted_weightB / totalweight) * (totalcost * 3)
IndividualPriceC = (converted_weightC / totalweight) * (totalcost * 3)

print('Specimen A is ' + formatted_floatA + ' ' + unit + ' and is worth $',IndividualPriceA)
print('Specimen B is ' + formatted_floatB + ' ' + unit + ' and is worth $', IndividualPriceB)
print('Specimen C is ' + formatted_floatC + ' ' + unit + ' and is worth $', IndividualPriceC)

input()

A: Strock, glad your here. I created a solution for you (below) but I wanted to offer some key advice you would benefit from first.
Your question isn't a hard one, but it's almost asking for someone to turn your code into a usable, repeatable script (your asking for loops, a function, etc.). In other words, it comes across as more of a 'will someone do this for me' vice 'How do I do [A] with Python'.
I'm not sure what your profession or intention is regarding python, but if you are seeking to gain more competence with the programming language, the following tips are much more important for you than the solution below.

*

*Break down your script into small parts, i.e., you know you need loops, so start by creating a very simple loop, understanding it's syntax (https://www.freecodecamp.org/news/python-for-loop-example-and-tutorial/). After you build a loop. Add another piece (like appending items to a list like I did below), and so on. Continue with some patience, and you will be rewarded with better python skills.

*I'm still fairly new to the stack overflow community, but here are some tips for getting good responses to questions:

*

*make your question as specific as possible, i.e., 'what's the proper syntax for defining a function in python' is better than 'I need a function and some loops and other things to make this script better'

*then before you post it, search to see if someone else already asked/answered your question

*if there is no answer, ask it here and provide the code involved (which you did nicely)
Best of luck!
Note: the calculations you did (which I copied exactly) didn't make much sense to me, but I also don't know exactly what this is for. Anyways, feel free to comment if you have any questions!
#create wt_convert function which has two required parameters: list of weights and total cost
def wt_convert(list_of_weights, total_cost):

    unit = "pounds"
    pounds = 0.00220462

    #create empty list to hold converted weights
    converted_weights = []

    #loop through the list of weights, convert them, add them to 'converted_weights' list
    for wt in list_of_weights:
        conversion = float(wt * pounds)
        converted_weights.append(conversion)

    #calculate total weight by using sum function and passing list of 'converted_weights'
    totalweight = sum(converted_weights)

    #loop through 'converted_weights', calculate price, print result for each
    i = 1
    n = 0
    for wt in converted_weights:
        price = (wt / totalweight) * (total_cost * 3)
        print('Specimen {} is {} {} and is worth $ {}'.format(
            i,
            converted_weights[n],
            unit,
            price
        ))
        i += 1
        n += 1

#now function (above) is ready, prepare the needed parameters to use it
specimen_weights = []

#used 'while loop' to enable user to make as many inputs as desired
keep_going = "y"
i = 1
while keep_going == "y":
    wt = int(input("What is the weight of specimen {}: ".format(i)))
    specimen_weights.append(wt)
    i += 1
    keep_going = input("To add another specimen, input 'y'. Otherwise press enter: ")

#ask user for total cost
totalcost = float(input("What is the total price of the lot?: "))

#now call function and pass list of specimen weights and totalcost
wt_convert(specimen_weights, totalcost)

example output:


text:
Q: How to visually group class methods into sections? I am a little on the pedantic side when it comes to organizing my code, so I've tried coming up with ways to visually group my class methods into logical parts/sections. My question is whether there are any preferable ways to visually separate class method groups in Python editors?. PEP8 doesn't mention this non-issue so I'm not sure how to do this "correctly".
I guess this desire comes from my Xcode usage where I would add #pragma mark - XY to separate the method sections. I'm using Sublime Text for Python, are there editors or IDEs that support a certain style of grouping?
So an example grouping that I'm currently using is to have logically similar methods one below each other but add more whitespace and a horizontal line (until it hits the 80 char border) between the "groups", like so:
class Foo (object):
    def __init__(self)

    # ------------------------- Properties
    @property
    def foo(self)
    @property
    def bar(self)

    # ------------------------- Querying
    def find(self, id)
    def find_siblings(self)
    def find_related(self, attr)

    # ------------------------- Class Methods
    @classmethod
    def setup(cls)
    @classmethod
    def purge_cache(cls)

    # ------------------------- Utilities
    def __str__(self)
    def __unicode__(self)
    def __repr__(self)

A: One useful method is to use a long docstring on the class itself that logically groups the methods, see PEP 258
In this case you would do something like:
class MyClass():
   """
   This class provides a number of methods grouped accordingly:
      Methods to do with a:
       - a_do_something - Quick Summary
       - a_do_something_else - Quick Summary
      Methods to do with b:
       - b_do_something - Quick Summary
       - b_do_something_else - Quick Summary
   """
   def __init__(self):
       """ Initialise MyClass """
       pass  # More likely some code

   if True:  # Allow group folding for Functional Group A
   ##
   ## The following functions and class methods are to do with a:
   ##
       def a_do_something(params):
          """ Quick Summary

          Parameters:
              Describe Each
          Returns:
              What

          Long description text.
          """
          pass # really the code for this function

etc.
However you may wish to consider breaking any code that is long enough to need this into more classes and grouping things that way.


text:
Q: Sorting a list of arrays and one value in pandas I'm trying to sort a list which is set up like list=([set of coordinates], euclidean distance of route between those coordinates. I want to sort the list by the shortest coordinates.
One list looks like this (via print(*sortedList, sep = "\n")):
([(1.0, 7.0), (4.0, 2.0), (8.0, 3.0), (3.0, 5.0), (1.0, 3.0), (6.0, 2.0)], 30.33773677780192)
([(3.0, 5.0), (4.0, 2.0), (6.0, 2.0), (8.0, 3.0), (1.0, 7.0), (1.0, 3.0)], 22.289030510712912)
([(8.0, 3.0), (1.0, 7.0), (4.0, 2.0), (1.0, 3.0), (3.0, 5.0), (6.0, 2.0)], 26.36262309267749)
([(4.0, 2.0), (3.0, 5.0), (1.0, 7.0), (1.0, 3.0), (6.0, 2.0), (8.0, 3.0)], 21.448897901624807)
([(8.0, 3.0), (4.0, 2.0), (6.0, 2.0), (3.0, 5.0), (1.0, 3.0), (1.0, 7.0)], 25.256431185781686)

What I would like to happen is that when it gets sorted, sortedList becomes:
([(4.0, 2.0), (3.0, 5.0), (1.0, 7.0), (1.0, 3.0), (6.0, 2.0), (8.0, 3.0)], 21.448897901624807)
([(3.0, 5.0), (4.0, 2.0), (6.0, 2.0), (8.0, 3.0), (1.0, 7.0), (1.0, 3.0)], 22.289030510712912)
([(8.0, 3.0), (4.0, 2.0), (6.0, 2.0), (3.0, 5.0), (1.0, 3.0), (1.0, 7.0)], 25.256431185781686)
([(8.0, 3.0), (1.0, 7.0), (4.0, 2.0), (1.0, 3.0), (3.0, 5.0), (6.0, 2.0)], 26.36262309267749)
([(1.0, 7.0), (4.0, 2.0), (8.0, 3.0), (3.0, 5.0), (1.0, 3.0), (6.0, 2.0)], 30.33773677780192)

But instead, the coordinates inside the arrays sort of get switched around in some way, which is definitely not what I want.
What I have been using is this code:
sortedList = list.sort_values(ascending=True)
print(*sortedList, sep = "\n")

I haven't really found anything that works, and when I try to sort "by columns", there is of course no attribute of columns in this list. I don't think it's feasible to add columns but that might be the only way. Is there another way?
Edit:
I've been looking into it and it seems like I might want to change it into a dictionary, although that might make it harder for me to change around later. I do also get a TypeError: unhashable type: 'list' when I try. If it's any help this is to try to keep track of a range of TSP solutions for a genetic algorithm I'm trying to work on.

A: You could try the following:
unsortedList = [([(1.0, 7.0), (4.0, 2.0), (8.0, 3.0), (3.0, 5.0), (1.0, 3.0), (6.0, 2.0)], 30.33773677780192),
([(3.0, 5.0), (4.0, 2.0), (6.0, 2.0), (8.0, 3.0), (1.0, 7.0), (1.0, 3.0)], 22.289030510712912),
([(8.0, 3.0), (1.0, 7.0), (4.0, 2.0), (1.0, 3.0), (3.0, 5.0), (6.0, 2.0)], 26.36262309267749),
([(4.0, 2.0), (3.0, 5.0), (1.0, 7.0), (1.0, 3.0), (6.0, 2.0), (8.0, 3.0)], 21.448897901624807),
([(8.0, 3.0), (4.0, 2.0), (6.0, 2.0), (3.0, 5.0), (1.0, 3.0), (1.0, 7.0)], 25.256431185781686)]

sorted_List = sorted(
    unsortedList,
    key=lambda x: x[1])

print(*sorted_List, sep='\n')

Output:
([(4.0, 2.0), (3.0, 5.0), (1.0, 7.0), (1.0, 3.0), (6.0, 2.0), (8.0, 3.0)], 21.448897901624807)
([(3.0, 5.0), (4.0, 2.0), (6.0, 2.0), (8.0, 3.0), (1.0, 7.0), (1.0, 3.0)], 22.289030510712912)
([(8.0, 3.0), (4.0, 2.0), (6.0, 2.0), (3.0, 5.0), (1.0, 3.0), (1.0, 7.0)], 25.256431185781686)
([(8.0, 3.0), (1.0, 7.0), (4.0, 2.0), (1.0, 3.0), (3.0, 5.0), (6.0, 2.0)], 26.36262309267749)
([(1.0, 7.0), (4.0, 2.0), (8.0, 3.0), (3.0, 5.0), (1.0, 3.0), (6.0, 2.0)], 30.33773677780192)

A: You can use the key argument to sorted() to specify that Python compares the second element (the euclidean distance) in the tuple when sorting.
coordinates = [
    ([(1.0, 7.0), (4.0, 2.0), (8.0, 3.0), (3.0, 5.0), (1.0, 3.0), (6.0, 2.0)], 30.33773677780192),
    ([(3.0, 5.0), (4.0, 2.0), (6.0, 2.0), (8.0, 3.0), (1.0, 7.0), (1.0, 3.0)], 22.289030510712912),
    ([(8.0, 3.0), (1.0, 7.0), (4.0, 2.0), (1.0, 3.0), (3.0, 5.0), (6.0, 2.0)], 26.36262309267749),
    ([(4.0, 2.0), (3.0, 5.0), (1.0, 7.0), (1.0, 3.0), (6.0, 2.0), (8.0, 3.0)], 21.448897901624807),
    ([(8.0, 3.0), (4.0, 2.0), (6.0, 2.0), (3.0, 5.0), (1.0, 3.0), (1.0, 7.0)], 25.256431185781686),
]
sorted_coordinates = sorted(coordinates, key=lambda coord: coord[1])
print(*sorted_coordinates, sep="\n")

Output:
([(4.0, 2.0), (3.0, 5.0), (1.0, 7.0), (1.0, 3.0), (6.0, 2.0), (8.0, 3.0)], 21.448897901624807)
([(3.0, 5.0), (4.0, 2.0), (6.0, 2.0), (8.0, 3.0), (1.0, 7.0), (1.0, 3.0)], 22.289030510712912)
([(8.0, 3.0), (4.0, 2.0), (6.0, 2.0), (3.0, 5.0), (1.0, 3.0), (1.0, 7.0)], 25.256431185781686)
([(8.0, 3.0), (1.0, 7.0), (4.0, 2.0), (1.0, 3.0), (3.0, 5.0), (6.0, 2.0)], 26.36262309267749)
([(1.0, 7.0), (4.0, 2.0), (8.0, 3.0), (3.0, 5.0), (1.0, 3.0), (6.0, 2.0)], 30.33773677780192)

Note: the sorted function creates a new list. You can also use the key argument with list.sort() if you would prefer to modify the list in place.


text:
Q: WPF Add custom class event handler to HierarchicalDataTemplate Essentially the problem that I have is that when I am trying to add an attribute to the checkbox in the HierarchicalDataTemplate in order to handle the checkbox's click event, I can't figure out how to assign the custom ModeNode's class handler onclick(object sender, RoutedEventArgs args). I can assign/create event handlers located to the main Window class which would also work just fine, but I think it is not the correct way to do it.
My .xaml file looks like this
<Window.Resources>
    <ResourceDictionary>
        <Style x:Key="TreeViewItemStyle" TargetType="TreeViewItem">
            <Setter Property="IsExpanded" Value="True" />
            <Setter Property="IsSelected" Value="{Binding IsInitiallySelected, Mode=OneTime}" />
            <Setter Property="KeyboardNavigation.AcceptsReturn" Value="True" />
        </Style>
        <HierarchicalDataTemplate x:Key="CheckBoxItemTemplate" DataType="{x:Type local:ModelNode}" ItemsSource="{Binding Children, Mode=OneTime}">
            <StackPanel Orientation="Horizontal">
                <CheckBox
                    Focusable="False"
                    IsChecked="{Binding IsChecked}"
                    VerticalAlignment="Center"
                />
                <ContentPresenter
                    Content="{Binding Name, Mode=OneTime}"
                    Margin="2,0"
                />
            </StackPanel>
        </HierarchicalDataTemplate>
    </ResourceDictionary>
    </Window.Resources>

    <Grid Margin="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
        <TreeView x:Name="SceneTreeView"
          ItemContainerStyle="{StaticResource TreeViewItemStyle}"
          ItemsSource="{Binding Mode=OneTime}"
          ItemTemplate="{StaticResource CheckBoxItemTemplate}">
        </TreeView>
    </Grid>

This is the datatype class I use for the treeview
public class ModelNode
{
    public List<ModelNode> Children { get; set; }

    public string Name { set; get; } = "";

    public bool IsChecked { get; set; }

    public ModelNode(string name)
    {
        Name = name;
        IsChecked = false;
        Children = new List<ModelNode>();
    }

    public void AddChild(ModelNode m)
    {
        Children.Add(m);
    }

    public static void onclick(object sender, RoutedEventArgs args)
    {
        //logic to handle the Click event
    }

}

I'm a newbie on WPF so I'm probably missing something.

A: ModelNode should have an ICommand property but not an event handler. You could then bind the Command property of the CheckBox to your ICommand source property:
<CheckBox  Command="{Binding CommandProperty}"
           IsChecked="{Binding IsChecked}"
           VerticalAlignment="Center" />

But you might as well handle the "event" logic in the setter of the IsChecked property. This one gets set when you check or uncheck the CheckBox:
private bool _isChecked;
public bool IsChecked
{
    get { return _isChecked; }
    set
    {
        _isChecked = value;
        //logic to handle the Click event

    }
}


text:
Q: Admin panel to keep signed in till logout In opencart version 2 admin panel how should we allow admin user to keep login till signout.
I have tried with session life time . Whether this problem related to session ?

A: there is a couple of things that can log an admin out:

*

*the session can expire

*the cookie can expire (which is partially connected to the session)

*the token parameter could be incorrect or changed

How to fix

*

*to increase the lifetime of a session in file 'admin/index.php' add this code to the top of the file right after <?php
ini_set('session.gc_maxlifetime', '315360000');

where 315360000 is 10 years in seconds.

*to increase the lifetime of the cookie in OpenCart you actually don't need to do anything if you added the code above for the session because opencart uses that lifetime to set the lifetime for the cookie.

*if you have two admin panels opened, you may face a situation where the tokens don't match. if the token in the url doesn't match the token in the session, you will be logged out. so keep that in mind.
let me know if that helped.


text:
Q: Can not catch NoProcessFoundForGivenName I have a powershell script that closes all instances of MS Word where the file name opened in MS Word matches a pattern.  There are times when the Powershell script is invoked but there are no instances of MS Word running.
The cmdlet Get-Process is used to find MS Word and check the names of files that are currently open.
Nether the catch [NoProcessFoundForGivenName,Microsoft.PowerShell.Commands.GetProcessCommand]   or
[Microsoft.PowerShell.Commands.GetProcessCommand]   are getting caught.
{
   $MSWordProcessHandle = Get-Process WINWORD
} catch [NoProcessFoundForGivenName,Microsoft.PowerShell.Commands.GetProcessCommand] {
   Write-Output "No instances of MS Word found running."
}

I keep getting the error below.

Get-Process : Cannot find a process with the name "WINWORD". Verify the process name and call the cmdlet again.
At C:\Utils\scripts\Dev_Set_Close.ps1:24 char:27
+    $MSWordProcessHandle = Get-Process WINWORD
+                           ~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (WINWORD:String) [Get-Process], ProcessCommandException
    + FullyQualifiedErrorId : NoProcessFoundForGivenName,Microsoft.PowerShell.Commands.GetProcessCommand

A: First, you need to use -ErrorAction Stop to force the non-terminating error to be an exception.
Then, When you can't figure out what specific exception to catch, Lee's suggestion to catch everything is helpful:
try {
   $MSWordProcessHandle = Get-Process WINWORD -ErrorAction Stop
} catch {
  $_.Exception.GetType().FullName
}

This outputs Microsoft.PowerShell.Commands.ProcessCommandException
So, this is what you want:
try {
   $MSWordProcessHandle = Get-Process WINWORD -ErrorAction Stop
} catch [Microsoft.PowerShell.Commands.ProcessCommandException]{
   Write-Output "No instances of MS Word found running."
}


text:
Q: Redirect bots using heroku to a different server I have a Django website running on Heroku where most of the data is served via AJAX.
In order to allow search engines to index those pages I want to serve requests with the _escaped_fragment url parameter using phantomjs running on a separate nodejs server. similar to this on apache:
RewriteEngine on
RewriteCond %{QUERY_STRING} ^_escaped_fragment_=(.*)$
RewriteRule (.*) http://webserver:3000/%1? [P]
(source: http://backbonetutorials.com/seo-for-single-page-apps/)

`
How can I do this in Heroku?

A: Heroku does not give you control over the frontend loadbalancer (which is where you'd ideally want this embedded). You would need to embed this logic into your application (See: Middleware), or run your own "mini loadbalancer" in front of your application (i.e. you would run nginx on each web worker, purely to implement this match and redirect scheme).
To use nginx, the fastest way is to use https://github.com/ryandotsmith/nginx-buildpack
Step 1: Use heroku-buildpack-multi
$ heroku config:set BUILDPACK_URL=https://github.com/ddollar/heroku-buildpack-multi.git

Step 2: Add the required extra buildpacks to .buildpacks
$ echo 'https://github.com/ryandotsmith/nginx-buildpack.git' >> .buildpacks
$ echo 'https://github.com/heroku/heroku-buildpack-python.git' >> .buildpacks
$ git commit .buildpacks -m 'Add multi-buildpack'

Step 3: Add uwsgi to your requirements.py. UWSGI is the fastest way to server python projects out of heroku, and importantly it can listen on a domain socket.
Step 4 : Add a uwsgi.conf to your project
[uwsgi]
http-socket = /tmp/nginx.socket
master = true
processes = 4
die-on-term = true
memory-report = true
module = yourapp.wsgi:application
env = DJANGO_SETTINGS_MODULE=yourapp.settings

Step 5: Create config/nginx.conf.erb in your project. Copy from here. Edit this to add your custom redirect logic.
Step 6 : Modify your app to touch /tmp/app-initialized when it starts up
Now obviously this is pretty heavy modification, and will take a while to get it set up right. If you don't really need this high-performance option, take the simpler route and set up a custom middleware layer instead.


text:
Q: EF 5 Conditional Mapping I'm using EF 5 Database first approach in my MVC application. all of my tables uses a Field called Deleted which is a boolean field to mark a record is deleted.
I'm trying to get rid of the requirement of having to check Deleted == false every time I query my database. The very straightforward way of doing this is to use a conditional mapping in the edmx file where EF always return data that are not deleted. That's all good.
But the problem of doing this condition mapping is that, when I want to allow the user to delete some record for e.g Address from their address book I don't have access to Delete field from EF as I used it in the conditional mapping and therefore I have to look for another option to allow user to delete a record.
The way I thought is to create a stored proc that handle the delete query and call it when I want to delete the record.
Is there a better way of doing this? Is it possible to make the Delete field accessible even it is used in the conditional mapping?

A: I have a working solution for Soft Delete in Entity Framework Code First that may help.
The key is that you add a discriminator to every model that you want to be able to soft delete. In code first that is done like this:
modelBuilder.Entity<Foo>().Map(m => m.Requires("IsDeleted").HasValue(false));
This makes it invisible to the context and therefore you have to do the deletes using sql.
If this is the equivalent of your "conditional mapping" in Database First then one way to modify the sql is to override SaveChanges and run sql from there:
public override int SaveChanges()
{
   foreach (var entry in ChangeTracker.Entries()
             .Where(p => p.State == EntityState.Deleted
             && p.Entity is ModelBase))//I do have a base class for entities with a single
                                       //"ID" property - all my entities derive from this,
                                       //but you could use ISoftDelete here
    SoftDelete(entry);

    return base.SaveChanges();
}

private void SoftDelete(DbEntityEntry entry)
{
    var e = entry.Entity as ModelBase;
    string tableName = GetTableName(e.GetType());
    Database.ExecuteSqlCommand(
             String.Format("UPDATE {0} SET IsDeleted = 1 WHERE ID = @id", tableName)
             , new SqlParameter("id", e.ID));

    //Marking it Unchanged prevents the hard delete
    //entry.State = EntityState.Unchanged;
    //So does setting it to Detached:
    //And that is what EF does when it deletes an item
    //http://msdn.microsoft.com/en-us/data/jj592676.aspx
    entry.State = EntityState.Detached;
}

Method used to Get Table Name explained here
That is the way I used to do it. Probably irrelevant to your Database First approach in EF5, but I have now moved to doing it in stored procedures. EF6 Code First generates CreateStoredProcedure calls in Migration files. I replace these with this.CreateDeleteProcedure("dbo.Foo_Delete", "[dbo].[Foos]"); - which is a call to my own extension method:
public static class MigrationExtensions
{
    internal static string DeleteSqlFormat
    {
        //I also hard delete anything deleted more than a day ago in the same table
        get { return "DELETE FROM {0} WHERE IsDeleted = 1 AND DATEADD(DAY, 1, DeletedAt) < GETUTCDATE(); UPDATE {0} SET IsDeleted = 1, DeletedAt = GETUTCDATE() WHERE ID = @ID;"; }
    }

    internal static void CreateDeleteProcedure(this DbMigration migration, string procName, string tableName)
    {
        migration.CreateStoredProcedure(
                        procName,
                        p => new
                        {
                            ID = p.Int(),
                        },
                        body:

                            string.Format(MigrationExtensions.DeleteSqlFormat, tableName)

                    );
    }

}


text:
Q: How to check whether a html form has a specific key in Flask? I have a form which has a input radio like the following:
<form class="search" action="{{ url_for('np.bkg') }}" method="post">

    <input type="text" name="query" style="max-width:700px" placeholder="Search over bkg..." id="query" value="{{query}}" autocomplete="on" required>
    <button type="submit"></button>

    <input type="radio" name="searchType" id="kmatch" value="kmatch" > match </input>
    <input type="radio" name="searchType" id="kextraction" value="kextraction"> extract </input>

</form>

There is no default value for the radio button. Then I have this line:
  search_type = request.form['searchType', None]

However, it reports this error when making a reqeust:
File "/bkg/myenv/lib/python3.7/site-packages/werkzeug/datastructures.py", line 443, in __getitem__
    raise exceptions.BadRequestKeyError(key)
werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: ('searchType', None)

I thought the default None value can prevent this error, but it didn't.
How to fix it?

A: For those who still have this problem it should be like this,
search_type = request.form.get('searchType', None)


text:
Q: How to use one single png image to create multiple website buttons (and their hovers) Changing a color of a png image button on hover is a basic example for me to start with:
HTML
CSS .button { display: block; float: left; width: 100px; height: 100px; background: url('#hover-img-url') bottom; }
.button:hover {background-position: 0 0;}
example Jiddle for above code
By using one single image (all buttons in one image), I want the same hover effect for all image buttons.
for example:
Trail Fiddle: I used one 'arrow' button that is present inside a portion of a group image (image consisting of other buttons as well).
My Questions:

*

*Is this a good way to implement or is there any other way to do this?

*Is there any name with which we call this kind of single image helping for multiple image hovers?

*It is difficult to select a portion of a image and use this portion as a button. Is there any other automated way to select Height and width of a portion of a image? If so, how to make use of that portion of a image (button) without loosing accuracy in the button hover effect?

A: Use image Sprites
Online generator with CSS markup included: http://www.spritecow.com/


text:
Q: Modules for powering and charging 3.3v and 5V projects I've little experience in the nitty gritty of electronics so am looking to inexpensive modules that can help me achieve my goals. Specifically I have ESP32 (3.3v) and Arduino Nano (5v) projects that I would like to power with LiPo (3.3v) batteries. Ideally, the project should be able to be powered by the battery alone, and still continue to operate when plugged into a USB power source, while also charging the battery.
I'm trying to understand whether a TP4056-type charging module like this one on AliExpress (https://www.aliexpress.com/item/1005001621934354.html) will fit the bill (charging the battery AND powering the project) or whether there are some serious gotchas that I need to consider?
I've read many questions on this SE and most of the answers get a bit too technical for me. I do want to learn the nitty-gritty, but for now I just want to get my project off the ground and it seems a fairly common use case.
Update: generally USB power banks are too large / overkill to be an option for the very small footprint, low power projects I have in mind - plus they tend to be expensive in comparison to a $3 module and a $5 battery.

A: A quick-and-easy solution would be to use a USB power bank for 5V. This deals with all the charging and protection issues, and boosts the LiPo output.
For your 3.3V projects, a linear low-dropout regulator to take 5V down to 3.3V might be the easiest solution, if not the most efficient. A DC-DC module that has good low-power efficiency would be better.


text:
Q: node - botframework/QnAMaker multiple answers How do I have multiple answers to same question?
I use Node and I'm pretty new to this, exampels?
This thread has an answer to my problem but its in C#
How can i use QnAMaker to provide random answers to same query

A: I'll assume you've already got a handle on how to use the botbuilder-cognitive services package.
Just like in the C# version, you can override respondFromQnAMakerResult(). You can see in the source code that you don't need to check if there are any answers because respondFromQnAMakerResult() is only called if there's at least one answer.
This is basically the solution from the other question translated into JavaScript:
basicQnAMakerDialog.respondFromQnAMakerResult = function(session, qnaMakerResult) {
    var msg = qnaMakerResult.answers[0].answer;
    var answersforhowareyou = msg.split('|');

    if (answersforhowareyou.count() > 1)
    {
        var index = Math.floor(Math.random() * answersforhowareyou.length);
        msg = answersforhowareyou[index];
    }

    session.send(msg);
}

A: Trying to implement this, errors as below
ReferenceError: answer is not defined
        at QnAMakerDialog.basicQnAMakerDialog.respondFromQnAMakerResult (D:\home\site\wwwroot\app.js:123:38)
        at QnAMakerDialog.invokeAnswer (D:\home\site\wwwroot\node_modules\botbuilder-cognitiveservices\lib\QnAMakerDialog.js:76:22)
        at D:\home\site\wwwroot\node_modules\botbuilder-cognitiveservices\lib\QnAMakerDialog.js:52:31
        at next (D:\home\site\wwwroot\node_modules\botbuilder\lib\dialogs\IntentRecognizer.js:68:17)
        at IntentRecognizerSet.IntentRecognizer.filter (D:\home\site\wwwroot\node_modules\botbuilder\lib\dialogs\IntentRecognizer.js:71:9)
        at D:\home\site\wwwroot\node_modules\botbuilder\lib\dialogs\IntentRecognizer.js:20:31
        at D:\home\site\wwwroot\node_modules\botbuilder\lib\dialogs\IntentRecognizerSet.js:80:17
        at D:\home\site\wwwroot\node_modules\async\lib\async.js:52:16
        at replenish (D:\home\site\wwwroot\node_modules\async\lib\async.js:306:28)
        at D:\home\site\wwwroot\node_modules\async\lib\async.js:326:29
        at D:\home\site\wwwroot\node_modules\async\lib\async.js:44:16
        at D:\home\site\wwwroot\node_modules\botbuilder\lib\dialogs\IntentRecognizerSet.js:72:21
        at D:\home\site\wwwroot\node_modules\botbuilder-cognitiveservices\lib\QnAMakerRecognizer.js:52:21
        at Request._callback (D:\home\site\wwwroot\node_modules\botbuilder-cognitiveservices\lib\QnAMakerRecognizer.js:107:25)
        at Request.self.callback (D:\home\site\wwwroot\node_modules\request\request.js:185:22)
        at emitTwo (events.js:106:13)


text:
Q: Is there a way to reset smbclient settings to the default? I think i made a few bugs in config settings of smb.conf and i want to get my original network settings back..is there any way for that?

A: If you want to get your edited smb.conf back and didn't backup before I fear there is no possibility. You can take a look at /etc/samba and watch for files like "smb.conf~", "smb.conf.bak" or something like this ...
An example smb.conf is to find at /usr/share/samba/. Replace your misconfigured file by
sudo cp /usr/share/samba/smb.conf /etc/samba/smb.conf
sudo initctl restart smbd

And from now backup your files before editing:
sudo cp /etc/samba/smb.conf /etc/samba/smb.conf.backup_120418

or something like this.