问:
symfony3.4 service container in template
I do have defined a service in my MainBundle/MainFunctions/ and in Controller I can call the service. How can I get the service container in SYMFONY 3.4 in a template now? Read the docs that it is not public anymore.

```<code>#view/template.html.php
<?php $shop_id = $this->container->get('main_functions')->getSessionShopId(); ?>
</code>```

My config.yml

```<code>imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: services.yml }
- { resource: "@FrontendMainBundle/Resources/config/services.yml
</code>```

my FrontendMainBundle/Resources/config/services.yml

```<code>services:
    _defaults:
        public: true
    frontend_locale.locale_listener:
        class: Frontend\MainBundle\EventListener\LocaleListener
        arguments: ["%kernel.default_locale%"]
        tags:
            - { name: kernel.event_subscriber }
    main_functions:
        public: true
        class: "%main_functions_class.class%"
        arguments: ['@translator', '@doctrine.orm.entity_manager'....
</code>```

I read the docs that it is not public anymore. But I can't get to main_functions in template. How?

THANKS!!!

答:
The answer by MatMouth is the best way to interface with your service from the twig template. You can create functions for each method you need access in the template. Attempting to add your object as a twig variable is not a good practice unless it is just basic getters like you would use with Doctrine entities for example.

Here is some great documentation on setting up a new function and registering it in the container service:

https://symfony.com/doc/3.2/templating/twig_extension.html

You can also register a filter instead of a function. The difference between the two are the function syntax someFunction(someVar) and the filter someVar|someFilter. If you need to add additional arguments to your function or filter, just add the arguments to your callable.

Here's some documentation from Twig:

https://twig.symfony.com/doc/2.x/advanced.html

You can do cool things like make it HTML safe, inject the twig environment, etc...

Good luck and happy coding!

Body:
I do have defined a service in my MainBundle/MainFunctions/ and in Controller I can call the service. How can I get the service container in SYMFONY 3.4 in a template now? Read the docs that it is not public anymore.

#view/template.html.php
<?php $shop_id = $this->container->get('main_functions')->getSessionShopId(); ?>

My config.yml

imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: services.yml }
- { resource: "@FrontendMainBundle/Resources/config/services.yml

my FrontendMainBundle/Resources/config/services.yml

services:
    _defaults:
        public: true
    frontend_locale.locale_listener:
        class: Frontend\MainBundle\EventListener\LocaleListener
        arguments: ["%kernel.default_locale%"]
        tags:
            - { name: kernel.event_subscriber }
    main_functions:
        public: true
        class: "%main_functions_class.class%"
        arguments: ['@translator', '@doctrine.orm.entity_manager'....

I read the docs that it is not public anymore. But I can't get to main_functions in template. How?

THANKS!!!


来源: stackexchange

问:
Sleak (SWT & RCP) : Device is not tracking resource allocation (eclipse 4.3)
my RCP application (Video-Player with OpenCV java) throws the famous:

org.eclipse.swt.SWTError: No more handles Error

So now I found Sleak and a tutorial

I tryed the first way, but when I start the app and click on the snap button in the Sleak-View I got:
 "WARNING: Device is not tracking resource allocation".

When I do it the second way(.options file and -debug in the eclipse.ini (inserted befor the -vmargs)
I get some results in the sleak view but they are all Eclipse Resources... like said there I've trace eclipse ... but I do not want to ...

I'am running on Eclipse 4.3 SR1 (RCP) with sleak build for 4.3
(I have tryed it with the 4.4 build but it did not work either)

And in my RCP (e4) application is no Part where I do

```<code>Display display = PlatformUI.createDisplay();
</code>```

like proposed here.

答:
Struggled with this for most of day, finding a variety of out-of-date cookbooks and HowTo pages...  In one of the eclipse forum posts, someone referenced this page, which worked for me. (Oxygen, pure E4 standalone RCP application)

https://wiki.eclipse.org/Eclipse4/RCP/FAQ#How_to_use_Sleak_in_e4AP

Even tho it seems odd, you have to have your Eclipse workbench application running with various flags set, before it pays any attention to your project settings when running your application in the debugger.

ContentLicense: CC BY-SA 3.0

Body:
my RCP application (Video-Player with OpenCV java) throws the famous:

org.eclipse.swt.SWTError: No more handles Error

So now I found Sleak and a tutorial

I tryed the first way, but when I start the app and click on the snap button in the Sleak-View I got:
 "WARNING: Device is not tracking resource allocation".

When I do it the second way(.options file and -debug in the eclipse.ini (inserted befor the -vmargs)
I get some results in the sleak view but they are all Eclipse Resources... like said there I've trace eclipse ... but I do not want to ...

I'am running on Eclipse 4.3 SR1 (RCP) with sleak build for 4.3
(I have tryed it with the 4.4 build but it did not work either)

And in my RCP (e4) application is no Part where I do

Display display = PlatformUI.createDisplay();

like proposed here.


问:
Why do two MySQL dates in 1582 appear to be the same but comparison result is false?
I know that Gregorian calendar started on Oct 15th 1582, and during the transition from Julian calendar, 10 days had been dropped.

When I'm doing this query:

```<code>SELECT STR_TO_DATE('1582-10-05', '%Y-%m-%d')
</code>```

I'm getting this result:

```<code>1582-10-15 (the 10 days difference).
</code>```

But when I'm trying to match between such dates I'm getting the original date (Oct 5th and not 15th).

For example:

```<code>SELECT STR_TO_DATE('1582-10-05', '%Y-%m-%d') = STR_TO_DATE('1582-10-15', '%Y-%m-%d')
</code>```

I'm getting a false response, although you would have expected to get a true since Oct 5th actually count as Oct 15th, as we saw in the first example.

Anyone can explain what's going on here?

答:
On documentation it is stated that, TO_DAYS and FROM_DAYS functions must be called cautiously because of the transformation you noticed. Additionally, when I inspect the source codes of MySQL, I realized that STR_TO_DATE uses similar methodology with these functions. As I understand, cutover dates are completely unsafe to store or apply operations. Documentation says; "Dates during a cutover are nonexistent.", too.

Also for the inconsistency between different servers I may have an explanation. I have 2 different machines which have MySQL installed in Istanbul, Turkey and Frankfurt, Germany. They have same setup excluding localisation settings. First one shows 1, the other one shows 11 for the date substraction query. It means (in my humble opinion) there is unexplained sections about calendar cutover & localisation on official documentation.

Body:
I know that Gregorian calendar started on Oct 15th 1582, and during the transition from Julian calendar, 10 days had been dropped.

When I'm doing this query:

SELECT STR_TO_DATE('1582-10-05', '%Y-%m-%d')

I'm getting this result:

1582-10-15 (the 10 days difference).

But when I'm trying to match between such dates I'm getting the original date (Oct 5th and not 15th).

For example:

SELECT STR_TO_DATE('1582-10-05', '%Y-%m-%d') = STR_TO_DATE('1582-10-15', '%Y-%m-%d')

I'm getting a false response, although you would have expected to get a true since Oct 5th actually count as Oct 15th, as we saw in the first example.

Anyone can explain what's going on here?


问:
iOS " current graphics context" - What is that
When I draw lines and shapes etc I get the " current graphics context" in iOS.

What exactly though is " current graphics context" - I'm looking for the 30,000 foot description.

Right now I just copy and paste UI code, not exactly sure what it's doing.

答: Basically it is a class in a platform (iOS, Android, JavaME and many others) that provides access to all the drawing/display capabilities provided for that platform. It varies a bit for different platforms of course, but this is the 30,000 foot description :)</p>

ContentLicense: CC BY-SA 2.5


问:
Push QML ChartView updates from c++
I'm trying to adapt the Qt5.9 QML Oscilloscope example to have the graph data pushed from c++ rather than requested from QML. Below are the pertinent sections from the QML Oscilloscope example.

datasource.h:

```<code>#ifndef DATASOURCE_H
#define DATASOURCE_H

#include <QtCore/QObject>
#include <QtCharts/QAbstractSeries>

QT_BEGIN_NAMESPACE
class QQuickView;
QT_END_NAMESPACE

QT_CHARTS_USE_NAMESPACE

class DataSource : public QObject
{
    Q_OBJECT
public:
    explicit DataSource(QQuickView *appViewer, QObject *parent = 0);

Q_SIGNALS:

public slots:
    void generateData(int type, int rowCount, int colCount);
    void update(QAbstractSeries *series);

private:
    QQuickView *m_appViewer;
    QList<QVector<QPointF> > m_data;
    int m_index;
};

#endif // DATASOURCE_H
</code>```

datasource.cpp:

```<code>#include "datasource.h"
#include <QtCharts/QXYSeries>
#include <QtCharts/QAreaSeries>
#include <QtQuick/QQuickView>
#include <QtQuick/QQuickItem>
#include <QtCore/QDebug>
#include <QtCore/QtMath>

QT_CHARTS_USE_NAMESPACE

Q_DECLARE_METATYPE(QAbstractSeries *)
Q_DECLARE_METATYPE(QAbstractAxis *)

DataSource::DataSource(QQuickView *appViewer, QObject *parent) :
    QObject(parent),
    m_appViewer(appViewer),
    m_index(-1)
{
    qRegisterMetaType<QAbstractSeries*>();
    qRegisterMetaType<QAbstractAxis*>();

    generateData(0, 5, 1024);
}

void DataSource::update(QAbstractSeries *series)
{
    if (series) {
        QXYSeries *xySeries = static_cast<QXYSeries *>(series);
        m_index++;
        if (m_index > m_data.count() - 1)
            m_index = 0;

        QVector<QPointF> points = m_data.at(m_index);
        // Use replace instead of clear + append, it's optimized for performance
        xySeries->replace(points);
    }
}

void DataSource::generateData(int type, int rowCount, int colCount)
{
    // Remove previous data
    m_data.clear();

    // Append the new data depending on the type
    for (int i(0); i < rowCount; i++) {
        QVector<QPointF> points;
        points.reserve(colCount);
        for (int j(0); j < colCount; j++) {
            qreal x(0);
            qreal y(0);
            switch (type) {
            case 0:
                // data with sin + random component
                y = qSin(3.14159265358979 / 50 * j) + 0.5 + (qreal) rand() / (qreal) RAND_MAX;
                x = j;
                break;
            case 1:
                // linear data
                x = j;
                y = (qreal) i / 10;
                break;
            default:
                // unknown, do nothing
                break;
            }
            points.append(QPointF(x, y));
        }
        m_data.append(points);
    }
}
</code>```

main.cpp:

```<code>#include <QtWidgets/QApplication>
#include <QtQml/QQmlContext>
#include <QtQuick/QQuickView>
#include <QtQml/QQmlEngine>
#include <QtCore/QDir>
#include "datasource.h"

int main(int argc, char *argv[])
{
    // Qt Charts uses Qt Graphics View Framework for drawing, therefore
QApplication must be used.
    QApplication app(argc, argv);

    QQuickView viewer;

    // The following are needed to make examples run without having to install the module
    // in desktop environments.
#ifdef Q_OS_WIN
    QString extraImportPath(QStringLiteral("%1/../../../../%2"));
#else
    QString extraImportPath(QStringLiteral("%1/../../../%2"));
#endif
    viewer.engine()->addImportPath(extraImportPath.arg(QGuiApplication::applicationDirPath(),
                                  QString::fromLatin1("qml")));
    //QObject::connect(viewer.engine(), &QQmlEngine::quit, &viewer, &QWindow::close);

    viewer.setTitle(QStringLiteral("QML Oscilloscope"));

    DataSource dataSource(&viewer);
    viewer.rootContext()->setContextProperty("dataSource", &dataSource);

    viewer.setSource(QUrl("qrc:/qml/qmloscilloscope/main.qml"));
    viewer.setResizeMode(QQuickView::SizeRootObjectToView);
    viewer.setColor(QColor("#404040"));
    viewer.show();

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

ScopeView.qml:

```<code>import QtQuick 2.0
import QtCharts 2.1

ChartView {
    id: chartView
    animationOptions: ChartView.NoAnimation
    theme: ChartView.ChartThemeDark
    property bool openGL: true
    property bool openGLSupported: true
    onOpenGLChanged: {
        if (openGLSupported) {
            series("signal 1").useOpenGL = openGL;
        }
    }
    Component.onCompleted: {
        if (!series("signal 1").useOpenGL) {
            openGLSupported = false
            openGL = false
        }
    }

    ValueAxis {
        id: axisY1
        min: -1
        max: 4
    }

    ValueAxis {
        id: axisX
        min: 0
        max: 1024
    }

    LineSeries {
        id: lineSeries1
        name: "signal 1"
        axisX: axisX
        axisY: axisY1
        useOpenGL: chartView.openGL
    }

    Timer {
        id: refreshTimer
        interval: 1 / 60 * 1000 // 60 Hz
        running: true
       repeat: true
        onTriggered: {
            dataSource.update(chartView.series(0));
        }
    }
}
</code>```

Rather than using the Timer in QML, I'd like to use an existing Timeout in a c++ class to push new data to the QML ChartView. I have two questions:

How would I achieve this for the QML Oscilloscope example posted above?

What format would be most suitable for the c++ data to facilitate this? I'm thinking a QVector of some sort; the data will be an integer or float with a vector index.

答:
As you say in a comment you need to pass a series, then we create a method that receives the series and saves it in a member of the C ++ class, We also create a QTimer, and we do the same to update the interval:

*.h

```<code>public:
    Q_INVOKABLE void setSeries(QAbstractSeries *series);
    Q_INVOKABLE void setInterval(int interval);
    [...]
private:
    QXYSeries *mSeries;
    QTimer *timer;
    [...]
</code>```

*.cpp

```<code>void DataSource::setSeries(QAbstractSeries *series)
{
    if (series) {
        mSeries = static_cast<QXYSeries *>(series);
    }
}
</code>```

Then we remove the update argument and use mSeries:

```<code>DataSource::DataSource(QQuickView *appViewer, QObject *parent) :
    QObject(parent),
    m_appViewer(appViewer),
    m_index(-1)
{
    [...]
    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &DataSource::update);
    timer->start(1 / 60 * 1000 );
}

void DataSource::update()
{
    if (mSeries) {
        m_index++;
        if (m_index > m_data.count() - 1)
            m_index = 0;

        QVector<QPointF> points = m_data.at(m_index);
        // Use replace instead of clear + append, it's optimized for performance
        mSeries->replace(points);
    }
}

void DataSource::setInterval(int interval)
{
    if(timer){
        if(timer->isActive())
            timer->stop();
        timer->start(interval);
    }
}
</code>```

*.qml

```<code>Component.onCompleted: {
    dataSource.setSeries(chartView.series(0));
    if (!series("signal 1").useOpenGL) {
        openGLSupported = false
        openGL = false
    }
}
[...]
function changeRefreshRate(rate) {
    dataSource.setInterval(1 / Number(rate) * 1000);
    //refreshTimer.interval = 1 / Number(rate) * 1000;
}
</code>```

You can find the complete example in the following link.

Title: Push QML ChartView updates from c++

Body:
I'm trying to adapt the Qt5.9 QML Oscilloscope example to have the graph data pushed from c++ rather than requested from QML. Below are the pertinent sections from the QML Oscilloscope example.

datasource.h:

#ifndef DATASOURCE_H
#define DATASOURCE_H

#include <QtCore/QObject>
#include <QtCharts/QAbstractSeries>

QT_BEGIN_NAMESPACE
class QQuickView;
QT_END_NAMESPACE

QT_CHARTS_USE_NAMESPACE

class DataSource : public QObject
{
    Q_OBJECT
public:
    explicit DataSource(QQuickView *appViewer, QObject *parent = 0);

Q_SIGNALS:

public slots:
    void generateData(int type, int rowCount, int colCount);
    void update(QAbstractSeries *series);

private:
    QQuickView *m_appViewer;
    QList<QVector<QPointF> > m_data;
    int m_index;
};

#endif // DATASOURCE_H

datasource.cpp:

#include "datasource.h"
#include <QtCharts/QXYSeries>
#include <QtCharts/QAreaSeries>
#include <QtQuick/QQuickView>
#include <QtQuick/QQuickItem>
#include <QtCore/QDebug>
#include <QtCore/QtMath>

QT_CHARTS_USE_NAMESPACE

Q_DECLARE_METATYPE(QAbstractSeries *)
Q_DECLARE_METATYPE(QAbstractAxis *)

DataSource::DataSource(QQuickView *appViewer, QObject *parent) :
    QObject(parent),
    m_appViewer(appViewer),
    m_index(-1)
{
    qRegisterMetaType<QAbstractSeries*>();
    qRegisterMetaType<QAbstractAxis*>();

    generateData(0, 5, 1024);
}

void DataSource::update(QAbstractSeries *series)
{
    if (series) {
        QXYSeries *xySeries = static_cast<QXYSeries *>(series);
        m_index++;
        if (m_index > m_data.count() - 1)
            m_index = 0;

        QVector<QPointF> points = m_data.at(m_index);
        // Use replace instead of clear + append, it's optimized for performance
        xySeries->replace(points);
    }
}

void DataSource::generateData(int type, int rowCount, int colCount)
{
    // Remove previous data
    m_data.clear();

    // Append the new data depending on the type
    for (int i(0); i < rowCount; i++) {
        QVector<QPointF> points;
        points.reserve(colCount);
        for (int j(0); j < colCount; j++) {
            qreal x(0);
            qreal y(0);
            switch (type) {
            case 0:
                // data with sin + random component
                y = qSin(3.14159265358979 / 50 * j) + 0.5 + (qreal) rand() / (qreal) RAND_MAX;
                x = j;
                break;
            case 1:
                // linear data
                x = j;
                y = (qreal) i / 10;
                break;
            default:
                // unknown, do nothing
                break;
            }
            points.append(QPointF(x, y));
        }
        m_data.append(points);
    }
}

main.cpp:

#include <QtWidgets/QApplication>
#include <QtQml/QQmlContext>
#include <QtQuick/QQuickView>
#include <QtQml/QQmlEngine>
#include <QtCore/QDir>
#include "datasource.h"

int main(int argc, char *argv[])
{
    // Qt Charts uses Qt Graphics View Framework for drawing, therefore
QApplication must be used.
    QApplication app(argc, argv);

    QQuickView viewer;

    // The following are needed to make examples run without having to install the module
    // in desktop environments.
#ifdef Q_OS_WIN
    QString extraImportPath(QStringLiteral("%1/../../../../%2"));
#else
    QString extraImportPath(QStringLiteral("%1/../../../%2"));
#endif
    viewer.engine()->addImportPath(extraImportPath.arg(QGuiApplication::applicationDirPath(),
                                  QString::fromLatin1("qml")));
    //QObject::connect(viewer.engine(), &QQmlEngine::quit, &viewer, &QWindow::close);

    viewer.setTitle(QStringLiteral("QML Oscilloscope"));

    DataSource dataSource(&viewer);
    viewer.rootContext()->setContextProperty("dataSource", &dataSource);

    viewer.setSource(QUrl("qrc:/qml/qmloscilloscope/main.qml"));
    viewer.setResizeMode(QQuickView::SizeRootObjectToView);
    viewer.setColor(QColor("#404040"));
    viewer.show();

    return app.exec();
}

ScopeView.qml:

import QtQuick 2.0
import QtCharts 2.1

ChartView {
    id: chartView
    animationOptions: ChartView.NoAnimation
    theme: ChartView.ChartThemeDark
    property bool openGL: true
    property bool openGLSupported: true
    onOpenGLChanged: {
        if (openGLSupported) {
            series("signal 1").useOpenGL = openGL;
        }
    }
    Component.onCompleted: {
        if (!series("signal 1").useOpenGL) {
            openGLSupported = false
            openGL = false
        }
    }

    ValueAxis {
        id: axisY1
        min: -1
        max: 4
    }

    ValueAxis {
        id: axisX
        min: 0
        max: 1024
    }

    LineSeries {
        id: lineSeries1
        name: "signal 1"
        axisX: axisX
        axisY: axisY1
        useOpenGL: chartView.openGL
    }

    Timer {
        id: refreshTimer
        interval: 1 / 60 * 1000 // 60 Hz
        running: true
       repeat: true
        onTriggered: {
            dataSource.update(chartView.series(0));
        }
    }
}

Rather than using the Timer in QML, I'd like to use an existing Timeout in a c++ class to push new data to the QML ChartView. I have two questions:

How would I achieve this for the QML Oscilloscope example posted above?

What format would be most suitable for the c++ data to facilitate this? I'm thinking a QVector of some sort; the data will be an integer or float with a vector index.

Body:
As you say in a comment you need to pass a series, then we create a method that receives the series and saves it in a member of the C ++ class, We also create a QTimer, and we do the same to update the interval:

*.h

public:
    Q_INVOKABLE void setSeries(QAbstractSeries *series);
    Q_INVOKABLE void setInterval(int interval);
    [...]
private:
    QXYSeries *mSeries;
    QTimer *timer;
    [...]

*.cpp

void DataSource::setSeries(QAbstractSeries *series)
{
    if (series) {
        mSeries = static_cast<QXYSeries *>(series);
    }
}

Then we remove the update argument and use mSeries:

DataSource::DataSource(QQuickView *appViewer, QObject *parent) :
    QObject(parent),
    m_appViewer(appViewer),
    m_index(-1)
{
    [...]
    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &DataSource::update);
    timer->start(1 / 60 * 1000 );
}

void DataSource::update()
{
    if (mSeries) {
        m_index++;
        if (m_index > m_data.count() - 1)
            m_index = 0;

        QVector<QPointF> points = m_data.at(m_index);
        // Use replace instead of clear + append, it's optimized for performance
        mSeries->replace(points);
    }
}

void DataSource::setInterval(int interval)
{
    if(timer){
        if(timer->isActive())
            timer->stop();
        timer->start(interval);
    }
}

*.qml

Component.onCompleted: {
    dataSource.setSeries(chartView.series(0));
    if (!series("signal 1").useOpenGL) {
        openGLSupported = false
        openGL = false
    }
}
[...]
function changeRefreshRate(rate) {
    dataSource.setInterval(1 / Number(rate) * 1000);
    //refreshTimer.interval = 1 / Number(rate) * 1000;
}

You can find the complete example in the following link.

ContentLicense: CC BY-SA 4.0


问:
free() the reserved data with malloc
Hi
 I have written this Program which create a list of books which is given by the User and i can't free the my_value at the end of program and get a lot of errors .
 This is my Code

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

int main(){

int n;
printf("Please Enter the Number of Books:\n");
scanf("%d",&n);
char **array=(char *) malloc((n+1)*sizeof(char *));

for(int i=0;i<n;i++){
 array[i] = (char *)malloc(sizeof(char *));
}

for(int i=0;i<n;i++){
char *my_value=(char *) malloc(sizeof(char)*100);
printf("Please Enter the Name of the %dth Book:\n",i+1);
scanf("%s",my_value);
*(array+i)=my_value;
free(my_value);

}

for(int i=0;i<n;i++){
 printf("\n The Book Nr.%d is %s \n",i+1,*(array+i));
}
for(int i=0;i<n;i++){
 free(array[i]);
}
free(array);

return 0 ;
}
</code>```

答:
First, in

```<code>char **array=(char *) malloc((n+1)*sizeof(char *));
</code>```

you don't need n+1 pointers since you use only n.

Then, this loop

```<code>for(int i=0;i<n;i++){
   array[i] = (char *)malloc(sizeof(char *));
}
</code>```

is unnecessary (and wrong). array[i] is to be overwritten just after.

In the next loop

```<code>*(array+i)=my_value; // is array[i] = my_value
free(my_value);      // <=== why? remove that line!
</code>```

you free what you just allocated -- array[i] cannot be used anymore from that point! Lead to undefined behavior.

Title: free() the reserved data with malloc

Body:
Hi
 I have written this Program which create a list of books which is given by the User and i can't free the my_value at the end of program and get a lot of errors .
 This is my Code

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

int main(){

int n;
printf("Please Enter the Number of Books:\n");
scanf("%d",&n);
char **array=(char *) malloc((n+1)*sizeof(char *));

for(int i=0;i<n;i++){
 array[i] = (char *)malloc(sizeof(char *));
}

for(int i=0;i<n;i++){
char *my_value=(char *) malloc(sizeof(char)*100);
printf("Please Enter the Name of the %dth Book:\n",i+1);
scanf("%s",my_value);
*(array+i)=my_value;
free(my_value);

}

for(int i=0;i<n;i++){
 printf("\n The Book Nr.%d is %s \n",i+1,*(array+i));
}
for(int i=0;i<n;i++){
 free(array[i]);
}
free(array);

return 0 ;
}

Body:
First, in

char **array=(char *) malloc((n+1)*sizeof(char *));

you don't need n+1 pointers since you use only n.

Then, this loop

for(int i=0;i<n;i++){
   array[i] = (char *)malloc(sizeof(char *));
}

is unnecessary (and wrong). array[i] is to be overwritten just after.

In the next loop

*(array+i)=my_value; // is array[i] = my_value
free(my_value);      // <=== why? remove that line!

you free what you just allocated -- array[i] cannot be used anymore from that point! Lead to undefined behavior.


问:
Javascript: lexical scoping issue using new keyword constructor
i have problem about scoping in javascipt. I tried to create new object using the "new" keyword without any problem. The code looks like this

```<code>"use strict";

 function Person() {
     this.name = "john doe";
     console.log(this.name);
 }

 Var foo = new Person()
</code>```

The problem i encountered is when i try to add inner function the scope of the name variable becomes undefined inside the inner function

```<code> "use strict";

 function Person() {
         this.name = "john doe";

         Function speak() {
                   console.log("my name is" + this.name);
         }

         speak();
  }

  var foo = new Person();

 //error: "cannot read property 'name' of undefined"
</code>```

Can somebody explained what seems to be the problem? Thank guys

答:
With Strict mode when you are creating the object with new Person(), this refers to the window object which does not have the property called name. property called name belongs to the Person object.
Thus you are getting error cannot read property 'name' of undefined.

User another variable to hold the value of Person object's this to use that inside the inner function.

var thatObj = this;

"use strict";

function Person() {
  this.name = "john doe";
  var thatObj = this;
  function speak() {
    console.log("my name is: " + thatObj.name);
  }

  speak();
}

var foo = new Person();```

Body:
i have problem about scoping in javascipt. I tried to create new object using the "new" keyword without any problem. The code looks like this

"use strict";

 function Person() {
     this.name = "john doe";
     console.log(this.name);
 }

 Var foo = new Person()

The problem i encountered is when i try to add inner function the scope of the name variable becomes undefined inside the inner function

 "use strict";

 function Person() {
         this.name = "john doe";

         Function speak() {
                   console.log("my name is" + this.name);
         }

         speak();
  }

  var foo = new Person();

 //error: "cannot read property 'name' of undefined"

Can somebody explained what seems to be the problem? Thank guys


问:
Vim leader key mapping for zR?
I've created many leader key mappings in my .vimrc file for commands that you enter after typing ":".  For example,

```<code>map <Leader>sw :StripWhitespace<CR>
</code>```

But how do you create a leader key mapping in .vimrc for a command that you like "zR" which opens all folds? This isn't a command that you would type ":" before entering it.

答:
You create it in much the same way: leader combination, followed by the key combination you want it to map to. There's nothing particularly special about the ex command mappings. So for example, I have Ctrl-^ mapped to leaderp:

```<code>map <Leader>p <C-^>
</code>```

because it's a particularly annoying combination to reach on my split keyboard. In your case, I imagine you'd use:

```<code>map <Leader>ff zR
</code>```

Obviously, ff is just an example binding. You don't need a <CR> because you don't need one when typing the command in normal mode either.

Title: Vim leader key mapping for zR?

Body:
I've created many leader key mappings in my .vimrc file for commands that you enter after typing ":".  For example,

map <Leader>sw :StripWhitespace<CR>

But how do you create a leader key mapping in .vimrc for a command that you like "zR" which opens all folds? This isn't a command that you would type ":" before entering it.

Body:
You create it in much the same way: leader combination, followed by the key combination you want it to map to. There's nothing particularly special about the ex command mappings. So for example, I have Ctrl-^ mapped to leaderp:

map <Leader>p <C-^>

because it's a particularly annoying combination to reach on my split keyboard. In your case, I imagine you'd use:

map <Leader>ff zR

Obviously, ff is just an example binding. You don't need a <CR> because you don't need one when typing the command in normal mode either.


问:
Binding to 'style.grid' throws 'sanitizing unsafe style value' warning
I'm creating a mechanism for defining and calculating my own reusable grids.  Here's an example of what's returned

[left-bleed-start] 10.245000000001024px [left-bleed-end content-col-start] 1331.8500000001332px [content-col-end right-bleed-start] 10.245000000001024px [right-bleed-end]/[top-bleed-start] 10.245000000001024px [top-bleed-end link-row-start] 81.9600000000082px [content-row-end footer-row-start] 163.9200000000164px [footer-row-end bottom-bleed-start] 10.245000000001024px [bottom-bleed-end]

When applying it like this

```<code><div class="appCompGrid" [style.grid]="Grid.GridCode"></div>
</code>```

I get the santization warning.  However if I copy and paste the value in like this

```<code><div class="appCompGrid" style="grid: (same code);"></div>
</code>```

everything works.  The  css class is where I define the display as grid seeing that it'll be consistent no matter what size the screen is.  The only thing I could think to do was go back into the function and add + ';' to the end of where the grid code is put together figuring maybe that was throwing something off but it still gives the same error.  I tried applying display: grid; inline to see if maybe there was a problem with it reading both from a css class and inline for some odd reason.

I'm using @HostListener to re-calculate the grid as the size or orientation changes, so far I haven't run into a problem with Angular functioning in this manner so I don't understand where to begin with figuring out why this is happening.  Here's how I have my  component classes set up.

Base Class

```<code>export class GridBuilder {
    Settings : GridInit        = new GridInit();
    GridData : Array<GridType> = new Array();
    Grid     : GridOutput      = new GridOutput();

    constructor() { this.GridData = GridDefs; }

    public buildGrid() {
        const coreSettings : GridInit   = this.Settings;
        const gridData     : GridType[] = this.GridData;

        const w: number     = multiply( coreSettings.Size.Width,  coreSettings.Size.PixelRatio );
        const h: number     = multiply( coreSettings.Size.Height, coreSettings.Size.PixelRatio );
        const o: string     = checkOrientation( w, h );
        const c: CellSpecs  = calcCell( o, w );
        const t: GridType   = gridData.find( a => a.GridName == coreSettings.GridStyle );

        const cols: string  = calcArea( t.Columns, c );
        const rows: string  = calcArea( t.Rows, c );

        this.Grid.GridCode  = cols + '/' + rows + ';';
        this.Grid.GridAreas = t.Areas;
    }
}
</code>```

Secondary class for app component/ any top tier container

```<code>export class SiteGrid extends GridBuilder {

    constructor(){
        super();
        this.applySizeSettings();
    }

    applySizeSettings(){
        this.Settings.Size.Width       = window.innerWidth;
        this.Settings.Size.Height      = window.innerHeight;
        this.Settings.Size.PixelRatio  = window.devicePixelRatio;
    }
}
</code>```

the AppComponent

```<code>@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent extends SiteGrid {
    title = 'app';

    @HostListener( 'window: resize', [ '$event' ] )onResize( event ){ this.applySizeSettings(); this.buildGrid(); }

    constructor(){
        super();
        this.Settings.GridStyle = 'SiteGridA';
        this.buildGrid();
    }
}
</code>```

I don't know how relevant this may be in helping figure out the solution but thought I'd show how things are flowing just incase.  Anyone know why this warning is occurring?

答:
You need to implement a sanitizer to cleanse your css, or bypass it...

```<code>constructor(private sanitizer: DomSanitizer) {
    this.sanitizedCSS = sanitizer.bypassSecurityTrustStyle(Grid.GridCode) ;
  }
</code>```

As for why, this blog explains it pretty well, as does the DomSanitizer documentation.

DomSanitizer helps preventing Cross Site Scripting Security bugs (XSS) by sanitizing values to be safe to use in the different DOM contexts.

Body:
I'm creating a mechanism for defining and calculating my own reusable grids.  Here's an example of what's returned

[left-bleed-start] 10.245000000001024px [left-bleed-end content-col-start] 1331.8500000001332px [content-col-end right-bleed-start] 10.245000000001024px [right-bleed-end]/[top-bleed-start] 10.245000000001024px [top-bleed-end link-row-start] 81.9600000000082px [content-row-end footer-row-start] 163.9200000000164px [footer-row-end bottom-bleed-start] 10.245000000001024px [bottom-bleed-end]

When applying it like this

I get the santization warning.  However if I copy and paste the value in like this

everything works.  The  css class is where I define the display as grid seeing that it'll be consistent no matter what size the screen is.  The only thing I could think to do was go back into the function and add + ';' to the end of where the grid code is put together figuring maybe that was throwing something off but it still gives the same error.  I tried applying display: grid; inline to see if maybe there was a problem with it reading both from a css class and inline for some odd reason.

I'm using @HostListener to re-calculate the grid as the size or orientation changes, so far I haven't run into a problem with Angular functioning in this manner so I don't understand where to begin with figuring out why this is happening.  Here's how I have my  component classes set up.

Base Class

export class GridBuilder {
    Settings : GridInit        = new GridInit();
    GridData : Array<GridType> = new Array();
    Grid     : GridOutput      = new GridOutput();

    constructor() { this.GridData = GridDefs; }

    public buildGrid() {
        const coreSettings : GridInit   = this.Settings;
        const gridData     : GridType[] = this.GridData;

        const w: number     = multiply( coreSettings.Size.Width,  coreSettings.Size.PixelRatio );
        const h: number     = multiply( coreSettings.Size.Height, coreSettings.Size.PixelRatio );
        const o: string     = checkOrientation( w, h );
        const c: CellSpecs  = calcCell( o, w );
        const t: GridType   = gridData.find( a => a.GridName == coreSettings.GridStyle );

        const cols: string  = calcArea( t.Columns, c );
        const rows: string  = calcArea( t.Rows, c );

        this.Grid.GridCode  = cols + '/' + rows + ';';
        this.Grid.GridAreas = t.Areas;
    }
}

Secondary class for app component/ any top tier container

export class SiteGrid extends GridBuilder {

    constructor(){
        super();
        this.applySizeSettings();
    }

    applySizeSettings(){
        this.Settings.Size.Width       = window.innerWidth;
        this.Settings.Size.Height      = window.innerHeight;
        this.Settings.Size.PixelRatio  = window.devicePixelRatio;
    }
}

the AppComponent

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent extends SiteGrid {
    title = 'app';

    @HostListener( 'window: resize', [ '$event' ] )onResize( event ){ this.applySizeSettings(); this.buildGrid(); }

    constructor(){
        super();
        this.Settings.GridStyle = 'SiteGridA';
        this.buildGrid();
    }
}

I don't know how relevant this may be in helping figure out the solution but thought I'd show how things are flowing just incase.  Anyone know why this warning is occurring?

Body:
You need to implement a sanitizer to cleanse your css, or bypass it...

constructor(private sanitizer: DomSanitizer) {
    this.sanitizedCSS = sanitizer.bypassSecurityTrustStyle(Grid.GridCode) ;
  }

As for why, this blog explains it pretty well, as does the DomSanitizer documentation.

DomSanitizer helps preventing Cross Site Scripting Security bugs (XSS) by sanitizing values to be safe to use in the different DOM contexts.


问:
That A-Ha Moment for Understanding OO Design in C#
I've been studying C# for a couple of years, reading voraciously, even taking a few C# data access courses from Microsoft.  I've also been reading books on OOP.  I'm coding a web-based database application at work.  While my job title is not "programmer", I'm fortunate enough to be able to work on this as a side project.  I coded in Basic in the early 80's and was even good at utilizing pokes and peeks to manipulate the Apple ][ + and the TRS-80 to astound and amaze my friends.  But that was a very linear approach to coding.

All this being said, something is just not clicking with me.  I haven't had that a-ha moment with either C# or OOP that gives me the ability to sit down, open up VS2008, and start coding.  I have to study other people's code so much that it simply seems like I'm not doing anything on my own.  I'm getting discouraged.

It's not like I'm not capable of it.  I picked up t-sql really quickly.  Someone can tell me what information they want out of the database and I can code out the tsql in a matter of a few minutes to give them what they want.  SQL is something that I get.  This isn't happening for me with OOP or C#.  Granted, C# is inherently more complex, but at some point it has to click.  Right?

I read over stackoverflow and I'm overwhelmed at how infinitely smart you all are.

What was it for you that made it click?

Edited to add:
A lot of the answers here were outstanding.  However, one in particular seemed to have risen to the top and that's the one I marked as the "answer".  I also hate not marking my questions with the answer.

答: Learning what Generics in C# are did it for me. Now I forever think in if-else statements.</p>

OwnerDisplayName: GregD

LastEditorDisplayName: GregD

OwnerDisplayName: BBetances


问:
Simplest way to remove something from the FPU stack
I've been having some trouble lately with FPU stack overflows.  I managed to track it back to a buggy library function that pushes a garbage value onto the FPU stack every time it's called and never cleans it up.

Fortunately, this is easily reproducible and I know exactly what conditions cause it.  I can drop a block of inline ASM into the routine that calls this routine to pop the top value back off the FPU stack... except I don't quite know what to write.  My ASM-fu is fair to middlin', but not that strong.

So what's the simplest way to get rid of the top value on the FPU stack in x86 assembly, assuming it's garbage data and I don't care about the value?

答:
If you know how much you need to adjust the stack by, you can use fincstp. You also want to ffree the registers that you increment over.

However, probably the simplest solution is to use one of the popping data transfer operations like fstp. Normally you would store the result into an area of memory for later use, something like:

```<code>mem_area: defs 10         ; ten bytes for 80 bits
          fstp mem_area   ; pop it
</code>```

But, if you know you just want to throw away the value, you can use st(0) itself as the destination, saving the memory requirement:

```<code>fstp st(0)
</code>```

See here for a detailed guide on the instructions (particularly this bit).

Body:
If you know how much you need to adjust the stack by, you can use fincstp. You also want to ffree the registers that you increment over.

However, probably the simplest solution is to use one of the popping data transfer operations like fstp. Normally you would store the result into an area of memory for later use, something like:

mem_area: defs 10         ; ten bytes for 80 bits
          fstp mem_area   ; pop it

But, if you know you just want to throw away the value, you can use st(0) itself as the destination, saving the memory requirement:

fstp st(0)

See here for a detailed guide on the instructions (particularly this bit).


问:
Can someone tell me why my listView isn't populating with the JSON data
I have figured out that my main issue right now is my intent code. I have no idea how to build my intent to make the data come back from the website so if anyone could help me with that, it would be awesome! I am trying to get JSON data from the openweather api and my app will load up the web page instead of bringing it into the list view. Right now with the intent I have, a web page opens up with the data I need. Any help would be great!</p>

```<code>      public class MainActivity extends AppCompatActivity {

      private String url = "http://api.openweathermap.org/data/2.5/weather?q=London,us&APPID=805bd9f830268d5274c60e41613c28a5";
      private List<String> items = new ArrayList<String>();
      private ArrayAdapter<String> mArrayAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final Button btnRequest = (Button) findViewById(R.id.button); //your button id must be button
        final ListView lv = (ListView) findViewById(R.id.listView); //your listview ide must be listview

        final RequestQueue requestQueue = Volley.newRequestQueue(this);

        final JsonObjectRequest jor = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                 public void onResponse(JSONObject response) {

                    try {

                        JSONObject jcity = response.getJSONObject("city");

                        String name = jcity.getString("name");
                        JSONArray wlist = response.getJSONArray("list");

                          for (int i = 0; i < 10; i++) {

                            JSONObject jsonObject = wlist.getJSONObject(i);

                            String dt = jsonObject.getString("dt");
                            JSONArray warray = jsonObject.getJSONArray("weather");

                                JSONObject wobj = warray.getJSONObject(0);
                                String desc = wobj.getString("description");

                                items.add(dt + " " + desc);

                                Log.d("date", dt);  //Log.d prints to the terminal
                                Log.d("desc", desc);//good for debugging

                            }

                            mArrayAdapter = new ArrayAdapter<String>
                                    (getApplicationContext(),
                                    android.R.layout.simple_list_item_1, items);

                            //lv.setAdapter(mArrayAdapter);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("Volley", "Error");

                    }
                }
        );

        btnRequest.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                requestQueue.add(jor);
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setData(Uri.parse(url));
                startActivity(i);

            }
            });
    }
}
</code>```

答:
I think that's because you missed the setting adapter to the ListView. And also make sure your items have data inside it .

```<code>mArrayAdapter = new ArrayAdapter<String> (getApplicationContext(), android.R.layout.simple_list_item_1, items);
lv.setAdapter(mArrayAdapter);
</code>```

Body:
I have figured out that my main issue right now is my intent code. I have no idea how to build my intent to make the data come back from the website so if anyone could help me with that, it would be awesome! I am trying to get JSON data from the openweather api and my app will load up the web page instead of bringing it into the list view. Right now with the intent I have, a web page opens up with the data I need. Any help would be great!

      public class MainActivity extends AppCompatActivity {

      private String url = "http://api.openweathermap.org/data/2.5/weather?q=London,us&APPID=805bd9f830268d5274c60e41613c28a5";
      private List<String> items = new ArrayList<String>();
      private ArrayAdapter<String> mArrayAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final Button btnRequest = (Button) findViewById(R.id.button); //your button id must be button
        final ListView lv = (ListView) findViewById(R.id.listView); //your listview ide must be listview

        final RequestQueue requestQueue = Volley.newRequestQueue(this);

        final JsonObjectRequest jor = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                 public void onResponse(JSONObject response) {

                    try {

                        JSONObject jcity = response.getJSONObject("city");

                        String name = jcity.getString("name");
                        JSONArray wlist = response.getJSONArray("list");

                          for (int i = 0; i < 10; i++) {

                            JSONObject jsonObject = wlist.getJSONObject(i);

                            String dt = jsonObject.getString("dt");
                            JSONArray warray = jsonObject.getJSONArray("weather");

                                JSONObject wobj = warray.getJSONObject(0);
                                String desc = wobj.getString("description");

                                items.add(dt + " " + desc);

                                Log.d("date", dt);  //Log.d prints to the terminal
                                Log.d("desc", desc);//good for debugging

                            }

                            mArrayAdapter = new ArrayAdapter<String>
                                    (getApplicationContext(),
                                    android.R.layout.simple_list_item_1, items);

                            //lv.setAdapter(mArrayAdapter);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("Volley", "Error");

                    }
                }
        );

        btnRequest.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                requestQueue.add(jor);
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setData(Uri.parse(url));
                startActivity(i);

            }
            });
    }
}

Body:
I think that's because you missed the setting adapter to the ListView. And also make sure your items have data inside it .

mArrayAdapter = new ArrayAdapter<String> (getApplicationContext(), android.R.layout.simple_list_item_1, items);
lv.setAdapter(mArrayAdapter);


问:
Sending an SMTP email through GMail with reply support
I am creating a gmail SMTP client like so:

```<code>client = new SmtpClient();
client.UseDefaultCredentials = false;
client.Host = "smtp.gmail.com";
client.Port = 587;
client.EnableSsl = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Credentials = new NetworkCredential(email, password);
client.Timeout = 20000;
</code>```

And sending an email like so:

```<code>MailMessage msg = new MailMessage();
msg.From = new MailAddress(myemail-no-reply@gmail.com);
msg.To.Add(to);
msg.Subject = subject;
msg.Body = body;
client.Send(msg);
</code>```

I wish that if someone replies to my email it'll go to the admins email address, not to my application, and also ideally for them not to even know about the existence of the application's email address.

I could have my application forward emails received to the admin, but that's an ugly solution.

I understood from other threads that there's no way to send an email with a "reply to" field.

What I'm wondering is what if I have the admin's email as a "Send mail as" registered account on the application's GMail account.

So through the GMail interface I can send an email as if I'm the admin, can I do this from my c# application?

I know that I can set the from field of the msg sent to the admin's email, but I'm wondering if this is the correct approach, if gmail supports this, and if the email doesn't have more likelihood of ending up in the spam folder.

答:
I have given authority to "Send mail as" in the application e-mail as the admin, and simply editing the "from" field to be sent as the admin's email address appears to be working flawlessly.

So I guess this is one of those cases that the simplest solution is the correct one.

Edit: It appears that editing the "from" field doesn't allow you to send from a different address, but what does work is setting up the default email to send emails from as a different email in the GMail "send mail as" options.

Body:
I am creating a gmail SMTP client like so:

client = new SmtpClient();
client.UseDefaultCredentials = false;
client.Host = "smtp.gmail.com";
client.Port = 587;
client.EnableSsl = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Credentials = new NetworkCredential(email, password);
client.Timeout = 20000;

And sending an email like so:

MailMessage msg = new MailMessage();
msg.From = new MailAddress(myemail-no-reply@gmail.com);
msg.To.Add(to);
msg.Subject = subject;
msg.Body = body;
client.Send(msg);

I wish that if someone replies to my email it'll go to the admins email address, not to my application, and also ideally for them not to even know about the existence of the application's email address.

I could have my application forward emails received to the admin, but that's an ugly solution.

I understood from other threads that there's no way to send an email with a "reply to" field.

What I'm wondering is what if I have the admin's email as a "Send mail as" registered account on the application's GMail account.

So through the GMail interface I can send an email as if I'm the admin, can I do this from my c# application?

I know that I can set the from field of the msg sent to the admin's email, but I'm wondering if this is the correct approach, if gmail supports this, and if the email doesn't have more likelihood of ending up in the spam folder.


问:
Javascript Array value not changing after join
In JavaScript with Node.js, I'm not able to join the global array.

test.csv ends up containing c,d

```<code>var placeName = ["a","b"];
var csvFile = 'test.csv';
fs.readFile(csvFile, 'UTF-8', function(err, csv) {
  $.csv.toArrays(csv, {}, function(err, data) {
    for(var i=0, len=data.length; i<len; i++) {
      console.log(data[i]); //Will print every csv line as a newline
      placeName.push(data[i][0].toString());
    }
  });
   console.log(placeName); //Inside the function the array show a,b,c,d
});

// Prints only a and b. Did not add c & d from the csv.
console.log(placeName);
</code>```

答: It is because of asynchronous behaviour of JavaScript. console.log(placeName) outside is executed before you even read your CSV file.

Body:
In JavaScript with Node.js, I'm not able to join the global array.

test.csv ends up containing c,d

var placeName = ["a","b"];
var csvFile = 'test.csv';
fs.readFile(csvFile, 'UTF-8', function(err, csv) {
  $.csv.toArrays(csv, {}, function(err, data) {
    for(var i=0, len=data.length; i<len; i++) {
      console.log(data[i]); //Will print every csv line as a newline
      placeName.push(data[i][0].toString());
    }
  });
   console.log(placeName); //Inside the function the array show a,b,c,d
});

// Prints only a and b. Did not add c & d from the csv.
console.log(placeName);


问:
Required license is missing: Runtime Sitecore
I am getting this error

Required license is missing: Runtime

I have checked datafolder path

```<code> <sc.variable name="dataFolder" value="C:\Path\Data" />
</code>```

and license file settings

```<code>  <setting name="LicenseFile" value="$(dataFolder)/license.xml" />
</code>```

also checked permission all is correct but still it is giving error.

答:
I have installed 8.2 update 5 on my local machine. The default installation adds a folder called 'zzz' in App_config/include folder and creates DataFolder.config in that folder and references the data folder name from that config file. My publish overwrote/deleted that folder and i got the error 'Required license is missing: Runtime Sitecore'.

Adding that folder 'zzz' from my backup site resolved that issue.

Body:
I am getting this error

Required license is missing: Runtime

I have checked datafolder path

 <sc.variable name="dataFolder" value="C:\Path\Data" />

and license file settings

  <setting name="LicenseFile" value="$(dataFolder)/license.xml" />

also checked permission all is correct but still it is giving error.


问:
How to unzip the files stored in hdfs using spark java
```<code>List<String> list= jsc.wholeTextFiles(hdfsPath).keys().collect();
        for (String string : list) {
        System.out.println(string);
        }
</code>```

Here i am getting all the zip files.From here i am unable to proceed how to extract each file and store into hdfs path with same zipname folder

答:
You can use like below, But only thing we need to do collect at zipFilesRdd.collect().forEach before writing the contents into hdfs. Map and flat map gives task not serializable at this point.

```<code>public void readWriteZipContents(String zipLoc,String hdfsBasePath){
    JavaSparkContext jsc = new JavaSparkContext(new SparkContext(new SparkConf()));
    JavaPairRDD<String, PortableDataStream> zipFilesRdd = jsc.binaryFiles(zipLoc);
    zipFilesRdd.collect().forEach(file -> {
        ZipInputStream zipStream = new ZipInputStream(file._2.open());
        ZipEntry zipEntry = null;
        Scanner sc = new Scanner(zipStream);
        try {
            while ((zipEntry = zipStream.getNextEntry()) != null) {
                String entryName = zipEntry.getName();
                if (!zipEntry.isDirectory()) {
                    //create the path in hdfs and write its contents
                   Configuration configuration = new Configuration();
                    configuration.set("fs.hdfs.impl", org.apache.hadoop.hdfs.DistributedFileSystem.class.getName());
                    configuration.set("fs.file.impl", org.apache.hadoop.fs.LocalFileSystem.class.getName());
                    FileSystem fs = FileSystem.get(URI.create("hdfs://localhost:8020"), configuration);
                    FSDataOutputStream hdfsfile = fs.create(new Path(hdfsBasePath + "/" + entryName));
                   while(sc.hasNextLine()){
                       hdfsfile.writeBytes(sc.nextLine());
                   }
                   hdfsfile.close();
                   hdfsfile.flush();
                }
                zipStream.closeEntry();
            }
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        sc.close();
        //return fileNames.iterator();
    });
}
</code>```

Body:
List<String> list= jsc.wholeTextFiles(hdfsPath).keys().collect();
        for (String string : list) {
        System.out.println(string);
        }

Here i am getting all the zip files.From here i am unable to proceed how to extract each file and store into hdfs path with same zipname folder

Body:
You can use like below, But only thing we need to do collect at zipFilesRdd.collect().forEach before writing the contents into hdfs. Map and flat map gives task not serializable at this point.

public void readWriteZipContents(String zipLoc,String hdfsBasePath){
    JavaSparkContext jsc = new JavaSparkContext(new SparkContext(new SparkConf()));
    JavaPairRDD<String, PortableDataStream> zipFilesRdd = jsc.binaryFiles(zipLoc);
    zipFilesRdd.collect().forEach(file -> {
        ZipInputStream zipStream = new ZipInputStream(file._2.open());
        ZipEntry zipEntry = null;
        Scanner sc = new Scanner(zipStream);
        try {
            while ((zipEntry = zipStream.getNextEntry()) != null) {
                String entryName = zipEntry.getName();
                if (!zipEntry.isDirectory()) {
                    //create the path in hdfs and write its contents
                   Configuration configuration = new Configuration();
                    configuration.set("fs.hdfs.impl", org.apache.hadoop.hdfs.DistributedFileSystem.class.getName());
                    configuration.set("fs.file.impl", org.apache.hadoop.fs.LocalFileSystem.class.getName());
                    FileSystem fs = FileSystem.get(URI.create("hdfs://localhost:8020"), configuration);
                    FSDataOutputStream hdfsfile = fs.create(new Path(hdfsBasePath + "/" + entryName));
                   while(sc.hasNextLine()){
                       hdfsfile.writeBytes(sc.nextLine());
                   }
                   hdfsfile.close();
                   hdfsfile.flush();
                }
                zipStream.closeEntry();
            }
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        sc.close();
        //return fileNames.iterator();
    });
}


问:
Change date format in a Java string
I've a String representing a date.

```<code>String date_s = "2011-01-18 00:00:00.0";
</code>```

I'd like to convert it to a Date and output it in YYYY-MM-DD format.

2011-01-18

How can I achieve this?

Okay, based on the answers I retrieved below, here's something I've tried:

```<code>String date_s = " 2011-01-18 00:00:00.0";
SimpleDateFormat dt = new SimpleDateFormat("yyyyy-mm-dd hh:mm:ss");
Date date = dt.parse(date_s);
SimpleDateFormat dt1 = new SimpleDateFormat("yyyyy-mm-dd");
System.out.println(dt1.format(date));
</code>```

But it outputs 02011-00-1 instead of the desired 2011-01-18. What am I doing wrong?

答:
The answer is of course to create a SimpleDateFormat object and use it to parse Strings to Date and to format Dates to Strings.  If you've tried SimpleDateFormat and it didn't work, then please show your code and any errors you may receive.

Addendum:  "mm" in the format String is not the same as "MM".  Use MM for months and mm for minutes. Also, yyyyy is not the same as yyyy.  e.g.,:

```<code>import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FormateDate {

    public static void main(String[] args) throws ParseException {
        String date_s = "2011-01-18 00:00:00.0";

        // *** note that it's "yyyy-MM-dd hh:mm:ss" not "yyyy-mm-dd hh:mm:ss"
        SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date date = dt.parse(date_s);

        // *** same for the format String below
        SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println(dt1.format(date));
    }

}
</code>```

Title: Change date format in a Java string

Body:
I've a String representing a date.

String date_s = "2011-01-18 00:00:00.0";

I'd like to convert it to a Date and output it in YYYY-MM-DD format.

2011-01-18

How can I achieve this?

Okay, based on the answers I retrieved below, here's something I've tried:

String date_s = " 2011-01-18 00:00:00.0";
SimpleDateFormat dt = new SimpleDateFormat("yyyyy-mm-dd hh:mm:ss");
Date date = dt.parse(date_s);
SimpleDateFormat dt1 = new SimpleDateFormat("yyyyy-mm-dd");
System.out.println(dt1.format(date));

But it outputs 02011-00-1 instead of the desired 2011-01-18. What am I doing wrong?

Body:
The answer is of course to create a SimpleDateFormat object and use it to parse Strings to Date and to format Dates to Strings.  If you've tried SimpleDateFormat and it didn't work, then please show your code and any errors you may receive.

Addendum:  "mm" in the format String is not the same as "MM".  Use MM for months and mm for minutes. Also, yyyyy is not the same as yyyy.  e.g.,:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FormateDate {

    public static void main(String[] args) throws ParseException {
        String date_s = "2011-01-18 00:00:00.0";

        // *** note that it's "yyyy-MM-dd hh:mm:ss" not "yyyy-mm-dd hh:mm:ss"
        SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date date = dt.parse(date_s);

        // *** same for the format String below
        SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println(dt1.format(date));
    }

}


问:
RAII and factory design pattern?
Let's say I have Foo class:

```<code>struct Resource {
  void block();
  void unblock();
};
struct Foo {
   static Foo create() {
      Resource resource;
      resource.block();
      return Foo{resource};
    }
   ~Foo() { resource.unblock(); }
   void f() {}
private:
   Resource resource;
   Foo(Resource resource): resource(resource) {}
};
</code>```

Am I right and there is no guarantee that ~Foo will be called only once in such block?

```<code>{
   Foo foo = Foo::create();
   foo.f();
}
</code>```

If there is no guarantee, is it possible to fix somehow if using c++11 and move semantic? For example not call unblock_resource in moved foo, but I am not sure is there guarantee to use move constructor/operator= in return from Foo::create?

答:
Rule of 3/5/0. You define a destructor, but not copy / move constructors / assignment operators, which is a red flag that your type is unsafe. Indeed, the destructor may get called twice prior to C++17, and it's easy to mess up while using it even post C++17.

I recommend using std::unique_ptr so that you don't define any copy/move operations or the destructor. You can use std::unique_ptr even if the resource you are managing isn't a pointer; it'd look something like this:

```<code>class Resource {
    int handle;

public:
    Resource(std::nullptr_t = nullptr)
        : handle{}
    {}
    Resource(int handle)
        : handle{ handle }
    {}

    explicit operator bool() const { return handle != 0; }
    friend bool operator==(Resource lhs, Resource rhs) { return lhs.handle == rhs.handle; }
    friend bool operator!=(Resource lhs, Resource rhs) { return !(lhs == rhs); }

    void block() { std::cout << "block\n"; }
    void unblock() { std::cout << "unblock\n"; }

    struct Deleter {
        using pointer = Resource;

        void operator()(Resource resource) const {
            resource.unblock();
        }
    };
};

struct Foo {
    static Foo create() {
        Resource resource{42};
        resource.block();
        return Foo{resource};
    }
    void f() {}
private:
    std::unique_ptr<Resource, Resource::Deleter> resource;
    Foo(Resource resource): resource(resource) {}
};
</code>```

Title: RAII and factory design pattern?

Body:
Let's say I have Foo class:

struct Resource {
  void block();
  void unblock();
};
struct Foo {
   static Foo create() {
      Resource resource;
      resource.block();
      return Foo{resource};
    }
   ~Foo() { resource.unblock(); }
   void f() {}
private:
   Resource resource;
   Foo(Resource resource): resource(resource) {}
};

Am I right and there is no guarantee that ~Foo will be called only once in such block?

{
   Foo foo = Foo::create();
   foo.f();
}

If there is no guarantee, is it possible to fix somehow if using c++11 and move semantic? For example not call unblock_resource in moved foo, but I am not sure is there guarantee to use move constructor/operator= in return from Foo::create?

Body:
Rule of 3/5/0. You define a destructor, but not copy / move constructors / assignment operators, which is a red flag that your type is unsafe. Indeed, the destructor may get called twice prior to C++17, and it's easy to mess up while using it even post C++17.

I recommend using std::unique_ptr so that you don't define any copy/move operations or the destructor. You can use std::unique_ptr even if the resource you are managing isn't a pointer; it'd look something like this:

class Resource {
    int handle;

public:
    Resource(std::nullptr_t = nullptr)
        : handle{}
    {}
    Resource(int handle)
        : handle{ handle }
    {}

    explicit operator bool() const { return handle != 0; }
    friend bool operator==(Resource lhs, Resource rhs) { return lhs.handle == rhs.handle; }
    friend bool operator!=(Resource lhs, Resource rhs) { return !(lhs == rhs); }

    void block() { std::cout << "block\n"; }
    void unblock() { std::cout << "unblock\n"; }

    struct Deleter {
        using pointer = Resource;

        void operator()(Resource resource) const {
            resource.unblock();
        }
    };
};

struct Foo {
    static Foo create() {
        Resource resource{42};
        resource.block();
        return Foo{resource};
    }
    void f() {}
private:
    std::unique_ptr<Resource, Resource::Deleter> resource;
    Foo(Resource resource): resource(resource) {}
};


问:
Trigger an API automatically based on user specified time using nodejs
I am working on an application which will trigger a http api based on user specified time. Basically it is a message scheduling app on Nodejs that will call different web-services to communicate and post data on user specified time. I am using AWS dynamo db to store user messages and date & time when they want to publish.
What will be the best solution to achieve this?

Thanks in advance.

答:
You can store the timestamp of data post and the end points in DynamoDB and use an Lambda Schedule Event that checks the records frequently to query and post the data.

You can store timestamp as a sortkey so that it can be queried comparing with the current timestamp.

Note: One of the challenges with the DynamoDB TTL approach is that the timestamp to post the data(at TTL value) can vary up to 48 hours. According to the documentation

DynamoDB typically deletes expired items within 48 hours of
  expiration. The exact duration within which an item truly gets deleted
  after expiration is specific to the nature of the workload and the
  size of the table.


问:
How do I iterate over a slice of nested list?
I have this nested list:

```<code>nested = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
</code>```

I wanted to subtract 1 from the first 2 elements of the inner list so I tried it with list comprehension:

```<code>nested = [[x - 1 for x in stack[0:2]] for stack in nested]
</code>```

It did give me back the first 2 elements subtracted by 1 for the inner lists but it removed the last element completely

```<code>nested = [[0, 0], [1, 1], [2, 2]]
</code>```

I thought that by slicing the list, it will not affect the other element. However in this case it didn't work. Can someone explain this to me?

答:
Try it like this:

```<code>nested = [[x - 1  if i < 2 else x for i,x in enumerate(stack)] for stack in nested]
</code>```

This will affect only first two elements keeping the rest as is.

Body:
I have this nested list:

nested = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]

I wanted to subtract 1 from the first 2 elements of the inner list so I tried it with list comprehension:

nested = [[x - 1 for x in stack[0:2]] for stack in nested]

It did give me back the first 2 elements subtracted by 1 for the inner lists but it removed the last element completely

nested = [[0, 0], [1, 1], [2, 2]]

I thought that by slicing the list, it will not affect the other element. However in this case it didn't work. Can someone explain this to me?

Body:
Try it like this:

nested = [[x - 1  if i < 2 else x for i,x in enumerate(stack)] for stack in nested]

This will affect only first two elements keeping the rest as is.


问:
Accessing the web page's HTTP Headers in JavaScript
How do I access a page's HTTP response headers via JavaScript?

Related to this question, which was modified to ask about accessing two specific HTTP headers.

Related:

  How do I access the HTTP request header fields via JavaScript?

答:
For those looking for a way to parse all HTTP headers into an object that can be accessed as a dictionary headers["content-type"], I've created a function parseHttpHeaders:

```<code>function parseHttpHeaders(httpHeaders) {
    return httpHeaders.split("\n")
     .map(x=>x.split(/: */,2))
     .filter(x=>x[0])
     .reduce((ac, x)=>{ac[x[0]] = x[1];return ac;}, {});
}

var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = parseHttpHeaders(req.getAllResponseHeaders());
// Now we can do:  headers["content-type"]
</code>```

OwnerDisplayName: keparo

LastEditorDisplayName: keparo

Body:
For those looking for a way to parse all HTTP headers into an object that can be accessed as a dictionary headers["content-type"], I've created a function parseHttpHeaders:

function parseHttpHeaders(httpHeaders) {
    return httpHeaders.split("\n")
     .map(x=>x.split(/: */,2))
     .filter(x=>x[0])
     .reduce((ac, x)=>{ac[x[0]] = x[1];return ac;}, {});
}

var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = parseHttpHeaders(req.getAllResponseHeaders());
// Now we can do:  headers["content-type"]


答:
To keep the 3rd element, include it in the list comprehension:

```<code>>>> [ [x - 1 for x in stack[0:2]] + stack[2:] for stack in nested ]
[[0, 0, 1], [1, 1, 2], [2, 2, 3]]
</code>```

The above works for stack of any length.

Or, if stack always has exactly three elements:

```<code>>>> [[x-1, y-1, z] for x, y, z in nested]
[[0, 0, 1], [1, 1, 2], [2, 2, 3]]
</code>```

Or, you can make the changes in place:

```<code>>>> for stack in nested: stack[0]-=1; stack[1]-=1
...
>>> nested
[[0, 0, 1], [1, 1, 2], [2, 2, 3]]
</code>```

Title: How do I iterate over a slice of nested list?

Body:
To keep the 3rd element, include it in the list comprehension:

>>> [ [x - 1 for x in stack[0:2]] + stack[2:] for stack in nested ]
[[0, 0, 1], [1, 1, 2], [2, 2, 3]]

The above works for stack of any length.

Or, if stack always has exactly three elements:

>>> [[x-1, y-1, z] for x, y, z in nested]
[[0, 0, 1], [1, 1, 2], [2, 2, 3]]

Or, you can make the changes in place:

>>> for stack in nested: stack[0]-=1; stack[1]-=1
...
>>> nested
[[0, 0, 1], [1, 1, 2], [2, 2, 3]]


答:
Try this:

```<code>ORDER BY pin DESC, FIELD(username, 'alice', 'bob') DESC, score DESC, date DESC
</code>```

You can simply your query by adding an auto generated column to your votecount table which returns the total like this:

```<code>ALTER TABLE commentvote ADD COLUMN votes int GENERATED ALWAYS AS (voteUp-voteDown)
</code>```

Title: Ordering of Comment section by multiple columns in MySql

Body:
I have a comment-section on my site and I want the ordering to be:

1. if user has pinned the comment to the top I want those comment to show first

2. then I want the comments made by the user who wrote the blog

3. then I want the comments made by the user reading the blog

4. and lastly I want the rest of the comments

And I want each section (1-4) to be ordered by:

1. a score based on upvotes/downvotes of their comment and how many answers (= activity on comment) the comment recieved

2. date the comment was posted

So the result should look something like this: (Bob wrote the blog and Alice is reading it)

------------------------------------------------
| pin | username | score | date comment posted |
------------------------------------------------
| 1   | Bob      | 2     | 2017-01-25 13:45:01 | // First the pins ordered by Bob, Alice, score, date
------------------------------------------------
| 1   | Bob      | 1     | 2017-06-12 18:42:54 |
------------------------------------------------
| 1   | Alice    | 20    | 2017-03-21 12:51:42 |
------------------------------------------------
| 1   | Jack     | 30    | 2015-02-27 12:58:32 |
------------------------------------------------
| NULL| Bob      | 11    | 2016-11-21 10:41:35 | // Then Bob's (as writer of blog) comments ordered by score, date
------------------------------------------------
| NULL| Bob      | 11    | 2016-10-30 23:56:01 |
------------------------------------------------
| NULL| Bob      | 9     | 2017-12-24 12:00:00 |
------------------------------------------------
| NULL| Alice    | 30    | 2017-04-21 13:48:05 | // Then Alice's (as reader of blog) comments ordered by score, date
------------------------------------------------
| NULL| Alice    | 30    | 2016-12-01 15:37:12 |
------------------------------------------------
| NULL| Alice    | 7     | 2017-05-21 11:12:11 |
------------------------------------------------
| NULL| Jack     | 93    | 2012-12-21 00:00:00 | // Then all other comments ordered by score, date
------------------------------------------------
| NULL| Jill     | 92    | 2015-04-08 15:45:29 |
------------------------------------------------
| NULL| Andrew   | 92    | 2014-12-31 19:45:12 |
------------------------------------------------
| NULL| Jack     | 32    | 2017-01-12 23:12:57 |
------------------------------------------------
.
.
.

But what I get is results ordered by pin/NULL correctly...

But then - as long as pin is first in the ORDER BY - no matter the order of the rest of the ORDER BY (ie. ORDER BY pin, ...) it orders by score, then Bob, then Alice, then date...

So the results from above I get looks like this instead:

------------------------------------------------
| pin | username | score | date comment posted |
------------------------------------------------
| 1   | Jack     | 30    | 2015-02-27 12:58:32 |
------------------------------------------------
| 1   | Alice    | 20    | 2017-03-21 12:51:42 |
------------------------------------------------
| 1   | Bob      | 2     | 2017-01-25 13:45:01 |
------------------------------------------------
| 1   | Bob      | 1     | 2017-06-12 18:42:54 |
------------------------------------------------
| NULL| Jack     | 93    | 2012-12-21 00:00:00 |
------------------------------------------------
| NULL| Jill     | 92    | 2015-04-08 15:45:29 |
------------------------------------------------
| NULL| Andrew   | 92    | 2014-12-31 19:45:12 |
------------------------------------------------
| NULL| Jack     | 32    | 2017-01-12 23:12:57 |
------------------------------------------------
| NULL| Alice    | 30    | 2017-04-21 13:48:05 |
------------------------------------------------
| NULL| Alice    | 30    | 2016-12-01 15:37:12 |
------------------------------------------------
| NULL| Bob      | 11    | 2016-11-21 10:41:35 |
------------------------------------------------
| NULL| Bob      | 11    | 2016-10-30 23:56:01 |
------------------------------------------------
| NULL| Bob      | 9     | 2017-12-24 12:00:00 |
------------------------------------------------
| NULL| Alice    | 7     | 2017-05-21 11:12:11 |
------------------------------------------------
.
.
.

Why is that? and what can I do to fix it?

Info if you need it:

SELECT-statement (unedited for copy/paste)

SELECT comment.id AS commentID , comment.date AS cDate , comment.comment AS cComment , comment.pin AS cPin , comment.randomString AS cRandomString , commentuser.username AS cuUsername , commentuser.randomString AS cuRandomString , ( SELECT COUNT(*) FROM commentvote AS commentvote WHERE commentvote.commentID = comment.id AND commentvote.voteUp = 1 ) AS cVoteUp , ( SELECT COUNT(*) FROM commentvote AS commentvote2 WHERE commentvote2.commentID = comment.id AND commentvote2.voteDown = 1 ) AS cVoteDown , ( ( SELECT COUNT(*) FROM commentvote AS commentvoteup WHERE commentvoteup.commentID = comment.id AND commentvoteup.voteUp = 1 ) - ( SELECT COUNT(*) FROM commentvote AS commentvotedown WHERE commentvotedown.commentID = comment.id AND commentvotedown.voteDown = 1 ) + ( SELECT COUNT(*) FROM comment AS comment2 WHERE comment2.commentID = comment.id ) ) AS score FROM comment AS comment LEFT JOIN userlogininfo AS commentuser ON commentuser.id = comment.userID LEFT JOIN blog AS blog ON blog.randomString = ? INNER JOIN userlogininfo AS viewer ON viewer.randomString = ? INNER JOIN userlogininfo AS author ON author.id = blog.userID WHERE comment.blogID = blog.id AND comment.commentID IS NULL ORDER BY CAST(comment.pin AS UNSIGNED) DESC , CAST(author.id AS UNSIGNED) DESC , CAST(viewer.id AS UNSIGNED) DESC , CAST(score AS UNSIGNED) DESC , CAST(comment.date AS UNSIGNED) DESC

SELECT-statement (easy read)

SELECT
    comment.id AS commentID ,
    comment.date AS cDate ,
    comment.comment AS cComment ,
    comment.pin AS cPin ,
    comment.randomString AS cRandomString ,
    commentuser.username AS cuUsername ,
    commentuser.randomString AS cuRandomString ,

    (
    SELECT
        COUNT(*)
    FROM commentvote
    AS commentvote
    WHERE
        commentvote.commentID = comment.id
        AND commentvote.voteUp = 1
    )
    AS cVoteUp ,

    (
    SELECT
        COUNT(*)
    FROM commentvote
    AS commentvote2
    WHERE
        commentvote2.commentID = comment.id
        AND commentvote2.voteDown = 1
    )
    AS cVoteDown ,

    (
        (
        SELECT
            COUNT(*)
        FROM commentvote
        AS commentvoteup
        WHERE
            commentvoteup.commentID = comment.id
            AND commentvoteup.voteUp = 1
        )
        - // minus
        (
        SELECT
            COUNT(*)
        FROM commentvote
        AS commentvotedown
        WHERE
            commentvotedown.commentID = comment.id
            AND commentvotedown.voteDown = 1
        )
        + // plus
        (
        SELECT
            COUNT(*)
        FROM comment
        AS comment2
        WHERE
            comment2.commentID = comment.id
        )
    )
    AS score

FROM comment
AS comment

LEFT JOIN
    userlogininfo
AS commentuser
ON
    commentuser.id = comment.userID

LEFT JOIN
    blog
AS blog
ON
    blog.randomString = ?

INNER JOIN
    userlogininfo
AS viewer
ON
    viewer.randomString = ?

INNER JOIN
    userlogininfo
AS author
ON
    author.id = blog.userID

WHERE
    comment.blogID = blog.id
    AND comment.commentID IS NULL

ORDER BY
    CAST(comment.pin AS UNSIGNED) DESC , // first order by pin/not-pin
    CAST(author.id AS UNSIGNED) DESC , // then order each by author/not-author
    CAST(viewer.id AS UNSIGNED) DESC , // then order not-author by viewer/rest
    CAST(score AS UNSIGNED) DESC , // then order pin/author/viewer/rest by score
    CAST(comment.date AS UNSIGNED) DESC // then order pin/author/viewer/rest/score by date

userlogininfo-table:

--------------------------------
| id | username | randomString |
--------------------------------
| 1  | Bob      | lkjsdf786dsf |
--------------------------------
| 2  | Jack     | 78dsauhkwhe7 |
--------------------------------
| 3  | Jill     | asd78687asyd |
--------------------------------
| 4  | Alice    | ua67asdsd87j |
--------------------------------
| 5  | Andrew   | sadf987dsf7s |
--------------------------------
.
.
.

blog-table

------------------------------
| id | userID | randomString |
------------------------------
| 1  | 3      | sad86f7s8d67 |
------------------------------
| 2  | 1      | isuydf786iuh |
------------------------------
| 3  | 2      | 876sdfhgwegk |
------------------------------
.
.
.

comment-table

---------------------------------------------------------------------------
| id | date | userID | blogID | commentID | pin | ... All info needed ... |
---------------------------------------------------------------------------
| 1  |<date>| 3      |  2     | NULL      | 1   |                         |
---------------------------------------------------------------------------
| 2  |<date>| 4      |  1     | 1         | NULL|                         | // is an answer to comment with id 1
---------------------------------------------------------------------------
.
.
.

commentvote-table

-----------------------------------------------
| id | userID | commentID | voteUp | voteDown |
-----------------------------------------------
| 1  | 2      | 3         | 1      | NULL     |
-----------------------------------------------
| 2  | 4      | 3         | 1      | NULL     |
-----------------------------------------------
| 3  | 3      | 2         | NULL   | 1        |
-----------------------------------------------
| 4  | 2      | 2         | 1      | NULL     |
-----------------------------------------------
.
.
.

Hope somebody can help because I'm stumped... thanks in advance...

Body:
Try this:

ORDER BY pin DESC, FIELD(username, 'alice', 'bob') DESC, score DESC, date DESC

You can simply your query by adding an auto generated column to your votecount table which returns the total like this:

ALTER TABLE commentvote ADD COLUMN votes int GENERATED ALWAYS AS (voteUp-voteDown)


问:
Trying to display all posts in given category - getting error
I'm building my first laravel app.

I'm trying to display all posts in x category.

My routes:

```<code>Route::get('/', 'PostsController@index')->name('home');
Route::get('/{id}/{slug?}', 'PostsController@show')->name('show');
Route::get('/categories/{category}', 'CategoriesController@index')->name('category');
</code>```

My category model:

```<code>namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    public function posts()
    {
        return $this->hasMany(Post::class);
    }

    public function getRouteKeyName()
    {
        return 'slug';
    }
}
</code>```

My category controller:

```<code>namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Category;

class CategoriesController extends Controller
{
    public function index(Category $category)
    {
        $posts = $category->posts;

        return view('index', compact('posts'));
    }
}
</code>```

Getting: "Sorry, the page you are looking for could not be found."

Works if I change:

```<code>Route::get('/{id}/{slug?}', 'PostsController@show')->name('show');
</code>```

To:

```<code>Route::get('/{post}', 'PostsController@show')->name('show');
</code>```

Thank you in advance!

答:
This sounds like it's the route that's configured incorrectly, sometimes the order that you define the routes can cause issues.

try to define the routes in theis order instead to see if it makes a difference:

```<code>Route::get('/{id}/{slug?}', 'PostsController@show')->name('show');
Route::get('/', 'PostsController@index')->name('home');
Route::get('/categories/{category}', 'CategoriesController@index')->name('category');
</code>```

Body:
I'm building my first laravel app.

I'm trying to display all posts in x category.

My routes:

Route::get('/', 'PostsController@index')->name('home');
Route::get('/{id}/{slug?}', 'PostsController@show')->name('show');
Route::get('/categories/{category}', 'CategoriesController@index')->name('category');

My category model:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    public function posts()
    {
        return $this->hasMany(Post::class);
    }

    public function getRouteKeyName()
    {
        return 'slug';
    }
}

My category controller:

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Category;

class CategoriesController extends Controller
{
    public function index(Category $category)
    {
        $posts = $category->posts;

        return view('index', compact('posts'));
    }
}

Getting: "Sorry, the page you are looking for could not be found."

Works if I change:

Route::get('/{id}/{slug?}', 'PostsController@show')->name('show');

To:

Route::get('/{post}', 'PostsController@show')->name('show');

Thank you in advance!

Body:
This sounds like it's the route that's configured incorrectly, sometimes the order that you define the routes can cause issues.

try to define the routes in theis order instead to see if it makes a difference:

Route::get('/{id}/{slug?}', 'PostsController@show')->name('show');
Route::get('/', 'PostsController@index')->name('home');
Route::get('/categories/{category}', 'CategoriesController@index')->name('category');


问:
How to find the equation for an ellipse from 3 points using python
I am bulding a game and I need to creat a map for it. in order to do it i have to use two kinds of elipse: one that is found using 2 points and one that found using 3 points (and go through them). I have found a way to find the equation with 2 points but now I have not found a way to do with 3 point. So I am looking to find the equation for an ellipse given 3 point.
that is how i have done 2 points (it is not elegant but it does the job great):</p>

```<code>import turtle
import sympy as sp
import random
SCREEN = turtle.Screen()
t = turtle.Turtle()
t.up()
t.ht()
t.speed(0)
tt = turtle.Turtle()
tt.up()
tt.ht()
tt.speed(0)
press = 1
def get_mouse_click_coor(x, y):
    turtle.onscreenclick(None)
    print(x, y)
    draw(x,y)

def draw(mou_x,mou_y):
    SCREEN.tracer(0)
    global press
    global x_press1, y_press1

    if press%2 != 0:
        t.goto(mou_x,mou_y)
        x_press1, y_press1 = mou_x, mou_y
        tt.color('blue')
        tt.goto(mou_x,mou_y)
        tt.dot(7)

    if press%2 == 0:
        if mou_x == x_press1 and mou_y == y_press1:
            press = press - 1
        else:
            tt.color('red')
            tt.goto(mou_x,mou_y)
            tt.dot(7)

            if mou_x > x_press1 and mou_y > y_press1:
                turn = 1
            if mou_x > x_press1 and mou_y < y_press1:
                turn = 2
            if mou_x < x_press1 and mou_y < y_press1:
                turn = 3
            if mou_x < x_press1 and mou_y > y_press1:
                turn = 4

      #   if turn <= 2:
            x0 = -mou_x+x_press1
            if turn >= 3:
                x0 = -x_press1+mou_x
            y0 = mou_y - y_press1

            for x in range(int(x0), 1, 1):
                y = y0 - y0*sp.root(1.0-(float((x-x0)**2)/(x0**2)),2)
                if turn >= 3:
                    x = -x
                t.goto(x+mou_x, y+y_press1)
                t.down()

    t.up()
    press = press + 1
    SCREEN.tracer(1)

while True:
    t.color('black')
    turtle.onscreenclick(get_mouse_click_coor)

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

答:
Not sure if I get your point as it is actually a math question. For me it seems like your looking for something like a function that requires 3 input parameters to draw an ellipse. This would be then following code, where width is the major axis and height the minor axis. xy is the center point of the ellipse.

```<code> import matplotlib.pyplot as plt
 import numpy as np
 from matplotlib.patches import Ellipse

 # These are 3 xy points
 xpoints=(1.5,1.4,1.9)
 ypoints=(2.5,2.4,1.5)

 # calculate the center
 mean_x=np.mean(xpoints)
 mean_y=np.mean(ypoints)

 # set the size of the ellipse
 w=np.max(xpoints)+0.1
 h=np.max(ypoints)+0.1

 # buid the ellipse around it
 ells = Ellipse((mean_x,mean_y), width=w, height=h,facecolor='None')

 # plot it
 fig = plt.figure(0)
 ax = fig.add_subplot(111, aspect='equal')
 ax.add_artist(ells)
 ax.scatter(xpoints,ypoints, color='r')

ax.set_xlim(-4, 4)
ax.set_ylim(-4, 4)
plt.show()
</code>```

Body:
I am bulding a game and I need to creat a map for it. in order to do it i have to use two kinds of elipse: one that is found using 2 points and one that found using 3 points (and go through them). I have found a way to find the equation with 2 points but now I have not found a way to do with 3 point. So I am looking to find the equation for an ellipse given 3 point.
that is how i have done 2 points (it is not elegant but it does the job great):

import turtle
import sympy as sp
import random
SCREEN = turtle.Screen()
t = turtle.Turtle()
t.up()
t.ht()
t.speed(0)
tt = turtle.Turtle()
tt.up()
tt.ht()
tt.speed(0)
press = 1
def get_mouse_click_coor(x, y):
    turtle.onscreenclick(None)
    print(x, y)
    draw(x,y)

def draw(mou_x,mou_y):
    SCREEN.tracer(0)
    global press
    global x_press1, y_press1

    if press%2 != 0:
        t.goto(mou_x,mou_y)
        x_press1, y_press1 = mou_x, mou_y
        tt.color('blue')
        tt.goto(mou_x,mou_y)
        tt.dot(7)

    if press%2 == 0:
        if mou_x == x_press1 and mou_y == y_press1:
            press = press - 1
        else:
            tt.color('red')
            tt.goto(mou_x,mou_y)
            tt.dot(7)

            if mou_x > x_press1 and mou_y > y_press1:
                turn = 1
            if mou_x > x_press1 and mou_y < y_press1:
                turn = 2
            if mou_x < x_press1 and mou_y < y_press1:
                turn = 3
            if mou_x < x_press1 and mou_y > y_press1:
                turn = 4

      #   if turn <= 2:
            x0 = -mou_x+x_press1
            if turn >= 3:
                x0 = -x_press1+mou_x
            y0 = mou_y - y_press1

            for x in range(int(x0), 1, 1):
                y = y0 - y0*sp.root(1.0-(float((x-x0)**2)/(x0**2)),2)
                if turn >= 3:
                    x = -x
                t.goto(x+mou_x, y+y_press1)
                t.down()

    t.up()
    press = press + 1
    SCREEN.tracer(1)

while True:
    t.color('black')
    turtle.onscreenclick(get_mouse_click_coor)

turtle.mainloop()

Body:
Not sure if I get your point as it is actually a math question. For me it seems like your looking for something like a function that requires 3 input parameters to draw an ellipse. This would be then following code, where width is the major axis and height the minor axis. xy is the center point of the ellipse.

 import matplotlib.pyplot as plt
 import numpy as np
 from matplotlib.patches import Ellipse

 # These are 3 xy points
 xpoints=(1.5,1.4,1.9)
 ypoints=(2.5,2.4,1.5)

 # calculate the center
 mean_x=np.mean(xpoints)
 mean_y=np.mean(ypoints)

 # set the size of the ellipse
 w=np.max(xpoints)+0.1
 h=np.max(ypoints)+0.1

 # buid the ellipse around it
 ells = Ellipse((mean_x,mean_y), width=w, height=h,facecolor='None')

 # plot it
 fig = plt.figure(0)
 ax = fig.add_subplot(111, aspect='equal')
 ax.add_artist(ells)
 ax.scatter(xpoints,ypoints, color='r')

ax.set_xlim(-4, 4)
ax.set_ylim(-4, 4)
plt.show()


问:
BeautifulSoup: find all tags before stopping condition is met
I'm trying to extract a class tag from an HTML file, but only if it is located before a given stopping point. What I have is:

```<code>import requests
from bs4 import BeautifulSoup

page = requests.get("https://mysite")
soup = BeautifulSoup(page.content, 'html.parser')
class_extr = soup.find_all("span", class_="myclass")
</code>```

This works, but it finds all instances of myclass, and i only want those before the following text shows in the soup:

```<code><h4 class="cat-title" id="55">
 Title text N1
 <small>
  Title text N2.
 </small>
</h4>
</code>```

The thing that makes this block unique are the Title text N lines, especially the Title text N2. line. There are many cat-title tags before, so I can't use that as a stopping condition.

The code surrounding this block looks like this:

```<code>...
<div class="myc">
<a class="bbb" href="linkhere_893">
<span class="myclass">Text893</span>
<img data-lazy="https://link893.jpg"/>
</a>
</div>
<div class="myc">
<a class="bbb" href="linkhere_96">
<span class="myclass">Text96</span>
<img data-lazy="https://link96.jpg"/>
</a>
</div>
</div><!-- This closes a list that starts above -->
<h4 class="cat-title" id="55">Title text N1 <small> Title text N2.</small></h4>
<div class="list" id="55">
<div class="myc">
<a class="bbb" href="linkhere_34">
<span class="myclass">Text34</span>
<img data-lazy="https://link34.jpg"/>
</a>
</div>
<div class="myc">
...
</code>```

continuing both above and below.

How can I do this?

答:
You can try something like this:

```<code>from bs4 import BeautifulSoup

page = """
<html><body><p>
<span class="myclass">text 1</span>
<span class="myclass">text 2</span>
</p>
<h4 class="cat-title" id="55">
 Title text N1
 <small>
  Title text N2.
 </small>
</h4>

<p>
<span class="myclass">text 3</span>
<span class="myclass">text 4</span>
</p>
</body>
</html>
"""
soup = BeautifulSoup(page, 'html.parser')

for i in soup.find_all():
    if i.name == 'h4' and i.has_attr('class') and i['class'][0] == 'cat-title' and i.has_attr('id') and i['id'] == '55':
        if i.find("small") and i.find("small").text.strip()== "Title text N2.":
            break
    elif i.name == 'span'and i.has_attr('class') and i['class'][0] == 'myclass':
        print (i)
</code>```

Outputs:

```<code><span class="myclass">text 1</span>
<span class="myclass">text 2</span>
</code>```

Body:
I'm trying to extract a class tag from an HTML file, but only if it is located before a given stopping point. What I have is:

import requests
from bs4 import BeautifulSoup

page = requests.get("https://mysite")
soup = BeautifulSoup(page.content, 'html.parser')
class_extr = soup.find_all("span", class_="myclass")

This works, but it finds all instances of myclass, and i only want those before the following text shows in the soup:

 Title text N1

  Title text N2.

The thing that makes this block unique are the Title text N lines, especially the Title text N2. line. There are many cat-title tags before, so I can't use that as a stopping condition.

The code surrounding this block looks like this:

...

Text893

Text96

Title text N1  Title text N2.

Text34

...

continuing both above and below.

How can I do this?

Body:
You can try something like this:

from bs4 import BeautifulSoup

page = """
<html><body><p>
<span class="myclass">text 1</span>
<span class="myclass">text 2</span>
</p>
<h4 class="cat-title" id="55">
 Title text N1
 <small>
  Title text N2.
 </small>
</h4>

<p>
<span class="myclass">text 3</span>
<span class="myclass">text 4</span>
</p>
</body>
</html>
"""
soup = BeautifulSoup(page, 'html.parser')

for i in soup.find_all():
    if i.name == 'h4' and i.has_attr('class') and i['class'][0] == 'cat-title' and i.has_attr('id') and i['id'] == '55':
        if i.find("small") and i.find("small").text.strip()== "Title text N2.":
            break
    elif i.name == 'span'and i.has_attr('class') and i['class'][0] == 'myclass':
        print (i)

Outputs:

<span class="myclass">text 1</span>
<span class="myclass">text 2</span>


问:
Spring boot application hot reload with text editors
How to develop spring boot application with pure text editors? </p>

<p>And with hot reload after you save your source code file. With build tools like maven or gradle. </p>

答:
It turns out you could install spring-boot-devtools to your pom.xml before start.

Start your application with command line
$ mvn spring-boot:run

As long as your text-editor support auto compile, it will reload.

I am using vs code in this case. A java compiler will popup for installation while you edit your source code. Amazing.

Body:
How to develop spring boot application with pure text editors?

And with hot reload after you save your source code file. With build tools like maven or gradle.


问:
Find the position of a specific number that appear first in the list [python]
So I want to find a number that appears more than once in the list. I want the position of the first one.

Example: Say I want 3

```<code>     s = [1,2,3,4,5,3,9,8]  => s[2] appears first
</code>```

答:
```<code>def first_dup( seq ):
    # keep track of the positions
    seen = {}
    for pos,item in enumerate(seq):
        if item in seen:
            # saw it before, so its a duplicate
            return seen[item]
        else:
            # first time we see it, store the pos
            seen[item] = pos
</code>```

Body:
So I want to find a number that appears more than once in the list. I want the position of the first one.

Example: Say I want 3

     s = [1,2,3,4,5,3,9,8]  => s[2] appears first