问:
Bearing Formula calculations in GraphicsScene producing erratic results
I'm getting very unpredictable results using basic bearing calculations.  What I need to happen is that as I draw these lines based on the angle of the dial, the lines need to uniformly get drawn into the center of the view. Right now, I'm just getting erratic results and I'm hoping someone here can elucidate my
issues. Best to see the results for yourself.

Only thing I did to the mainwindow.ui form was:

set centralWidget to Width: 530, Height: 633

add a QGraphicsView display widget to X: 8, Y: 8, Width/Height: 256.

add a QDial to X: 210, Y: 530, Width/Height: 100, maximum: 359, wrapping:true

All other default values should be fine.

//mainwindow.h

```<code>#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QLineF>
#include <QDial>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

public slots:
    void slt_updateAngleFromDial(int angle);
private slots:
    void slt_drainTheBowl();

private:
    Ui::MainWindow *ui;
    QGraphicsScene *scene;
    QGraphicsView *view;
    QDial dial;
    QGraphicsLineItem *line;
    QGraphicsLineItem *green_needle;
    QGraphicsEllipseItem *mCircle;
    QGraphicsEllipseItem *cCircle;
    QList<QGraphicsLineItem*> m_line_list;
    QLineF green_line;
    QLineF history_line;
    QPointF sceneCenter;
    QPointF drawing_point;
    QPointF historyPointA;
    QPointF historyPointB;
    int historyPoint_count;
    int draw_Radius;
    int draw_angle;
    int viewSize;
    bool started;

    double getBearing(QPointF point);
    double getPointRange(double Xpos, double Ypos);
    QPointF calculate_Bearing_Range(double screenCenter, double bearing, double range, double offset);
    QPointF setPointPosition(double bearing, double range, double centerPos);
    QPointF getQPointOnDisplay(double bearing, double range);
    void addNewHistoryPoint(int drawBearing);
    void drawpath();
    void drainTheBowl_Timer();
    void addNewHistoryPoint(int drawBearing);
};
#endif //MAINWINDOW_H
</code>```

//mainwindow.cpp

```<code>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtMath>
#include <QTimer>

MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    scene = new QGraphicsScene(this);
    view = ui->graphicsView;
    view->setScene(scene);
    view->setSceneRect(0,0,512,512);
    view->setHorizontalScrollBarPolicy(Qt::ScrollbarAlwaysOff);
    view->setVerticalScrollBarPolicy(Qt::ScrollbarAlwaysOff);
    viewSize = view->width() /2;
    sceneCenter = QPointF(viewSize,viewSize);
    draw_Radius = 200;
    connect(ui->dial, &QDial::valueChanged, this, &MainWindow::slt_updateAngleFromDial);

    //add drawing line
    drawing_point = sceneCenter + QPointF(0,draw_Radius);
    green_line = QLineF(drawing_point, sceneCenter + QPointF(0, draw_Radius + 20));
    QPen dirLine(Qt::green, Qt::SolidLine);
    dirLine.setWidth(3);
    green_needle = scene->addLine(green_line, dirLine);
    green_needle->setTransformOriginPoint(sceneCenter);

    //draw static outer circle
    int mSize = draw_Radius *2;
    QRectF rimCircle(QPointF(mSize,mSize),QSize(mSize,mSize));
    int mCenter = rimCircle.center().x();
    mCircle = new QGraphicsEllipseItem(rimCircle);
    QBrush rimTip(Qt::darkCyan, Qt::NoBrush);
    QPen rimPen(Qt::darkCyan, Qt:;SolidLine);
    mCircle->setBrush(rimTip);
    mCircle->setPen(rimPen);
    mCircle->setPos(setPointPosition(0,0, mCenter));
    scene->addItem(mCircle);

    //draw static inner circle
    int cSize = 3;
    QRectF circ(QPointF(cSize,cSize),QSize(cSize,cSize));
    int circCenter = circ.center().x();
    cCircle = new QGraphicsEllipseItem(circ);
    QBrush rimTip2(Qt::black, Qt::SolidPattern);
    QPen rimPen2(Qt::black, Qt:;SolidLine);
    cCircle->setBrush(rimTip2);
    cCircle->setPen(rimPen2);
    cCircle->setPos(setPointPosition(0,0, circCenter + 1));// +1 offset to get to center
    scene->addItem(cCircle);

    started = false;
    historyPoint_count = 0;
    draw_angle = 0;
    drainTheBowl_Timer();
    view->centerOn(sceneCenter);

}

MainWindow::~MainWindow(){delete ui;}

void MainWindow::slt_updateAngleFromDial(int angle){
    draw_angle = angle;
    green_needle->setRotation(draw_angle);
}

QPointF MainWindow::setPointPosition(double bearing, double range, double centerPos){
    double pos = viewSize - centerPos;
    QPointF newPoint = calculate_Bearing_Range(pos,bearing,range,90);
    return newPoint;
}

//using info, get new position in scene, account for offset
QPointF MainWindow::calculate_Bearing_Range(double screenCenter, double bearing, double range, double offset){
    double oldX = screenCenter;
    double oldY = oldX;
    double newX = oldX + qCos(qDegreesToRadians(bearing - offset)) * range;
    double newY = oldY + qSin(qDegreesToRadians(bearing - offset)) * range;
    QPointF pos = QPointF(newX, newY);
    return pos;
 }

double MainWindow::getBearing(QPointF point){
    double cX = viewSize;
    double cY = cX;
    double nX = point.x();
    double nY = point.y();

    /** Inverted Y parameter of atan2
    correct look (no mirroring-no blinking), but upper quadrant dead, spatial relationships horrible*/
    double bearing = qRadiansToDegrees(M_PI_2 - atan2(cY - nY, nX - cX));

    /** "Correct" Bearing formula
    left quadrants move at correct speed for the most part, right quad speeds to center, best spatial relationships, but not perfect*/
    //double bearing = qRadiansToDegrees(M_PI_2 - atan2(nY - cY, nX - cX));

    /** Invert both parameters of atan2
    no dead quadrants, but mirrored and blinking, spatial relationships horrible*/
    //double bearing = qRadiansToDegrees(M_PI_2 - atan2(cY - nY, cX - nX));

    if(bearing < 0)
        bearing += 360;

    return bearing;
}

double Mainwindow::getPointRange(double xPos, double yPos){
    double centerX = viewSize;
    double center = centerX;
    double newX = centerX - Xpos;
    double newY = center - Ypos;
    //pythagoros
    double distance = qPow(newX,2) + qPow(newY,2);
    double range = qSqrt(distance);
    return range;
 }

//gather 2 points from angle of dial to draw a line
void MainWindow::addNewHistoryPoint(int drawBearing){
    double pos = viewSize;
    double range = draw_Radius;
    QPointF pt = calculate_Bearing_Range(pos, drawBearing, range, -90);//align to draw point
    historyPoint_count++;

    switch(historyPoint_count){
        case 1:
            historyPointA = pt;
            break;
        case 2:
            historyPointB = pt;
            historyPoint_count = 0;
            break;
     }
}

void MainWindow::drainTheBowl_Timer(){
    QTimer* drainTimer = new QTimer(this);
    connect(drainTimer, SIGNAL(timeout()), this, SLOT(slt_drainTheBowl()));
    drainTimer->start(100);
}

//perform all updates
void MainWindow::slt_drainTheBowl(){
   //always add new points for continuous line
   addNewHistoryPoint(draw_angle);

   //handle moving lines to center
   foreach(QGraphicsLineItem* line, m_line_list){

        //get coordinates of the 2 points for this line
        QLineF adjLine = line->line();
        int adjLine_pt1_x = adjLine.p1().x();
        int adjLine_pt1_y = adjLine.p1().y();
        int adjLine_pt2_x = adjLine.p2().x();
        int adjLine_pt2_y = adjLine.p2().y();

        //find range of the points
        double pt1_range = getPointRange( adjLine_pt1_x, adjLine_pt1_y);
        double pt2_range = getPointRange( adjLine_pt2_x, adjLine_pt2_y);

        //reduce the range towards center
        pt1_range = (pt1_range - 1);
        pt2_range = (pt2_range - 1);

        //determine bearing of the points
        double pt1Bearing = qRound(getBearing(QPointF(adjLine_pt1_x, adjLine_pt1_y)));
        double pt2Bearing = qRound(getBearing(QPointF(adjLine_pt2_x, adjLine_pt2_y)));

        QPointF newOffset1;
        QPointF newOffset2;

        //handle how points get to center
        if(pt1_range > 1.0)
            newOffset1 = QPointF(getQPointOnDisplay(pt1Bearing, pt1_range));
        else{
            pt1_range = 0.0;
            newOffset1 = QPointF(getQPointOnDisplay(pt1Bearing, pt1_range));
        }

        if(pt2_range > 1.0)
            newOffset2 = QPointF(getQPointOnDisplay(pt2Bearing, pt2_range));
        else{
            pt2_range = 0.0;
            newOffset2 = QPointF(getQPointOnDisplay(pt2Bearing, pt2_range));
            //! scene->removeItem(line); //remove line generates errors
            //! m_line_list.removeFirst();// because points don't get to center in order, everything breaks
        }

        //apply new adjustments to this line
        adjLine.setP1(newOffset1);
        adjLine.setPt1(newOffset2);
        line->setline(adjLine);
   }

   drawPath();//connect the dots
}

//track the tip of the needle for drawing
QPointF MainWindow::getQPointOnDisplay(double bearing, double range){
    int offset = 90;
    double pos = viewSize;
    QPointF newPoint = calculate_Bearing_Range(pos, bearing, range, offset);
    return newPoint;
}

//draw the new line segment base on history points gathered above
void MainWindow:drawPath(){
    history_line = QLineF(historyPointA, historyPointB);
    QPen mainline(Qt::blue, Qt::SolidLine);
    mainline.setWidth(2);
    line = scene->addLine(history_line, mainline);

    //remove the initial line drawn at 0,0
    if(!started){
         scene->removeItem(line);
         started = true;
    }
    m_line_list.append(line);
}
</code>```

So a couple of things to note here. First inside of the getBearing method, you'll see the 3 main formulas I have had success with, tried many others, but these are the only ones that produced coherent lines. I added some comments that should help generalize what those formulas are doing.  The first formula, the one not commented out, is the closest to what I'm hoping to achieve.

Two main things wrong with it: 1) the upper left quadrant of the circle is dead, no points/lines move at all 2) the points that do move to center do not follow a steady progression. Some points race to center while others drag behind. This is what I'm referring to in my comments when I mention the spatial relationships.  Each line drawn should move to center behind the line drawn before it, and ahead of the line drawn afterwards.

The other 2 formulas that are commented out produce a closer behavior in regards to there being no dead quadrants, but they both have a mirrored line being drawn, and every line blinks for some reason.

My best guess as to what is happening is there is some coordinate confusion going on. Another thought I had is that maybe I'm not correctly determining the center of the scene and the center of the points being drawn inwards.

You'll notice on the drawing of the inner static circle, I have a " circCenter + 1" offset. Without this small offset, the circle is not quite in the center.

I've been on this for 3 weeks now and would love some assistance figuring this out.

*Please forgive any spelling inconsistencies as I had to transfer this code by hand from one machine to the other.

答:
I think there are a few ways to simplify this which would help.

I would center everything about 0,0 in the GraphicsScene - that will make the mathematics more clear.

Rather than using a set of QLines, really I think what you after is a set of points which all move towards the origin. So rather than using multiple QGraphicsLineItems, use one QGraphicsPathItem and do the updates to the path. Instead of storing lots of graphics items, store a set of points - QList<QPointF> m_points in my example.

Where possible, use inbuilt Qt geometry primitives like QLineF and QPointF to do the geometry work rather than rolling your own.

Full code for my solution at https://gist.github.com/docsteer/64483cc8f44ca53565912c50d11cf4a9, but the key function:

```<code>void MainWindow::slt_drainTheBowl()
{
    // Move the points towards center
    QMutableListIterator<QPointF> i(m_points);
    while(i.hasNext())
    {
        i.next();
        QLineF line(QPointF(0,0), i.value());
        // We move a point by decreasing the length from the origin to the point by 1
        qreal length = line.length();
        length -=1;
        line.setLength(length);
        // If the point is now at (or past) the origin, remove from the list
        if(length<=0)
        {
            i.remove();
        }
        else
        {
            // Update the point in the list
            i.setValue(line.p2());
        }
    }

    // Add a new point to the list based on the current angle
    QPointF newPoint;
    newPoint.setY( qSin(qDegreesToRadians((double)draw_angle)) * 200 );
    newPoint.setX( qCos(qDegreesToRadians((double)draw_angle)) * 200 );

    // Set the points into the path item
    QPainterPath path;
    path.moveTo(newPoint);
    for(int i=0; i<m_points.count(); i++)
        path.lineTo(m_points[i]);

    m_points << newPoint;

    m_pathItem->setPath(path);
}
</code>```

Body:
I'm getting very unpredictable results using basic bearing calculations.  What I need to happen is that as I draw these lines based on the angle of the dial, the lines need to uniformly get drawn into the center of the view. Right now, I'm just getting erratic results and I'm hoping someone here can elucidate my
issues. Best to see the results for yourself.

Only thing I did to the mainwindow.ui form was:

set centralWidget to Width: 530, Height: 633

add a QGraphicsView display widget to X: 8, Y: 8, Width/Height: 256.

add a QDial to X: 210, Y: 530, Width/Height: 100, maximum: 359, wrapping:true

All other default values should be fine.

//mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QLineF>
#include <QDial>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

public slots:
    void slt_updateAngleFromDial(int angle);
private slots:
    void slt_drainTheBowl();

private:
    Ui::MainWindow *ui;
    QGraphicsScene *scene;
    QGraphicsView *view;
    QDial dial;
    QGraphicsLineItem *line;
    QGraphicsLineItem *green_needle;
    QGraphicsEllipseItem *mCircle;
    QGraphicsEllipseItem *cCircle;
    QList<QGraphicsLineItem*> m_line_list;
    QLineF green_line;
    QLineF history_line;
    QPointF sceneCenter;
    QPointF drawing_point;
    QPointF historyPointA;
    QPointF historyPointB;
    int historyPoint_count;
    int draw_Radius;
    int draw_angle;
    int viewSize;
    bool started;

    double getBearing(QPointF point);
    double getPointRange(double Xpos, double Ypos);
    QPointF calculate_Bearing_Range(double screenCenter, double bearing, double range, double offset);
    QPointF setPointPosition(double bearing, double range, double centerPos);
    QPointF getQPointOnDisplay(double bearing, double range);
    void addNewHistoryPoint(int drawBearing);
    void drawpath();
    void drainTheBowl_Timer();
    void addNewHistoryPoint(int drawBearing);
};
#endif //MAINWINDOW_H

//mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtMath>
#include <QTimer>

MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    scene = new QGraphicsScene(this);
    view = ui->graphicsView;
    view->setScene(scene);
    view->setSceneRect(0,0,512,512);
    view->setHorizontalScrollBarPolicy(Qt::ScrollbarAlwaysOff);
    view->setVerticalScrollBarPolicy(Qt::ScrollbarAlwaysOff);
    viewSize = view->width() /2;
    sceneCenter = QPointF(viewSize,viewSize);
    draw_Radius = 200;
    connect(ui->dial, &QDial::valueChanged, this, &MainWindow::slt_updateAngleFromDial);

    //add drawing line
    drawing_point = sceneCenter + QPointF(0,draw_Radius);
    green_line = QLineF(drawing_point, sceneCenter + QPointF(0, draw_Radius + 20));
    QPen dirLine(Qt::green, Qt::SolidLine);
    dirLine.setWidth(3);
    green_needle = scene->addLine(green_line, dirLine);
    green_needle->setTransformOriginPoint(sceneCenter);

    //draw static outer circle
    int mSize = draw_Radius *2;
    QRectF rimCircle(QPointF(mSize,mSize),QSize(mSize,mSize));
    int mCenter = rimCircle.center().x();
    mCircle = new QGraphicsEllipseItem(rimCircle);
    QBrush rimTip(Qt::darkCyan, Qt::NoBrush);
    QPen rimPen(Qt::darkCyan, Qt:;SolidLine);
    mCircle->setBrush(rimTip);
    mCircle->setPen(rimPen);
    mCircle->setPos(setPointPosition(0,0, mCenter));
    scene->addItem(mCircle);

    //draw static inner circle
    int cSize = 3;
    QRectF circ(QPointF(cSize,cSize),QSize(cSize,cSize));
    int circCenter = circ.center().x();
    cCircle = new QGraphicsEllipseItem(circ);
    QBrush rimTip2(Qt::black, Qt::SolidPattern);
    QPen rimPen2(Qt::black, Qt:;SolidLine);
    cCircle->setBrush(rimTip2);
    cCircle->setPen(rimPen2);
    cCircle->setPos(setPointPosition(0,0, circCenter + 1));// +1 offset to get to center
    scene->addItem(cCircle);

    started = false;
    historyPoint_count = 0;
    draw_angle = 0;
    drainTheBowl_Timer();
    view->centerOn(sceneCenter);

}

MainWindow::~MainWindow(){delete ui;}

void MainWindow::slt_updateAngleFromDial(int angle){
    draw_angle = angle;
    green_needle->setRotation(draw_angle);
}

QPointF MainWindow::setPointPosition(double bearing, double range, double centerPos){
    double pos = viewSize - centerPos;
    QPointF newPoint = calculate_Bearing_Range(pos,bearing,range,90);
    return newPoint;
}

//using info, get new position in scene, account for offset
QPointF MainWindow::calculate_Bearing_Range(double screenCenter, double bearing, double range, double offset){
    double oldX = screenCenter;
    double oldY = oldX;
    double newX = oldX + qCos(qDegreesToRadians(bearing - offset)) * range;
    double newY = oldY + qSin(qDegreesToRadians(bearing - offset)) * range;
    QPointF pos = QPointF(newX, newY);
    return pos;
 }

double MainWindow::getBearing(QPointF point){
    double cX = viewSize;
    double cY = cX;
    double nX = point.x();
    double nY = point.y();

    /** Inverted Y parameter of atan2
    correct look (no mirroring-no blinking), but upper quadrant dead, spatial relationships horrible*/
    double bearing = qRadiansToDegrees(M_PI_2 - atan2(cY - nY, nX - cX));

    /** "Correct" Bearing formula
    left quadrants move at correct speed for the most part, right quad speeds to center, best spatial relationships, but not perfect*/
    //double bearing = qRadiansToDegrees(M_PI_2 - atan2(nY - cY, nX - cX));

    /** Invert both parameters of atan2
    no dead quadrants, but mirrored and blinking, spatial relationships horrible*/
    //double bearing = qRadiansToDegrees(M_PI_2 - atan2(cY - nY, cX - nX));

    if(bearing < 0)
        bearing += 360;

    return bearing;
}

double Mainwindow::getPointRange(double xPos, double yPos){
    double centerX = viewSize;
    double center = centerX;
    double newX = centerX - Xpos;
    double newY = center - Ypos;
    //pythagoros
    double distance = qPow(newX,2) + qPow(newY,2);
    double range = qSqrt(distance);
    return range;
 }

//gather 2 points from angle of dial to draw a line
void MainWindow::addNewHistoryPoint(int drawBearing){
    double pos = viewSize;
    double range = draw_Radius;
    QPointF pt = calculate_Bearing_Range(pos, drawBearing, range, -90);//align to draw point
    historyPoint_count++;

    switch(historyPoint_count){
        case 1:
            historyPointA = pt;
            break;
        case 2:
            historyPointB = pt;
            historyPoint_count = 0;
            break;
     }
}

void MainWindow::drainTheBowl_Timer(){
    QTimer* drainTimer = new QTimer(this);
    connect(drainTimer, SIGNAL(timeout()), this, SLOT(slt_drainTheBowl()));
    drainTimer->start(100);
}

//perform all updates
void MainWindow::slt_drainTheBowl(){
   //always add new points for continuous line
   addNewHistoryPoint(draw_angle);

   //handle moving lines to center
   foreach(QGraphicsLineItem* line, m_line_list){

        //get coordinates of the 2 points for this line
        QLineF adjLine = line->line();
        int adjLine_pt1_x = adjLine.p1().x();
        int adjLine_pt1_y = adjLine.p1().y();
        int adjLine_pt2_x = adjLine.p2().x();
        int adjLine_pt2_y = adjLine.p2().y();

        //find range of the points
        double pt1_range = getPointRange( adjLine_pt1_x, adjLine_pt1_y);
        double pt2_range = getPointRange( adjLine_pt2_x, adjLine_pt2_y);

        //reduce the range towards center
        pt1_range = (pt1_range - 1);
        pt2_range = (pt2_range - 1);

        //determine bearing of the points
        double pt1Bearing = qRound(getBearing(QPointF(adjLine_pt1_x, adjLine_pt1_y)));
        double pt2Bearing = qRound(getBearing(QPointF(adjLine_pt2_x, adjLine_pt2_y)));

        QPointF newOffset1;
        QPointF newOffset2;

        //handle how points get to center
        if(pt1_range > 1.0)
            newOffset1 = QPointF(getQPointOnDisplay(pt1Bearing, pt1_range));
        else{
            pt1_range = 0.0;
            newOffset1 = QPointF(getQPointOnDisplay(pt1Bearing, pt1_range));
        }

        if(pt2_range > 1.0)
            newOffset2 = QPointF(getQPointOnDisplay(pt2Bearing, pt2_range));
        else{
            pt2_range = 0.0;
            newOffset2 = QPointF(getQPointOnDisplay(pt2Bearing, pt2_range));
            //! scene->removeItem(line); //remove line generates errors
            //! m_line_list.removeFirst();// because points don't get to center in order, everything breaks
        }

        //apply new adjustments to this line
        adjLine.setP1(newOffset1);
        adjLine.setPt1(newOffset2);
        line->setline(adjLine);
   }

   drawPath();//connect the dots
}

//track the tip of the needle for drawing
QPointF MainWindow::getQPointOnDisplay(double bearing, double range){
    int offset = 90;
    double pos = viewSize;
    QPointF newPoint = calculate_Bearing_Range(pos, bearing, range, offset);
    return newPoint;
}

//draw the new line segment base on history points gathered above
void MainWindow:drawPath(){
    history_line = QLineF(historyPointA, historyPointB);
    QPen mainline(Qt::blue, Qt::SolidLine);
    mainline.setWidth(2);
    line = scene->addLine(history_line, mainline);

    //remove the initial line drawn at 0,0
    if(!started){
         scene->removeItem(line);
         started = true;
    }
    m_line_list.append(line);
}

So a couple of things to note here. First inside of the getBearing method, you'll see the 3 main formulas I have had success with, tried many others, but these are the only ones that produced coherent lines. I added some comments that should help generalize what those formulas are doing.  The first formula, the one not commented out, is the closest to what I'm hoping to achieve.

Two main things wrong with it: 1) the upper left quadrant of the circle is dead, no points/lines move at all 2) the points that do move to center do not follow a steady progression. Some points race to center while others drag behind. This is what I'm referring to in my comments when I mention the spatial relationships.  Each line drawn should move to center behind the line drawn before it, and ahead of the line drawn afterwards.

The other 2 formulas that are commented out produce a closer behavior in regards to there being no dead quadrants, but they both have a mirrored line being drawn, and every line blinks for some reason.

My best guess as to what is happening is there is some coordinate confusion going on. Another thought I had is that maybe I'm not correctly determining the center of the scene and the center of the points being drawn inwards.

You'll notice on the drawing of the inner static circle, I have a " circCenter + 1" offset. Without this small offset, the circle is not quite in the center.

I've been on this for 3 weeks now and would love some assistance figuring this out.

*Please forgive any spelling inconsistencies as I had to transfer this code by hand from one machine to the other.

Body:
I think there are a few ways to simplify this which would help.

I would center everything about 0,0 in the GraphicsScene - that will make the mathematics more clear.

Rather than using a set of QLines, really I think what you after is a set of points which all move towards the origin. So rather than using multiple QGraphicsLineItems, use one QGraphicsPathItem and do the updates to the path. Instead of storing lots of graphics items, store a set of points - QList<QPointF> m_points in my example.

Where possible, use inbuilt Qt geometry primitives like QLineF and QPointF to do the geometry work rather than rolling your own.

Full code for my solution at https://gist.github.com/docsteer/64483cc8f44ca53565912c50d11cf4a9, but the key function:

void MainWindow::slt_drainTheBowl()
{
    // Move the points towards center
    QMutableListIterator<QPointF> i(m_points);
    while(i.hasNext())
    {
        i.next();
        QLineF line(QPointF(0,0), i.value());
        // We move a point by decreasing the length from the origin to the point by 1
        qreal length = line.length();
        length -=1;
        line.setLength(length);
        // If the point is now at (or past) the origin, remove from the list
        if(length<=0)
        {
            i.remove();
        }
        else
        {
            // Update the point in the list
            i.setValue(line.p2());
        }
    }

    // Add a new point to the list based on the current angle
    QPointF newPoint;
    newPoint.setY( qSin(qDegreesToRadians((double)draw_angle)) * 200 );
    newPoint.setX( qCos(qDegreesToRadians((double)draw_angle)) * 200 );

    // Set the points into the path item
    QPainterPath path;
    path.moveTo(newPoint);
    for(int i=0; i<m_points.count(); i++)
        path.lineTo(m_points[i]);

    m_points << newPoint;

    m_pathItem->setPath(path);
}


来源: stackexchange

问:
Failing on call to _mm_loadu_si128() with AESNI intrinsics enabled
We are compiling a 32bit application that links with a static build of cryptopp.

gcc : 4.4.7

  CPU : Intel Xeon E5-2680

  OS : CentoOS 6.5

  Crypto++ : 5.6.2

Our program compiles and runs fine on this machine. When we attempt to run on

CPU : Intel Xeon X5690

  OS : CentoOS 6.5

  gcc : 4.4.6

We are getting a segmentation fault in cryptopp -> rijndael.cpp -> Rijndael::Base::UncheckedSetKey() call to _mm_loadu_si128()

If we build cryptopp with CRYPTOPP_BOOL_AESNI_INTRINSICS_AVAILABLE set to 0 everything runs ok.  It seems like AES-NI should be available on this server, and the cryptopp call to HasAESNI() returns true.

Any ideas as to what could be causing this, or how to track down further?

答:
The "Intel(R) Xeon(R) CPU E5606  @ 2.13GH" don't support "AESNI" instruction too.  I have compiled Crypto++ on "Intel Xeon E312xx (Sandy Bridge)",  and get the same error on "E5606"! Disable "AESNI" in the CMakeLists.txt file, turn on "DISABLE_AESNI" option.
option(DISABLE_AESNI "Disable AES-NI" ON)

ContentLicense: CC BY-SA 3.0


问:
AutoIt's "WinActivate" function doesn't recognize window
I have a problem using AutoIt to identify a window; it has no title, the class isn't helpful, and the handle changes every time the window reopens. How can I identify it?

It is the 'save' dialog for the Safari browser, on Windows 10.

答:
Try this:</p>

```<code>AutoItSetOption('WinTitleMatchMode',4)
WinWaitActive("[TITLE:; CLASS:WebViewWindowClass1]", "")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Try this:

AutoItSetOption('WinTitleMatchMode',4)
WinWaitActive("[TITLE:; CLASS:WebViewWindowClass1]", "")


问:
extract values in array and create variable php
Hi Stackoverflow and programmer!

I have this code :

```<code>$result = print_r($reponse, true);

echo $result;
</code>```

Wich give me this output :

```<code>Array ( [333212] => Array ( [view] => 323 [sold] => 3 [buy] => 43 [number] => 333212 ) )
</code>```

I need to find a way to have something like :

```<code>echo $variable['view']; (323)

echo $variable['buy']; (3)

echo $variable['sold']; (43)
</code>```

I check and try a lot of things like extract(); serialize(); dumb_var i try explode("")  i search a little everywhere but dint find answer.

Thanks a lot for the help ! much apreciated !!!

Pierre-luc

答:
You can output array values with the specific index this way:

```<code>echo $reponse['333212']['view'];
</code>```

Like in your example, if you want to use $variable you can assign the array $reponse to $variable:

$variable['333212'] = $reponse;

Then your code would work:

```<code>echo $variable['view']; // (323)
echo $variable['buy']; // (3)
echo $variable['sold']; // (43)
</code>```

Also consider renaming reponse to response (typo?).

Body:
Hi Stackoverflow and programmer!

I have this code :

$result = print_r($reponse, true);

echo $result;

Wich give me this output :

Array ( [333212] => Array ( [view] => 323 [sold] => 3 [buy] => 43 [number] => 333212 ) )

I need to find a way to have something like :

echo $variable['view']; (323)

echo $variable['buy']; (3)

echo $variable['sold']; (43)

I check and try a lot of things like extract(); serialize(); dumb_var i try explode("")  i search a little everywhere but dint find answer.

Thanks a lot for the help ! much apreciated !!!

Pierre-luc

Body:
You can output array values with the specific index this way:

echo $reponse['333212']['view'];

Like in your example, if you want to use $variable you can assign the array $reponse to $variable:

$variable['333212'] = $reponse;

Then your code would work:

echo $variable['view']; // (323)
echo $variable['buy']; // (3)
echo $variable['sold']; // (43)

Also consider renaming reponse to response (typo?).


问:
Is it one channel ops affect another channel ops
I made this simple code, trying to know how's channel works, somehow if channel c is sent after channel b is sent, channel in last routine is not being sent,

I have 2 channel, channel c is for spliting channel b to 4 part of slice.

```<code> package main

 import (
      "fmt"
      "strconv"
 )

 func runner(idx int, c chan []int, b chan []int) {
      var temp []int
      fmt.Println("runner " + strconv.Itoa(idx))
      bucket := <-b
      for k, v := range bucket {
           if v != 0 {
                temp = append(temp, v)
                bucket[k] = 0
           }
           if len(temp) == 5 {
                break
           }
      }

      //Strange condition if channel c is sent after channel b is sent,
      //somehow the last chan is not being sent
      b <- bucket
      c <- temp

      //this is right if channel b is sent after channel c is sent
    //c <- temp
    //b <- bucket

 }

 func printer(c chan []int) {
      for {
           select {
           case msg := <-c:
                fmt.Println(msg)
                //time.Sleep(time.Second * 1)
           }
      }
 }

 func main() {

      c := make(chan []int, 5)
      bucket := make(chan []int)

      go runner(1, c, bucket)
      go runner(2, c, bucket)
      go runner(3, c, bucket)
      go runner(4, c, bucket)

      bucket <- []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}

      go printer(c)

      var input string
      fmt.Scanln(&input)

 }
</code>```

答:
```<code>  bucket := make(chan []int)
</code>```

Your b channel's capacity is 0. This means whenever you send something to this channel, the channel is full immediately and will block until a receiver reads the channel.

When there is only one runner left, no one is going to call bucket := <-b to read the last bucket, thus this last goroutine is stuck forever on the b <- bucket line, and thus the next line c <- temp will never be called for this last goroutine.

Body:
I made this simple code, trying to know how's channel works, somehow if channel c is sent after channel b is sent, channel in last routine is not being sent,

I have 2 channel, channel c is for spliting channel b to 4 part of slice.

 package main

 import (
      "fmt"
      "strconv"
 )

 func runner(idx int, c chan []int, b chan []int) {
      var temp []int
      fmt.Println("runner " + strconv.Itoa(idx))
      bucket := <-b
      for k, v := range bucket {
           if v != 0 {
                temp = append(temp, v)
                bucket[k] = 0
           }
           if len(temp) == 5 {
                break
           }
      }

      //Strange condition if channel c is sent after channel b is sent,
      //somehow the last chan is not being sent
      b <- bucket
      c <- temp

      //this is right if channel b is sent after channel c is sent
    //c <- temp
    //b <- bucket

 }

 func printer(c chan []int) {
      for {
           select {
           case msg := <-c:
                fmt.Println(msg)
                //time.Sleep(time.Second * 1)
           }
      }
 }

 func main() {

      c := make(chan []int, 5)
      bucket := make(chan []int)

      go runner(1, c, bucket)
      go runner(2, c, bucket)
      go runner(3, c, bucket)
      go runner(4, c, bucket)

      bucket <- []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}

      go printer(c)

      var input string
      fmt.Scanln(&input)

 }

Body:
  bucket := make(chan []int)

Your b channel's capacity is 0. This means whenever you send something to this channel, the channel is full immediately and will block until a receiver reads the channel.

When there is only one runner left, no one is going to call bucket := <-b to read the last bucket, thus this last goroutine is stuck forever on the b <- bucket line, and thus the next line c <- temp will never be called for this last goroutine.


问:
How to render formatted post content in widget in Wordpress
I am new on wordpress and try to make a widget which will only show the last post of particuler category.

TO do this I have given some settings in admin to select category for which admin wants to display last post (post of last ID).

I am using the below code to in widget to display post content:

```<code>$query_arguments = array(
        'posts_per_page' => (int) 1,
        'post_type' => 'post',
        'post_status' => 'publish',
        'cat' => (int) $settings['category'],
        'order' => 'DESC',
        'orderby' => (($settings['display_by'] == 0) ? 'ID' : 'date')
    );

$posts_query = new WP_Query( $query_arguments );
if ($posts_query->have_posts()) {
    $posts = $posts_query->get_posts();
    $post = $posts[0];
    echo $post->post_content;
}
</code>```

But the above code is showing content in one paragraph or you can say that without format. I have done lot of search and found that, I need to apply  "the_content" filter to format the content. So I have done the same as below code:

```<code>if ($posts_query->have_posts()) {
    $posts = $posts_query->get_posts();
    $post = $posts[0];
    $content = apply_filters('the_content', $post->post_content);
    echo $content;
}
</code>```

Now the above changes is returning the null string. I have google lot of things but everyone is saying that to use apply filter or use the_content() function. I have tried both solutions but nothing happening.

Can anyone please share the solution for this problem?

答:
please check whether you are getting any text in $post->post_content
by echo $post->post_content</p>

Body:
I am new on wordpress and try to make a widget which will only show the last post of particuler category.

TO do this I have given some settings in admin to select category for which admin wants to display last post (post of last ID).

I am using the below code to in widget to display post content:

$query_arguments = array(
        'posts_per_page' => (int) 1,
        'post_type' => 'post',
        'post_status' => 'publish',
        'cat' => (int) $settings['category'],
        'order' => 'DESC',
        'orderby' => (($settings['display_by'] == 0) ? 'ID' : 'date')
    );

$posts_query = new WP_Query( $query_arguments );
if ($posts_query->have_posts()) {
    $posts = $posts_query->get_posts();
    $post = $posts[0];
    echo $post->post_content;
}

But the above code is showing content in one paragraph or you can say that without format. I have done lot of search and found that, I need to apply  "the_content" filter to format the content. So I have done the same as below code:

if ($posts_query->have_posts()) {
    $posts = $posts_query->get_posts();
    $post = $posts[0];
    $content = apply_filters('the_content', $post->post_content);
    echo $content;
}

Now the above changes is returning the null string. I have google lot of things but everyone is saying that to use apply filter or use the_content() function. I have tried both solutions but nothing happening.

Can anyone please share the solution for this problem?


问:
Business Logic when Saving in Entity Framework
If I want to perform some action when an entity is saved, I can do something as described here.

However, suppose I retrieve an object from the database. This object has a list of items within it. If I instantiate a new item and add it to this list and then save all changes, the item in the list is not part of the "GetObjectStateEntries".

答:
The problem for my situation, I believe, has been resolved. There appears to be a bug, in my opinion, in the ObjectContext.SaveChanges(SaveOptions) method. Even though this method will call DetectChanges (depending on the saveOptions), the OnSavingChanges method is called FIRST. This, I think, is a problem.

The solution to this is to call ObjectContext.DetectChanges() prior to calling SaveChanges().

ContentLicense: CC BY-SA 2.5


问:
Which type of threads are better for computation-intensive parallel applications and I/O intensive parallel applications?
Multi threading at the kernel level means that multiples processes can be executed on different threads at the same time.

User level threads reside in the processes which do not share same address space.

So, which type of thread is better for computation-intensive parallel applications and I/O intensive parallel applications?

答:
In reality there is no advantage whatsoever of user level threads over kernel level threads. (There are some useless textbooks that invent such advantages.)

User threads are poor-mans threading that was invented in the days before kernel threads existed. They persist only because certain operating systems have not implemented kernel threads.


问:
The target type of this expression must be a functional interface -Java 8 Functoinal Interface
I just have a small doubt on lambdas.I'm getting the below error with the following code.If i'm calling a method which returns boolean or other type, I don't see this issue.How can i solve this problem?

Error:

Exception in thread "main" java.lang.Error: Unresolved compilation problems:
          The method forEach(Consumer) in the type Iterable is not applicable for the arguments (( bean) -> {})
          The target type of this expression must be a functional interface

at com.wipro.MethodReference.main(MethodReference.java:18)

```<code>package com.sample;

import com.student.MockClass;

import java.util.ArrayList;
import java.util.List;

public class MethodReference {
    public static void main(String[] args) {
        MockClass obj = new MockClass("JSP", 2);
        MockClass obj1 = new MockClass("Java", 8);
        List<MockClass> listofBeans = new ArrayList<MockClass>();
        listofBeans.add(obj);
        listofBeans.add(obj1);
        listofBeans.forEach(bean -> MethodReference::call);
    }

     public static void call(){
        System.out.println("Hii!!!");
    }
}
</code>```

答:
The purpose of functional interfaces (in this case a Consumer) is to pass data through the stream. Your method call() makes not much sense since it accepts no parameter and returns nothing. You can do it but not with a method reference.

Try this instead:

```<code>listofBeans.forEach(MethodReference::call);
public static void call(MockClass bean){...}
</code>```

or

```<code>listofBeans.forEach(bean -> call());
</code>```

Body:
I just have a small doubt on lambdas.I'm getting the below error with the following code.If i'm calling a method which returns boolean or other type, I don't see this issue.How can i solve this problem?

Error:

Exception in thread "main" java.lang.Error: Unresolved compilation problems:
          The method forEach(Consumer) in the type Iterable is not applicable for the arguments (( bean) -> {})
          The target type of this expression must be a functional interface

at com.wipro.MethodReference.main(MethodReference.java:18)

package com.sample;

import com.student.MockClass;

import java.util.ArrayList;
import java.util.List;

public class MethodReference {
    public static void main(String[] args) {
        MockClass obj = new MockClass("JSP", 2);
        MockClass obj1 = new MockClass("Java", 8);
        List<MockClass> listofBeans = new ArrayList<MockClass>();
        listofBeans.add(obj);
        listofBeans.add(obj1);
        listofBeans.forEach(bean -> MethodReference::call);
    }

     public static void call(){
        System.out.println("Hii!!!");
    }
}

Body:
The purpose of functional interfaces (in this case a Consumer) is to pass data through the stream. Your method call() makes not much sense since it accepts no parameter and returns nothing. You can do it but not with a method reference.

Try this instead:

listofBeans.forEach(MethodReference::call);
public static void call(MockClass bean){...}

or

listofBeans.forEach(bean -> call());


问:
Responsive design: Mobile version of site shows full version while loading
I'm trying to build mobile version of my website using CSS and jQuery. Website works fine but when page is still loading on mobile browser, it shows full version of website for a second then shows mobile version when page is fully loaded. Last time even I made different website for mobile for same domain name using:

```<code>if($(window).width()<500){window.loacation('mobile.webtsite.com')}
</code>```

still I have the same problem.
But this time what I am doing is:

```<code> if($(window).width()<500){
        $("#linkCss").attr('href','styles/mobile.css');
        var high=$(window).height()*60/100;
</code>```

答:
Try placing your script tag with the above code before the body of the page in your head tag.</p>

```<code><head>
<script>
  if($(window).width()<500){
  .
  .
  .
  }
</script>
</head>
<body></body>
</code>```

Body:
I'm trying to build mobile version of my website using CSS and jQuery. Website works fine but when page is still loading on mobile browser, it shows full version of website for a second then shows mobile version when page is fully loaded. Last time even I made different website for mobile for same domain name using:

if($(window).width()<500){window.loacation('mobile.webtsite.com')}

still I have the same problem.
But this time what I am doing is:

 if($(window).width()<500){
        $("#linkCss").attr('href','styles/mobile.css');
        var high=$(window).height()*60/100;

Body:
Try placing your script tag with the above code before the body of the page in your head tag.

<head>
<script>
  if($(window).width()<500){
  .
  .
  .
  }
</script>
</head>
<body></body>


问:
Type aliasing in Scala
I don't actually know what to call this question. The title presented was the best I could come up with.

We are currently working with functional programming in Scala in school, and every so often there are a few instances where something just doesn't make sense in the way of things I am used to... A particular example is this:

```<code>type Rand[+A] = RNG => (A, RNG)

val int: Rand[Int] = _.nextInt

def unit[A](a: A): Rand[A] =
   rng => (a, rng)
</code>```

We are dealing with states here, trying to combat the repetition of having to transfer a new state to each function every time we are generating new random numbers using our RNG trait.

My question is this:

The lambda function expression defines the predicate "rng =>" to be used as the place holder for our state. Normally what this predicate defines is clear such as with List.map(x => x) where x is each element of the list. But it is not clear to me what rng is here.

EDIT: I guess some people didn't understand the question so I will give some further examples here to clarify...

I'm not asking what Rand[A] is representing. I am asking what the received argument rng => is supposed to be interpreted as... For example

```<code>def map[A,B](l: List[A])(f: A => B): List[B] = ...
val l = List(1,2,3,4,5)
// l.map(x => x+1) -> List(2,3,4,5,6)
</code>```

In the above map example, it is very easy to conceptually understand that the received argument x => given by the function argument f is to be interpreted as each individual element of the list l.

I am specifically looking for such a conceptual connection with rng => in unit.

答:
OK, I'll have a go at it.

```<code>def unit[A](a: A): Rand[A] = rng => (a, rng)
</code>```

Here unit takes one argument and builds half of a tuple. It returns the means to build the completed tuple.

```<code>val uHalf = unit('q')  // this is the "a" parameter
</code>```

Now, because of the definition of type Rand (and uHalf is of type Rand) the other half of the tuple can only be of type RNG, which isn't defined in your code example. But let's say you have a blob of type RNG handy.

```<code>val tup = uHalf(blob)  // this is the "rng" parameter
</code>```

Now you have the tuple ('q', blob).

You're right, in the example List(3,2,1).map(x => ..., x is the stand-in for values supplied from the List. In the case of Rand, rng is the stand-in for a value (of type RNG) to be supplied sometime/somewhere later in the code.

Title: Type aliasing in Scala

Body:
I don't actually know what to call this question. The title presented was the best I could come up with.

We are currently working with functional programming in Scala in school, and every so often there are a few instances where something just doesn't make sense in the way of things I am used to... A particular example is this:

type Rand[+A] = RNG => (A, RNG)

val int: Rand[Int] = _.nextInt

def unit[A](a: A): Rand[A] =
   rng => (a, rng)

We are dealing with states here, trying to combat the repetition of having to transfer a new state to each function every time we are generating new random numbers using our RNG trait.

My question is this:

The lambda function expression defines the predicate "rng =>" to be used as the place holder for our state. Normally what this predicate defines is clear such as with List.map(x => x) where x is each element of the list. But it is not clear to me what rng is here.

EDIT: I guess some people didn't understand the question so I will give some further examples here to clarify...

I'm not asking what Rand[A] is representing. I am asking what the received argument rng => is supposed to be interpreted as... For example

def map[A,B](l: List[A])(f: A => B): List[B] = ...
val l = List(1,2,3,4,5)
// l.map(x => x+1) -> List(2,3,4,5,6)

In the above map example, it is very easy to conceptually understand that the received argument x => given by the function argument f is to be interpreted as each individual element of the list l.

I am specifically looking for such a conceptual connection with rng => in unit.

Body:
OK, I'll have a go at it.

def unit[A](a: A): Rand[A] = rng => (a, rng)

Here unit takes one argument and builds half of a tuple. It returns the means to build the completed tuple.

val uHalf = unit('q')  // this is the "a" parameter

Now, because of the definition of type Rand (and uHalf is of type Rand) the other half of the tuple can only be of type RNG, which isn't defined in your code example. But let's say you have a blob of type RNG handy.

val tup = uHalf(blob)  // this is the "rng" parameter

Now you have the tuple ('q', blob).

You're right, in the example List(3,2,1).map(x => ..., x is the stand-in for values supplied from the List. In the case of Rand, rng is the stand-in for a value (of type RNG) to be supplied sometime/somewhere later in the code.


问:
Pandas dataframe group values in the order in which they appear
I have a dataframe that looks like this:

Would like to create a new dataframe that takes the values of A and B and arranges them like this:

答:
groupby column 'A' and use cumcount to index each grouping separately

then argsort and pass that to iloc to reorder accordingly

solution

```<code>df.iloc[df.groupby('A').cumcount().argsort()]

   A   B
0  1  40
3  2  58
6  3   9
1  1  39
4  2  65
7  3   0
2  1  73
5  2  22
8  3  21
</code>```

Body:
groupby column 'A' and use cumcount to index each grouping separately

then argsort and pass that to iloc to reorder accordingly

solution

df.iloc[df.groupby('A').cumcount().argsort()]

   A   B
0  1  40
3  2  58
6  3   9
1  1  39
4  2  65
7  3   0
2  1  73
5  2  22
8  3  21


问:
Splitting CSV data in Blender Game Engine with Python
I'm working on a small project in BGE and trying to import data.txt to a data.csv file and then split the data into 2 columns.

My data.txt looks like this;

```<code>Breathing rate:, 1.0
Pulse:, 140
Spinal Injury:, Yes
</code>```

As you would guess, I want "," as a delimiter for the columns.

And here's my current code;

```<code>try:
    file = open(path+"dialogue.txt", 'r')
    info = file.readlines()
    own.text = str(info[currentLineNumber])
except:
    own.text = "end of script"

column1 = []
column2 = []
if own ["currentLine"] == 10:
    own.sendMessage("resume")
    with open(path+"data.txt", 'r') as in_file:
        stripped = (line.strip() for line in in_file)
        datalines = (line.split(",") for line in stripped if line)
        with open(path+"data.csv", 'w') as out_file:
            writer = csv.writer(out_file)
            writer.writerow(('subject', 'value'))
            writer.writerow(('ID: ', (uuid.uuid1())))
            writer.writerows(datalines)
os.rename(path+"data.csv", path+"newData.csv")
with open('newData.csv', 'r') as f:
    reader = csv.reader(f, delimiter=',')
    for row in reader:
        column1.append(row[0])
        column2.append(row[1])
</code>```

I can import the data to data.csv but I can't split the data into columns, all the imported data in a single column. How can I fix this?

答:
At least if the format in your example is consistent, you can just do this:

```<code>datafile = "path/to/textfile"
with open (datafile, 'rt') as filehandle:
   csv_reader = csv.reader(filehandle, delimiter = ',')
   data = [row for row in csv_reader]
</code>```

this will collect the comma-separated pairs into a list-of-lists like this:

```<code>[['Breathing rate:', ' 1.0'], ['Pulse:', ' 140'], ['Spinal Injury:', ' Yes']]
</code>```

If the data you want is a subset of the larger file, you can copy it into a stringIO object and pass that to the csv reader instead; it will look like a disk file to the reader. Here's a simple example:

```<code>import StringIO
filtered_data = StringIO.StringIO()
with open(datafile, 'rt') as originalfile:
     for line in originalfile:
        if ":," in line:  # your real criteria would go here...
            filtered_data.write(line.strip() + "\n")

# rewind to beginning of your stringIO
filtered_data.seek(0)
csv_reader = csv.reader(filtered_data, delimiter = ',')
data = [row for row in csv_reader]
</code>```

I just guessed what the criteria for finding good lines actually -- you could use any logic you needed to pick only comma-separated lines

Body:
I'm working on a small project in BGE and trying to import data.txt to a data.csv file and then split the data into 2 columns.

My data.txt looks like this;

Breathing rate:, 1.0
Pulse:, 140
Spinal Injury:, Yes

As you would guess, I want "," as a delimiter for the columns.

And here's my current code;

try:
    file = open(path+"dialogue.txt", 'r')
    info = file.readlines()
    own.text = str(info[currentLineNumber])
except:
    own.text = "end of script"

column1 = []
column2 = []
if own ["currentLine"] == 10:
    own.sendMessage("resume")
    with open(path+"data.txt", 'r') as in_file:
        stripped = (line.strip() for line in in_file)
        datalines = (line.split(",") for line in stripped if line)
        with open(path+"data.csv", 'w') as out_file:
            writer = csv.writer(out_file)
            writer.writerow(('subject', 'value'))
            writer.writerow(('ID: ', (uuid.uuid1())))
            writer.writerows(datalines)
os.rename(path+"data.csv", path+"newData.csv")
with open('newData.csv', 'r') as f:
    reader = csv.reader(f, delimiter=',')
    for row in reader:
        column1.append(row[0])
        column2.append(row[1])

I can import the data to data.csv but I can't split the data into columns, all the imported data in a single column. How can I fix this?

Body:
At least if the format in your example is consistent, you can just do this:

datafile = "path/to/textfile"
with open (datafile, 'rt') as filehandle:
   csv_reader = csv.reader(filehandle, delimiter = ',')
   data = [row for row in csv_reader]

this will collect the comma-separated pairs into a list-of-lists like this:

[['Breathing rate:', ' 1.0'], ['Pulse:', ' 140'], ['Spinal Injury:', ' Yes']]

If the data you want is a subset of the larger file, you can copy it into a stringIO object and pass that to the csv reader instead; it will look like a disk file to the reader. Here's a simple example:

import StringIO
filtered_data = StringIO.StringIO()
with open(datafile, 'rt') as originalfile:
     for line in originalfile:
        if ":," in line:  # your real criteria would go here...
            filtered_data.write(line.strip() + "\n")

# rewind to beginning of your stringIO
filtered_data.seek(0)
csv_reader = csv.reader(filtered_data, delimiter = ',')
data = [row for row in csv_reader]

I just guessed what the criteria for finding good lines actually -- you could use any logic you needed to pick only comma-separated lines


问:
Compare-And-Swap not working on many Cores
When I discovered the "CAS" instruction, I remember that I well understood that it could work for threads running on one single CPU but I was surprised that it could for many CPUs

Yesterday, I had my first opportunity to test it on one of my developments. I implemented it and it really worked fine; all my unit-tests was green. Perfect.

But today, I ran my unit-tests on another machine and they are now failing. Less perfect

The main difference on the two machines is that the first one (the one on which the unit-tests are green) is a quit old laptop, with only one core! The second one is more recent i7, and more powerfull...

Now, on my i7, if I force my unit-tests to run on one single core, they become successful. I do this by running

```<code>taskset -c <cpu-id> my-unit-test
</code>```

Legitimately, my original question comes back: is CAS working on many cores? OK, according to what I read, I would be surprised if it didn't...

So what? I hope it comes from a bug in my code. To give you more information, I have a class with a critical section. I added an attribute

```<code>bool m_isBeingModified;
</code>```

It is initialized to false. Moreover, at the beginning of my critical section, I run the function

```<code>inline void waitForClassBeingModified()
{
  while (!__sync_bool_compare_and_swap(&m_isBeingModified, false, true))
  {} /// I concider that I can to such a loop as my critical section is very light/short
}
</code>```

Finally, at the end of my critical section, I reset my boolean variable

```<code> m_isBeingModified = false;
</code>```

I tried to set my attribute as volatile but it did not change anything: my unit-tests are still failing

Last information:

```<code>gcc --version
gcc (Ubuntu 6.2.0-5ubuntu12) 6.2.0 20161005
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
</code>```

Thank you for your help

答:
Thanks to Uli's precious help, I think that I have now all the elements to answer to my question.

First of all, I may not be clear until there but the function I want to protect against concurrent access is very light. It takes around 80 cpu cycles to complete (TSC). That's why I prefer to implement my own 'light' concurrent mutex based one CAS than using pthread_mutex.

I found this interesting page that explains how to 'temporarily' disable the code-reordering thanks to the following instruction:

```<code>__asm__ __volatile__("":::"memory");
</code>```

Using it, I really boost my concurrency-protection and, of course all my tests are still successful.

To get a summary, the following list reports the impact on performance of different solutions I tried:

Original code (without protection): around 80 TSC

Double CAS (set & unset variable): around 105 TSC

Mutexes based solution: around 120 TSC

Single CAS + disable reordering: around 85 TSC

Body:
When I discovered the "CAS" instruction, I remember that I well understood that it could work for threads running on one single CPU but I was surprised that it could for many CPUs

Yesterday, I had my first opportunity to test it on one of my developments. I implemented it and it really worked fine; all my unit-tests was green. Perfect.

But today, I ran my unit-tests on another machine and they are now failing. Less perfect

The main difference on the two machines is that the first one (the one on which the unit-tests are green) is a quit old laptop, with only one core! The second one is more recent i7, and more powerfull...

Now, on my i7, if I force my unit-tests to run on one single core, they become successful. I do this by running

taskset -c <cpu-id> my-unit-test

Legitimately, my original question comes back: is CAS working on many cores? OK, according to what I read, I would be surprised if it didn't...

So what? I hope it comes from a bug in my code. To give you more information, I have a class with a critical section. I added an attribute

bool m_isBeingModified;

It is initialized to false. Moreover, at the beginning of my critical section, I run the function

inline void waitForClassBeingModified()
{
  while (!__sync_bool_compare_and_swap(&m_isBeingModified, false, true))
  {} /// I concider that I can to such a loop as my critical section is very light/short
}

Finally, at the end of my critical section, I reset my boolean variable

 m_isBeingModified = false;

I tried to set my attribute as volatile but it did not change anything: my unit-tests are still failing

Last information:

gcc --version
gcc (Ubuntu 6.2.0-5ubuntu12) 6.2.0 20161005
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Thank you for your help

Body:
Thanks to Uli's precious help, I think that I have now all the elements to answer to my question.

First of all, I may not be clear until there but the function I want to protect against concurrent access is very light. It takes around 80 cpu cycles to complete (TSC). That's why I prefer to implement my own 'light' concurrent mutex based one CAS than using pthread_mutex.

I found this interesting page that explains how to 'temporarily' disable the code-reordering thanks to the following instruction:

__asm__ __volatile__("":::"memory");

Using it, I really boost my concurrency-protection and, of course all my tests are still successful.

To get a summary, the following list reports the impact on performance of different solutions I tried:

Original code (without protection): around 80 TSC

Double CAS (set & unset variable): around 105 TSC

Mutexes based solution: around 120 TSC

Single CAS + disable reordering: around 85 TSC


问:
How to launch the default Music Player in Windows10

How could I launch the default music player in Windows 10 from my WinForms application.
And how to get the play status (like the info in picture)?

答:
You can launch the default music app by using the Launcher api (https://learn.microsoft.com/en-us/uwp/api/Windows.System.Launcher) and pointing it to a music file (.mp3, .wav).

However, you can't control another UWP app or get info from it since UWP apps are sandboxed.

Windows, being the OS and host of the app, has access to everything the app is doing and so it can monitor it and get any data from it, this is why the Volume Control can display this info.

Edit: technically, an app playing music in background will have access to APIs that control that Volume Control display and using those APIs, the app can set the picture, track name, artist name, and so on.


问:
Where is the entry count for an object stored in Java
I understand that the each Java object can be used as a Monitor. A thread can acquire the lock if the entry count associated with the object is zero. And if the same thread acquires the lock, the entry count is incremented thru the "monitorenter" opcode and is decremented when the same thread releases the code during "monitorexit". Where is this entry count stored? How is it linked to a Java object? Does it get allocated when the object is created?</p>

答:
This count is used internally in JVM and cannot be visible from your code.
You can however count it for yourself, but be aware, that lock is released (counter in JVM decreased until 0) even, if Exception occurs in "synchronized" code.</p>


问:
PHP AMAZON API GATEWAY : The request signature we calculated does not match the signature you provided
I want to get response from website content.geappliances.io using AWS API Gateway but always get error :

{"message":"The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.\n\nThe Canonical String for this request should have been\n'GET\n/search/b2b/results\n\ncontent-type:\nhost:content.geappliances.io\nx-amz-date:20170401T041050Z\n\ncontent-type;host;x-amz-date\ne3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'\n\nThe String-to-Sign should have been\n'AWS4-HMAC-SHA256\n20170401T041050Z\n20170401/us-east-1/execute-api/aws4_request\na8aec6a82c0f9a2471bd17faa5f2ce5cd810a16f129fca9b04347ceed54fdc61'\n"}

please somebody help me, what's wrong with my code. Here's the code :

```<code>function signRequest(){

    $method ='GET';
    $uri = '/search/b2b/results?N=0&Ntk=SKU&Ntt=GTX33EASKWW';

    $access_key         = 'my-access-key';
    $secretKey          = 'my-secret-key';
    $region             = 'us-east-1';
    $kService           = 'execute-api';
    $service            = 'execute-api';

    $options = array();
    $headers = array();
    $host    = "content.geappliances.io";
    $alg = 'sha256';

    $date = new DateTime( 'UTC' );

    $dd = $date->format( 'Ymd\THis\Z' );

    $amzdate2 = new DateTime( 'UTC' );
    $amzdate2 = $amzdate2->format( 'Ymd' );
    $amzdate = $dd;

    $algorithm = 'AWS4-HMAC-SHA256';

    $requestPayload = "UNSIGNED_PAYLOAD";
    $hashedPayload = hash($alg, $requestPayload);

    $canonical_uri = $uri;
    $canonical_querystring = '';

    $canonical_headers = "content-type:"."application/json"."\n"."host:".$host."\n"."x-amz-date:".$amzdate."\n";
    $signed_headers = 'content-type;host;x-amz-date';
    $canonical_request = "".$method."\n".$canonical_uri."\n".$canonical_querystring."\n".$canonical_headers."\n".$signed_headers."\n".$hashedPayload;

    $credential_scope = $amzdate2 . '/' . $region . '/' . $service . '/' . 'aws4_request';
    $string_to_sign  = "".$algorithm."\n".$amzdate ."\n".$credential_scope."\n".hash('sha256', $canonical_request)."";

    $kSecret = 'AWS4' . $secretKey;
    $kDate = hash_hmac( $alg, $amzdate2, $kSecret, true );
    $kRegion = hash_hmac( $alg, $region, $kDate, true );
    $kService = hash_hmac( $alg, $service, $kRegion, true );
    $kSigning = hash_hmac( $alg, 'aws4_request', $kService, true );
    $signature = hash_hmac( $alg, $string_to_sign, $kSigning );
    $authorization_header = $algorithm . ' ' . 'Credential=' . $access_key . '/' . $credential_scope . ', ' .  'SignedHeaders=' . $signed_headers . ', ' . 'Signature=' . $signature;

    $headers = array(
                'content-typeapplication/json',
                "cache-control: no-cache",
                "host: content.geappliances.io",
                'x-amz-date: '.$amzdate.'',
                'Authorization: '.$authorization_header.''
            );
    return $headers;

}

$curl = curl_init();

curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://content.geappliances.io/search/b2b/results?N=0&Ntk=SKU&Ntt=GTX33EASKWW",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => signRequest(),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
</code>```

in the postman, I generate my access key and secret key then it works nicely.

postman result

答:
Take a look at your code

```<code>$access_key         = 'my-access-key';
$secretKey          = 'my-secret-key';
</code>```

You have to enter your values for access key and secret key there. I assume Amazon provided them for you?

Because your error message says

The request signature we calculated does not match the signature you
  provided. Check your AWS Secret Access Key and signing method.

Body:
I want to get response from website content.geappliances.io using AWS API Gateway but always get error :

{"message":"The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.\n\nThe Canonical String for this request should have been\n'GET\n/search/b2b/results\n\ncontent-type:\nhost:content.geappliances.io\nx-amz-date:20170401T041050Z\n\ncontent-type;host;x-amz-date\ne3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'\n\nThe String-to-Sign should have been\n'AWS4-HMAC-SHA256\n20170401T041050Z\n20170401/us-east-1/execute-api/aws4_request\na8aec6a82c0f9a2471bd17faa5f2ce5cd810a16f129fca9b04347ceed54fdc61'\n"}

please somebody help me, what's wrong with my code. Here's the code :

function signRequest(){

    $method ='GET';
    $uri = '/search/b2b/results?N=0&Ntk=SKU&Ntt=GTX33EASKWW';

    $access_key         = 'my-access-key';
    $secretKey          = 'my-secret-key';
    $region             = 'us-east-1';
    $kService           = 'execute-api';
    $service            = 'execute-api';

    $options = array();
    $headers = array();
    $host    = "content.geappliances.io";
    $alg = 'sha256';

    $date = new DateTime( 'UTC' );

    $dd = $date->format( 'Ymd\THis\Z' );

    $amzdate2 = new DateTime( 'UTC' );
    $amzdate2 = $amzdate2->format( 'Ymd' );
    $amzdate = $dd;

    $algorithm = 'AWS4-HMAC-SHA256';

    $requestPayload = "UNSIGNED_PAYLOAD";
    $hashedPayload = hash($alg, $requestPayload);

    $canonical_uri = $uri;
    $canonical_querystring = '';

    $canonical_headers = "content-type:"."application/json"."\n"."host:".$host."\n"."x-amz-date:".$amzdate."\n";
    $signed_headers = 'content-type;host;x-amz-date';
    $canonical_request = "".$method."\n".$canonical_uri."\n".$canonical_querystring."\n".$canonical_headers."\n".$signed_headers."\n".$hashedPayload;

    $credential_scope = $amzdate2 . '/' . $region . '/' . $service . '/' . 'aws4_request';
    $string_to_sign  = "".$algorithm."\n".$amzdate ."\n".$credential_scope."\n".hash('sha256', $canonical_request)."";

    $kSecret = 'AWS4' . $secretKey;
    $kDate = hash_hmac( $alg, $amzdate2, $kSecret, true );
    $kRegion = hash_hmac( $alg, $region, $kDate, true );
    $kService = hash_hmac( $alg, $service, $kRegion, true );
    $kSigning = hash_hmac( $alg, 'aws4_request', $kService, true );
    $signature = hash_hmac( $alg, $string_to_sign, $kSigning );
    $authorization_header = $algorithm . ' ' . 'Credential=' . $access_key . '/' . $credential_scope . ', ' .  'SignedHeaders=' . $signed_headers . ', ' . 'Signature=' . $signature;

    $headers = array(
                'content-typeapplication/json',
                "cache-control: no-cache",
                "host: content.geappliances.io",
                'x-amz-date: '.$amzdate.'',
                'Authorization: '.$authorization_header.''
            );
    return $headers;

}

$curl = curl_init();

curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://content.geappliances.io/search/b2b/results?N=0&Ntk=SKU&Ntt=GTX33EASKWW",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => signRequest(),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

in the postman, I generate my access key and secret key then it works nicely.

postman result

Body:
Take a look at your code

$access_key         = 'my-access-key';
$secretKey          = 'my-secret-key';

You have to enter your values for access key and secret key there. I assume Amazon provided them for you?

Because your error message says

The request signature we calculated does not match the signature you
  provided. Check your AWS Secret Access Key and signing method.


问:
Invalid argument when converting float to datetime
I have to get a datetime from a float using Python. I am tryint to use the following code:

```<code>import time
print (time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(float(63650571169.50261))))
</code>```

But when executing this code, I get an error:

```<code>OSError: [Errno 22] Invalid argument
</code>```

The sys.float_info.max displays 1.7976931348623157e+308.

How do I convert this float number into a datetime?

答:
It looks like your OS is using the ISO 8601:2004 (clause 4.3.2.1 The Gregorian calendar) with the epoch at Year 0.  This can be converted by applying the correct zero offset as:

Code:

```<code>import datetime as dt

# define some constants
epoch = dt.datetime(1970, 1, 1)
gregorian_8601_to_unix_epoch = 62167305600

def gregorian_8601_to_datetime(gregorian_8601_seconds):

    # get number of seconds from epoch
    from_epoch = gregorian_8601_seconds - gregorian_8601_to_unix_epoch

    # convert to python datetime
    return epoch + dt.timedelta(seconds=from_epoch)
</code>```

Test Code:

```<code>print(gregorian_8601_to_datetime(63650571169.50261))
</code>```

Results:

```<code>2017-01-01 10:12:49.502609
</code>```

Body:
I have to get a datetime from a float using Python. I am tryint to use the following code:

import time
print (time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(float(63650571169.50261))))

But when executing this code, I get an error:

OSError: [Errno 22] Invalid argument

The sys.float_info.max displays 1.7976931348623157e+308.

How do I convert this float number into a datetime?

Body:
It looks like your OS is using the ISO 8601:2004 (clause 4.3.2.1 The Gregorian calendar) with the epoch at Year 0.  This can be converted by applying the correct zero offset as:

Code:

import datetime as dt

# define some constants
epoch = dt.datetime(1970, 1, 1)
gregorian_8601_to_unix_epoch = 62167305600

def gregorian_8601_to_datetime(gregorian_8601_seconds):

    # get number of seconds from epoch
    from_epoch = gregorian_8601_seconds - gregorian_8601_to_unix_epoch

    # convert to python datetime
    return epoch + dt.timedelta(seconds=from_epoch)

Test Code:

print(gregorian_8601_to_datetime(63650571169.50261))

Results:

2017-01-01 10:12:49.502609


问:
How to post an event using IPC EventBus?
I am following the answer on this post IPC in Android using GreenRobot eventbus about IPCEventBus.

```<code>public class Listener implements IIpcEventBusConnectionListener, IIpcEventBusObserver {

    public Listener() {
        IIpcEventBusConnector connector =
            ConnectorFactory.getInstance().buildConnector(context, this, "com.blueengine.login");
        connector.startConnection();
    }

    @Override
    public void onConnected(IIpcEventBusConnector connector) {
        connector.registerObserver(this);
    }

    @Override
    public void onEvent(IEventIpc event) {

    }

    @Override
    public void onDisconnected(IIpcEventBusConnector connector) {

    }
}
</code>```

Then on my Login app

I want to send an event called UserLoggin. How do I do this?

```<code>public class UserLoggin implements IEventIpc
{
}
</code>```

答:
When your event triggers post the event by calling this:

```<code>IpcEventBus.getInstance().postEvent(event);
</code>```

As outlined in the documentation.

Body:
I am following the answer on this post IPC in Android using GreenRobot eventbus about IPCEventBus.

public class Listener implements IIpcEventBusConnectionListener, IIpcEventBusObserver {

    public Listener() {
        IIpcEventBusConnector connector =
            ConnectorFactory.getInstance().buildConnector(context, this, "com.blueengine.login");
        connector.startConnection();
    }

    @Override
    public void onConnected(IIpcEventBusConnector connector) {
        connector.registerObserver(this);
    }

    @Override
    public void onEvent(IEventIpc event) {

    }

    @Override
    public void onDisconnected(IIpcEventBusConnector connector) {

    }
}

Then on my Login app

I want to send an event called UserLoggin. How do I do this?

public class UserLoggin implements IEventIpc
{
}

Body:
When your event triggers post the event by calling this:

IpcEventBus.getInstance().postEvent(event);

As outlined in the documentation.


答:
You are using multi array

```<code> <?php
   $response = Array ( "333212" => Array ( "view" => 323, "sold" => 3, "buy" => 43, "number" => 333212 ) ) ;
   $variable = $response["333212"];
   echo $variable['view']."\n";
   echo $variable['buy']."\n";
   echo $variable['sold'];
?>
</code>```

Demo : https://eval.in/765754

Title: extract values in array and create variable php

Body:
Hi Stackoverflow and programmer!

I have this code :

$result = print_r($reponse, true);

echo $result;

Wich give me this output :

Array ( [333212] => Array ( [view] => 323 [sold] => 3 [buy] => 43 [number] => 333212 ) )

I need to find a way to have something like :

echo $variable['view']; (323)

echo $variable['buy']; (3)

echo $variable['sold']; (43)

I check and try a lot of things like extract(); serialize(); dumb_var i try explode("")  i search a little everywhere but dint find answer.

Thanks a lot for the help ! much apreciated !!!

Pierre-luc

Body:
You are using multi array

 <?php
   $response = Array ( "333212" => Array ( "view" => 323, "sold" => 3, "buy" => 43, "number" => 333212 ) ) ;
   $variable = $response["333212"];
   echo $variable['view']."\n";
   echo $variable['buy']."\n";
   echo $variable['sold'];
?>

Demo : https://eval.in/765754


问:
jQuery or CSS changing and fading background-position on hover
I have tried a few things but at this point now, i want to fadeout change background position and fadein but not working.... any ideas? or a better solution?

```<code>  $('.collection-hover a').on("mouseenter touchstart", function(event) {
    $(this).find('.collection-list-hover-desc').fadeIn(1000);
    $(this).animate({backgroundPosition: "-50% 100%"});
  });
  $('.collection-hover a').on("mouseleave touchend", function(event) {
    $(this).find('.collection-list-hover-desc').fadeOut(1000);
    $(this).animate({backgroundPosition: "0 0"});
  });
</code>```

snippet of html

```<code><li class="collection-list-item grid-item first collection-hover">
   <a href="/collections/butterfly-sofa" class="position-left" data-image="//cdn.shopify.com/s/files/1/1839/7697/collections/category-panel-butterfly.jpg?v=1491014401" style="background-image: url("//cdn.shopify.com/s/files/1/1839/7697/collections/category-panel-butterfly.jpg?v=1491014401"); height: 108.009px;">
  <div class="collection-list-hover-desc">

    <p>Dein eigener Ruhepol in einer hektischen Welt. Der durch eine Struktur im Inneren formstabile Sitzsack vereint Komfort und Ästhetik.</p>
  </div>
  <div class="collection-list-hover-button">
    <span class="button" style="
    padding: 5px 8px;
">Entdecken</span>
  </div>
</a>
</li>
</code>```

答:
A super easy way of moving elements on the page as well as changing opacity with jQuery is using GreenSock animations.

https://greensock.com/

They have many free versions that would be exactly what you are looking for in a matter of only a few lines. Something like the following below:

```<code><head>
//Calls to the Greensock CDN
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.19.1/TweenMax.min.js"></script>

<script>
   $('#your-element').hover(function() {

      TweenMax.to($('.your-element-to-change'), 1, {alpha: 0.5, left: 100, top: 100});
     })
</script>
</head>
</code>```

That code would animate your element left 100px, down 100px, and change the opacity to 0.5 over the course of 1 second. All of which you can change to meet your needs.

Body:
I have tried a few things but at this point now, i want to fadeout change background position and fadein but not working.... any ideas? or a better solution?

  $('.collection-hover a').on("mouseenter touchstart", function(event) {
    $(this).find('.collection-list-hover-desc').fadeIn(1000);
    $(this).animate({backgroundPosition: "-50% 100%"});
  });
  $('.collection-hover a').on("mouseleave touchend", function(event) {
    $(this).find('.collection-list-hover-desc').fadeOut(1000);
    $(this).animate({backgroundPosition: "0 0"});
  });

snippet of html

Dein eigener Ruhepol in einer hektischen Welt. Der durch eine Struktur im Inneren formstabile Sitzsack vereint Komfort und Ästhetik.

    Entdecken

Body:
A super easy way of moving elements on the page as well as changing opacity with jQuery is using GreenSock animations.

https://greensock.com/

They have many free versions that would be exactly what you are looking for in a matter of only a few lines. Something like the following below:

<head>
//Calls to the Greensock CDN
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.19.1/TweenMax.min.js"></script>

<script>
   $('#your-element').hover(function() {

      TweenMax.to($('.your-element-to-change'), 1, {alpha: 0.5, left: 100, top: 100});
     })
</script>
</head>

That code would animate your element left 100px, down 100px, and change the opacity to 0.5 over the course of 1 second. All of which you can change to meet your needs.


问:
How do detect that transaction has already been started?
I am using Zend_Db to insert some data inside a transaction. My function starts a transaction and then calls another method that also attempts to start a transaction and of course fails(I am using MySQL5). So, the question is - how do I detect that transaction has already been  started?
Here is a sample bit of code:

```<code>       try {
                    Zend_Registry::get('database')->beginTransaction();

                    $totals = self::calculateTotals($Cart);
                    $PaymentInstrument = new PaymentInstrument;
                    $PaymentInstrument->create();
                    $PaymentInstrument->validate();
                    $PaymentInstrument->save();

                    Zend_Registry::get('database')->commit();
                    return true;

            } catch(Zend_Exception $e) {
                    Bootstrap::$Log->err($e->getMessage());
                    Zend_Registry::get('database')->rollBack();
                    return false;
            }
</code>```

Inside PaymentInstrument::create there is another beginTransaction statement that produces the exception that says that transaction has already been started.

答:
I disagree with Bill Karwin's assessment that keeping track of transactions started is cockamamie, although I do like that word.

I have a situation where I have event handler functions that might get called by a module not written by me. My event handlers create a lot of records in the db. I definitely need to roll back if something wasn't passed correctly or is missing or something goes, well, cockamamie. I cannot know whether the outside module's code triggering the event handler is handling db transactions, because the code is written by other people. I have not found a way to query the database to see if a transaction is in progress.

So I DO keep count. I'm using CodeIgniter, which seems to do strange things if I ask it to start using nested db transactions (e.g. calling it's trans_start() method more than once). In other words, I can't just include trans_start() in my event handler, because if an outside function is also using trans_start(), rollbacks and commits don't occur correctly. There is always the possibility that I haven't yet figured out to manage those functions correctly, but I've run many tests.

All my event handlers need to know is, has a db transaction already been initiated by another module calling in? If so, it does not start another new transaction and does not honor any rollbacks or commits either. It does trust that if some outside function has initiated a db transaction then it will also be handling rollbacks/commits.

I have wrapper functions for CodeIgniter's transaction methods and these functions increment/decrement a counter.

```<code>function transBegin(){
    //increment our number of levels
    $this->_transBegin += 1;
    //if we are only one level deep, we can create transaction
    if($this->_transBegin ==1) {
        $this->db->trans_begin();
    }
}

function transCommit(){
    if($this->_transBegin == 1) {
        //if we are only one level deep, we can commit transaction
        $this->db->trans_commit();
    }
    //decrement our number of levels
    $this->_transBegin -= 1;

}

function transRollback(){
    if($this->_transBegin == 1) {
        //if we are only one level deep, we can roll back transaction
        $this->db->trans_rollback();
    }
    //decrement our number of levels
    $this->_transBegin -= 1;
}
</code>```

In my situation, this is the only way to check for an existing db transaction. And it works. I wouldn't say that "The Application is managing db transactions". That's really untrue in this situation. It is simply checking whether some other part of the application has started any db transactions, so that it can avoid creating nested db transactions.

Body:
I am using Zend_Db to insert some data inside a transaction. My function starts a transaction and then calls another method that also attempts to start a transaction and of course fails(I am using MySQL5). So, the question is - how do I detect that transaction has already been  started?
Here is a sample bit of code:

       try {
                    Zend_Registry::get('database')->beginTransaction();

                    $totals = self::calculateTotals($Cart);
                    $PaymentInstrument = new PaymentInstrument;
                    $PaymentInstrument->create();
                    $PaymentInstrument->validate();
                    $PaymentInstrument->save();

                    Zend_Registry::get('database')->commit();
                    return true;

            } catch(Zend_Exception $e) {
                    Bootstrap::$Log->err($e->getMessage());
                    Zend_Registry::get('database')->rollBack();
                    return false;
            }

Inside PaymentInstrument::create there is another beginTransaction statement that produces the exception that says that transaction has already been started.

Body:
I disagree with Bill Karwin's assessment that keeping track of transactions started is cockamamie, although I do like that word.

I have a situation where I have event handler functions that might get called by a module not written by me. My event handlers create a lot of records in the db. I definitely need to roll back if something wasn't passed correctly or is missing or something goes, well, cockamamie. I cannot know whether the outside module's code triggering the event handler is handling db transactions, because the code is written by other people. I have not found a way to query the database to see if a transaction is in progress.

So I DO keep count. I'm using CodeIgniter, which seems to do strange things if I ask it to start using nested db transactions (e.g. calling it's trans_start() method more than once). In other words, I can't just include trans_start() in my event handler, because if an outside function is also using trans_start(), rollbacks and commits don't occur correctly. There is always the possibility that I haven't yet figured out to manage those functions correctly, but I've run many tests.

All my event handlers need to know is, has a db transaction already been initiated by another module calling in? If so, it does not start another new transaction and does not honor any rollbacks or commits either. It does trust that if some outside function has initiated a db transaction then it will also be handling rollbacks/commits.

I have wrapper functions for CodeIgniter's transaction methods and these functions increment/decrement a counter.

function transBegin(){
    //increment our number of levels
    $this->_transBegin += 1;
    //if we are only one level deep, we can create transaction
    if($this->_transBegin ==1) {
        $this->db->trans_begin();
    }
}

function transCommit(){
    if($this->_transBegin == 1) {
        //if we are only one level deep, we can commit transaction
        $this->db->trans_commit();
    }
    //decrement our number of levels
    $this->_transBegin -= 1;

}

function transRollback(){
    if($this->_transBegin == 1) {
        //if we are only one level deep, we can roll back transaction
        $this->db->trans_rollback();
    }
    //decrement our number of levels
    $this->_transBegin -= 1;
}

In my situation, this is the only way to check for an existing db transaction. And it works. I wouldn't say that "The Application is managing db transactions". That's really untrue in this situation. It is simply checking whether some other part of the application has started any db transactions, so that it can avoid creating nested db transactions.


问:
Golang. Import only one file from package
Hi all. I am new in GO and need some help. I've got a project with this structure

But let's pretend that I have 100500 items in my logic package. What if I need import only one or two files for the specific package. Can I do it or I only can import a full package?

答:
I realize this question is largely already answered. But here are my thoughts anyways.

If the specific files can work independently from the rest of the package or do so with some minor modifications you can just simply copy those files to the project you want to use them in. Then reference the functions/methods/etc directly. But if you are using parts of a big package in various projects it would definitely be more suitable to break it into smaller packages. Then you can use those parts independently in as many projects as you wish without the excess baggage.


问:
jQuery .change event not firing on multiple same class
HTML code:

$(".imageupload").change(function() {
  alert($(this).attr('data-id'));
  var ID = $(this).attr('data-id');

  if (typeof(FileReader) != "undefined") {

    var image_holder = $("#image-holder" + ID);
    image_holder.empty();

    var reader = new FileReader();
    reader.onload = function(e) {
      $("", {
        "src": e.target.result,
        "class": "thumb-image"
      }).appendTo(image_holder);

    }
    image_holder.show();
    reader.readAsDataURL($(this)[0].files[0]);
  } else {
    alert("This browser does not support FileReader.");
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-6 col-md-3">
  <div id="image-holder1" style="margin-bottom:20px"> </div>
  <input type="file" class="input-file full-width imageupload" data-id="1" name="imageupload1" id="imageupload1" value="" placeholder="">
  <div id="displayimagefield">
    <div id="image-holder2" style="margin-bottom:20px"> </div>
    <input type="file" class="input-file full-width imageupload" data-id="2" name="imageupload2" id="imageupload2" value="" placeholder="">
    <div id="image-holder3" style="margin-bottom:20px"> </div>
    <input type="file" class="input-file full-width imageupload" data-id="3" name="imageupload3" id="imageupload3" value="" placeholder="">
  </div>
</div></code>```

class imageupload is in multiple element. Change event is firing only in data-id="1" not firing anywhere else. How can I resolve this error? Sorry for my weak English.

答:
Use event delegation for attachine events to dynamically added elements:</p>

```<code>$("body").on('change','.imageupload',function() {
    //CHANGE EVENT CODE HERE
});
</code>```

Body:
HTML code:

$(".imageupload").change(function() {
  alert($(this).attr('data-id'));
  var ID = $(this).attr('data-id');

  if (typeof(FileReader) != "undefined") {

    var image_holder = $("#image-holder" + ID);
    image_holder.empty();

    var reader = new FileReader();
    reader.onload = function(e) {
      $("", {
        "src": e.target.result,
        "class": "thumb-image"
      }).appendTo(image_holder);

    }
    image_holder.show();
    reader.readAsDataURL($(this)[0].files[0]);
  } else {
    alert("This browser does not support FileReader.");
  }
});

  <input type="file" class="input-file full-width imageupload" data-id="1" name="imageupload1" id="imageupload1" value="" placeholder="">

    <input type="file" class="input-file full-width imageupload" data-id="2" name="imageupload2" id="imageupload2" value="" placeholder="">

    <input type="file" class="input-file full-width imageupload" data-id="3" name="imageupload3" id="imageupload3" value="" placeholder="">

class imageupload is in multiple element. Change event is firing only in data-id="1" not firing anywhere else. How can I resolve this error? Sorry for my weak English.

Body:
Use event delegation for attachine events to dynamically added elements:

$("body").on('change','.imageupload',function() {
    //CHANGE EVENT CODE HERE
});


问:
filter by text in specifiec property
I have an array of objects, like those

```<code>{ name: "task1", owner: "david", des: "task1 description" },
{ name: "task2", owner: "Smith", des: "task2 description" },
{ name: "task1", owner: "david", des: "task1 description" },
</code>```

also a select and textbox
and a table that shows them all.

i am looking a way to filter, the data in the table.
The user will select a value from drop-down and enter text in the textbox.

Then the table data will be filtered by text matches in selected value (object property) from drop-down.

Example:

choosing "name" from dropdown and write "task" in textbox will return all 3 items in array. text word is contained within all 3 records.

choosing "name" from dropdown and write "task1" in textbox will return record 1 and 3.

textbox value will be required for the filter to happen.

Can it be done with angularjs filter?

https://plnkr.co/edit/Afs7MOIziUOvFWzBY7qf?p=preview

答:
You need to use ng-disabled property on text-box

Working Plunker

Html need to update

```<code><input ng-model="filterdata[filterProperty]" type="text" ng-disabled="!filterProperty" />
</code>```

Title: filter by text in specifiec property

Body:
I have an array of objects, like those

{ name: "task1", owner: "david", des: "task1 description" },
{ name: "task2", owner: "Smith", des: "task2 description" },
{ name: "task1", owner: "david", des: "task1 description" },

also a select and textbox
and a table that shows them all.

i am looking a way to filter, the data in the table.
The user will select a value from drop-down and enter text in the textbox.

Then the table data will be filtered by text matches in selected value (object property) from drop-down.

Example:

choosing "name" from dropdown and write "task" in textbox will return all 3 items in array. text word is contained within all 3 records.

choosing "name" from dropdown and write "task1" in textbox will return record 1 and 3.

textbox value will be required for the filter to happen.

Can it be done with angularjs filter?

https://plnkr.co/edit/Afs7MOIziUOvFWzBY7qf?p=preview

Body:
You need to use ng-disabled property on text-box

Working Plunker

Html need to update

<input ng-model="filterdata[filterProperty]" type="text" ng-disabled="!filterProperty" />


问:
Organize table in SQL Server to remove NULL values and start from same level
I want to format table data in SQL Server.
Currently my table shows data as:-

I want to modify table data to show as:-

Please tell the query I need to make the changes.

答:
If you just want to query the data in that way, then simple aggregation should be enough.

```<code>select code,
    max(val1) as val1,
    max(val2) as val2,
    max(val3) as val3
from your_table
group by code;
</code>```

If you want to modify data in your table i.e. update and delete rows to get the final result, one way is to use MERGE:

```<code>with cte as (
    select t.*,
        row_number() over (partition by code order by code) as seqnum,
        max(val1) over (partition by code) as max_val1,
        max(val2) over (partition by code) as max_val2,
        max(val3) over (partition by code) as max_val3
    from your_table t
)
merge into cte as t
using cte as s
on (
    t.code = s.code
    and t.seqnum = s.seqnum
    and t.seqnum = 1
)
when matched then update set
    t.val1 = s.max_val1,
    t.val2 = s.max_val2,
    t.val3 = s.max_val3
when not matched by source then delete;
</code>```

Demo

Body:
If you just want to query the data in that way, then simple aggregation should be enough.

select code,
    max(val1) as val1,
    max(val2) as val2,
    max(val3) as val3
from your_table
group by code;

If you want to modify data in your table i.e. update and delete rows to get the final result, one way is to use MERGE:

with cte as (
    select t.*,
        row_number() over (partition by code order by code) as seqnum,
        max(val1) over (partition by code) as max_val1,
        max(val2) over (partition by code) as max_val2,
        max(val3) over (partition by code) as max_val3
    from your_table t
)
merge into cte as t
using cte as s
on (
    t.code = s.code
    and t.seqnum = s.seqnum
    and t.seqnum = 1
)
when matched then update set
    t.val1 = s.max_val1,
    t.val2 = s.max_val2,
    t.val3 = s.max_val3
when not matched by source then delete;

Demo


问:
Jcabi Github ExceptionInInitializerError
I am currently working on a Bukkit plugin, and trying to implement to get config files from github. I am trying to use JCabi-Github for this. I got the library implemented and working, but whenever I use it, it creates an error. I tried to use this code:

```<code>Github git = new RtGitHub(user, pass);
</code>```

Which doesn't give any compile-time errors

And following the Javadoc should be just right

But when it runs, it creates a java.lang.ExceptionInInitializerError.

How do I fix this?

答:
Check how you are using your program with JCabi-GitHub.

See issue 1270:

I'm afraid that "compile via eclipse" is what broke the structure of the JAR file.

  Try to package with Maven.

Body:
I am currently working on a Bukkit plugin, and trying to implement to get config files from github. I am trying to use JCabi-Github for this. I got the library implemented and working, but whenever I use it, it creates an error. I tried to use this code:

Github git = new RtGitHub(user, pass);

Which doesn't give any compile-time errors

And following the Javadoc should be just right

But when it runs, it creates a java.lang.ExceptionInInitializerError.

How do I fix this?


问:
Reading CSV file and storing values into an array
I am trying to read a *.csv-file.

The *.csv-file consist of two columns separated by semicolon (";").

I am able to read the *.csv-file using StreamReader and able to separate each line by using the Split() function. I want to store each column into a separate array and then display it.

Is it possible to do that?

答:
I have a library that is doing exactly you need.

Some time ago I had wrote simple and fast enough library for work with CSV files. You can find it by the following link: https://github.com/ukushu/DataExporter/blob/master/Csv.cs

It works with CSV like with 2 dimensions array. Exactly like you need.

As example, in case of you need all of values of 3rd row only you need is to write:

```<code>Csv csv = new Csv();

csv.FileOpen("c:\\file1.csv");

var allValuesOf3rdRow = csv.Rows[2];
</code>```

or to read 2nd cell of 3rd row:

```<code>var value = csv.Rows[2][1];
</code>```

Body:
I have a library that is doing exactly you need.

Some time ago I had wrote simple and fast enough library for work with CSV files. You can find it by the following link: https://github.com/ukushu/DataExporter/blob/master/Csv.cs

It works with CSV like with 2 dimensions array. Exactly like you need.

As example, in case of you need all of values of 3rd row only you need is to write:

Csv csv = new Csv();

csv.FileOpen("c:\\file1.csv");

var allValuesOf3rdRow = csv.Rows[2];

or to read 2nd cell of 3rd row:

var value = csv.Rows[2][1];