问:
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>```

答:
First, a JPanel that wants to grab focus has to be focusable or focus traversable.
You should consider overriding isFocusTraversable to return true.

In your panel class :

```<code>@Override
public boolean isFocusTraversable()
{
  return true;
}//met
</code>```

This means your component can have focus.

Second, if you want your jpanel to* actually have the focus*, you can call his method

```<code>panel.requestFocus();
</code>```

you should do that at the beginning of the game, right after the pack/setVisible( true ); and at the end of every actionlistener that will make it loose focus (typically buttons'actionlisteners).

Regards,
 Stéphane

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

        }
     }
}

Body:
First, a JPanel that wants to grab focus has to be focusable or focus traversable.
You should consider overriding isFocusTraversable to return true.

In your panel class :

@Override
public boolean isFocusTraversable()
{
  return true;
}//met

This means your component can have focus.

Second, if you want your jpanel to* actually have the focus*, you can call his method

panel.requestFocus();

you should do that at the beginning of the game, right after the pack/setVisible( true ); and at the end of every actionlistener that will make it loose focus (typically buttons'actionlisteners).

Regards,
 Stéphane


来源: stackexchange

问:
How to get the textarea value from jQuery LineControl Editor?
I'm using this jquery plugin  to create a wysiwyg text editor,

I created a textarea where I want to display the text editor:

```<code><textarea class="editor" rows="3" name="textEditor" id="textEditor"></textarea>
</code>```

and then I called the jquery function:

```<code><script type="text/javascript">
  $(document).ready( function() {
    $("#textEditor").Editor();
  });
</script>
</code>```

Until now everything is working good, but when I wanted to know if the text is writed correctly or not by using this function:

```<code>function displayText(){
  alert($("#textEditor").val());
}
</code>```

it gives me an empty text!

What am I missing ?

答:
```<code>function displayText() {
        alert($('#txtEditor').text($('#txtEditor').Editor("getText"))[0].value);
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using this jquery plugin  to create a wysiwyg text editor,

I created a textarea where I want to display the text editor:

<textarea class="editor" rows="3" name="textEditor" id="textEditor"></textarea>

and then I called the jquery function:

Until now everything is working good, but when I wanted to know if the text is writed correctly or not by using this function:

function displayText(){
  alert($("#textEditor").val());
}

it gives me an empty text!

What am I missing ?

ContentLicense: CC BY-SA 4.0


问:
Issue with SourceTree while cloning a GitHub repository
I know that similar questions have already been posted here. However, I think my scenario is a bit different. Here is what I have.

I downloaded and installed the latest official version of the SourceTree software. Also, I have a GitHub account with permissions to clone and push the repository. In order to manage a local copy, I need to clone the online version. Here are the steps that I take:

Start the SourceTree and navigate to File -> Clone / New ...

In the opened window I paste the HTTPS clone URL. I copied it from the browser after I logged in to my GitHub account so the link is correct.

The nest step is to specify a local folder where the repository will be copied. However, when I click to enter Destination Path, the window shows an error:

```<code>This is not a valid source path / URL
</code>```

Clicking the error may give the following details:

```<code>remote: Repository not found.
fatal: repository 'https://github.com/org/repo.git/' not found
remote: Repository not found.
fatal: repository 'https://github.com/org/repo.git/' not found
</code>```

Or the details may be empty. SourceTree does not tell me the reason for the error or anything else.

I tried to re-install SourceTree but the error still exists. I asked the Administration of the GitHub repository for any other permissions but my account has all of them. I am able to push changes to the online repository using the Terminal console but I would like to use a UI (that SourceTree provides) to manage and compare changes in the code.

One think I did not try is to clone the repository using another GtHub account. However, I don't want to do that because I need to commit any changes to the repository on my behalf.

Does anybody know how can this error be fixed or worked around?

答:
The issue might be because of SourceTree didn't have all private access from Github

I have answered here please check to avoid the duplicate answer posting reference link

https://stackoverflow.com/a/62145210/4328589

Body:
I know that similar questions have already been posted here. However, I think my scenario is a bit different. Here is what I have.

I downloaded and installed the latest official version of the SourceTree software. Also, I have a GitHub account with permissions to clone and push the repository. In order to manage a local copy, I need to clone the online version. Here are the steps that I take:

Start the SourceTree and navigate to File -> Clone / New ...

In the opened window I paste the HTTPS clone URL. I copied it from the browser after I logged in to my GitHub account so the link is correct.

The nest step is to specify a local folder where the repository will be copied. However, when I click to enter Destination Path, the window shows an error:

This is not a valid source path / URL

Clicking the error may give the following details:

remote: Repository not found.
fatal: repository 'https://github.com/org/repo.git/' not found
remote: Repository not found.
fatal: repository 'https://github.com/org/repo.git/' not found

Or the details may be empty. SourceTree does not tell me the reason for the error or anything else.

I tried to re-install SourceTree but the error still exists. I asked the Administration of the GitHub repository for any other permissions but my account has all of them. I am able to push changes to the online repository using the Terminal console but I would like to use a UI (that SourceTree provides) to manage and compare changes in the code.

One think I did not try is to clone the repository using another GtHub account. However, I don't want to do that because I need to commit any changes to the repository on my behalf.

Does anybody know how can this error be fixed or worked around?


问:
Unable to create DI for retrofit with Koin, android?
I am trying to have DI for creating a retrofit instance with KOIN
this is the module

```<code>val networkModule = module {
factory { provideRetrofit(get()) }
single { provideNetworkApi(get()) }
}

fun provideRetrofit(): Retrofit {
return Retrofit.Builder()
    .baseUrl(NetworkConstant.BASE_URL)
    .addConverterFactory(MoshiConverterFactory.create())
    .client(OkHttpClient.Builder().build())
    .build()

}

fun provideNetworkApi(retrofit: Retrofit): NetworkCall =
retrofit.create(NetworkCall::class.java)
</code>```

In the application class

```<code>class BaseApp :Application() {

override fun onCreate() {
    super.onCreate()
    startKoin {
        androidLogger()
        androidContext(this@BaseApp)
        modules(listOf(prefModule,networkModule))
    }
}
}
</code>```

The compiler is showing error on provideRetrofit(get()

```<code>Too many arguments for public fun provideRetrofit():
</code>```

I was able to create DI for another class

```<code>val prefModule = module {
single { AppPreference(androidContext()) }
}
</code>```

Can someone point me whats wrong here?

答:
Was being caused because of get()

```<code>val networkModule = module {
factory { provideRetrofit() }

single { provideNetworkApi(get()) }
}
</code>```

Body:
I am trying to have DI for creating a retrofit instance with KOIN
this is the module

val networkModule = module {
factory { provideRetrofit(get()) }
single { provideNetworkApi(get()) }
}

fun provideRetrofit(): Retrofit {
return Retrofit.Builder()
    .baseUrl(NetworkConstant.BASE_URL)
    .addConverterFactory(MoshiConverterFactory.create())
    .client(OkHttpClient.Builder().build())
    .build()

}

fun provideNetworkApi(retrofit: Retrofit): NetworkCall =
retrofit.create(NetworkCall::class.java)

In the application class

class BaseApp :Application() {

override fun onCreate() {
    super.onCreate()
    startKoin {
        androidLogger()
        androidContext(this@BaseApp)
        modules(listOf(prefModule,networkModule))
    }
}
}

The compiler is showing error on provideRetrofit(get()

Too many arguments for public fun provideRetrofit():

I was able to create DI for another class

val prefModule = module {
single { AppPreference(androidContext()) }
}

Can someone point me whats wrong here?

Body:
Was being caused because of get()

val networkModule = module {
factory { provideRetrofit() }

single { provideNetworkApi(get()) }
}


问:
How to use a repository object inside a function in a ViewModel class Kotlin?
I have this class:

```<code>class MyViewModel @Inject constructor(repository: MyRepository): ViewModel () {
    lateinit var myLiveData: LiveData<User>

    fun signIn(credential: AuthCredential) {
        myLiveData = repository.signIn(credential)
    }

    val otherLiveData = repository.signOut() //Works fine
}
</code>```

The problem is that the repository cannot be used inside the signIn function and I don't know why. However, the second call to signOut works. Can anyone please help?

答:
Creating a class with primary constructor and parameter like this:

```<code>class MyViewModel @Inject constructor(repository: MyRepository): ViewModel () { ... }
</code>```

leads to the fact that repository parameter is not a property, which means it can't be used in other functions of the class. But it can be used in the initializer blocks and in property initializers declared in the class body:

```<code>class MyViewModel(repo: MyRepository) {
    val repository = repo
}
</code>```

However, Kotlin has more concise syntax for declaring properties and initializing them from the primary constructor, using val or var keyword:

```<code>class MyViewModel @Inject constructor(val repository: MyRepository): ViewModel () { ... }
</code>```

If you declare parameter with val or var keyword it will be treated as a property and be available in other functions of the class.

More info about constructors and parameters in Kotlin.

Body:
I have this class:

class MyViewModel @Inject constructor(repository: MyRepository): ViewModel () {
    lateinit var myLiveData: LiveData<User>

    fun signIn(credential: AuthCredential) {
        myLiveData = repository.signIn(credential)
    }

    val otherLiveData = repository.signOut() //Works fine
}

The problem is that the repository cannot be used inside the signIn function and I don't know why. However, the second call to signOut works. Can anyone please help?

Body:
Creating a class with primary constructor and parameter like this:

class MyViewModel @Inject constructor(repository: MyRepository): ViewModel () { ... }

leads to the fact that repository parameter is not a property, which means it can't be used in other functions of the class. But it can be used in the initializer blocks and in property initializers declared in the class body:

class MyViewModel(repo: MyRepository) {
    val repository = repo
}

However, Kotlin has more concise syntax for declaring properties and initializing them from the primary constructor, using val or var keyword:

class MyViewModel @Inject constructor(val repository: MyRepository): ViewModel () { ... }

If you declare parameter with val or var keyword it will be treated as a property and be available in other functions of the class.

More info about constructors and parameters in Kotlin.


问:
wcf add service reference config
Adding service reference to the project does not affect app.config file. My Service exposes two service contracts via two endpoints. svc util did not generate config file too. What is the problem?

Thank you!

答: Did you add mex endpoint address="mex" binding="mexHttpBinding" ?</p>

ContentLicense: CC BY-SA 2.5

Title: wcf add service reference config


问:
What's Telegram chat memory space limit?
The Telegram has a cloud storage for users self-chat. Limit for uploading files - 1.5GB, yeah, I know about it. But I didn't find something about space limit for a chat. Is it unlimited? I mean, if yes, I can create Telegram-bot for cloud storage? Just, I have more than 20TB files and can I use Telegram for my site files storage and don't be afraid for safety/keeping?</p>

答:
There are no storage limits.

In general it is not adviced to store backups unencrypted on cloud, so check the above link.


问:
Trouble mapping json to golang struct
I have a json stream as follows ...

```<code>[
  {
    "page": 1,
    "pages": 7,
    "per_page": "2000",
    "total": 13200
  },
  [
    {
      "indicator": {
        "id": "SP.POP.TOTL",
        "value": "Population, total"
      },
      "country": {
        "id": "1A",
        "value": "Arab World"
      },
      "value": null,
      "decimal": "0",
      "date": "2019"
    },
    {
      "indicator": {
        "id": "SP.POP.TOTL",
        "value": "Population, total"
      },
      "country": {
        "id": "1A",
        "value": "Arab World"
      },
      "value": "419790588",
      "decimal": "0",
      "date": "2018"
    },
   ...
   ]
]
</code>```

And I'm trying to decode it ... so I have the following struct ... but I keep getting
"cannot unmarshal array into Go value of type struct { P struct ... "

```<code>type Message []struct {
        P struct {
                Page int
        }
        V []struct {
                Indicator struct {
                        Id    string
                        Value string
                }
                Country struct {
                        Value string
                }
                Value   string
                Decimal string
                Date    string
        }
}
</code>```

My struct looks to match the json ... but obviously not! Any ideas?

答:
As poWar said, the JSON you actually have is a list of objects whose types do not conform to each other.  You must therefore unmarshal into something capable of holding different object types, such as interface{} or—since there is an outer array—[]interface{}.

You can also, if you like, decode into a []json.RawMessage.  The underlying json.RawMessage itself has underlying type []byte so that it's basically the undecoded "inner" JSON.  In at least some cases this is going to be more work than just decoding directly to []interface{} and checking each resulting interface, but you can, if you wish, decode to struct once you have the JSON separated out.  For instance:

func main() {
    var x []json.RawMessage
    err := json.Unmarshal(input, &x)
    if err != nil {
        fmt.Printf("err = %v\n", err)
        return
    }
    if len(x) != 2 {
        fmt.Println("unexpected input")
        return
    }
    var page struct {
        Page int
    }
    err = json.Unmarshal(x[0], &page)
    if err != nil {
        fmt.Printf("unable to unmarshal page part: %v\n", err)
        return
    }
    fmt.Printf("page = %d\n", page.Page)
    // ...
}
```

Here on the Go Playground is a more complete example.  See also Eklavya's answer.

Title: Trouble mapping json to golang struct

Body:
I have a json stream as follows ...

[
  {
    "page": 1,
    "pages": 7,
    "per_page": "2000",
    "total": 13200
  },
  [
    {
      "indicator": {
        "id": "SP.POP.TOTL",
        "value": "Population, total"
      },
      "country": {
        "id": "1A",
        "value": "Arab World"
      },
      "value": null,
      "decimal": "0",
      "date": "2019"
    },
    {
      "indicator": {
        "id": "SP.POP.TOTL",
        "value": "Population, total"
      },
      "country": {
        "id": "1A",
        "value": "Arab World"
      },
      "value": "419790588",
      "decimal": "0",
      "date": "2018"
    },
   ...
   ]
]

And I'm trying to decode it ... so I have the following struct ... but I keep getting
"cannot unmarshal array into Go value of type struct { P struct ... "

type Message []struct {
        P struct {
                Page int
        }
        V []struct {
                Indicator struct {
                        Id    string
                        Value string
                }
                Country struct {
                        Value string
                }
                Value   string
                Decimal string
                Date    string
        }
}

My struct looks to match the json ... but obviously not! Any ideas?

Body:
As poWar said, the JSON you actually have is a list of objects whose types do not conform to each other.  You must therefore unmarshal into something capable of holding different object types, such as interface{} or—since there is an outer array—[]interface{}.

You can also, if you like, decode into a []json.RawMessage.  The underlying json.RawMessage itself has underlying type []byte so that it's basically the undecoded "inner" JSON.  In at least some cases this is going to be more work than just decoding directly to []interface{} and checking each resulting interface, but you can, if you wish, decode to struct once you have the JSON separated out.  For instance:

func main() {
    var x []json.RawMessage
    err := json.Unmarshal(input, &x)
    if err != nil {
        fmt.Printf("err = %v\n", err)
        return
    }
    if len(x) != 2 {
        fmt.Println("unexpected input")
        return
    }
    var page struct {
        Page int
    }
    err = json.Unmarshal(x[0], &page)
    if err != nil {
        fmt.Printf("unable to unmarshal page part: %v\n", err)
        return
    }
    fmt.Printf("page = %d\n", page.Page)
    // ...
}

Here on the Go Playground is a more complete example.  See also Eklavya's answer.


问:
Getting Null Value joining 3 tables
Below is the Query,I had joined 3 tables supplier is main table. The actual scenario is I want all the data from table account payable table though it is not their in purchase order table, so I have joined using FULL Outer with supplier and Purchase Order, but the supplier details were not coming against the data of account payable though supplier key is available.

```<code>SELECT ISNULL(dbo.Supplier.supplier_key,dbo.Fact_AccountPayables.supplier_key) AS supplier_key,
                  dbo.Supplier.Supplier,
                  dbo.Supplier.Name,
                  dbo.Supplier.Status,
                  dbo.Supplier.AddressCode,
                  dbo.Supplier.Address,
                  dbo.Supplier.HouseNo,
                  dbo.Supplier.Street,
                  dbo.Supplier.City,
                  dbo.Supplier.Country,
                  dbo.Supplier.ZipCode,
                  dbo.Supplier.StartDate,
                  dbo.Supplier.CreditLimit,
                  dbo.Supplier.FinancialGroup,
                  dbo.Supplier.LastTransactionDate,
                  dbo.Fact_PurchaseOrder.Company,
                  ISNULL(dbo.Fact_PurchaseOrder.[Purchase Order],dbo.Fact_AccountPayables.[PO Number]) AS PurchaseOrder,
                  ISNULL( dbo.Fact_PurchaseOrder.Sequence,dbo.Fact_AccountPayables.Line) AS POSequence,
                  dbo.Fact_PurchaseOrder.[Order Quantity],
                  dbo.Fact_PurchaseOrder.[Per Purchase Unit],
                  dbo.Fact_PurchaseOrder.[Per Quantity Price],
                  dbo.Fact_PurchaseOrder.[Purchase price unit],
                  dbo.Fact_PurchaseOrder.[Total Order Amount],
                  dbo.Fact_PurchaseOrder.Currency,
                  dbo.Fact_PurchaseOrder.[Rate Date],
                  dbo.Fact_PurchaseOrder.[Actual Receipt Date],
                  dbo.Fact_PurchaseOrder.[Receipt No],
                  dbo.Fact_PurchaseOrder.[Receipt Sequence],
                  dbo.Fact_PurchaseOrder.[Received Quantity],
                  dbo.Fact_PurchaseOrder.[Approved Quantity],
                  dbo.Fact_PurchaseOrder.[Purchase Office],
                  dbo.Fact_PurchaseOrder.[Invoice Number],
                  dbo.Fact_PurchaseOrder.[Invoice Date],
                  dbo.Fact_PurchaseOrder.[Invoice Quantity],
                  dbo.Fact_PurchaseOrder.[Invoice Amount],
                  dbo.Fact_AccountPayables.InvoiceNumber,
                  dbo.Fact_AccountPayables.Type AS InvoiceType,
                  dbo.Fact_AccountPayables.[Order Type] AS OrderInvoiceType,
                  dbo.Fact_AccountPayables.AP_Balance_EUR,
                  dbo.Fact_AccountPayables.[Invoice Amount_EUR],
                  dbo.Fact_AccountPayables.supplier_key AS EXPR2,
                  dbo.Fact_AccountPayables.[IntercompanyTrade Order No] AS EXPR23,
                  dbo.Fact_AccountPayables.[IntercompanyTrade Line Number] AS EXPR24,
                  dbo.Fact_AccountPayables.[Intercompany Trade Financial Company] AS EXPR25,
                  dbo.Fact_AccountPayables.[Intercompany Trade Purchase Company] AS EXPR26,
                  dbo.Fact_AccountPayables.InvoiceNumber,
                  dbo.Fact_AccountPayables.DueDate,
                  dbo.Fact_AccountPayables.DocDate,
                  dbo.Fact_PurchaseOrder.[Order Date],
                  dbo.Fact_AccountPayables.[Invoice Amount_EUR],
                  (CASE WHEN dbo.Fact_PurchaseOrder.[Receipt No] = ' ' THEN dbo.Fact_PurchaseOrder.[Total Order Amount]
                        WHEN  dbo.Fact_PurchaseOrder.[Receipt No] != ' ' and dbo.Fact_AccountPayables.InvoiceNumber IS NULL then dbo.Fact_PurchaseOrder.[Total Order Amount] END) AS ORDERBALANCE,
                  (dbo.Supplier.CreditLimit -(ORDERBALANCE + dbo.Fact_AccountPayables.[Invoice Amount_EUR])) AS Availablecredit
    FROM            dbo.Supplier
            LEFT OUTER JOIN dbo.Fact_PurchaseOrder ON dbo.Supplier.supplier_key = dbo.Fact_PurchaseOrder.buyfrom_supplier_key
            full OUTER JOIN dbo.Fact_AccountPayables ON dbo.Fact_AccountPayables.supplier_key = dbo.Supplier.supplier_key AND
                                                        dbo.Fact_AccountPayables.[PO Number] = dbo.Fact_PurchaseOrder.[Purchase Order]   AND
                                                    dbo.Fact_AccountPayables.[PO Line] = dbo.Fact_PurchaseOrder.Sequence
</code>```

The output is like this:

答:
Some of the rows are getting filtered in the Fact_PurchaseOrder, if they dont have supplier. You need to go for FULL OUTER JOIN for all tables, to get data for all rows of AccountPayables, irrespective of whether they have got suppliers or not.

FROM  dbo.Supplier
FULL OUTER JOIN dbo.Fact_PurchaseOrder ON dbo.Supplier.supplier_key = dbo.Fact_PurchaseOrder.buyfrom_supplier_key
FULL OUTER JOIN dbo.Fact_AccountPayables ON dbo.Fact_AccountPayables.supplier_key = dbo.Supplier.supplier_key AND
                                                        dbo.Fact_AccountPayables.[PO Number] = dbo.Fact_PurchaseOrder.[Purchase Order]   AND
                                                    dbo.Fact_AccountPayables.[PO Line] = dbo.Fact_PurchaseOrder.Sequence
```

Title: Getting Null Value joining 3 tables

Body:
Below is the Query,I had joined 3 tables supplier is main table. The actual scenario is I want all the data from table account payable table though it is not their in purchase order table, so I have joined using FULL Outer with supplier and Purchase Order, but the supplier details were not coming against the data of account payable though supplier key is available.

SELECT ISNULL(dbo.Supplier.supplier_key,dbo.Fact_AccountPayables.supplier_key) AS supplier_key,
                  dbo.Supplier.Supplier,
                  dbo.Supplier.Name,
                  dbo.Supplier.Status,
                  dbo.Supplier.AddressCode,
                  dbo.Supplier.Address,
                  dbo.Supplier.HouseNo,
                  dbo.Supplier.Street,
                  dbo.Supplier.City,
                  dbo.Supplier.Country,
                  dbo.Supplier.ZipCode,
                  dbo.Supplier.StartDate,
                  dbo.Supplier.CreditLimit,
                  dbo.Supplier.FinancialGroup,
                  dbo.Supplier.LastTransactionDate,
                  dbo.Fact_PurchaseOrder.Company,
                  ISNULL(dbo.Fact_PurchaseOrder.[Purchase Order],dbo.Fact_AccountPayables.[PO Number]) AS PurchaseOrder,
                  ISNULL( dbo.Fact_PurchaseOrder.Sequence,dbo.Fact_AccountPayables.Line) AS POSequence,
                  dbo.Fact_PurchaseOrder.[Order Quantity],
                  dbo.Fact_PurchaseOrder.[Per Purchase Unit],
                  dbo.Fact_PurchaseOrder.[Per Quantity Price],
                  dbo.Fact_PurchaseOrder.[Purchase price unit],
                  dbo.Fact_PurchaseOrder.[Total Order Amount],
                  dbo.Fact_PurchaseOrder.Currency,
                  dbo.Fact_PurchaseOrder.[Rate Date],
                  dbo.Fact_PurchaseOrder.[Actual Receipt Date],
                  dbo.Fact_PurchaseOrder.[Receipt No],
                  dbo.Fact_PurchaseOrder.[Receipt Sequence],
                  dbo.Fact_PurchaseOrder.[Received Quantity],
                  dbo.Fact_PurchaseOrder.[Approved Quantity],
                  dbo.Fact_PurchaseOrder.[Purchase Office],
                  dbo.Fact_PurchaseOrder.[Invoice Number],
                  dbo.Fact_PurchaseOrder.[Invoice Date],
                  dbo.Fact_PurchaseOrder.[Invoice Quantity],
                  dbo.Fact_PurchaseOrder.[Invoice Amount],
                  dbo.Fact_AccountPayables.InvoiceNumber,
                  dbo.Fact_AccountPayables.Type AS InvoiceType,
                  dbo.Fact_AccountPayables.[Order Type] AS OrderInvoiceType,
                  dbo.Fact_AccountPayables.AP_Balance_EUR,
                  dbo.Fact_AccountPayables.[Invoice Amount_EUR],
                  dbo.Fact_AccountPayables.supplier_key AS EXPR2,
                  dbo.Fact_AccountPayables.[IntercompanyTrade Order No] AS EXPR23,
                  dbo.Fact_AccountPayables.[IntercompanyTrade Line Number] AS EXPR24,
                  dbo.Fact_AccountPayables.[Intercompany Trade Financial Company] AS EXPR25,
                  dbo.Fact_AccountPayables.[Intercompany Trade Purchase Company] AS EXPR26,
                  dbo.Fact_AccountPayables.InvoiceNumber,
                  dbo.Fact_AccountPayables.DueDate,
                  dbo.Fact_AccountPayables.DocDate,
                  dbo.Fact_PurchaseOrder.[Order Date],
                  dbo.Fact_AccountPayables.[Invoice Amount_EUR],
                  (CASE WHEN dbo.Fact_PurchaseOrder.[Receipt No] = ' ' THEN dbo.Fact_PurchaseOrder.[Total Order Amount]
                        WHEN  dbo.Fact_PurchaseOrder.[Receipt No] != ' ' and dbo.Fact_AccountPayables.InvoiceNumber IS NULL then dbo.Fact_PurchaseOrder.[Total Order Amount] END) AS ORDERBALANCE,
                  (dbo.Supplier.CreditLimit -(ORDERBALANCE + dbo.Fact_AccountPayables.[Invoice Amount_EUR])) AS Availablecredit
    FROM            dbo.Supplier
            LEFT OUTER JOIN dbo.Fact_PurchaseOrder ON dbo.Supplier.supplier_key = dbo.Fact_PurchaseOrder.buyfrom_supplier_key
            full OUTER JOIN dbo.Fact_AccountPayables ON dbo.Fact_AccountPayables.supplier_key = dbo.Supplier.supplier_key AND
                                                        dbo.Fact_AccountPayables.[PO Number] = dbo.Fact_PurchaseOrder.[Purchase Order]   AND
                                                    dbo.Fact_AccountPayables.[PO Line] = dbo.Fact_PurchaseOrder.Sequence

The output is like this:


问:
Hibernate: Fetch all records from a single table, regardless of type defined with @DiscriminatorValue
Hibernate has powerful mechanism to make several entities to share same table in the database. For me, being able to fetch all records regardless of the subtypes would be the most important thing. However this doesn't seem to work.

Provided we have some standard setup:

```<code>@Entity
@Table(name = "plane")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(
    name="planetype",
    discriminatorType=DiscriminatorType.STRING
)
public abstract class Plane { ... }

@Entity
@Table(name = "plane")
@DiscriminatorValue("A320")
public class A320 extends Plane { ... }

@Entity
@Table(name = "plane")
@DiscriminatorValue("B777")
public class B777 extends Plane { ... }
</code>```

What do I need to access all the planes we have on the table?

```<code>@Entity
@DiscriminatorValue("")
public class AnyPlane extends Plane { ... } // this doesn't work

@Entity
public class AnyPlane extends Plane { ... } // this doesn't work either
</code>```

I try to fetch AnyPlanes same way I usually do...

```<code>CriteriaBuilder cb = getSession().getCriteriaBuilder();
CriteriaQuery<AnyPlane> q = cb.createQuery(AnyPlane.class);
Root<AnyPlane> root = q.from(AnyPlane.class);

Query<AnyPlane> query = getSession().createQuery(q.select(root)
    .where(someRestrictions)
);
return query.list();
</code>```

...and get empty list, because Hibernate considers even empty string to be a valid denominator. What would I do?

Worth to mention, that the planes already happyly fly up the code stack, and my goal is to refactor the DB layer without introducing much changes. I'm also not keen to use native SQL.

答:
Simple solution I found is to make the AnyPlane to fly on it own, without extending the Plane:

```<code>@Entity
@Table(name = "plane")
public class AnyPlane {
    ... // same fields we would have on the parent

    @Enumerated(EnumType.STRING)
    @Column(name = "planetype", insertable = false, updatable = false)
    private PlaneType planeType;

    ...
}

public enum LikedEntityType {
    A320,
    B777
}
</code>```

Also consider making a common parent for Plane and AnyPlane to avoid the copypaste for the common fields, while not bearing the sins of @DiscriminatorColumn.

Body:
Hibernate has powerful mechanism to make several entities to share same table in the database. For me, being able to fetch all records regardless of the subtypes would be the most important thing. However this doesn't seem to work.

Provided we have some standard setup:

@Entity
@Table(name = "plane")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(
    name="planetype",
    discriminatorType=DiscriminatorType.STRING
)
public abstract class Plane { ... }

@Entity
@Table(name = "plane")
@DiscriminatorValue("A320")
public class A320 extends Plane { ... }

@Entity
@Table(name = "plane")
@DiscriminatorValue("B777")
public class B777 extends Plane { ... }

What do I need to access all the planes we have on the table?

@Entity
@DiscriminatorValue("")
public class AnyPlane extends Plane { ... } // this doesn't work

@Entity
public class AnyPlane extends Plane { ... } // this doesn't work either

I try to fetch AnyPlanes same way I usually do...

CriteriaBuilder cb = getSession().getCriteriaBuilder();
CriteriaQuery<AnyPlane> q = cb.createQuery(AnyPlane.class);
Root<AnyPlane> root = q.from(AnyPlane.class);

Query<AnyPlane> query = getSession().createQuery(q.select(root)
    .where(someRestrictions)
);
return query.list();

...and get empty list, because Hibernate considers even empty string to be a valid denominator. What would I do?

Worth to mention, that the planes already happyly fly up the code stack, and my goal is to refactor the DB layer without introducing much changes. I'm also not keen to use native SQL.

Body:
Simple solution I found is to make the AnyPlane to fly on it own, without extending the Plane:

@Entity
@Table(name = "plane")
public class AnyPlane {
    ... // same fields we would have on the parent

    @Enumerated(EnumType.STRING)
    @Column(name = "planetype", insertable = false, updatable = false)
    private PlaneType planeType;

    ...
}

public enum LikedEntityType {
    A320,
    B777
}

Also consider making a common parent for Plane and AnyPlane to avoid the copypaste for the common fields, while not bearing the sins of @DiscriminatorColumn.


问:
Create a list with all sentences from a text
How can I create a list with all sentences, where a sentence needs to have at least 3 words, from a text. The sentences are split by ".?!".
For example:

```<code>text = "Hi! How are you? I am fine."
</code>```

The list will be: ["How are you", "I am fine"]

答:
You can use split function with regex.

import re

s_nums = 'Hi! How are you? I am fine.'

print([sen for sen in re.split('\.|!|\?', s_nums) if len(sen) > 2])
```

Body:
How can I create a list with all sentences, where a sentence needs to have at least 3 words, from a text. The sentences are split by ".?!".
For example:

text = "Hi! How are you? I am fine."

The list will be: ["How are you", "I am fine"]


问:
linux uptime history
How can I get a history of uptimes for my debian box? After a reboot, I dont see an option for the uptime command to print a history of uptimes. If it matters, I would like to use these uptimes for graphing a page in php to show my webservers uptime lengths between boots.

Update:
Not sure if it is based on a length of time or if last gets reset on reboot but I only get the most recent boot timestamp with the last command. last -x also does not return any further info.  Sounds like a script is my best bet.

Update:
Uptimed is the information I am looking for, not sure how to grep that info in code. Managing my own script for a db sounds like the best fit for an application.

答:
Use Syslog

For anyone coming here searching for their past uptime.
The solution of @1800_Information is a good advise for the future, but I needed to find information for my past uptimes on a specific date.

Therefore I used syslog to determine when that day the system was started (first log entry of that day) and when the system was shutdown again.

Boot time

To get the system start time grep for the month and day and show only the first lines:

```<code>sudo grep "May 28" /var/log/syslog* | head
</code>```

Shutdown time

To get the system shutdown time grep for the month and day and show only the last few lines:

```<code>sudo grep "May 28" /var/log/syslog* | tail
</code>```

OwnerDisplayName: Jas

Title: linux uptime history

LastEditorDisplayName: Jas

Body:
Use Syslog

For anyone coming here searching for their past uptime.
The solution of @1800_Information is a good advise for the future, but I needed to find information for my past uptimes on a specific date.

Therefore I used syslog to determine when that day the system was started (first log entry of that day) and when the system was shutdown again.

Boot time

To get the system start time grep for the month and day and show only the first lines:

sudo grep "May 28" /var/log/syslog* | head

Shutdown time

To get the system shutdown time grep for the month and day and show only the last few lines:

sudo grep "May 28" /var/log/syslog* | tail


问:
making the whole page blur when I click on a certain button
So, I have a button and want the whole body to go blurry when I click on it and show an alert or a pop-up message. this is what I have been trying to do:

function myFunction() {
  $('body').css("filter","blur(2px)");
  alert("hello");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="phone_num d-none d-xl-block">
  {% trans 'try' %}
</div></code>```

But I have a couple of issues:
1- the blur doesn't last until I click okay to the alert and moves to the next page right away.
2- the alert is way up on the top of the page o can I some how move to the middle of the page?

答:
You can use this, but this may not match your need. Here's how to do it:

```<code>$('.blurBtn').on('click', function(){
  $('body').css("opacity","0.1");
  return false;
})
</code>```

Body:
So, I have a button and want the whole body to go blurry when I click on it and show an alert or a pop-up message. this is what I have been trying to do:

function myFunction() {
  $('body').css("filter","blur(2px)");
  alert("hello");
}

  {% trans 'try' %}

But I have a couple of issues:
1- the blur doesn't last until I click okay to the alert and moves to the next page right away.
2- the alert is way up on the top of the page o can I some how move to the middle of the page?

Body:
You can use this, but this may not match your need. Here's how to do it:

$('.blurBtn').on('click', function(){
  $('body').css("opacity","0.1");
  return false;
})


问:
Unable to generate cucumber reports in jenkins. net.masterthought.cucumber.ValidationException: None report file was added
I am using jenkins to run jobs that uses maven with cucumber . my jobs are running succesfully. I have also managed the plugin Cucumber report in jenkins. But when i view the report i am getting the message as shown in below picture.

I have tried to install various plugins like Jenkins plugin, standalone but with no joy. These are shown as options in the bottom right of the report.

Any clue is helpful. I have tried to check this error in stackover flow also. I didnt get any clue

I could see the reports file in xml which is created by surefire plugin. Any way i can achive reporting part in my project

答:
First of all in runner file we need to provide following plugin as follows: plugin= {"json:target/cucumber.json" }

Now in Jenkins job, in "post build" section during configuration, add cucumber reports, click on advanced option and provide 'target' text in "JSON Reports Path" text field. Save the job, it will run and will work fine.

Note: target text is the name of folder which we have provided in runner file for generating reports in Json, also cucumber report plugin works on json so need to generate report in json.


问:
C++ - Behaviour of derived class constructor
I'm preparing my exam. Below is output of a sample question, the block 3 confuses me.

```<code>--- Block 1 ---
H
SM
2 x S
DP
--- Block 2 ---
H
SM
2 x S
DP
--- Block 3 ---
H
Copy SM
1 x S
Copy DP
--- Block 4 ---
H=
--- Block 5 ---
 ̃H
--- Block 6 ---
 ̃DP
 ̃S
 ̃SM
 ̃H
 ̃DP
 ̃S
 ̃SM
 ̃H
</code>```

We pass a Deadpool type object to construct a new Deadpool object, so copy constructor(ctor) should be called. Deadpool copy ctor should call Spiderman copy ctor, because of inheritance. Then, Spiderman copy ctor calls Hero ctor for same reason, so why is there 1 x S? Who called the Sword constructor?

```<code>#include <iostream>
using namespace std;

class Weapon { };

class Sword : public Weapon {
public:
    Sword(int n = 1) { cout << n << " x S" << endl; }
    ~Sword() { cout << " ̃S" << endl; }
};

class Hero {
    Weapon* w;
public:
    Hero() { cout << "H" << endl; w = new Weapon; }
   ~Hero() { cout << " ̃H" << endl; delete w; }
    virtual const Hero& operator=(const Hero& h) { cout << "H=" << endl; return *this;}
};

class SpiderMan : public Hero {
    Weapon* w;
public:
    SpiderMan() { cout << "SM" << endl; w = new Weapon; }
    SpiderMan(const SpiderMan& s) { cout << "Copy SM" << endl; w = new Weapon; }
    virtual ~SpiderMan() { cout << " ̃SM" << endl; delete w; }
    const SpiderMan& operator=(const SpiderMan& s) { cout << "SM=" << endl; return *this;}
};

class DeadPool : public SpiderMan {
    Sword sword;
public:
    DeadPool() : sword(2) { cout << "DP" << endl; }
    DeadPool(const DeadPool& d) : SpiderMan(d) { cout << "Copy DP" << endl; }
    ~DeadPool() { cout << " ̃DP" << endl; }
    const DeadPool& operator=(const DeadPool& d) { cout << "DP=" << endl; return *this;}
};

int main() {
    cout << "--- Block 1 ---" << endl;
    Hero* hero = new DeadPool;
    cout << "--- Block 2 ---" << endl;
    SpiderMan* spiderman = new DeadPool;
    cout << "--- Block 3 ---" << endl;
    DeadPool deadpool(*dynamic_cast<DeadPool*>(spiderman));
    cout << "---        Block 4 ---" << endl;
    *hero = *spiderman;
    cout << "--- Block 5 ---" << endl;
    delete hero;
    cout << "--- Block 6 ---" << endl;
    delete spiderman;
}

</code>```

答:
Who called the Sword constructor?

DeadPool has a data member sword with type Sword, it's not mentioned in the copy constructor of DeadPool, then it'll be initialized by its default constructor. That's why you got the output 1 x S, between the invocation of the constructor of base SpiderMan and invocation of the constructor of DeadPool.

Body:
I'm preparing my exam. Below is output of a sample question, the block 3 confuses me.

--- Block 1 ---
H
SM
2 x S
DP
--- Block 2 ---
H
SM
2 x S
DP
--- Block 3 ---
H
Copy SM
1 x S
Copy DP
--- Block 4 ---
H=
--- Block 5 ---
 ̃H
--- Block 6 ---
 ̃DP
 ̃S
 ̃SM
 ̃H
 ̃DP
 ̃S
 ̃SM
 ̃H

We pass a Deadpool type object to construct a new Deadpool object, so copy constructor(ctor) should be called. Deadpool copy ctor should call Spiderman copy ctor, because of inheritance. Then, Spiderman copy ctor calls Hero ctor for same reason, so why is there 1 x S? Who called the Sword constructor?

#include <iostream>
using namespace std;

class Weapon { };

class Sword : public Weapon {
public:
    Sword(int n = 1) { cout << n << " x S" << endl; }
    ~Sword() { cout << " ̃S" << endl; }
};

class Hero {
    Weapon* w;
public:
    Hero() { cout << "H" << endl; w = new Weapon; }
   ~Hero() { cout << " ̃H" << endl; delete w; }
    virtual const Hero& operator=(const Hero& h) { cout << "H=" << endl; return *this;}
};

class SpiderMan : public Hero {
    Weapon* w;
public:
    SpiderMan() { cout << "SM" << endl; w = new Weapon; }
    SpiderMan(const SpiderMan& s) { cout << "Copy SM" << endl; w = new Weapon; }
    virtual ~SpiderMan() { cout << " ̃SM" << endl; delete w; }
    const SpiderMan& operator=(const SpiderMan& s) { cout << "SM=" << endl; return *this;}
};

class DeadPool : public SpiderMan {
    Sword sword;
public:
    DeadPool() : sword(2) { cout << "DP" << endl; }
    DeadPool(const DeadPool& d) : SpiderMan(d) { cout << "Copy DP" << endl; }
    ~DeadPool() { cout << " ̃DP" << endl; }
    const DeadPool& operator=(const DeadPool& d) { cout << "DP=" << endl; return *this;}
};

int main() {
    cout << "--- Block 1 ---" << endl;
    Hero* hero = new DeadPool;
    cout << "--- Block 2 ---" << endl;
    SpiderMan* spiderman = new DeadPool;
    cout << "--- Block 3 ---" << endl;
    DeadPool deadpool(*dynamic_cast<DeadPool*>(spiderman));
    cout << "---        Block 4 ---" << endl;
    *hero = *spiderman;
    cout << "--- Block 5 ---" << endl;
    delete hero;
    cout << "--- Block 6 ---" << endl;
    delete spiderman;
}


问:
"SSL certificate verify failed" using pip to install packages
I am trying to install the Scrapy package (among others) for python using pip. I have tried doing the installation using python 3 and python 2, I have installed/upgraded the setuptools like so: $ pip3 install --upgrade setuptools, I have tried to use the --trusted-host option like so: $ pip3 install --trusted-host pypi.python.org Scrapy. But I always get the same error message when I run $ pip3 install Scrapy. The complete output is this:

```<code>Collecting Scrapy
  Using cached Scrapy-1.3.2-py2.py3-none-any.whl
Collecting PyDispatcher>=2.0.5 (from Scrapy)
  Using cached PyDispatcher-2.0.5.tar.gz
Collecting service-identity (from Scrapy)
  Using cached service_identity-16.0.0-py2.py3-none-any.whl
Collecting pyOpenSSL (from Scrapy)
  Using cached pyOpenSSL-16.2.0-py2.py3-none-any.whl
Collecting w3lib>=1.15.0 (from Scrapy)
  Using cached w3lib-1.17.0-py2.py3-none-any.whl
Collecting parsel>=1.1 (from Scrapy)
  Using cached parsel-1.1.0-py2.py3-none-any.whl
Collecting queuelib (from Scrapy)
  Using cached queuelib-1.4.2-py2.py3-none-any.whl
Requirement already satisfied: six>=1.5.2 in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from Scrapy)
Collecting Twisted>=13.1.0 (from Scrapy)
  Using cached Twisted-17.1.0.tar.bz2
    Complete output from command python setup.py egg_info:
    Download error on https://pypi.python.org/simple/incremental/: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749) -- Some packages may not be found!
    Couldn't find index page for 'incremental' (maybe misspelled?)
    Download error on https://pypi.python.org/simple/: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749) -- Some packages may not be found!
    No local packages or working download links found for incremental>=16.10.1
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/private/var/folders/gy/5xt04_452z791v1qjs1yzxkh0000gn/T/pip-build-nkv4jozy/Twisted/setup.py", line 21, in <module>
        setuptools.setup(**_setup["getSetupArgs"]())
      File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/distutils/core.py", line 108, in setup
        _setup_distribution = dist = klass(attrs)
      File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/setuptools/dist.py", line 317, in __init__
        self.fetch_build_eggs(attrs['setup_requires'])
      File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/setuptools/dist.py", line 372, in fetch_build_eggs
        replace_conflicting=True,
      File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pkg_resources/__init__.py", line 851, in resolve
        dist = best[req.key] = env.best_match(req, ws, installer)
      File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pkg_resources/__init__.py", line 1123, in best_match
        return self.obtain(req, installer)
      File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pkg_resources/__init__.py", line 1135, in obtain
        return installer(requirement)
      File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/setuptools/dist.py", line 440, in fetch_build_egg
        return cmd.easy_install(req)
      File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/setuptools/command/easy_install.py", line 668, in easy_install
        raise DistutilsError(msg)
    distutils.errors.DistutilsError: Could not find suitable distribution for Requirement.parse('incremental>=16.10.1')

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/gy/5xt04_452z791v1qjs1yzxkh0000gn/T/pip-build-nkv4jozy/Twisted/
</code>```

I am on a mac OS version 10.12.1 and am using python 3.6.
Does anybody know a solution to this problem?

答:
Thank you for the solution. In my case the file %appdata%\pip\pip.ini was not present. I created it manually with this content:</p>

```<code>[global]
trusted-host = pypi.python.org files.pythonhosted.org pypi.org pypi.io
</code>```

Body:
I am trying to install the Scrapy package (among others) for python using pip. I have tried doing the installation using python 3 and python 2, I have installed/upgraded the setuptools like so: $ pip3 install --upgrade setuptools, I have tried to use the --trusted-host option like so: $ pip3 install --trusted-host pypi.python.org Scrapy. But I always get the same error message when I run $ pip3 install Scrapy. The complete output is this:

Collecting Scrapy
  Using cached Scrapy-1.3.2-py2.py3-none-any.whl
Collecting PyDispatcher>=2.0.5 (from Scrapy)
  Using cached PyDispatcher-2.0.5.tar.gz
Collecting service-identity (from Scrapy)
  Using cached service_identity-16.0.0-py2.py3-none-any.whl
Collecting pyOpenSSL (from Scrapy)
  Using cached pyOpenSSL-16.2.0-py2.py3-none-any.whl
Collecting w3lib>=1.15.0 (from Scrapy)
  Using cached w3lib-1.17.0-py2.py3-none-any.whl
Collecting parsel>=1.1 (from Scrapy)
  Using cached parsel-1.1.0-py2.py3-none-any.whl
Collecting queuelib (from Scrapy)
  Using cached queuelib-1.4.2-py2.py3-none-any.whl
Requirement already satisfied: six>=1.5.2 in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from Scrapy)
Collecting Twisted>=13.1.0 (from Scrapy)
  Using cached Twisted-17.1.0.tar.bz2
    Complete output from command python setup.py egg_info:
    Download error on https://pypi.python.org/simple/incremental/: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749) -- Some packages may not be found!
    Couldn't find index page for 'incremental' (maybe misspelled?)
    Download error on https://pypi.python.org/simple/: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749) -- Some packages may not be found!
    No local packages or working download links found for incremental>=16.10.1
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/private/var/folders/gy/5xt04_452z791v1qjs1yzxkh0000gn/T/pip-build-nkv4jozy/Twisted/setup.py", line 21, in <module>
        setuptools.setup(**_setup["getSetupArgs"]())
      File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/distutils/core.py", line 108, in setup
        _setup_distribution = dist = klass(attrs)
      File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/setuptools/dist.py", line 317, in __init__
        self.fetch_build_eggs(attrs['setup_requires'])
      File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/setuptools/dist.py", line 372, in fetch_build_eggs
        replace_conflicting=True,
      File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pkg_resources/__init__.py", line 851, in resolve
        dist = best[req.key] = env.best_match(req, ws, installer)
      File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pkg_resources/__init__.py", line 1123, in best_match
        return self.obtain(req, installer)
      File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pkg_resources/__init__.py", line 1135, in obtain
        return installer(requirement)
      File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/setuptools/dist.py", line 440, in fetch_build_egg
        return cmd.easy_install(req)
      File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/setuptools/command/easy_install.py", line 668, in easy_install
        raise DistutilsError(msg)
    distutils.errors.DistutilsError: Could not find suitable distribution for Requirement.parse('incremental>=16.10.1')

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/gy/5xt04_452z791v1qjs1yzxkh0000gn/T/pip-build-nkv4jozy/Twisted/

I am on a mac OS version 10.12.1 and am using python 3.6.
Does anybody know a solution to this problem?

Body:
Thank you for the solution. In my case the file %appdata%\pip\pip.ini was not present. I created it manually with this content:

[global]
trusted-host = pypi.python.org files.pythonhosted.org pypi.org pypi.io


问:
Trying to recursively add the square of numbers
```<code>def recursive_add(s):
    sum = 0
    if len(s) == 1:
        sum += s[0] ** 2
    else:
        recursive_add(s[1:])
        sum += s[0]**2
    return sum

s = [8, 6, 8, 4]

print recursive_add(s)
</code>```

however, for some reason, 8 gets squared right away and 64 is returned, even though it should be the last number to be squared and added to sum.

答:
The answer was quite simple just add the recursive-add(s[1:]) to sum in else part:</p>

```<code>def recursive_add(s):
    sum = 0
    if len(s) == 1:
        sum += int(s[0]) ** 2
    else:
        sum = sum+int(s[0])**2+recursive_add(s[1:])
    return sum
s = [8, 6, 8, 4]
print (recursive_add(s))
</code>```

Body:
def recursive_add(s):
    sum = 0
    if len(s) == 1:
        sum += s[0] ** 2
    else:
        recursive_add(s[1:])
        sum += s[0]**2
    return sum

s = [8, 6, 8, 4]

print recursive_add(s)

however, for some reason, 8 gets squared right away and 64 is returned, even though it should be the last number to be squared and added to sum.

Body:
The answer was quite simple just add the recursive-add(s[1:]) to sum in else part:

def recursive_add(s):
    sum = 0
    if len(s) == 1:
        sum += int(s[0]) ** 2
    else:
        sum = sum+int(s[0])**2+recursive_add(s[1:])
    return sum
s = [8, 6, 8, 4]
print (recursive_add(s))


问:
TypeError: float() argument must be a string or a number, not 'dict_values',
I was trying to plot the loss for my model, so coded like below, but I am getting below error:

TypeError: float() argument must be a string or a number, not 'dict_values'

code:

```<code>def fit(self, X, Y, epochs=1, learning_rate=1, initialise=True, display_loss=False):

    #initialise w,b
    if initialise:
        self.w = np.random.randn(1,X.shape[1])
        self.b = 0

    if display_loss:
        loss = {}

    for i in tqdm_notebook(range(epochs), total=epochs, unit='epoch'):
        dw = 0
        db = 0
        for x,y in zip(X,Y,):
            dw += self.grad_w(x,y)
            db += self.grad_b(x,y)

        self.w -= learning_rate * dw
        self.b -= learning_rate * db

        if display_loss:
            Y_pred = self.sigmoid(self.perceptron(X))
            loss[i] = mean_squared_error(Y_pred, Y)

    if display_loss:
        plt.plot(loss.values())
        plt.xlabel('Epochs')
        plt.ylabel('Mean Squared Error')
        plt.show()

def predict(self, X):
    Y_pred = []
    for x in X:
        y_pred = self.sigmoid(self.perceptron(x))
        Y_pred.append(y_pred)
    return np.array(Y_pred)

sn = SigmoidNeuron()
sn.fit(X_scaled_train, Y_scaled_train, epochs=1000, learning_rate=0.01, display_loss=True)
</code>```

答:
TypeError: float() argument must be a string or a number, not 'dict_values'

I got your error. This error occur if you are plotting the loss.values as it is...
  which you shouldn't do it.

You should change this dict_values to a list

which creates an array of type object and puts the dict_values object inside:

plt.plot(loss.values())  instead of this you should use

>plt.plot(np.array(list(loss.values())).astype(float))

so your code should look like this:

```<code>    if display_loss:
        plt.plot(np.array(list(loss.values())).astype(float))
        plt.xlabel('Epochs')
        plt.ylabel('Mean Squared Error')
        plt.show()
</code>```

so when you run the fit function or invoke that function with this
sn.fit(X_scaled_train, Y_scaled_train, epochs=2000, learning_rate=0.015, display_loss=True)

then you will get the loss plotting image as loss_plotting.

I took reference of this snippet
Float Arguments and dict_values with NumPy

Hope you get it...!

Body:
I was trying to plot the loss for my model, so coded like below, but I am getting below error:

TypeError: float() argument must be a string or a number, not 'dict_values'

code:

def fit(self, X, Y, epochs=1, learning_rate=1, initialise=True, display_loss=False):

    #initialise w,b
    if initialise:
        self.w = np.random.randn(1,X.shape[1])
        self.b = 0

    if display_loss:
        loss = {}

    for i in tqdm_notebook(range(epochs), total=epochs, unit='epoch'):
        dw = 0
        db = 0
        for x,y in zip(X,Y,):
            dw += self.grad_w(x,y)
            db += self.grad_b(x,y)

        self.w -= learning_rate * dw
        self.b -= learning_rate * db

        if display_loss:
            Y_pred = self.sigmoid(self.perceptron(X))
            loss[i] = mean_squared_error(Y_pred, Y)

    if display_loss:
        plt.plot(loss.values())
        plt.xlabel('Epochs')
        plt.ylabel('Mean Squared Error')
        plt.show()

def predict(self, X):
    Y_pred = []
    for x in X:
        y_pred = self.sigmoid(self.perceptron(x))
        Y_pred.append(y_pred)
    return np.array(Y_pred)

sn = SigmoidNeuron()
sn.fit(X_scaled_train, Y_scaled_train, epochs=1000, learning_rate=0.01, display_loss=True)

Body:
TypeError: float() argument must be a string or a number, not 'dict_values'

I got your error. This error occur if you are plotting the loss.values as it is...
  which you shouldn't do it.

You should change this dict_values to a list

which creates an array of type object and puts the dict_values object inside:

plt.plot(loss.values())  instead of this you should use

>plt.plot(np.array(list(loss.values())).astype(float))

so your code should look like this:

    if display_loss:
        plt.plot(np.array(list(loss.values())).astype(float))
        plt.xlabel('Epochs')
        plt.ylabel('Mean Squared Error')
        plt.show()

so when you run the fit function or invoke that function with this
sn.fit(X_scaled_train, Y_scaled_train, epochs=2000, learning_rate=0.015, display_loss=True)

then you will get the loss plotting image as loss_plotting.

I took reference of this snippet
Float Arguments and dict_values with NumPy

Hope you get it...!


问:
Encode special characters with UTF-8 characters
I have a String Address: Mount Road (Back) [Contact-Ron] & give him the {data}
I need to use SAX parser and it doesn't parse special characters, we need to replace them with UTF-8 characters.
Example-- & is replaced with &amp.
Is there any way to replace special characters with their corresponding UTF-8 characters without individually writing replace code ?

答:
You can use a library like the Apache Commons StringEscapeUtils.unescapeHtml4
to decode HTML character code sequences to corresponding UTF-8 chars.</p>


问:
how to get max time from a report
i want to filter my report and only show that row which has maximum time
 first i use

enddate = fr.First().EndDate

but it given me first value occured not the maximum time
i try to use

endDate = fr.Max().EndDate

but failed.

Title: how to get max time from a report

Body: try fr.OrderByDescending(x=> x.EndDate).First().EndDate


问:
Enumerating installed browsers on OS X
How would one enumerate the installed browsers on an OS X system from a local app. I would like to build something like choosy, but different (long story). However, I would like to enumerate all installed browsers on the system.

On windows, I can dive the installed browsers in the Default Programs registries, however, I don't believe there is a similar concept on OS X. Do I have to manually search through all the bundles & their info.plist files?

答:
LSCopyAllHandlersForURLScheme has been deprecated in 10.15

You can use LSCopyApplicationURLsForURL instead

```<code>LSCopyApplicationURLsForURL(URL(string: "https:")! as CFURL, .all)?.takeRetainedValue() as? [URL]
</code>```

Also, unlike LSCopyAllHandlersForURLScheme, LSCopyApplicationURLsForURL returns the URL of the file path of Applications.

You can then use Bundle(url: fileURL)!.bundleIdentifier to extract the bundleID

To extract the apps name you can use

```<code>Bundle(url: fileURL)!.infoDictionary?["CFBundleDisplayName"]
</code>```

and if CFBundleDisplayName returns nil then CFBundleName can be used

Title: Enumerating installed browsers on OS X

Body:
LSCopyAllHandlersForURLScheme has been deprecated in 10.15

You can use LSCopyApplicationURLsForURL instead

LSCopyApplicationURLsForURL(URL(string: "https:")! as CFURL, .all)?.takeRetainedValue() as? [URL]

Also, unlike LSCopyAllHandlersForURLScheme, LSCopyApplicationURLsForURL returns the URL of the file path of Applications.

You can then use Bundle(url: fileURL)!.bundleIdentifier to extract the bundleID

To extract the apps name you can use

Bundle(url: fileURL)!.infoDictionary?["CFBundleDisplayName"]

and if CFBundleDisplayName returns nil then CFBundleName can be used


问:
Python script for outputting JSON has wrong output for attribute-value pair
I'm writing a Python script to output some JSON files to Cosmos DB on Azure. My script looks as follows:

```<code>import logging
import uuid
import json

import azure.functions as func

def main(event: func.EventHubEvent, message: func.Out[func.Document]) -> None:
    event_body = event.get_body().decode('utf-8')

    logging.info('Python event trigger function processed an event item: %s',event_body)

    data = {
        "value": event_body,
        "insertion_time": event_body
        }

    message.set(func.Document.from_json(json.dumps(data)))
</code>```

The output is written like:

```<code>{
    "value": "{\n  \"value\": \"66\",\n  \"insertion_time\": \"2020-06-02T05:50:00+00:00\"\n}",
    "insertion_time": "{\n  \"value\": \"66\",\n  \"insertion_time\": \"2020-06-02T05:50:00+00:00\"\n}"
}
</code>```

However, I'd like it to be like:

```<code>{
    "value": "66",
    "insertion_time": "2020-06-02T05:50:00+00:00"
}
</code>```

How do I correct this?

答:
Your event_body appears to be a JSON string which already contains exactly what you want. It appears you don’t need to do anything and just use it directly:

```<code>message.set(func.Document.from_json(event_body))
</code>```

Body:
I'm writing a Python script to output some JSON files to Cosmos DB on Azure. My script looks as follows:

import logging
import uuid
import json

import azure.functions as func

def main(event: func.EventHubEvent, message: func.Out[func.Document]) -> None:
    event_body = event.get_body().decode('utf-8')

    logging.info('Python event trigger function processed an event item: %s',event_body)

    data = {
        "value": event_body,
        "insertion_time": event_body
        }

    message.set(func.Document.from_json(json.dumps(data)))

The output is written like:

{
    "value": "{\n  \"value\": \"66\",\n  \"insertion_time\": \"2020-06-02T05:50:00+00:00\"\n}",
    "insertion_time": "{\n  \"value\": \"66\",\n  \"insertion_time\": \"2020-06-02T05:50:00+00:00\"\n}"
}

However, I'd like it to be like:

{
    "value": "66",
    "insertion_time": "2020-06-02T05:50:00+00:00"
}

How do I correct this?

Body:
Your event_body appears to be a JSON string which already contains exactly what you want. It appears you don’t need to do anything and just use it directly:

message.set(func.Document.from_json(event_body))


问:
Flutter plugin project build breaks: @import module not found for iOS
I'm developing a Flutter plugin that was running until a minute ago.

I haven't changed my Flutter project or the generated Xcode workspace at all. But all of a sudden the iOS Runner build breaks:

/path/to/myplugin/example/ios/Runner/GeneratedPluginRegistrant.m:10:9:
    fatal error: module 'nativeguest' not found
    @import myplugin;
     ~~~~~~~^~~~~~~~~~~
    1 error generated.
```
<p>I haven't renamed or moved anything so I have no clue where this came from. I double checked there are no changes through my Git history.</p>
<p>I don't quite remember what happened except a few <code>flutter clean</code> and <code>flutter run -d <udid></code> ops. I probably did these in both the plugin example folder and the plugin root folder.</p>
<p>My Flutter global setup is perfectly fine</p>
<pre class="lang-bash prettyprint-override"><code>$ flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel dev, 1.19.0-1.0.pre, on Mac OS X 10.15.4 19E287, locale en-CN)

[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
[✓] Xcode - develop for iOS and macOS (Xcode 11.5)
[✓] Android Studio (version 3.6)
[✓] VS Code (version 1.45.1)
[✓] Connected device (2 available)

• No issues found!
</code>```

答:
This turned out to be a Bundle ID issue. I renamed the bundle on flutter side in the .yaml, but the new name didn't reflect back to the Xcode project.

One must manually rename the following metadata entries of the generated Xcode Runner project

Runner > Runner > Info.plist: Bundle name

`Runner > Main Editor: Signing & Capabilities > Bundle Identifier

IMHO, this is such a bad dev experience on Flutter's part. Renaming on Android is another roller-coaster ride, having to edit multiple manifests and Gradle configs.

Due to so many separate config files, renaming or reorganizing a project becomes such a risky act!

Body:
I'm developing a Flutter plugin that was running until a minute ago.

I haven't changed my Flutter project or the generated Xcode workspace at all. But all of a sudden the iOS Runner build breaks:

/path/to/myplugin/example/ios/Runner/GeneratedPluginRegistrant.m:10:9:
    fatal error: module 'nativeguest' not found
    @import myplugin;
     ~~~~~~~^~~~~~~~~~~
    1 error generated.

I haven't renamed or moved anything so I have no clue where this came from. I double checked there are no changes through my Git history.

I don't quite remember what happened except a few flutter clean and flutter run -d <udid> ops. I probably did these in both the plugin example folder and the plugin root folder.

My Flutter global setup is perfectly fine

$ flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel dev, 1.19.0-1.0.pre, on Mac OS X 10.15.4 19E287, locale en-CN)

[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
[✓] Xcode - develop for iOS and macOS (Xcode 11.5)
[✓] Android Studio (version 3.6)
[✓] VS Code (version 1.45.1)
[✓] Connected device (2 available)

• No issues found!


问:
ImportError: cannot import name 'quote'
I have learned basics of python, so tried this code below

```<code>from pytube import YouTube

Save_path="E:\python\youtube downloader"

link="https://www.youtube.com/watch?v=xWOoBJUqlbI"

try:
    yt=YouTube(link)

except:
    print("Connection error!")

mp4file=yt.filter('mp4')

yt.set_filename("ashshak")

d_file=yt.get(mp4files[-1].extention,mp4files[-1].resolution)

try:
    d_file.download(Save_path)

except:
    print("Error in downlaod")
    print("Download failed")
</code>```

when I try this code or with GUI interface code I have given bellow, the compiler will show this error. but  I have already installed "pip install pytube" library

```<code>Traceback (most recent call last):
  File "E:\python\youtube downloader\practiceyoutube.py", line 1, in <module>
    from pytube import YouTube
  File "C:\Users\PC\AppData\Local\Programs\Python\Python36\lib\site-packages\pytube\__init__.py", line 16, in <module>
    from pytube.streams import Stream
  File "C:\Users\PC\AppData\Local\Programs\Python\Python36\lib\site-packages\pytube\streams.py", line 17, in <module>
    from pytube import extract
  File "C:\Users\PC\AppData\Local\Programs\Python\Python36\lib\site-packages\pytube\extract.py", line 7, in <module>
    from pytube.compat import quote
ImportError: cannot import name 'quote'
</code>```

what was the problem that I have made here. I have finished all the basic of python. So I'm aspiring to something new project in python. can anybody help me please?

This was the GUI code that I had used here, but make same problem here.

```<code>import tkinter as tk

from pytube import YouTube
def downloadVid():
    global E1
    string =E1.get()
    yt = YouTube(str(string))
    videos = yt.get_videos()
    s=1
    for v in videos:
        print(str(s) + '.' + str(v))
        s +=1
    n=int(input("Enter your choice"))
    vid=videos[n-1]
    destination=str(input("Enter your destination"))
    vid.download(destination)
    print(yt.filename+"\n Ha been downloaded")
root=tk.Tk()

w=tk.Label(root,text="Youtube Downloader")
w.pack()

E1=tk.Entry(root,bd=5)
E1.pack(side=tk.TOP)

button=tk.Button(root,text="Download",fg="red",command=downloadVid   )
button.pack(side=tk.BOTTOM)

root.mainloop()
</code>```

答:
I found this github issue with a possible solution:
ImportError: cannot import name 'quote' from 'pytube.compat'</p>
```<code>pip uninstall pytube
pip install pytube3
</code>```

Title: ImportError: cannot import name 'quote'

Body:
I have learned basics of python, so tried this code below

from pytube import YouTube

Save_path="E:\python\youtube downloader"

link="https://www.youtube.com/watch?v=xWOoBJUqlbI"

try:
    yt=YouTube(link)

except:
    print("Connection error!")

mp4file=yt.filter('mp4')

yt.set_filename("ashshak")

d_file=yt.get(mp4files[-1].extention,mp4files[-1].resolution)

try:
    d_file.download(Save_path)

except:
    print("Error in downlaod")
    print("Download failed")

when I try this code or with GUI interface code I have given bellow, the compiler will show this error. but  I have already installed "pip install pytube" library

Traceback (most recent call last):
  File "E:\python\youtube downloader\practiceyoutube.py", line 1, in <module>
    from pytube import YouTube
  File "C:\Users\PC\AppData\Local\Programs\Python\Python36\lib\site-packages\pytube\__init__.py", line 16, in <module>
    from pytube.streams import Stream
  File "C:\Users\PC\AppData\Local\Programs\Python\Python36\lib\site-packages\pytube\streams.py", line 17, in <module>
    from pytube import extract
  File "C:\Users\PC\AppData\Local\Programs\Python\Python36\lib\site-packages\pytube\extract.py", line 7, in <module>
    from pytube.compat import quote
ImportError: cannot import name 'quote'

what was the problem that I have made here. I have finished all the basic of python. So I'm aspiring to something new project in python. can anybody help me please?

This was the GUI code that I had used here, but make same problem here.

import tkinter as tk

from pytube import YouTube
def downloadVid():
    global E1
    string =E1.get()
    yt = YouTube(str(string))
    videos = yt.get_videos()
    s=1
    for v in videos:
        print(str(s) + '.' + str(v))
        s +=1
    n=int(input("Enter your choice"))
    vid=videos[n-1]
    destination=str(input("Enter your destination"))
    vid.download(destination)
    print(yt.filename+"\n Ha been downloaded")
root=tk.Tk()

w=tk.Label(root,text="Youtube Downloader")
w.pack()

E1=tk.Entry(root,bd=5)
E1.pack(side=tk.TOP)

button=tk.Button(root,text="Download",fg="red",command=downloadVid   )
button.pack(side=tk.BOTTOM)

root.mainloop()

Body:
I found this github issue with a possible solution:
ImportError: cannot import name 'quote' from 'pytube.compat'

pip uninstall pytube
pip install pytube3


问:
How to check if a image has any text or not?
I'm looking for a simple solution that would return a boolean if ANY kind of English text is present in an image file. I wish to use this to detect memes. For example, the following file should be detected as an image with text.

I've come across elaborate machine learning techniques using OpenCV but I haven't been able to fully implement it. Is there any quicker, simpler, and just as effective solution for this?

I look forward to your valuable feedback!

答:
There is indeed simple way with opencv and pytessaract after installing you will only need to use a few lines in order to get the text

pip install opencv-python

pip install pytesseract

```<code>import cv2
import pytesseract

img = cv2.imread('yourimage.jpeg')

text = pytesseract.image_to_string(img)
</code>```

Read Text from Image with One Line of Python Code

Also if you don't like the first way you can use Google vision, keep in mind it will return Json and you will extract what you need.

https://cloud.google.com/vision/docs/ocr

Python Client for Google Cloud Vision

Body:
There is indeed simple way with opencv and pytessaract after installing you will only need to use a few lines in order to get the text

pip install opencv-python

pip install pytesseract

import cv2
import pytesseract

img = cv2.imread('yourimage.jpeg')

text = pytesseract.image_to_string(img)

Read Text from Image with One Line of Python Code

Also if you don't like the first way you can use Google vision, keep in mind it will return Json and you will extract what you need.

https://cloud.google.com/vision/docs/ocr

Python Client for Google Cloud Vision


问:
How to add value with zen coding?
I like to add value when I type zen coding. For example, input:text becomes :. How do I make it so that input:text becomes  and place keyboard cursor between '' of value property?</p>

答: As far as I know, you can't - at least not in the default Zen Coding standard. There is at least one project that tries to add values and some rudimentary logic (like looping) to Zen Coding though, see https://github.com/zodoz/jquery-ZenCoding. This is a Javascript implementation, mind.</p>

Title: How to add value with zen coding?


问:
Why is my copy constructor not working? (C++)
I'm studying C++ and created this simple code to practice copy constructors.

```<code>class Cube{
    private:
        double length;
    public:
        Cube(){
            length = 1;
            cout << "default constructor called" << endl;
        };
        Cube(const Cube& obj){
            length = obj.length;
            cout << "copy constructor called" << endl;
        };
};

Cube foo(){
    Cube c;
    return c;
}

int main(){
    Cube c2 = foo();
    return 0;
}
</code>```

I expected this to print

"default constructor called"

"copy constructor called"

"copy constructor called"

as default constructor is called in "Cube C", and copy constructor is called in "return c" and "Cube c2 = foo()".

However my console only shows "default constructor called"

Am I misunderstanding on how copy constructor works?

答:
This won't call your copy constructor, instead what happens is that the created object in foo gets initialized to c2.

```<code>Cube c2 = foo();
</code>```

This will call the = assignment operator:

```<code>Cube c2; // default constructor
c2 = foo(); // default constructor inside foo() and then assignment operator
</code>```

This will call the copy constructor:

```<code>Cube c3; // default constructor
Cube c2(c3); // copy constructor
</code>```

The copy constructor has the syntax:

```<code>Cube(const Cube& obj)
</code>```

It is a constructor that creates a copy of an object from another object.

Body:
I'm studying C++ and created this simple code to practice copy constructors.

class Cube{
    private:
        double length;
    public:
        Cube(){
            length = 1;
            cout << "default constructor called" << endl;
        };
        Cube(const Cube& obj){
            length = obj.length;
            cout << "copy constructor called" << endl;
        };
};

Cube foo(){
    Cube c;
    return c;
}

int main(){
    Cube c2 = foo();
    return 0;
}

I expected this to print

"default constructor called"

"copy constructor called"

"copy constructor called"

as default constructor is called in "Cube C", and copy constructor is called in "return c" and "Cube c2 = foo()".

However my console only shows "default constructor called"

Am I misunderstanding on how copy constructor works?

Body:
This won't call your copy constructor, instead what happens is that the created object in foo gets initialized to c2.

Cube c2 = foo();

This will call the = assignment operator:

Cube c2; // default constructor
c2 = foo(); // default constructor inside foo() and then assignment operator

This will call the copy constructor:

Cube c3; // default constructor
Cube c2(c3); // copy constructor

The copy constructor has the syntax:

Cube(const Cube& obj)

It is a constructor that creates a copy of an object from another object.