问:
How to know what was clicked in a click event?
```<code>var list = document.createElement("div");
        list.classList.add("list");
        list.innerHTML = '<ul>'+
                        '<li class="on">'+
                            '<span>1</span>'+
                        '</li>'+
                        '<li class="on">'+
                            '<span>2</span>'+
                        '</li>'+
                        '<li>'+
                            '<span>3</span>'+
                        '</li>'+
                        '<li>'+
                            '<span>4</span>'+
                        '</li>'+
                        '<li>'+
                            '<span>5</span>'+
                        '</li>'+
                    '</ul>';

list.addEventListener("click", function(e){
     //How to get the li I clicked
});
</code>```

I created element as createElement and content as innerHTML. And I created a click event.
I am not sure how to get the li I clicked here.

答:
You can use the event.target property:

var list = document.createElement("div");
        list.classList.add("list");
        list.innerHTML = '
'+
                        '
'+
                            '1'+
                        '
'+
                        '
'+
                            '2'+
                        '
'+
                        '
'+
                            '3'+
                        '
'+
                        '
'+
                            '4'+
                        '
'+
                        '
'+
                            '5'+
                        '
'+
                    '
';

list.addEventListener("click", function(e){
  console.log('clicked', e.target);
});

document.body.append(list);```

Body:
var list = document.createElement("div");
        list.classList.add("list");
        list.innerHTML = '
'+
                        '
'+
                            '1'+
                        '
'+
                        '
'+
                            '2'+
                        '
'+
                        '
'+
                            '3'+
                        '
'+
                        '
'+
                            '4'+
                        '
'+
                        '
'+
                            '5'+
                        '
'+
                    '
';

list.addEventListener("click", function(e){
     //How to get the li I clicked
});

I created element as createElement and content as innerHTML. And I created a click event.
I am not sure how to get the li I clicked here.

Body:
You can use the event.target property:

var list = document.createElement("div");
        list.classList.add("list");
        list.innerHTML = '<ul>'+
                        '<li class="on">'+
                            '<span>1</span>'+
                        '</li>'+
                        '<li class="on">'+
                            '<span>2</span>'+
                        '</li>'+
                        '<li>'+
                            '<span>3</span>'+
                        '</li>'+
                        '<li>'+
                            '<span>4</span>'+
                        '</li>'+
                        '<li>'+
                            '<span>5</span>'+
                        '</li>'+
                    '</ul>';

list.addEventListener("click", function(e){
  console.log('clicked', e.target);
});

document.body.append(list);


来源: stackexchange

问:
Problem with KeyListener and jframe
I've got problem with JFrame and KeyListerner in Tetris game. I've got two frames - one with Start Button and second with Board. In the second frame I want to control shapes from keyboard, but when I click start I can't do that. When I disactivate first frame - everything is ok. I know I have to focus on second frame and I tried do that, but with no effect. Could someone help me?
First frame:

```<code>package tetris;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Tetris implements ActionListener {
public Tetris() {
initComponents();
}
Component contentPane;
JLabel statusbar  = new JLabel(" 0");
JLabel name  = new JLabel("Tetris");
JButton startbut = new JButton("Start");
JFrame window = new JFrame();
JPanel panelStart = new JPanel();
JPanel game = new JPanel();
int nameSize=24;
Font fontName = new Font("Dialog", Font.BOLD, nameSize);
BorderLayout borderLayout = new BorderLayout();
Board board = new Board(this);

public void initComponents() {
    window.setBounds(500,200,200,400);
    window.setTitle("Tetris");
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setVisible(true);

    window.add(panelStart);
    window.add(game);
    panelStart.setLayout (null);
    panelStart.setVisible(true);
    window.setContentPane(panelStart);

    name.setSize(70,25);
    name.setLocation(53,10);
    name.setFont(fontName);
    panelStart.add(name);
    startbut.setSize(70,25);
    startbut.setLocation(50,80);
    panelStart.add(startbut);
    startbut.addActionListener(this);
  }

public void initGame() {

    game.setLayout (borderLayout);
    panelStart.setVisible(false);
    window.remove(panelStart);

    game.setVisible(true);
    window.setContentPane(game);

    game.setFocusable(true);
    statusbar = new JLabel(" 0");
   game.add(statusbar, BorderLayout.SOUTH);
     game.add(board);
   board.start();

 }
 public JLabel getStatusBar() {
   return statusbar;
 }
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == startbut)
{
    initGame();

}
}

}
</code>```

Board code:

```<code>package tetris;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;

import tetris.Shape.Tetrominoes;

public class Board extends JPanel implements ActionListener      {

    final int BoardWidth = 10;
    final int BoardHeight = 22;

    Timer timer;
    boolean isFallingFinished = false;
    boolean isStarted = false;
    boolean isPaused = false;
    int numLinesRemoved = 0;
    int curX = 0;
    int curY = 0;
    JLabel statusbar;
    Shape curPiece;
    Tetrominoes[] board;

    public Board(Tetris parent) {

    //   setFocusable(true);
       curPiece = new Shape();
       timer = new Timer(400, this);
       timer.start();

       statusbar =  parent.getStatusBar();
       board = new Tetrominoes[BoardWidth * BoardHeight];
       KeyListener keyListener = new TAdapter();
       addKeyListener(keyListener);
       repaint();
       clearBoard();

    }

    public void actionPerformed(ActionEvent e) {
        if (isFallingFinished) {
            isFallingFinished = false;
            newPiece();
        } else {
            oneLineDown();
        }
    }

    int squareWidth() { return (int) getSize().getWidth() / BoardWidth; }
    int squareHeight() { return (int) getSize().getHeight() / BoardHeight; }
    Tetrominoes shapeAt(int x, int y) { return board[(y * BoardWidth) + x]; }

    public void start()
    {
        if (isPaused)
            return;

        isStarted = true;
        isFallingFinished = false;
        numLinesRemoved = 0;
        clearBoard();

        newPiece();
        timer.start();
    }

    private void pause()
    {
        if (!isStarted)
            return;

        isPaused = !isPaused;
        if (isPaused) {
            timer.stop();
            statusbar.setText("paused");
        } else {
            timer.start();
            statusbar.setText(String.valueOf(numLinesRemoved));
        }
        repaint();
    }

    public void paint(Graphics g)
    {
        super.paint(g);

        Dimension size = getSize();
        int boardTop = (int) size.getHeight() - BoardHeight * squareHeight();

        for (int i = 0; i < BoardHeight; ++i) {
            for (int j = 0; j < BoardWidth; ++j) {
                Tetrominoes shape = shapeAt(j, BoardHeight - i - 1);
                if (shape != Tetrominoes.NoShape)
                    drawSquare(g, 0 + j * squareWidth(),
                               boardTop + i * squareHeight(), shape);
            }
        }

        if (curPiece.getShape() != Tetrominoes.NoShape) {
            for (int i = 0; i < 4; ++i) {
                int x = curX + curPiece.x(i);
                int y = curY - curPiece.y(i);
                drawSquare(g, 0 + x * squareWidth(),
                           boardTop + (BoardHeight - y - 1) * squareHeight(),
                           curPiece.getShape());
            }
        }
    }

    private void dropDown()
    {
        int newY = curY;
        while (newY > 0) {
            if (!tryMove(curPiece, curX, newY - 1))
                break;
            --newY;
        }
        pieceDropped();
    }

    private void oneLineDown()
    {
        if (!tryMove(curPiece, curX, curY - 1))
            pieceDropped();
    }

    private void clearBoard()
    {
        for (int i = 0; i < BoardHeight * BoardWidth; ++i)
            board[i] = Tetrominoes.NoShape;
    }

    private void pieceDropped()
    {
        for (int i = 0; i < 4; ++i) {
            int x = curX + curPiece.x(i);
            int y = curY - curPiece.y(i);
            board[(y * BoardWidth) + x] = curPiece.getShape();
        }

        removeFullLines();

        if (!isFallingFinished)
            newPiece();
    }

    private void newPiece()
    {
        curPiece.setRandomShape();
        curX = BoardWidth / 2 + 1;
        curY = BoardHeight - 1 + curPiece.minY();

        if (!tryMove(curPiece, curX, curY)) {
            curPiece.setShape(Tetrominoes.NoShape);
            timer.stop();
            isStarted = false;
            statusbar.setText("game over");
        }
    }

    private boolean tryMove(Shape newPiece, int newX, int newY)
    {
        for (int i = 0; i < 4; ++i) {
            int x = newX + newPiece.x(i);
            int y = newY - newPiece.y(i);
            if (x < 0 || x >= BoardWidth || y < 0 || y >= BoardHeight)
                return false;
            if (shapeAt(x, y) != Tetrominoes.NoShape)
                return false;
        }

        curPiece = newPiece;
        curX = newX;
        curY = newY;
        repaint();
        return true;
    }

    private void removeFullLines()
    {
        int numFullLines = 0;

        for (int i = BoardHeight - 1; i >= 0; --i) {
            boolean lineIsFull = true;

            for (int j = 0; j < BoardWidth; ++j) {
                if (shapeAt(j, i) == Tetrominoes.NoShape) {
                    lineIsFull = false;
                    break;
                }
            }

            if (lineIsFull) {
                ++numFullLines;
                for (int k = i; k < BoardHeight - 1; ++k) {
                    for (int j = 0; j < BoardWidth; ++j)
                         board[(k * BoardWidth) + j] = shapeAt(j, k + 1);
                }
            }
        }

        if (numFullLines > 0) {
            numLinesRemoved += numFullLines;
            statusbar.setText(String.valueOf(numLinesRemoved));
            isFallingFinished = true;
            curPiece.setShape(Tetrominoes.NoShape);
            repaint();
        }
     }

    private void drawSquare(Graphics g, int x, int y, Tetrominoes shape)
    {
        Color colors[] = { new Color(0, 0, 0), new Color(204, 102, 102),
            new Color(102, 204, 102), new Color(102, 102, 204),
            new Color(204, 204, 102), new Color(204, 102, 204),
            new Color(102, 204, 204), new Color(218, 170, 0)
        };

        Color color = colors[shape.ordinal()];

        g.setColor(color);
        g.fillRect(x + 1, y + 1, squareWidth() - 2, squareHeight() - 2);

        g.setColor(color.brighter());
        g.drawLine(x, y + squareHeight() - 1, x, y);
        g.drawLine(x, y, x + squareWidth() - 1, y);

        g.setColor(color.darker());
        g.drawLine(x + 1, y + squareHeight() - 1,
                         x + squareWidth() - 1, y + squareHeight() - 1);
        g.drawLine(x + squareWidth() - 1, y + squareHeight() - 1,
                         x + squareWidth() - 1, y + 1);

    }
    public boolean isFocusable() {
        return true;
    }
  public class TAdapter implements KeyListener  {
          public void keyTyped(KeyEvent e) {
          }
         public void keyPressed(KeyEvent e) {
             if (!isStarted || curPiece.getShape() == Tetrominoes.NoShape) {
                 return;
             }

             int keycode = e.getKeyCode();

             if (keycode == 'p' || keycode == 'P') {
                 pause();
                 return;
             }

             if (isPaused)
                 return;

             switch (keycode) {
             case KeyEvent.VK_LEFT:
                 tryMove(curPiece, curX - 1, curY);
                 break;
             case KeyEvent.VK_RIGHT:
                 tryMove(curPiece, curX + 1, curY);
                 break;
             case KeyEvent.VK_DOWN:
                 tryMove(curPiece.rotateRight(), curX, curY);
                 break;
             case KeyEvent.VK_UP:
                 tryMove(curPiece.rotateLeft(), curX, curY);
                 break;
             case KeyEvent.VK_SPACE:
                 dropDown();
                 break;
             case 'd':
                 oneLineDown();
                 break;
             case 'D':
                 oneLineDown();
                 break;
             }

         }
        @Override
        public void keyReleased(KeyEvent arg0) {
            // TODO Auto-generated method stub

        }
     }
}
</code>```

答:
Your code is to large for me to want to dig through, but what you want to do is possible.

Either way, I would suggest you move to one frame and possibly use a CardLayout or another GUI item to hide and show components because having the user change screens when the game starts is a strange UI.  It will be more user friendly to just have it all in one frame.  And this might fix your current issue.

ContentLicense: CC BY-SA 3.0

Title: Problem with KeyListener and jframe

Body:
I've got problem with JFrame and KeyListerner in Tetris game. I've got two frames - one with Start Button and second with Board. In the second frame I want to control shapes from keyboard, but when I click start I can't do that. When I disactivate first frame - everything is ok. I know I have to focus on second frame and I tried do that, but with no effect. Could someone help me?
First frame:

package tetris;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Tetris implements ActionListener {
public Tetris() {
initComponents();
}
Component contentPane;
JLabel statusbar  = new JLabel(" 0");
JLabel name  = new JLabel("Tetris");
JButton startbut = new JButton("Start");
JFrame window = new JFrame();
JPanel panelStart = new JPanel();
JPanel game = new JPanel();
int nameSize=24;
Font fontName = new Font("Dialog", Font.BOLD, nameSize);
BorderLayout borderLayout = new BorderLayout();
Board board = new Board(this);

public void initComponents() {
    window.setBounds(500,200,200,400);
    window.setTitle("Tetris");
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setVisible(true);

    window.add(panelStart);
    window.add(game);
    panelStart.setLayout (null);
    panelStart.setVisible(true);
    window.setContentPane(panelStart);

    name.setSize(70,25);
    name.setLocation(53,10);
    name.setFont(fontName);
    panelStart.add(name);
    startbut.setSize(70,25);
    startbut.setLocation(50,80);
    panelStart.add(startbut);
    startbut.addActionListener(this);
  }

public void initGame() {

    game.setLayout (borderLayout);
    panelStart.setVisible(false);
    window.remove(panelStart);

    game.setVisible(true);
    window.setContentPane(game);

    game.setFocusable(true);
    statusbar = new JLabel(" 0");
   game.add(statusbar, BorderLayout.SOUTH);
     game.add(board);
   board.start();

 }
 public JLabel getStatusBar() {
   return statusbar;
 }
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == startbut)
{
    initGame();

}
}

}

Board code:

package tetris;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;

import tetris.Shape.Tetrominoes;

public class Board extends JPanel implements ActionListener      {

    final int BoardWidth = 10;
    final int BoardHeight = 22;

    Timer timer;
    boolean isFallingFinished = false;
    boolean isStarted = false;
    boolean isPaused = false;
    int numLinesRemoved = 0;
    int curX = 0;
    int curY = 0;
    JLabel statusbar;
    Shape curPiece;
    Tetrominoes[] board;

    public Board(Tetris parent) {

    //   setFocusable(true);
       curPiece = new Shape();
       timer = new Timer(400, this);
       timer.start();

       statusbar =  parent.getStatusBar();
       board = new Tetrominoes[BoardWidth * BoardHeight];
       KeyListener keyListener = new TAdapter();
       addKeyListener(keyListener);
       repaint();
       clearBoard();

    }

    public void actionPerformed(ActionEvent e) {
        if (isFallingFinished) {
            isFallingFinished = false;
            newPiece();
        } else {
            oneLineDown();
        }
    }

    int squareWidth() { return (int) getSize().getWidth() / BoardWidth; }
    int squareHeight() { return (int) getSize().getHeight() / BoardHeight; }
    Tetrominoes shapeAt(int x, int y) { return board[(y * BoardWidth) + x]; }

    public void start()
    {
        if (isPaused)
            return;

        isStarted = true;
        isFallingFinished = false;
        numLinesRemoved = 0;
        clearBoard();

        newPiece();
        timer.start();
    }

    private void pause()
    {
        if (!isStarted)
            return;

        isPaused = !isPaused;
        if (isPaused) {
            timer.stop();
            statusbar.setText("paused");
        } else {
            timer.start();
            statusbar.setText(String.valueOf(numLinesRemoved));
        }
        repaint();
    }

    public void paint(Graphics g)
    {
        super.paint(g);

        Dimension size = getSize();
        int boardTop = (int) size.getHeight() - BoardHeight * squareHeight();

        for (int i = 0; i < BoardHeight; ++i) {
            for (int j = 0; j < BoardWidth; ++j) {
                Tetrominoes shape = shapeAt(j, BoardHeight - i - 1);
                if (shape != Tetrominoes.NoShape)
                    drawSquare(g, 0 + j * squareWidth(),
                               boardTop + i * squareHeight(), shape);
            }
        }

        if (curPiece.getShape() != Tetrominoes.NoShape) {
            for (int i = 0; i < 4; ++i) {
                int x = curX + curPiece.x(i);
                int y = curY - curPiece.y(i);
                drawSquare(g, 0 + x * squareWidth(),
                           boardTop + (BoardHeight - y - 1) * squareHeight(),
                           curPiece.getShape());
            }
        }
    }

    private void dropDown()
    {
        int newY = curY;
        while (newY > 0) {
            if (!tryMove(curPiece, curX, newY - 1))
                break;
            --newY;
        }
        pieceDropped();
    }

    private void oneLineDown()
    {
        if (!tryMove(curPiece, curX, curY - 1))
            pieceDropped();
    }

    private void clearBoard()
    {
        for (int i = 0; i < BoardHeight * BoardWidth; ++i)
            board[i] = Tetrominoes.NoShape;
    }

    private void pieceDropped()
    {
        for (int i = 0; i < 4; ++i) {
            int x = curX + curPiece.x(i);
            int y = curY - curPiece.y(i);
            board[(y * BoardWidth) + x] = curPiece.getShape();
        }

        removeFullLines();

        if (!isFallingFinished)
            newPiece();
    }

    private void newPiece()
    {
        curPiece.setRandomShape();
        curX = BoardWidth / 2 + 1;
        curY = BoardHeight - 1 + curPiece.minY();

        if (!tryMove(curPiece, curX, curY)) {
            curPiece.setShape(Tetrominoes.NoShape);
            timer.stop();
            isStarted = false;
            statusbar.setText("game over");
        }
    }

    private boolean tryMove(Shape newPiece, int newX, int newY)
    {
        for (int i = 0; i < 4; ++i) {
            int x = newX + newPiece.x(i);
            int y = newY - newPiece.y(i);
            if (x < 0 || x >= BoardWidth || y < 0 || y >= BoardHeight)
                return false;
            if (shapeAt(x, y) != Tetrominoes.NoShape)
                return false;
        }

        curPiece = newPiece;
        curX = newX;
        curY = newY;
        repaint();
        return true;
    }

    private void removeFullLines()
    {
        int numFullLines = 0;

        for (int i = BoardHeight - 1; i >= 0; --i) {
            boolean lineIsFull = true;

            for (int j = 0; j < BoardWidth; ++j) {
                if (shapeAt(j, i) == Tetrominoes.NoShape) {
                    lineIsFull = false;
                    break;
                }
            }

            if (lineIsFull) {
                ++numFullLines;
                for (int k = i; k < BoardHeight - 1; ++k) {
                    for (int j = 0; j < BoardWidth; ++j)
                         board[(k * BoardWidth) + j] = shapeAt(j, k + 1);
                }
            }
        }

        if (numFullLines > 0) {
            numLinesRemoved += numFullLines;
            statusbar.setText(String.valueOf(numLinesRemoved));
            isFallingFinished = true;
            curPiece.setShape(Tetrominoes.NoShape);
            repaint();
        }
     }

    private void drawSquare(Graphics g, int x, int y, Tetrominoes shape)
    {
        Color colors[] = { new Color(0, 0, 0), new Color(204, 102, 102),
            new Color(102, 204, 102), new Color(102, 102, 204),
            new Color(204, 204, 102), new Color(204, 102, 204),
            new Color(102, 204, 204), new Color(218, 170, 0)
        };

        Color color = colors[shape.ordinal()];

        g.setColor(color);
        g.fillRect(x + 1, y + 1, squareWidth() - 2, squareHeight() - 2);

        g.setColor(color.brighter());
        g.drawLine(x, y + squareHeight() - 1, x, y);
        g.drawLine(x, y, x + squareWidth() - 1, y);

        g.setColor(color.darker());
        g.drawLine(x + 1, y + squareHeight() - 1,
                         x + squareWidth() - 1, y + squareHeight() - 1);
        g.drawLine(x + squareWidth() - 1, y + squareHeight() - 1,
                         x + squareWidth() - 1, y + 1);

    }
    public boolean isFocusable() {
        return true;
    }
  public class TAdapter implements KeyListener  {
          public void keyTyped(KeyEvent e) {
          }
         public void keyPressed(KeyEvent e) {
             if (!isStarted || curPiece.getShape() == Tetrominoes.NoShape) {
                 return;
             }

             int keycode = e.getKeyCode();

             if (keycode == 'p' || keycode == 'P') {
                 pause();
                 return;
             }

             if (isPaused)
                 return;

             switch (keycode) {
             case KeyEvent.VK_LEFT:
                 tryMove(curPiece, curX - 1, curY);
                 break;
             case KeyEvent.VK_RIGHT:
                 tryMove(curPiece, curX + 1, curY);
                 break;
             case KeyEvent.VK_DOWN:
                 tryMove(curPiece.rotateRight(), curX, curY);
                 break;
             case KeyEvent.VK_UP:
                 tryMove(curPiece.rotateLeft(), curX, curY);
                 break;
             case KeyEvent.VK_SPACE:
                 dropDown();
                 break;
             case 'd':
                 oneLineDown();
                 break;
             case 'D':
                 oneLineDown();
                 break;
             }

         }
        @Override
        public void keyReleased(KeyEvent arg0) {
            // TODO Auto-generated method stub

        }
     }
}


问:
Given the dataset, how to select the learning algorithm?
I've to build an ML model to classify sentences into different categories. I have a dataset with 2 columns (sentence and label) and 350 rows i.e. with shape (350, 2). To convert the sentences into numeric representation I've used TfIdf vectorization, and so the transformed dataset now has 452 columns (451 columns were obtained using TfIdf, and 1 is the label) i.e. with shape (350, 452). More generally speaking, I have a dataset with a lot more features than training samples. In such a scenario what's the best classification algorithm to use? Logistic Regression, SVM (again what kernel?), neural networks (again which architecture?), naive Bayes or is there any other algorithm?

How about if I get more training samples in the future (but the number of columns doesn't increase much), say with a shape (10000, 750)?

Edit: The sentences are actually narrations from bank statements. I have around 10 to 15 labels, all of which I have labelled manually. Eg. Tax, Bank Charges, Loan etc. In future I do plan to get more statements and I will be labelling them as well. I believe I may end up having around 20 labels at most.

答: With such a small training set, I think you would only get any reasonable results by getting some pre-trained language model such as GPT-2 and fine tune to your problem. That probably is still true even for a larger dataset, a neural net would probably still do best even if you train your own from scratch. Btw, how many labels do you have? What kind of labels are those?</p>

ContentLicense: CC BY-SA 4.0


问:
Bootstrap Tabs Float Image Right
I've got a basic nav-tabs in Twitter Bootstrap and I've got an image after all of my tabs, that I'd like to float right. I've tried modifying its float, text-align, and other attributes, and even the pull-right class as mentioned on a separate but related SO question.

```<code><ul class="nav nav-tabs" role="tablist">
<li class="nav-item">
    <a class="nav-link active" id="stuff-tab" data-toggle="tab" href="#stuff" role="tab" aria-controls="stuff" aria-selected="true">Stuff</a>
</li>
<!-- ... -->

<img class="pull-right text-right float-right" src="myimg.png" width="32px" height="32px">
</code>```

What Bootstrap class or CSS should I write to make my image float to the right?

(Bootstrap 4 if that matters)

答:
Put a div tag around the image and use d-flex justify-content-end like this:

```<code><div class="row">
    <div class="col-md-12">
        <div class="">
            <div class="">
                <ul class="nav nav-pills w-100">
                    <li class="nav-item">
                        <a class="nav-link active" id="stuff-tab" data-toggle="tab" href="#stuff" role="tab"
                            aria-controls="stuff" aria-selected="true">Stuff</a>
                    </li>
                </ul>
            </div>
            <div class="d-flex justify-content-end">
                <img src="https://cdn.searchenginejournal.com/wp-content/uploads/2019/09/f46bc1a6-9ffa-4434-a77a-ea1491d3597a-760x400.jpeg"
                    class="">
            </div>
        </div>
    </div>
</div>
</code>```

I tested this. Should work.

Another you can try:

```<code><div class="col-md-12" style="border-top: 2px solid #000;">
    <div class="mx-4">
        <div class="footer pt-3">
            <div class="row">
                <div class="col-md-6">
                    <ul>
                        <li class="nav-item">
                            <a class="nav-link active" id="stuff-tab" data-toggle="tab" href="#stuff" role="tab" aria-controls="stuff"
                                aria-selected="true">Stuff</a>
                        </li>
                    </ul>
                </div>
                <div class="col-md-6">
                    <div class="float-right">
                        <img class="pull-right text-right float-right" src="http://placekitten.com/301/301" width="32px" height="32px">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

Title: Bootstrap Tabs Float Image Right

Body:
I've got a basic nav-tabs in Twitter Bootstrap and I've got an image after all of my tabs, that I'd like to float right. I've tried modifying its float, text-align, and other attributes, and even the pull-right class as mentioned on a separate but related SO question.

    Stuff

What Bootstrap class or CSS should I write to make my image float to the right?

(Bootstrap 4 if that matters)

Body:
Put a div tag around the image and use d-flex justify-content-end like this:

<div class="row">
    <div class="col-md-12">
        <div class="">
            <div class="">
                <ul class="nav nav-pills w-100">
                    <li class="nav-item">
                        <a class="nav-link active" id="stuff-tab" data-toggle="tab" href="#stuff" role="tab"
                            aria-controls="stuff" aria-selected="true">Stuff</a>
                    </li>
                </ul>
            </div>
            <div class="d-flex justify-content-end">
                <img src="https://cdn.searchenginejournal.com/wp-content/uploads/2019/09/f46bc1a6-9ffa-4434-a77a-ea1491d3597a-760x400.jpeg"
                    class="">
            </div>
        </div>
    </div>
</div>

I tested this. Should work.

Another you can try:

<div class="col-md-12" style="border-top: 2px solid #000;">
    <div class="mx-4">
        <div class="footer pt-3">
            <div class="row">
                <div class="col-md-6">
                    <ul>
                        <li class="nav-item">
                            <a class="nav-link active" id="stuff-tab" data-toggle="tab" href="#stuff" role="tab" aria-controls="stuff"
                                aria-selected="true">Stuff</a>
                        </li>
                    </ul>
                </div>
                <div class="col-md-6">
                    <div class="float-right">
                        <img class="pull-right text-right float-right" src="http://placekitten.com/301/301" width="32px" height="32px">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>


问:
What is the purpose of using JSON.stringify()?
I'm using JSON.stringify in my react redux application. What's the purpose of JSON.stringify in the following context? Even without JSON.stringify it works, but yet I've been advised to use JSON.stringify.

```<code>if (JSON.stringify(earlyBird.eBird) !== JSON.stringify(prevProps.earlyBird.eBird)) {
</code>```

答:
It is actually not recommended because of the fact, JavaScript doesn’t guarantee the order of the keys. Example

Instead use:

Deep’s Equal.

Lodash’s isEqual.

Fast’s Equals.

For details refer to why-you-shouldnt-use-json-stringify

Body:
I'm using JSON.stringify in my react redux application. What's the purpose of JSON.stringify in the following context? Even without JSON.stringify it works, but yet I've been advised to use JSON.stringify.

if (JSON.stringify(earlyBird.eBird) !== JSON.stringify(prevProps.earlyBird.eBird)) {


问:
Difference between Take/TryTake and Add/TryAdd on a Blocking Collection
I have been trying to get my head around the Blocking Collection and I came across Take() and TryTake() also Add() and TryAdd()

I understand that if there are no items to take, Take() will wait till an item is added, similarly with Add() if the collection has reached its max limit, it will wait till the item is removed.

As per Josheph Albahari's article on Parallel Programming

"Add and TryAdd may block if the collection size is bounded; Take and
  TryTake block while the collection is empty."

So Take() and TryTake() both wait for an item to be added. So, if we are not providing any timeout or cancellation token, what is the difference between Take() and TryTake(), shouldn't TryTake() return false straightaway and not wait ? and same for TryAdd() ?

答:
I stumbled upon this question and I think this document of Microsoft is really helpful to figure out what's happening behind the science.

If no item is present, maximum capacity on a bounded collection has been reached, or the timeout period has elapsed, then the TryAdd or TryTake operation returns false. This allows the thread to do some other useful work for a while and then try again later to either retrieve a new item or try to add the same item that could not be added previously.

How to Add and Take Items Individually from a BlockingCollection


问:
Unable to add permissions to Linkedin app and getting error unauthorized_scope_error
I want to add LinkedIn loggin button to my site which is made with React.

Thus, I've created a new app on Linkedin and I have CLIENT_ID and CLIENT_SECRET. I've also added REDIRECT_URL. But in the PERMISSIONS section I see no permissions and I cannot add them.

And now when I try to do an API call to the url from the docs:

```<code>const url = `https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=${REACT_APP_CLIENT_ID}&redirect_uri=${REACT_APP_REDIRECT_URI}&scope=r_emailaddress`
</code>```

It doesn't work and I get error=unauthorized_scope_error

Any idea how to solve that?

I think that if I be able to add those permissions it would be solved.

Thanks in advance.

答:
On LinkedIn developer portal ,go to your app and In product tab select "Share on LinkedIn" and "Sign In With LinkedIn" product then you got following permissions.

r_liteprofile
r_emailaddress
w_member_social

Body:
I want to add LinkedIn loggin button to my site which is made with React.

Thus, I've created a new app on Linkedin and I have CLIENT_ID and CLIENT_SECRET. I've also added REDIRECT_URL. But in the PERMISSIONS section I see no permissions and I cannot add them.

And now when I try to do an API call to the url from the docs:

const url = `https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=${REACT_APP_CLIENT_ID}&redirect_uri=${REACT_APP_REDIRECT_URI}&scope=r_emailaddress`

It doesn't work and I get error=unauthorized_scope_error

Any idea how to solve that?

I think that if I be able to add those permissions it would be solved.

Thanks in advance.


答: If your prevProps.earlyBird.eBird is a string, JSON.stringify is absolutely not needed. However, if it's an object, then to compare two objects in JavaScript, you need to stringify them first. Since you said without JSON.stringify it's working, that just points to the fact that the both are strings and, hence JSON.stringify is not needed here.

Title: What is the purpose of using JSON.stringify()?


问:
How to connect to EC2 instance which is in Private subnet from my Windows OS client machine through Bastion host.?
I have a scenario as following,
I have one EC2 instance in private subnet and one EC2 instance in public subnet.
How can I connect to private subnet EC2 instance through public subnet EC2 instance which is also called Bastion host (Jump box) from my Windows OS client machine.??</p>

答:
You need to connect to the Bastion host, and use that connection to open a tunnel from your machine to the target machine in the private subnet. That allows you open a second connection to the target machine, using the tunnel.

Here is a guide on how to do this using Putty: AWS Setup Bastion Host SSH Tunnel (they are also opening a second tunnel to a Windows server, you can ignore that part).


问:
Which is better for design, .container or .container-fluid?
I am currently developing a website but have a lack of expertise in designing the UI and since I am using Bootstrap 4.5 to help with the CSS, I wasn't sure which class is better, .container or .container-fluid? I understand the fundamentals of these two Bootstrap classes and how to implement them correctly but once again still not sure which one would be better to use from a design standpoint.</p>

答:
Actually you cannot claim to one of them as best for designing, It's a matter of choice for you to go with. If you want spacing like below in the image on the sides then use container class

Or if you want full page layout without spacing then go with container-fluid class

I hope it helps.


问:
Perl reverse array function not working correctly as intended
I'm trying to reverse an array using reverse function but the output of array is same as input i.e my intended output is 0,1,1 but the output I'm getting is 1,1,0...I'm using online compiler for the code.</p>

```<code>@arr=qw(1,1,0);
@rev=reverse @arr;
print @rev;
</code>```

答:
Just remove the comma in qw elements. More details about quote operators

```<code>@arr = qw(1 1 0);

print @arr;
print "\n";
@rev=reverse @arr;
print @rev;
</code>```

Body:
I'm trying to reverse an array using reverse function but the output of array is same as input i.e my intended output is 0,1,1 but the output I'm getting is 1,1,0...I'm using online compiler for the code.

@arr=qw(1,1,0);
@rev=reverse @arr;
print @rev;

Body:
Just remove the comma in qw elements. More details about quote operators

@arr = qw(1 1 0);

print @arr;
print "\n";
@rev=reverse @arr;
print @rev;


问:
Calling ASP.net Web Service from C# Application
I have a question. How can i invoke a web service and get the result from a C# desktop application. I am making a desktop app and I want it to be able to connect to my online ASP.net web services. How is this possible?</p>

答:
Add a Web Reference to the webservice in your Desktop App project reference. Doing so would generate a Proxy for the Webservice called Reference.cs
You can access your webservice using the proxy.</p>

OwnerDisplayName: QAH

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: AB Kolan


问:
Mapping Data To Non-Table Entites In .NET
I've got a problem I've been going round and round on, and every time I think I have a solution I seem to come back to a core requirement not being fulfilled (I will detail this later).

What I'm trying to do, at a simplistic level, is to return a collection of objects from data supplied by a stored procedure.  The object hierarchy is a follows

Shipment Object - this has a ShipmentNumber string property and a List collection

OrderHeader Object - this has OrderNumber double, OrderType string, ShipmentNumber string properties and a List collection

OrderLine Object - this had OrderNumber double, OrderType string, OrderLine double, ItemNumber string properties

Shipment <-> OrderHeader is a 1 to many based on ShipmentNumber on either object

OrderNumber <-> OrderLine is a 1 to many based on OrderNumber and OrderType on either object

This object structure visualises how I need to view my data for a particular report (it's actually a lot more complex than this, but this is a simple example I am initially trying to get working) and bears no resemblence to my database table structure.  I am trying to map data from a stored procedure into this structure so that I end up with a collection of shipments, which then have a collection of order headers within them and these have a collection of lines within them, but I don't seem to be able to do this.  I can't seem to do it with LINQ so I am looking at the Entity Framework.  It seems that you can set an SP to return several SELECT outputs and then use the ObjectContext.Translate<...>(...) method to map data into objects, like this, and then the Translate method will take care of applying the associations, but when I trying this I'm getting an error reporting that the entity object properties aren't mapped.  Looking into this mapping it seems to come back to the objects having to refer to actual database tables (this is my recurring problem).

How, if it is possible, can I load this data, from a stored procedure(s), into this structure of objects using LINQ, EF, or something else without having to base my classes on database tables?  Surely this is possible?  I can do this with a single collection of objects, but the problem seems to come when these objects contain collections of other objects.

Just a few background points:- I have to use stored procedures to get the data - this is out of my control and won't change.  The tables concerned are spread across several database servers, some of which the web server physically doesn't have access to, but the database server it does have access to has cross-server querying access to all the servers (hence another reason to use SPs as, AFAIK, LINQ, etc can't do cross-server joins) so if I do pull table definitions from my development environment (where, obviously, I do have access to all the tables) these won't be accessible in the production environment.

I could either create a flattened dataset of all the data then read through it, manually detecting the grouping changes (Shipment Number, OrderNumber) and then write my code accordingly, but then this doesn't make use of OOP and seems a large step backwards, plus it doesn't supply a reusable object for other, future, requirements.  Instead, I could write code to go through the datasets and load the data manually into these objects but I figure why reinvent the wheel - surely this isn't an unusual requirement and there must be a way to do this?

Thanks - MH

答:
How, if it is possible, can I load
  this data, from a stored procedure(s),
  into this structure of objects using
  LINQ, EF, or something else without
  having to base my classes on database
  tables?

Do I understand correctly that you want stored procedure to materialize result set for you and make connection among objects without mapping objects in entity data model? In such case the answer is no, it is not possible.

The Translate method uses mapping information so it cannot translate result sets into custom information. Automatic wiring of related objects works only if objects are tracked by the context => they must be mapped entities.

Default stored procedure mapping in EF can use only flatten hierarchy where columns from result set are mapped to properties in target objects. EF doesn't natively support stored procedures returning multiple result sets (Linq-to-sql does) but you can use EFExtensions to have this support (but it is more like using native ADO.NET).


问:
How can I display all files in Music Library on startup of app in UWP
I am trying to display all music files (Mp3) that is in the Music folder in Windows IoT Core on startup of the app in my ListView.

What I have at the moment is:

```<code>public MainPage()
    {
        this.InitializeComponent();
        InitGPIO();
        ListfilesAsync();
        Unloaded += MainPage_Unloaded;

    }

 private async Task ListfilesAsync()
    {
        var folderPicker = new Windows.Storage.Pickers.FolderPicker();
        folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.MusicLibrary;
        folderPicker.FileTypeFilter.Add("*.mp3");

        StorageFolder folder = await folderPicker.PickSingleFolderAsync();

        List<string> fileTypeFilter = new List<string>();
        fileTypeFilter.Add(".mp3");

        if (folder != null)
        {
            QueryOptions queryOptions = new QueryOptions(CommonFileQuery.OrderByDate, fileTypeFilter);
            StorageFileQueryResult results = folder.CreateFileQueryWithOptions(queryOptions);
            IReadOnlyList<StorageFile> sortedFiles = await results.GetFilesAsync();
            foreach (StorageFile item in sortedFiles)
            {
                AudioFilesLV.Items.Add(item.Path.ToString());
            }
        }
    }
</code>```

The app starts with no errors but there is nothing displayed in the ListView?

Not sure if it is being initialized correctly or there is fault with my code?

Thanks

答:
FolderPicker and FolderOpenPicker can not work on Windows IoT Core. You can use KnownFolders.MusicLibrary to list the file in music library.

```<code>            var files = await Windows.Storage.KnownFolders.MusicLibrary.GetFilesAsync();
            foreach (StorageFile item in files)
            {
                AudioFilesLV.Items.Add(item.Path.ToString());
            }
</code>```

Please note that, you need to specify the Music Library capability in Package.appxmanifest.

```<code>  <Capabilities>
    <uap:Capability Name="musicLibrary"/>
  </Capabilities>
</code>```

Body:
I am trying to display all music files (Mp3) that is in the Music folder in Windows IoT Core on startup of the app in my ListView.

What I have at the moment is:

public MainPage()
    {
        this.InitializeComponent();
        InitGPIO();
        ListfilesAsync();
        Unloaded += MainPage_Unloaded;

    }

 private async Task ListfilesAsync()
    {
        var folderPicker = new Windows.Storage.Pickers.FolderPicker();
        folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.MusicLibrary;
        folderPicker.FileTypeFilter.Add("*.mp3");

        StorageFolder folder = await folderPicker.PickSingleFolderAsync();

        List<string> fileTypeFilter = new List<string>();
        fileTypeFilter.Add(".mp3");

        if (folder != null)
        {
            QueryOptions queryOptions = new QueryOptions(CommonFileQuery.OrderByDate, fileTypeFilter);
            StorageFileQueryResult results = folder.CreateFileQueryWithOptions(queryOptions);
            IReadOnlyList<StorageFile> sortedFiles = await results.GetFilesAsync();
            foreach (StorageFile item in sortedFiles)
            {
                AudioFilesLV.Items.Add(item.Path.ToString());
            }
        }
    }

The app starts with no errors but there is nothing displayed in the ListView?

Not sure if it is being initialized correctly or there is fault with my code?

Thanks

Body:
FolderPicker and FolderOpenPicker can not work on Windows IoT Core. You can use KnownFolders.MusicLibrary to list the file in music library.

            var files = await Windows.Storage.KnownFolders.MusicLibrary.GetFilesAsync();
            foreach (StorageFile item in files)
            {
                AudioFilesLV.Items.Add(item.Path.ToString());
            }

Please note that, you need to specify the Music Library capability in Package.appxmanifest.

  <Capabilities>
    <uap:Capability Name="musicLibrary"/>
  </Capabilities>


问:
How to display the firebase array in the list view in flutter

```<code>Future<List<DocumentSnapshot>> getData() async {
    var firestore = Firestore.instance;
    QuerySnapshot qn = await firestore
        .collection("UserTransactions")
        .where("AuthUserId", isEqualTo: userId)
        .getDocuments();
    return qn.documents;
}
</code>```

Here I am getting all the documents according to the id, I want to display the transactions which is an array in the List View

```<code>FutureBuilder(
    future: getData(),
    builder: (_, AsyncSnapshot<List<DocumentSnapshot>> snapshot) {
        return ListView.builder(
            itemCount: snapshot.data.length,
            itemBuilder: (_, index) {
                return Text(snapshot.data[index].data["transactions"][index]["Mode"])
            })
    }
);
</code>```

I am getting the error:

```<code>The getter 'length' was called on null.
Receiver: null
Tried calling: length
</code>```

How to display those values and also display nothing if the array is blank?

答:
You need to check if data is retrieved all not:

```<code> FutureBuilder(
    future: getData(),
    builder: (_, AsyncSnapshot<List<DocumentSnapshot>> snapshot) {
             if(snapshot.hasData){
             return ListView.builder(
                       itemCount: snapshot.data.length,
                       itemBuilder: (_, index) {
                       return Text(snapshot.data[index].data["transactions"][index]["Mode"])
                       }
           return CircularProgressIndicator();
        }
  )
</code>```

Use snapshot.hasData to check if the data is retrieved and CircularProgressIndicator which will display a loading icon until data is fully retrieved.

Body:
Future<List<DocumentSnapshot>> getData() async {
    var firestore = Firestore.instance;
    QuerySnapshot qn = await firestore
        .collection("UserTransactions")
        .where("AuthUserId", isEqualTo: userId)
        .getDocuments();
    return qn.documents;
}

Here I am getting all the documents according to the id, I want to display the transactions which is an array in the List View

FutureBuilder(
    future: getData(),
    builder: (_, AsyncSnapshot<List<DocumentSnapshot>> snapshot) {
        return ListView.builder(
            itemCount: snapshot.data.length,
            itemBuilder: (_, index) {
                return Text(snapshot.data[index].data["transactions"][index]["Mode"])
            })
    }
);

I am getting the error:

The getter 'length' was called on null.
Receiver: null
Tried calling: length

How to display those values and also display nothing if the array is blank?

Body:
You need to check if data is retrieved all not:

 FutureBuilder(
    future: getData(),
    builder: (_, AsyncSnapshot<List<DocumentSnapshot>> snapshot) {
             if(snapshot.hasData){
             return ListView.builder(
                       itemCount: snapshot.data.length,
                       itemBuilder: (_, index) {
                       return Text(snapshot.data[index].data["transactions"][index]["Mode"])
                       }
           return CircularProgressIndicator();
        }
  )

Use snapshot.hasData to check if the data is retrieved and CircularProgressIndicator which will display a loading icon until data is fully retrieved.


问:
How to remove UIWebView component completely in current project?
when submitting my latest build, Apple has a response with this warning.

ITMS-90809: Deprecated API Usage - Apple will stop accepting
  submissions of apps that use UIWebView APIs . See
  https://developer.apple.com/documentation/uikit/uiwebview for more
  information.

Fyi,

I already migrate all UIWebView component to the WKWebView component in my project based on Apple recommendation.

I tried grep -r UIWebView . and grep -r UIWebView /Path/To/Project/* to cleared all UIWeview in Project.

but Apple still response with the same warning.

Is there any ways to search for any UIWebView element that still attached to my project? Kindly suggest.

答:
Remove UniWebView package reference from Manifest file
and also update unity ads to latest version</p>


问:
Node red: how to make inject fire at given seconds per minute
Is it possible to make an inject node that fires every 5 seconds, but not depending on deployment, instead in a fixed time grid.

For example, an inject node with a 5 second interval would fire at  hh:mm:08, hh:mm:13, hh:mm:18 etc. when deployed at hh:mm:03.

Is there a way to delay it so that messages are sent exactly(*) at hh:mm:05, hh:mm:10, hh:mm:15 no matter in which second it was deployed?

A possible solution would be to set the repeat interval to 1 second, and use a function node to only pass the appropriate messages (i.e. the first message arriving after a multiple-of-5secs-timestamp), but maybe there is a better way to archive that.

(*) within the limits of the machine, of course

Edit: Description of what the flow actually does, as requested. This timer is used in a datalogger for environmental monitoring (air quality, water quality, meteorology). To make this datalogger compatible with an older system, we have to apply the same timing constraints.

答: node-red-contrib-interval-multiples-timer does exactly what you want. It injects a message in a configurable interval. This interval is fixed on the mentioned timegrid, so e.g. it will always fire at the first second of each minute. https://flows.nodered.org/node/node-red-contrib-interval-multiples-timer</p>


问:
Find the Last Cell Value of the 2nd Column Set for each 1st Column Cell in EXCEL
I have the following structured table in excel where 1000s of rows included.

I want to return the Last Cell Value of Column B for Each value in Column A.

For example:

For Cell A1 -> I want to return the Cell B5.

For Cell A6 -> I want to return the Cell B9.

I have tried with VLOOKUP, HLOOKUP, INDEX likewise so many formulas where I ended with more conflict situations. Can anyone please write down a Formula to give my requirement a life?

答:
If you won't use Array formula you can Use this solution:
like this image:

use column C as helper with this formula in first cell =OFFSET(A1;SUMPRODUCT(MAX(($A$1:$A1<>"")*(ROW($A$1:$A1))))-ROW(A1);0)

and use this formula in column D's first cell =IF(A1="";"";INDEX($B$1:$B$13;SUMPRODUCT(MAX((ROW($A$1:$A$13))*($C$1:$C$13=A1)))))

and copy fill-down to all cells.


问:
Can my docker image connect with a database running on same machine without network configuration?
I have created a docker image of my web application. I have a cassandra database running on my laptop and I am starting the container of my web application from the same laptop. The uri to connect to database is localhost:9042. However, the image is not able to connect with the database. Do I need to do some network configuration for the container to connect to the database?

```<code>[trace] CassandraRepositoryComponents - database will connect using parameters uri: cassandra://localhost:9042/, cluster name: myCluster
[trace] s.d.c.CassandraConnectionUri - created logger Logger[services.db.cassandra.CassandraConnectionUri]
[trace] s.d.c.CassandraConnectionManagementService - creating session with uri CassandraConnectionUri(cassandra://localhost:9042/) and cluster name myCluster
[trace] s.d.c.CassandraConnectionManagementService - exception in connecting with database com.datastax.driver.core.exceptions.NoHostAvailableException: All host(s) tried for query failed (tried: localhost/127.0.0.1:9042 (com.datastax.driver.core.exceptions.TransportException: [localhost/127.0.0.1:9042] Cannot connect))
Oops, cannot start the server.
</code>```

docker file

```<code>FROM openjdk:8
RUN mkdir deploy
WORKDIR deploy
COPY target/universal/myapp-1.0.zip .

COPY conf/logback_dev.xml ./logback.xml
COPY conf/application_dev.conf ./application.conf
RUN unzip myapp-1.0.zip
RUN chmod +x myapp-1.0/bin/myapp
EXPOSE 9000
ENTRYPOINT myapp-1.0/bin/myapp -Dplay.http.secret.key=changemeplease -Dlogger.file=/deploy/logback.xml -Dconfig.file=/deploy/application.conf
</code>```

Cassandra is running as a standalone application

答:
referring to From inside of a Docker container, how do I connect to the localhost of the machine?, I changed the uri string to connect to Cassandra to cassandra://host.docker.internal:9042/. And the application is up now!!!

Also, it seems that host.docker.internal maps to the ip address of main network interface. When I tried to run cqlsh (in another experiment of running cassandra as well via docker - Unable to start Cassandra docker image on Win10 Home), I noticed this.

```<code>C:\Users\manuc>cqlsh host.docker.internal 9042
Connection error: ('Unable to connect to any servers', {'192.168.1.12': error(10061, "Tried connecting to [('192.168.1.12', 9042)]. Last error: No connection could be made because the target machine actively refused it")})
</code>```

Also,
ping host.docker.internal

```<code>Pinging host.docker.internal [192.168.1.12] with 32 bytes of data:
Reply from 192.168.1.12: bytes=32 time<1ms TTL=128
Reply from 192.168.1.12: bytes=32 time<1ms TTL=128
Reply from 192.168.1.12: bytes=32 time<1ms TTL=128
Reply from 192.168.1.12: bytes=32 time<1ms TTL=128
</code>```

This domain is configured when docker gets installed in etc/hosts in windows

```<code># Added by Docker Desktop
192.168.1.12 host.docker.internal
192.168.1.12 gateway.docker.internal
# To allow the same kube context to work on the host and the container:
127.0.0.1 kubernetes.docker.internal
# End of section
</code>```

Body:
I have created a docker image of my web application. I have a cassandra database running on my laptop and I am starting the container of my web application from the same laptop. The uri to connect to database is localhost:9042. However, the image is not able to connect with the database. Do I need to do some network configuration for the container to connect to the database?

[trace] CassandraRepositoryComponents - database will connect using parameters uri: cassandra://localhost:9042/, cluster name: myCluster
[trace] s.d.c.CassandraConnectionUri - created logger Logger[services.db.cassandra.CassandraConnectionUri]
[trace] s.d.c.CassandraConnectionManagementService - creating session with uri CassandraConnectionUri(cassandra://localhost:9042/) and cluster name myCluster
[trace] s.d.c.CassandraConnectionManagementService - exception in connecting with database com.datastax.driver.core.exceptions.NoHostAvailableException: All host(s) tried for query failed (tried: localhost/127.0.0.1:9042 (com.datastax.driver.core.exceptions.TransportException: [localhost/127.0.0.1:9042] Cannot connect))
Oops, cannot start the server.

docker file

FROM openjdk:8
RUN mkdir deploy
WORKDIR deploy
COPY target/universal/myapp-1.0.zip .

COPY conf/logback_dev.xml ./logback.xml
COPY conf/application_dev.conf ./application.conf
RUN unzip myapp-1.0.zip
RUN chmod +x myapp-1.0/bin/myapp
EXPOSE 9000
ENTRYPOINT myapp-1.0/bin/myapp -Dplay.http.secret.key=changemeplease -Dlogger.file=/deploy/logback.xml -Dconfig.file=/deploy/application.conf

Cassandra is running as a standalone application

Body:
referring to From inside of a Docker container, how do I connect to the localhost of the machine?, I changed the uri string to connect to Cassandra to cassandra://host.docker.internal:9042/. And the application is up now!!!

Also, it seems that host.docker.internal maps to the ip address of main network interface. When I tried to run cqlsh (in another experiment of running cassandra as well via docker - Unable to start Cassandra docker image on Win10 Home), I noticed this.

C:\Users\manuc>cqlsh host.docker.internal 9042
Connection error: ('Unable to connect to any servers', {'192.168.1.12': error(10061, "Tried connecting to [('192.168.1.12', 9042)]. Last error: No connection could be made because the target machine actively refused it")})

Also,
ping host.docker.internal

Pinging host.docker.internal [192.168.1.12] with 32 bytes of data:
Reply from 192.168.1.12: bytes=32 time<1ms TTL=128
Reply from 192.168.1.12: bytes=32 time<1ms TTL=128
Reply from 192.168.1.12: bytes=32 time<1ms TTL=128
Reply from 192.168.1.12: bytes=32 time<1ms TTL=128

This domain is configured when docker gets installed in etc/hosts in windows

# Added by Docker Desktop
192.168.1.12 host.docker.internal
192.168.1.12 gateway.docker.internal
# To allow the same kube context to work on the host and the container:
127.0.0.1 kubernetes.docker.internal
# End of section


问:
How to add SDK files manually that needs a package.xml in android studio?
I have just installed Android studio and it needs to download some SDK files. But my internet connection is slow and the download keeps failing.

so I took the links and downloaded all SDK files manually with my download manager and then I unzipped them and put them in SDK path which in my case is:

C:\Users\USERNAME\AppData\Local\Android\Sdk

the problem is when I open Android studio it still downloads these SDK files. I don't know how to tell android studio that these files are already downloaded. Can anyone solve this?
Android Studio that I am using is version 4.0.0.

Check the images for more information:

And when I click the edit:

And after clicking next:

答:
Android SDK >>  Android SDK location >> Edit >>(C:\Users\USERNAME\AppData\Local\Android\Sdk)

then click Apply >> Ok


问:
How to speed up Get-ChildItem in Powershell
Just wandering how could I speed up the Get-ChildItem in Powershell?

I have the following script to search for a file that created by today and copy it over to another folder.

```<code>$fromDirectory = "test_file_*.txt"
$fromDirectory = "c:\sour\"
$toDirectory = "c:\test\"

Get-ChildItem $fromDirectory -Include $fileName -Recurse | Where {$_.LastWriteTime -gt (Get-Date).Date} | Copy-Item -Destination $toDirectory
</code>```

Due to the folder that I search have 124,553 history files, it's take me age for the search. Does any know how could I improve my script to speed up my search and copy?

答:
Here are some things to try:

First, use Measure-Command {} to get the actual performance:

```<code>Measure-Command { Get-ChildItem $fromDirectory -Include $fileName -Recurse | Where {$_.LastWriteTime -gt (Get-Date).Date} | Copy-Item -Destination $toDirectory }
</code>```

Then, consider removing the '-Recurse' flag, because this is actually going inside every directory and child and child of child.  If your target log files are really that scattered, then...

Try using robocopy to match a pattern in the filename and lastwritetime, then use powershell to copy over.  You could even use robocopy to do the copying.

It's possible that you just have a huge, slow problem to solve, but try these to see if you can break it down.

Body:
Just wandering how could I speed up the Get-ChildItem in Powershell?

I have the following script to search for a file that created by today and copy it over to another folder.

$fromDirectory = "test_file_*.txt"
$fromDirectory = "c:\sour\"
$toDirectory = "c:\test\"

Get-ChildItem $fromDirectory -Include $fileName -Recurse | Where {$_.LastWriteTime -gt (Get-Date).Date} | Copy-Item -Destination $toDirectory

Due to the folder that I search have 124,553 history files, it's take me age for the search. Does any know how could I improve my script to speed up my search and copy?

Body:
Here are some things to try:

First, use Measure-Command {} to get the actual performance:

Measure-Command { Get-ChildItem $fromDirectory -Include $fileName -Recurse | Where {$_.LastWriteTime -gt (Get-Date).Date} | Copy-Item -Destination $toDirectory }

Then, consider removing the '-Recurse' flag, because this is actually going inside every directory and child and child of child.  If your target log files are really that scattered, then...

Try using robocopy to match a pattern in the filename and lastwritetime, then use powershell to copy over.  You could even use robocopy to do the copying.

It's possible that you just have a huge, slow problem to solve, but try these to see if you can break it down.


问:
How to hide aliases from help screen in a cobra app
Is it possible to suppress Aliases to show up in the help screen of a golang cobra app? I basically would like to get rid of the whole "Aliases" section below:

```<code>Usage:
  my-app [flags]

Aliases:
 alias1 , alias2

Flags:
  -h, --help              help for this command
</code>```

I know it's possible to hide flags from showing up in help (cmd.Flags().MarkHidden("myflag")). Is it somehow possible to hide Aliases as well?

答:
use custom Usage template, just remove alias part

```<code>customUsageTpl:=`Usage:{{if .Runnable}}
  {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}
  {{.CommandPath}} [command]{{end}}{{if .HasExample}}
Examples:
{{.Example}}{{end}}{{if .HasAvailableSubCommands}}
Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
  {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}
Flags:
{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}
Global Flags:
{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}
Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}
  {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}
`
</code>```

Then set custom template

```<code>cmd.SetUsageTemplate(customUsageTpl)
</code>```

Body:
Is it possible to suppress Aliases to show up in the help screen of a golang cobra app? I basically would like to get rid of the whole "Aliases" section below:

Usage:
  my-app [flags]

Aliases:
 alias1 , alias2

Flags:
  -h, --help              help for this command

I know it's possible to hide flags from showing up in help (cmd.Flags().MarkHidden("myflag")). Is it somehow possible to hide Aliases as well?

Body:
use custom Usage template, just remove alias part

customUsageTpl:=`Usage:{{if .Runnable}}
  {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}
  {{.CommandPath}} [command]{{end}}{{if .HasExample}}
Examples:
{{.Example}}{{end}}{{if .HasAvailableSubCommands}}
Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
  {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}
Flags:
{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}
Global Flags:
{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}
Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}
  {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}
`

Then set custom template

cmd.SetUsageTemplate(customUsageTpl)


问:
EF Add-Migration: connection string issue using app.config
I am trying to learn something about EF step by step by I'm stucked on this since this morning :-|
If I try "Add-Migration" with the follow all works well

```<code>    public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
         => options.UseSqlServer(@"Server=MyServer;Database=MyDb;User Id=MyUser;Password=MyPsw");
}
</code>```

But I tried to move the connection string to app.config and modify the above code as follow:

```<code> public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
         => options.UseSqlServer(ConfigurationManager.ConnectionStrings["db"].ConnectionString);
}
</code>```

I also added "using System.Configuration;"

App.Config:

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

  <connectionStrings>
    <add name="db"
         providerName="System.Data.SqlClient"
         connectionString="Server=MyServer;Database=MyDb;User Id=MyUser;Password=MyPsw"/>
  </connectionStrings>

</configuration>
</code>```

But in that case it doesn't work and when I try the "Add-Migration" the operation fails and in the PMC appears "Object reference not set to an instance of an object.". What could the problem be?

(I know storing User/psw in app.config is not good, this will be next step to improve...)

Thanks in advance.

答:
Here is how i got the ConnectionString. Not sure if this is working for you.

App.config

```<code><connectionStrings>
<add name="con" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=PRWSolution2020;Integrated Security=True" providerName="System.Data.SqlClient"/>
</code>```

DBContext

```<code>public DbSet<Machine> Machines { get; set; }
    public DbSet<User> Users { get; set; }
    public DbSet<ContractDetail> ContractDetails { get; set; }
    public DbSet<TimeSheet> TimeSheets { get; set; }
    public DbSet<MachineClient> MachineClients { get; set; }
    public DbSet<ServiceReport> ServiceReports { get; set; }

    public PRWContext()
        : base("name=con")
    {

    }
</code>```

Body:
I am trying to learn something about EF step by step by I'm stucked on this since this morning :-|
If I try "Add-Migration" with the follow all works well

    public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
         => options.UseSqlServer(@"Server=MyServer;Database=MyDb;User Id=MyUser;Password=MyPsw");
}

But I tried to move the connection string to app.config and modify the above code as follow:

 public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
         => options.UseSqlServer(ConfigurationManager.ConnectionStrings["db"].ConnectionString);
}

I also added "using System.Configuration;"

App.Config:

    <?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <connectionStrings>
    <add name="db"
         providerName="System.Data.SqlClient"
         connectionString="Server=MyServer;Database=MyDb;User Id=MyUser;Password=MyPsw"/>
  </connectionStrings>

</configuration>

But in that case it doesn't work and when I try the "Add-Migration" the operation fails and in the PMC appears "Object reference not set to an instance of an object.". What could the problem be?

(I know storing User/psw in app.config is not good, this will be next step to improve...)

Thanks in advance.

Body:
Here is how i got the ConnectionString. Not sure if this is working for you.

App.config

<connectionStrings>
<add name="con" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=PRWSolution2020;Integrated Security=True" providerName="System.Data.SqlClient"/>

DBContext

public DbSet<Machine> Machines { get; set; }
    public DbSet<User> Users { get; set; }
    public DbSet<ContractDetail> ContractDetails { get; set; }
    public DbSet<TimeSheet> TimeSheets { get; set; }
    public DbSet<MachineClient> MachineClients { get; set; }
    public DbSet<ServiceReport> ServiceReports { get; set; }

    public PRWContext()
        : base("name=con")
    {

    }


问:
Mooc Helsinki Part 1 Week 4 Exercise 18 Java
The program described here should be implemented in the class PersonalInformationCollection. NB! Do not modify the class PersonalInformation.

After the user has entered the last set of details (they enter an empty first name), exit the repeat statement.

Then print the collected personal information so that each entered object is printed in the following format: first and last names separated by a space (you don't print the identification number). An example of the working program is given below:

```<code>Sample output
First name: Jean
Last name: Bartik
Identification number: 271224
First name: Betty
Last name: Holberton
Identification number: 070317
First name:

Jean Bartik
Betty Holberton
</code>```

The PersonalInformation class:

```<code>public class PersonalInformation {

    private String firstName;
    private String lastName;
    private String identificationNumber;

    public PersonalInformation(String firstName, String lastName, String identificationNumber) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.identificationNumber = identificationNumber;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public String getIdentificationNumber() {
        return identificationNumber;
    }

    @Override
    public String toString() {
        return this.lastName + ", " + this.firstName + " (" + this.identificationNumber + ")";
    }
}
</code>```

My solution which I can only print all values instead of only Firstnames and the Lastnames from the array:

```<code>public class Main {

    public static void main(String[] args) {
        // write your code here
        Scanner scanner = new Scanner(System.in);
        ArrayList<PersonalInformation> infoCollection = new ArrayList<>();

        while (true) {
            System.out.println("First name: ");
            String firstName = scanner.nextLine();
            if (firstName.equals("")) {
                break;
            }
            System.out.println("Last name: ");
            String lastName = scanner.nextLine();
            System.out.println("Identification number: ");
            String identificationNumber = scanner.nextLine();

            infoCollection.add(new PersonalInformation(firstName, lastName, identificationNumber));

        }
        System.out.println(infoCollection);

    }

}
</code>```

I need to modify the code. I am a beginner, an explanatory suggestion would be much appreciated.

答:
```<code>public class Main {

    public static void main(String[] args) {
        // write your code here
        ArrayList<PersonalInformation> infoCollection = new ArrayList<>();
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("First name: ");
            String firstName = scanner.nextLine();
            if (firstName.equals("")) {
                break;
            }
            System.out.println("Last name: ");
            String lastName = scanner.nextLine();
            System.out.println("Identification number: ");
            String identificationNumber = scanner.nextLine();
            infoCollection.add(new PersonalInformation(firstName, lastName, identificationNumber));

        }
        for (int i = 0; i < infoCollection.size(); i++) {
            System.out.println(infoCollection.get(i).getFirstName() + " "
                    + infoCollection.get(i).getLastName());
        }

    }
}
</code>```

Body:
The program described here should be implemented in the class PersonalInformationCollection. NB! Do not modify the class PersonalInformation.

After the user has entered the last set of details (they enter an empty first name), exit the repeat statement.

Then print the collected personal information so that each entered object is printed in the following format: first and last names separated by a space (you don't print the identification number). An example of the working program is given below:

Sample output
First name: Jean
Last name: Bartik
Identification number: 271224
First name: Betty
Last name: Holberton
Identification number: 070317
First name:

Jean Bartik
Betty Holberton

The PersonalInformation class:

public class PersonalInformation {

    private String firstName;
    private String lastName;
    private String identificationNumber;

    public PersonalInformation(String firstName, String lastName, String identificationNumber) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.identificationNumber = identificationNumber;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public String getIdentificationNumber() {
        return identificationNumber;
    }

    @Override
    public String toString() {
        return this.lastName + ", " + this.firstName + " (" + this.identificationNumber + ")";
    }
}

My solution which I can only print all values instead of only Firstnames and the Lastnames from the array:

public class Main {

    public static void main(String[] args) {
        // write your code here
        Scanner scanner = new Scanner(System.in);
        ArrayList<PersonalInformation> infoCollection = new ArrayList<>();

        while (true) {
            System.out.println("First name: ");
            String firstName = scanner.nextLine();
            if (firstName.equals("")) {
                break;
            }
            System.out.println("Last name: ");
            String lastName = scanner.nextLine();
            System.out.println("Identification number: ");
            String identificationNumber = scanner.nextLine();

            infoCollection.add(new PersonalInformation(firstName, lastName, identificationNumber));

        }
        System.out.println(infoCollection);

    }

}

I need to modify the code. I am a beginner, an explanatory suggestion would be much appreciated.


问:
Get latest ID in Django returns object is not iterable
I tried to get the latest id in Django but get the error. </p>

```<code>def getlatestid(request):
    cot_info = COT.objects.latest('id')
    return JsonResponse({"data": list(cot_info)})

TypeError: 'COT' object is not iterable
</code>```

答:
latest(...) returns an object, not a list. So, you can try like this to fix the error:

```<code>def getlatestid(request):
    cot_info = COT.objects.values().latest('id')
    return JsonResponse({"data": cot_info})
</code>```

Body:
I tried to get the latest id in Django but get the error.

def getlatestid(request):
    cot_info = COT.objects.latest('id')
    return JsonResponse({"data": list(cot_info)})

TypeError: 'COT' object is not iterable

Body:
latest(...) returns an object, not a list. So, you can try like this to fix the error:

def getlatestid(request):
    cot_info = COT.objects.values().latest('id')
    return JsonResponse({"data": cot_info})


问:
LINQ to XML - Elements() works but Elements(XName) does not work
Given below is my xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<Report xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner" xmlns="http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition">
    <Body>
        <ReportItems>
            <Textbox Name="txtCurrentDate">
                <CanGrow>true</CanGrow>
                <KeepTogether>true</KeepTogether>
                <Paragraphs>
                    <Paragraph>
                        <TextRuns>
                            <TextRun>
                                <Value>=Today()</Value>
                                <Style>
                                    <FontWeight>Medium</FontWeight>
                                    <Format>d</Format>
                                </Style>
                            </TextRun>
                        </TextRuns>
                        <Style>
                            <TextAlign>Left</TextAlign>
                        </Style>
                    </Paragraph>
                </Paragraphs>
                <Left>0.36958in</Left>
                <Height>0.22917in</Height>
                <Width>1in</Width>
                <Style>
                    <Border>
                        <Style>None</Style>
                    </Border>
                    <PaddingLeft>2pt</PaddingLeft>
                    <PaddingRight>2pt</PaddingRight>
                    <PaddingTop>2pt</PaddingTop>
                    <PaddingBottom>2pt</PaddingBottom>
                </Style>
            </Textbox>
            <Textbox Name="txtName">
                <CanGrow>true</CanGrow>
                <KeepTogether>true</KeepTogether>
                <Paragraphs>
                    <Paragraph>
                        <TextRuns>
                            <TextRun>
                                <Value>Mark Wilkinson</Value>
                                <Style />
                            </TextRun>
                        </TextRuns>
                        <Style />
                    </Paragraph>
                </Paragraphs>
                <Top>0.22917in</Top>
                <Left>0.36958in</Left>
                <Height>0.20833in</Height>
                <Width>3.22917in</Width>
                <ZIndex>1</ZIndex>
                <Style>
                    <Border>
                        <Style>None</Style>
                    </Border>
                    <PaddingLeft>2pt</PaddingLeft>
                    <PaddingRight>2pt</PaddingRight>
                    <PaddingTop>2pt</PaddingTop>
                    <PaddingBottom>2pt</PaddingBottom>
                </Style>
            </Textbox>
        </ReportItems>
        <Height>6.01667in</Height>
        <Style />
    </Body>
    <Width>7.92333in</Width>
</Report>
</code>```

I want to get all the Textbox names and values. This is what I tried and it does not work:

```<code>XDocument data = XDocument.Load("..\\..\\testxml.rdl");

            var elements = from c in data.Elements("ReportItems")
                           select c;
            foreach (var element in elements)
            {
                Console.WriteLine("Element : " + element.Attribute("Name").Value);

            }
            Console.ReadKey();
</code>```

but when I change the query to something like this

```<code>var elements = from c in data.Elements().Elements().ElementAt(0).Elements().ElementAt(0).Elements()
                           select c;
</code>```

it works.

Any help in this regard is much appreciated.

Edit: With the help of answers I was able to get the desired results. Thank you so much :)

```<code>XDocument data = XDocument.Load("..\\..\\testxml.rdl");
            XNamespace ns = data.Root.Name.Namespace;
            var elements = from c in data.Descendants(ns + "Textbox")
                           select c;
            foreach (var element in elements)
            {
                Console.WriteLine("Element : " + element.Attribute("Name").Value);
            }
            Console.ReadKey();
</code>```

TIA.

Raja

答:
You need to take the namespace into account:

```<code>XNamespace df = data.Root.Name.Namespace;
</code>```

Then use df + "foo" to select elements with local name foo in the namespace defined on the root element.

And as already mentioned you probably want to select descendants, not child elements:

```<code>        var elements = from c in data.Descendants(df + "Textbox")
                       select c;
</code>```

Body:
Given below is my xml:

<?xml version="1.0" encoding="utf-8"?>
<Report xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner" xmlns="http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition">

        <ReportItems>
            <Textbox Name="txtCurrentDate">
                <CanGrow>true</CanGrow>
                <KeepTogether>true</KeepTogether>
                <Paragraphs>
                    <Paragraph>
                        <TextRuns>
                            <TextRun>
                                <Value>=Today()</Value>

                            </TextRun>
                        </TextRuns>

                    </Paragraph>
                </Paragraphs>
                <Left>0.36958in</Left>
                <Height>0.22917in</Height>
                <Width>1in</Width>

                    </Border>
                    <PaddingLeft>2pt</PaddingLeft>
                    <PaddingRight>2pt</PaddingRight>
                    <PaddingTop>2pt</PaddingTop>
                    <PaddingBottom>2pt</PaddingBottom>
                </Style>
            </Textbox>
            <Textbox Name="txtName">
                <CanGrow>true</CanGrow>
                <KeepTogether>true</KeepTogether>
                <Paragraphs>
                    <Paragraph>
                        <TextRuns>
                            <TextRun>
                                <Value>Mark Wilkinson</Value>

                    </Border>
                    <PaddingLeft>2pt</PaddingLeft>
                    <PaddingRight>2pt</PaddingRight>
                    <PaddingTop>2pt</PaddingTop>
                    <PaddingBottom>2pt</PaddingBottom>
                </Style>
            </Textbox>
        </ReportItems>
        <Height>6.01667in</Height>

Body:
You need to take the namespace into account:

XNamespace df = data.Root.Name.Namespace;

Then use df + "foo" to select elements with local name foo in the namespace defined on the root element.

And as already mentioned you probably want to select descendants, not child elements:

        var elements = from c in data.Descendants(df + "Textbox")
                       select c;


问:
curl: (60) SSL certificate problem: self signed certificate
I would like to install nvm on my Linux computer.
(My Debian version is 10.)

I read this document https://github.com/nvm-sh/nvm#install--update-script
and I input this script.

```<code>curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash
</code>```

This is the result.

```<code> % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
curl: (60) SSL certificate problem: self signed certificate in certificate chain
More details here: https://curl.haxx.se/docs/sslcerts.html

curl failed to verify the legitimacy of the server and therefore could not
establish a secure connection to it. To learn more about this situation and
how to fix it, please visit the web page mentioned above.
</code>```

I read this document https://curl.haxx.se/docs/sslcerts.html but I could not understand what to do. Therefore, I searched the Internet and found that I need proxy configuration.

```<code>export http_proxy="http://webfilter.**********.com:8000/"
export https_proxy="http://webfilter.**********.com:8000/"
</code>```

I entered these commands in my terminal and tried this script again.

```<code>curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash
</code>```

Then I get the same result.

```<code>  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
curl: (60) SSL certificate problem: self signed certificate in certificate chain
More details here: https://curl.haxx.se/docs/sslcerts.html

curl failed to verify the legitimacy of the server and therefore could not
establish a secure connection to it. To learn more about this situation and
how to fix it, please visit the web page mentioned above.
</code>```

How can can I resolve this problem?

答:
found that I need proxy configuration.

Check first if you did need any proxy before that call.

For instance (without proxy exported):

```<code>curl -Is http://www.google.com | head -1 | grep 200; if [[ $? -eq 0 ]]; then; echo "Online"; else; echo "Offline"; fi
</code>```

If that works, then the issue is different.

If not, try again with your proxy in place.

Body:
I would like to install nvm on my Linux computer.
(My Debian version is 10.)

I read this document https://github.com/nvm-sh/nvm#install--update-script
and I input this script.

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash

This is the result.

 % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
curl: (60) SSL certificate problem: self signed certificate in certificate chain
More details here: https://curl.haxx.se/docs/sslcerts.html

curl failed to verify the legitimacy of the server and therefore could not
establish a secure connection to it. To learn more about this situation and
how to fix it, please visit the web page mentioned above.

I read this document https://curl.haxx.se/docs/sslcerts.html but I could not understand what to do. Therefore, I searched the Internet and found that I need proxy configuration.

export http_proxy="http://webfilter.**********.com:8000/"
export https_proxy="http://webfilter.**********.com:8000/"

I entered these commands in my terminal and tried this script again.

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash

Then I get the same result.

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
curl: (60) SSL certificate problem: self signed certificate in certificate chain
More details here: https://curl.haxx.se/docs/sslcerts.html

curl failed to verify the legitimacy of the server and therefore could not
establish a secure connection to it. To learn more about this situation and
how to fix it, please visit the web page mentioned above.

How can can I resolve this problem?

Body:
found that I need proxy configuration.

Check first if you did need any proxy before that call.

For instance (without proxy exported):

curl -Is http://www.google.com | head -1 | grep 200; if [[ $? -eq 0 ]]; then; echo "Online"; else; echo "Offline"; fi

If that works, then the issue is different.

If not, try again with your proxy in place.


问:
Handling Optional field search in Elasticsearch
I'm using ES 5.5 and having a query dsl with javasript API request like this

```<code>client.search({
  index: 'demo',
  type: 'sample',
  body: {
    "query": {
      "bool": {
        "must": [
          {
            "match": {
              "CityName": {
                query: req.params.city,
                slop: 100
              }
            }
          },
          {
            "match": {
              "StateName": {
                query: req.params.state,
                slop: 100
              }
            },
            {
              "match": {
                "Code": {
                  query: req.params.code,
                  slop: 100
                }
              }
            }
          ]
        }
      }
    }
  })
</code>```

This query works fine when user gives all three values.But In my case these three parameters are not mandatory.Either user can give one value or more than one value and given fields must match the documents.Searching with one or two values doesn't return anything.

答:
You need to replace the must with should. refer boolean query for more details

```<code>client.search({
  index: 'demo',
  type: 'sample',
  body: {
    "query": {
      "bool": {
        "must": [ --> replace this `must` with `should`
          {
            "match": {
              "CityName": {
                query: req.params.city,
                slop: 100
              }
            }
          },
          {
            "match": {
              "StateName": {
                query: req.params.state,
                slop: 100
              }
            },
            {
              "match": {
                "Code": {
                  query: req.params.code,
                  slop: 100
                }
              }
            }
          ]
        }
      }
    }
  })
</code>```

Body:
I'm using ES 5.5 and having a query dsl with javasript API request like this

client.search({
  index: 'demo',
  type: 'sample',
  body: {
    "query": {
      "bool": {
        "must": [
          {
            "match": {
              "CityName": {
                query: req.params.city,
                slop: 100
              }
            }
          },
          {
            "match": {
              "StateName": {
                query: req.params.state,
                slop: 100
              }
            },
            {
              "match": {
                "Code": {
                  query: req.params.code,
                  slop: 100
                }
              }
            }
          ]
        }
      }
    }
  })

This query works fine when user gives all three values.But In my case these three parameters are not mandatory.Either user can give one value or more than one value and given fields must match the documents.Searching with one or two values doesn't return anything.

Body:
You need to replace the must with should. refer boolean query for more details

client.search({
  index: 'demo',
  type: 'sample',
  body: {
    "query": {
      "bool": {
        "must": [ --> replace this `must` with `should`
          {
            "match": {
              "CityName": {
                query: req.params.city,
                slop: 100
              }
            }
          },
          {
            "match": {
              "StateName": {
                query: req.params.state,
                slop: 100
              }
            },
            {
              "match": {
                "Code": {
                  query: req.params.code,
                  slop: 100
                }
              }
            }
          ]
        }
      }
    }
  })


问:
Integrating modal component onto page on load React JS
I have webpage with React JS.  The structure of site is MainContent.js --> Main.js -->ReactDOM render.  I wanted to have modal popup when page opens so built modal component Modal.js--> DashModal.js  which worked on its own project but not when imported to my site.

How do I import it correctly to have modal popup on load like it does on its own project?  Thanks.  I provided code below.

```<code>**Index JS**
import React from "react";
import ReactDOM from "react-dom";
import Main from "./containers/Main";
import { CookiesProvider } from "react-cookie";
import DashModal from "./components/DashModal"

// Import main sass file to apply global styles
import "./static/sass/style.scss";

ReactDOM.render(
    <CookiesProvider>
            <Main />

    </CookiesProvider>,
    document.getElementById("app")
    );

**DashModal.js - the modal component**

import React from 'react'
import ReactDOM from 'react-dom'
import Modal from "../components/modal"
import "../components/modal.css"
import AppStore from "../static/images/AppLogoBlue.png";

class DashModal extends React.Component {

    constructor(props) {
        super(props)
        this.state = {show:true}
    }

showModal = () => {
    this.setState({show: true});
};

hideModal = () => {
    this.setState({show:false});
};
render() {
    return(
        <main>
         <h1> React Modal </h1>
        <Modal show = {this.state.show} handleClose ={this.hideModal}>

           <div className = "left">
              <a>
             <img src={AppStore} alt= ""></img>
              </a>
    </div>

              <div className = "left">
                 <button className= "button" onClick={this.hideModal}>Regular site </button>
              </div>

            </div>

        </Modal>
        <button type = "button" onClick = {this.showModal}>
            open
        </button>
       </main>
    );
}

}

const container = document.createElement("div");
document.body.appendChild(container);
ReactDOM.render(<DashModal/>, container);

export default DashModal;

**modal.js- part of modal which goes into DashModal.js**
import React from 'react';
import "./modal.css"

    const Modal = ({ handleClose, show, children}) => {

    const showHideClassName = show? "modal display-block" : "modal display-none"

    return(
        <div className={showHideClassName}>
            <section style={ModalBox} className= "modal-main">
            {children}
            <button onClick={handleClose}>close</button>
            </section>

        </div>

    );

    };
export default Modal;

</code>```

Thanks in advance

答:
From my understanding, you want to open the modal by default when the <DashModal /> was imported into another component.

You can pass a prop show={true|false} to DashModal component <DashModal show={true} /> and inside that component add a componentDidMount lifecycle method

```<code>componentDidMount = () =>{
    const {show} = this.props;
    if(show){
       this.showModal()
    }
}
</code>```

This will check the props and call the showModal when the component is loaded.

Body:
I have webpage with React JS.  The structure of site is MainContent.js --> Main.js -->ReactDOM render.  I wanted to have modal popup when page opens so built modal component Modal.js--> DashModal.js  which worked on its own project but not when imported to my site.

How do I import it correctly to have modal popup on load like it does on its own project?  Thanks.  I provided code below.

**Index JS**
import React from "react";
import ReactDOM from "react-dom";
import Main from "./containers/Main";
import { CookiesProvider } from "react-cookie";
import DashModal from "./components/DashModal"

// Import main sass file to apply global styles
import "./static/sass/style.scss";

ReactDOM.render(
    <CookiesProvider>

    </CookiesProvider>,
    document.getElementById("app")
    );

**DashModal.js - the modal component**

import React from 'react'
import ReactDOM from 'react-dom'
import Modal from "../components/modal"
import "../components/modal.css"
import AppStore from "../static/images/AppLogoBlue.png";

class DashModal extends React.Component {

    constructor(props) {
        super(props)
        this.state = {show:true}
    }

showModal = () => {
    this.setState({show: true});
};

hideModal = () => {
    this.setState({show:false});
};
render() {
    return(

 React Modal

        <Modal show = {this.state.show} handleClose ={this.hideModal}>

                 <button className= "button" onClick={this.hideModal}>Regular site </button>

        </Modal>
        <button type = "button" onClick = {this.showModal}>
            open
        </button>

    );
}

}

const container = document.createElement("div");
document.body.appendChild(container);
ReactDOM.render(<DashModal/>, container);

export default DashModal;

**modal.js- part of modal which goes into DashModal.js**
import React from 'react';
import "./modal.css"

    const Modal = ({ handleClose, show, children}) => {

    const showHideClassName = show? "modal display-block" : "modal display-none"

    return(

            {children}
            <button onClick={handleClose}>close</button>

    );

    };
export default Modal;

Thanks in advance

Body:
From my understanding, you want to open the modal by default when the <DashModal /> was imported into another component.

You can pass a prop show={true|false} to DashModal component <DashModal show={true} /> and inside that component add a componentDidMount lifecycle method

componentDidMount = () =>{
    const {show} = this.props;
    if(show){
       this.showModal()
    }
}

This will check the props and call the showModal when the component is loaded.