问:
Memory leak from repeatedly applying d3 transition
I have an SVG map and an interval that polls for data changes and updates the colors on the map accordingly.  That all works fine unless I use a transition to fade to the new color.  Then the tab slowly eats up more and more memory until it crashes.

I've made a simplified example that shows the same behavior:

```<code>var size = 500;
var num = 25;
var boxSize = size / num;

function color(d) {
    return '#' + Math.random().toString(16).slice(2,8);
}

var svg = d3.select('body')
    .append("svg")
    .attr("width", size)
    .attr("height", size);

var squares = svg.selectAll(".square")
    .data(d3.range(num * num))
  .enter().append("rect")
    .attr("class", "square")
    .attr("width", boxSize)
    .attr("height", boxSize)
    .attr("x", function (d) { return boxSize * (d % num);})
    .attr("y", function (d) { return boxSize * Math.floor(d / num); })
    .style("fill", color);

function shuffleColors() {
    squares.interrupt().transition().duration(500).style("fill", color);
    timer = setTimeout(shuffleColors, 1000);
}

var timer = setTimeout(shuffleColors, 1000);
</code>```

https://plnkr.co/edit/p71QmO

I've tried it in Chromium (49) and Firefox (45) on Linux.  It seems to blow up faster on the former, but it's a problem on both.  In neither does it show up in the memory profiler, but about:memory shows the tab growing.

My understanding from the documentation is that adding a transition to a selection replaces any previous transition by the same name (including for empty name), but my hypothesis is that the functions created to implement the transition aren't actually getting thrown out.  But I haven't managed to get at them to confirm that or work around the issue.

So, a two-part question:

Is that a proper use of d3 transitions, or is there a more correct way to do what I'm going for?

If I'm using the transition properly, how do I get it to stop leaking memory?

EDIT:

Per the comment from Blindman67, I changed it to use setTimeout and be slightly smaller. The original that I'm trying to simulate is smaller and slower, but it takes hours to grow definitively bigger, so I was trying to speed that up.  This version still appears to be growing, at least for me on Chromium.

I got as far as observing that d3_selectionPrototype.transition makes a new d3_transition with an incrementing ID every time, but that's fine if the old one gets garbage-collected. And I still can't point to whether or why it's being retained.

答:
I'm fairly certain it has to do this piece right here:

```<code>function shuffleColors() {
    squares.interrupt().transition().duration(500).style("fill", color);
    timer = setTimeout(shuffleColors, 1000);
}

var timer = setTimeout(shuffleColors, 1000);
</code>```

Every time you call the function shuffleColors(), it calls itself again, essentially creating a recursion loop without a base case. The reason it doesn't blow up immediately is that every call of the function it delayed 1000ms, however, I think it takes longer for the squares.interrupt().transition().duration(500).style("fill", color); to finish than it is for setTimeout() to be called. So even though you call it every 1000ms, it could be stacking up in some fashion since some color changes may require more time to process.

Though it technically shouldn't do that, knowing how asynchronous JavaScript is, it may have a role. I would suggest doing this instead and reporting back the results:

```<code>function shuffleColors() {
    squares.interrupt().transition().duration(500).style("fill", color);
}

var timer = setInterval(shuffleColors, 1000);
</code>```

You can also call clearInterval(timer) if you need to at any point. setInterval() was created for the very reason you implemented setTimeout().

Edit: This may not work completely as you may still have you wait for the color change to finish, however, it would at least be a cleaner approach. You may be able to implement some sort of wait() function to wait for the color change to complete.

Though vector (SVG) images are lightweight, the amount of processing it requires to constantly change colors or something like that is enormous compared to decoding a JPEG image.

You might find better results if you make the original image size much smaller and then expand it to your resolution. You could make a 100x100 canvas SVG and expand it to 2000x2000 or something, so it doesn't have to draw such a large image.

Body:
I have an SVG map and an interval that polls for data changes and updates the colors on the map accordingly.  That all works fine unless I use a transition to fade to the new color.  Then the tab slowly eats up more and more memory until it crashes.

I've made a simplified example that shows the same behavior:

var size = 500;
var num = 25;
var boxSize = size / num;

function color(d) {
    return '#' + Math.random().toString(16).slice(2,8);
}

var svg = d3.select('body')
    .append("svg")
    .attr("width", size)
    .attr("height", size);

var squares = svg.selectAll(".square")
    .data(d3.range(num * num))
  .enter().append("rect")
    .attr("class", "square")
    .attr("width", boxSize)
    .attr("height", boxSize)
    .attr("x", function (d) { return boxSize * (d % num);})
    .attr("y", function (d) { return boxSize * Math.floor(d / num); })
    .style("fill", color);

function shuffleColors() {
    squares.interrupt().transition().duration(500).style("fill", color);
    timer = setTimeout(shuffleColors, 1000);
}

var timer = setTimeout(shuffleColors, 1000);

https://plnkr.co/edit/p71QmO

I've tried it in Chromium (49) and Firefox (45) on Linux.  It seems to blow up faster on the former, but it's a problem on both.  In neither does it show up in the memory profiler, but about:memory shows the tab growing.

My understanding from the documentation is that adding a transition to a selection replaces any previous transition by the same name (including for empty name), but my hypothesis is that the functions created to implement the transition aren't actually getting thrown out.  But I haven't managed to get at them to confirm that or work around the issue.

So, a two-part question:

Is that a proper use of d3 transitions, or is there a more correct way to do what I'm going for?

If I'm using the transition properly, how do I get it to stop leaking memory?

EDIT:

Per the comment from Blindman67, I changed it to use setTimeout and be slightly smaller. The original that I'm trying to simulate is smaller and slower, but it takes hours to grow definitively bigger, so I was trying to speed that up.  This version still appears to be growing, at least for me on Chromium.

I got as far as observing that d3_selectionPrototype.transition makes a new d3_transition with an incrementing ID every time, but that's fine if the old one gets garbage-collected. And I still can't point to whether or why it's being retained.

Body:
I'm fairly certain it has to do this piece right here:

function shuffleColors() {
    squares.interrupt().transition().duration(500).style("fill", color);
    timer = setTimeout(shuffleColors, 1000);
}

var timer = setTimeout(shuffleColors, 1000);

Every time you call the function shuffleColors(), it calls itself again, essentially creating a recursion loop without a base case. The reason it doesn't blow up immediately is that every call of the function it delayed 1000ms, however, I think it takes longer for the squares.interrupt().transition().duration(500).style("fill", color); to finish than it is for setTimeout() to be called. So even though you call it every 1000ms, it could be stacking up in some fashion since some color changes may require more time to process.

Though it technically shouldn't do that, knowing how asynchronous JavaScript is, it may have a role. I would suggest doing this instead and reporting back the results:

function shuffleColors() {
    squares.interrupt().transition().duration(500).style("fill", color);
}

var timer = setInterval(shuffleColors, 1000);

You can also call clearInterval(timer) if you need to at any point. setInterval() was created for the very reason you implemented setTimeout().

Edit: This may not work completely as you may still have you wait for the color change to finish, however, it would at least be a cleaner approach. You may be able to implement some sort of wait() function to wait for the color change to complete.

Though vector (SVG) images are lightweight, the amount of processing it requires to constantly change colors or something like that is enormous compared to decoding a JPEG image.

You might find better results if you make the original image size much smaller and then expand it to your resolution. You could make a 100x100 canvas SVG and expand it to 2000x2000 or something, so it doesn't have to draw such a large image.


来源: stackexchange

问:
How do I avoid unschedulable pods when running an autoscale-enabled Google Container/Kubernetes Engine cluster?
I'm running into an issue where I seem to max out my Container Engine (Kubernetes Engine) cluster at 9 nodes (or 9 vCPUs). For context, I'm trying to run around 50 or so web scrapers as Kubernetes Cron Jobs. Here is the gcloud command I am using to create the cluster in the us-east1-c zone:

```<code>gcloud beta container clusters create my-example-cluster \
  --cluster-version=1.8.1-gke.1 \
  --machine-type=f1-micro \
  --enable-autoscaling \
  --min-nodes=1 \
  --max-nodes=60
</code>```

When I checked out IAM & Admin > Quotas, it looked like I was possibly maxing out on in-use IP addresses (max=8).

After launching all the scrapers, I'm ending up around 35 pods that are unschedulable (seemingly because I can't exceed 9 nodes?).

Has anyone run into a similar situation and come up with a solution? Is there a way, perhaps via Kubernetes config, to not count against IP address usage since these nodes do not need to be accessible externally (if that's even the issue)? Also open to other setups if anyone has recommendations.

Thanks for all the help!

P.S. I do have billing enabled

答:
I received some help on this issue from the Google Cloud Platform Community Slack. It turns out I was hitting the In-use IP addresses quota; however, I didn't realize you could request increased quotas.

I was able to increase quotas by:

Navigating to Menu > IAM & admin > Quotas in the Google Cloud Platform console for my project

Selecting/checking the services in the region I was using (e.g., In-use IP addresses in us-west1)

Click EDIT QUOTAS button above the table of services

Input/verify contact information

Comply with GCP support when they reach out to you

So, basically an oversight on my end but maybe it will help somebody else who didn't notice or wasn't aware of that option.

ContentLicense: CC BY-SA 3.0

Body:
I'm running into an issue where I seem to max out my Container Engine (Kubernetes Engine) cluster at 9 nodes (or 9 vCPUs). For context, I'm trying to run around 50 or so web scrapers as Kubernetes Cron Jobs. Here is the gcloud command I am using to create the cluster in the us-east1-c zone:

gcloud beta container clusters create my-example-cluster \
  --cluster-version=1.8.1-gke.1 \
  --machine-type=f1-micro \
  --enable-autoscaling \
  --min-nodes=1 \
  --max-nodes=60

When I checked out IAM & Admin > Quotas, it looked like I was possibly maxing out on in-use IP addresses (max=8).

After launching all the scrapers, I'm ending up around 35 pods that are unschedulable (seemingly because I can't exceed 9 nodes?).

Has anyone run into a similar situation and come up with a solution? Is there a way, perhaps via Kubernetes config, to not count against IP address usage since these nodes do not need to be accessible externally (if that's even the issue)? Also open to other setups if anyone has recommendations.

Thanks for all the help!

P.S. I do have billing enabled


问:
Concurrency issues with QThreads. Threads receiving the same signal are blocking each other
So I'm working on a program that processes video in real-time and I'm having some trouble with threads "blocking" each other.

My system is pretty much set up like this:

```<code>         DataSourceThread
             /      \
            /        \
           /          \
     Receiver       Receiver
         /              \
        /                \
       /                  \
 Processor1            Processor2
</code>```

(All these classes are extending QThread.)

So DataSourceThread fetches frames from a videostream and emits a signal containing the frame to the receivers. Connection type: Qt::DirectConnection

The receivers basically receive the the frames sent out by DataSourceThread and if the Processor is done processing the previous frame, it will emit a signal containing the frame to the Processor. Connection type: Qt::QueuedConnection.
If the processor is not done processing the previous frame, it will just return without emitting a signal (skipping frames).

To test if this works, all I've done is have Processor1 just print out a message when it receives a frame and Processor2 does QThread::sleep(3); and print out a message.

(The receivers will also do a deep copy of the frame before passing it on to the processors.)

Expected result:

Processor1 should be constantly printing messages.
Processor2 should be printing a message every 3 seconds.

The problem:

Both processors print their messages at the same time (every 3 seconds).
Processor1 waits until Processor2 is done before printing its message.
So the output is pretty much like this:

```<code>"Message from processor1"
"Message from processor2"
"Message from processor1"
"Message from processor2"
"Message from processor1"
"Message from processor2"
</code>```

and so on.

I'm running out of ideas here,
so any help would be greatly appreciated!

EDIT:
Here's some of the code:

main.cpp:

```<code>int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    DataSourceThread dataSourceThread;
    dataSourceThread.start();

    GUIThread *guiProcessor = new GUIThread();
    FrameReceiver *guiReceiver = new FrameReceiver(guiProcessor, 0);

    QObject::connect(
        &dataSourceThread, SIGNAL(frameReceived(Frame*)),
        guiReceiver, SLOT(receive(Frame*)),
        Qt::DirectConnection
    );

    DetectorThread *detectorProcessor = new DetectorThread();
    FrameReceiver *detectorReceiver = new FrameReceiver(detectorProcessor, 0);

    QObject::connect(
        &dataSourceThread, SIGNAL(frameReceived(Frame*)),
        detectorReceiver, SLOT(receive(Frame*)),
        Qt::DirectConnection
    );

    return app.exec();
}
</code>```

From DataSourceThread.cpp:

```<code>void DataSourceThread::run()
{
    ... stuff ...

    while (true) {
        image = cvQueryFrame(capture);

        if (!image) {
            qDebug() << QString("Could not capture frame");
            continue;
        }

        cvReleaseImage(&temp_image);
        temp_image = cvCreateImage(cvSize(640, 480), image->depth, 3);

        cvResize(image, temp_image, 1);

        frame->lock();
        frame->setImage(temp_image);
        frame->unlock();

        emit frameReceived(frame);

        msleep(1);
    }
}
</code>```

FrameReceiver.cpp:

```<code>FrameReceiver::FrameReceiver(FrameProcessor* processor, QObject *parent) : QThread(parent) {
    m_ready = true;

    m_processor = processor;
    m_processor->start();

    QObject::connect(
        (QObject*)this, SIGNAL(frameReceived(Frame*)),
        m_processor, SLOT(receive(Frame*)),
        Qt::QueuedConnection
    );

    QObject::connect(
        m_processor, SIGNAL(ready()),
        (QObject*)this, SLOT(processCompleted()),
        Qt::DirectConnection
    ); }

void FrameReceiver::processCompleted() {
    m_ready = true; }

void FrameReceiver::receive(Frame *frame) {
    if (m_ready == true) {
        m_ready = false;
        frame->lock();
        Frame *f = new Frame(*frame);
        frame->unlock();
        emit frameReceived(f);
    } else {
        // SKIPPED THIS FRAME
    }
}
</code>```

GUIThread.cpp: (Processor1)

```<code>GUIThread::GUIThread(QObject *parent) : FrameProcessor(parent)
{
    m_frame = new Frame();
}

void GUIThread::setFrame(Frame *frame)
{
    qDebug() << QString("Guithread received frame");
}
</code>```

FrameProcessor.cpp

```<code>// (The processors extend this class)
void FrameProcessor::receive(Frame *frame)
 {
     setFrame(frame);
     delete frame;
     emit ready();
 }
</code>```

DetectorThread (Processor2) does the same as guithread, but with a 3 sec sleep in setFrame.

答:
I think part of the problem is that all of your QObjects are owned by the main application thread. This means they all share a one event loop for delivering asynchronous signals, effectively serializing your whole processing chain.

I think the proper way to set this up would be something like:

```<code>GUIProcessor *guiProcessor = new GUIProcessor();
QThread guiProcessorThread;
guiProcessor.moveToThread(&guiProcessorThread);

FrameReceiver *guiReceiver = new FrameReceiver(guiProcessor, 0);
QThread guiReceiverThread;
guiReceiver.moveToThread(&guiReceiverThread);

guiProcessorThread.start();
guiReceiverThread.start();
</code>```

If you do it this way I would suggest not using DirectConnection between threads, but rather BlockingQueuedConnection if you want to ensure that the current frame is processed before you capture the next one.

See this: http://labs.qt.nokia.com/2010/06/17/youre-doing-it-wrong/

And this: http://labs.qt.nokia.com/2006/12/04/threading-without-the-headache/

Hope this helps!

EDIT: To be clear, with my suggestion your classes would inherit QObject instead of QThread.

ContentLicense: CC BY-SA 2.5

Body:
So I'm working on a program that processes video in real-time and I'm having some trouble with threads "blocking" each other.

My system is pretty much set up like this:

         DataSourceThread
             /      \
            /        \
           /          \
     Receiver       Receiver
         /              \
        /                \
       /                  \
 Processor1            Processor2

(All these classes are extending QThread.)

So DataSourceThread fetches frames from a videostream and emits a signal containing the frame to the receivers. Connection type: Qt::DirectConnection

The receivers basically receive the the frames sent out by DataSourceThread and if the Processor is done processing the previous frame, it will emit a signal containing the frame to the Processor. Connection type: Qt::QueuedConnection.
If the processor is not done processing the previous frame, it will just return without emitting a signal (skipping frames).

To test if this works, all I've done is have Processor1 just print out a message when it receives a frame and Processor2 does QThread::sleep(3); and print out a message.

(The receivers will also do a deep copy of the frame before passing it on to the processors.)

Expected result:

Processor1 should be constantly printing messages.
Processor2 should be printing a message every 3 seconds.

The problem:

Both processors print their messages at the same time (every 3 seconds).
Processor1 waits until Processor2 is done before printing its message.
So the output is pretty much like this:

"Message from processor1"
"Message from processor2"
"Message from processor1"
"Message from processor2"
"Message from processor1"
"Message from processor2"

and so on.

I'm running out of ideas here,
so any help would be greatly appreciated!

EDIT:
Here's some of the code:

main.cpp:

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    DataSourceThread dataSourceThread;
    dataSourceThread.start();

    GUIThread *guiProcessor = new GUIThread();
    FrameReceiver *guiReceiver = new FrameReceiver(guiProcessor, 0);

    QObject::connect(
        &dataSourceThread, SIGNAL(frameReceived(Frame*)),
        guiReceiver, SLOT(receive(Frame*)),
        Qt::DirectConnection
    );

    DetectorThread *detectorProcessor = new DetectorThread();
    FrameReceiver *detectorReceiver = new FrameReceiver(detectorProcessor, 0);

    QObject::connect(
        &dataSourceThread, SIGNAL(frameReceived(Frame*)),
        detectorReceiver, SLOT(receive(Frame*)),
        Qt::DirectConnection
    );

    return app.exec();
}

From DataSourceThread.cpp:

void DataSourceThread::run()
{
    ... stuff ...

    while (true) {
        image = cvQueryFrame(capture);

        if (!image) {
            qDebug() << QString("Could not capture frame");
            continue;
        }

        cvReleaseImage(&temp_image);
        temp_image = cvCreateImage(cvSize(640, 480), image->depth, 3);

        cvResize(image, temp_image, 1);

        frame->lock();
        frame->setImage(temp_image);
        frame->unlock();

        emit frameReceived(frame);

        msleep(1);
    }
}

FrameReceiver.cpp:

FrameReceiver::FrameReceiver(FrameProcessor* processor, QObject *parent) : QThread(parent) {
    m_ready = true;

    m_processor = processor;
    m_processor->start();

    QObject::connect(
        (QObject*)this, SIGNAL(frameReceived(Frame*)),
        m_processor, SLOT(receive(Frame*)),
        Qt::QueuedConnection
    );

    QObject::connect(
        m_processor, SIGNAL(ready()),
        (QObject*)this, SLOT(processCompleted()),
        Qt::DirectConnection
    ); }

void FrameReceiver::processCompleted() {
    m_ready = true; }

void FrameReceiver::receive(Frame *frame) {
    if (m_ready == true) {
        m_ready = false;
        frame->lock();
        Frame *f = new Frame(*frame);
        frame->unlock();
        emit frameReceived(f);
    } else {
        // SKIPPED THIS FRAME
    }
}

GUIThread.cpp: (Processor1)

GUIThread::GUIThread(QObject *parent) : FrameProcessor(parent)
{
    m_frame = new Frame();
}

void GUIThread::setFrame(Frame *frame)
{
    qDebug() << QString("Guithread received frame");
}

FrameProcessor.cpp

// (The processors extend this class)
void FrameProcessor::receive(Frame *frame)
 {
     setFrame(frame);
     delete frame;
     emit ready();
 }

DetectorThread (Processor2) does the same as guithread, but with a 3 sec sleep in setFrame.

Body:
I think part of the problem is that all of your QObjects are owned by the main application thread. This means they all share a one event loop for delivering asynchronous signals, effectively serializing your whole processing chain.

I think the proper way to set this up would be something like:

GUIProcessor *guiProcessor = new GUIProcessor();
QThread guiProcessorThread;
guiProcessor.moveToThread(&guiProcessorThread);

FrameReceiver *guiReceiver = new FrameReceiver(guiProcessor, 0);
QThread guiReceiverThread;
guiReceiver.moveToThread(&guiReceiverThread);

guiProcessorThread.start();
guiReceiverThread.start();

If you do it this way I would suggest not using DirectConnection between threads, but rather BlockingQueuedConnection if you want to ensure that the current frame is processed before you capture the next one.

See this: http://labs.qt.nokia.com/2010/06/17/youre-doing-it-wrong/

And this: http://labs.qt.nokia.com/2006/12/04/threading-without-the-headache/

Hope this helps!

EDIT: To be clear, with my suggestion your classes would inherit QObject instead of QThread.


问:
Fast row deletion in numpy
I am working with a big numpy matrix (approximately 75k rows of 2 integers each) from which I have to delete some rows. I would like to know if there is a fast way to delete a row without regenerating the whole array i.e. is there a function the change just the "mask" (or whatever is called) of the matrix, without effectively delete the row in memory? I could then regenerate a clean matrix after I delete all the proper rows.</p>

答:
Although masked arrays are a thing, I would probably do this with a separate boolean mask, e.g.

```<code>big_array = np.random.rand(75000, 2)

rows_to_delete = np.random.randint(0, 75000, 500)
mask = np.ones(75000, dtype=bool)
mask[rows_to_delete] = False

output = big_array[mask]
print(output.shape)
# (74503, 2)
</code>```

If you just have a list of indices to delete, the np.delete function is also an option:

```<code>output = np.delete(big_array, rows_to_delete, axis=0)
print(output.shape)
# (74503, 2)
</code>```

Note that in either of these options, it is a new array that is returned, not a view of the original array.

Title: Fast row deletion in numpy

Body:
Although masked arrays are a thing, I would probably do this with a separate boolean mask, e.g.

big_array = np.random.rand(75000, 2)

rows_to_delete = np.random.randint(0, 75000, 500)
mask = np.ones(75000, dtype=bool)
mask[rows_to_delete] = False

output = big_array[mask]
print(output.shape)
# (74503, 2)

If you just have a list of indices to delete, the np.delete function is also an option:

output = np.delete(big_array, rows_to_delete, axis=0)
print(output.shape)
# (74503, 2)

Note that in either of these options, it is a new array that is returned, not a view of the original array.


问:
Why this loop is not working?
```<code>while(a!=1&&c!=1)
{
    r=rand()%2;
    if(r==0)
    {
        cout<<"Cruz"<<endl;
        if(a==1)
        {
            c=0;
        }
        c++;
    }
    else if(r==1)
    {
        if(a>1)
        {
            a=0;
        }
        cout<<"Cara"<<endl;
        a++;
    }
    b++;
}
</code>```

I don't know why but this loop always exits when one of the two conditions is false... and I need when both are false.
Does anyone know why is this happening?

答: pretty sure you want an || instead of a && because you want it to continue if either of them are true statements. (alternatively, and this would be probably more coherent, you could do:!(a==1||c==1))

Title: Why this loop is not working?

Body:
while(a!=1&&c!=1)
{
    r=rand()%2;
    if(r==0)
    {
        cout<<"Cruz"<<endl;
        if(a==1)
        {
            c=0;
        }
        c++;
    }
    else if(r==1)
    {
        if(a>1)
        {
            a=0;
        }
        cout<<"Cara"<<endl;
        a++;
    }
    b++;
}

I don't know why but this loop always exits when one of the two conditions is false... and I need when both are false.
Does anyone know why is this happening?


问:
User Check-In History in Visual Studio 2012 / 2013
In Visual Studio 2010, I was able to view the check-in history of a particular user from
Team Explorer -> Team Project -> Team Members -> Right-click on a user name -> Show Check-in History.

I just can't find such option in Visual Studio 2012/2013 after the drastic Team Explorer UI re-design.

答: In visual studio Professional 2015, Team Explorer->Team Foundation Server (TFS),double click in the TFS server link then provide user Name and Password, click OK -> click Code  on top -> click Changesets-> provide author Name.</p>


问:
Library for displaying image sets on an iPad
I'm looking for some cool libraries out there to display a bunch of images in my iPad application.

I think they are already out there, and I don't have to start from scratch, but I can't find some good ones.

答: I would simply create a web page with all the images, and then display it using UIWebView.</p>


问:
MySQL Query to list users who have recently messaged
I'm building a chat application and I want to list the users who have recently messaged, with their id, name, pic, and last message (id, timestamp, content)

My two tables look like this:

```<code>users:
------
id
name
pic

messages:
---------
id
content
timestamp
user_id (foreign key of user's id)
</code>```

Here is the query that I've tried:

```<code>SELECT U.*,
    MAX(M.id) as lastmessage_id
FROM users U, messages M
WHERE M.user_id=U.id
GROUP BY user_id
ORDER BY lastmessage_id DESC
</code>```

It will list the users who have messaged recently but it doesn't contain the last message's 'content'

Current output:

```<code>id, name, pic, lastmessage_id
</code>```

Required output:

```<code>id, name, pic, lastmessage_id, lastmessage_content, lastmessage_timestamp
</code>```

答:
In your script, you display all the columns in users table, but just id from messages table. Change your script to below one.</p>

```<code>SELECT U.*,
    MAX(M.id) as lastmessage_id , M.content, M.timestamp
FROM users U, messages M
WHERE M.user_id=U.id
GROUP BY user_id
ORDER BY lastmessage_id DESC
</code>```

Body:
I'm building a chat application and I want to list the users who have recently messaged, with their id, name, pic, and last message (id, timestamp, content)

My two tables look like this:

users:
------
id
name
pic

messages:
---------
id
content
timestamp
user_id (foreign key of user's id)

Here is the query that I've tried:

SELECT U.*,
    MAX(M.id) as lastmessage_id
FROM users U, messages M
WHERE M.user_id=U.id
GROUP BY user_id
ORDER BY lastmessage_id DESC

It will list the users who have messaged recently but it doesn't contain the last message's 'content'

Current output:

id, name, pic, lastmessage_id

Required output:

id, name, pic, lastmessage_id, lastmessage_content, lastmessage_timestamp

Body:
In your script, you display all the columns in users table, but just id from messages table. Change your script to below one.

SELECT U.*,
    MAX(M.id) as lastmessage_id , M.content, M.timestamp
FROM users U, messages M
WHERE M.user_id=U.id
GROUP BY user_id
ORDER BY lastmessage_id DESC


问:
Swift 4 function returning 0 for multiple return values
I have been searching around but couldn't find a solution. can someone please let me know what I am doing wrong.
 here is my function code: in my database I have hour=5 as Int and Minute=45 as Int
but when I print, the values of the function prints 0,0</p>

```<code>var docRefF : DocumentReference!

func getTime()-> (Int, Int){
    var FHour = Int()
    var FMinute = Int()

    docRefF = Firestore.firestore().document("sampleTime/worktime")
    dataListener =  docRefF.addSnapshotListener { (docSnapshot, error) in
        guard let docSnapshot = docSnapshot, docSnapshot.exists else { return }

        let data = docSnapshot.data()
        let Hour:Int = data["Hour"]! as! Int
        let Minute: Int = data["Minute"]! as! Int

        FHour = Hour
        FMinute = Minute
    }

    return (FHour, FMinute)
}
let time = getTime()
print("\(time.0),\(time.1)" )
 //printed 0,0
</code>```

答:
Clearly its issue of asynchronous execution. Use * function with Closure*  Instead of function with returning value.

Please refer following code

```<code>var docRefF : DocumentReference!
func getTime(_ then:(_ first:Int, _ second:Int)->()){
    var FHour = Int()
    var FMinute = Int()

    docRefF = Firestore.firestore().document("sampleTime/worktime")
    dataListener =  docRefF.addSnapshotListener { (docSnapshot, error) in
     guard let docSnapshot = docSnapshot, docSnapshot.exists else { return }
   let data = docSnapshot.data()
    let Hour:Int = data["Hour"]! as! Int
    let Minute: Int = data["Minute"]! as! Int

        FHour = Hour
        FMinute = Minute

    //TODO:- Use other firebase related task same as your code, so that uncomment other lines same as your origional

    then(FHour, FMinute) // This is closure call back line

     }
   }

   //Calling your function
    getTime { (first, second) in

    print(first,second)

    }
</code>```

Body:
I have been searching around but couldn't find a solution. can someone please let me know what I am doing wrong.
 here is my function code: in my database I have hour=5 as Int and Minute=45 as Int
but when I print, the values of the function prints 0,0

var docRefF : DocumentReference!

func getTime()-> (Int, Int){
    var FHour = Int()
    var FMinute = Int()

    docRefF = Firestore.firestore().document("sampleTime/worktime")
    dataListener =  docRefF.addSnapshotListener { (docSnapshot, error) in
        guard let docSnapshot = docSnapshot, docSnapshot.exists else { return }

        let data = docSnapshot.data()
        let Hour:Int = data["Hour"]! as! Int
        let Minute: Int = data["Minute"]! as! Int

        FHour = Hour
        FMinute = Minute
    }

    return (FHour, FMinute)
}
let time = getTime()
print("\(time.0),\(time.1)" )
 //printed 0,0

Body:
Clearly its issue of asynchronous execution. Use * function with Closure*  Instead of function with returning value.

Please refer following code

var docRefF : DocumentReference!
func getTime(_ then:(_ first:Int, _ second:Int)->()){
    var FHour = Int()
    var FMinute = Int()

    docRefF = Firestore.firestore().document("sampleTime/worktime")
    dataListener =  docRefF.addSnapshotListener { (docSnapshot, error) in
     guard let docSnapshot = docSnapshot, docSnapshot.exists else { return }
   let data = docSnapshot.data()
    let Hour:Int = data["Hour"]! as! Int
    let Minute: Int = data["Minute"]! as! Int

        FHour = Hour
        FMinute = Minute

    //TODO:- Use other firebase related task same as your code, so that uncomment other lines same as your origional

    then(FHour, FMinute) // This is closure call back line

     }
   }

   //Calling your function
    getTime { (first, second) in

    print(first,second)

    }


问:
Xamarin.GooglePlayServices.Ads. broke my project
Xamarin.GooglePlayServices.Ads. v10.2.1 My project broke, and this message appears

Severity  Code    Description Project File    Line    Suppression State
  Error   CS0012  The type 'FragmentActivity' is defined in an assembly that is not referenced. You must add a reference to assembly 'Xamarin.Android.Support.v4, Version=1.0.0.0, Culture=neutral, PublicKeyToken=71f3e3261ac778b5'. App16   C:\Users\jon\Documents\New folder\App16 - Copy (8)\App16\MainActivity.cs    11  Active

How to fix this?

Target Framwork 8.0,

Minimum 4.4,

Target Android Vesion 8.0

I found the problem, it was conflict between the CrossLight RecyclerView package with V4. I unplugged CrossLight and reinstalled the V7 package. Everything is OK

答:
You need to update your Android Support Libraries. Your Xamarin version must also be updated. Try it. Let me know if it works.

Lastly, put your projects as close to your C drive as possible.


答:
Try using a JOIN:</p>

```<code>SELECT U.*, MAX(M.id) AS lastmessage_id
FROM users U

JOIN MESSAGES M ON U.id = M.user_id

GROUP BY user_id
ORDER BY lastmessage_id DESC
</code>```

Title: MySQL Query to list users who have recently messaged

Body:
Try using a JOIN:

SELECT U.*, MAX(M.id) AS lastmessage_id
FROM users U

JOIN MESSAGES M ON U.id = M.user_id

GROUP BY user_id
ORDER BY lastmessage_id DESC


问:
Passing values to MySQL IN operation in PDO prepared statement?
I have a form field that is returning a comma-delimited string that I want to pass in to a PHP PDO MySQL query IN operation, but the IN operation requires that the values be comma-delimited (as opposed to my string of delimited values).

How do I do this?

```<code>$values = $_POST['values']; # '10,5,4,3' (string)
$query = "SELECT * FROM table WHERE id IN (:values)";
$data = array( ':values' => $values );
</code>```

答:
The trick is to recognize that $values is a bunch of individual values, and set up your query with this in mind. This is easier to do if you use ? placeholders instead of named placeholders. For example, you could do something like the following:

```<code>$values = explode(',', $_POST['values']); //array(10,5,4,3)
$placeholder_string = implode(',', array_fill(0, count($values), '?')); // string '?,?,?,?'
$query = "SELECT * FROM table WHERE id IN ($placeholder_string)";

$statement = $db->prepare($query);
$statement->execute($values);
</code>```

Body:
I have a form field that is returning a comma-delimited string that I want to pass in to a PHP PDO MySQL query IN operation, but the IN operation requires that the values be comma-delimited (as opposed to my string of delimited values).

How do I do this?

$values = $_POST['values']; # '10,5,4,3' (string)
$query = "SELECT * FROM table WHERE id IN (:values)";
$data = array( ':values' => $values );

Body:
The trick is to recognize that $values is a bunch of individual values, and set up your query with this in mind. This is easier to do if you use ? placeholders instead of named placeholders. For example, you could do something like the following:

$values = explode(',', $_POST['values']); //array(10,5,4,3)
$placeholder_string = implode(',', array_fill(0, count($values), '?')); // string '?,?,?,?'
$query = "SELECT * FROM table WHERE id IN ($placeholder_string)";

$statement = $db->prepare($query);
$statement->execute($values);


问:
Tensorflow- ImportError: libcublas.so.8.0: cannot open shared object file: No such file or directory
I'm trying to run Tensorflow-gpu.

I installed Cuda-9.0 and cuDNN v7.0.3. I tested both(as said in their guides) and they were working fine.

Then I installed Tensorflow-gpu using pip3(I use python3) and it gave me this error upon import:

```<code>Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "/usr/lib/python3.5/imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "/usr/lib/python3.5/imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: libcublas.so.8.0: cannot open shared object file: No such file or directory

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/__init__.py", line 24, in <module>
    from tensorflow.python import *
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow.py", line 72, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "/usr/lib/python3.5/imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "/usr/lib/python3.5/imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: libcublas.so.8.0: cannot open shared object file: No such file or directory

Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/install_sources#common_installation_problems

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.
</code>```

There are some similar questions I found, but all are for some or the other previous version of Cuda (mostly 8.0) and I'm not sure whether they'll work. I also tried some of them, like setting the LD_LIBRARY_PATH but nothing worked. I also tried the link in the error itself but that is also a solution for cuda 8.0

答:
Currently, the binary installable versions of TF-GPU require CUDA 8. This will probably change in the future, but for those binaries, you can't satisfy the requirement with CUDA 9.

If you really want to use CUDA 9/CUDNN 7, you will need to build TF from sources. Otherwise install CUDA 8 and point TF at that. CUDA 8 can be installed alongside CUDA 9 and you don't need to modify the driver; the CUDA 9 GPU driver will work with CUDA 8 install.

You can see more details in the answer here:
https://devtalk.nvidia.com/default/topic/1026198/cuda-9-0-importerror-libcublas-so-8-0/

I hope this helps :D

Body:
I'm trying to run Tensorflow-gpu.

I installed Cuda-9.0 and cuDNN v7.0.3. I tested both(as said in their guides) and they were working fine.

Then I installed Tensorflow-gpu using pip3(I use python3) and it gave me this error upon import:

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "/usr/lib/python3.5/imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "/usr/lib/python3.5/imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: libcublas.so.8.0: cannot open shared object file: No such file or directory

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/__init__.py", line 24, in <module>
    from tensorflow.python import *
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow.py", line 72, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "/usr/lib/python3.5/imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "/usr/lib/python3.5/imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: libcublas.so.8.0: cannot open shared object file: No such file or directory

Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/install_sources#common_installation_problems

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.

There are some similar questions I found, but all are for some or the other previous version of Cuda (mostly 8.0) and I'm not sure whether they'll work. I also tried some of them, like setting the LD_LIBRARY_PATH but nothing worked. I also tried the link in the error itself but that is also a solution for cuda 8.0


问:
/usr/include/boost/filesystem/path.hpp:307: undefined reference to `boost::filesystem::path::operator
I have some code, when I compile it, I got the following errors, and I don't know how to solve it. I have tried to add -L/usr/lib/x86_64-linux-gnu, -lboost_system and -lboost_filesystem, but I still got the same errors. I don't know how to fix this problem now, if anybody could help?

Agent.o: In function `boost::filesystem::path::append(char const*, std::codecvt<wchar_t, char, __mbstate_t> const&)':
/usr/include/boost/filesystem/path.hpp:307: undefined reference to `boost::filesystem::path::operator/=(char const*)'
Agent.o: In function `boost::filesystem::exists(boost::filesystem::path const&)':
/usr/include/boost/filesystem/operations.hpp:289: undefined reference to `boost::filesystem::detail::status(boost::filesystem::path const&, boost::system::error_code*)'
Agent.o: In function `boost::filesystem::create_directories(boost::filesystem::path const&)':
/usr/include/boost/filesystem/operations.hpp:399: undefined reference to `boost::filesystem::detail::create_directories(boost::filesystem::path const&, boost::system::error_code*)'
Agent.o: In function `boost::enable_if<boost::filesystem::path_traits::is_pathable<boost::decay<char [256]>::type>, boost::filesystem::path&>::type boost::filesystem::path::operator/=<char [256]>(char const (&) [256])':
/usr/include/boost/filesystem/path.hpp:302: undefined reference to `boost::filesystem::path::codecvt()'
collect2: error: ld returned 1 exit status
make: *** [player] Error 1
```

<p>The related code are as following</p>

```bool Agent::openTupleLog()
{
 std::string dir="~/Experiments/Nov/";
 // create the log directory & file path string

try
{
    boost::filesystem::path kaway_log( dir
#if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION == 2
#  ifndef BOOST_FILESYSTEM_NO_DEPRECATED
                                       , &boost::filesystem::native
#  endif
#endif
                                       );
    if ( ! boost::filesystem::exists( kaway_log )
         && ! boost::filesystem::create_directories( kaway_log ) )
    {
        std::cerr << __FILE__ << ": " << __LINE__
                  << ": can't create log directory '"
                  << kaway_log.BOOST_FS_DIRECTORY_STRING() << "'" << std::endl;
        return false;
    }

    kaway_log /= tuplesFilename;

   M_kaway_log_name = kaway_log.BOOST_FS_FILE_STRING();
}
catch ( std::exception & e )
{
    std::cerr << __FILE__ << ": " << __LINE__
              << " Exception caught! " << e.what()
              << "\nCould not create log directory '"
              << dir
              << "'" << std::endl;
    return false;
}

// open the output file stream
M_kaway_log.open( M_kaway_log_name.c_str() );

if ( ! M_kaway_log.is_open() )
{
    std::cerr << __FILE__ << ": " << __LINE__
              << ": can't open log_file " << M_kaway_log_name
              << std::endl;
    return false;
}

return true;
```

}

答:
Problem solved.

I asked a friend, he told me to add /usr/lib/x86_64-linux-gnu/libboost_filesystem.a -lboost_filesystem -lboost_system at the end of the command, then it works. He said:

The order of putting those flags are dependent, and thus I have to move the .a to very end. Then it ask for boost_system and thus I appended -lboost_system for its pleasure.

And note that it's libboost_filesystem.a, not libboost_filesystem.so

Body:
I have some code, when I compile it, I got the following errors, and I don't know how to solve it. I have tried to add -L/usr/lib/x86_64-linux-gnu, -lboost_system and -lboost_filesystem, but I still got the same errors. I don't know how to fix this problem now, if anybody could help?

Agent.o: In function `boost::filesystem::path::append(char const*, std::codecvt<wchar_t, char, __mbstate_t> const&)':
/usr/include/boost/filesystem/path.hpp:307: undefined reference to `boost::filesystem::path::operator/=(char const*)'
Agent.o: In function `boost::filesystem::exists(boost::filesystem::path const&)':
/usr/include/boost/filesystem/operations.hpp:289: undefined reference to `boost::filesystem::detail::status(boost::filesystem::path const&, boost::system::error_code*)'
Agent.o: In function `boost::filesystem::create_directories(boost::filesystem::path const&)':
/usr/include/boost/filesystem/operations.hpp:399: undefined reference to `boost::filesystem::detail::create_directories(boost::filesystem::path const&, boost::system::error_code*)'
Agent.o: In function `boost::enable_if<boost::filesystem::path_traits::is_pathable<boost::decay<char [256]>::type>, boost::filesystem::path&>::type boost::filesystem::path::operator/=<char [256]>(char const (&) [256])':
/usr/include/boost/filesystem/path.hpp:302: undefined reference to `boost::filesystem::path::codecvt()'
collect2: error: ld returned 1 exit status
make: *** [player] Error 1

The related code are as following

bool Agent::openTupleLog()
{
 std::string dir="~/Experiments/Nov/";
 // create the log directory & file path string

try
{
    boost::filesystem::path kaway_log( dir
#if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION == 2
#  ifndef BOOST_FILESYSTEM_NO_DEPRECATED
                                       , &boost::filesystem::native
#  endif
#endif
                                       );
    if ( ! boost::filesystem::exists( kaway_log )
         && ! boost::filesystem::create_directories( kaway_log ) )
    {
        std::cerr << __FILE__ << ": " << __LINE__
                  << ": can't create log directory '"
                  << kaway_log.BOOST_FS_DIRECTORY_STRING() << "'" << std::endl;
        return false;
    }

    kaway_log /= tuplesFilename;

   M_kaway_log_name = kaway_log.BOOST_FS_FILE_STRING();
}
catch ( std::exception & e )
{
    std::cerr << __FILE__ << ": " << __LINE__
              << " Exception caught! " << e.what()
              << "\nCould not create log directory '"
              << dir
              << "'" << std::endl;
    return false;
}

// open the output file stream
M_kaway_log.open( M_kaway_log_name.c_str() );

if ( ! M_kaway_log.is_open() )
{
    std::cerr << __FILE__ << ": " << __LINE__
              << ": can't open log_file " << M_kaway_log_name
              << std::endl;
    return false;
}

return true;

}


问:
perl GetOptions, option-triggered subroutine that accepts arguments
I am trying to use the GetOptions function from GetOpt::Long to call a subroutine that accepts an argument. However, the subroutine gets called regardless of whether the option is specified on the command line. This unexpected behavior does not occur if an argument is not passed to the subroutine in the GetOptions line.

What follows is a minimal demonstration of the problem:

If an argument is provided to the subroutine in the GetOptions line, the subroutine ends up being called regardless of whether its controlling option is supplied on the command line:

```<code>$ cat a1.pl
#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long qw(GetOptions);
my $var="entered";
GetOptions ( "opt" => \&sub1($var) );
sub sub1 { print "sub1 $_[0]\n"; }

$ perl a1.pl --opt
sub1 entered

$ perl a1.pl
sub1 entered
</code>```

In contrast, if the subroutine is called in GetOptions without an argument, it behaves appropriately:

```<code>$ cat a2.pl
#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long qw(GetOptions);
GetOptions ( "opt" => \&sub2 );
sub sub2 { print "sub2 entered\n"; }

$ perl a2.pl --opt
sub2 entered

$ perl a2.pl
</code>```

What am I doing wrong?

PS: I know that I can simply set a variable that controls whether the subroutine is called after the GetOptions block, but I would like to determine the correct syntax for calling the subroutine within the GetOptions line, as well as understand why the observed behavior is happening.

答:
The module expects a code reference, and that is taken with the sub name alone (\&name) or as an anonymous sub; there is no notion of "arguments" as you are not making a function call but rather obtaining a reference (to code). Then call you sub in that code.  Details follow.

Associate the option with an anonymous subroutine, inside of which you can call your sub

```<code>use warnings;
use strict;
use feature 'say';

use Getopt::Long;

my $opt;
my $var = 'entered';

GetOptions ( 'opt' => sub { $opt = 1; sub1($var) } );

sub sub1 { say "sub1 $_[0]"; }
</code>```

Or use 'opt' => \&cb and in the sub cb() call sub1(...). This callback is passed the option name and value (or name, key, and value in case of a hash), and doesn't take other arguments. So you cannot in any way dynamically resolve what arguments to pass to sub1().

The invocation in the question is not how a subroutine reference is obtained; you must only use the subroutine name, \&name. This is not about Getopt, which just wants a code reference.

When you attempt to "pass arguments" that isn't a coderef anymore but the sub is executed and then the reference taken of its return; same as \sub() or \( sub() ). This can be seen by

```<code>perl -wE'sub tt { say "@_"; return "ret" }; $r = \&tt("hi"); say $$r'
</code>```

what prints

```
hi
ret
```

While this just isn't a way to take a reference let me still warn of possible surprises (if one ends up trying to take a "reference to a list")

Body:
I am trying to use the GetOptions function from GetOpt::Long to call a subroutine that accepts an argument. However, the subroutine gets called regardless of whether the option is specified on the command line. This unexpected behavior does not occur if an argument is not passed to the subroutine in the GetOptions line.

What follows is a minimal demonstration of the problem:

If an argument is provided to the subroutine in the GetOptions line, the subroutine ends up being called regardless of whether its controlling option is supplied on the command line:

$ cat a1.pl
#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long qw(GetOptions);
my $var="entered";
GetOptions ( "opt" => \&sub1($var) );
sub sub1 { print "sub1 $_[0]\n"; }

$ perl a1.pl --opt
sub1 entered

$ perl a1.pl
sub1 entered

In contrast, if the subroutine is called in GetOptions without an argument, it behaves appropriately:

$ cat a2.pl
#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long qw(GetOptions);
GetOptions ( "opt" => \&sub2 );
sub sub2 { print "sub2 entered\n"; }

$ perl a2.pl --opt
sub2 entered

$ perl a2.pl

What am I doing wrong?

PS: I know that I can simply set a variable that controls whether the subroutine is called after the GetOptions block, but I would like to determine the correct syntax for calling the subroutine within the GetOptions line, as well as understand why the observed behavior is happening.

Body:
The module expects a code reference, and that is taken with the sub name alone (\&name) or as an anonymous sub; there is no notion of "arguments" as you are not making a function call but rather obtaining a reference (to code). Then call you sub in that code.  Details follow.

Associate the option with an anonymous subroutine, inside of which you can call your sub

use warnings;
use strict;
use feature 'say';

use Getopt::Long;

my $opt;
my $var = 'entered';

GetOptions ( 'opt' => sub { $opt = 1; sub1($var) } );

sub sub1 { say "sub1 $_[0]"; }

Or use 'opt' => \&cb and in the sub cb() call sub1(...). This callback is passed the option name and value (or name, key, and value in case of a hash), and doesn't take other arguments. So you cannot in any way dynamically resolve what arguments to pass to sub1().

The invocation in the question is not how a subroutine reference is obtained; you must only use the subroutine name, \&name. This is not about Getopt, which just wants a code reference.

When you attempt to "pass arguments" that isn't a coderef anymore but the sub is executed and then the reference taken of its return; same as \sub() or \( sub() ). This can be seen by

perl -wE'sub tt { say "@_"; return "ret" }; $r = \&tt("hi"); say $$r'

what prints

hi
ret

While this just isn't a way to take a reference let me still warn of possible surprises (if one ends up trying to take a "reference to a list")

ContentLicense: CC BY-SA 4.0


问:
How do I add constraints to a subview loaded from a nib file?
I'm trying to load a sub view on to every single page of my app from a nib file. Right now I'm using a somewhat unusual approach to loading this sub view in that I am doing it through an extension of UIStoryboard (probably not relevant to my problem, but I'm not sure). So this is how the code looks when I load the nib file:

```<code>extension UIStoryboard {
    public func appendCustomView(to viewController: UIViewController) {
        if let myCustomSubview = Bundle.main.loadNibNamed("MyCustomSubview", owner: nil, options: nil)![0] as? MyCustomSubview {
            viewController.view.addSubview(myCustomSubview)
        }
    }
}
</code>```

This code does what it's supposed to do and adds "MyCustomSubview" to the view controller (I won't go in to detail on exactly how this method gets called because it works so it doesn't seem important). The problem is I can't for the life of me figure out how to add constraints that effect the size of myCustomSubview. I have tried putting code in the function I showed above as well as in the MyCustomSubview swift file to add constraints but no matter what I do the subview never changes.

Ideally the constraints would pin "MyCustomSubview" to the bottom of the ViewController, with width set to the size of the screen and a hard coded height constraint.

Here are the two main methods I tried (with about 100 minor variations for each) that did NOT work:

Method 1 - Add constraint directly from "appendCustomView"

```<code>public func appendCustomView(to viewController: UIViewController) {
    if let myCustomSubview = Bundle.main.loadNibNamed("MyCustomSubview", owner: nil, options: nil)![0] as? MyCustomSubview {

        let top = NSLayoutConstraint(item: myCustomSubview, attribute: .top, relatedBy: .equal
        , toItem: viewController.view, attribute: .top, multiplier: 1, constant: 50.0)

        viewController.view.addSubview(myCustomSubview)
        viewController.view.addConstraint(top)
    }
}
</code>```

Method 2 - Add constraint outlets and setter method in MyCustomSubview

```<code>class MyCustomSubview: UIView {
    @IBOutlet weak var widthConstraint: NSLayoutConstraint!
    @IBOutlet weak var heightConstraint: NSLayoutConstraint!

    func setConstraints(){
        self.widthConstraint.constant = UIScreen.main.bounds.size.width
        self.heightConstraint.constant = 20
    }
}
</code>```

And call setter method in "appendCustomView"

```<code>public func appendCustomView(to viewController: UIViewController) {
    if let myCustomSubview = Bundle.main.loadNibNamed("MyCustomSubview", owner: nil, options: nil)![0] as? MyCustomSubview {

        myCustomSubview.setConstraints()
        viewController.view.addSubview(myCustomSubview)
    }
}
</code>```

(*note: the actual constraints of these examples are irrelevant and I wasn't trying to meet the specs I mentioned above, I was just trying to make any sort of change to the view to know that the constraints were updating. They weren't.)

Edit : Changed "MyCustomNib" to "MyCustomSubview" for clarity.

答:
For anyone who comes across this in the future, this is the solution I came up with by tweaking this answer a little bit

Add a setConstraints(withRelationshipTo) method in the swift class that corresponds to the nib file:

```<code>class MyCustomSubview: UIView {

    func setConstraints(withRelationshipTo view: UIView){
        self.translatesAutoresizingMaskIntoConstraints = false

        // Replace with your own custom constraints
        self.heightAnchor.constraint(equalToConstant: 40.0).isActive = true
        self.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
        self.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        self.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
    }
}
</code>```

Then call the setConstraints method after you add the nib file to the view (probably in viewWillAppear or viewDidLoad of a view controller )

```<code>class MyViewController: UIViewController {

    override func viewWillAppear(_ animated: Bool){
        super.viewWillAppear(animated)
        if let myCustomSubview = Bundle.main.loadNibNamed("MyCustomSubview", owner: nil, options: nil)![0] as? MyCustomSubview {
            let view = self.view  // Added for clarity
            view.addSubview(myCustomSubview)
            myCustomSubview.setConstraints(withRelationshipTo: view)
        }
    }
}
</code>```

Body:
I'm trying to load a sub view on to every single page of my app from a nib file. Right now I'm using a somewhat unusual approach to loading this sub view in that I am doing it through an extension of UIStoryboard (probably not relevant to my problem, but I'm not sure). So this is how the code looks when I load the nib file:

extension UIStoryboard {
    public func appendCustomView(to viewController: UIViewController) {
        if let myCustomSubview = Bundle.main.loadNibNamed("MyCustomSubview", owner: nil, options: nil)![0] as? MyCustomSubview {
            viewController.view.addSubview(myCustomSubview)
        }
    }
}

This code does what it's supposed to do and adds "MyCustomSubview" to the view controller (I won't go in to detail on exactly how this method gets called because it works so it doesn't seem important). The problem is I can't for the life of me figure out how to add constraints that effect the size of myCustomSubview. I have tried putting code in the function I showed above as well as in the MyCustomSubview swift file to add constraints but no matter what I do the subview never changes.

Ideally the constraints would pin "MyCustomSubview" to the bottom of the ViewController, with width set to the size of the screen and a hard coded height constraint.

Here are the two main methods I tried (with about 100 minor variations for each) that did NOT work:

Method 1 - Add constraint directly from "appendCustomView"

public func appendCustomView(to viewController: UIViewController) {
    if let myCustomSubview = Bundle.main.loadNibNamed("MyCustomSubview", owner: nil, options: nil)![0] as? MyCustomSubview {

        let top = NSLayoutConstraint(item: myCustomSubview, attribute: .top, relatedBy: .equal
        , toItem: viewController.view, attribute: .top, multiplier: 1, constant: 50.0)

        viewController.view.addSubview(myCustomSubview)
        viewController.view.addConstraint(top)
    }
}

Method 2 - Add constraint outlets and setter method in MyCustomSubview

class MyCustomSubview: UIView {
    @IBOutlet weak var widthConstraint: NSLayoutConstraint!
    @IBOutlet weak var heightConstraint: NSLayoutConstraint!

    func setConstraints(){
        self.widthConstraint.constant = UIScreen.main.bounds.size.width
        self.heightConstraint.constant = 20
    }
}

And call setter method in "appendCustomView"

public func appendCustomView(to viewController: UIViewController) {
    if let myCustomSubview = Bundle.main.loadNibNamed("MyCustomSubview", owner: nil, options: nil)![0] as? MyCustomSubview {

        myCustomSubview.setConstraints()
        viewController.view.addSubview(myCustomSubview)
    }
}

(*note: the actual constraints of these examples are irrelevant and I wasn't trying to meet the specs I mentioned above, I was just trying to make any sort of change to the view to know that the constraints were updating. They weren't.)

Edit : Changed "MyCustomNib" to "MyCustomSubview" for clarity.

Body:
For anyone who comes across this in the future, this is the solution I came up with by tweaking this answer a little bit

Add a setConstraints(withRelationshipTo) method in the swift class that corresponds to the nib file:

class MyCustomSubview: UIView {

    func setConstraints(withRelationshipTo view: UIView){
        self.translatesAutoresizingMaskIntoConstraints = false

        // Replace with your own custom constraints
        self.heightAnchor.constraint(equalToConstant: 40.0).isActive = true
        self.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
        self.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        self.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
    }
}

Then call the setConstraints method after you add the nib file to the view (probably in viewWillAppear or viewDidLoad of a view controller )

class MyViewController: UIViewController {

    override func viewWillAppear(_ animated: Bool){
        super.viewWillAppear(animated)
        if let myCustomSubview = Bundle.main.loadNibNamed("MyCustomSubview", owner: nil, options: nil)![0] as? MyCustomSubview {
            let view = self.view  // Added for clarity
            view.addSubview(myCustomSubview)
            myCustomSubview.setConstraints(withRelationshipTo: view)
        }
    }
}


问:
JSF 2.0,JPA2.0 eclipseLink 2.5.1 7 EJB 3.0 application Migrating from websphere 8.0 to liberty 8.5.5.9 profile
JSF 2.0,JPA2.0 eclipseLink 2.5.1 7 EJB 3.0 application Migrating from websphere to liberty profile
getting below error while migrating from websphere to websphere liberty profile

[ERROR   ] CWWKZ0002E: An exception occurred while starting the
  application fagerEar. The exception message was:
  com.ibm.ws.container.service.state.StateChangeException:
  java.lang.NoClassDefFoundError: org.slf4j.Logger

答: Your slf4j jar which contains org.slf4j.Logger class is missing in the MANIFEST.MF file of the project which is trying to load it. If this error is occurring in your Web project, please add the slf4j jar in the MANIFEST.MF of your web project. </p>


问:
Using bash, how do you make a classpath out of all files in a directory?
This will be a really simple freebie for a bash guru:

Question

Using bash, how do you make a classpath out of all files in a directory?

Details

Given a directory:

```<code>LIB=/path/to/project/dir/lib
</code>```

that contains nothing but *.jar files such as:

```<code>junit-4.8.1.jar
jurt-3.2.1.jar
log4j-1.2.16.jar
mockito-all-1.8.5.jar
</code>```

I need to create a colon-separated classpath variable in the form:

```<code>CLASSPATH=/path/to/project/dir/lib/junit-4.8.1.jar:/path/to/project/dir/lib/jurt-3.2.1.jar:/path/to/project/dir/lib/log4j-1.2.16.jar:/path/to/project/dir/lib/mockito-all-1.8.5.jar
</code>```

Some seudo-code that nearly expresses the logic I'm looking for would be along the lines of:

```<code>for( each file in directory ) {
   classpath = classpath + ":" + LIB + file.name
}
</code>```

What is a simple way to accomplish this via bash script?

答:
New Answer

(October 2012)

There's no need to manually build the classpath list. Java supports a convenient wildcard syntax for directories containing jar files.

```<code>java -cp "$LIB/*"
</code>```

(Notice that the * is inside the quotes.)

Explanation from man java:

As a special convenience, a class path element containing a basename of * is considered equivalent to specifying a list of all the files in the directory with the extension .jar or .JAR (a java program cannot tell the difference between the two invocations).

For example, if directory foo contains a.jar and b.JAR, then the class path element foo/* is expanded to a A.jar:b.JAR, except that the order of jar files is unspecified. All jar files in the specified directory, even hidden ones, are included in the list. A classpath entry consisting simply of * expands to a list of all  the  jar  files  in  the  current directory. The CLASSPATH environment variable, where defined, will be similarly expanded. Any classpath wildcard expansion occurs before the Java virtual machine is started — no Java program will ever see unexpanded wildcards except by querying the environment.

Old Answer

Good

Simple but not perfect solution:

```<code>CLASSPATH=$(echo "$LIB"/*.jar | tr ' ' ':')
</code>```

There's a slight flaw in that this will not handle file names with spaces correctly. If that matters try this slightly more complicated version:

Better

```<code>CLASSPATH=$(find "$LIB" -name '*.jar' -printf '%p:' | sed 's/:$//')
</code>```

This only works if your find command supports -printf (as GNU find does).

If you don't have GNU find, as on Mac OS X, you can use xargs instead:

```<code>CLASSPATH=$(find "." -name '*.jar' | xargs echo | tr ' ' ':')
</code>```

Best?

Another (weirder) way to do it is to change the field separator variable $IFS. This is very strange-looking but will behave well with all file names and uses only shell built-ins.

```<code>CLASSPATH=$(JARS=("$LIB"/*.jar); IFS=:; echo "${JARS[*]}")
</code>```

Explanation:

JARS is set to an array of file names.

IFS is changed to :.

The array is echoed, and $IFS is used as the separator between array entries. Meaning the file names are printed with colons between them.

All of this is done in a sub-shell so the change to $IFS isn't permanent (which would be baaaad).

Body:
This will be a really simple freebie for a bash guru:

Question

Using bash, how do you make a classpath out of all files in a directory?

Details

Given a directory:

LIB=/path/to/project/dir/lib

that contains nothing but *.jar files such as:

junit-4.8.1.jar
jurt-3.2.1.jar
log4j-1.2.16.jar
mockito-all-1.8.5.jar

I need to create a colon-separated classpath variable in the form:

CLASSPATH=/path/to/project/dir/lib/junit-4.8.1.jar:/path/to/project/dir/lib/jurt-3.2.1.jar:/path/to/project/dir/lib/log4j-1.2.16.jar:/path/to/project/dir/lib/mockito-all-1.8.5.jar

Some seudo-code that nearly expresses the logic I'm looking for would be along the lines of:

for( each file in directory ) {
   classpath = classpath + ":" + LIB + file.name
}

What is a simple way to accomplish this via bash script?

Body:
New Answer

(October 2012)

There's no need to manually build the classpath list. Java supports a convenient wildcard syntax for directories containing jar files.

java -cp "$LIB/*"

(Notice that the * is inside the quotes.)

Explanation from man java:

As a special convenience, a class path element containing a basename of * is considered equivalent to specifying a list of all the files in the directory with the extension .jar or .JAR (a java program cannot tell the difference between the two invocations).

For example, if directory foo contains a.jar and b.JAR, then the class path element foo/* is expanded to a A.jar:b.JAR, except that the order of jar files is unspecified. All jar files in the specified directory, even hidden ones, are included in the list. A classpath entry consisting simply of * expands to a list of all  the  jar  files  in  the  current directory. The CLASSPATH environment variable, where defined, will be similarly expanded. Any classpath wildcard expansion occurs before the Java virtual machine is started — no Java program will ever see unexpanded wildcards except by querying the environment.

Old Answer

Good

Simple but not perfect solution:

CLASSPATH=$(echo "$LIB"/*.jar | tr ' ' ':')

There's a slight flaw in that this will not handle file names with spaces correctly. If that matters try this slightly more complicated version:

Better

CLASSPATH=$(find "$LIB" -name '*.jar' -printf '%p:' | sed 's/:$//')

This only works if your find command supports -printf (as GNU find does).

If you don't have GNU find, as on Mac OS X, you can use xargs instead:

CLASSPATH=$(find "." -name '*.jar' | xargs echo | tr ' ' ':')

Best?

Another (weirder) way to do it is to change the field separator variable $IFS. This is very strange-looking but will behave well with all file names and uses only shell built-ins.

CLASSPATH=$(JARS=("$LIB"/*.jar); IFS=:; echo "${JARS[*]}")

Explanation:

JARS is set to an array of file names.

IFS is changed to :.

The array is echoed, and $IFS is used as the separator between array entries. Meaning the file names are printed with colons between them.

All of this is done in a sub-shell so the change to $IFS isn't permanent (which would be baaaad).


问:
Change Package Name of Windows Store App
How do we change the package name of a Windows Store App? Please note we do not want to change the app display name.

We have published a UWP app to the Windows Store. Visual Studio generated a package name <PublisherName>.<AppName>in the package manifest.

When I changed the package name in the package manifest to a guid and published to the store I got the errors

```<code> Invalid package identity name
 Invalid package family name
</code>```

I can see the store app is associated with the package name. Do we have to delete the store app and create a new submission?

Can a UWP store app have a guid for a package name?

答:
You app identity in Package.appmanifest should be the same as in the store.

Check your app identity in the store:

Check your Package.appmanifest. Name and Publisher must be same as in store:

If they are not. Copy Package name from the store in your manifest, and then click Choose Certificate... button. Then select Configure Certificate...->Create test certificate. And copy there your publisher name from the store.

After that you cag generate your upload package and submit it to the store.

Body:
How do we change the package name of a Windows Store App? Please note we do not want to change the app display name.

We have published a UWP app to the Windows Store. Visual Studio generated a package name <PublisherName>.<AppName>in the package manifest.

When I changed the package name in the package manifest to a guid and published to the store I got the errors

 Invalid package identity name
 Invalid package family name

I can see the store app is associated with the package name. Do we have to delete the store app and create a new submission?

Can a UWP store app have a guid for a package name?


问:
get information from struct in swift file
so i have a class swift file that has a UserAccount class like this

```<code>class UserAccount{

 var userName: String!
 var email: String!
 var instaGram: String!
 var timeCreated: String!
 var like: String!
 var role: String!
 var active: String!
 var id: String!

init(userName: String, email: String, instaGram: String, timeCreated: String, like: String, role: String, active: String, id: String){

    self.userName = userName
    self.email = email
    self.instaGram  = instaGram
    self.timeCreated = timeCreated
    self.like = like
    self.role = role
    self.active = active
    self.id = id

 }
</code>```

}

i have login view controller where i get the class variables and do my json and assign their values like this :

```<code>var userAcount = [UserAccount]() // Array Of Object
var user = UserAccount(userName: "", email: "", instaGram: "", timeCreated: "", like: "", role: "", active: "", id: "") //Init of Object
</code>```

This is where i get my Json and add its value to its corresponding user class varible, i do this on my login view controller:

```<code>self.user.userName = userData.value(forKey: "userName") as! String
self.user.email = userData.value(forKey: "email") as! String
self.user.instaGram = userData.value(forKey: "instaGram") as! String
self.user.timeCreated = userData.value(forKey: "timeCreated") as! String
self.user.role = userData.value(forKey: "role") as! String
self.user.like = userData.value(forKey: "likes") as! String
self.user.id = userData.value(forKey: "id") as! String
self.user.active = userData.value(forKey: "active") as! String
</code>```

this is where i append the information to my class array:

```<code>self.userAcount.append(self.user)
</code>```

now my problem is that i dont know how to display the information in the UserAccount class on other view controllers, example the user profile view controller, is my first time working with users and profile, any help would be appreciated it, thank you

答:
To provide data to another UIViewController

Using Storyboard or segue

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
   if segue.identifier == "your_identifier",
      let destinationVC = segue.destination as? YourViewController {
        destinationVC.userAcount = self.userAcount
    }
}
</code>```

Programmatically

```<code>func gotoNextVC() {
    let destinationVC = YourViewController(nibName: "YourViewController", bundle: nil)
    destinationVC.userAcount = self.userAcount
    self.navigationController?.pushViewController(destinationVC, animated: true)

    // OR
    self.present(destinationVC, animated: true, completion: nil)
}
</code>```

Body:
so i have a class swift file that has a UserAccount class like this

class UserAccount{

 var userName: String!
 var email: String!
 var instaGram: String!
 var timeCreated: String!
 var like: String!
 var role: String!
 var active: String!
 var id: String!

init(userName: String, email: String, instaGram: String, timeCreated: String, like: String, role: String, active: String, id: String){

    self.userName = userName
    self.email = email
    self.instaGram  = instaGram
    self.timeCreated = timeCreated
    self.like = like
    self.role = role
    self.active = active
    self.id = id

 }

}

i have login view controller where i get the class variables and do my json and assign their values like this :

var userAcount = [UserAccount]() // Array Of Object
var user = UserAccount(userName: "", email: "", instaGram: "", timeCreated: "", like: "", role: "", active: "", id: "") //Init of Object

This is where i get my Json and add its value to its corresponding user class varible, i do this on my login view controller:

self.user.userName = userData.value(forKey: "userName") as! String
self.user.email = userData.value(forKey: "email") as! String
self.user.instaGram = userData.value(forKey: "instaGram") as! String
self.user.timeCreated = userData.value(forKey: "timeCreated") as! String
self.user.role = userData.value(forKey: "role") as! String
self.user.like = userData.value(forKey: "likes") as! String
self.user.id = userData.value(forKey: "id") as! String
self.user.active = userData.value(forKey: "active") as! String

this is where i append the information to my class array:

self.userAcount.append(self.user)

now my problem is that i dont know how to display the information in the UserAccount class on other view controllers, example the user profile view controller, is my first time working with users and profile, any help would be appreciated it, thank you

Body:
To provide data to another UIViewController

Using Storyboard or segue

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
   if segue.identifier == "your_identifier",
      let destinationVC = segue.destination as? YourViewController {
        destinationVC.userAcount = self.userAcount
    }
}

Programmatically

func gotoNextVC() {
    let destinationVC = YourViewController(nibName: "YourViewController", bundle: nil)
    destinationVC.userAcount = self.userAcount
    self.navigationController?.pushViewController(destinationVC, animated: true)

    // OR
    self.present(destinationVC, animated: true, completion: nil)
}


答:
```<code>SELECT *
FROM users U, messages M
WHERE M.user_id=U.id
 and M.id=(select max(M2.id)
    from messages M2
    where M2.user_id = U.id)
</code>```

Body:
I'm building a chat application and I want to list the users who have recently messaged, with their id, name, pic, and last message (id, timestamp, content)

My two tables look like this:

users:
------
id
name
pic

messages:
---------
id
content
timestamp
user_id (foreign key of user's id)

Here is the query that I've tried:

SELECT U.*,
    MAX(M.id) as lastmessage_id
FROM users U, messages M
WHERE M.user_id=U.id
GROUP BY user_id
ORDER BY lastmessage_id DESC

It will list the users who have messaged recently but it doesn't contain the last message's 'content'

Current output:

id, name, pic, lastmessage_id

Required output:

id, name, pic, lastmessage_id, lastmessage_content, lastmessage_timestamp


问:
How do I return only the form in the UpdateView class in Django?
I am trying to switch form a functional view that edits and submits a form to class based view, UpdateView. I need to access the form.

Until now I use this view:

```<code>@login_required
def edit_sale_view(request, id):
    instance = get_object_or_404(Sale, id=id)
    form = EditSaleForm(instance=instance)
    if request.method == "POST":
        form = EditSaleForm(request.POST, instance=instance)

        if form.is_valid():
            obj = form.save(commit=False)
            obj.user = request.user
            obj.save()
            return JsonResponse({'msg': 'Data saved'})
        else:
           return JsonResponse({'msg': 'Data not saved'})
    return HttpResponse(form.as_p())
</code>```

The form.as_p() is important because it is used in the form that is displayed in a modal window.

So, I think that I need to find out how to return only the form and not the whole template.

答:
You can access form instance by overriding form_valid method. For example:

```<code>class SomeView(UpdateView):
    ...
    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.user = self.request.user
        self.object.save()
        return HttpResponseRedirect(self.get_success_url()) # or use return JsonResponse({'msg': 'Data saved'})

    def get_initial(self):
        initial = super(SomeView, self).get_initial()
        # do something
        return initial()
</code>```

Body:
I am trying to switch form a functional view that edits and submits a form to class based view, UpdateView. I need to access the form.

Until now I use this view:

@login_required
def edit_sale_view(request, id):
    instance = get_object_or_404(Sale, id=id)
    form = EditSaleForm(instance=instance)
    if request.method == "POST":
        form = EditSaleForm(request.POST, instance=instance)

        if form.is_valid():
            obj = form.save(commit=False)
            obj.user = request.user
            obj.save()
            return JsonResponse({'msg': 'Data saved'})
        else:
           return JsonResponse({'msg': 'Data not saved'})
    return HttpResponse(form.as_p())

The form.as_p() is important because it is used in the form that is displayed in a modal window.

So, I think that I need to find out how to return only the form and not the whole template.

Body:
You can access form instance by overriding form_valid method. For example:

class SomeView(UpdateView):
    ...
    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.user = self.request.user
        self.object.save()
        return HttpResponseRedirect(self.get_success_url()) # or use return JsonResponse({'msg': 'Data saved'})

    def get_initial(self):
        initial = super(SomeView, self).get_initial()
        # do something
        return initial()


问:
Matching Keywords in a List to a Line of Words in Python
The following are two examples of many lines that I need to analyze and extract specific words from.

```<code>[40.748330000000003, -73.878609999999995] 6 2011-08-28 19:52:47 Sometimes I wish my life was a movie; #unreal I hate the fact I feel lonely surrounded by so many ppl

[37.786221300000001, -122.1965002] 6 2011-08-28 19:55:26 I wish I could lay up with the love of my life And watch cartoons all day.
</code>```

The coordinates and numbers are ignored

The case is to find how many of the words in each tweet line are present in this keywords list:

```<code>['hate', 1]
['hurt', 1]
['hurting', 1]
['like', 5]
['lonely', 1]
['love', 10]
</code>```

And also, find the sum of the values (e.g ['love', 10]) of the keywords found in each tweet line.

For example, for the sentence

```<code>'I hate to feel lonely at times'
</code>```

The sum of sentiments values for hate=1 and lonely=1 is equal to 2.
And the no. of words in the line is 7.

I've tried to use list into lists method and even trying to go through each sentence and keywords, but those haven't worked because the no. of tweets and keywords are several and I need to use loop format to find the values.

Appreciate your insight in advance!! :)

My Code:

```<code>try:
    KeywordFileName=input('Input keyword file name: ')
    KeywordFile = open(KeywordFileName, 'r')
except FileNotFoundError:
    print('The file you entered does not exist or is not in the directory')
    exit()
KeyLine = KeywordFile.readline()
while KeyLine != '':
    if list != []:
        KeyLine = KeywordFile.readline()
        KeyLine = KeyLine.rstrip()
        list = KeyLine.split(',')
        list[1] = int(list[1])
        print(list)
    else:
        break

try:
    TweetFileName = input('Input Tweet file name: ')
    TweetFile = open(TweetFileName, 'r')
except FileNotFoundError:
    print('The file you entered does not exist or is not in the directory')
    exit()

TweetLine = TweetFile.readline()
while TweetLine != '':
    TweetLine = TweetFile.readline()
    TweetLine = TweetLine.rstrip()
</code>```

答:
You can use simple regular expression to extract the words and use a tokenizer to count the number of occurrence of each of them in your sample string.</p>

```<code>from nltk.tokenize import word_tokenize
import collections
import re

str = '[40.748330000000003, -73.878609999999995] 6 2011-08-28 19:52:47 Sometimes I wish my life was a movie; #unreal I hate the fact I feel lonely surrounded by so many ppl'
num_regex = re.compile(r"[+-]?\d+(?:\.\d+)?")
str = num_regex.sub('',str)
words = word_tokenize(str)
final_list = collections.Counter(words)
print final_list
</code>```

Body:
The following are two examples of many lines that I need to analyze and extract specific words from.

[40.748330000000003, -73.878609999999995] 6 2011-08-28 19:52:47 Sometimes I wish my life was a movie; #unreal I hate the fact I feel lonely surrounded by so many ppl

[37.786221300000001, -122.1965002] 6 2011-08-28 19:55:26 I wish I could lay up with the love of my life And watch cartoons all day.

The coordinates and numbers are ignored

The case is to find how many of the words in each tweet line are present in this keywords list:

['hate', 1]
['hurt', 1]
['hurting', 1]
['like', 5]
['lonely', 1]
['love', 10]

And also, find the sum of the values (e.g ['love', 10]) of the keywords found in each tweet line.

For example, for the sentence

'I hate to feel lonely at times'

The sum of sentiments values for hate=1 and lonely=1 is equal to 2.
And the no. of words in the line is 7.

I've tried to use list into lists method and even trying to go through each sentence and keywords, but those haven't worked because the no. of tweets and keywords are several and I need to use loop format to find the values.

Appreciate your insight in advance!! :)

My Code:

try:
    KeywordFileName=input('Input keyword file name: ')
    KeywordFile = open(KeywordFileName, 'r')
except FileNotFoundError:
    print('The file you entered does not exist or is not in the directory')
    exit()
KeyLine = KeywordFile.readline()
while KeyLine != '':
    if list != []:
        KeyLine = KeywordFile.readline()
        KeyLine = KeyLine.rstrip()
        list = KeyLine.split(',')
        list[1] = int(list[1])
        print(list)
    else:
        break

try:
    TweetFileName = input('Input Tweet file name: ')
    TweetFile = open(TweetFileName, 'r')
except FileNotFoundError:
    print('The file you entered does not exist or is not in the directory')
    exit()

TweetLine = TweetFile.readline()
while TweetLine != '':
    TweetLine = TweetFile.readline()
    TweetLine = TweetLine.rstrip()

Body:
You can use simple regular expression to extract the words and use a tokenizer to count the number of occurrence of each of them in your sample string.

from nltk.tokenize import word_tokenize
import collections
import re

str = '[40.748330000000003, -73.878609999999995] 6 2011-08-28 19:52:47 Sometimes I wish my life was a movie; #unreal I hate the fact I feel lonely surrounded by so many ppl'
num_regex = re.compile(r"[+-]?\d+(?:\.\d+)?")
str = num_regex.sub('',str)
words = word_tokenize(str)
final_list = collections.Counter(words)
print final_list


问:
new ActionResult that can render the view generated and send contents via email
I was wondering if it were possible to write a file FileResult that worked something like this.

```<code>public ActionResult Generate(int id)
{
    //Fill Model
    string ViewName = "template1";

    return new FileResult(ViewName, @"c:\save"+ id +".txt");
}
</code>```

where it would take the model, and combine it with the view to give you the output that would normally be displayed to the screen but instead just save it with the filename specified.

Note: This file will be saved on the webserver

答:
As has been mentioned you can't do that for security reasons, but you can save a file if the user is prompted for saving the file.  I have done that for my resume.  I have a word version of my resume which is
generated from xml.  So I have a WordResult like this:

```<code>public class WordResult : ActionResult
{
public string FileName { get { return "Resume.doc"; } }

public override void ExecuteResult(ControllerContext context)
{
  GenerateMsWordDoc(context);
}

public void GenerateMsWordDoc(ControllerContext context)
{
  // You can add whatever you want to add as the HTML and it will be generated as Ms Word docs
  context.HttpContext.Response.AppendHeader("Content-Type", "application/msword");
  context.HttpContext.Response.AppendHeader("Content-disposition", "attachment; filename=" + FileName);

}
</code>```

}

To see this in action: http://www.aspevia.com/resume/show is the standard web version
http://www.aspevia.com/resume/show?format=word is the word version

OwnerDisplayName: Schotime

Body:
I was wondering if it were possible to write a file FileResult that worked something like this.

public ActionResult Generate(int id)
{
    //Fill Model
    string ViewName = "template1";

    return new FileResult(ViewName, @"c:\save"+ id +".txt");
}

where it would take the model, and combine it with the view to give you the output that would normally be displayed to the screen but instead just save it with the filename specified.

Note: This file will be saved on the webserver

LastEditorDisplayName: Schotime

Body:
As has been mentioned you can't do that for security reasons, but you can save a file if the user is prompted for saving the file.  I have done that for my resume.  I have a word version of my resume which is
generated from xml.  So I have a WordResult like this:

public class WordResult : ActionResult
{
public string FileName { get { return "Resume.doc"; } }

public override void ExecuteResult(ControllerContext context)
{
  GenerateMsWordDoc(context);
}

public void GenerateMsWordDoc(ControllerContext context)
{
  // You can add whatever you want to add as the HTML and it will be generated as Ms Word docs
  context.HttpContext.Response.AppendHeader("Content-Type", "application/msword");
  context.HttpContext.Response.AppendHeader("Content-disposition", "attachment; filename=" + FileName);

}

}

To see this in action: http://www.aspevia.com/resume/show is the standard web version
http://www.aspevia.com/resume/show?format=word is the word version

OwnerDisplayName: Trevor de Koekkoek


问:
Getting can not resolve 'PhoneAuthCredential' symbol
I am using Firebase Phone Authentication in my app. I have added all Gradle configuration like in app and in project using Firebase Assistant.
The Gradle file look like:

```<code>compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:design:25.3.1'
compile 'com.android.support:cardview-v7:25.3.1'
compile 'com.google.firebase:firebase-auth:10.0.1'
compile "com.google.android.gms:play-services-gcm:10.0.1"
</code>```

But still getting can not resolve 'PhoneAuthCredential' error.

答:
You need to use a newer version of the firebase-auth library.

Check out the documentation on Phone Number Authentication. The latest version is 11.6.0, and from the Google Play Services Release Notes it looks like Phone authentication features weren't added until version 11.

Body:
I am using Firebase Phone Authentication in my app. I have added all Gradle configuration like in app and in project using Firebase Assistant.
The Gradle file look like:

compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:design:25.3.1'
compile 'com.android.support:cardview-v7:25.3.1'
compile 'com.google.firebase:firebase-auth:10.0.1'
compile "com.google.android.gms:play-services-gcm:10.0.1"

But still getting can not resolve 'PhoneAuthCredential' error.


问:
Element-wise mutiplication .* of vectors gives matrix in Matlab
Given two vectors

```<code>a = 1:3;
b = 2:4;
</code>```

it's well known that the element-wise mutiplication a.*b produces

```<code>[ 2  6  12 ]
</code>```

Calling that result c, we have c(i) = a(i)*b(i)

But I don't understand how a.*b', b'.*a and b'*a all produce

```<code>[ 2     4     6
  3     6     9
  4     8    12 ]
</code>```

For the matrix multiplication b'*a, we know c(i,j) = b(i)*a(j).

But why do the other two also produce the same result?

答:
The examples you listed are all element-wise multiplication.

a.*b' will give error in earlier matlab, while it performs

```<code>bsxfun(@times, a, b')
</code>```

in Matlab since R2016b. This should explain the identical result for a.*b', b'.*a and b'*a.

a * b' will be matrix multiplication (inner dimension match).

Body:
Given two vectors

a = 1:3;
b = 2:4;

it's well known that the element-wise mutiplication a.*b produces

[ 2  6  12 ]

Calling that result c, we have c(i) = a(i)*b(i)

But I don't understand how a.*b', b'.*a and b'*a all produce

[ 2     4     6
  3     6     9
  4     8    12 ]

For the matrix multiplication b'*a, we know c(i,j) = b(i)*a(j).

But why do the other two also produce the same result?

Body:
The examples you listed are all element-wise multiplication.

a.*b' will give error in earlier matlab, while it performs

bsxfun(@times, a, b')

in Matlab since R2016b. This should explain the identical result for a.*b', b'.*a and b'*a.

a * b' will be matrix multiplication (inner dimension match).


问:
MySQL count registered users joined across multiple tables
There are 3 tables needed to create this report.  Two are tables with the data, and the 3rd table is one used in previous steps to gather the report data.

Table 1.  Users.

```<code>us_usid (int)
us_user (varchar) default empty string
</code>```

Table 2. UserGroups

```<code>ug_usid (int) = users.us_usid
ug_group (varchar 6) = group id
</code>```

Table 3. Report

```<code>re_group (varchar 6) = usergroups.ug_group
re_registered_count (int) = count of users with username
</code>```

Must simplifed schema, but shows the columns involved.  The report table has around 500 group IDs in them.  I need to count the users whose us_user <> '' and whos us_usid is in the ug_usid grouped by the ug_group IDs in the report table.

For example, the report table has '533103' as a group ID.  The UserGroups table has 545 users who have that ug_group.  Those ug_usids correspond to 545 users in the users table of which 373 have a value for the us_user string.  I need to get that "373" number into the report table.

If figured out how to pull all of the other necessary data but cannot find a working (and efficient way- these are groups with between 1000 and 100000 members) method to figure out how many are registered in one fell swoop.

答:
Count of users per user group, where there is a value in us_user</p>

```<code>select ug.us_user, count(u.us_usid)
from UserGroups ug
inner join Usersu on ug.ug_usid = u.us_usid
where u.us_user IS NOT NULL
</code>```

Body:
There are 3 tables needed to create this report.  Two are tables with the data, and the 3rd table is one used in previous steps to gather the report data.

Table 1.  Users.

us_usid (int)
us_user (varchar) default empty string

Table 2. UserGroups

ug_usid (int) = users.us_usid
ug_group (varchar 6) = group id

Table 3. Report

re_group (varchar 6) = usergroups.ug_group
re_registered_count (int) = count of users with username

Must simplifed schema, but shows the columns involved.  The report table has around 500 group IDs in them.  I need to count the users whose us_user <> '' and whos us_usid is in the ug_usid grouped by the ug_group IDs in the report table.

For example, the report table has '533103' as a group ID.  The UserGroups table has 545 users who have that ug_group.  Those ug_usids correspond to 545 users in the users table of which 373 have a value for the us_user string.  I need to get that "373" number into the report table.

If figured out how to pull all of the other necessary data but cannot find a working (and efficient way- these are groups with between 1000 and 100000 members) method to figure out how many are registered in one fell swoop.

Body:
Count of users per user group, where there is a value in us_user

select ug.us_user, count(u.us_usid)
from UserGroups ug
inner join Usersu on ug.ug_usid = u.us_usid
where u.us_user IS NOT NULL