问:
How can I change QGraphicsView background using check box
In this code,which change the QGraphicsView background.Now I need to change the background when I check true checkBox.When I set to checkBox to check true I need to set the background like this code.When I set checkBox to check false. I need to set QGraphicsView for normal default way. How can I do this.

here is my code:

mainwindow.cpp

```<code>#include "mainwindow.h"
#include <QGraphicsTextItem>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
{
    scene = new Scene(this);
    scene->setSceneRect(10,10,260,200);
    view = new QGraphicsView(scene);
    setCentralWidget(view);
}
</code>```

mainwindow.h

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

#include <QMainWindow>
#include <QGraphicsView>
#include "scene.h"
#include "customrectitem.h"

class MainWindow : public QMainWindow
{
public:
    explicit MainWindow(QWidget *parent = 0);
private:
    QGraphicsView* view;
    QGraphicsScene* scene;
};

#endif // MAINWINDOW_H
</code>```

Scene.h

```<code>#ifndef SCENE_H
#define SCENE_H

#include <QGraphicsScene>
#include <QPainter>
#include <QApplication>

class Scene : public QGraphicsScene
{
    Q_OBJECT
public:
    explicit Scene(QObject *parent = 0);
    int getGridSize() const {return this->gridSize;}

protected:
    void drawBackground (QPainter* painter, const QRectF &rect);
private:
    int gridSize;

};

#endif // SCENE_H
</code>```

Scene.cpp

```<code>#include "scene.h"

Scene::Scene(QObject *parent) : QGraphicsScene(parent), gridSize(20)
{
    Q_ASSERT(gridSize > 0);
}

void Scene::drawBackground(QPainter *painter, const QRectF &rect)
{
        QColor c (10,140,255,155);
        painter->setPen(c);
        qreal left = int(rect.left()) - (int(rect.left()) % gridSize);
        qreal top = int(rect.top()) - (int(rect.top()) % gridSize);
        QVarLengthArray<QLineF,100> lines;
        for (qreal x = left; x < rect.right(); x += gridSize)
            lines.append(QLineF(x,rect.top(),x,rect.bottom()));

        for (qreal y = top; y < rect.bottom(); y += gridSize)
            lines.append(QLineF(rect.left(),y,rect.right(),y));
        painter->drawLines(lines.data(),lines.size());
}
</code>```

答:
I have two opportunities in mind to draw a grid:

deriving a class from QGraphicsView and overloading the paintEvent() and drawing the grid before falling back to QGraphicsView::paintEvent()

adding the grid lines as scene items under a QGraphicsItemGroup which allows control of visibility.

The first method has the advantage that it can seamlessly adapt to any resizing of viewport.

This is my sample code testQGraphicsView-BgGrid.cc:

```<code>#include <QtWidgets>

class Canvas: public QGraphicsView {
  private:
    int _gridSize;
    QColor _gridColor;
    bool _gridVisible;

  public:
    explicit Canvas(QWidget *pQParent = nullptr):
      QGraphicsView(pQParent),
      _gridSize(20), _gridColor(0x0a8affu), _gridVisible(true)
    { }

    bool gridVisible() const { return _gridVisible; }
    void setGridVisible(bool gridVisible)
    {
      _gridVisible = gridVisible;
      viewport()->update();
    }

  protected:
    virtual void paintEvent(QPaintEvent *pQEvent) override
    {
      QPainter qPainter(viewport());
      if (_gridVisible) {
        const int wView = viewport()->width(), hView = viewport()->height();
        qPainter.setPen(_gridColor);
        for (int x = _gridSize / 2; x < wView; x += _gridSize) {
          qPainter.drawLine(x, 0, x, hView - 1);
        }
        for (int y = _gridSize / 2; y < hView; y += _gridSize) {
          qPainter.drawLine(0, y, wView - 1, y);
        }
      }
      QGraphicsView::paintEvent(pQEvent);
    }
};

void makeGrid(
  QGraphicsItemGroup &qItemGrp, const QSize &size,
  int gridSize = 20, const QColor &gridColor = 0x0a8affu)
{
  const int wView = size.width(), hView = size.height();
  for (int x = gridSize / 2; x < wView; x += gridSize) {
    QGraphicsLineItem *pQItem = new QGraphicsLineItem(x, 0, x, hView - 1);
    pQItem->setPen(gridColor);
    qItemGrp.addToGroup(pQItem);
  }
  for (int y = gridSize / 2; y < hView; y += gridSize) {
    QGraphicsLineItem *pQItem = new QGraphicsLineItem(0, y, wView - 1, y);
    pQItem->setPen(gridColor);
    qItemGrp.addToGroup(pQItem);
  }
}

int main(int argc, char **argv)
{
  QApplication app(argc, argv);
  // setup GUI
  QWidget qWnd;
  QGridLayout qGrid;
  QLabel qLblL(QString::fromUtf8("Grid as part of scene"));
  qGrid.addWidget(&qLblL, 0, 0);
  QCheckBox qTglGridL(QString::fromUtf8("Show Grid"));
  qGrid.addWidget(&qTglGridL, 0, 1);
  QGraphicsView qGraphView;
  qGrid.addWidget(&qGraphView, 1, 0, 1, 2);
  QLabel qLblR(QString::fromUtf8("Grid painted as background"));
  qGrid.addWidget(&qLblR, 0, 2);
  QCheckBox qTglGridR(QString::fromUtf8("Show Grid"));
  qGrid.addWidget(&qTglGridR, 0, 3);
  Canvas canvas;
  qGrid.addWidget(&canvas, 1, 2, 1, 2);
  qWnd.setLayout(&qGrid);
  qWnd.show();
  // init GUI
  QGraphicsScene qGraphSceneL;
  QGraphicsItemGroup qItemGrid;
  makeGrid(qItemGrid, qGraphView.viewport()->size());
  qGraphSceneL.addItem(&qItemGrid);
  qGraphView.setScene(&qGraphSceneL);
  qTglGridL.setCheckState(
    qItemGrid.isVisible() ? Qt::Checked : Qt::Unchecked);
  qTglGridR.setCheckState(
    canvas.gridVisible() ? Qt::Checked : Qt::Unchecked);
  // install signal handlers
  QObject::connect(&qTglGridL, &QCheckBox::stateChanged,
    [&qItemGrid](int state)
    {
      qItemGrid.setVisible(state != Qt::Unchecked);
    });
  QObject::connect(&qTglGridR, &QCheckBox::stateChanged,
    [&canvas](int state)
    {
      canvas.setGridVisible(state != Qt::Unchecked);
    });
  // runtime loop
  return app.exec();
}
</code>```

Compiled with VS2013 and Qt 5.9.2, tested on Window 10 (64 bit):

Update:

The QMake script testQGraphicsView-BgGrid.pro:

SOURCES = testQGraphicsView-BgGrid.cc

QT += widgets
```

<p>Building and testing in <code>bash</code> on cygwin:</p>

<pre class="lang-none prettyprint-override"><code>$ qmake-qt5 testQGraphicsView-BgGrid.pro

$ make
g++ -c -fno-keep-inline-dllexport -D_GNU_SOURCE -pipe -O2 -Wall -W -D_REENTRANT -DQT_NO_DEBUG -DQT_WIDGETS_LIB -DQT_GUI_LIB -DQT_CORE_LIB -I. -isystem /usr/include/qt5 -isystem /usr/include/qt5/QtWidgets -isystem /usr/include/qt5/QtGui -isystem /usr/include/qt5/QtCore -I. -I/usr/lib/qt5/mkspecs/cygwin-g++ -o testQGraphicsView-BgGrid.o testQGraphicsView-BgGrid.cc
g++  -o testQGraphicsView-BgGrid.exe testQGraphicsView-BgGrid.o   -lQt5Widgets -lQt5Gui -lQt5Core -lGL -lpthread

$ ./testQGraphicsView-BgGrid
</code>```

The same program as X11 application:

Yet Another Update:

I've to admit that, in my first version, I focused on How can I change QGraphicsView background using check box with emphasis on check box ignoring QGraphicsScene::drawBackground() (which I didn't know) and ignoring issues in the grid rendering itself (which I used instead). As pointed out in eyllanesc's answer, both showed solutions offer some weaknesses which (at least) I should have documented.

The left view (which involves the grid into scene) doesn't necessarily fill the viewport(). IMHO, this is acceptable if the grid fills the relevant range which is used by scene. (It might be intended to visualize that the scene covers only a part of the viewport().) However, the argument const QSize &size of makeGrid() was an unlucky choice concerning this intention. I fixed this design issue by replacing it with const QRect &rect.

The right view (which overloads paintEvent()) didn't consider possible scrolling of scene. I fixed this by mapping the upper left corner to scene coordinates (const QPointF offs = mapToScene(0, 0);) and consider the offset as start value in the loops.

The update sample code testQGrapicsView-BgGrid.cc:

```<code>#include <QtWidgets>

class Canvas: public QGraphicsView {
  private:
    int _gridSize;
    QColor _gridColor;
    bool _gridVisible;

  public:
    explicit Canvas(QWidget *pQParent = nullptr):
      QGraphicsView(pQParent),
      _gridSize(20), _gridColor(0x0a8affu), _gridVisible(true)
    { }

    bool gridVisible() const { return _gridVisible; }
    void setGridVisible(bool gridVisible)
    {
      _gridVisible = gridVisible;
      viewport()->update();
    }

  protected:
    virtual void paintEvent(QPaintEvent *pQEvent) override
    {
      QPainter qPainter(viewport());
      if (_gridVisible) {
        const int wView = viewport()->width(), hView = viewport()->height();
        const QPointF offs = mapToScene(0, 0);
        qPainter.setPen(_gridColor);
        for (int x = (int)offs.x() % _gridSize; x < wView; x += _gridSize) {
          qPainter.drawLine(x, 0, x, hView - 1);
        }
        for (int y = (int)offs.y() % _gridSize; y < hView; y += _gridSize) {
          qPainter.drawLine(0, y, wView - 1, y);
        }
      }
      QGraphicsView::paintEvent(pQEvent);
    }
};

void makeGrid(
  QGraphicsItemGroup &qItemGrp, const QRect &rect,
  int gridSize = 20, const QColor &gridColor = 0x0a8affu)
{
  for (int x = rect.x(), xE = x + rect.width(); x < xE; x += gridSize) {
    QGraphicsLineItem *pQItem
      = new QGraphicsLineItem(x, rect.y(), x, rect.height() - 1);
    pQItem->setPen(gridColor);
    qItemGrp.addToGroup(pQItem);
  }
  for (int y = rect.y(), yE = y + rect.height(); y < yE; y += gridSize) {
    QGraphicsLineItem *pQItem
      = new QGraphicsLineItem(rect.x(), y, rect.width() - 1, y);
    pQItem->setPen(gridColor);
    qItemGrp.addToGroup(pQItem);
  }
}

int main(int argc, char **argv)
{
  QApplication app(argc, argv);
  // setup GUI
  QWidget qWnd;
  QGridLayout qGrid;
  QLabel qLblL(QString::fromUtf8("Grid as part of scene"));
  qGrid.addWidget(&qLblL, 0, 0);
  QCheckBox qTglGridL(QString::fromUtf8("Show Grid"));
  qGrid.addWidget(&qTglGridL, 0, 1);
  QGraphicsView qGraphView;
  qGrid.addWidget(&qGraphView, 1, 0, 1, 2);
  QLabel qLblR(QString::fromUtf8("Grid painted as background"));
  qGrid.addWidget(&qLblR, 0, 2);
  QCheckBox qTglGridR(QString::fromUtf8("Show Grid"));
  qGrid.addWidget(&qTglGridR, 0, 3);
  Canvas canvas;
  qGrid.addWidget(&canvas, 1, 2, 1, 2);
  qWnd.setLayout(&qGrid);
  qWnd.show();
  // init GUI
  QGraphicsScene qGraphSceneL;
  QGraphicsItemGroup qItemGrid;
  makeGrid(qItemGrid, QRect(0, 0, 320, 240));
  qGraphSceneL.addItem(&qItemGrid);
  qGraphView.setScene(&qGraphSceneL);
  qTglGridL.setCheckState(
    qItemGrid.isVisible() ? Qt::Checked : Qt::Unchecked);
  qTglGridR.setCheckState(
    canvas.gridVisible() ? Qt::Checked : Qt::Unchecked);
  // install signal handlers
  QObject::connect(&qTglGridL, &QCheckBox::stateChanged,
    [&qItemGrid](int state)
    {
      qItemGrid.setVisible(state != Qt::Unchecked);
    });
  QObject::connect(&qTglGridR, &QCheckBox::stateChanged,
    [&canvas](int state)
    {
      canvas.setGridVisible(state != Qt::Unchecked);
    });
  // runtime loop
  return app.exec();
}
</code>```

The following snapshots show the application after start and after resizing:

Body:
In this code,which change the QGraphicsView background.Now I need to change the background when I check true checkBox.When I set to checkBox to check true I need to set the background like this code.When I set checkBox to check false. I need to set QGraphicsView for normal default way. How can I do this.

here is my code:

mainwindow.cpp

#include "mainwindow.h"
#include <QGraphicsTextItem>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
{
    scene = new Scene(this);
    scene->setSceneRect(10,10,260,200);
    view = new QGraphicsView(scene);
    setCentralWidget(view);
}

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QGraphicsView>
#include "scene.h"
#include "customrectitem.h"

class MainWindow : public QMainWindow
{
public:
    explicit MainWindow(QWidget *parent = 0);
private:
    QGraphicsView* view;
    QGraphicsScene* scene;
};

#endif // MAINWINDOW_H

Scene.h

#ifndef SCENE_H
#define SCENE_H

#include <QGraphicsScene>
#include <QPainter>
#include <QApplication>

class Scene : public QGraphicsScene
{
    Q_OBJECT
public:
    explicit Scene(QObject *parent = 0);
    int getGridSize() const {return this->gridSize;}

protected:
    void drawBackground (QPainter* painter, const QRectF &rect);
private:
    int gridSize;

};

#endif // SCENE_H

Scene.cpp

#include "scene.h"

Scene::Scene(QObject *parent) : QGraphicsScene(parent), gridSize(20)
{
    Q_ASSERT(gridSize > 0);
}

void Scene::drawBackground(QPainter *painter, const QRectF &rect)
{
        QColor c (10,140,255,155);
        painter->setPen(c);
        qreal left = int(rect.left()) - (int(rect.left()) % gridSize);
        qreal top = int(rect.top()) - (int(rect.top()) % gridSize);
        QVarLengthArray<QLineF,100> lines;
        for (qreal x = left; x < rect.right(); x += gridSize)
            lines.append(QLineF(x,rect.top(),x,rect.bottom()));

        for (qreal y = top; y < rect.bottom(); y += gridSize)
            lines.append(QLineF(rect.left(),y,rect.right(),y));
        painter->drawLines(lines.data(),lines.size());
}

Body:
I have two opportunities in mind to draw a grid:

deriving a class from QGraphicsView and overloading the paintEvent() and drawing the grid before falling back to QGraphicsView::paintEvent()

adding the grid lines as scene items under a QGraphicsItemGroup which allows control of visibility.

The first method has the advantage that it can seamlessly adapt to any resizing of viewport.

This is my sample code testQGraphicsView-BgGrid.cc:

#include <QtWidgets>

class Canvas: public QGraphicsView {
  private:
    int _gridSize;
    QColor _gridColor;
    bool _gridVisible;

  public:
    explicit Canvas(QWidget *pQParent = nullptr):
      QGraphicsView(pQParent),
      _gridSize(20), _gridColor(0x0a8affu), _gridVisible(true)
    { }

    bool gridVisible() const { return _gridVisible; }
    void setGridVisible(bool gridVisible)
    {
      _gridVisible = gridVisible;
      viewport()->update();
    }

  protected:
    virtual void paintEvent(QPaintEvent *pQEvent) override
    {
      QPainter qPainter(viewport());
      if (_gridVisible) {
        const int wView = viewport()->width(), hView = viewport()->height();
        qPainter.setPen(_gridColor);
        for (int x = _gridSize / 2; x < wView; x += _gridSize) {
          qPainter.drawLine(x, 0, x, hView - 1);
        }
        for (int y = _gridSize / 2; y < hView; y += _gridSize) {
          qPainter.drawLine(0, y, wView - 1, y);
        }
      }
      QGraphicsView::paintEvent(pQEvent);
    }
};

void makeGrid(
  QGraphicsItemGroup &qItemGrp, const QSize &size,
  int gridSize = 20, const QColor &gridColor = 0x0a8affu)
{
  const int wView = size.width(), hView = size.height();
  for (int x = gridSize / 2; x < wView; x += gridSize) {
    QGraphicsLineItem *pQItem = new QGraphicsLineItem(x, 0, x, hView - 1);
    pQItem->setPen(gridColor);
    qItemGrp.addToGroup(pQItem);
  }
  for (int y = gridSize / 2; y < hView; y += gridSize) {
    QGraphicsLineItem *pQItem = new QGraphicsLineItem(0, y, wView - 1, y);
    pQItem->setPen(gridColor);
    qItemGrp.addToGroup(pQItem);
  }
}

int main(int argc, char **argv)
{
  QApplication app(argc, argv);
  // setup GUI
  QWidget qWnd;
  QGridLayout qGrid;
  QLabel qLblL(QString::fromUtf8("Grid as part of scene"));
  qGrid.addWidget(&qLblL, 0, 0);
  QCheckBox qTglGridL(QString::fromUtf8("Show Grid"));
  qGrid.addWidget(&qTglGridL, 0, 1);
  QGraphicsView qGraphView;
  qGrid.addWidget(&qGraphView, 1, 0, 1, 2);
  QLabel qLblR(QString::fromUtf8("Grid painted as background"));
  qGrid.addWidget(&qLblR, 0, 2);
  QCheckBox qTglGridR(QString::fromUtf8("Show Grid"));
  qGrid.addWidget(&qTglGridR, 0, 3);
  Canvas canvas;
  qGrid.addWidget(&canvas, 1, 2, 1, 2);
  qWnd.setLayout(&qGrid);
  qWnd.show();
  // init GUI
  QGraphicsScene qGraphSceneL;
  QGraphicsItemGroup qItemGrid;
  makeGrid(qItemGrid, qGraphView.viewport()->size());
  qGraphSceneL.addItem(&qItemGrid);
  qGraphView.setScene(&qGraphSceneL);
  qTglGridL.setCheckState(
    qItemGrid.isVisible() ? Qt::Checked : Qt::Unchecked);
  qTglGridR.setCheckState(
    canvas.gridVisible() ? Qt::Checked : Qt::Unchecked);
  // install signal handlers
  QObject::connect(&qTglGridL, &QCheckBox::stateChanged,
    [&qItemGrid](int state)
    {
      qItemGrid.setVisible(state != Qt::Unchecked);
    });
  QObject::connect(&qTglGridR, &QCheckBox::stateChanged,
    [&canvas](int state)
    {
      canvas.setGridVisible(state != Qt::Unchecked);
    });
  // runtime loop
  return app.exec();
}

Compiled with VS2013 and Qt 5.9.2, tested on Window 10 (64 bit):

Update:

The QMake script testQGraphicsView-BgGrid.pro:

SOURCES = testQGraphicsView-BgGrid.cc

QT += widgets

Building and testing in bash on cygwin:

$ qmake-qt5 testQGraphicsView-BgGrid.pro

$ make
g++ -c -fno-keep-inline-dllexport -D_GNU_SOURCE -pipe -O2 -Wall -W -D_REENTRANT -DQT_NO_DEBUG -DQT_WIDGETS_LIB -DQT_GUI_LIB -DQT_CORE_LIB -I. -isystem /usr/include/qt5 -isystem /usr/include/qt5/QtWidgets -isystem /usr/include/qt5/QtGui -isystem /usr/include/qt5/QtCore -I. -I/usr/lib/qt5/mkspecs/cygwin-g++ -o testQGraphicsView-BgGrid.o testQGraphicsView-BgGrid.cc
g++  -o testQGraphicsView-BgGrid.exe testQGraphicsView-BgGrid.o   -lQt5Widgets -lQt5Gui -lQt5Core -lGL -lpthread

$ ./testQGraphicsView-BgGrid

The same program as X11 application:

Yet Another Update:

I've to admit that, in my first version, I focused on How can I change QGraphicsView background using check box with emphasis on check box ignoring QGraphicsScene::drawBackground() (which I didn't know) and ignoring issues in the grid rendering itself (which I used instead). As pointed out in eyllanesc's answer, both showed solutions offer some weaknesses which (at least) I should have documented.

The left view (which involves the grid into scene) doesn't necessarily fill the viewport(). IMHO, this is acceptable if the grid fills the relevant range which is used by scene. (It might be intended to visualize that the scene covers only a part of the viewport().) However, the argument const QSize &size of makeGrid() was an unlucky choice concerning this intention. I fixed this design issue by replacing it with const QRect &rect.

The right view (which overloads paintEvent()) didn't consider possible scrolling of scene. I fixed this by mapping the upper left corner to scene coordinates (const QPointF offs = mapToScene(0, 0);) and consider the offset as start value in the loops.

The update sample code testQGrapicsView-BgGrid.cc:

#include <QtWidgets>

class Canvas: public QGraphicsView {
  private:
    int _gridSize;
    QColor _gridColor;
    bool _gridVisible;

  public:
    explicit Canvas(QWidget *pQParent = nullptr):
      QGraphicsView(pQParent),
      _gridSize(20), _gridColor(0x0a8affu), _gridVisible(true)
    { }

    bool gridVisible() const { return _gridVisible; }
    void setGridVisible(bool gridVisible)
    {
      _gridVisible = gridVisible;
      viewport()->update();
    }

  protected:
    virtual void paintEvent(QPaintEvent *pQEvent) override
    {
      QPainter qPainter(viewport());
      if (_gridVisible) {
        const int wView = viewport()->width(), hView = viewport()->height();
        const QPointF offs = mapToScene(0, 0);
        qPainter.setPen(_gridColor);
        for (int x = (int)offs.x() % _gridSize; x < wView; x += _gridSize) {
          qPainter.drawLine(x, 0, x, hView - 1);
        }
        for (int y = (int)offs.y() % _gridSize; y < hView; y += _gridSize) {
          qPainter.drawLine(0, y, wView - 1, y);
        }
      }
      QGraphicsView::paintEvent(pQEvent);
    }
};

void makeGrid(
  QGraphicsItemGroup &qItemGrp, const QRect &rect,
  int gridSize = 20, const QColor &gridColor = 0x0a8affu)
{
  for (int x = rect.x(), xE = x + rect.width(); x < xE; x += gridSize) {
    QGraphicsLineItem *pQItem
      = new QGraphicsLineItem(x, rect.y(), x, rect.height() - 1);
    pQItem->setPen(gridColor);
    qItemGrp.addToGroup(pQItem);
  }
  for (int y = rect.y(), yE = y + rect.height(); y < yE; y += gridSize) {
    QGraphicsLineItem *pQItem
      = new QGraphicsLineItem(rect.x(), y, rect.width() - 1, y);
    pQItem->setPen(gridColor);
    qItemGrp.addToGroup(pQItem);
  }
}

int main(int argc, char **argv)
{
  QApplication app(argc, argv);
  // setup GUI
  QWidget qWnd;
  QGridLayout qGrid;
  QLabel qLblL(QString::fromUtf8("Grid as part of scene"));
  qGrid.addWidget(&qLblL, 0, 0);
  QCheckBox qTglGridL(QString::fromUtf8("Show Grid"));
  qGrid.addWidget(&qTglGridL, 0, 1);
  QGraphicsView qGraphView;
  qGrid.addWidget(&qGraphView, 1, 0, 1, 2);
  QLabel qLblR(QString::fromUtf8("Grid painted as background"));
  qGrid.addWidget(&qLblR, 0, 2);
  QCheckBox qTglGridR(QString::fromUtf8("Show Grid"));
  qGrid.addWidget(&qTglGridR, 0, 3);
  Canvas canvas;
  qGrid.addWidget(&canvas, 1, 2, 1, 2);
  qWnd.setLayout(&qGrid);
  qWnd.show();
  // init GUI
  QGraphicsScene qGraphSceneL;
  QGraphicsItemGroup qItemGrid;
  makeGrid(qItemGrid, QRect(0, 0, 320, 240));
  qGraphSceneL.addItem(&qItemGrid);
  qGraphView.setScene(&qGraphSceneL);
  qTglGridL.setCheckState(
    qItemGrid.isVisible() ? Qt::Checked : Qt::Unchecked);
  qTglGridR.setCheckState(
    canvas.gridVisible() ? Qt::Checked : Qt::Unchecked);
  // install signal handlers
  QObject::connect(&qTglGridL, &QCheckBox::stateChanged,
    [&qItemGrid](int state)
    {
      qItemGrid.setVisible(state != Qt::Unchecked);
    });
  QObject::connect(&qTglGridR, &QCheckBox::stateChanged,
    [&canvas](int state)
    {
      canvas.setGridVisible(state != Qt::Unchecked);
    });
  // runtime loop
  return app.exec();
}

The following snapshots show the application after start and after resizing:


来源: stackexchange

问:
Set select option 'selected', by value
I have a select field with some options in it. Now I need to select one of those options with jQuery. But how can I do that when I only know the value of the option that must be selected?

I have the following HTML:

  <select>
    <option value="val1">Val 1</option>
    <option value="val2">Val 2</option>
    <option value="val3">Val 3</option>
  </select>

```

I need to select the option with value val2. How can this be done?

Here's a demo page:
http://jsfiddle.net/9Stxb/

答:
A simple answer is, in HTML:

<select name="ukuran" id="idUkuran">
    <option value="1000">pilih ukuran</option>
    <option value="11">M</option>
    <option value="12">L</option>
    <option value="13">XL</option>
</select>
```
<p>In jQuery, call the below function by a button or whatever</p>
```$('#idUkuran').val(11).change();
```

It is simple and 100% works, because it's taken from my work... :)

ContentLicense: CC BY-SA 4.0

Title: Set select option 'selected', by value

Body:
I have a select field with some options in it. Now I need to select one of those options with jQuery. But how can I do that when I only know the value of the option that must be selected?

I have the following HTML:

  <select>
    <option value="val1">Val 1</option>
    <option value="val2">Val 2</option>
    <option value="val3">Val 3</option>
  </select>

I need to select the option with value val2. How can this be done?

Here's a demo page:
http://jsfiddle.net/9Stxb/

Body:
A simple answer is, in HTML:

<select name="ukuran" id="idUkuran">
    <option value="1000">pilih ukuran</option>
    <option value="11">M</option>
    <option value="12">L</option>
    <option value="13">XL</option>
</select>

In jQuery, call the below function by a button or whatever

$('#idUkuran').val(11).change();

It is simple and 100% works, because it's taken from my work... :)


问:
R - Spatial Join Between SpatialPoints (GPS coordinates) and SpatialLinesDataFrame
I am working on a university project which combines data science and GIS. We need to find an open-source solution capable of obtaining additional information from a massive GPS coordinates dataset. Clearly, I cannot use any API with daily request limit.

THE DATA

Here you can find a sample of the dataset the Professor provided us:

```<code>longitude <- c(10.86361, 10.96062, 10.93032, 10.93103, 10.93212)
latitude <- c(44.53355, 44.63234, 44.63470, 44.63634, 44.64559)
longlat <- data.frame(longitude, latitude)
ID <- seq.int(1, 10)
</code>```

FIRST TASK: Already Accomplished!

The first step was joining my SpatialPoints with a SpatialPolygonsDataFrame using over() of rgeos. The SpatialPolygonsDataFrame was obtained through getData('GADM', country='ITA', level=3) of rgeos.

For this first accomplished task, the objective was to associate to each GPS coordinates the information about City and Region which they belong to.

An example of the result I was able to obtain is:

```<code>require(sp)
require(rgeos)
my_spdf <- SpatialPointsDataFrame(coords = longlat, data = ID, proj4string = CRS(" +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0 "))
italy_administrative_boundaries_level3 <- getData('GADM', country='ITA', level=3)
result <- over(my_spdf, italy_administrative_boundaries_level3)[, c("NAME_0", "NAME_1", "NAME_2", "NAME_3")]
result$ID <- ID
print(result)
</code>```

SECOND TASK: MY QUESTION

Now the stuff become tricky because I need to associate additional and deeper information like road_name and road_type.

This information are contained in the shapefiles created on OpenStreetMap and available at: download.geofabrik.de/europe/italy.html.
I loaded the shapefile in R obtaining a SpatialLinesDataFrame:

```<code>require(rgdal)
shapefile_roads <- readOGR(dsn = "./road", layer = "roads")
</code>```

Then, I naively tried to apply the same technique as for joining SpatialPoints and SpatialPolygonsDataFrame:

```<code>result <- over(my_spdf, shapefile_roads)
</code>```

Clearly, the result is just NA. One possible reason that came into my mind was that the coordinates of my_df are not in the exact position of the Lines in shapefile_roads, therefore, I should need some kind of radius parameter. However, I am not really sure.

Can you suggest me the correct approach to perform this spatial join between my SpatialPoints and the attributes of the SpatialLinesDataFrame obtained from the road_shapefile of OpenStreetMap?

Please if something is not very clear do not hesitate to ask.

答:
Your example data

```<code>library(raster)
longitude <- c(10.86361, 10.96062, 10.93032, 10.93103, 10.93212)
latitude <- c(44.53355, 44.63234, 44.63470, 44.63634, 44.64559)
longlat <- data.frame(longitude, latitude)
ID <- data.frame(ID=1:5)
ita_gadm3 <- getData('GADM', country='ITA', level=3)[, c("NAME_0", "NAME_1", "NAME_2", "NAME_3")]
 #use `sp::over` or `raster::extract`
 result <- extract(ita_gadm3, longlat)
</code>```

Some roads:

```<code>road <- spLines(cbind(longitude+.1, latitude), cbind(longitude-.1, rev(latitude)), cbind(longitude-.1, latitude+1), crs=crs(ita_gadm3))
</code>```

Now find the nearest road segment. You can use geosphere::dist2Line because you are using angular (lon/lat) coordinates.

```<code>library(geosphere)
geosphere::dist2Line(longlat, road)
#     distance      lon      lat ID
#[1,] 2498.825 10.83212 44.53355  2
#[2,] 5527.646 11.03032 44.63470  1
#[3,] 5524.227 10.86062 44.63634  2
#[4,] 5577.372 10.86062 44.63634  2
#[5,] 5756.113 10.86062 44.63634  2
</code>```

Note the variable ID which refers back to the roads. The problem is that dist2line is currently slow and you have a large data set.

The alternative is to transform your spatial data to a planar coordinate system appropriate for Italy and use gDistance.

```<code>library(rgeos)
library(rgeos)
sp <- SpatialPoints(longlat, proj4string=crs(ita_gadm3))
spita <- spTransform(sp, "+proj=tmerc +lat_0=0 +lon_0=15 +k=0.9996 +x_0=2520000 +y_0=0 +ellps=intl +units=m")
rdita <- spTransform(road, "+proj=tmerc +lat_0=0 +lon_0=15 +k=0.9996 +x_0=2520000 +y_0=0 +ellps=intl +units=m")

gd <- gDistance(rdita, spita, byid=TRUE)
a <- apply(gd, 1, which.min)
a
#1 2 3 4 5
#2 1 2 2 2
</code>```

That is, point 2 is closest to road 1. The other points are closest to road 2.
You probably need to do that in batches of points or tiles to avoid getting a distance matrix that is too large.

The buffer solution suggested by Sébastien could work in principle, but gets really complicated as there is no good buffer size. At the one hand, points may be outside any buffer and, at the other hand, they may overlap with several buffers. If you use buffers, sp::over returns an arbitrary match if there are multiple matches, whereas raster::extract will return them all. Neither is pretty, and I would avoid this approach. Illustrated here:

```<code>b <- buffer(road, width=.15, dissolve=F)
plot(b)
lines(road, col='red', lwd=2)
points(longlat, pch=20, col='blue')

extract(b, longlat)
#   point.ID poly.ID
#1         1       1
#2         1       2
#3         2       2
#4         2       1
#5         3       2
#6         3       1
#7         4       2
#8         4       1
#9         5       1
#10        5       2

over(sp, b)
#1 2 3 4 5
#2 2 2 2 2
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am working on a university project which combines data science and GIS. We need to find an open-source solution capable of obtaining additional information from a massive GPS coordinates dataset. Clearly, I cannot use any API with daily request limit.

THE DATA

Here you can find a sample of the dataset the Professor provided us:

longitude <- c(10.86361, 10.96062, 10.93032, 10.93103, 10.93212)
latitude <- c(44.53355, 44.63234, 44.63470, 44.63634, 44.64559)
longlat <- data.frame(longitude, latitude)
ID <- seq.int(1, 10)

FIRST TASK: Already Accomplished!

The first step was joining my SpatialPoints with a SpatialPolygonsDataFrame using over() of rgeos. The SpatialPolygonsDataFrame was obtained through getData('GADM', country='ITA', level=3) of rgeos.

For this first accomplished task, the objective was to associate to each GPS coordinates the information about City and Region which they belong to.

An example of the result I was able to obtain is:

require(sp)
require(rgeos)
my_spdf <- SpatialPointsDataFrame(coords = longlat, data = ID, proj4string = CRS(" +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0 "))
italy_administrative_boundaries_level3 <- getData('GADM', country='ITA', level=3)
result <- over(my_spdf, italy_administrative_boundaries_level3)[, c("NAME_0", "NAME_1", "NAME_2", "NAME_3")]
result$ID <- ID
print(result)

SECOND TASK: MY QUESTION

Now the stuff become tricky because I need to associate additional and deeper information like road_name and road_type.

This information are contained in the shapefiles created on OpenStreetMap and available at: download.geofabrik.de/europe/italy.html.
I loaded the shapefile in R obtaining a SpatialLinesDataFrame:

require(rgdal)
shapefile_roads <- readOGR(dsn = "./road", layer = "roads")

Then, I naively tried to apply the same technique as for joining SpatialPoints and SpatialPolygonsDataFrame:

result <- over(my_spdf, shapefile_roads)

Clearly, the result is just NA. One possible reason that came into my mind was that the coordinates of my_df are not in the exact position of the Lines in shapefile_roads, therefore, I should need some kind of radius parameter. However, I am not really sure.

Can you suggest me the correct approach to perform this spatial join between my SpatialPoints and the attributes of the SpatialLinesDataFrame obtained from the road_shapefile of OpenStreetMap?

Please if something is not very clear do not hesitate to ask.

Body:
Your example data

library(raster)
longitude <- c(10.86361, 10.96062, 10.93032, 10.93103, 10.93212)
latitude <- c(44.53355, 44.63234, 44.63470, 44.63634, 44.64559)
longlat <- data.frame(longitude, latitude)
ID <- data.frame(ID=1:5)
ita_gadm3 <- getData('GADM', country='ITA', level=3)[, c("NAME_0", "NAME_1", "NAME_2", "NAME_3")]
 #use `sp::over` or `raster::extract`
 result <- extract(ita_gadm3, longlat)

Some roads:

road <- spLines(cbind(longitude+.1, latitude), cbind(longitude-.1, rev(latitude)), cbind(longitude-.1, latitude+1), crs=crs(ita_gadm3))

Now find the nearest road segment. You can use geosphere::dist2Line because you are using angular (lon/lat) coordinates.

library(geosphere)
geosphere::dist2Line(longlat, road)
#     distance      lon      lat ID
#[1,] 2498.825 10.83212 44.53355  2
#[2,] 5527.646 11.03032 44.63470  1
#[3,] 5524.227 10.86062 44.63634  2
#[4,] 5577.372 10.86062 44.63634  2
#[5,] 5756.113 10.86062 44.63634  2

Note the variable ID which refers back to the roads. The problem is that dist2line is currently slow and you have a large data set.

The alternative is to transform your spatial data to a planar coordinate system appropriate for Italy and use gDistance.

library(rgeos)
library(rgeos)
sp <- SpatialPoints(longlat, proj4string=crs(ita_gadm3))
spita <- spTransform(sp, "+proj=tmerc +lat_0=0 +lon_0=15 +k=0.9996 +x_0=2520000 +y_0=0 +ellps=intl +units=m")
rdita <- spTransform(road, "+proj=tmerc +lat_0=0 +lon_0=15 +k=0.9996 +x_0=2520000 +y_0=0 +ellps=intl +units=m")

gd <- gDistance(rdita, spita, byid=TRUE)
a <- apply(gd, 1, which.min)
a
#1 2 3 4 5
#2 1 2 2 2

That is, point 2 is closest to road 1. The other points are closest to road 2.
You probably need to do that in batches of points or tiles to avoid getting a distance matrix that is too large.

The buffer solution suggested by Sébastien could work in principle, but gets really complicated as there is no good buffer size. At the one hand, points may be outside any buffer and, at the other hand, they may overlap with several buffers. If you use buffers, sp::over returns an arbitrary match if there are multiple matches, whereas raster::extract will return them all. Neither is pretty, and I would avoid this approach. Illustrated here:

b <- buffer(road, width=.15, dissolve=F)
plot(b)
lines(road, col='red', lwd=2)
points(longlat, pch=20, col='blue')

extract(b, longlat)
#   point.ID poly.ID
#1         1       1
#2         1       2
#3         2       2
#4         2       1
#5         3       2
#6         3       1
#7         4       2
#8         4       1
#9         5       1
#10        5       2

over(sp, b)
#1 2 3 4 5
#2 2 2 2 2


问:
rspec stack trace on autotest
I'm just getting into autotest and i have the following problem.

How do I get autotest to print stack traces on errors.
If i run "rake spec" i get output

```<code>  4) Transaction should get date with poor form
 Failure/Error: transaction = Transaction.build_from_email(@email)
 NoMethodError:
   private method `gsub' called for 112:Fixnum
 # ./app/models/transaction.rb:46:in `build_from_email'
 # ./spec/models/transaction_spec.rb:104
</code>```

but i get the following with autotest

```<code>  4) Transaction should get date with poor form
 Failure/Error: transaction = Transaction.build_from_email(@email)
 NoMethodError:
   private method `gsub' called for 112:Fixnum
</code>```

Would just be alot easier to find where the error is.

Thanks a bunch

答:
If you're using RSpec 2 you can add a file called .rspec in the project root with this content:

```<code>--backtrace
</code>```

RSpec will read this file when it's run, whether it's through Rake or Autotest.

ContentLicense: CC BY-SA 2.5

Title: rspec stack trace on autotest

Body:
I'm just getting into autotest and i have the following problem.

How do I get autotest to print stack traces on errors.
If i run "rake spec" i get output

  4) Transaction should get date with poor form
 Failure/Error: transaction = Transaction.build_from_email(@email)
 NoMethodError:
   private method `gsub' called for 112:Fixnum
 # ./app/models/transaction.rb:46:in `build_from_email'
 # ./spec/models/transaction_spec.rb:104

but i get the following with autotest

  4) Transaction should get date with poor form
 Failure/Error: transaction = Transaction.build_from_email(@email)
 NoMethodError:
   private method `gsub' called for 112:Fixnum

Would just be alot easier to find where the error is.

Thanks a bunch

Body:
If you're using RSpec 2 you can add a file called .rspec in the project root with this content:

--backtrace

RSpec will read this file when it's run, whether it's through Rake or Autotest.


问:
org.springframework.context.NoSuchMessageException on I18N properties
I was trying to understand the concept of internationalization (I18N) in spring framework by deploying a simple dynamic web project. I am getting an unsolvable problem. Following were the jar files used:

```<code>*commons-logging.jar
*org.springframework.asm-3.0.1.RELEASE.jar
*org.springframework.asm-sources-3.0.1.RELEASE.jar
*org.springframework.beans-3.0.1.RELEASE.jar
*org.springframework.beans-sources-3.0.1.RELEASE.jar
*org.springframework.context-3.0.1.RELEASE.jar
*org.springframework.context-sources-3.0.1.RELEASE.jar
*org.springframework.core-3.0.1.RELEASE.jar
*org.springframework.core-sources-3.0.1.RELEASE.jar
*org.springframework.expression-3.0.1.RELEASE.jar
*org.springframework.expression-sources-3.0.1.RELEASE.jar
</code>```

Following were the properties files:

Data_ka.properties

```<code>label=ಹೆಸರು
</code>```

Data_hi.properties

```<code>label=नाम्
</code>```

XML file:

spring.xml

```<code><!-- spring - I18N deomo -->
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
            "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename" value="resources/Data" />
    </bean>
</beans>
</code>```

JSP file:

index.jsp

```<code><%@page import="org.springframework.context.support.ClassPathXmlApplicationContext"%>
<%@page import="org.springframework.context.ApplicationContext"%>
<%@page import="java.util.Locale"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

 <%
    String lang= request.getHeader("accept-language");
    Locale locale = new Locale(lang);
    ApplicationContext ap = new ClassPathXmlApplicationContext("resources/spring.xml");
    String value = ap.getMessage("label",null,locale);
 %>

 <form action="./hello">
    <%= value %> :<input type="text" name="name" />
                <input type="submit" value="submit">
 </form>
</code>```

I am getting errors in my console as follows:

Dec 09, 2017 10:45:49 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre1.8.0_151\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jre1.8.0_151/bin/server;C:/Program Files/Java/jre1.8.0_151/bin;C:/Program Files/Java/jre1.8.0_151/lib/amd64;C:\ProgramData\Oracle\Java\javapath;C:\oraclexe\app\oracle\product\11.2.0\server\bin;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Java\jdk1.8.0_73\bin;C:\apache-ant-1.9.6-bin\apache-ant-1.9.6\bin;C:\WINDOWS\system32\config\systemprofile\.dnx\bin;C:\Program Files\Microsoft DNX\Dnvm\;C:\Program Files (x86)\Skype\Phone\;C:\apache-opennlp-1.7.2\bin;C:\Program Files\MySQL\MySQL Utilities 1.6\;%JAVA_HOME%\bin;%HADOOP_HOME%\bin;%HADOOP_BIN_PATH%;C:\Users\Nithin\Anaconda3;C:\Users\Nithin\Anaconda3\Scripts;C:\Users\Nithin\Anaconda3\Library\bin;C:\Users\Nithin\AppData\Local\Microsoft\WindowsApps;;C:\eclipse-jee-neon-2-win32-x86_64\eclipse;;.
Dec 09, 2017 10:45:50 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:Spring1_IOC7_I18N' did not find a matching property.
Dec 09, 2017 10:45:53 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-80"]
Dec 09, 2017 10:45:54 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Dec 09, 2017 10:45:54 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 5091 ms
Dec 09, 2017 10:45:54 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Dec 09, 2017 10:45:54 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.34
Dec 09, 2017 10:46:01 PM org.apache.catalina.util.SessionIdGenerator createSecureRandom
INFO: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [3,560] milliseconds.
Dec 09, 2017 10:46:03 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-80"]
Dec 09, 2017 10:46:03 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Dec 09, 2017 10:46:03 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 9342 ms
Dec 09, 2017 10:46:19 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1a35458e: startup date [Sat Dec 09 22:46:19 IST 2017]; root of context hierarchy
Dec 09, 2017 10:46:20 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [resources/spring.xml]
Dec 09, 2017 10:46:20 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@61e5c0d: defining beans [messageSource]; root of factory hierarchy
Dec 09, 2017 10:46:20 PM org.springframework.context.support.ResourceBundleMessageSource getResourceBundle
WARNING: ResourceBundle [resources/Data] not found for MessageSource: Can't find bundle for base name resources/Data, locale en-us,en-in;q=0.7,en;q=0.3
Dec 09, 2017 10:46:20 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [jsp] in context with path [/Spring1_IOC7_I18N] threw exception [An exception occurred processing JSP page /index.jsp at line 11

8:      String lang= request.getHeader("accept-language");
9:      Locale locale = new Locale(lang);
10:     ApplicationContext ap = new ClassPathXmlApplicationContext("resources/spring.xml");
11:     String value = ap.getMessage("label",null,locale);
12:  %>
13:
14:  <form action="./hello">

Stacktrace:] with root cause
org.springframework.context.NoSuchMessageException: No message found under code 'label' for locale 'en-us,en-in;q=0.7,en;q=0.3'.
    at org.springframework.context.support.AbstractMessageSource.getMessage(AbstractMessageSource.java:135)
    at org.springframework.context.support.AbstractApplicationContext.getMessage(AbstractApplicationContext.java:1161)
    at org.apache.jsp.index_jsp._jspService(index_jsp.java:75)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
```

答:
```<code>Locale locale = new Locale("lang");
</code>```

should be

```<code>Locale locale = new Locale(lang);
</code>```

without the quotes

Body:
I was trying to understand the concept of internationalization (I18N) in spring framework by deploying a simple dynamic web project. I am getting an unsolvable problem. Following were the jar files used:

*commons-logging.jar
*org.springframework.asm-3.0.1.RELEASE.jar
*org.springframework.asm-sources-3.0.1.RELEASE.jar
*org.springframework.beans-3.0.1.RELEASE.jar
*org.springframework.beans-sources-3.0.1.RELEASE.jar
*org.springframework.context-3.0.1.RELEASE.jar
*org.springframework.context-sources-3.0.1.RELEASE.jar
*org.springframework.core-3.0.1.RELEASE.jar
*org.springframework.core-sources-3.0.1.RELEASE.jar
*org.springframework.expression-3.0.1.RELEASE.jar
*org.springframework.expression-sources-3.0.1.RELEASE.jar

Following were the properties files:

Data_ka.properties

label=ಹೆಸರು

Data_hi.properties

label=नाम्

XML file:

spring.xml

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
            "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename" value="resources/Data" />
    </bean>
</beans>

JSP file:

index.jsp

<%@page import="org.springframework.context.support.ClassPathXmlApplicationContext"%>
<%@page import="org.springframework.context.ApplicationContext"%>
<%@page import="java.util.Locale"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

 <%
    String lang= request.getHeader("accept-language");
    Locale locale = new Locale(lang);
    ApplicationContext ap = new ClassPathXmlApplicationContext("resources/spring.xml");
    String value = ap.getMessage("label",null,locale);
 %>

 <form action="./hello">
    <%= value %> :<input type="text" name="name" />
                <input type="submit" value="submit">
 </form>

I am getting errors in my console as follows:

Dec 09, 2017 10:45:49 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre1.8.0_151\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jre1.8.0_151/bin/server;C:/Program Files/Java/jre1.8.0_151/bin;C:/Program Files/Java/jre1.8.0_151/lib/amd64;C:\ProgramData\Oracle\Java\javapath;C:\oraclexe\app\oracle\product\11.2.0\server\bin;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Java\jdk1.8.0_73\bin;C:\apache-ant-1.9.6-bin\apache-ant-1.9.6\bin;C:\WINDOWS\system32\config\systemprofile\.dnx\bin;C:\Program Files\Microsoft DNX\Dnvm\;C:\Program Files (x86)\Skype\Phone\;C:\apache-opennlp-1.7.2\bin;C:\Program Files\MySQL\MySQL Utilities 1.6\;%JAVA_HOME%\bin;%HADOOP_HOME%\bin;%HADOOP_BIN_PATH%;C:\Users\Nithin\Anaconda3;C:\Users\Nithin\Anaconda3\Scripts;C:\Users\Nithin\Anaconda3\Library\bin;C:\Users\Nithin\AppData\Local\Microsoft\WindowsApps;;C:\eclipse-jee-neon-2-win32-x86_64\eclipse;;.
Dec 09, 2017 10:45:50 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:Spring1_IOC7_I18N' did not find a matching property.
Dec 09, 2017 10:45:53 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-80"]
Dec 09, 2017 10:45:54 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Dec 09, 2017 10:45:54 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 5091 ms
Dec 09, 2017 10:45:54 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Dec 09, 2017 10:45:54 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.34
Dec 09, 2017 10:46:01 PM org.apache.catalina.util.SessionIdGenerator createSecureRandom
INFO: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [3,560] milliseconds.
Dec 09, 2017 10:46:03 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-80"]
Dec 09, 2017 10:46:03 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Dec 09, 2017 10:46:03 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 9342 ms
Dec 09, 2017 10:46:19 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1a35458e: startup date [Sat Dec 09 22:46:19 IST 2017]; root of context hierarchy
Dec 09, 2017 10:46:20 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [resources/spring.xml]
Dec 09, 2017 10:46:20 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@61e5c0d: defining beans [messageSource]; root of factory hierarchy
Dec 09, 2017 10:46:20 PM org.springframework.context.support.ResourceBundleMessageSource getResourceBundle
WARNING: ResourceBundle [resources/Data] not found for MessageSource: Can't find bundle for base name resources/Data, locale en-us,en-in;q=0.7,en;q=0.3
Dec 09, 2017 10:46:20 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [jsp] in context with path [/Spring1_IOC7_I18N] threw exception [An exception occurred processing JSP page /index.jsp at line 11

8:      String lang= request.getHeader("accept-language");
9:      Locale locale = new Locale(lang);
10:     ApplicationContext ap = new ClassPathXmlApplicationContext("resources/spring.xml");
11:     String value = ap.getMessage("label",null,locale);
12:  %>
13:
14:  <form action="./hello">

Stacktrace:] with root cause
org.springframework.context.NoSuchMessageException: No message found under code 'label' for locale 'en-us,en-in;q=0.7,en;q=0.3'.
    at org.springframework.context.support.AbstractMessageSource.getMessage(AbstractMessageSource.java:135)
    at org.springframework.context.support.AbstractApplicationContext.getMessage(AbstractApplicationContext.java:1161)
    at org.apache.jsp.index_jsp._jspService(index_jsp.java:75)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

Body:
Locale locale = new Locale("lang");

should be

Locale locale = new Locale(lang);

without the quotes


问:
Select, groupby by subquery
The below query works perfect for counting distinct UNIQUE_MEM_ID for any row that had amount>0.  I would like to change the logic of this query to capture distinct UNIQUE_MEM_ID that had sum(amount) > 100 in a single month.

Conceptually, changing logic from had amount > 100 in any row, to sum(amount) > 100 for any user in a month.

```<code>select to_char(optimized_transaction_date, 'YYYY-MM') as month, cobrand_id as cobrand,
   count(distinct UNIQUE_MEM_ID) as distinct_count
into temp_09.z_members
from yi_fourmpanel.card_panel
and amount >0
group by  to_char(optimized_transaction_date, 'YYYY-MM'), cobrand;
</code>```

答:
Use a having clause:

```<code>select to_char(optimized_transaction_date, 'YYYY-MM') as month,
       cobrand_id as cobrand,
       count(distinct UNIQUE_MEM_ID) as distinct_count
into temp_09.z_members
from yi_fourmpanel.card_panel
group by to_char(optimized_transaction_date, 'YYYY-MM'), cobrand
having sum(amount) > 100;
</code>```

Title: Select, groupby by subquery

Body:
The below query works perfect for counting distinct UNIQUE_MEM_ID for any row that had amount>0.  I would like to change the logic of this query to capture distinct UNIQUE_MEM_ID that had sum(amount) > 100 in a single month.

Conceptually, changing logic from had amount > 100 in any row, to sum(amount) > 100 for any user in a month.

select to_char(optimized_transaction_date, 'YYYY-MM') as month, cobrand_id as cobrand,
   count(distinct UNIQUE_MEM_ID) as distinct_count
into temp_09.z_members
from yi_fourmpanel.card_panel
and amount >0
group by  to_char(optimized_transaction_date, 'YYYY-MM'), cobrand;

Body:
Use a having clause:

select to_char(optimized_transaction_date, 'YYYY-MM') as month,
       cobrand_id as cobrand,
       count(distinct UNIQUE_MEM_ID) as distinct_count
into temp_09.z_members
from yi_fourmpanel.card_panel
group by to_char(optimized_transaction_date, 'YYYY-MM'), cobrand
having sum(amount) > 100;


问:
When I am passing a 2d array with the size of column it is showing some error?
Here is my code where I am getting error:

```<code>#include<bits/stdc++.h>
using namespace std;
int n;
bool is_attacked(int board[][n],int x,int y) //Here I am getting error
{
    for(int i=0;i<n;i++)
    {
        if(board[x][i])
        return false;
    }
    for(int i=0;i<n;i++)
    {
        if(board[i][y])
        return false;
    }
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<n;j++)
        {
            if(board[i][j]&&(x+y==i+j||i-j==x-y))
            return false;
        }
    }
    return true;
}
</code>```

It is giving error in function parameters of is_attacked and the error coming is:

```<code>array bound is not an integer constant before ']' token
</code>```

Could anyone please tell me what I am doing wrong?
Thanks in advance?

答:
The thing is the parameter you pass as the index of the 2D array needs to be a compile time evaluable constant expression. And since you are inputting n at run-time it is giving you an error.

An alternate method could be you define a macro, say #define MAX 10 and change your function signature to

```<code>bool is_attacked(int board[][MAX],int x,int y, int n)
</code>```

I am assuming this is N-queens or K-knights sort of problem, so you could define the macro accordingly.

Body:
Here is my code where I am getting error:

#include<bits/stdc++.h>
using namespace std;
int n;
bool is_attacked(int board[][n],int x,int y) //Here I am getting error
{
    for(int i=0;i<n;i++)
    {
        if(board[x][i])
        return false;
    }
    for(int i=0;i<n;i++)
    {
        if(board[i][y])
        return false;
    }
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<n;j++)
        {
            if(board[i][j]&&(x+y==i+j||i-j==x-y))
            return false;
        }
    }
    return true;
}

It is giving error in function parameters of is_attacked and the error coming is:

array bound is not an integer constant before ']' token

Could anyone please tell me what I am doing wrong?
Thanks in advance?

Body:
The thing is the parameter you pass as the index of the 2D array needs to be a compile time evaluable constant expression. And since you are inputting n at run-time it is giving you an error.

An alternate method could be you define a macro, say #define MAX 10 and change your function signature to

bool is_attacked(int board[][MAX],int x,int y, int n)

I am assuming this is N-queens or K-knights sort of problem, so you could define the macro accordingly.


问:
Stable topological sort
Let say I have a graph where the nodes is stored in a sorted list. I now want to topological sort this graph while keeping the original order where the topological order is undefined.
Are there any good algorithms for this?</p>

答:
Here's an easy iterative approach to topological sorting: continually remove a node with in-degree 0, along with its edges.

To achieve a stable version, just modify to: continually remove the smallest-index node with in-degree 0, along with its edges.

In pseudo-python:

```<code># N is the number of nodes, labeled 0..N-1
# edges[i] is a list of nodes j, corresponding to edges (i, j)

inDegree = [0] * N
for i in range(N):
   for j in edges[i]:
      inDegree[j] += 1

# Now we maintain a "frontier" of in-degree 0 nodes.
# We take the smallest one until the frontier is exhausted.
# Note: You could use a priority queue / heap instead of a list,
#       giving O(NlogN) runtime. This naive implementation is
#       O(N^2) worst-case (when the order is very ambiguous).

frontier = []
for i in range(N):
    if inDegree[i] == 0:
        frontier.append(i)

order = []
while frontier:
    i = min(frontier)
    frontier.remove(i)
    for j in edges[i]:
       inDegree[j] -= 1
       if inDegree[j] == 0:
           frontier.append(j)

 # Done - order is now a list of the nodes in topological order,
 # with ties broken by original order in the list.
</code>```

Title: Stable topological sort

Body:
Here's an easy iterative approach to topological sorting: continually remove a node with in-degree 0, along with its edges.

To achieve a stable version, just modify to: continually remove the smallest-index node with in-degree 0, along with its edges.

In pseudo-python:

# N is the number of nodes, labeled 0..N-1
# edges[i] is a list of nodes j, corresponding to edges (i, j)

inDegree = [0] * N
for i in range(N):
   for j in edges[i]:
      inDegree[j] += 1

# Now we maintain a "frontier" of in-degree 0 nodes.
# We take the smallest one until the frontier is exhausted.
# Note: You could use a priority queue / heap instead of a list,
#       giving O(NlogN) runtime. This naive implementation is
#       O(N^2) worst-case (when the order is very ambiguous).

frontier = []
for i in range(N):
    if inDegree[i] == 0:
        frontier.append(i)

order = []
while frontier:
    i = min(frontier)
    frontier.remove(i)
    for j in edges[i]:
       inDegree[j] -= 1
       if inDegree[j] == 0:
           frontier.append(j)

 # Done - order is now a list of the nodes in topological order,
 # with ties broken by original order in the list.


问:
Initialize tensor Variable to numpyArray - Reduced Sum Issues
I am pre-processing a numpy array and want to enter it in as a tensorflow Variable.  I've tried following other stack exchange advice, but so far without success.  I would like to see if I'm doing something uniquely wrong here.

```<code>  npW = np.zeros((784,10))
  npW[0,0] = 20
  W = tf.Variable(tf.convert_to_tensor(npW, dtype = tf.float32))

  sess = tf.InteractiveSession()
  tf.global_variables_initializer().run()

  print("npsum", np.sum(npW))
  print(tf.reduce_sum(W))
</code>```

And this is the result.

```<code>npsum 20.0
Tensor("Sum:0", shape=(), dtype=float32)
</code>```

I don't know why the reduced sum of the W variable remains zero.  Am i missing something here?

答:
You need to understand that Tensorflow differs from traditionnal computing. First, you declare a computational graph. Then, you run operations through the graph.

Taking your example, you have your numpy variables :

```<code>npW = np.zeros((784,10))
npW[0,0] = 20
</code>```

Next, these instructions are a definition of tensorflow variables, i.e. nodes in the computational graph:

```<code>W = tf.Variable(tf.convert_to_tensor(npW, dtype = tf.float32))
sum = tf.reduce_sum(W)
</code>```

And to be able to compute the operation, you need to run the op through the graph, with a sesssion, i.e. :

```<code>sess = tf.InteractiveSession()
tf.global_variables_initializer().run()
result = sess.run(sum)
print(result) # print 20
</code>```

Another way is to call eval instead of sess.run()

```<code>print(sum.eval()) # print 20
</code>```

Body:
I am pre-processing a numpy array and want to enter it in as a tensorflow Variable.  I've tried following other stack exchange advice, but so far without success.  I would like to see if I'm doing something uniquely wrong here.

  npW = np.zeros((784,10))
  npW[0,0] = 20
  W = tf.Variable(tf.convert_to_tensor(npW, dtype = tf.float32))

  sess = tf.InteractiveSession()
  tf.global_variables_initializer().run()

  print("npsum", np.sum(npW))
  print(tf.reduce_sum(W))

And this is the result.

npsum 20.0
Tensor("Sum:0", shape=(), dtype=float32)

I don't know why the reduced sum of the W variable remains zero.  Am i missing something here?

Body:
You need to understand that Tensorflow differs from traditionnal computing. First, you declare a computational graph. Then, you run operations through the graph.

Taking your example, you have your numpy variables :

npW = np.zeros((784,10))
npW[0,0] = 20

Next, these instructions are a definition of tensorflow variables, i.e. nodes in the computational graph:

W = tf.Variable(tf.convert_to_tensor(npW, dtype = tf.float32))
sum = tf.reduce_sum(W)

And to be able to compute the operation, you need to run the op through the graph, with a sesssion, i.e. :

sess = tf.InteractiveSession()
tf.global_variables_initializer().run()
result = sess.run(sum)
print(result) # print 20

Another way is to call eval instead of sess.run()

print(sum.eval()) # print 20


问:
Dynamically updating a specific view in a RecyclerView
I'm currently working on android using RecyclerView, let's say I have 2 TextView in my custom row, I wanted to dynamically change the text of one in the TextView, how can I do that?

I do have the following code in my MainActivity

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

    private RecyclerView recyclerView;
    private AdaptersOnline adaptersOnline;
    private RecyclerView.LayoutManager mLayoutManager;
    private List<ModelClientInformation> modelOnlineLists = new ArrayList<>();

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

        mLayoutManager = new LinearLayoutManager(this);
        adaptersOnline = new AdaptersOnline(this, modelOnlineLists);
        recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(adaptersOnline);
    }

    //call this to new row
    public void initializeClient(String id, String data1, String data2){
        this.modelOnlineLists.add(new ModelClientInformation(id, data1, data2));
        adaptersOnline.notifyDataSetChanged();
    }

    //Call this method to update textview
    public void updateSpecificViewItem(String theID){
         //get position base on the ID
         adaptersOnline.updateTextView(
         adaptersOnline.getPositionBaseOnItemID(theID));
    }

}
</code>```

in my Adapter Class

```<code>public class AdaptersOnline extends RecyclerView.Adapter<AdaptersOnline.TheViewHolder> {
    Context mContext;
    public List<ModelClientInformation> onlineList;

    public AdaptersOnline(Context mContext, List<ModelClientInformation> modelOnlineList){
        this.mContext = mContext;
        this.onlineList = modelOnlineList;
    }

    public class TheViewHolder extends RecyclerView.ViewHolder {

        TextView text1, text2;

        public TheViewHolder(View view) {
            super(view);

            text1 = (TextView)view.findViewById(R.id.text1);
            text2 = (TextView)view.findViewById(R.id.text2);
        }
    }

    @Override
    public TheViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.recyclerview_row, parent, false);
        return new TheViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(TheViewHolder holder, int position) {
        final ModelClientInformation info = onlineList.get(position);

        holder.text1.setText(holder.getText1());
        holder.text1.setText(holder.getText2());
    }

    /**Function to Return the size of List**/
    @Override
    public int getItemCount() {
        return onlineList.size();
    }

    /**Function to Clear the List**/
    public void clear(){
        onlineList.clear();
    }

    /**Possibly way to update one of the TextView here**/
    public void updateTextView(int position){
        //what should I do to update the TextView
    }

    /*Get the position of item inside data list base on the given ID*/
    public int getPositionBaseOnItemID(String theID) {

    int length = onlineList.size();
    for (int i = 0; i < length; i ++) {
        if(onlineList.get(i).getItemID().equals(theID)) {
            return i;
        }
    }
    return -1; //Item not found
}
}
</code>```

and the Pojo

```<code>public ModelClientInformation class{

    private String theID, text1, text2;

    public ModelClientInformation(String theID, String text1, String text2){
        this.theID = theID;
        this.text1 = text1;
        this.text2 = text2;
    }

    public String getItemID(){
        return theID;
    }

    public String getText1(){
        return text1;
    }

    public String getText2(){
        return text2;
    }

}
</code>```

I'm don't have any idea to do it. . .
Anyone can help me?

UPDATE:

Please look at my changes,

1: I want to update one of the TextView inside MainActivity class by calling updateSpecificViewItem("theID").

2: Get the position of the item base on the given id by calling getPositionBaseOnItemID("theID").

3: To finally update the specific item, I want to call updateTextView(int position) method.

the only problem I'm facing right now is the number 3, how can I update only the text2 and not the entire item?

答:
Create a a public static in the RecylerView class, simply assign a text in that method. Next, in the class where your geting a hook to the recycler view instance, make sure to add a onclick and ontouch interface to store the position of the selected text row. Use the recycler view instance to calling notifyItemChanged.

Here is a description from Documentation.

notifyItemChanged added in version 22.1.0

void notifyItemChanged (int position)

Notify any registered observers that the item at position has changed. Equivalent to calling notifyItemChanged(position, null);.

This is an item change event, not a structural change event. It indicates that any reflection of the data at position is out of date and should be updated. The item at position retains the same identity.

Body:
I'm currently working on android using RecyclerView, let's say I have 2 TextView in my custom row, I wanted to dynamically change the text of one in the TextView, how can I do that?

I do have the following code in my MainActivity

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private AdaptersOnline adaptersOnline;
    private RecyclerView.LayoutManager mLayoutManager;
    private List<ModelClientInformation> modelOnlineLists = new ArrayList<>();

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

        mLayoutManager = new LinearLayoutManager(this);
        adaptersOnline = new AdaptersOnline(this, modelOnlineLists);
        recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(adaptersOnline);
    }

    //call this to new row
    public void initializeClient(String id, String data1, String data2){
        this.modelOnlineLists.add(new ModelClientInformation(id, data1, data2));
        adaptersOnline.notifyDataSetChanged();
    }

    //Call this method to update textview
    public void updateSpecificViewItem(String theID){
         //get position base on the ID
         adaptersOnline.updateTextView(
         adaptersOnline.getPositionBaseOnItemID(theID));
    }

}

in my Adapter Class

public class AdaptersOnline extends RecyclerView.Adapter<AdaptersOnline.TheViewHolder> {
    Context mContext;
    public List<ModelClientInformation> onlineList;

    public AdaptersOnline(Context mContext, List<ModelClientInformation> modelOnlineList){
        this.mContext = mContext;
        this.onlineList = modelOnlineList;
    }

    public class TheViewHolder extends RecyclerView.ViewHolder {

        TextView text1, text2;

        public TheViewHolder(View view) {
            super(view);

            text1 = (TextView)view.findViewById(R.id.text1);
            text2 = (TextView)view.findViewById(R.id.text2);
        }
    }

    @Override
    public TheViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.recyclerview_row, parent, false);
        return new TheViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(TheViewHolder holder, int position) {
        final ModelClientInformation info = onlineList.get(position);

        holder.text1.setText(holder.getText1());
        holder.text1.setText(holder.getText2());
    }

    /**Function to Return the size of List**/
    @Override
    public int getItemCount() {
        return onlineList.size();
    }

    /**Function to Clear the List**/
    public void clear(){
        onlineList.clear();
    }

    /**Possibly way to update one of the TextView here**/
    public void updateTextView(int position){
        //what should I do to update the TextView
    }

    /*Get the position of item inside data list base on the given ID*/
    public int getPositionBaseOnItemID(String theID) {

    int length = onlineList.size();
    for (int i = 0; i < length; i ++) {
        if(onlineList.get(i).getItemID().equals(theID)) {
            return i;
        }
    }
    return -1; //Item not found
}
}

and the Pojo

public ModelClientInformation class{

    private String theID, text1, text2;

    public ModelClientInformation(String theID, String text1, String text2){
        this.theID = theID;
        this.text1 = text1;
        this.text2 = text2;
    }

    public String getItemID(){
        return theID;
    }

    public String getText1(){
        return text1;
    }

    public String getText2(){
        return text2;
    }

}

I'm don't have any idea to do it. . .
Anyone can help me?

UPDATE:

Please look at my changes,

1: I want to update one of the TextView inside MainActivity class by calling updateSpecificViewItem("theID").

2: Get the position of the item base on the given id by calling getPositionBaseOnItemID("theID").

3: To finally update the specific item, I want to call updateTextView(int position) method.

the only problem I'm facing right now is the number 3, how can I update only the text2 and not the entire item?


问:
If-else blocks not returning true on a condition that is clearly true, what do I do?
I'm having some trouble understanding why the Scanner is not picking up the "(" character when it is clearly there. When I tried to save my program, there was a pop-up that said that some of the characters couldn't be saved in the proper encoding. (I'm using Eclipse, and it uses Cp1252 encoding if that would be of any help) I changed it to UTF-8, and now I'm having these issues.</p>

```<code>String input = "a 0 ( b 4 ( * 100 b 6 ) w 9 ( x 3 y 5 ( * 2 z 3 ) ) )";
LinkedStack<TreeNode<String>> stack = new LinkedStack<TreeNode<String>>();
Scanner in = new Scanner(input);
    while (in.hasNext()) {
        String temp = in.next();
        System.out.println("Here's a temp:" + temp);
        if (temp == "(") {
            System.out.println("Continuing.");
            continue;
        }
        else if (temp == ")") {
            System.out.println("Closed Paren.");
            TreeNode<String> leftChild = stack.pop();
            TreeNode<String> rightChild = stack.pop();
            TreeNode<String> parent = stack.pop();
            parent.setLeft(leftChild);
            parent.setRight(rightChild);
            stack.push(parent);
        }
        else {
            System.out.println("Hit the else block.");
            String label = temp;
            String distanceString = in.next();
            double distance = Double.parseDouble(distanceString);
            System.out.println("Here is the distance of this node: " +distance);
            stack.push(new TreeNode<String>(label, null, null, distance));
        }
    }
</code>```

答:
When using == like that, the two string are checked to see if they have the same reference, which in this case will return false.

You should use temp.equals("(") and temp.equals(")") and so on.

Comparing the strings with equals method checks their values, which will be true here.

Body:
I'm having some trouble understanding why the Scanner is not picking up the "(" character when it is clearly there. When I tried to save my program, there was a pop-up that said that some of the characters couldn't be saved in the proper encoding. (I'm using Eclipse, and it uses Cp1252 encoding if that would be of any help) I changed it to UTF-8, and now I'm having these issues.

String input = "a 0 ( b 4 ( * 100 b 6 ) w 9 ( x 3 y 5 ( * 2 z 3 ) ) )";
LinkedStack<TreeNode<String>> stack = new LinkedStack<TreeNode<String>>();
Scanner in = new Scanner(input);
    while (in.hasNext()) {
        String temp = in.next();
        System.out.println("Here's a temp:" + temp);
        if (temp == "(") {
            System.out.println("Continuing.");
            continue;
        }
        else if (temp == ")") {
            System.out.println("Closed Paren.");
            TreeNode<String> leftChild = stack.pop();
            TreeNode<String> rightChild = stack.pop();
            TreeNode<String> parent = stack.pop();
            parent.setLeft(leftChild);
            parent.setRight(rightChild);
            stack.push(parent);
        }
        else {
            System.out.println("Hit the else block.");
            String label = temp;
            String distanceString = in.next();
            double distance = Double.parseDouble(distanceString);
            System.out.println("Here is the distance of this node: " +distance);
            stack.push(new TreeNode<String>(label, null, null, distance));
        }
    }


问:
Chart.js title is not showing
I am trying to load graphs based on XML data. my script and everything works fine. Just, the problem is for each of the graph , there should be a title. and title is not showing up at all. within the for loop it create the convas dynamically, and then Labels and Values are initiating when the HTML page is called. just the missing part is the TITLE of each graph. any body has any idea?</p>

```<code>var command = xmlDoc.getElementsByTagName("COMMAND");

for (var commandIndex = 0; commandIndex  < command.length; commandIndex++) {
var canvas = document.createElement('canvas');
canvas.id = "Convas"+commandIndex;
canvas.width = 800;
canvas.style.zIndex = 8;
canvas.style.position = "inherit";
document.getElementById("chartdiv").insertBefore(canvas,document.getElementById
    ("Convas"+commandIndex));
  var barData = {
 labels : [{% for item in labels %}
               "{{item}}",
          {% endfor %}],
datasets : [
   {
        fillColor: "rgba(151,187,205,0.2)",
         strokeColor: "rgba(151,187,205,1)",
        pointColor: "rgba(151,187,205,1)",
        pointStrokeColor: "#fff",
        pointHighlightFill: "#fff",
        pointHighlightStroke: "rgba(151,187,205,1)",
        bezierCurve : false,
        data : [{% for item in values %}
                  {{item}},
                {% endfor %}]
  }]
}

Chart.defaults.global.animationSteps = 50;
Chart.defaults.global.tooltipYPadding = 16;
Chart.defaults.global.tooltipCornerRadius = 0;
Chart.defaults.global.tooltipTitleFontStyle = "normal";
Chart.defaults.global.tooltipFillColor = "rgba(0,0,0,0.8)";
Chart.defaults.global.animationEasing = "easeOutBounce";
Chart.defaults.global.responsive = false;
Chart.defaults.global.scaleLineColor = "black";
Chart.defaults.global.scaleFontSize = 16;

 // get bar chart canvas

 var mychart =
 document.getElementById("Convas"+commandIndex).getContext("2d");
 steps = 100
 max = 100
 // draw bar chart
  var LineChartDemo = new Chart(mychart).Line(barData, {
      scaleOverride: false,
      scaleSteps: steps,
      scaleStepWidth: Math.ceil(max / steps),
      scaleStartValue: 0,
      scaleShowVerticalLines: false,
      scaleShowGridLines : false,
      barShowStroke : true,
      scaleShowLabels: false,
      bezierCurve: true,
      options: { title: {display: true,text: 'FARShAD'}},
 });
}})
</code>```

答:
Well, I could not find my problem with my code. however, i re wrote it in another way.</p>

```<code>var canvas = document.createElement('canvas');
canvas.id = "Convas"+commandIndex;
canvas.width = 800;
canvas.style.zIndex = 8;
canvas.style.position = "inherit";
  document.getElementById("chartdiv").insertBefore(canvas,document.getElementById("Convas"+commandIndex));

var barData = {
labels : [{% for item in labels %}
              "{{item}}",
          {% endfor %}],
datasets : [
   {
        fillColor: "rgba(151,187,205,0.2)",
        strokeColor: "rgba(151,187,205,1)",
        pointColor: "rgba(241, 14, 75, 1)",
        pointStrokeColor: "#fff",
        pointHighlightFill: "#fff",
        pointHighlightStroke: "rgba(241, 14, 75, 1)",
        backgroundColor: "rgba(241, 14, 75, 1)",
        borderColor: "rgba(241, 14, 75, 1)",
        bezierCurve : false,
        fill: false,
        label: "My First dataset",
        data : [{% for item in values %}
                  {{item}},
                {% endfor %}]
  }]
 }
   var config = {
   type: 'line',
   data: barData,
   options: {
       responsive: true,
       title:{
           display:true,
           text:'Chart.js Line Chart'
       },
       tooltips: {
           mode: 'index',
           intersect: false,
       },
       hover: {
           mode: 'nearest',
           intersect: true
       },
       scales: {
           xAxes: [{
               display: true,
               scaleLabel: {
                   display: true,
                   labelString: 'Month'
               }
           }],
           yAxes: [{
               display: true,
               scaleLabel: {
                   display: true,
                   labelString: 'Value'
               },
               ticks: {
                   min: 0,
                   max: 100,

                   // forces step size to be 5 units
                   stepSize: 5
               }
           }]
       }
   }
 };
  var mychart =
  document.getElementById("Convas"+commandIndex).getContext("2d");

steps = 100
max = 100
// draw bar cha
  var LineChartDemo = new Chart(mychart, config);
</code>```

Title: Chart.js title is not showing

Body:
I am trying to load graphs based on XML data. my script and everything works fine. Just, the problem is for each of the graph , there should be a title. and title is not showing up at all. within the for loop it create the convas dynamically, and then Labels and Values are initiating when the HTML page is called. just the missing part is the TITLE of each graph. any body has any idea?

var command = xmlDoc.getElementsByTagName("COMMAND");

for (var commandIndex = 0; commandIndex  < command.length; commandIndex++) {
var canvas = document.createElement('canvas');
canvas.id = "Convas"+commandIndex;
canvas.width = 800;
canvas.style.zIndex = 8;
canvas.style.position = "inherit";
document.getElementById("chartdiv").insertBefore(canvas,document.getElementById
    ("Convas"+commandIndex));
  var barData = {
 labels : [{% for item in labels %}
               "{{item}}",
          {% endfor %}],
datasets : [
   {
        fillColor: "rgba(151,187,205,0.2)",
         strokeColor: "rgba(151,187,205,1)",
        pointColor: "rgba(151,187,205,1)",
        pointStrokeColor: "#fff",
        pointHighlightFill: "#fff",
        pointHighlightStroke: "rgba(151,187,205,1)",
        bezierCurve : false,
        data : [{% for item in values %}
                  {{item}},
                {% endfor %}]
  }]
}

Chart.defaults.global.animationSteps = 50;
Chart.defaults.global.tooltipYPadding = 16;
Chart.defaults.global.tooltipCornerRadius = 0;
Chart.defaults.global.tooltipTitleFontStyle = "normal";
Chart.defaults.global.tooltipFillColor = "rgba(0,0,0,0.8)";
Chart.defaults.global.animationEasing = "easeOutBounce";
Chart.defaults.global.responsive = false;
Chart.defaults.global.scaleLineColor = "black";
Chart.defaults.global.scaleFontSize = 16;

 // get bar chart canvas

 var mychart =
 document.getElementById("Convas"+commandIndex).getContext("2d");
 steps = 100
 max = 100
 // draw bar chart
  var LineChartDemo = new Chart(mychart).Line(barData, {
      scaleOverride: false,
      scaleSteps: steps,
      scaleStepWidth: Math.ceil(max / steps),
      scaleStartValue: 0,
      scaleShowVerticalLines: false,
      scaleShowGridLines : false,
      barShowStroke : true,
      scaleShowLabels: false,
      bezierCurve: true,
      options: { title: {display: true,text: 'FARShAD'}},
 });
}})

Body:
Well, I could not find my problem with my code. however, i re wrote it in another way.

var canvas = document.createElement('canvas');
canvas.id = "Convas"+commandIndex;
canvas.width = 800;
canvas.style.zIndex = 8;
canvas.style.position = "inherit";
  document.getElementById("chartdiv").insertBefore(canvas,document.getElementById("Convas"+commandIndex));

var barData = {
labels : [{% for item in labels %}
              "{{item}}",
          {% endfor %}],
datasets : [
   {
        fillColor: "rgba(151,187,205,0.2)",
        strokeColor: "rgba(151,187,205,1)",
        pointColor: "rgba(241, 14, 75, 1)",
        pointStrokeColor: "#fff",
        pointHighlightFill: "#fff",
        pointHighlightStroke: "rgba(241, 14, 75, 1)",
        backgroundColor: "rgba(241, 14, 75, 1)",
        borderColor: "rgba(241, 14, 75, 1)",
        bezierCurve : false,
        fill: false,
        label: "My First dataset",
        data : [{% for item in values %}
                  {{item}},
                {% endfor %}]
  }]
 }
   var config = {
   type: 'line',
   data: barData,
   options: {
       responsive: true,
       title:{
           display:true,
           text:'Chart.js Line Chart'
       },
       tooltips: {
           mode: 'index',
           intersect: false,
       },
       hover: {
           mode: 'nearest',
           intersect: true
       },
       scales: {
           xAxes: [{
               display: true,
               scaleLabel: {
                   display: true,
                   labelString: 'Month'
               }
           }],
           yAxes: [{
               display: true,
               scaleLabel: {
                   display: true,
                   labelString: 'Value'
               },
               ticks: {
                   min: 0,
                   max: 100,

                   // forces step size to be 5 units
                   stepSize: 5
               }
           }]
       }
   }
 };
  var mychart =
  document.getElementById("Convas"+commandIndex).getContext("2d");

steps = 100
max = 100
// draw bar cha
  var LineChartDemo = new Chart(mychart, config);


问:
Don't understand why my multiplication isn't working?
I'm trying to make a temperature conversion function for a class assignment, and my function receives all of the arguments correctly but for some reason after it hits the equation to convert the number it just makes the number 0.

Here is the code so you know what I'm talking about:

```<code>void convertToCelsius(int farenheitTemperature, int temperatureType){

if (temperatureType == 1)
{

farenheitTemperature = ((5/9) * (farenheitTemperature - 32));
printf("Your temperature in Celsius is %i\n", farenheitTemperature);

}

else
{
    printf("Your temperature is already in celsius!\n");
}
}
</code>```

the main function puts the arguments in correctly, so I don't think that's the problem.

Thank you very much for any help you can give!

答:
Kindly check operators precedence & associativity, there is a problem in below statement

```<code>farenheitTemperature = ((5/9) * (farenheitTemperature - 32));
</code>```

(5/9) yields in 0 not some decimal fractional digit because coefficient is 0.

If you ant correct result either typecast or replace like

```<code>farenheitTemperature = ((5 * (farenheitTemperature - 32)/9);
</code>```

I hope it helps.

Body:
I'm trying to make a temperature conversion function for a class assignment, and my function receives all of the arguments correctly but for some reason after it hits the equation to convert the number it just makes the number 0.

Here is the code so you know what I'm talking about:

void convertToCelsius(int farenheitTemperature, int temperatureType){

if (temperatureType == 1)
{

farenheitTemperature = ((5/9) * (farenheitTemperature - 32));
printf("Your temperature in Celsius is %i\n", farenheitTemperature);

}

else
{
    printf("Your temperature is already in celsius!\n");
}
}

the main function puts the arguments in correctly, so I don't think that's the problem.

Thank you very much for any help you can give!

Body:
Kindly check operators precedence & associativity, there is a problem in below statement

farenheitTemperature = ((5/9) * (farenheitTemperature - 32));

(5/9) yields in 0 not some decimal fractional digit because coefficient is 0.

If you ant correct result either typecast or replace like

farenheitTemperature = ((5 * (farenheitTemperature - 32)/9);

I hope it helps.


问:
HttpClient exception: java.lang.IllegalArgumentException: host parameter is null
I have next code

```<code>    URL targetUrl = ...
    HttpClient client = new HttpClient(connectionManager);
    GetMethod getMethod = new GetMethod();
    getMethod.setPath(targetUrl.getPath());

    HostConfiguration hostConfiguration = getConfiguration(targetUrl) //unknown lib code

    client.executeMethod(hostConfiguration, getMethod);
</code>```

In some cases(on some hosts) I get

java.lang.IllegalArgumentException: host parameter is null"

on client.executeMethod call.

Why may this happen?

答:
This error means that you are using incomplete url or without protocol. For example
String url ="google.com". Change it to String url="http://google.com". It will work now

Body:
I have next code

    URL targetUrl = ...
    HttpClient client = new HttpClient(connectionManager);
    GetMethod getMethod = new GetMethod();
    getMethod.setPath(targetUrl.getPath());

    HostConfiguration hostConfiguration = getConfiguration(targetUrl) //unknown lib code

    client.executeMethod(hostConfiguration, getMethod);

In some cases(on some hosts) I get

java.lang.IllegalArgumentException: host parameter is null"

on client.executeMethod call.

Why may this happen?


问:
Google Fonts Font Doesn't load
I'm trying to add PT Sans into a newsletter, but for some reason it isn't loading I've copied almost all of the code, but it isn't working. I would be so grateful for anyone who can help.

Here is the CSS code:

```<code>h1, h2, h3 {
    font-family: 'PT Sans', sans-serif;
}
</code>```

and the HTML code:

```<code><link href="http://fonts.googleapis.com/css?family=PT+Sans" rel="stylesheet" type="text/css">
</code>```

EDIT:
Here's the rest of the CSS:

```<code>h1, h2, h3 {
    font-family: 'PT Sans', sans-serif;
}

#logo{width:810px}

#saveDateText{
    position:relative;
    top:30px;
    left:80px;
    font-size:50px;
    color:rgb(228,242,214)
}

#october{
    position:relative;
    top:0px;
    left:90px;
    font-size:35px;
    color:rgb(228,242,214)
}

#raftLogo{
    position:relative;
    top:-125px;
    left:550px;
}

#saveTheDate {
    background-color:rgb(123, 190, 48);
    height:170px;
    width:810px;
}

#honoring {
    position:relative;
    background-color:rgb(9, 65, 30);
    width:810px;
    top:-30px;
    font-size:20px;
    height:400px;
}

#honoringTextDiv {
    position:relative;
    width:740px;
    left:70px;
    top:50px
}

#infoText {
    color:white;
    font-size:25px;
}

#honoringText {
    color:rgb(242, 183, 51);
}

#benifit{
    color:white;
    font-size:25px
}

#morgridge {
    position:relative;
    top:20px
}
#sponsorships {
    position:relative;
    left:20px;
    top:-30px;
    height:300px;
    width:400px;
    border-right-style:solid;
    border-right-color:rgb(160, 202, 129);
    border-right-width:1px;
}

#inventiveSponsorsDiv {
    position:relative;
    left:425px;
    top:-155px
}
#dmns {
    position:relative;
    top:-40px;
}
#1stbank {
    position:relative;
    top:80px;
}

#inspirationalSponsors, #inventiveSponsors{
    position:relative;
    top:0px;
    color:rgb(123,190,48);
    font-size:18px;
}
#inventiveSponsors {
    top:-20px;
}

#names, #names2 {
    line-height:25px;
    font-size:14px

}
#names2 {
    position:relative;
    top:-94px;
    left:160px;
    text-align:left;
}
</code>```

答:
I had the same problem and if using the CSS tag of:

"font: 3em bold;" ---this overrides the google api call and loads your next default font.

SOLUTION: Use font-style and font-size

Title: Google Fonts Font Doesn't load

Body:
I'm trying to add PT Sans into a newsletter, but for some reason it isn't loading I've copied almost all of the code, but it isn't working. I would be so grateful for anyone who can help.

Here is the CSS code:

h1, h2, h3 {
    font-family: 'PT Sans', sans-serif;
}

and the HTML code:

<link href="http://fonts.googleapis.com/css?family=PT+Sans" rel="stylesheet" type="text/css">

EDIT:
Here's the rest of the CSS:

h1, h2, h3 {
    font-family: 'PT Sans', sans-serif;
}

#logo{width:810px}

#saveDateText{
    position:relative;
    top:30px;
    left:80px;
    font-size:50px;
    color:rgb(228,242,214)
}

#october{
    position:relative;
    top:0px;
    left:90px;
    font-size:35px;
    color:rgb(228,242,214)
}

#raftLogo{
    position:relative;
    top:-125px;
    left:550px;
}

#saveTheDate {
    background-color:rgb(123, 190, 48);
    height:170px;
    width:810px;
}

#honoring {
    position:relative;
    background-color:rgb(9, 65, 30);
    width:810px;
    top:-30px;
    font-size:20px;
    height:400px;
}

#honoringTextDiv {
    position:relative;
    width:740px;
    left:70px;
    top:50px
}

#infoText {
    color:white;
    font-size:25px;
}

#honoringText {
    color:rgb(242, 183, 51);
}

#benifit{
    color:white;
    font-size:25px
}

#morgridge {
    position:relative;
    top:20px
}
#sponsorships {
    position:relative;
    left:20px;
    top:-30px;
    height:300px;
    width:400px;
    border-right-style:solid;
    border-right-color:rgb(160, 202, 129);
    border-right-width:1px;
}

#inventiveSponsorsDiv {
    position:relative;
    left:425px;
    top:-155px
}
#dmns {
    position:relative;
    top:-40px;
}
#1stbank {
    position:relative;
    top:80px;
}

#inspirationalSponsors, #inventiveSponsors{
    position:relative;
    top:0px;
    color:rgb(123,190,48);
    font-size:18px;
}
#inventiveSponsors {
    top:-20px;
}

#names, #names2 {
    line-height:25px;
    font-size:14px

}
#names2 {
    position:relative;
    top:-94px;
    left:160px;
    text-align:left;
}


问:
Call array variable inside of array in php
I want to call array variable inside the current array. Something like this:

```<code>$conv= array (
"hello" => array("Hello", "Hi", "Hello, how are you?"),
"helo" => array_merge($conv['hello'])
);
print_r($conv['helo']);
</code>```

How can I do this.
thanks.

答:
The way you try to build the array is probably impossible.

Because the array is not made untill the end of the function ; when you try to set 'helo', 'hello' is undefined.

You need to set 'hello' first then copy it to 'helo'.

```<code>$conv = array("hello" => array("Hello", "Hi", "Hello, how are you?"));

$conv["helo"] = $conv['hello'];
print_r($conv['helo']);
</code>```

https://3v4l.org/PCJH7

Body:
I want to call array variable inside the current array. Something like this:

$conv= array (
"hello" => array("Hello", "Hi", "Hello, how are you?"),
"helo" => array_merge($conv['hello'])
);
print_r($conv['helo']);

How can I do this.
thanks.

Body:
The way you try to build the array is probably impossible.

Because the array is not made untill the end of the function ; when you try to set 'helo', 'hello' is undefined.

You need to set 'hello' first then copy it to 'helo'.

$conv = array("hello" => array("Hello", "Hi", "Hello, how are you?"));

$conv["helo"] = $conv['hello'];
print_r($conv['helo']);

https://3v4l.org/PCJH7


问:
How to remove popup message of NFC tag in iOS?
In the give image, when NFC session begin, "Ready to scan" popup appear in screen. In my application I only need to scan NFC tag without popup. Is there any solution to remove popup as shown in image?

答:
Not possible with current API. I've had several discussions with Apple direct about their NFC implementation which I specifically brought up the system UI modal and if it can be disabled from showing. They basically told me it'll never happen.

If you want to consider accessing private functions then I think it is possible but your app get approved for the iTunes Store.


问:
Not able to create new app in itunes connect
I am assigned as developer admin but I am not able to add
a new app in iTunes connect. When I click on the New app it shows:

"You have no eligible Bundle IDs for iOS app"

Here is the screen shot: link here.

When I click on the Register One here, it opens my Apple
developer account where there is no option for creating a certificate. My Apple id is not paid one. I don't know where to add
certificate as there is nowhere mentioning certificate. Here is the screen shot: link.

答:
An ItunesConnect Information can only be added by the AGENT Login not the person with ADMIN/TEAM MEMBER privilege given.

The Admin can only create and organise developer.apple.com/member centre portal. Not the iTunesConnect that needs to register the app first then all the rest story follows.


问:
Browserless JavaScript
I talked to the Team Lead at Snap-On Tools once, and she told they used an "implementation of JavaScript" for their server-side coding. It's been a while, but I was thinking, WTF is she talking about? Are there interpreters for JavaScript besides those implemented in browsers?

How can you create a program or code, especially server-side, using JavaScript that doesn't execute in the context of a browser? What the hell is server-side about JavaScript if it's not generating content after the browser has loaded it? Can "server-side" JavaScript generate content before the HTTP response is deliver—and if so, how does that work/is set up?

I have many issues with JavaScript, but first-class functions are so sexy. And JavaScript Object Notation is so pure; I couldn't imagine an easier way to define data structures. Plus, you can hack out some code pretty quickly with dynamic typing if you're not writing something that's mission critical.

As a side question, given the last paragraph, have any suggestions about a good language to learn (comments will suffice)?

答:
Yes, JavaScript Virtual Machines exists outside of the browser. Here's a list of specially tailored server side adaptations.

I personally use it Spidermonkey on the command line to try code out. Rhino is the same adaptation of ECMAScript as Spidermonkey (same language implementation) but Rhino runs on the Java VM, and Spidermonkey was written in C.

OwnerDisplayName: Chris

Title: Browserless JavaScript

LastEditorDisplayName: Chris

OwnerDisplayName: Zach