问:
Display images on google map markers using viewinfowindow
I am trying to display images when user clicks on marker but unable to make it. The map id displayed and the marker too,but when I click on marker it isn't showing any image. Can anyone help me in displaying images:
Here is my code :</p>

```<code><html>
        <body>
    <head>
<script src="http://maps.googleapis.com/maps/api/js">
       </script>
<script>
       var x=12.35;
       var y=14.25;
       var myCenter=new google.maps.LatLng(x,y);

       function initialize()
       {
       var mapProp = {
                      center:myCenter,
                      zoom:10,
                      mapTypeId:google.maps.MapTypeId.ROADMAP
                      };

       var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);

       var marker=new google.maps.Marker({
                      position:myCenter,
                                          });

       marker.setMap(map);

       var infowindow=new google.maps.Infowindow({
                                                  content:'<div><img src="download.png"></img></div>'
                                                });
       infowindow.open(map,marker);
       }
       google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
       <div id="googleMap" style="width:500px;height:500px;"></div>
</body>
</body>
</html>
</code>```

答:
First issue is with google.maps.Infowindow it should be google.maps.InfoWindow. Capitalization matters!

That will resolve the issue with the window not opening.

For getting your popup to open and close on mouse click you will need to add click handlers to your marker like so.

```<code>        var currentPopup;

        google.maps.event.addListener(marker, "click", function() {
            if (currentPopup != null) {
                currentPopup.close();
                currentPopup = null;
            }
            infowindow.open(map, marker);
            currentPopup = infowindow;
        });

        google.maps.event.addListener(infowindow, "closeclick", function() {
            map.panTo(center);
            currentPopup = null;
        });
</code>```

The first method adds an event listener to the marker and assigns it to a variable to ensure that multiple InfoWindows are not generated then opens the popup. The closeclick method nulls out the variable which closes the popup.

        var x=12.35;
        var y=14.25;
        var myCenter=new google.maps.LatLng(x,y);

        function initialize()
        {
            var mapProp = {
                center:myCenter,
                zoom:10,
                mapTypeId:google.maps.MapTypeId.ROADMAP
            };

            var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);

            var marker=new google.maps.Marker({
                position:myCenter,
            });

            marker.setMap(map);

            var infowindow=new google.maps.InfoWindow({
                content:'

'
            });

            var currentPopup;

            google.maps.event.addListener(marker, "click", function() {
                if (currentPopup != null) {
                    currentPopup.close();
                    currentPopup = null;
                }
                infowindow.open(map, marker);
                currentPopup = infowindow;
            });

            google.maps.event.addListener(infowindow, "closeclick", function() {
                map.panTo(center);
                currentPopup = null;
            });

        }
        google.maps.event.addDomListener(window, 'load', initialize);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<body>
<head>
    <script src="http://maps.googleapis.com/maps/api/js"></script>
</head>
<body>
<div id="googleMap" style="width:500px;height:500px;"></div>
</body>
</body>
</html></code>```

Body:
First issue is with google.maps.Infowindow it should be google.maps.InfoWindow. Capitalization matters!

That will resolve the issue with the window not opening.

For getting your popup to open and close on mouse click you will need to add click handlers to your marker like so.

        var currentPopup;

        google.maps.event.addListener(marker, "click", function() {
            if (currentPopup != null) {
                currentPopup.close();
                currentPopup = null;
            }
            infowindow.open(map, marker);
            currentPopup = infowindow;
        });

        google.maps.event.addListener(infowindow, "closeclick", function() {
            map.panTo(center);
            currentPopup = null;
        });

The first method adds an event listener to the marker and assigns it to a variable to ensure that multiple InfoWindows are not generated then opens the popup. The closeclick method nulls out the variable which closes the popup.

        var x=12.35;
        var y=14.25;
        var myCenter=new google.maps.LatLng(x,y);

        function initialize()
        {
            var mapProp = {
                center:myCenter,
                zoom:10,
                mapTypeId:google.maps.MapTypeId.ROADMAP
            };

            var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);

            var marker=new google.maps.Marker({
                position:myCenter,
            });

            marker.setMap(map);

            var infowindow=new google.maps.InfoWindow({
                content:'<div><img src="icon.png"></img></div>'
            });

            var currentPopup;

            google.maps.event.addListener(marker, "click", function() {
                if (currentPopup != null) {
                    currentPopup.close();
                    currentPopup = null;
                }
                infowindow.open(map, marker);
                currentPopup = infowindow;
            });

            google.maps.event.addListener(infowindow, "closeclick", function() {
                map.panTo(center);
                currentPopup = null;
            });

        }
        google.maps.event.addDomListener(window, 'load', initialize);

<html>
<body>
<head>
    <script src="http://maps.googleapis.com/maps/api/js"></script>
</head>
<body>
<div id="googleMap" style="width:500px;height:500px;"></div>
</body>
</body>
</html>


来源: stackexchange

问:
What could cause a VB.NET application to crash before running any code?
My VB.NET application compiles, installs and works fine on the development PC.

However, when I take the install package elsewhere, it installs ok but crashes before any code is executed.

The error is " has encountered a problem and needs to close..."

I have removed all references to external files e.g. icon files etc.

I have only one local dll and the reference seems ok.

What other issues could cause this problem?

Thanks!
Jon

Update: On 1 PC, re-installing MDAC has solved the issue. However most client's are XP, and so this is not going to help.

I am still receiving the same error on some Windows XP laptops.

答: I've seen this before with an invalid app.config file.  Given the error you just posted, you might check the manifest file for the machine as well.</p>

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Joel Coehoorn


问:
C/C++ API ODBC process ID
I would like to know if it's possible to get the current process id of an SQL connection through ODBC C/C++ API.
Under SqlServer it is @@spid, connection_id() with MySQL.
Cannot find that in ODBC documentation.

Thanks...

答:
You can write a stored procedure to return @@spid on the connection

CREATE PROC

    GetSPID

AS

    SELECT @@SPID AS 'ID';

Then exec as per usual OBDC API

Title: C/C++ API ODBC process ID


问:
Moving rows in sqlite database
I have a table that is actually a ranking list. I want to give user a chance to rearrange that top the way he wants, ergo, allow him to move the rows in that table. Should I create a separate column that would hold the place, or can it be done using embedded order in table?</p>

答:
The documentation says:

If a SELECT statement that returns more than one row does not have an ORDER BY clause, the order in which the rows are returned is undefined.

(This is true for all SQL databases.)

So you cannot rely on the order that the rows happen to be stored in; you have to use some value in some table column.

ContentLicense: CC BY-SA 3.0

Title: Moving rows in sqlite database


问:
MySql table column deleted its AI flag when I altered the size of the column from BIGINT(11) to BIGINT(20)
I have a table name file_upload
It has column upload_id as BIGINT(11) AI PK NOT NULL
when I altered the tables column size to BIGINT(20) the AI flag got deleted,
Should I provide the new definition to the column everytime I alter anything from the column?</p>

Body:
Only a little note. There is no real difference between BIGINT(10) and BIGINT(20). You can store always the same values. The size if only use with ZEROFILL.

See my Sample

mysql> CREATE TABLE `bigints` (
    ->   `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
    ->   `bigint1` BIGINT(1) UNSIGNED DEFAULT NULL,
    ->   `bigint10` BIGINT(10) UNSIGNED ZEROFILL DEFAULT NULL,
    ->   `bigint20` BIGINT(20) UNSIGNED ZEROFILL DEFAULT NULL,
    ->   PRIMARY KEY (`id`)
    -> ) ENGINE=INNODB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
Query OK, 0 rows affected (0,04 sec)

mysql>
mysql> INSERT INTO `bigints` (`id`, `bigint1`, `bigint10`, `bigint20`)
    -> VALUES
    ->     (1, 1, 1, 1),
    ->     (2, 100, 100, 100),
    ->     (3, 1000000000, 1000000000, 1000000000),
    ->     (4, 18446744073709551615, 18446744073709551615, 18446744073709551615);
Query OK, 4 rows affected (0,01 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> SELECT * from bigints;
+----+----------------------+----------------------+----------------------+
| id | bigint1              | bigint10             | bigint20             |
+----+----------------------+----------------------+----------------------+
|  1 |                    1 |           0000000001 | 00000000000000000001 |
|  2 |                  100 |           0000000100 | 00000000000000000100 |
|  3 |           1000000000 |           1000000000 | 00000000001000000000 |
|  4 | 18446744073709551615 | 18446744073709551615 | 18446744073709551615 |
+----+----------------------+----------------------+----------------------+
4 rows in set (0,01 sec)

mysql>


问:
Drawing connect 4 board in Java
I am using WindowBuilder in eclipse to draw a board for my connect 4 game. The first 2 images in the link below are what I currently have.

It works but it's rectangular. How can I change the labels of the board to make them circular so it would look more like the 3rd pic in the link.

答:
You can use an AlphaComposite.

Here is some code I found on the web years ago. Just click on a column to start the animation:

```<code>import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;

public class CompositeBoardTest extends JFrame {
    private static int size = 400;
    private static int offset = 10;
    private static int ovalSize = size/4 - offset*2;
    private static int pos = offset/2;
    private static int incr = size/4;

    public static void main( String[] args ) throws Exception {
        SwingUtilities.invokeLater( new Runnable() {
            public void run() { new CompositeBoardTest(); }
        } );
    }

    public CompositeBoardTest() {
        super( "CompositeBoardTest" );
        setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

        Board board = new Board();
        getContentPane().add( board );
        setSize( size, size+34 );
        setVisible( true );
    }

    static class Board extends JPanel implements ActionListener {
        private int[][] pieces = new int[4][4];
        private Piece addingPiece = null;
        private Timer pieceDropped = null;

        public Board() {
            setPreferredSize( new Dimension( size, size ) );
            setBounds( 0, 0, size, size );
            pieceDropped = new Timer( 50, this );
            addMouseListener( new MouseAdapter() {
                public void mousePressed( MouseEvent e ) {
                    int column = ( e.getPoint().x-pos )/incr;
                    addPiece( column );
                }
            });
        }

        protected void paintComponent( Graphics g ) {
            super.paintComponent( g );

            Graphics2D g2d = (Graphics2D) g;
            Composite comp = g2d.getComposite();

            Dimension d = getSize();
            int w = d.width;
            int h = d.height;

            BufferedImage buffImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
            Graphics2D gbi = buffImg.createGraphics();

            // Clear area
            g2d.setColor( Color.WHITE );
            g2d.fillRect( 0, 0, w, h );

            // Draw screen
//          gbi.setColor( Color.YELLOW );
            gbi.setColor( Color.BLUE );
            gbi.fillRect( 0, 0, w, h );

            // Draw pieces or holes
            gbi.setColor( Color.RED );
            for ( int row = 0 ; row < 4 ; row++ ) {
                for ( int column = 0 ; column < 4 ; column++ ) {
                    if ( pieces[row][column] == 1 ) {
                        gbi.setComposite( AlphaComposite.getInstance( AlphaComposite.SRC_OVER, .1f ) );
                    } else {
                        gbi.setComposite( AlphaComposite.getInstance( AlphaComposite.CLEAR, 0.5f ) );
                    }
                    gbi.fillOval( incr*column+pos, incr*row+pos, ovalSize, ovalSize );
                }
            }

            // Draw adding piece if we have it
            if ( addingPiece != null ) {
                gbi.setComposite( AlphaComposite.getInstance( AlphaComposite.DST_OVER, 1.0f ) );
                gbi.fillOval( addingPiece.x, addingPiece.y, ovalSize, ovalSize );
            }

            // Draws the buffered image.
            g2d.drawImage(buffImg, null, 0, 0);

//          g2d.setComposite( comp );
        }

        public void addPiece( int column ) {
            if ( addingPiece == null ) {
                if ( pieces[0][column] == 0 ) {
                    addingPiece = new Piece();
                    addingPiece.row = 0;
                    addingPiece.column = column;
                    addingPiece.x = incr*column+pos;
                    addingPiece.y = 0;
                    pieceDropped.start();
                } else {
                    getToolkit().beep();
                }
            }
        }

        public void actionPerformed( ActionEvent e ) {
            if ( addingPiece != null ) {
                addingPiece.y += 5;
                int row = ( addingPiece.y - pos )/incr + 1;
                if ( row > 3 || pieces[row][addingPiece.column] == 1 ) {
                    pieces[row-1][addingPiece.column] = 1;
                    addingPiece = null;
                    pieceDropped.stop();
                }
            }
            repaint();
        }
    }

    private static class Piece {
        public int row, column, x, y;
    }
}
</code>```

(Sorry I don't remember the original creator)

Title: Drawing connect 4 board in Java

Body:
You can use an AlphaComposite.

Here is some code I found on the web years ago. Just click on a column to start the animation:

import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;

public class CompositeBoardTest extends JFrame {
    private static int size = 400;
    private static int offset = 10;
    private static int ovalSize = size/4 - offset*2;
    private static int pos = offset/2;
    private static int incr = size/4;

    public static void main( String[] args ) throws Exception {
        SwingUtilities.invokeLater( new Runnable() {
            public void run() { new CompositeBoardTest(); }
        } );
    }

    public CompositeBoardTest() {
        super( "CompositeBoardTest" );
        setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

        Board board = new Board();
        getContentPane().add( board );
        setSize( size, size+34 );
        setVisible( true );
    }

    static class Board extends JPanel implements ActionListener {
        private int[][] pieces = new int[4][4];
        private Piece addingPiece = null;
        private Timer pieceDropped = null;

        public Board() {
            setPreferredSize( new Dimension( size, size ) );
            setBounds( 0, 0, size, size );
            pieceDropped = new Timer( 50, this );
            addMouseListener( new MouseAdapter() {
                public void mousePressed( MouseEvent e ) {
                    int column = ( e.getPoint().x-pos )/incr;
                    addPiece( column );
                }
            });
        }

        protected void paintComponent( Graphics g ) {
            super.paintComponent( g );

            Graphics2D g2d = (Graphics2D) g;
            Composite comp = g2d.getComposite();

            Dimension d = getSize();
            int w = d.width;
            int h = d.height;

            BufferedImage buffImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
            Graphics2D gbi = buffImg.createGraphics();

            // Clear area
            g2d.setColor( Color.WHITE );
            g2d.fillRect( 0, 0, w, h );

            // Draw screen
//          gbi.setColor( Color.YELLOW );
            gbi.setColor( Color.BLUE );
            gbi.fillRect( 0, 0, w, h );

            // Draw pieces or holes
            gbi.setColor( Color.RED );
            for ( int row = 0 ; row < 4 ; row++ ) {
                for ( int column = 0 ; column < 4 ; column++ ) {
                    if ( pieces[row][column] == 1 ) {
                        gbi.setComposite( AlphaComposite.getInstance( AlphaComposite.SRC_OVER, .1f ) );
                    } else {
                        gbi.setComposite( AlphaComposite.getInstance( AlphaComposite.CLEAR, 0.5f ) );
                    }
                    gbi.fillOval( incr*column+pos, incr*row+pos, ovalSize, ovalSize );
                }
            }

            // Draw adding piece if we have it
            if ( addingPiece != null ) {
                gbi.setComposite( AlphaComposite.getInstance( AlphaComposite.DST_OVER, 1.0f ) );
                gbi.fillOval( addingPiece.x, addingPiece.y, ovalSize, ovalSize );
            }

            // Draws the buffered image.
            g2d.drawImage(buffImg, null, 0, 0);

//          g2d.setComposite( comp );
        }

        public void addPiece( int column ) {
            if ( addingPiece == null ) {
                if ( pieces[0][column] == 0 ) {
                    addingPiece = new Piece();
                    addingPiece.row = 0;
                    addingPiece.column = column;
                    addingPiece.x = incr*column+pos;
                    addingPiece.y = 0;
                    pieceDropped.start();
                } else {
                    getToolkit().beep();
                }
            }
        }

        public void actionPerformed( ActionEvent e ) {
            if ( addingPiece != null ) {
                addingPiece.y += 5;
                int row = ( addingPiece.y - pos )/incr + 1;
                if ( row > 3 || pieces[row][addingPiece.column] == 1 ) {
                    pieces[row-1][addingPiece.column] = 1;
                    addingPiece = null;
                    pieceDropped.stop();
                }
            }
            repaint();
        }
    }

    private static class Piece {
        public int row, column, x, y;
    }
}

(Sorry I don't remember the original creator)

ContentLicense: CC BY-SA 4.0


问:
Perceive Dimensions (or prominent points) of a Cuboid in a 2D image using OpenCV
I was wondering if it is possible to find the dimensions (in pixel) of a cube/cuboid in an image like the one shown below?

I know its nearly impossible because of no information about the depth,the viewing angle, etc. But at least can one find the appropriate corners of the cube so that the length, width and height can be approximated?

Any type help or information would be appreciated.

Thanks in advance.

答:
I guess I could suggest a solution to the "at least" part of the question. You can find the corners of the cube by finding the lines in the image.

Firstly, find the edges in the image. If the target images are as plain and clear as the provided one, finding edges must be straighforward. Use cv::Canny().

```<code>cv::Mat img = cv::imread("cube.png");
cv::Mat edges;
cv::Canny(img, edges, 20, 60);
</code>```

Secondly, in the edges image, detect the straight lines. Use either cv::HoughLines() or cv::HoughLinesP(). Here, I proceed with the former one:

```<code>std::vector<cv::Vec2f> lines;
cv::HoughLines(edges, lines, 0.6, CV_PI / 120, 50);
</code>```

Plaese refer to the on the OpenCV documentation on Hough lines. I also took the code for the visualization from there.

The cv::HoughLines() function detects straight lines and, for each line, returns 2 values (ρ - distance, and θ - rotation angle) which define this line's equation in polar coordinates. This function would often return several lines for one source edge (as it did for a couple of lines here). In our case, we can remove such duplicates by filtering lines with the very close ρ values.

The benefit of our case is that the sides of the cube resposible for each dimension (length, width, and height) will have the same rotation angle θ in found line equations. For instance, we can expect vertical sides of the cube (responsible for the height dimension) to remain vertical and have their θ close to 0 or π (see the OpenCV documentation). We could find such lines in the vector of the detected Hough lines:

```<code>std::vector<cv::Vec2f> vertical_lines;
std::copy_if(lines.begin(), lines.end(), std::back_inserter(vertical_lines), [](cv::Vec2f line) {
    //copy if θ is near 0 or CV_PI
    return ((0 < line[1]) && (line[1] < 0 + CV_PI / 10)) ||
           ((line[1] < CV_PI) && (line[1] > CV_PI - CV_PI / 10));
});
</code>```

The same reasoning applies to finding the lines for the rest of the cube sides. Just filter the found Hough lines by appropriate θ.

Now that we have the equations of the lines of our interest, we can find their corresponding edge pixels (not optimal code below, just demo):

```<code>std::vector<cv::Point> non_zero_points;
cv::findNonZero(edges, non_zero_points);

std::vector<std::vector<cv::Point>> corresponding_points(vertical_lines.size());
for (int i = 0; i < vertical_lines.size(); ++i)
    for (auto point : non_zero_points)
        if (abs(cos(vertical_lines[i][1])*point.x + sin(vertical_lines[i][1])*point.y - vertical_lines[i][0]) < 2)
            corresponding_points[i].push_back(point);
</code>```

Now, for each found cluster find the top-most, the bottom-most points (or left-most/right-most for the other sides) and get your cube corners.

Please note the pixel I denoted by exclamation marks. It got accidently sorted to one of the vertical Hough lines, but it actually belongs to a non-vertical top side. It needs to be removed, by some outlier detection or by some other approach to the corresponding pixel search.

About retreiving actual lengths of the sides: to my knowledge, it is really a non-trivial problem. Maybe this SO question would be a good place to start.

Body:
I guess I could suggest a solution to the "at least" part of the question. You can find the corners of the cube by finding the lines in the image.

Firstly, find the edges in the image. If the target images are as plain and clear as the provided one, finding edges must be straighforward. Use cv::Canny().

cv::Mat img = cv::imread("cube.png");
cv::Mat edges;
cv::Canny(img, edges, 20, 60);

Secondly, in the edges image, detect the straight lines. Use either cv::HoughLines() or cv::HoughLinesP(). Here, I proceed with the former one:

std::vector<cv::Vec2f> lines;
cv::HoughLines(edges, lines, 0.6, CV_PI / 120, 50);

Plaese refer to the on the OpenCV documentation on Hough lines. I also took the code for the visualization from there.

The cv::HoughLines() function detects straight lines and, for each line, returns 2 values (ρ - distance, and θ - rotation angle) which define this line's equation in polar coordinates. This function would often return several lines for one source edge (as it did for a couple of lines here). In our case, we can remove such duplicates by filtering lines with the very close ρ values.

The benefit of our case is that the sides of the cube resposible for each dimension (length, width, and height) will have the same rotation angle θ in found line equations. For instance, we can expect vertical sides of the cube (responsible for the height dimension) to remain vertical and have their θ close to 0 or π (see the OpenCV documentation). We could find such lines in the vector of the detected Hough lines:

std::vector<cv::Vec2f> vertical_lines;
std::copy_if(lines.begin(), lines.end(), std::back_inserter(vertical_lines), [](cv::Vec2f line) {
    //copy if θ is near 0 or CV_PI
    return ((0 < line[1]) && (line[1] < 0 + CV_PI / 10)) ||
           ((line[1] < CV_PI) && (line[1] > CV_PI - CV_PI / 10));
});

The same reasoning applies to finding the lines for the rest of the cube sides. Just filter the found Hough lines by appropriate θ.

Now that we have the equations of the lines of our interest, we can find their corresponding edge pixels (not optimal code below, just demo):

std::vector<cv::Point> non_zero_points;
cv::findNonZero(edges, non_zero_points);

std::vector<std::vector<cv::Point>> corresponding_points(vertical_lines.size());
for (int i = 0; i < vertical_lines.size(); ++i)
    for (auto point : non_zero_points)
        if (abs(cos(vertical_lines[i][1])*point.x + sin(vertical_lines[i][1])*point.y - vertical_lines[i][0]) < 2)
            corresponding_points[i].push_back(point);

Now, for each found cluster find the top-most, the bottom-most points (or left-most/right-most for the other sides) and get your cube corners.

Please note the pixel I denoted by exclamation marks. It got accidently sorted to one of the vertical Hough lines, but it actually belongs to a non-vertical top side. It needs to be removed, by some outlier detection or by some other approach to the corresponding pixel search.

About retreiving actual lengths of the sides: to my knowledge, it is really a non-trivial problem. Maybe this SO question would be a good place to start.


问:
Checking several If conditions in C randomly
I have a program in C programming language in which there are several if conditions like below:

    if(condition 1) {instructions}

 if(condition 2) {instructions}

 if(condition 3) {instructions}

 // and some other conditions

Is there anyway that, when I run the program each time, the checking order of Ifs rearranged randomly e.g. like below:

    if(condition 3) {instructions}

 if(condition 1) {instructions}

 if(condition 2) {instructions}

 // and some other conditions

答:
You could:

put each if(conditition) { instructions } in a function so that each function has the same signature

create an array of function pointers to the functions

shuffle the array

go through the array and call each member

(Alternatively, if you're concerned about fn-call overhead but not standard compliance, you could replace the function pointers with GNU computed gotos).

Below is an example based computed gotos, which are here used as cheaper, addressable functions:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

void shuffle(void *obj, size_t nmemb, size_t size);

#define ARRAY_SIZE(A) (sizeof(A)/sizeof(A[0]))

int main(int c, char **v)
{
    int n = c>1 ? atoi(v[1]) : 0;
    void *ret=&&ret_lbl;
    int i;
    srand(time(0));

    void *checks[] = { &&lt_10, &&lt_100, &&lt_1000, &&lt_10000 };
    shuffle(checks, ARRAY_SIZE(checks), sizeof checks[0]);

    for(i=0; i<ARRAY_SIZE(checks); i++){
        goto *checks[i];
        ret_lbl:;
    }

return 0;

    /*the if checks*/

    lt_10: if (n < 10)  puts("lt_10");
           goto *ret;
    lt_100: if (n < 100)  puts("lt_100");
           goto *ret;
    lt_1000: if (n < 1000)  puts("lt_1000");
           goto *ret;
    lt_10000: if (n < 10000)  puts("lt_10000");
           goto *ret;

}

/* From
   http://rosettacode.org/wiki/Knuth_shuffle#C
*/
int rrand(int m)
{
  return (int)((double)m * ( rand() / (RAND_MAX+1.0) ));
}

#define BYTE(X) ((unsigned char *)(X))
void shuffle(void *obj, size_t nmemb, size_t size)
{
  void *temp = malloc(size);
  size_t n = nmemb;
  while ( n > 1 ) {
    size_t k = rrand(n--);
    memcpy(temp, BYTE(obj) + n*size, size);
    memcpy(BYTE(obj) + n*size, BYTE(obj) + k*size, size);
    memcpy(BYTE(obj) + k*size, temp, size);
  }
  free(temp);
}
</code>```

Body:
You could:

put each if(conditition) { instructions } in a function so that each function has the same signature

create an array of function pointers to the functions

shuffle the array

go through the array and call each member

(Alternatively, if you're concerned about fn-call overhead but not standard compliance, you could replace the function pointers with GNU computed gotos).

Below is an example based computed gotos, which are here used as cheaper, addressable functions:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

void shuffle(void *obj, size_t nmemb, size_t size);

#define ARRAY_SIZE(A) (sizeof(A)/sizeof(A[0]))

int main(int c, char **v)
{
    int n = c>1 ? atoi(v[1]) : 0;
    void *ret=&&ret_lbl;
    int i;
    srand(time(0));

    void *checks[] = { &&lt_10, &&lt_100, &&lt_1000, &&lt_10000 };
    shuffle(checks, ARRAY_SIZE(checks), sizeof checks[0]);

    for(i=0; i<ARRAY_SIZE(checks); i++){
        goto *checks[i];
        ret_lbl:;
    }

return 0;

    /*the if checks*/

    lt_10: if (n < 10)  puts("lt_10");
           goto *ret;
    lt_100: if (n < 100)  puts("lt_100");
           goto *ret;
    lt_1000: if (n < 1000)  puts("lt_1000");
           goto *ret;
    lt_10000: if (n < 10000)  puts("lt_10000");
           goto *ret;

}

/* From
   http://rosettacode.org/wiki/Knuth_shuffle#C
*/
int rrand(int m)
{
  return (int)((double)m * ( rand() / (RAND_MAX+1.0) ));
}

#define BYTE(X) ((unsigned char *)(X))
void shuffle(void *obj, size_t nmemb, size_t size)
{
  void *temp = malloc(size);
  size_t n = nmemb;
  while ( n > 1 ) {
    size_t k = rrand(n--);
    memcpy(temp, BYTE(obj) + n*size, size);
    memcpy(BYTE(obj) + n*size, BYTE(obj) + k*size, size);
    memcpy(BYTE(obj) + k*size, temp, size);
  }
  free(temp);
}


问:
Is it possible to create a GridView that has children of different sizes?
So let's try to explain what I am trying to do...

I have a design that looks like this -

![alt text][1]

For this I have I created two GridViews like so:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="wrap_content">

    <LinearLayout android:orientation="vertical"
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content">

        <TextView style="@style/GroupName"
                  android:text="@string/currency_badges"/>

        <GridView android:id="@+id/currency_grid"
                  android:layout_width="fill_parent"
                  android:layout_height="wrap_content"
                  android:columnWidth="90dp"
                  android:numColumns="auto_fit"
                  android:verticalSpacing="10dp"
                  android:horizontalSpacing="10dp"
                  android:stretchMode="columnWidth"
                  android:gravity="left"/>

    </LinearLayout>

    <LinearLayout android:orientation="vertical"
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content">

        <TextView style="@style/GroupName"
                  android:text="@string/foursquare_badges"/>

        <GridView android:id="@+id/foursquare_grid"
                  android:layout_width="fill_parent"
                  android:layout_height="wrap_content"
                  android:columnWidth="90dp"
                  android:numColumns="auto_fit"
                  android:verticalSpacing="10dp"
                  android:horizontalSpacing="10dp"
                  android:stretchMode="columnWidth"
                  android:gravity="left"/>

    </LinearLayout>
</LinearLayout>
</code>```

I am not really happy with it because as you can see the top right icon's label is hidden. I can click and scroll but that's not what I want. Also the bigger problem is that each GridView HAS ITS OWN SCROLLBAR. Again not what I want. So I think I would like to use one GridView to accomplish this. How can I use a GridView to have icons and then show the GroupName in the middle of the icons. I know I can create a BaseAdapter to return different types of Views, but I need to have one item that takes horizontally the whole space. Is this possible?

Edit:

I guess a better question is how do I create grouped GridViews?

答: I'm not sure how you are adding items right now, but you might look at using a SimpleAdapter.  It lets you supply an xml layout and map items from your data objects into places in the xml layout.  There are a number of tutorials for using it if you do a quick search.</p>

Body:
So let's try to explain what I am trying to do...

I have a design that looks like this -

![alt text][1]

For this I have I created two GridViews like so:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="wrap_content">

    <LinearLayout android:orientation="vertical"
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content">

        <TextView style="@style/GroupName"
                  android:text="@string/currency_badges"/>

        <GridView android:id="@+id/currency_grid"
                  android:layout_width="fill_parent"
                  android:layout_height="wrap_content"
                  android:columnWidth="90dp"
                  android:numColumns="auto_fit"
                  android:verticalSpacing="10dp"
                  android:horizontalSpacing="10dp"
                  android:stretchMode="columnWidth"
                  android:gravity="left"/>

    </LinearLayout>

    <LinearLayout android:orientation="vertical"
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content">

        <TextView style="@style/GroupName"
                  android:text="@string/foursquare_badges"/>

        <GridView android:id="@+id/foursquare_grid"
                  android:layout_width="fill_parent"
                  android:layout_height="wrap_content"
                  android:columnWidth="90dp"
                  android:numColumns="auto_fit"
                  android:verticalSpacing="10dp"
                  android:horizontalSpacing="10dp"
                  android:stretchMode="columnWidth"
                  android:gravity="left"/>

    </LinearLayout>
</LinearLayout>

I am not really happy with it because as you can see the top right icon's label is hidden. I can click and scroll but that's not what I want. Also the bigger problem is that each GridView HAS ITS OWN SCROLLBAR. Again not what I want. So I think I would like to use one GridView to accomplish this. How can I use a GridView to have icons and then show the GroupName in the middle of the icons. I know I can create a BaseAdapter to return different types of Views, but I need to have one item that takes horizontally the whole space. Is this possible?

Edit:

I guess a better question is how do I create grouped GridViews?


问:
Cannot access to BaseColumns provides _ID property in Kotlin
I am defining my Users SQLite database table, and to do so, I have created the following UserContract and UserEntry classes:

```<code>class UserContract private constructor(){

    class UserEntry private constructor(): BaseColumns {

        companion object {
            val TABLE_NAME = "users"
            val COLUMN_DISPLAY_NAME = "display_name"
            val COLUMN_EMAIL = "email"
            //...
        }
    }
}
</code>```

The problem I am facing is that I cannot access _ID property provided by BaseColums implementation:

```<code>val columnDisplayName = UserContract.UserEntry.COLUMN_DISPLAY_NAME //It is OK
val columnId = UserContract.UserEntry._ID //Unresolved reference: _ID
</code>```

The equivalent code in Java works fine, so, does anybody knows what would be the reason or where the mistake is?

答:
You can only access it using BaseColumns._ID since it's a Java interface defining a constant.

On Kotlin, a companion object is an actual object with inheritance, whereas in java a class with static methods does not really behave like an object.

For instance, if you had BaseColumns as a kotlin class instead of a java interface, you could have done something like:

```<code>open class KBaseColumns  {
    val _ID = "_id"
}

class UserContract private constructor(){
    class UserEntry private constructor(): BaseColumns {
        companion object : KBaseColumns() {
            val TABLE_NAME = "users"
            val COLUMN_DISPLAY_NAME = "display_name"
            val COLUMN_EMAIL = "email"
        }
    }
}

object Example {
    fun someMethod() {
        val id = UserContract.UserEntry._ID
    }
}
</code>```

Where _ID is accessible in this case because the companion object is actually a subclass of KBaseColumns

Body:
I am defining my Users SQLite database table, and to do so, I have created the following UserContract and UserEntry classes:

class UserContract private constructor(){

    class UserEntry private constructor(): BaseColumns {

        companion object {
            val TABLE_NAME = "users"
            val COLUMN_DISPLAY_NAME = "display_name"
            val COLUMN_EMAIL = "email"
            //...
        }
    }
}

The problem I am facing is that I cannot access _ID property provided by BaseColums implementation:

val columnDisplayName = UserContract.UserEntry.COLUMN_DISPLAY_NAME //It is OK
val columnId = UserContract.UserEntry._ID //Unresolved reference: _ID

The equivalent code in Java works fine, so, does anybody knows what would be the reason or where the mistake is?

Body:
You can only access it using BaseColumns._ID since it's a Java interface defining a constant.

On Kotlin, a companion object is an actual object with inheritance, whereas in java a class with static methods does not really behave like an object.

For instance, if you had BaseColumns as a kotlin class instead of a java interface, you could have done something like:

open class KBaseColumns  {
    val _ID = "_id"
}

class UserContract private constructor(){
    class UserEntry private constructor(): BaseColumns {
        companion object : KBaseColumns() {
            val TABLE_NAME = "users"
            val COLUMN_DISPLAY_NAME = "display_name"
            val COLUMN_EMAIL = "email"
        }
    }
}

object Example {
    fun someMethod() {
        val id = UserContract.UserEntry._ID
    }
}

Where _ID is accessible in this case because the companion object is actually a subclass of KBaseColumns


问:
Conditionally binding dropdownlist in asp.net
I have a string in this particular format

```<code>string LogInIDs = 124,345, 876 | 765,322, 98 | 565,99
</code>```

All the numbers in the string are Unique LogIn ID. Using the Pipe symbol, the grouping is done of id's. Now, Suppose the LogInID is 345, then i need to bind other numbers (in this case 124 & 876) which are in the group in a dropdown. The below function is what i have made to retrieve the other numbers.

Can anybody come up with any better idea or suggestion

```<code>public static List<string> RetrieveAffCodes(string LogInIDs , string LogInID)
{
    List<string> _finale = new List<string>();

    string[] sep1 = new string[1];
    sep1[0] = "|";

    int count = LogInIDs.Count(x => x == '|');
    string[] groups = new string[count + 1];
    groups = LogInIDs.Split(sep1, StringSplitOptions.RemoveEmptyEntries);

    foreach (string g in groups)
    {
        string p = g;
        string[] sep2 = new string[1];
        sep2[0] = ",";
        int counter = p.Count(x => x == ',');
        string[] final_list = new string[counter + 1];
        final_list = p.Split(sep2, StringSplitOptions.RemoveEmptyEntries);

        foreach (string _f in final_list)
        {
            if (_f.Trim() == LogInID)
            {
          _finale =  AddLogInIDs(final_list, final_list.Count());
            }
        }
    }
    return _finale;
}

private static List<string> AddLogInIDs(string[] final_list, int p)
{
    List<string> _finale = new List<string>();
    foreach (var item in final_list)
    {
        _finale.Add(item.Trim());
    }
    return _finale;
}
</code>```

Any suggestions will be embraced.

Thanks for your time and patience.

Note: The string will be expanding up to 200 groups

答:
Would this work for you?

```<code>using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        string LogInIDs = "124,345,876|765,322,98 |565,99";

        Console.WriteLine(string.Join("\n", RetrieveAffCodes(LogInIDs, "322")));
        Console.WriteLine(string.Join("\n", RetrieveAffCodes(LogInIDs, "565")));
    }

    public static IEnumerable<string> RetrieveAffCodes(string logInIDs , string logInID)
    {
        //We split the list
        var list = logInIDs.Split('|');
        //We look for an item with the logInID, if found (?) we split using ',' and then we remove the item
        var match = list
            .Select(i => i.Split(',').Select(item => item.Trim()))
            .FirstOrDefault(i => i.Contains(logInID))?
            .Where(i => i != logInID);

        if(match != null)
        {
            return match;
        }

        return new List<string>();

    }
}
</code>```

Source code: https://dotnetfiddle.net/M2FyNk

Body:
I have a string in this particular format

string LogInIDs = 124,345, 876 | 765,322, 98 | 565,99

All the numbers in the string are Unique LogIn ID. Using the Pipe symbol, the grouping is done of id's. Now, Suppose the LogInID is 345, then i need to bind other numbers (in this case 124 & 876) which are in the group in a dropdown. The below function is what i have made to retrieve the other numbers.

Can anybody come up with any better idea or suggestion

public static List<string> RetrieveAffCodes(string LogInIDs , string LogInID)
{
    List<string> _finale = new List<string>();

    string[] sep1 = new string[1];
    sep1[0] = "|";

    int count = LogInIDs.Count(x => x == '|');
    string[] groups = new string[count + 1];
    groups = LogInIDs.Split(sep1, StringSplitOptions.RemoveEmptyEntries);

    foreach (string g in groups)
    {
        string p = g;
        string[] sep2 = new string[1];
        sep2[0] = ",";
        int counter = p.Count(x => x == ',');
        string[] final_list = new string[counter + 1];
        final_list = p.Split(sep2, StringSplitOptions.RemoveEmptyEntries);

        foreach (string _f in final_list)
        {
            if (_f.Trim() == LogInID)
            {
          _finale =  AddLogInIDs(final_list, final_list.Count());
            }
        }
    }
    return _finale;
}

private static List<string> AddLogInIDs(string[] final_list, int p)
{
    List<string> _finale = new List<string>();
    foreach (var item in final_list)
    {
        _finale.Add(item.Trim());
    }
    return _finale;
}

Any suggestions will be embraced.

Thanks for your time and patience.

Note: The string will be expanding up to 200 groups

Body:
Would this work for you?

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        string LogInIDs = "124,345,876|765,322,98 |565,99";

        Console.WriteLine(string.Join("\n", RetrieveAffCodes(LogInIDs, "322")));
        Console.WriteLine(string.Join("\n", RetrieveAffCodes(LogInIDs, "565")));
    }

    public static IEnumerable<string> RetrieveAffCodes(string logInIDs , string logInID)
    {
        //We split the list
        var list = logInIDs.Split('|');
        //We look for an item with the logInID, if found (?) we split using ',' and then we remove the item
        var match = list
            .Select(i => i.Split(',').Select(item => item.Trim()))
            .FirstOrDefault(i => i.Contains(logInID))?
            .Where(i => i != logInID);

        if(match != null)
        {
            return match;
        }

        return new List<string>();

    }
}

Source code: https://dotnetfiddle.net/M2FyNk


问:
CSV PapaParse doesn't work for some links
I'm using PapaParse for my CSV file with JavaScript. I'm able to use a CSV file from this website and using this link, which is the 5th one down. Everything works great using this link.

The problem arises when I download this file and then upload it to either github or one of my websites and then use that link instead. So basically, if I use the same file hosted on a different site the parser doesn't work. Any idea why?

Update:

Rawgit does work for github.com files but I still can't seem to parse CSV files from my website. It's just a link so I don't know why it wouldn't work. Thoughts?

Also, the first link above is from github.io. Why do CSV files that are on github.io work and not files from github.com or my website?

document.getElementById('submit').addEventListener("click", function() {
  checkLogin();
});

function checkLogin() {

  /* DOESN'T WORK */
  // "https://github.com/dhust/test/blob/master/Formaldehyde.csv"
  // "http://csfor.us/cs1/wp-content/uploads/2017/06/Formaldehyde.csv"

  /* WORKS */
  // "https://vincentarelbundock.github.io/Rdatasets/csv/datasets/Formaldehyde.csv"

  Papa.parse("https://vincentarelbundock.github.io/Rdatasets/csv/datasets/Formaldehyde.csv", {
    download: true,
    complete: function(results) {
      document.getElementById("output").innerHTML = results.data;
      console.log(results.data);
    }
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.rawgit.com/mholt/PapaParse/3bf63f0a/papaparse.min.js"></script>
<input id="submit" type="button" value="Submit" />
<p id="output"></p></code>```

Link to JSFiddle

答:
Thanks to palfrey for leading me in the right direction. Here is what solved my problem:

Add SSL to each of my websites (free for basic SSL)

Added this to my .htaccess file in each website's root folder

```<code>Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
</code>```

Body:
I'm using PapaParse for my CSV file with JavaScript. I'm able to use a CSV file from this website and using this link, which is the 5th one down. Everything works great using this link.

The problem arises when I download this file and then upload it to either github or one of my websites and then use that link instead. So basically, if I use the same file hosted on a different site the parser doesn't work. Any idea why?

Update:

Rawgit does work for github.com files but I still can't seem to parse CSV files from my website. It's just a link so I don't know why it wouldn't work. Thoughts?

Also, the first link above is from github.io. Why do CSV files that are on github.io work and not files from github.com or my website?

document.getElementById('submit').addEventListener("click", function() {
  checkLogin();
});

function checkLogin() {

  /* DOESN'T WORK */
  // "https://github.com/dhust/test/blob/master/Formaldehyde.csv"
  // "http://csfor.us/cs1/wp-content/uploads/2017/06/Formaldehyde.csv"

  /* WORKS */
  // "https://vincentarelbundock.github.io/Rdatasets/csv/datasets/Formaldehyde.csv"

  Papa.parse("https://vincentarelbundock.github.io/Rdatasets/csv/datasets/Formaldehyde.csv", {
    download: true,
    complete: function(results) {
      document.getElementById("output").innerHTML = results.data;
      console.log(results.data);
    }
  });
}

<input id="submit" type="button" value="Submit" />

Link to JSFiddle

Body:
Thanks to palfrey for leading me in the right direction. Here is what solved my problem:

Add SSL to each of my websites (free for basic SSL)

Added this to my .htaccess file in each website's root folder

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"


问:
Use Amazon Alexa to switch on Hue Light and switch off Wemo plug simultaneously
I have a Philips Hue light dimmable bulb for a night light and a regular floor lamp connected to a Belkin Mini WeMo smart plug. I have added both as devices in the Alexa app and can control them individually, or together as part of a group. But I need their states to be mutually exlusive, i.e. when I say "switch on night light", I want the Hue light bulb to turn on and the WeMo controlled floor lamp to turn off. And vice versa. This sounds like a typical "scene", but the Alexa App does not seem to facilitate such an option. What is a good way to achieve this type of control?</p>

答:
There is a great example and write up here about how to control a WEMO device using an ESP8266. It includes code for your perusal and writing your own control.

Hope it helps.


问:
Compile angularjs templates with data to html
I am writing an Add-In for outlook client.

Think of like the user selects a item from a drop down menu and selects insert in email while composing.

The Add-In is written using angularjs and I get json data from server side. I want to compile the json data against some angular template and get the HTML div object so I can insert it in the email body.

What are my options here and how to do it,
I have the template and json data in hand on client side when the user chooses to insert in email body. How can I compile to HTML on client side? Any pointers or examples will be appreciated.

Example:
Suppose the user selects Student2 and chooses to insert in the email
And the json data I get from the server is

```<code>{ "name":"John", "age":20, "city":"New York", "profilepic":"https://profilepicurl" }
</code>```

And my template is

```<code><div>
  <span><b>{{name}}</b><i>{{age}}</i></span>
  <span>{{city}}</span>
</div>
</code>```

I want to get the below HTML so I can insert in the email

```<code><div>
  <span><b>John</b><i>21</i></span>
  <span>New York</span>
</div>
</code>```

答:
Html:

```<code><div>
  <span><b>{{myJson.name}}</b><i>{{myJson.age}}</i></span>
  <span>{{myJson.city}}</span>
</div>
</code>```

In your angularjs Controller:

```<code>$scope.myJson = { "name":"John", "age":20, "city":"New York", "profilepic":"https://profilepicurl" }
</code>```

Body:
I am writing an Add-In for outlook client.

Think of like the user selects a item from a drop down menu and selects insert in email while composing.

The Add-In is written using angularjs and I get json data from server side. I want to compile the json data against some angular template and get the HTML div object so I can insert it in the email body.

What are my options here and how to do it,
I have the template and json data in hand on client side when the user chooses to insert in email body. How can I compile to HTML on client side? Any pointers or examples will be appreciated.

Example:
Suppose the user selects Student2 and chooses to insert in the email
And the json data I get from the server is

{ "name":"John", "age":20, "city":"New York", "profilepic":"https://profilepicurl" }

And my template is

  {{name}}{{age}}
  {{city}}

I want to get the below HTML so I can insert in the email

  John21
  New York

Body:
Html:

<div>
  <span><b>{{myJson.name}}</b><i>{{myJson.age}}</i></span>
  <span>{{myJson.city}}</span>
</div>

In your angularjs Controller:

$scope.myJson = { "name":"John", "age":20, "city":"New York", "profilepic":"https://profilepicurl" }


问:
Angular Nested Comments - Values undefined when submitting form
I am trying to get a dynamic script for nested comments to work.

My first problem is that I don't know how I can do endless nesting. For now I planned to do 3 layers, cause I don't know how to make it work dynamicly.

The second problem is that when i submit the form, the values of the models is not submitted to the JS-script. The values are just undefined.

I guess my approach is just wrong - The ng-model elements are not bound inside of the ng-repeat, also the values of all forms would be bound to the same element... Maybe someone has some tips. If it is important, my backend runs with Laravel 4. Here is my code

var commentsApp = angular.module('commentsApp', []);

function CommentsCtrl($scope, $http, $compile) {

    var url_segments = window.location.host.split('.');
    var section = url_segments[0];

    $http.get('/api/' + section + window.location.pathname + '/comments').success(function (comments) {
        $scope.comments = comments;
    });

    $scope.toggleForm = function (id) {

        var container = document.getElementById(id);

        var html = '
<input name="category" type="text" ng-model="person.category" placeholder="Category" required/>Required';

        var elem = $compile(html)($scope);
        angular.element(container).append(elem);
    }

    $scope.addComment = function () {
        var comment = {
            body: $scope.body,
            commentable_id: $scope.commentable_id,
            commentable_type: $scope.commentable_type
        };

        $scope.comments.push(comment);
    };

}

commentsApp.controller('CommentsCtrl', CommentsCtrl);```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="content-row basic" ng-controller="CommentsCtrl" class="comments">
                    <form ng-submit="addComment()">
                        <input type="text" placeholder="Add Comment" ng-model="body">
                        <input type="hidden" value="@{{c.id}}" ng-model="commentable_id">
                        <input type="hidden" value="Player" ng-model="commentable_type">
                        <button type="submit">Add Comment</button>
                    </form>

                    <div ng-repeat="c in comments" class="comment">
                        <span>@{{c.author.username}}</span>
                        <p>@{{c.body}}</p>
                        Answer
                        <div class="reply-container" ng-show="showForm">
                            <form ng-submit="addComment()">
                                <input type="text" placeholder="Add Comment" ng-model="body">
                                <input type="hidden" value="@{{c.id}}" ng-model="commentable_id">
                                <input type="hidden" value="Comment" ng-model="commentable_type">
                                <button type="submit">Add Comment</button>
                            </form>
                        </div>

                        <div ng-repeat="cc in c.comments" class="s-comment">
                            <span>@{{cc.author.username}}</span>
                            <p>@{{cc.body}}</p>
                            Answer
                            <div class="reply-container" ng-show="showForm">
                                <form ng-submit="addComment()">
                                    <input type="text" placeholder="Add Comment" ng-model="body">
                                    <input type="hidden" value="@{{c.id}}" ng-model="commentable_id">
                                    <input type="hidden" value="Comment" ng-model="commentable_type">
                                    <button type="submit">Add Comment</button>
                                </form>
                            </div>

                            <div ng-repeat="ccc in cc.comments" class="ss-comment">
                                <span>@{{ccc.author.username}}</span>
                                <p>@{{ccc.body}}</p>
                                Answer
                                <div class="reply-container" ng-show="showForm">
                                    <form ng-submit="addComment()">
                                        <input type="text" placeholder="Add Comment" ng-model="body">
                                        <input type="hidden" value="@{{c.id}}" ng-model="commentable_id">
                                        <input type="hidden" value="Comment" ng-model="commentable_type">
                                        <button type="submit">Add Comment</button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                </div></code>```

答:
  var app = angular.module('myApp', []);
        app.controller('myCtrl', function ($scope) {

            //Comments object having reply oject
            $scope.comments = [{ comment: 'hi', reply: [{ comment: 'hi inside commnet' }, { comment: 'hi inside commnet' }] }];

            //push reply
            $scope.insertReply = function (index, reply) {
                $scope.comments[index].reply.push({ comment: reply });
            }

            //push commnet
            $scope.newComment = function (comment) {
                $scope.comments.push({ comment:comment, reply: [] });
            }
        });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">

        <!--Comment section-->
        <ul ng-repeat="comment in comments track by $index" style="background: skyblue; padding: 10px;">
            <li>
                <b>Comment {{$index}} : </b>
                <br>
                {{comment.comment}}
                <!--Reply section-->
                    <ul ng-repeat="reply in comment.reply track by $index">
                        <li><i>Reply {{$index}} :</i><br>
                            {{reply.comment}}</li>
                    </ul>
                <!--End reply section-->
                <input type="text" ng-model="reply" placeholder=" Write your reply." />Reply
            </li>
        </ul>
        <!--End comment section -->

        <!--Post your comment-->
        <b>New comment</b>
        <input type="text" placeholder="Your comment" ng-model="comment" />
        Post
    </div></code>```

Body:
I am trying to get a dynamic script for nested comments to work.

My first problem is that I don't know how I can do endless nesting. For now I planned to do 3 layers, cause I don't know how to make it work dynamicly.

The second problem is that when i submit the form, the values of the models is not submitted to the JS-script. The values are just undefined.

I guess my approach is just wrong - The ng-model elements are not bound inside of the ng-repeat, also the values of all forms would be bound to the same element... Maybe someone has some tips. If it is important, my backend runs with Laravel 4. Here is my code

var commentsApp = angular.module('commentsApp', []);

function CommentsCtrl($scope, $http, $compile) {

    var url_segments = window.location.host.split('.');
    var section = url_segments[0];

    $http.get('/api/' + section + window.location.pathname + '/comments').success(function (comments) {
        $scope.comments = comments;
    });

    $scope.toggleForm = function (id) {

        var container = document.getElementById(id);

        var html = '
<input name="category" type="text" ng-model="person.category" placeholder="Category" required/>Required';

        var elem = $compile(html)($scope);
        angular.element(container).append(elem);
    }

    $scope.addComment = function () {
        var comment = {
            body: $scope.body,
            commentable_id: $scope.commentable_id,
            commentable_type: $scope.commentable_type
        };

        $scope.comments.push(comment);
    };

}

commentsApp.controller('CommentsCtrl', CommentsCtrl);

                    <form ng-submit="addComment()">
                        <input type="text" placeholder="Add Comment" ng-model="body">
                        <input type="hidden" value="@{{c.id}}" ng-model="commentable_id">
                        <input type="hidden" value="Player" ng-model="commentable_type">
                        <button type="submit">Add Comment</button>
                    </form>

                        @{{c.author.username}}

@{{c.body}}

                        Answer

                            <form ng-submit="addComment()">
                                <input type="text" placeholder="Add Comment" ng-model="body">
                                <input type="hidden" value="@{{c.id}}" ng-model="commentable_id">
                                <input type="hidden" value="Comment" ng-model="commentable_type">
                                <button type="submit">Add Comment</button>
                            </form>

                            @{{cc.author.username}}

@{{cc.body}}

                            Answer

                                <form ng-submit="addComment()">
                                    <input type="text" placeholder="Add Comment" ng-model="body">
                                    <input type="hidden" value="@{{c.id}}" ng-model="commentable_id">
                                    <input type="hidden" value="Comment" ng-model="commentable_type">
                                    <button type="submit">Add Comment</button>
                                </form>

                                @{{ccc.author.username}}

@{{ccc.body}}

                                Answer

                                    <form ng-submit="addComment()">
                                        <input type="text" placeholder="Add Comment" ng-model="body">
                                        <input type="hidden" value="@{{c.id}}" ng-model="commentable_id">
                                        <input type="hidden" value="Comment" ng-model="commentable_type">
                                        <button type="submit">Add Comment</button>
                                    </form>

Body:
  var app = angular.module('myApp', []);
        app.controller('myCtrl', function ($scope) {

            //Comments object having reply oject
            $scope.comments = [{ comment: 'hi', reply: [{ comment: 'hi inside commnet' }, { comment: 'hi inside commnet' }] }];

            //push reply
            $scope.insertReply = function (index, reply) {
                $scope.comments[index].reply.push({ comment: reply });
            }

            //push commnet
            $scope.newComment = function (comment) {
                $scope.comments.push({ comment:comment, reply: [] });
            }
        });

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">

        <!--Comment section-->
        <ul ng-repeat="comment in comments track by $index" style="background: skyblue; padding: 10px;">
            <li>
                <b>Comment {{$index}} : </b>
                <br>
                {{comment.comment}}
                <!--Reply section-->
                    <ul ng-repeat="reply in comment.reply track by $index">
                        <li><i>Reply {{$index}} :</i><br>
                            {{reply.comment}}</li>
                    </ul>
                <!--End reply section-->
                <input type="text" ng-model="reply" placeholder=" Write your reply." /><a href="" ng-click="insertReply($index,reply)">Reply</a>
            </li>
        </ul>
        <!--End comment section -->

        <!--Post your comment-->
        <b>New comment</b>
        <input type="text" placeholder="Your comment" ng-model="comment" />
        <a href="" ng-click="newComment(comment)">Post </a>
    </div>


问:
Beginner flex question: Using external MXML and states (and calling functions of parent)
Relatively new to Flex/FlashBuilder and am currently trying to make an Android AIR app. I'm currently struggling to use external MXML files for each page and opening them by calling states.

The way I'm planning it is to call a function on buttonClicks which is housed in the main MXML file.

The thing is, how do I call this function? When I try using:

```<code><s:Button id="b1" label="Change to State 1" click="Main.goHome()'"/>
</code>```

Although this throws up an error.

Is this the best approach to take first of all? And second of all, how can I access the main function? It seems somewhat different to ActionScript in that sense!

答: You could try Adnan's method; though for a more general principle I might suggest passing a reference of Main into the class you are trying to access it from.</p>

Body:
Relatively new to Flex/FlashBuilder and am currently trying to make an Android AIR app. I'm currently struggling to use external MXML files for each page and opening them by calling states.

The way I'm planning it is to call a function on buttonClicks which is housed in the main MXML file.

The thing is, how do I call this function? When I try using:

<s:Button id="b1" label="Change to State 1" click="Main.goHome()'"/>

Although this throws up an error.

Is this the best approach to take first of all? And second of all, how can I access the main function? It seems somewhat different to ActionScript in that sense!


问:
Database driver-class dynamic loading
I want to develop a DB-Agnostic application in java. I have chosen hibernate as ORM. The problem with jdbc is that , it is just an interface and we need the driver class of the db in the class path.  Since the database should be configurable i have to go for  loading the driver class of DB dynamically. (User should keep the driver class in a folder and it should be loaded dynamically )
Below is my code.

```<code>File driverJar = new File("E:\\Jomon\\backup_2017_05_25\\2.2\\WS\\2.2_1\\lib\\Drivers\\postgresql-42.1.1.jar");
URL[] urls = new URL[] { driverJar.toURL() };
URLClassLoader classLoader = new URLClassLoader(urls,DBUtils.class.getClassLoader());
Class.forName("org.postgresql.Driver", true, classLoader);
</code>```

No error till now.
But after this, while initializing hibernate connection, I am getting error java.lang.ClassNotFoundException: org.postgresql.Driver.

May I know what is the problem here.

答:
Hibernate will always to attempt the load the driver from the current thread classloader and in your case, it doesn't have the driver.

You own class loader works fine and just before you initialize sessionFactory ,set your custom loader into contextClassLoader like this.

```<code>    File f = new File( "E:\\Jomon\\backup_2017_05_25\\2.2\\WS\\2.2_1\\lib\\Drivers\\postgresql-42.1.1.jar" );
    URLClassLoader urlCl = new URLClassLoader( new URL[] { f.toURL() }, System.class.getClassLoader() );
    Class postGreDriver = urlCl.loadClass( "org.postgresql.Driver" );
    System.out.println( postGreDriver.newInstance() );

    Thread.currentThread().setContextClassLoader(postGreDriver);

    //Hibernate can start

    //you should restore your old classloader when hibernate services end
</code>```

This may not be the best solution. Have got this snippet from this  discussion

Hope this helps!!!

Title: Database driver-class dynamic loading

Body:
I want to develop a DB-Agnostic application in java. I have chosen hibernate as ORM. The problem with jdbc is that , it is just an interface and we need the driver class of the db in the class path.  Since the database should be configurable i have to go for  loading the driver class of DB dynamically. (User should keep the driver class in a folder and it should be loaded dynamically )
Below is my code.

File driverJar = new File("E:\\Jomon\\backup_2017_05_25\\2.2\\WS\\2.2_1\\lib\\Drivers\\postgresql-42.1.1.jar");
URL[] urls = new URL[] { driverJar.toURL() };
URLClassLoader classLoader = new URLClassLoader(urls,DBUtils.class.getClassLoader());
Class.forName("org.postgresql.Driver", true, classLoader);

No error till now.
But after this, while initializing hibernate connection, I am getting error java.lang.ClassNotFoundException: org.postgresql.Driver.

May I know what is the problem here.

Body:
Hibernate will always to attempt the load the driver from the current thread classloader and in your case, it doesn't have the driver.

You own class loader works fine and just before you initialize sessionFactory ,set your custom loader into contextClassLoader like this.

    File f = new File( "E:\\Jomon\\backup_2017_05_25\\2.2\\WS\\2.2_1\\lib\\Drivers\\postgresql-42.1.1.jar" );
    URLClassLoader urlCl = new URLClassLoader( new URL[] { f.toURL() }, System.class.getClassLoader() );
    Class postGreDriver = urlCl.loadClass( "org.postgresql.Driver" );
    System.out.println( postGreDriver.newInstance() );

    Thread.currentThread().setContextClassLoader(postGreDriver);

    //Hibernate can start

    //you should restore your old classloader when hibernate services end

This may not be the best solution. Have got this snippet from this  discussion

Hope this helps!!!


问:
In Rails 5, on submitting a form with remote true, I want the controller to execute a javascript, But all the javascript code is rendered as text
Here is the form tag:

```<code><%= form_tag api_bill_upload_url(:format=> :js), :method=> 'post', :class=> 'form-horizontal', :id=> 'uploadForm',
               :multipart=> 'true', :remote=> 'true', :authenticity_token => true do%>
 <%end%>
</code>```

Here is the action code:

```<code>def bill_upload
 respond_to do |format|
  format.js {render js: "alert('Hello Rails');"}
  format.html {redirect_to root_url}
 end
end
</code>```

Here is the Development Log:

Started POST "/api/bill_upload.js" for 127.0.0.1 at 2017-06-01 20:19:47 +0530
Processing by ApiController#bill_upload as JS
Completed 200 OK in 2ms (Views: 0.5ms | ActiveRecord: 0.0ms)

Edit: Looks like it has something to do with file input, when i upload a file, the script is rendered as text but when i submit the form without any file, the script works correctly.

答: I also had a problem like this while uploading images. I think you might be using carrier wave to upload files.I added a little fix to that problem, what I did was I just used the form in a modal and after that when I uploaded images using modal it went as js format.  It's the multipart which causes the trouble. I think you can use a modal or so to upload and you will get as Js in action. </p>

Body:
Here is the form tag:

<%= form_tag api_bill_upload_url(:format=> :js), :method=> 'post', :class=> 'form-horizontal', :id=> 'uploadForm',
               :multipart=> 'true', :remote=> 'true', :authenticity_token => true do%>
 <%end%>

Here is the action code:

def bill_upload
 respond_to do |format|
  format.js {render js: "alert('Hello Rails');"}
  format.html {redirect_to root_url}
 end
end

Here is the Development Log:

Started POST "/api/bill_upload.js" for 127.0.0.1 at 2017-06-01 20:19:47 +0530
Processing by ApiController#bill_upload as JS
Completed 200 OK in 2ms (Views: 0.5ms | ActiveRecord: 0.0ms)

Edit: Looks like it has something to do with file input, when i upload a file, the script is rendered as text but when i submit the form without any file, the script works correctly.


问:
Convert DataTable to IEnumerable<T>
I am trying to convert a DataTable to an IEnumerable. Where T is a custom type I created. I know I can do it by creating a List<T> but I was thinking if there is a slicker way to do it using IEnumerable. Here is what I have now:

```<code>private IEnumerable<TankReading> ConvertToTankReadings(DataTable dataTable)
{
    var tankReadings = new List<TankReading>();
    foreach (DataRow row in dataTable.Rows)
    {
        var tankReading =
              new TankReading
              {
                  TankReadingsID = Convert.ToInt32(row["TRReadingsID"]),
                  TankID = Convert.ToInt32(row["TankID"]),
                  ReadingDateTime = Convert.ToDateTime(row["ReadingDateTime"]),
                  ReadingFeet = Convert.ToInt32(row["ReadingFeet"]),
                  ReadingInches = Convert.ToInt32(row["ReadingInches"]),
                  MaterialNumber = row["MaterialNumber"].ToString(),
                  EnteredBy = row["EnteredBy"].ToString(),
                  ReadingPounds = Convert.ToDecimal(row["ReadingPounds"]),
                  MaterialID = Convert.ToInt32(row["MaterialID"]),
                  Submitted = Convert.ToBoolean(row["Submitted"]),
              };

        tankReadings.Add(tankReading);
    }
    return tankReadings.AsEnumerable();
}
</code>```

The key part being I am creating a List<T> then returning it using AsEnumerable().

答:
Universal extension method for DataTable. May be somebody be interesting. Idea creating dynamic properties I take from another post: https://stackoverflow.com/a/15819760/8105226</p>

```<code>    public static IEnumerable<dynamic> AsEnumerable(this DataTable dt)
    {
        List<dynamic> result = new List<dynamic>();
        Dictionary<string, object> d;
        foreach (DataRow dr in dt.Rows)
        {
            d = new Dictionary<string, object>();

            foreach (DataColumn dc in dt.Columns)
                d.Add(dc.ColumnName, dr[dc]);

            result.Add(GetDynamicObject(d));
        }
        return result.AsEnumerable<dynamic>();
    }

    public static dynamic GetDynamicObject(Dictionary<string, object> properties)
    {
        return new MyDynObject(properties);
    }

    public sealed class MyDynObject : DynamicObject
    {
        private readonly Dictionary<string, object> _properties;

        public MyDynObject(Dictionary<string, object> properties)
        {
            _properties = properties;
        }

        public override IEnumerable<string> GetDynamicMemberNames()
        {
            return _properties.Keys;
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            if (_properties.ContainsKey(binder.Name))
            {
                result = _properties[binder.Name];
                return true;
            }
            else
            {
                result = null;
                return false;
            }
        }

        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            if (_properties.ContainsKey(binder.Name))
            {
                _properties[binder.Name] = value;
                return true;
            }
            else
            {
                return false;
            }
        }
    }
</code>```

Title: Convert DataTable to IEnumerable<T>

Body:
I am trying to convert a DataTable to an IEnumerable. Where T is a custom type I created. I know I can do it by creating a List<T> but I was thinking if there is a slicker way to do it using IEnumerable. Here is what I have now:

private IEnumerable<TankReading> ConvertToTankReadings(DataTable dataTable)
{
    var tankReadings = new List<TankReading>();
    foreach (DataRow row in dataTable.Rows)
    {
        var tankReading =
              new TankReading
              {
                  TankReadingsID = Convert.ToInt32(row["TRReadingsID"]),
                  TankID = Convert.ToInt32(row["TankID"]),
                  ReadingDateTime = Convert.ToDateTime(row["ReadingDateTime"]),
                  ReadingFeet = Convert.ToInt32(row["ReadingFeet"]),
                  ReadingInches = Convert.ToInt32(row["ReadingInches"]),
                  MaterialNumber = row["MaterialNumber"].ToString(),
                  EnteredBy = row["EnteredBy"].ToString(),
                  ReadingPounds = Convert.ToDecimal(row["ReadingPounds"]),
                  MaterialID = Convert.ToInt32(row["MaterialID"]),
                  Submitted = Convert.ToBoolean(row["Submitted"]),
              };

        tankReadings.Add(tankReading);
    }
    return tankReadings.AsEnumerable();
}

The key part being I am creating a List<T> then returning it using AsEnumerable().

Body:
Universal extension method for DataTable. May be somebody be interesting. Idea creating dynamic properties I take from another post: https://stackoverflow.com/a/15819760/8105226

    public static IEnumerable<dynamic> AsEnumerable(this DataTable dt)
    {
        List<dynamic> result = new List<dynamic>();
        Dictionary<string, object> d;
        foreach (DataRow dr in dt.Rows)
        {
            d = new Dictionary<string, object>();

            foreach (DataColumn dc in dt.Columns)
                d.Add(dc.ColumnName, dr[dc]);

            result.Add(GetDynamicObject(d));
        }
        return result.AsEnumerable<dynamic>();
    }

    public static dynamic GetDynamicObject(Dictionary<string, object> properties)
    {
        return new MyDynObject(properties);
    }

    public sealed class MyDynObject : DynamicObject
    {
        private readonly Dictionary<string, object> _properties;

        public MyDynObject(Dictionary<string, object> properties)
        {
            _properties = properties;
        }

        public override IEnumerable<string> GetDynamicMemberNames()
        {
            return _properties.Keys;
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            if (_properties.ContainsKey(binder.Name))
            {
                result = _properties[binder.Name];
                return true;
            }
            else
            {
                result = null;
                return false;
            }
        }

        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            if (_properties.ContainsKey(binder.Name))
            {
                _properties[binder.Name] = value;
                return true;
            }
            else
            {
                return false;
            }
        }
    }


问:
Why GridView item don't wrap?
I'm using a GridView in my qml code but it shows all the item in only one row but I don't want it. You can see in picture below:

and this is my code:

```<code>import QtQuick 2.8
import QtQuick.Controls 2.1
import Qt.labs.folderlistmodel 2.1

ApplicationWindow{
    id: a
    width: 480
    height: 640
    FolderListModel{
        id : listModel
        folder: "/home/muhammad/Pictures"
        nameFilters: ["*.jpg"]
    }
    Component{
        id: dd
        Image {
            id: m
            width: a.width/3
            height: width
            source: filePath
        }
    }

    GridView{
        verticalLayoutDirection: GridView.TopToBottom
        layoutDirection: Qt.LeftToRight
        anchors.fill: parent
        flow: GridView.FlowLeftToRight
        model: listModel
        delegate: dd
    }

}
</code>```

how can I solve it?

答:
The size of each cell in a GridView is determined by cellWidth and cellHeight. The default cell size is 100x100. Notice that the cell size determines the layout of the view. Delegates can decide how to cover the area that is reserved for each cell. You may want to resize the Image-delegate to cellWidth and cellHeight, and set its fillMode to Image.PreserveAspectFit, for example.

```<code>GridView {
    id: gridView

    cellWidth: 200
    cellHeight: 200

    delegate: Image {
        width: gridView.cellWidth
        height: gridView.cellHeight
        fillMode: Image.PreserveAspectFit
    }
}
</code>```

Title: Why GridView item don't wrap?

Body:
I'm using a GridView in my qml code but it shows all the item in only one row but I don't want it. You can see in picture below:

and this is my code:

import QtQuick 2.8
import QtQuick.Controls 2.1
import Qt.labs.folderlistmodel 2.1

ApplicationWindow{
    id: a
    width: 480
    height: 640
    FolderListModel{
        id : listModel
        folder: "/home/muhammad/Pictures"
        nameFilters: ["*.jpg"]
    }
    Component{
        id: dd
        Image {
            id: m
            width: a.width/3
            height: width
            source: filePath
        }
    }

    GridView{
        verticalLayoutDirection: GridView.TopToBottom
        layoutDirection: Qt.LeftToRight
        anchors.fill: parent
        flow: GridView.FlowLeftToRight
        model: listModel
        delegate: dd
    }

}

how can I solve it?

Body:
The size of each cell in a GridView is determined by cellWidth and cellHeight. The default cell size is 100x100. Notice that the cell size determines the layout of the view. Delegates can decide how to cover the area that is reserved for each cell. You may want to resize the Image-delegate to cellWidth and cellHeight, and set its fillMode to Image.PreserveAspectFit, for example.

GridView {
    id: gridView

    cellWidth: 200
    cellHeight: 200

    delegate: Image {
        width: gridView.cellWidth
        height: gridView.cellHeight
        fillMode: Image.PreserveAspectFit
    }
}


问:
how generate only darken random colors in javascript?
I've been reading the questions here about how to generate random colors in JS/JQuery. But I want to generate only darken colors avoiding the black, yellow and gray range colors, in order to be able to draw areas in google maps with different colors.

Thanks

答:
For simplicity of implementation and thoroughness, I can't recommend this script highly enough:

David Merfeld's randomColor

Choose between hex or rgb, add in some alpha, specify light or dark palettes, avoid repeats, etc.


问:
C# --> Java code generator
I have a small (~2000 lines of code) class that I would like to use from both java & .NET. There are several approaches to do this - among them wrapping the class as a service, using some interop voodoo, or duplicating the code to both C# & java.

Do you know an out-of-the-box tool that accomplishes the latter - takes a simple C# class with no dependencies and converts it to an equivalent java class?

答: This is list of tools I know. Sharpen or j2cstranslator looks like good options.</p>

Title: C# --> Java code generator


问:
What is Docker attach?
I am very new to Docker and I have been able to understand 4 things

Dockerfile

Docker image

Docker container

docker-compose

along with some basic commands like docker run, docker log etc.

Now, I came across this command docker attach with a description here

Use docker attach to attach to a running container using the container’s ID or name, either to view its ongoing output or to control it interactively. You can attach to the same contained process multiple times simultaneously, screen sharing style, or quickly view the progress of your detached process.`

I have no idea what do they mean when they say we can attach if we want to view a container's ongoing activity or output? If I have a Container for a console application and I simply do docker run on it then I can see the output right there in the console window.

What could be a few benefits of docker attach?

答:
When containers are run with the interactive option, you can connect to the container and enter commands as if you are on the terminal:

```<code>$ docker run -itd --name busybox busybox
dcaecf3335f9142e8c70a2ae05a386395b49d610be345b3a12d2961fccab1478

$ docker attach busybox
/ # echo hello world
hello world
</code>```

The attach option also allows multiple connections to view the same container and see what each is typing.

Lastly, while connected to a container with the tty option (-t), you can type Control-P Control-Q to detach from that container and leave it running in the background. You can then attach to that container again in the future.

Title: What is Docker attach?

Body:
When containers are run with the interactive option, you can connect to the container and enter commands as if you are on the terminal:

$ docker run -itd --name busybox busybox
dcaecf3335f9142e8c70a2ae05a386395b49d610be345b3a12d2961fccab1478

$ docker attach busybox
/ # echo hello world
hello world

The attach option also allows multiple connections to view the same container and see what each is typing.

Lastly, while connected to a container with the tty option (-t), you can type Control-P Control-Q to detach from that container and leave it running in the background. You can then attach to that container again in the future.


问:
Integrate a function that returns a matrix numpy
I want to do something similar to this question.

```<code>Nm, Mm = np.meshgrid(range(3), range(2))
y = lambda x: x*Nm + x*Mm
</code>```

Then, y returns a 3x2 matrix. I want to integrate y from a to b, for instance we can choose a=0 and b=1. This means that the i, j component of the integrated matrix should be int from 0 to 1 of (x * i + x * j) dx. If I take into account one of the answers:

```<code>>>> a = [sin, cos]
>>> vectorize(quad)(a, 0, pi)
</code>```

Clearly a is a list of functions, but what I have is a function that returns an array, which is different. I get:

```<code>res = np.vectorize(integrate.quad)(y, 0, 1)

error: Supplied function does not return a valid float.
</code>```

How can I fix this? Thanks for your help

Edit:

The desired result is

```<code>res = np.empty((3,2))
for i in range(3):
    for j in range(2):
        res[i, j] = quad(lambda x: x*i + x*j, 0, 1)[0]
</code>```

答:
What you want can be achieved this way :

```<code>Nm, Mm = np.meshgrid(range(3), range(2))

def f(m,n):
    def g(x):
        return m*x+n*x
    return g

fv=np.vectorize(f)

u=fv(Mm,Nm)

np.vectorize(quad)(u,0,1)
</code>```

But no numpy acceleration will arise here. it's just a commodity to mimic numpy loopless style.

Body:
I want to do something similar to this question.

Nm, Mm = np.meshgrid(range(3), range(2))
y = lambda x: x*Nm + x*Mm

Then, y returns a 3x2 matrix. I want to integrate y from a to b, for instance we can choose a=0 and b=1. This means that the i, j component of the integrated matrix should be int from 0 to 1 of (x * i + x * j) dx. If I take into account one of the answers:

>>> a = [sin, cos]
>>> vectorize(quad)(a, 0, pi)

Clearly a is a list of functions, but what I have is a function that returns an array, which is different. I get:

res = np.vectorize(integrate.quad)(y, 0, 1)

error: Supplied function does not return a valid float.

How can I fix this? Thanks for your help

Edit:

The desired result is

res = np.empty((3,2))
for i in range(3):
    for j in range(2):
        res[i, j] = quad(lambda x: x*i + x*j, 0, 1)[0]

Body:
What you want can be achieved this way :

Nm, Mm = np.meshgrid(range(3), range(2))

def f(m,n):
    def g(x):
        return m*x+n*x
    return g

fv=np.vectorize(f)

u=fv(Mm,Nm)

np.vectorize(quad)(u,0,1)

But no numpy acceleration will arise here. it's just a commodity to mimic numpy loopless style.


问:
Given sorted integer array, write an algo based on divide and conquer for A[i]=i
Given: sorted integer array, integers are all different - no duplicates.

Problem: Write an algorithm (as good as possible in runtime) based on divide and conquer for checking if there is an index i that A[i]=i exists in the array.

Well I thought about Binary Search which is O(logn) run time complexity.
Is there something faster than that?

答:
The requirement that the input is sorted in itself is not enough. The additional requirement that there are no two equal values in the input array is a necessary condition to be able to use a binary search.

If that would not be a condition, you could not use a binary search, as can be seen in the following example (assuming 0 is the first index):

```<code>    i:   0 1 2 3 4 5 6
        --------------
  A[i]: -1 0 x 4 y 6 7
               ^
</code>```

With a binary search you'd take the middle element and decide at which side of it there could be an i with A[i]=i. The problem is that in the above example the solution could be at either side of the centre: if x=2, then the solution is at the left, and when y=4, the solution is at the right. So divide and conquer will not work. Only when it is assured that the input has no duplicate values, a divide and conquer algorithm can work.

On top of that you can immediately exclude input arrays where the first value is greater than 0, because then there is no way to achieve A[i]=i without having duplicate values. Similarly, an input array where the last value is less than the last index, does not have an i with A[i]=i.

This consideration will also work during the divide and conquer. Take this example:

```<code>    i:   0 1 2 3 4 5 6 7 8
        -------------------
  A[i]: -4 0 1 2 5 6 7 8 10
</code>```

At first both values at the ends are verified: they don't exclude a solution, so the middle value at index 4 is taken. Since its value (5) is greater than the index (4), the range from index 4 to 8 can be ignored. So in the next iteration of the algorithm the range between index 0 and 3 (included) are considered.

But the value at the rightmost index (3) is less than 3 (it is 2). By the above mentioned rule, this means there cannot be a solution, and so the algorithm can stop right there: making more divisions would be futile.

So here is a JavaScript implementation for this:

function hasSelfReference(arr) {
    let last = arr.length - 1;
    if (last < 0 || arr[0] > 0 || arr[last] < last) return false;

    let first = 0;
    while (first < last) {
        let mid = (first + last) >> 1;
        if (arr[mid] < mid) {
            first = mid + 1;
            if (arr[first] > first) return false;
        } else if (arr[mid] > mid) {
            last = mid - 1;
            if (arr[last] < last) return false;
        } else
            return true;
    }
    return arr[first] === first; // arr[first] may be undefined: not a problem in JS
}

console.log(hasSelfReference([3, 4, 5, 6])); // false
console.log(hasSelfReference([-4, -2, 1, 2, 7])); // false
console.log(hasSelfReference([-4, -2, 1, 3, 7])); // true
console.log(hasSelfReference([])); // false
console.log(hasSelfReference([-4, 0, 1, 2, 5, 6, 7, 8, 10])); // false```

As with the usual divide and conquer algorithms, this has a O(logn) (worst-case) time complexity.

When the array has a matching index, then the number of iterations is logn, but when there is no match, and the array is large, there will often be an early exit out of the loop.

Body:
The requirement that the input is sorted in itself is not enough. The additional requirement that there are no two equal values in the input array is a necessary condition to be able to use a binary search.

If that would not be a condition, you could not use a binary search, as can be seen in the following example (assuming 0 is the first index):

    i:   0 1 2 3 4 5 6
        --------------
  A[i]: -1 0 x 4 y 6 7
               ^

With a binary search you'd take the middle element and decide at which side of it there could be an i with A[i]=i. The problem is that in the above example the solution could be at either side of the centre: if x=2, then the solution is at the left, and when y=4, the solution is at the right. So divide and conquer will not work. Only when it is assured that the input has no duplicate values, a divide and conquer algorithm can work.

On top of that you can immediately exclude input arrays where the first value is greater than 0, because then there is no way to achieve A[i]=i without having duplicate values. Similarly, an input array where the last value is less than the last index, does not have an i with A[i]=i.

This consideration will also work during the divide and conquer. Take this example:

    i:   0 1 2 3 4 5 6 7 8
        -------------------
  A[i]: -4 0 1 2 5 6 7 8 10

At first both values at the ends are verified: they don't exclude a solution, so the middle value at index 4 is taken. Since its value (5) is greater than the index (4), the range from index 4 to 8 can be ignored. So in the next iteration of the algorithm the range between index 0 and 3 (included) are considered.

But the value at the rightmost index (3) is less than 3 (it is 2). By the above mentioned rule, this means there cannot be a solution, and so the algorithm can stop right there: making more divisions would be futile.

So here is a JavaScript implementation for this:

function hasSelfReference(arr) {
    let last = arr.length - 1;
    if (last < 0 || arr[0] > 0 || arr[last] < last) return false;

    let first = 0;
    while (first < last) {
        let mid = (first + last) >> 1;
        if (arr[mid] < mid) {
            first = mid + 1;
            if (arr[first] > first) return false;
        } else if (arr[mid] > mid) {
            last = mid - 1;
            if (arr[last] < last) return false;
        } else
            return true;
    }
    return arr[first] === first; // arr[first] may be undefined: not a problem in JS
}

console.log(hasSelfReference([3, 4, 5, 6])); // false
console.log(hasSelfReference([-4, -2, 1, 2, 7])); // false
console.log(hasSelfReference([-4, -2, 1, 3, 7])); // true
console.log(hasSelfReference([])); // false
console.log(hasSelfReference([-4, 0, 1, 2, 5, 6, 7, 8, 10])); // false

As with the usual divide and conquer algorithms, this has a O(logn) (worst-case) time complexity.

When the array has a matching index, then the number of iterations is logn, but when there is no match, and the array is large, there will often be an early exit out of the loop.


问:
Converting Matlab code to C++ (no image processing is included in the code)
I want to convert my Matlab code to c++. I did search for it but I got more confused.
 Could anyone show me the simplest way to do that? If any information about code is needed please let me know. Any help is highly appreciated.</p>

答: Matlab has a tool that converts your Matlab .m to .mex and may also generate a C/C++ code, see https://www.mathworks.com/examples/matlab-coder</p>


问:
Objective-C: Automatically create Views/ViewController from data structure
I'm starting to write an app to display the following data structure:

Category #0

Subcategory #0.0

Item #0.0.0

Item description

...

Item #0.0.n

...

Subcategory #0.n

...

Category #n

In words there are categories with subcategories, which in turn may contain subcategories as well, and so on. The final subcategory contains a list of items and on click a short description should be displayed.

I was thinking about a design just like the native Settings app on the iPhone. Everything is included in an Navigation controller and the first categories are displayed. When clicked a new view shows up displaying the subcategories. This goes on until an item is clicked and the description is displayed.

I'm wondering how I could go about implementing this.

What is a reliable, scalable way to store the data (like above). I don't want to hardcore the data into an NSDictionary of NSDictionary's of NSString's. Maybe something like JSON and then use a parser, to write the data into an NSDictionary?

All the Views/ViewControllers are of the same nature (maybe except the final controller to display the description). They display the list of categories and hold the data to create the VC one step deeper. But how can one VC create another VC programmatically and display it? I'm sure there is a more elegant way.

答:
You can store data in any format you like, for instance XML or JSON is OK, the main point is to consider a comfortable structure, like index = data. You can pass data from previous VC to the next and track its index

Then you can use it as follows:

Root View Controller with a navigation controller

```<code>#import "ViewController.h"
#import "DetailViewController.h"

@interface ViewController ()
@property (strong, nonatomic) IBOutlet UIButton *navButton;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (IBAction)navigate:(UIButton *)sender
{
    DetailViewController *vc = [DetailViewController new];
    vc.prevIndex = 0;
    vc.dataString = @"data";
    vc.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController pushViewController:vc animated:YES];
}

@end
</code>```

DetailViewController - for showing subcategories/items

DetailViewController.h

```<code>@interface DetailViewController : UIViewController

@property (nonatomic, assign) NSInteger prevIndex;
@property (nonatomic, strong) NSString *dataString;

@end
</code>```

DetailViewController.m

```<code>#import "DetailViewController.h"

@implementation DetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(10, 100, 0, 0)];
    [button setTitle:[NSString stringWithFormat:@"navigate from %li", (long)_prevIndex] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(navigate) forControlEvents:UIControlEventTouchUpInside];
    [button sizeToFit];
    [self.view addSubview:button];
}

- (void)navigate
{
    DetailViewController *vc = [DetailViewController new];
    vc.prevIndex = _prevIndex + 1;
    vc.dataString = [NSString stringWithFormat:@"data %li", (long)vc.prevIndex];
    vc.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController pushViewController:vc animated:YES];
}

@end
</code>```

Body:
You can store data in any format you like, for instance XML or JSON is OK, the main point is to consider a comfortable structure, like index = data. You can pass data from previous VC to the next and track its index

Then you can use it as follows:

Root View Controller with a navigation controller

#import "ViewController.h"
#import "DetailViewController.h"

@interface ViewController ()
@property (strong, nonatomic) IBOutlet UIButton *navButton;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (IBAction)navigate:(UIButton *)sender
{
    DetailViewController *vc = [DetailViewController new];
    vc.prevIndex = 0;
    vc.dataString = @"data";
    vc.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController pushViewController:vc animated:YES];
}

@end

DetailViewController - for showing subcategories/items

DetailViewController.h

@interface DetailViewController : UIViewController

@property (nonatomic, assign) NSInteger prevIndex;
@property (nonatomic, strong) NSString *dataString;

@end

DetailViewController.m

#import "DetailViewController.h"

@implementation DetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(10, 100, 0, 0)];
    [button setTitle:[NSString stringWithFormat:@"navigate from %li", (long)_prevIndex] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(navigate) forControlEvents:UIControlEventTouchUpInside];
    [button sizeToFit];
    [self.view addSubview:button];
}

- (void)navigate
{
    DetailViewController *vc = [DetailViewController new];
    vc.prevIndex = _prevIndex + 1;
    vc.dataString = [NSString stringWithFormat:@"data %li", (long)vc.prevIndex];
    vc.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController pushViewController:vc animated:YES];
}

@end