问:
QML: Close all QWidgets when QApplication is exited
I have a Qt program that uses QApplication for its main window and also spawns potentially many QMessageBox widgets. I need to close all of these QMessageBox dialogs when the main QApplication window is quit. However, I am unable to use any of the normal callbacks as the QMessageBox's seem to block the onDestruction() signal. When I click the X to quit the QApplication, its window goes away, but the onDestruction() symbol is only fired when the last QMessageBox is quit. Please let me know the right way to do this.

Edit:

Here's my main.cpp:

```<code>int main(int argc, char* argv[]) {
    QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    Application app(argc, argv);
    QQmlApplicationEngine engine;

    engine.rootContext()->setContextProperty("applicationVersion", VER_FILEVERSION_STR);
    engine.rootContext()->setContextProperty("applicationDirPath", QGuiApplication::applicationDirPath());
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    int retval = app.exec();
    qInstallMessageHandler(0);

    return retval;
}
</code>```

And here's how I instantiate a QMessageBox:

```<code>QMessageBox* errorD = new QMessageBox();
errorD->setStandardButtons(QMessageBox::Ok);
errorD->setDefaultButton(QMessageBox::Ok);
errorD->setModal(false);
errorD->setWindowTitle(title);
errorD->setText(msg);
// We reset when closed
QObject::connect(errorD, &QMessageBox::destroyed, [=]() { printf("QMBox destroyed.");});
errorD->raise();
errorD->activateWindow();
errorD->show();
QApplication::processEvents();
</code>```

答:
A possible solution is to create a Helper that calls a function that closes the widgets, and this should be called in onClosing:

main.cpp

```<code>class Helper : public QObject
{
    Q_OBJECT
    QWidgetList widgets;
  public:
    Q_INVOKABLE void closeAllWidgets(){
        for(QWidget *w: widgets)
            w->close();
    }
    void addWidget(QWidget *w){
        widgets<<w;
    }
};

#include "main.moc"

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QApplication app(argc, argv);

    QQmlApplicationEngine engine;
    Helper helper;
    engine.rootContext()->setContextProperty("helper", &helper);
    engine.load(QUrl(QLatin1String("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    for(int i=1; i < 5; i++){
        QMessageBox* errorD = new QMessageBox();
        helper.addWidget(errorD);
        [...]
</code>```

main.qml

```<code>import QtQuick 2.7
import QtQuick.Controls 2.0

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
    onClosing: helper.closeAllWidgets();
}
</code>```

In the following link you will find an example

Body:
I have a Qt program that uses QApplication for its main window and also spawns potentially many QMessageBox widgets. I need to close all of these QMessageBox dialogs when the main QApplication window is quit. However, I am unable to use any of the normal callbacks as the QMessageBox's seem to block the onDestruction() signal. When I click the X to quit the QApplication, its window goes away, but the onDestruction() symbol is only fired when the last QMessageBox is quit. Please let me know the right way to do this.

Edit:

Here's my main.cpp:

int main(int argc, char* argv[]) {
    QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    Application app(argc, argv);
    QQmlApplicationEngine engine;

    engine.rootContext()->setContextProperty("applicationVersion", VER_FILEVERSION_STR);
    engine.rootContext()->setContextProperty("applicationDirPath", QGuiApplication::applicationDirPath());
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    int retval = app.exec();
    qInstallMessageHandler(0);

    return retval;
}

And here's how I instantiate a QMessageBox:

QMessageBox* errorD = new QMessageBox();
errorD->setStandardButtons(QMessageBox::Ok);
errorD->setDefaultButton(QMessageBox::Ok);
errorD->setModal(false);
errorD->setWindowTitle(title);
errorD->setText(msg);
// We reset when closed
QObject::connect(errorD, &QMessageBox::destroyed, [=]() { printf("QMBox destroyed.");});
errorD->raise();
errorD->activateWindow();
errorD->show();
QApplication::processEvents();

Body:
A possible solution is to create a Helper that calls a function that closes the widgets, and this should be called in onClosing:

main.cpp

class Helper : public QObject
{
    Q_OBJECT
    QWidgetList widgets;
  public:
    Q_INVOKABLE void closeAllWidgets(){
        for(QWidget *w: widgets)
            w->close();
    }
    void addWidget(QWidget *w){
        widgets<<w;
    }
};

#include "main.moc"

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QApplication app(argc, argv);

    QQmlApplicationEngine engine;
    Helper helper;
    engine.rootContext()->setContextProperty("helper", &helper);
    engine.load(QUrl(QLatin1String("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    for(int i=1; i < 5; i++){
        QMessageBox* errorD = new QMessageBox();
        helper.addWidget(errorD);
        [...]

main.qml

import QtQuick 2.7
import QtQuick.Controls 2.0

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
    onClosing: helper.closeAllWidgets();
}

In the following link you will find an example


来源: stackexchange

问:
test for the file related function in python
I am rather new to software testing. I wonder how to write a unit test for file related functions in python. e.g., if I have a file copy function as follows. </p>

```<code>def copy_file (self):
    if not os.path.isdir(dest_path):
        os.makedirs(dest_path)
    try:
        shutil.copy2(src_path, dest_path)
    except IOError as e:
        print e
</code>```

<p>What should I do about testing above function? what should I assert (directory, file content, exceptions)? </p>

答:
You can rely on shutil.copy2 copying the contents correctly. You only need to test your code. In this case that it creates the directories if they don't exist, and that it swallows IOErrors.

And don't forget to clean up. ;)

ContentLicense: CC BY-SA 3.0

Body:
I am rather new to software testing. I wonder how to write a unit test for file related functions in python. e.g., if I have a file copy function as follows.

def copy_file (self):
    if not os.path.isdir(dest_path):
        os.makedirs(dest_path)
    try:
        shutil.copy2(src_path, dest_path)
    except IOError as e:
        print e

What should I do about testing above function? what should I assert (directory, file content, exceptions)?

ContentLicense: CC BY-SA 2.5


问:
Open a folder using Process.Start
I saw the other topic and I'm having another problem. The process is starting (saw at task manager) but the folder is not opening on my screen. What's wrong?</p>

```<code>System.Diagnostics.Process.Start("explorer.exe", @"c:\teste");
</code>```

答:
Ive just had this issue, and i found out why. my reason isnt listed here so anyone else who gets this issue and none of these fix it.

If you run Visual Studio as another user and attempt to use Process.Start it will run in that users context and you will not see it on your screen.

Title: Open a folder using Process.Start

Body:
I saw the other topic and I'm having another problem. The process is starting (saw at task manager) but the folder is not opening on my screen. What's wrong?

System.Diagnostics.Process.Start("explorer.exe", @"c:\teste");


问:
Python - Animate basemap scatterplot
I have a DataFrame with shape (14403, 438) that consists of longitudes and latitudes as well as values. The DataFrame is as:

I am plotting the coordinates as:

```<code># define map colors
land_color = '#f5f5f3'
water_color = '#cdd2d4'
coastline_color = '#f5f5f3'
border_color = '#bbbbbb'
meridian_color = '#f5f5f3'
marker_fill_color = '#0000ff'
marker_edge_color = 'None'

# create the plot
fig = plt.figure(figsize = (15, 10))
ax = fig.add_subplot(111, facecolor = '#ffffff', frame_on = False)
ax.set_title('Transportable Array', fontsize = 24, color = '#333333')

#lon_0  center of desired map domain (in degrees).
#lat_0  center of desired map domain (in degrees).
#width  width of desired map domain in projection coordinates (meters).
#height height of desired map domain in projection coordinates (meters).

# draw the basemap and its features
m = Basemap(width = 5500000,height = 3300000,
            resolution = 'l', area_thresh = 1000., projection = 'lcc',\
            lat_1 = 45., lat_2 = 55, lat_0 = 37, lon_0 = -98.)
m.drawmapboundary(color = border_color, fill_color = water_color)
m.drawcoastlines(color = coastline_color)
m.drawcountries(color = border_color)
m.fillcontinents(color = land_color, lake_color = water_color)
m.drawparallels(np.arange(-90., 120., 30.), color = meridian_color)
m.drawmeridians(np.arange(0., 420., 60.), color = meridian_color)

# project the location history points then scatter plot them
x, y = m(stations.loc['longitude'].values, stations.loc['latitude'].values)
m.scatter(x, y, s = 8, color = marker_fill_color, edgecolor = marker_edge_color, alpha = 1, zorder = 3)

# show & save the map
plt.savefig('Transportable_Array.png', dpi = 96, bbox_inches = 'tight', pad_inches = 0.2)
plt.show()
</code>```

I am trying to create an animation that will plot the coordinates for each column and then iterate over the values in the index. In the end I am trying to have it iterate over the 14,403 rows and change the markings color based on the value. I am currently having trouble even animating the plot for the coordinates alone.

I would love to be able to implement bqplot, but the scatter animations I've followed on GitHub have not worked yet.

The map currently looks like below. It'd be wicked cool if each dot can fluctuate in color based on the current iterations value.

Thank you for reading.

答:
You can use the animation module for this. These are the general steps:

Convert the values into a colour

Update the color at each step

Save the animation

Here is some code:

```<code>import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import matplotlib.animation as animation
import numpy as np

land_color = '#f5f5f3'
water_color = '#cdd2d4'
coastline_color = '#f5f5f3'
border_color = '#bbbbbb'
meridian_color = '#f5f5f3'
marker_fill_color = '#0000ff'
marker_edge_color = 'None'

# Some dummy data
longVals = np.random.uniform(-120,-80, 1000)
latVals = np.random.uniform(35, 45, 1000)
vals = np.random.uniform(size=(200,1000))

# Be careful - the values that go into the colormap function
#  must be integers between 0 and 254
normalisedVals = 254*(vals-vals.min())/(vals.max()-vals.min())
normalisedVals = normalisedVals.astype(np.int)
cm = plt.cm.spectral_r

fig = plt.figure(figsize = (15, 10))
ax = fig.add_subplot(111, facecolor = '#ffffff', frame_on = False)
ax.set_title('Transportable Array', fontsize = 24, color = '#333333')

# draw the basemap and its features
m = Basemap(width = 5500000,height = 3300000,
            resolution = 'l', area_thresh = 1000., projection = 'lcc',
            lat_1 = 45., lat_2 = 55, lat_0 = 37, lon_0 = -98.)
m.drawmapboundary(color = border_color, fill_color = water_color)
m.drawcoastlines(color = coastline_color)
m.drawcountries(color = border_color)
m.fillcontinents(color = land_color, lake_color = water_color)
m.drawparallels(np.arange(-90., 120., 30.), color = meridian_color)
m.drawmeridians(np.arange(0., 420., 60.), color = meridian_color)

x, y = m(longVals, latVals)
scat = m.scatter(x, y, s = 8, c = normalisedVals[0], edgecolor = marker_edge_color, alpha = 1, zorder = 3)

def init():
    return scat,

def animate(i):
    col = cm(normalisedVals[i])
    scat.set_color(col)
    return scat,

anim = animation.FuncAnimation(fig, animate, init_func=init, frames=100, interval=20, blit=False, repeat=False)
anim.save('animation.gif', writer='imagemagick', fps=60)
</code>```

I should warn you that for 14k rows this will take a while.
Also I would recommend saving as an mp4 rather than a gif due to better compression.
If you have any questions let me know!

Title: Python - Animate basemap scatterplot

Body:
I have a DataFrame with shape (14403, 438) that consists of longitudes and latitudes as well as values. The DataFrame is as:

I am plotting the coordinates as:

# define map colors
land_color = '#f5f5f3'
water_color = '#cdd2d4'
coastline_color = '#f5f5f3'
border_color = '#bbbbbb'
meridian_color = '#f5f5f3'
marker_fill_color = '#0000ff'
marker_edge_color = 'None'

# create the plot
fig = plt.figure(figsize = (15, 10))
ax = fig.add_subplot(111, facecolor = '#ffffff', frame_on = False)
ax.set_title('Transportable Array', fontsize = 24, color = '#333333')

#lon_0  center of desired map domain (in degrees).
#lat_0  center of desired map domain (in degrees).
#width  width of desired map domain in projection coordinates (meters).
#height height of desired map domain in projection coordinates (meters).

# draw the basemap and its features
m = Basemap(width = 5500000,height = 3300000,
            resolution = 'l', area_thresh = 1000., projection = 'lcc',\
            lat_1 = 45., lat_2 = 55, lat_0 = 37, lon_0 = -98.)
m.drawmapboundary(color = border_color, fill_color = water_color)
m.drawcoastlines(color = coastline_color)
m.drawcountries(color = border_color)
m.fillcontinents(color = land_color, lake_color = water_color)
m.drawparallels(np.arange(-90., 120., 30.), color = meridian_color)
m.drawmeridians(np.arange(0., 420., 60.), color = meridian_color)

# project the location history points then scatter plot them
x, y = m(stations.loc['longitude'].values, stations.loc['latitude'].values)
m.scatter(x, y, s = 8, color = marker_fill_color, edgecolor = marker_edge_color, alpha = 1, zorder = 3)

# show & save the map
plt.savefig('Transportable_Array.png', dpi = 96, bbox_inches = 'tight', pad_inches = 0.2)
plt.show()

I am trying to create an animation that will plot the coordinates for each column and then iterate over the values in the index. In the end I am trying to have it iterate over the 14,403 rows and change the markings color based on the value. I am currently having trouble even animating the plot for the coordinates alone.

I would love to be able to implement bqplot, but the scatter animations I've followed on GitHub have not worked yet.

The map currently looks like below. It'd be wicked cool if each dot can fluctuate in color based on the current iterations value.

Thank you for reading.

Body:
You can use the animation module for this. These are the general steps:

Convert the values into a colour

Update the color at each step

Save the animation

Here is some code:

import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import matplotlib.animation as animation
import numpy as np

land_color = '#f5f5f3'
water_color = '#cdd2d4'
coastline_color = '#f5f5f3'
border_color = '#bbbbbb'
meridian_color = '#f5f5f3'
marker_fill_color = '#0000ff'
marker_edge_color = 'None'

# Some dummy data
longVals = np.random.uniform(-120,-80, 1000)
latVals = np.random.uniform(35, 45, 1000)
vals = np.random.uniform(size=(200,1000))

# Be careful - the values that go into the colormap function
#  must be integers between 0 and 254
normalisedVals = 254*(vals-vals.min())/(vals.max()-vals.min())
normalisedVals = normalisedVals.astype(np.int)
cm = plt.cm.spectral_r

fig = plt.figure(figsize = (15, 10))
ax = fig.add_subplot(111, facecolor = '#ffffff', frame_on = False)
ax.set_title('Transportable Array', fontsize = 24, color = '#333333')

# draw the basemap and its features
m = Basemap(width = 5500000,height = 3300000,
            resolution = 'l', area_thresh = 1000., projection = 'lcc',
            lat_1 = 45., lat_2 = 55, lat_0 = 37, lon_0 = -98.)
m.drawmapboundary(color = border_color, fill_color = water_color)
m.drawcoastlines(color = coastline_color)
m.drawcountries(color = border_color)
m.fillcontinents(color = land_color, lake_color = water_color)
m.drawparallels(np.arange(-90., 120., 30.), color = meridian_color)
m.drawmeridians(np.arange(0., 420., 60.), color = meridian_color)

x, y = m(longVals, latVals)
scat = m.scatter(x, y, s = 8, c = normalisedVals[0], edgecolor = marker_edge_color, alpha = 1, zorder = 3)

def init():
    return scat,

def animate(i):
    col = cm(normalisedVals[i])
    scat.set_color(col)
    return scat,

anim = animation.FuncAnimation(fig, animate, init_func=init, frames=100, interval=20, blit=False, repeat=False)
anim.save('animation.gif', writer='imagemagick', fps=60)

I should warn you that for 14k rows this will take a while.
Also I would recommend saving as an mp4 rather than a gif due to better compression.
If you have any questions let me know!


问:
Why is this nested relation in LoopBack returning duplicate results?
When I query to include a nested model – e.g. GET /api/Widgets/1?filter={include: {"foos": "bars"}} – I get duplicate foos in my results. I thought this was due to a LEFT JOIN or something like that, as I'm using MySQL, but when I run LoopBack in the loopback:connector:mysql debug mode, I can see that the query for the initial widget runs once, but that the query for foo runs twice, and the query for bar runs twice. Why is this behavior occurring, and what can I alter (my models, my code or my expectations)?

Models:

```<code>{
  "name": "Widget",
  ...
  "relations": {
    "foos": {
      "type": "hasMany",
      "model": "Foo",
      "foreignKey": "widgetId"
    }
  }
}

{
  "name": "Foo",
  ...
  "relations": {
    "bars": {
      "type": "hasMany",
      "model": "Bar",
      "foreignKey": "fooId"
    },
    "widget": {
      "type": "belongsTo",
      "model": "Widget",
      "foreignKey": ""
    }
  }
}

{
  "name": "Bar"
  ...
  "relations": {
    "foo": {
      "type": "belongsTo",
      "model": "Foo",
      "foreignKey": ""
    }
  }
}
</code>```

Results:

```<code>{
  id: 1
  foos: [
    {
      id: 2,
      bars: [
        {
          id: 3
        }
      ]
    },
    {
      id: 2,
      bars: [
        {
          id: 3
        }
      ]
    }
  ]
}
</code>```

Expecting:

```<code>{
  id: 1
  foos: [
    {
      id: 2,
      bars: [
        {
          id: 3
        }
      ]
    }
  ]
}
</code>```

This is paraphrased SQL that I see being run for this request:

```<code>SELECT `...` FROM `Widget` WHERE `id`=1 ORDER BY `id` LIMIT 1
SELECT `...` FROM `Foo` WHERE `widget_id` IN (1) ORDER BY `id`
SELECT `...` FROM `Foo` WHERE `widget_id` IN (1) ORDER BY `id`
SELECT `...` FROM `Bar` WHERE `foo_id` IN (2) ORDER BY `id`
SELECT `...` FROM `Bar` WHERE `foo_id` IN (2) ORDER BY `id`
</code>```

I'm using Loopback 3.x.

Update: While a request of GET /api/Widgets/1?filter={include: {"foos": "bars"}} exhibits this behavior, a server-side execution of Widgets.findById(id, {include: {"foos": "bars"}}) works perfectly. So, at the moment I'll create a remote method that does this and perhaps file a bug report with LoopBack.

答:
I was using this mixin that limits the limit of a query to max out at a defined value. When include is present in a query, the mixin also sets a limit on the scope of the include like so:

"include": {"foo":"bar","scope":{"limit":1}}

Seems the mixin was assuming all includes that are objects would be written in the form of {"relation":"foo", "scope":{"include:"bars"}}, so includes were getting added twice.

For what it's worth, I wrote this simple mixin to limit the maximum number of results unless specified and stopped using the one linked above:

common/models/model.json:

"mixins": {
    "ResultsetLimit": {
        "limit": 100
    }
}
```

<p><strong>common/mixins/resultset-limit.js:</strong></p>

<pre class="lang-js prettyprint-override"><code>const _ = require('lodash');

module.exports = (Model, options) => {

    /**
     * Modify incoming query to apply appropriate limit filters.
     */
    Model.beforeRemote('**', (ctx, unused, next) => {

        // Get the limit from the request, defaulting to the max limit.
        const request_limit = _.toNumber(_.get(ctx, 'args.filter.limit', options.limit));

        // Set the limit.
        _.set(ctx, 'args.filter.limit', request_limit);

        next();

    });

};
</code>```

Body:
When I query to include a nested model – e.g. GET /api/Widgets/1?filter={include: {"foos": "bars"}} – I get duplicate foos in my results. I thought this was due to a LEFT JOIN or something like that, as I'm using MySQL, but when I run LoopBack in the loopback:connector:mysql debug mode, I can see that the query for the initial widget runs once, but that the query for foo runs twice, and the query for bar runs twice. Why is this behavior occurring, and what can I alter (my models, my code or my expectations)?

Models:

{
  "name": "Widget",
  ...
  "relations": {
    "foos": {
      "type": "hasMany",
      "model": "Foo",
      "foreignKey": "widgetId"
    }
  }
}

{
  "name": "Foo",
  ...
  "relations": {
    "bars": {
      "type": "hasMany",
      "model": "Bar",
      "foreignKey": "fooId"
    },
    "widget": {
      "type": "belongsTo",
      "model": "Widget",
      "foreignKey": ""
    }
  }
}

{
  "name": "Bar"
  ...
  "relations": {
    "foo": {
      "type": "belongsTo",
      "model": "Foo",
      "foreignKey": ""
    }
  }
}

Results:

{
  id: 1
  foos: [
    {
      id: 2,
      bars: [
        {
          id: 3
        }
      ]
    },
    {
      id: 2,
      bars: [
        {
          id: 3
        }
      ]
    }
  ]
}

Expecting:

{
  id: 1
  foos: [
    {
      id: 2,
      bars: [
        {
          id: 3
        }
      ]
    }
  ]
}

This is paraphrased SQL that I see being run for this request:

SELECT `...` FROM `Widget` WHERE `id`=1 ORDER BY `id` LIMIT 1
SELECT `...` FROM `Foo` WHERE `widget_id` IN (1) ORDER BY `id`
SELECT `...` FROM `Foo` WHERE `widget_id` IN (1) ORDER BY `id`
SELECT `...` FROM `Bar` WHERE `foo_id` IN (2) ORDER BY `id`
SELECT `...` FROM `Bar` WHERE `foo_id` IN (2) ORDER BY `id`

I'm using Loopback 3.x.

Update: While a request of GET /api/Widgets/1?filter={include: {"foos": "bars"}} exhibits this behavior, a server-side execution of Widgets.findById(id, {include: {"foos": "bars"}}) works perfectly. So, at the moment I'll create a remote method that does this and perhaps file a bug report with LoopBack.

Body:
I was using this mixin that limits the limit of a query to max out at a defined value. When include is present in a query, the mixin also sets a limit on the scope of the include like so:

"include": {"foo":"bar","scope":{"limit":1}}

Seems the mixin was assuming all includes that are objects would be written in the form of {"relation":"foo", "scope":{"include:"bars"}}, so includes were getting added twice.

For what it's worth, I wrote this simple mixin to limit the maximum number of results unless specified and stopped using the one linked above:

common/models/model.json:

"mixins": {
    "ResultsetLimit": {
        "limit": 100
    }
}

common/mixins/resultset-limit.js:

const _ = require('lodash');

module.exports = (Model, options) => {

    /**
     * Modify incoming query to apply appropriate limit filters.
     */
    Model.beforeRemote('**', (ctx, unused, next) => {

        // Get the limit from the request, defaulting to the max limit.
        const request_limit = _.toNumber(_.get(ctx, 'args.filter.limit', options.limit));

        // Set the limit.
        _.set(ctx, 'args.filter.limit', request_limit);

        next();

    });

};

ContentLicense: CC BY-SA 4.0


问:
Why is my python file not able to be imported into my pycharm program
I have a code in a python file named happy_histogram.py :

```<code> __author__ = 'Bauer'

from graphics import GraphicsWindow

def drawHappyFace(canvas,x,y):
canvas.setColor("yellow")
canvas.setOutline("black")
#canvas.drawOval(100, 100, 30, 30)
canvas.drawOval(x, y, 30, 30)
canvas.setColor("black")
#canvas.drawOval(108, 110, 5, 5)
canvas.drawOval(x+8, y+10, 5, 5)
#canvas.drawOval(118, 110, 5, 5)
canvas.drawOval(x+18, y+10, 5, 5)
#canvas.drawLine(110, 122, 113, 125)
canvas.drawLine(x+10, y+22, x+13, y+25)
#canvas.drawLine(113, 125, 117, 125)
canvas.drawLine(x+13, y+25, x+17, y+25)
#canvas.drawLine(117, 125, 120, 122)
canvas.drawLine(x+17, y+25, x+20, y+22)
</code>```

I need to import this into my pycharm program to use the functions.
I tried a few ways to import, but they dont work.
NOTE: The pycharm project and the python file are in the same folder.

Thanks!

答:
Not sure what you mean by import, but the indentation was wrong. And I guess the package-name where you were trying to import GraphicsWindow from.

First download:

http://www.ezgraphics.org/uploads/Software/Download/ezgraphics-2.1.tar.gz

Install it:

pip install ezgraphics-2.1.tar.gz

Then try this:

```<code>__author__ = 'Bauer'

from ezgraphics import GraphicsWindow

def drawHappyFace(canvas,x,y):
    canvas.setColor("yellow")
    canvas.setOutline("black")
    #canvas.drawOval(100, 100, 30, 30)
    canvas.drawOval(x, y, 30, 30)
    canvas.setColor("black")
    #canvas.drawOval(108, 110, 5, 5)
    canvas.drawOval(x+8, y+10, 5, 5)
    #canvas.drawOval(118, 110, 5, 5)
    canvas.drawOval(x+18, y+10, 5, 5)
    #canvas.drawLine(110, 122, 113, 125)
    canvas.drawLine(x+10, y+22, x+13, y+25)
    #canvas.drawLine(113, 125, 117, 125)
    canvas.drawLine(x+13, y+25, x+17, y+25)
    #canvas.drawLine(117, 125, 120, 122)
    canvas.drawLine(x+17, y+25, x+20, y+22)

    drawHappyFace(GraphicsWindow().canvas(),400,400)
</code>```

I guess you want something like this:

```<code>__author__ = 'Bauer'

from ezgraphics import GraphicsWindow
import time

def drawHappyFace(canvas,x,y):
    canvas.setHeight(200)
    canvas.setWidth(200)
    canvas.setColor("yellow")
    canvas.setOutline("black")
    canvas.drawOval(100, 100, 30, 30)
    canvas.drawOval(x, y, 30, 30)
    canvas.setColor("black")
    canvas.drawOval(108, 110, 5, 5)
    canvas.drawOval(x+8, y+10, 5, 5)
    canvas.drawOval(118, 110, 5, 5)
    canvas.drawOval(x+18, y+10, 5, 5)
    canvas.drawLine(110, 122, 113, 125)
    canvas.drawLine(x+10, y+22, x+13, y+25)
    canvas.drawLine(113, 125, 117, 125)
    canvas.drawLine(x+13, y+25, x+17, y+25)
    canvas.drawLine(117, 125, 120, 122)
    canvas.drawLine(x+17, y+25, x+20, y+22)
    time.sleep(10000)

    drawHappyFace(GraphicsWindow().canvas(),10,10)
</code>```

Body:
I have a code in a python file named happy_histogram.py :

 __author__ = 'Bauer'

from graphics import GraphicsWindow

def drawHappyFace(canvas,x,y):
canvas.setColor("yellow")
canvas.setOutline("black")
#canvas.drawOval(100, 100, 30, 30)
canvas.drawOval(x, y, 30, 30)
canvas.setColor("black")
#canvas.drawOval(108, 110, 5, 5)
canvas.drawOval(x+8, y+10, 5, 5)
#canvas.drawOval(118, 110, 5, 5)
canvas.drawOval(x+18, y+10, 5, 5)
#canvas.drawLine(110, 122, 113, 125)
canvas.drawLine(x+10, y+22, x+13, y+25)
#canvas.drawLine(113, 125, 117, 125)
canvas.drawLine(x+13, y+25, x+17, y+25)
#canvas.drawLine(117, 125, 120, 122)
canvas.drawLine(x+17, y+25, x+20, y+22)

I need to import this into my pycharm program to use the functions.
I tried a few ways to import, but they dont work.
NOTE: The pycharm project and the python file are in the same folder.

Thanks!

Body:
Not sure what you mean by import, but the indentation was wrong. And I guess the package-name where you were trying to import GraphicsWindow from.

First download:

http://www.ezgraphics.org/uploads/Software/Download/ezgraphics-2.1.tar.gz

Install it:

pip install ezgraphics-2.1.tar.gz

Then try this:

__author__ = 'Bauer'

from ezgraphics import GraphicsWindow

def drawHappyFace(canvas,x,y):
    canvas.setColor("yellow")
    canvas.setOutline("black")
    #canvas.drawOval(100, 100, 30, 30)
    canvas.drawOval(x, y, 30, 30)
    canvas.setColor("black")
    #canvas.drawOval(108, 110, 5, 5)
    canvas.drawOval(x+8, y+10, 5, 5)
    #canvas.drawOval(118, 110, 5, 5)
    canvas.drawOval(x+18, y+10, 5, 5)
    #canvas.drawLine(110, 122, 113, 125)
    canvas.drawLine(x+10, y+22, x+13, y+25)
    #canvas.drawLine(113, 125, 117, 125)
    canvas.drawLine(x+13, y+25, x+17, y+25)
    #canvas.drawLine(117, 125, 120, 122)
    canvas.drawLine(x+17, y+25, x+20, y+22)

    drawHappyFace(GraphicsWindow().canvas(),400,400)

I guess you want something like this:

__author__ = 'Bauer'

from ezgraphics import GraphicsWindow
import time

def drawHappyFace(canvas,x,y):
    canvas.setHeight(200)
    canvas.setWidth(200)
    canvas.setColor("yellow")
    canvas.setOutline("black")
    canvas.drawOval(100, 100, 30, 30)
    canvas.drawOval(x, y, 30, 30)
    canvas.setColor("black")
    canvas.drawOval(108, 110, 5, 5)
    canvas.drawOval(x+8, y+10, 5, 5)
    canvas.drawOval(118, 110, 5, 5)
    canvas.drawOval(x+18, y+10, 5, 5)
    canvas.drawLine(110, 122, 113, 125)
    canvas.drawLine(x+10, y+22, x+13, y+25)
    canvas.drawLine(113, 125, 117, 125)
    canvas.drawLine(x+13, y+25, x+17, y+25)
    canvas.drawLine(117, 125, 120, 122)
    canvas.drawLine(x+17, y+25, x+20, y+22)
    time.sleep(10000)

    drawHappyFace(GraphicsWindow().canvas(),10,10)


问:
jQuery form validation check returns 'undefined'
I am having some trouble with a form I am trying to submit using jquery $.post, I am using this validation plugin to validate the form, but when I try to check the form with $("#form").validationEngine('validate') I constantly get undefined and then the page reloads, here is the code:

```<code>$(document).ready(function() {

        $("#form").validationEngine();

        $("#submit").live('click',function(){
            var valid = $("#form").validationEngine('validate');
            var vars = $("#form").serialize();

            if(valid == true){

                //disable submit button
                $("#submit").attr('disabled','disabled');

                $.post('thank_you.php',vars,function(data){
                    alert(data);
                });

            }else{
                $("#form").validationEngine();
            }
        });
});
</code>```

the HTML:

```<code><form id="form">
    <div>
        <label for='province'>Select your current province </label>
        <select id='province' name='province' class='validate[required] text-input'>
            <option value=''>Select one</option>
            <option>province1</option>
            <option>province2</option>
        </select>
    </div>
    <br />
    <div>
        <label for="city">Select your current city</label><br />
        <select id="city" name="city" class="validate[required] text-input">
            <option value="">Select one</option>
            <option>city1</option>
            <option>city2</option>
        </select>
    </div>
    <br />
    <div>
        <label for="name_surname">Name & Surname</label><br />
        <input type="text" id="name_surname" name="name_surname" class="validate[required] text-input" />
    </div>
    <br />
    <div>
        <label for="email">Email Address</label><br />
        <input type="text" id="email" name="email" class="validate[required,custom[email]] text-input" />
    </div>
    <div>
        <input type="image" src="images/solar_38.gif" width="82" height="32" alt"submit" id="submit" />
    </div>
</form>
</code>```

I have had a look on the plugin's site, and have found nothing that could indicate why I am getting this, is there anything in my code that could be causing me to get undefined when I try to validate the form?

答:
I tried creating at a demo and ran into the same error as you.
Only when i included both the below js , did it start working.
May be its the same in your case :)</p>

```<code><script src="http://www.position-relative.net/creation/formValidator/js/jquery.validationEngine-en.js"></script>
<script src="http://www.position-relative.net/creation/formValidator/js/jquery.validationEngine.js"></script>
</code>```

Body:
I am having some trouble with a form I am trying to submit using jquery $.post, I am using this validation plugin to validate the form, but when I try to check the form with $("#form").validationEngine('validate') I constantly get undefined and then the page reloads, here is the code:

$(document).ready(function() {

        $("#form").validationEngine();

        $("#submit").live('click',function(){
            var valid = $("#form").validationEngine('validate');
            var vars = $("#form").serialize();

            if(valid == true){

                //disable submit button
                $("#submit").attr('disabled','disabled');

                $.post('thank_you.php',vars,function(data){
                    alert(data);
                });

            }else{
                $("#form").validationEngine();
            }
        });
});

the HTML:

<form id="form">

        Select your current province
        <select id='province' name='province' class='validate[required] text-input'>
            <option value=''>Select one</option>
            <option>province1</option>
            <option>province2</option>
        </select>

        Select your current city

        <select id="city" name="city" class="validate[required] text-input">
            <option value="">Select one</option>
            <option>city1</option>
            <option>city2</option>
        </select>

        Name & Surname

        <input type="text" id="name_surname" name="name_surname" class="validate[required] text-input" />

        Email Address

        <input type="text" id="email" name="email" class="validate[required,custom[email]] text-input" />

        <input type="image" src="images/solar_38.gif" width="82" height="32" alt"submit" id="submit" />

</form>

I have had a look on the plugin's site, and have found nothing that could indicate why I am getting this, is there anything in my code that could be causing me to get undefined when I try to validate the form?

Body:
I tried creating at a demo and ran into the same error as you.
Only when i included both the below js , did it start working.
May be its the same in your case :)

<script src="http://www.position-relative.net/creation/formValidator/js/jquery.validationEngine-en.js"></script>
<script src="http://www.position-relative.net/creation/formValidator/js/jquery.validationEngine.js"></script>


问:
Finding first paired string in a string
Let's say you have this string:

"3434989348584934944989353534989".

How do you find the first paired string? In this case I want the output to be 4989.

I want my method to be:

```<code>static string FindFirst(int length, string stringpair)
{
// code here
}
</code>```

Thank you.

答:
You can implement following method:

```<code>        static string FindFirst(int length, string stringpair)
        {
            var set = new HashSet<string>();
            for (int i = 0; i < stringpair.Length; i++)
            {
                string subStr = stringpair.Substring(i, length);

                if (set.Contains(subStr)) // if contains, then there is already 1 key with same value
                    return subStr;

                set.Add(subStr);
            }
            return null;
        }
</code>```

DotNetFiddle

Title: Finding first paired string in a string

Body:
Let's say you have this string:

"3434989348584934944989353534989".

How do you find the first paired string? In this case I want the output to be 4989.

I want my method to be:

static string FindFirst(int length, string stringpair)
{
// code here
}

Thank you.

Body:
You can implement following method:

        static string FindFirst(int length, string stringpair)
        {
            var set = new HashSet<string>();
            for (int i = 0; i < stringpair.Length; i++)
            {
                string subStr = stringpair.Substring(i, length);

                if (set.Contains(subStr)) // if contains, then there is already 1 key with same value
                    return subStr;

                set.Add(subStr);
            }
            return null;
        }

DotNetFiddle


问:
R - ReporteRs package - word template with dynamic values
good day people,

I'm working on a word based reports automation task. These reports are basically some standard text, a dozen or so charts, some numeric/trend text values that I need to populated based on logic. The trend text, numeric values or charts are to be generated from backend database.

I'm able to produce a blank document with charts using database, the R packages I used are ReporteRs, RODBC, officer and corresponding dependency packages, ggplot2 for charts.
However what I would like to achieve is, have a word document template with some sort of placeholders where I can put the charts and these numeric values.

I've basic code as following

```<code>    doc <- docx(title="my doc")
    mychart <- ggplot(.....)
    doc <- addPlot(doc, fun=print, x = mychart)
    writeDoc(doc, filename)
</code>```

Can anyone advise how to approach this task. I saw usage of template parameter in docx but I couldn't find suitable examples of putting values in placeholders or putting charts at particular placeholders inside Word document.

Hope I've explained it clearly, if not please let me know.

答:
I would recommend using VBA for this, not R.  Do some google-research on DocVariables in Word.  Add some DocVariables to your Word template, keep your analytics in Excel, and then push what you have in Excel into the Word DocVariables.  Use the script below, which runs in Excel, to make everything work.

```<code>Sub PushToWord()

Dim objWord As New Word.Application
Dim doc As Word.Document
Dim bkmk As Word.Bookmark
sWdFileName = Application.GetOpenFilename(, , , , False)
Set doc = objWord.Documents.Open(sWdFileName)
'On Error Resume Next

objWord.ActiveDocument.variables("BrokerFirstName").Value = Range("BrokerFirstName").Value
objWord.ActiveDocument.variables("BrokerLastName").Value = Range("BrokerLastName").Value
objWord.ActiveDocument.variables("Ryan").Value = Range("Ryan").Value

objWord.ActiveDocument.Fields.Update

'On Error Resume Next
objWord.Visible = True

End Sub
</code>```

Finally, add a reference to Word, from Excel.  Tools > References > Microsoft Word xxx Object Library.

Body:
good day people,

I'm working on a word based reports automation task. These reports are basically some standard text, a dozen or so charts, some numeric/trend text values that I need to populated based on logic. The trend text, numeric values or charts are to be generated from backend database.

I'm able to produce a blank document with charts using database, the R packages I used are ReporteRs, RODBC, officer and corresponding dependency packages, ggplot2 for charts.
However what I would like to achieve is, have a word document template with some sort of placeholders where I can put the charts and these numeric values.

I've basic code as following

    doc <- docx(title="my doc")
    mychart <- ggplot(.....)
    doc <- addPlot(doc, fun=print, x = mychart)
    writeDoc(doc, filename)

Can anyone advise how to approach this task. I saw usage of template parameter in docx but I couldn't find suitable examples of putting values in placeholders or putting charts at particular placeholders inside Word document.

Hope I've explained it clearly, if not please let me know.

Body:
I would recommend using VBA for this, not R.  Do some google-research on DocVariables in Word.  Add some DocVariables to your Word template, keep your analytics in Excel, and then push what you have in Excel into the Word DocVariables.  Use the script below, which runs in Excel, to make everything work.

Sub PushToWord()

Dim objWord As New Word.Application
Dim doc As Word.Document
Dim bkmk As Word.Bookmark
sWdFileName = Application.GetOpenFilename(, , , , False)
Set doc = objWord.Documents.Open(sWdFileName)
'On Error Resume Next

objWord.ActiveDocument.variables("BrokerFirstName").Value = Range("BrokerFirstName").Value
objWord.ActiveDocument.variables("BrokerLastName").Value = Range("BrokerLastName").Value
objWord.ActiveDocument.variables("Ryan").Value = Range("Ryan").Value

objWord.ActiveDocument.Fields.Update

'On Error Resume Next
objWord.Visible = True

End Sub

Finally, add a reference to Word, from Excel.  Tools > References > Microsoft Word xxx Object Library.


问:
R help - either/or function?
Very new coder over here so excuse me if this is overwhelmingly simple.

I'm trying to build a dataframe to sort certain data points (x) that fall beyond given dimensions but I'm having trouble doing so.

```<code> outside <- subset(dataframe, x == "1" & wid < 1 | wid > 5 | hei < 1 | hei > 5)
</code>```

x is a binary variable, so I'm just looking for 1s.

After corrections, this current formula seems just to determine any points in the dataset that fall outside of the dimensions but is counting x variables of both 0 and 1.

Thanks for your help everybody! Sorry I'm new to this website (and code, for that matter).

答:
If your condition works apart from the x == "1" part, then you probably just need to use parens to group the conditions:

```<code>outside <- subset(dataframe, (x == "1") & (wid < 1 | wid > 5 | hei < 1 | hei > 5))
</code>```

As conditions get more complex it sometimes helps to separate these out, e.g.:

```<code>x_match = x == "1"
outside_box = wid < 1 | wid > 5 | hei < 1 | hei > 5
outside = subset(dataframe, x_match & outside_box)
</code>```

Title: R help - either/or function?

Body:
Very new coder over here so excuse me if this is overwhelmingly simple.

I'm trying to build a dataframe to sort certain data points (x) that fall beyond given dimensions but I'm having trouble doing so.

 outside <- subset(dataframe, x == "1" & wid < 1 | wid > 5 | hei < 1 | hei > 5)

x is a binary variable, so I'm just looking for 1s.

After corrections, this current formula seems just to determine any points in the dataset that fall outside of the dimensions but is counting x variables of both 0 and 1.

Thanks for your help everybody! Sorry I'm new to this website (and code, for that matter).

Body:
If your condition works apart from the x == "1" part, then you probably just need to use parens to group the conditions:

outside <- subset(dataframe, (x == "1") & (wid < 1 | wid > 5 | hei < 1 | hei > 5))

As conditions get more complex it sometimes helps to separate these out, e.g.:

x_match = x == "1"
outside_box = wid < 1 | wid > 5 | hei < 1 | hei > 5
outside = subset(dataframe, x_match & outside_box)


问:
AngularFire2 Suscribe return values FAIL
I have this code in my authService

```<code>    constructor(
    private afAuth: AngularFireAuth,
    private db: AngularFireDatabase,
    private router: Router
  ) {
    this.authState = afAuth.authState;
    this.authState.subscribe((user: firebase.User) => {
        this.authState = user;
    });
    if ( this.authenticated ) {
      // this.router.navigate([`/content`]);
    }
  }

  // Returns true if user is logged in
  get authenticated(): any {
    return this.authState;
  }
</code>```

I call the get authenticated and it returns undefined:

COMPONENT

```<code>    constructor(
    private auth: AuthService
  ) {
      this.currentUser = this.auth.authenticated;
  }
showUser() {
    console.log(this.currentUser.uid);
  }
</code>```

I need help to fix it, any idea?

答:
AngularFireAuth.authState is async and an Observable. You can read up on what an Observable is here on the ReativeX site.

In sort, the authState observable is a sequence of values over time, aysnc (takes some time to resolve), and lazy (you need to subscribe to get a value, which is why your console.log outside is not working.)

If you need to access the "current" value outside of a subscribe block I recommend using a BehaviorSubject (again check out ReactiveX for more information on subjects):

```<code>currentAuthState: BehaviorSubject<firebase.User|null|undefined>;

constructor(afAuth: AngularFireAuth) {
  this.currentAuthState = new BehaviorSubject(undefined);
  afAuth.authState.subscribe(this.currentAuthState);
}
</code>```

Then you can access: this.currentAuthState.getValue() to see what the current value is; .subscribe to listen to changes; use any other RxJS operator such as map, do, swtichMap, etc.; and use an async pipes in your view {{ (currentAuthState | async)?.email }}

It will be undefined when loading, null if no user is logged in, and a firebase.User if a user is logged in.

Body:
I have this code in my authService

    constructor(
    private afAuth: AngularFireAuth,
    private db: AngularFireDatabase,
    private router: Router
  ) {
    this.authState = afAuth.authState;
    this.authState.subscribe((user: firebase.User) => {
        this.authState = user;
    });
    if ( this.authenticated ) {
      // this.router.navigate([`/content`]);
    }
  }

  // Returns true if user is logged in
  get authenticated(): any {
    return this.authState;
  }

I call the get authenticated and it returns undefined:

COMPONENT

    constructor(
    private auth: AuthService
  ) {
      this.currentUser = this.auth.authenticated;
  }
showUser() {
    console.log(this.currentUser.uid);
  }

I need help to fix it, any idea?

Body:
AngularFireAuth.authState is async and an Observable. You can read up on what an Observable is here on the ReativeX site.

In sort, the authState observable is a sequence of values over time, aysnc (takes some time to resolve), and lazy (you need to subscribe to get a value, which is why your console.log outside is not working.)

If you need to access the "current" value outside of a subscribe block I recommend using a BehaviorSubject (again check out ReactiveX for more information on subjects):

currentAuthState: BehaviorSubject<firebase.User|null|undefined>;

constructor(afAuth: AngularFireAuth) {
  this.currentAuthState = new BehaviorSubject(undefined);
  afAuth.authState.subscribe(this.currentAuthState);
}

Then you can access: this.currentAuthState.getValue() to see what the current value is; .subscribe to listen to changes; use any other RxJS operator such as map, do, swtichMap, etc.; and use an async pipes in your view {{ (currentAuthState | async)?.email }}

It will be undefined when loading, null if no user is logged in, and a firebase.User if a user is logged in.


问:
Invalid syntax CASE statement
I've been struggling all day with a really simple case statement in SQL...

I have this piece of code:

```<code>UPDATE `alugueis`
    SET    `status` = CASE
             WHEN `pago_em` is null THEN 'Atrasado'
             WHEN `pago_em` is '' THEN 'Atrasado'
             ELSE `status`
           END
WHERE  `vencimento` <= CURDATE()
</code>```

and the error I get is: [1064][42000]: (conn:235) You have an error in your SQL syntax; check the manual .......

I don`t think I am mixing up the two forms of CASE, or am I?

Thank you so much!

答:
You cannot use IS ''

```<code>UPDATE `alugueis`
    SET    `status` = CASE
             WHEN `pago_em` is null THEN 'Atrasado'
             WHEN `pago_em` = '' THEN 'Atrasado'
             ELSE `status`
           END
WHERE  `vencimento` <= CURDATE()
</code>```

Title: Invalid syntax CASE statement

Body:
I've been struggling all day with a really simple case statement in SQL...

I have this piece of code:

UPDATE `alugueis`
    SET    `status` = CASE
             WHEN `pago_em` is null THEN 'Atrasado'
             WHEN `pago_em` is '' THEN 'Atrasado'
             ELSE `status`
           END
WHERE  `vencimento` <= CURDATE()

and the error I get is: [1064][42000]: (conn:235) You have an error in your SQL syntax; check the manual .......

I don`t think I am mixing up the two forms of CASE, or am I?

Thank you so much!

Body:
You cannot use IS ''

UPDATE `alugueis`
    SET    `status` = CASE
             WHEN `pago_em` is null THEN 'Atrasado'
             WHEN `pago_em` = '' THEN 'Atrasado'
             ELSE `status`
           END
WHERE  `vencimento` <= CURDATE()


问:
How to do a relative import from the parent directory?
I have searched this and found many answers, all of which tell me to do exactly what I am doing, here is my directory structure:

app/
+-- __init__.py
+-- app_manager.py
+-- app_gui/
|   +-- __init__.py
|   +-- app_gui.py
```

<p>in app_gui.py I have:</p>

```import tkinter as tk
from tkinter import ttk
from app_manager import AppManager
```

<p>in app manager:</p>

```class AppManager():
    def __init__(self):
    """ default constructor for app manager """
```

<p>In Visual Code, it actually resolves this to an auto completion, which tells me that at least Visual Code sees it as correctly done. However, if I run this I get the following error:</p>

<pre class="lang-none prettyprint-override"><code>ModuleNotFoundError: No Module named "app_manager"
</code>```

Edit

Full stack trace when changing to from app.app_manager import AppManager:

Traceback (most recent call last):
   File ".\app_gui\app_gui.py", line 4, in <module>
     from app_manager import AppManager
ModuleNotFoundError: No module named 'app_manager'
```

答:
Since app_manager.py is a directory above app_gui.py, I believe your import (if you wish to use a relative import) should be

```<code>from ..app_manager import AppManager
</code>```

EDIT to address error in comments: If you try to run this file directly, you will get a ValueError like in the comments. Relative imports work between modules inside of packages. Let's say that you use the import I wrote above, and then you have a file ONE LEVEL ABOVE your app directory called stuff.py, with the following contents:

```<code>import app.app_gui.app_gui
print('hello')
</code>```

Running stuff.py would look like:

```<code>$ python stuff.py
hello
</code>```

In other words, executing a file with relative imports directly with the python interpreter will result in an error, as it was not intended to be used this way. Rather, your model should be imported and executed by something outside of the module itself.

If you have a __main__ file inside of your app directory with the exact same code, you can also execute the module directly.

```<code>$ cat app/__main__.py
import app.app_gui.app_gui
print('hello')

$ python -m app
hello
</code>```

Body:
I have searched this and found many answers, all of which tell me to do exactly what I am doing, here is my directory structure:

app/
+-- __init__.py
+-- app_manager.py
+-- app_gui/
|   +-- __init__.py
|   +-- app_gui.py

in app_gui.py I have:

import tkinter as tk
from tkinter import ttk
from app_manager import AppManager

in app manager:

class AppManager():
    def __init__(self):
    """ default constructor for app manager """

In Visual Code, it actually resolves this to an auto completion, which tells me that at least Visual Code sees it as correctly done. However, if I run this I get the following error:

ModuleNotFoundError: No Module named "app_manager"

Edit

Full stack trace when changing to from app.app_manager import AppManager:

Traceback (most recent call last):
   File ".\app_gui\app_gui.py", line 4, in <module>
     from app_manager import AppManager
ModuleNotFoundError: No module named 'app_manager'

Body:
Since app_manager.py is a directory above app_gui.py, I believe your import (if you wish to use a relative import) should be

from ..app_manager import AppManager

EDIT to address error in comments: If you try to run this file directly, you will get a ValueError like in the comments. Relative imports work between modules inside of packages. Let's say that you use the import I wrote above, and then you have a file ONE LEVEL ABOVE your app directory called stuff.py, with the following contents:

import app.app_gui.app_gui
print('hello')

Running stuff.py would look like:

$ python stuff.py
hello

In other words, executing a file with relative imports directly with the python interpreter will result in an error, as it was not intended to be used this way. Rather, your model should be imported and executed by something outside of the module itself.

If you have a __main__ file inside of your app directory with the exact same code, you can also execute the module directly.

$ cat app/__main__.py
import app.app_gui.app_gui
print('hello')

$ python -m app
hello


答:
I think you intend:

```<code>UPDATE alugueis
    SET status = (CASE WHEN pago_em is null THEN 'Atrasado'
                       WHEN pago_em = '' THEN 'Atrasado'
                       ELSE status
                  END)
    WHERE vencimento <= CURDATE();
</code>```

The problem is the is ''.

This would more normally be written without the CASE:

```<code>UPDATE alugueis
    SET status = 'Atrasado'
    WHERE vencimento <= CURDATE() AND
          (pago_em IS NULL OR pago_em = '')
</code>```

Title: Invalid syntax CASE statement

Body:
I think you intend:

UPDATE alugueis
    SET status = (CASE WHEN pago_em is null THEN 'Atrasado'
                       WHEN pago_em = '' THEN 'Atrasado'
                       ELSE status
                  END)
    WHERE vencimento <= CURDATE();

The problem is the is ''.

This would more normally be written without the CASE:

UPDATE alugueis
    SET status = 'Atrasado'
    WHERE vencimento <= CURDATE() AND
          (pago_em IS NULL OR pago_em = '')


问:
Talend Data preparation : Mongodb already installed locally on this computer
I am trying to install Talend Data Preparation V1.3 on my windows server 2012R2.

I have uninstalled previous version 1.2 and deleted all directories related to it from my machine.
Now when i am trying to install v1.3 it is giving me the following error.
"MongoDB is ALREADY installed locally on this computer. Please either uninstall it or use "External Mongo DB" option to proceed."

Currently I dont have any external mongodb or can install it.

Please help me how to get rid of this.

答:
I managed to remove mongoDB from services list by running the following command:

```<code>sc delete talend-mongodb-6.4.1
</code>```

I restarted and errors stopped.

Body:
I managed to remove mongoDB from services list by running the following command:

sc delete talend-mongodb-6.4.1

I restarted and errors stopped.


问:
Efficient Python to Python IPC
What would be an inter-process communication (IPC) framework\technique with the following requirements:

Transfer native Python objects between two Python processes

Efficient in time and CPU (RAM efficiency irrelevant)

Cross-platform Win\Linux

Nice to have: works with PyPy

UPDATE 1: the processes are on the same host and use the same versions of Python and other modules

UPDATE 2: the processes are run independently by the user, no one of them spawns the others

答:
After some test, I found that the following approach works for Linux using mmap.

Linux has /dev/shm. If you create a shared memory using POSIX shm_open, a new file is created in this folder.

Although python's mmap module does not provide the shm_open function. we can use a normal open to create a file in /dev/shm and it is actually similar and reside in memory. (Use os.unlink to remove it)

Then for IPC, we can use mmap to map that file to the different processes' virtual memory space. All the processes share that memory. Python can use the memory as buffer and create object such as bytes and numpy arrays on top of it. Or we can use it through the ctypes interface.

Of course, process sync primitives are still needed to avoid race conditions.

See mmap doc, ctypes doc and numpy.load which has an mmap_mode option.

Title: Efficient Python to Python IPC


问:
Recursively remove element from tuple
having some issues with getting the correct result. I am trying to, by recursion, pass in a tuple of words and an item that is one word. The method should return the tuple minus the item. However I am getting an error that reads 'must be str, not tuple'. Here is what I have so far. Thanks in advance.

```<code>def filter_sequence(seq, item):
    try:
        if not seq:
            return ()
        elif item is seq[0]:
            return filter_sequence(seq[1:], item)
        else:
            return seq[0] + filter_sequence(seq[1:], item)
    except TypeError as e:
        print(e)
</code>```

Example:

If I call filter_sequence(("jelly","butter", "mustard"), 'butter')

 I should receive the tuple of ("jelly", "mustard")

I've attempted wrapping the last recursive call in str(), but then I just get a string back. Which I would have to break apart and format, which is not what I want to do.

I should mention that it is my goal to achieve this result with using built in solutions like for loops, while loops, if x in y... etc.

答:
A simpler method may be to try this:

```<code>def filter_sequence(l, target, total):
     if not l[1:]:
         return tuple(list(total)+[l[0]])
     if l[0] == target:
         return filter_sequence(l[1:], target, total)
     return filter_sequence(l[1:], target, tuple(list(total)+[l[0]]))

print(filter_sequence(("jelly","butter", "mustard"), 'butter'))
</code>```

Output:

```<code>('jelly', 'mustard')
</code>```

Title: Recursively remove element from tuple

Body:
having some issues with getting the correct result. I am trying to, by recursion, pass in a tuple of words and an item that is one word. The method should return the tuple minus the item. However I am getting an error that reads 'must be str, not tuple'. Here is what I have so far. Thanks in advance.

def filter_sequence(seq, item):
    try:
        if not seq:
            return ()
        elif item is seq[0]:
            return filter_sequence(seq[1:], item)
        else:
            return seq[0] + filter_sequence(seq[1:], item)
    except TypeError as e:
        print(e)

Example:

If I call filter_sequence(("jelly","butter", "mustard"), 'butter')

 I should receive the tuple of ("jelly", "mustard")

I've attempted wrapping the last recursive call in str(), but then I just get a string back. Which I would have to break apart and format, which is not what I want to do.

I should mention that it is my goal to achieve this result with using built in solutions like for loops, while loops, if x in y... etc.

Body:
A simpler method may be to try this:

def filter_sequence(l, target, total):
     if not l[1:]:
         return tuple(list(total)+[l[0]])
     if l[0] == target:
         return filter_sequence(l[1:], target, total)
     return filter_sequence(l[1:], target, tuple(list(total)+[l[0]]))

print(filter_sequence(("jelly","butter", "mustard"), 'butter'))

Output:

('jelly', 'mustard')


问:
how to get value if index contains certain value php
I have an array which contains alot of keys and values. I can get any value using the index. But I dont have the full index, I have a part of it, would I be able to get the value based on a part of the index.

Example:

```<code>$arr = array("Index"->"MyValue");
</code>```

$arr["Index"] will return "MyValue" but I need to do something like $arr["dex"] or $arr["My Index"]to return the same "MyValue"

答:
A foreach loop in the following form will allow you to inspect both the value and the key:

```<code>foreach( $my_array as $key => $value ) {
  // partial matching on $key here
}
</code>```

For simple substring matching strpos() would be preferable, but for more complex matching you may want preg_match().

Body:
I have an array which contains alot of keys and values. I can get any value using the index. But I dont have the full index, I have a part of it, would I be able to get the value based on a part of the index.

Example:

$arr = array("Index"->"MyValue");

$arr["Index"] will return "MyValue" but I need to do something like $arr["dex"] or $arr["My Index"]to return the same "MyValue"

Body:
A foreach loop in the following form will allow you to inspect both the value and the key:

foreach( $my_array as $key => $value ) {
  // partial matching on $key here
}

For simple substring matching strpos() would be preferable, but for more complex matching you may want preg_match().


问:
Different threads don't work together while doing different tasks
I'm creating two different threads which will solve same problem with different ways and I will calculate their solving time. I've created a structure like that;

MainController.java

```<code>public static void main(String[] args) throws Exception {
        MainController mc= new MainController();
        mc.setProblem();
        Thread1 thread1 = new Thread1("thread1",problem,approach1);
        Thread2 thread2 = new Thread2("thread2",problem,approach2);
        thread1.start();
        thread2.start();
    }
</code>```

Thread1.java

```<code>class Thread1 implements Runnable{

       public void run() {
          System.out.println("Running " +  threadName );
          try {
             solve(approach);
          } catch (Exception e) {
             System.out.println("Thread " +  threadName + " interrupted.");
          }
          //showTable();
          System.out.println("Thread " +  threadName + " exiting.");
       }

       public void start () {
          System.out.println("Starting " +  threadName );
          if (t == null) {
             t = new Thread (this, threadName);
             t.start ();
          }
       }

       public void solve(approach) throws Exception {

            // Throw an exception to stop the process if the puzzle is solved
            if (didIsolve())  {//true if yes
                    System.out.println("----" + threadName +"----");
                    showResult();
                    System.out.println("--------------------------");
                    throw new Exception("ex");
            }
        }
    }
</code>```

Thread2.java is the same as above code block.

And output like

```<code>    Creating thread1
    Creating thread2
    Starting thread1
    Starting thread2
    Running thread2
    Running thread1
    Thread thread1 exiting.
    ----thread2----
   RESULT METHOD OUTPUT
    --------------------------
    Thread thread2 interrupted.
    Thread thread2 exiting.
</code>```

As you see above, thread1 did not solve problem, at least did not show result.

Also I've checked this topics so far

multiple threads performing different tasks

Java threads to do different tasks?

Edit:

Well, I think I found the problem. I changed MainController class;

```<code>public static void main(String[] args) throws Exception {
        MainController mc= new MainController();
        mc.setProblem();
        MainController mc2 = new MainContoller();
        mc1.setProblem();
        Thread1 thread1 = new Thread1("thread1",mc.problem,approach1);
        Thread2 thread2 = new Thread2("thread2",mc1.problem,approach2);
        thread1.start();
        thread2.start();
    }
</code>```

And it worked, but I don't know why. I will not accept my answer as correct answer for few days, may someone explain this situation?

Body:
I'm creating two different threads which will solve same problem with different ways and I will calculate their solving time. I've created a structure like that;

MainController.java

public static void main(String[] args) throws Exception {
        MainController mc= new MainController();
        mc.setProblem();
        Thread1 thread1 = new Thread1("thread1",problem,approach1);
        Thread2 thread2 = new Thread2("thread2",problem,approach2);
        thread1.start();
        thread2.start();
    }

Thread1.java

class Thread1 implements Runnable{

       public void run() {
          System.out.println("Running " +  threadName );
          try {
             solve(approach);
          } catch (Exception e) {
             System.out.println("Thread " +  threadName + " interrupted.");
          }
          //showTable();
          System.out.println("Thread " +  threadName + " exiting.");
       }

       public void start () {
          System.out.println("Starting " +  threadName );
          if (t == null) {
             t = new Thread (this, threadName);
             t.start ();
          }
       }

       public void solve(approach) throws Exception {

            // Throw an exception to stop the process if the puzzle is solved
            if (didIsolve())  {//true if yes
                    System.out.println("----" + threadName +"----");
                    showResult();
                    System.out.println("--------------------------");
                    throw new Exception("ex");
            }
        }
    }

Thread2.java is the same as above code block.

And output like

    Creating thread1
    Creating thread2
    Starting thread1
    Starting thread2
    Running thread2
    Running thread1
    Thread thread1 exiting.
    ----thread2----
   RESULT METHOD OUTPUT
    --------------------------
    Thread thread2 interrupted.
    Thread thread2 exiting.

As you see above, thread1 did not solve problem, at least did not show result.

Also I've checked this topics so far

multiple threads performing different tasks

Java threads to do different tasks?

Edit:

Well, I think I found the problem. I changed MainController class;

public static void main(String[] args) throws Exception {
        MainController mc= new MainController();
        mc.setProblem();
        MainController mc2 = new MainContoller();
        mc1.setProblem();
        Thread1 thread1 = new Thread1("thread1",mc.problem,approach1);
        Thread2 thread2 = new Thread2("thread2",mc1.problem,approach2);
        thread1.start();
        thread2.start();
    }

And it worked, but I don't know why. I will not accept my answer as correct answer for few days, may someone explain this situation?


问:
How to load dynamically UserControl that contains asp controls
I have UserControl that has asp control(<asp:Button runat="server" ID="btn" />) and I want to render it.

I tried 1:

```<code>            Page loader = new Page();

            Control ctrl = loader.LoadControl("WebUserControl1.ascx");
            loader.Controls.Add(ctrl);
            loader.ProcessRequest(context);

            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            loader.RenderControl(htw);
</code>```

It doesn't works because it says that each control that has runat="server" must be in Form.

I also tried 2:

Because loader.Form is null, I create HtmlForm and added the ctrl to it and then added HtmlForm to loader's Control, BUT it says that it has 2 HtmlForm. So, instead I "injected" HtmlForm to loader like this

```<code>            Page loader = new Page();

            HtmlForm form = new HtmlForm();
            var method = loader.GetType().GetMethod("SetForm", BindingFlags.NonPublic | BindingFlags.Instance);
            method.Invoke(loader, new object[] { form });

            Control ctrl = loader.LoadControl("WebUserControl1.ascx");
            loader.Form.Controls.Add(ctrl);
            loader.ProcessRequest(context);

            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            loader.RenderControl(htw);
</code>```

Now no error is occurred, BUT StringWriter is empty

Where is my mistake.
Please don't tell me to add Page to solution and override OnRender. I want to do it as I mentioned above.

Thank you

答:
Dont use Form.Controls.Add,

Add a PlaceHolder control to Form. And add control to PlaceHolder.

PlaceHolder.Controls.Add(ctrl);

Try this.

Body:
I have UserControl that has asp control(<asp:Button runat="server" ID="btn" />) and I want to render it.

I tried 1:

            Page loader = new Page();

            Control ctrl = loader.LoadControl("WebUserControl1.ascx");
            loader.Controls.Add(ctrl);
            loader.ProcessRequest(context);

            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            loader.RenderControl(htw);

It doesn't works because it says that each control that has runat="server" must be in Form.

I also tried 2:

Because loader.Form is null, I create HtmlForm and added the ctrl to it and then added HtmlForm to loader's Control, BUT it says that it has 2 HtmlForm. So, instead I "injected" HtmlForm to loader like this

            Page loader = new Page();

            HtmlForm form = new HtmlForm();
            var method = loader.GetType().GetMethod("SetForm", BindingFlags.NonPublic | BindingFlags.Instance);
            method.Invoke(loader, new object[] { form });

            Control ctrl = loader.LoadControl("WebUserControl1.ascx");
            loader.Form.Controls.Add(ctrl);
            loader.ProcessRequest(context);

            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            loader.RenderControl(htw);

Now no error is occurred, BUT StringWriter is empty

Where is my mistake.
Please don't tell me to add Page to solution and override OnRender. I want to do it as I mentioned above.

Thank you


问:
Moving an object from one unique_ptr to another C++
I've created 2 classes: Crane and Container. Crane has a private member unique_ptr<Container> container and a public method load() taking a unique_ptr<Container> as a parameter, like this:

```<code>void Crane::load(unique_ptr<Container> container)
{
    if(isUnloaded())
    {
        this->container = move(container);
    }
}
</code>```

My goal here is to give a crane a container to hold, so other Crane methods can put the currently held container down in a warehouse, check its id, weight, etc.

Now, in main() I create 2 objects: Crane crane; and unique_ptr<Container> con(new Container(1));.

In main(), when I want to call crane.load(con), I get this error:

error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Container; _Dp = std::default_delete<Container>]'

I thought that this is the way when you want to change ownership of an object?  Please help.

答:
std::unique_ptr cannot be copied (its copy constructor is deleted).  Allowing copies would break the uniqueness of its pointer ownership.

The container parameter of load() is taken by value, so when your code passes the con variable to load(), the compiler tries to copy-construct container, thus the error (which, if you read it carefully, is complaining about the deleted copy constructor).

You need to use crane.load(std::move(con)); instead, so the compiler can move-construct container so ownership of the pointer is moved from con to container.

The alternative is to change load() to take container by reference instead:

```<code>void Crane::load(unique_ptr<Container> &container)
{
    if(isUnloaded())
    {
        this->container = move(container);
    }
}
</code>```

That way, crane.load(con); will work, and take ownership only if isUnloaded() is false, otherwise ownership stays with the caller (for instance, if you wanted to then try loading the container to a different Crane).

Body:
I've created 2 classes: Crane and Container. Crane has a private member unique_ptr<Container> container and a public method load() taking a unique_ptr<Container> as a parameter, like this:

void Crane::load(unique_ptr<Container> container)
{
    if(isUnloaded())
    {
        this->container = move(container);
    }
}

My goal here is to give a crane a container to hold, so other Crane methods can put the currently held container down in a warehouse, check its id, weight, etc.

Now, in main() I create 2 objects: Crane crane; and unique_ptr<Container> con(new Container(1));.

In main(), when I want to call crane.load(con), I get this error:

error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Container; _Dp = std::default_delete<Container>]'

I thought that this is the way when you want to change ownership of an object?  Please help.

Body:
std::unique_ptr cannot be copied (its copy constructor is deleted).  Allowing copies would break the uniqueness of its pointer ownership.

The container parameter of load() is taken by value, so when your code passes the con variable to load(), the compiler tries to copy-construct container, thus the error (which, if you read it carefully, is complaining about the deleted copy constructor).

You need to use crane.load(std::move(con)); instead, so the compiler can move-construct container so ownership of the pointer is moved from con to container.

The alternative is to change load() to take container by reference instead:

void Crane::load(unique_ptr<Container> &container)
{
    if(isUnloaded())
    {
        this->container = move(container);
    }
}

That way, crane.load(con); will work, and take ownership only if isUnloaded() is false, otherwise ownership stays with the caller (for instance, if you wanted to then try loading the container to a different Crane).


问:
VBA - enable and disable validation
I would like to ask is there a way to enable and disable data validation on excel? I would like to disable validation on a certain input,'others'. And enable it if the input is not others.

I had a list data validation, when option cell== others, user is able to free text. Else disable free text.

My list validation is done by the excel build in data validation, not using VBA.

This is the code that I have tried:

```<code>Sub Remove_Data_Validation_Selection()

Selection.Validation.Delete

End Sub

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    If Cells(2, 6).Value = "Others" Then
            Selection.Validation.Delete
    Else
           //Enable the validation
    End If
End Sub
</code>```

Right now, when 'Others' is being selected, the validation will be DELETED. How do I enable it back? As Selection.Validation.Delete deletes the object, will I be able to enable it back?

答:
This is exactly what I'm looking for, when user chooses other, it will modify the validation setting. You can change the modify to delete if you would like to remove the validation.  </p>

```<code>Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
If Target.Address = "$F$2" Then
    If Target.Value = "Others" Then
        With Target.Validation
        .Delete
        .Add Type:=xlValidateInputOnly, AlertStyle:=xlValidAlertStop, Operator _
        :=xlBetween
        .IgnoreBlank = False
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = ""
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = True
    End With
    End
    End If
End If

If Target.Address = "$F$2" Then
  With Target.Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
    xlBetween, Formula1:="1,2,3,Others"
        .IgnoreBlank = False
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = ""
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = True
  End With
End If
End Sub
</code>```

Title: VBA - enable and disable validation

Body:
I would like to ask is there a way to enable and disable data validation on excel? I would like to disable validation on a certain input,'others'. And enable it if the input is not others.

I had a list data validation, when option cell== others, user is able to free text. Else disable free text.

My list validation is done by the excel build in data validation, not using VBA.

This is the code that I have tried:

Sub Remove_Data_Validation_Selection()

Selection.Validation.Delete

End Sub

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    If Cells(2, 6).Value = "Others" Then
            Selection.Validation.Delete
    Else
           //Enable the validation
    End If
End Sub

Right now, when 'Others' is being selected, the validation will be DELETED. How do I enable it back? As Selection.Validation.Delete deletes the object, will I be able to enable it back?

Body:
This is exactly what I'm looking for, when user chooses other, it will modify the validation setting. You can change the modify to delete if you would like to remove the validation.

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
If Target.Address = "$F$2" Then
    If Target.Value = "Others" Then
        With Target.Validation
        .Delete
        .Add Type:=xlValidateInputOnly, AlertStyle:=xlValidAlertStop, Operator _
        :=xlBetween
        .IgnoreBlank = False
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = ""
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = True
    End With
    End
    End If
End If

If Target.Address = "$F$2" Then
  With Target.Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
    xlBetween, Formula1:="1,2,3,Others"
        .IgnoreBlank = False
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = ""
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = True
  End With
End If
End Sub


问:
Gradle on Android Studio loading with error
I'm running android studio on Debian distribution(32 bits) and whenever I start android studio I'm facing a problem with gradle,it keeps loading forever and in the gradle window I get a long list of errors which says:

```<code>***Executing tasks: [:app:generateDebugSources, :app:mockableAndroidJar, :app:prepareDebugUnitTestDependencies, :app:generateDebugAndroidTestSources]

Configuration on demand is an incubating feature.
Incremental java compilation is an incubating feature.
:app:preBuild UP-TO-DATE
:app:preDebugBuild UP-TO-DATE
:app:checkDebugManifest
:app:preReleaseBuild UP-TO-DATE
:app:prepareComAndroidSupportAnimatedVectorDrawable2421Library UP-TO-DATE
:app:prepareComAndroidSupportAppcompatV72421Library UP-TO-DATE
:app:prepareComAndroidSupportSupportCompat2421Library UP-TO-DATE
:app:prepareComAndroidSupportSupportCoreUi2421Library UP-TO-DATE
:app:prepareComAndroidSupportSupportCoreUtils2421Library UP-TO-DATE
:app:prepareComAndroidSupportSupportFragment2421Library UP-TO-DATE
:app:prepareComAndroidSupportSupportMediaCompat2421Library UP-TO-DATE
:app:prepareComAndroidSupportSupportV42421Library UP-TO-DATE
:app:prepareComAndroidSupportSupportVectorDrawable2421Library UP-TO-DATE
:app:prepareDebugDependencies
:app:compileDebugAidl UP-TO-DATE
:app:compileDebugRenderscript UP-TO-DATE
:app:generateDebugBuildConfig UP-TO-DATE
:app:generateDebugResValues UP-TO-DATE
:app:generateDebugResources UP-TO-DATE
:app:mergeDebugResources
AAPT err(Facade for 22453413): /home/user1/android-sdk-linux/build-tools/24.0.2/aapt: 1: /home/user1/android-sdk-linux/build-tools/24.0.2/aapt: Syntax error: Unterminated quoted string
AAPT err(Facade for 7072356): /home/user1/android-sdk-linux/build-tools/24.0.2/aapt: 1: /home/user1/android-sdk-linux/build-tools/24.0.2/aapt: Syntax error: Unterminated quoted string
AAPT err(Facade for 31338389): /home/user1/android-sdk-linux/build-tools/24.0.2/aapt: 1: /home/user1/android-sdk-linux/build-tools/24.0.2/aapt: Syntax error: Unterminated quoted string

Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands

AAPT err(Facade for 17737675): /home/user1/android-sdk-linux/build-tools/24.0.2/aapt: 1: /home/user1/android-sdk-linux/build-tools/24.0.2/aapt: Syntax error: Unterminated quoted string

Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands

AAPT err(Facade for 11417836): /home/user1/android-sdk-linux/build-tools/24.0.2/aapt: 1: /home/user1/android-sdk-linux/build-tools/24.0.2/aapt: Syntax error: Unterminated quoted string
Thread(png-cruncher_5): Broken pipe
java.io.IOException: Broken pipe
    at java.io.FileOutputStream.writeBytes(Native Method)
    at java.io.FileOutputStream.write(FileOutputStream.java:326)
    at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
    at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140)
    at sun.nio.cs.StreamEncoder.implFlush(StreamEncoder.java:297)
    at sun.nio.cs.StreamEncoder.flush(StreamEncoder.java:141)
    at java.io.OutputStreamWriter.flush(OutputStreamWriter.java:229)
    at com.android.builder.png.AaptProcess.shutdown(AaptProcess.java:143)
    at com.android.builder.png.QueuedCruncher$1.destruction(QueuedCruncher.java:144)
    at com.android.builder.tasks.WorkQueue.run(WorkQueue.java:245)
    at java.lang.Thread.run(Thread.java:745)
***
</code>```

there are pages and pages of this error repeated.
what can I do to fix this problem?

答:
I am running Debian Stretch 64 bit attempting to run a React Native Android application. The fix for me is I had to run the following command,

sudo apt-get install zlib1g:i386

If anyone else stumbles across this thread with the same situation as me I thought it would save them some pain.

Body:
I'm running android studio on Debian distribution(32 bits) and whenever I start android studio I'm facing a problem with gradle,it keeps loading forever and in the gradle window I get a long list of errors which says:

***Executing tasks: [:app:generateDebugSources, :app:mockableAndroidJar, :app:prepareDebugUnitTestDependencies, :app:generateDebugAndroidTestSources]

Configuration on demand is an incubating feature.
Incremental java compilation is an incubating feature.
:app:preBuild UP-TO-DATE
:app:preDebugBuild UP-TO-DATE
:app:checkDebugManifest
:app:preReleaseBuild UP-TO-DATE
:app:prepareComAndroidSupportAnimatedVectorDrawable2421Library UP-TO-DATE
:app:prepareComAndroidSupportAppcompatV72421Library UP-TO-DATE
:app:prepareComAndroidSupportSupportCompat2421Library UP-TO-DATE
:app:prepareComAndroidSupportSupportCoreUi2421Library UP-TO-DATE
:app:prepareComAndroidSupportSupportCoreUtils2421Library UP-TO-DATE
:app:prepareComAndroidSupportSupportFragment2421Library UP-TO-DATE
:app:prepareComAndroidSupportSupportMediaCompat2421Library UP-TO-DATE
:app:prepareComAndroidSupportSupportV42421Library UP-TO-DATE
:app:prepareComAndroidSupportSupportVectorDrawable2421Library UP-TO-DATE
:app:prepareDebugDependencies
:app:compileDebugAidl UP-TO-DATE
:app:compileDebugRenderscript UP-TO-DATE
:app:generateDebugBuildConfig UP-TO-DATE
:app:generateDebugResValues UP-TO-DATE
:app:generateDebugResources UP-TO-DATE
:app:mergeDebugResources
AAPT err(Facade for 22453413): /home/user1/android-sdk-linux/build-tools/24.0.2/aapt: 1: /home/user1/android-sdk-linux/build-tools/24.0.2/aapt: Syntax error: Unterminated quoted string
AAPT err(Facade for 7072356): /home/user1/android-sdk-linux/build-tools/24.0.2/aapt: 1: /home/user1/android-sdk-linux/build-tools/24.0.2/aapt: Syntax error: Unterminated quoted string
AAPT err(Facade for 31338389): /home/user1/android-sdk-linux/build-tools/24.0.2/aapt: 1: /home/user1/android-sdk-linux/build-tools/24.0.2/aapt: Syntax error: Unterminated quoted string

Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands
Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands

AAPT err(Facade for 17737675): /home/user1/android-sdk-linux/build-tools/24.0.2/aapt: 1: /home/user1/android-sdk-linux/build-tools/24.0.2/aapt: Syntax error: Unterminated quoted string

Exception while processing task java.lang.RuntimeException: AAPT process not ready to receive commands

AAPT err(Facade for 11417836): /home/user1/android-sdk-linux/build-tools/24.0.2/aapt: 1: /home/user1/android-sdk-linux/build-tools/24.0.2/aapt: Syntax error: Unterminated quoted string
Thread(png-cruncher_5): Broken pipe
java.io.IOException: Broken pipe
    at java.io.FileOutputStream.writeBytes(Native Method)
    at java.io.FileOutputStream.write(FileOutputStream.java:326)
    at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
    at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140)
    at sun.nio.cs.StreamEncoder.implFlush(StreamEncoder.java:297)
    at sun.nio.cs.StreamEncoder.flush(StreamEncoder.java:141)
    at java.io.OutputStreamWriter.flush(OutputStreamWriter.java:229)
    at com.android.builder.png.AaptProcess.shutdown(AaptProcess.java:143)
    at com.android.builder.png.QueuedCruncher$1.destruction(QueuedCruncher.java:144)
    at com.android.builder.tasks.WorkQueue.run(WorkQueue.java:245)
    at java.lang.Thread.run(Thread.java:745)
***

there are pages and pages of this error repeated.
what can I do to fix this problem?


问:
Not able to insert data into oracle Table
I have created one table called as Booking.

Structure of Booking is

I am inserting the data using below syntax :-

```<code>INSERT INTO Booking (
(id,price,date1,c_id)
values(1,1235.01,'2016-10-11', 1));
</code>```

but I am getting ORA-00928: missing SELECT keyword error.
I am using Oracle apex application.

what is the problem with this query?

答:
```<code>INSERT INTO Booking (id,price,date1,c_id)
values(1,1235.01,to_date('2016-10-11','yyyy-mm-dd'), 1)
;
</code>```

there was an extra set of parentheses that had to be removed

the string holding a date needs to be converted into a date, this can be done using the very flexible to_date() function, or if the string is strictly in YYYY-MM-DD format you can use DATE.

when creating a decimal field the first number is the TOTAL number of digits, an the second number is the number of digits after the decimal point. So 4,2 allow -99.99 to 99.99 as the maximum. To store 1235.01 you need at least 6 digits so 6,2 as a minimum.

Body:
I have created one table called as Booking.

Structure of Booking is

I am inserting the data using below syntax :-

INSERT INTO Booking (
(id,price,date1,c_id)
values(1,1235.01,'2016-10-11', 1));

but I am getting ORA-00928: missing SELECT keyword error.
I am using Oracle apex application.

what is the problem with this query?

Body:
INSERT INTO Booking (id,price,date1,c_id)
values(1,1235.01,to_date('2016-10-11','yyyy-mm-dd'), 1)
;

there was an extra set of parentheses that had to be removed

the string holding a date needs to be converted into a date, this can be done using the very flexible to_date() function, or if the string is strictly in YYYY-MM-DD format you can use DATE.

when creating a decimal field the first number is the TOTAL number of digits, an the second number is the number of digits after the decimal point. So 4,2 allow -99.99 to 99.99 as the maximum. To store 1235.01 you need at least 6 digits so 6,2 as a minimum.


问:
Does MySql support extproc?
I just want to know if MySql supports low-level database functions such as xp_cmdshell and extproc. I know xp_cmdshell is not supported for MySql due to security policies but what about extproc?</p>

答:
Probably the closest thing to extproc for MySQL is ProxySQL. But it's not really a very close match, architecturally.

If you develop plugins or user-defined functions (UDFs)† for MySQL, they run as shared libraries (DLLs) in the mysqld process.

https://dev.mysql.com/doc/refman/5.7/en/adding-udf.html and https://dev.mysql.com/doc/refman/5.7/en/writing-plugins.html say:

A [UDF/server plugin] contains code that becomes part of the running server, so when you write a UDF, you are bound by any and all constraints that apply to writing server code.

In other words, effectively no security, and these compiled objects  have total access to everything in that process. You are responsible for not installing plugins or UDFs that would compromise security.

† Note that UDFs are not the same as MySQL Stored Functions. UDFs are written in C/C++. Stored functions are written in MySQL's implementation of ANSI SQL procedure language.

Title: Does MySql support extproc?


问:
Python-requests - Download progress bar
I make a POST request to a server to generate a CSV file and response of the POST request is CSV data that I want to write to a file.

I can never know the size of the CSV file (it can be 10MB, 100MB or 1000MB) and as such there is no content-length header.

I have written a function that downloads makes a POST request to the server, generates a CSV file and writes the response to a CSV file. However, I am struggling with progress bar.

How do I add a progress bar?

```<code>r = requests.post(URL, data, stream=True)
#Download progress here
</code>```

答:
```<code>def download_file(url, local_path="./"):
    local_filename = url.split('/')[-1]
    path = local_path + local_filename

    r = requests.get(url, stream=True)
    total_size = int(r.headers.get('content-length', 0))

    with open(local_filename, 'wb') as f:
        for chunk in tqdm(r.iter_content(32*1024), total=total_size,unit='B', unit_scale=True):
            if chunk:
                f.write(chunk)

    return path
</code>```

Title: Python-requests - Download progress bar

Body:
I make a POST request to a server to generate a CSV file and response of the POST request is CSV data that I want to write to a file.

I can never know the size of the CSV file (it can be 10MB, 100MB or 1000MB) and as such there is no content-length header.

I have written a function that downloads makes a POST request to the server, generates a CSV file and writes the response to a CSV file. However, I am struggling with progress bar.

How do I add a progress bar?

r = requests.post(URL, data, stream=True)
#Download progress here


问:
Pass vector elements to a function in c++
I now have a vector of objects. And a pre-defined function that can take objects as parameters. Just curious if there's a way of passing these objects to this function?

```<code>std::vector<obj> objects; //contains obj1, obj2 .., objn
</code>```

And I'd like to achieve something like this:

```<code> foo(obj1, obj2 ... , objn) //foo can take as many objects as I want
</code>```

答:
Yes，in C++ 11 you can use a variadic template, like this:

```<code>template<typename ...Ts>
void f(Ts...args);
</code>```

The following code is a working example:

```<code>#include <vector>

class obj {
public:
    obj(int _id) {id = _id; }
    int id;
};

std::vector<obj> objects;

template<typename ...Ts>
void f(Ts...args)
{
    const int size = sizeof...(args);
    obj objs[size] = { args... };

    for(int i=0;i<size;i++)
        objects.push_back(objs[i]);
}

int main()
{
    obj obj1(1), obj2(2), obj3(3);
    f(obj1, obj2, obj3);
    return 0;
}
</code>```

Body:
I now have a vector of objects. And a pre-defined function that can take objects as parameters. Just curious if there's a way of passing these objects to this function?

std::vector<obj> objects; //contains obj1, obj2 .., objn

And I'd like to achieve something like this:

 foo(obj1, obj2 ... , objn) //foo can take as many objects as I want

Body:
Yes，in C++ 11 you can use a variadic template, like this:

template<typename ...Ts>
void f(Ts...args);

The following code is a working example:

#include <vector>

class obj {
public:
    obj(int _id) {id = _id; }
    int id;
};

std::vector<obj> objects;

template<typename ...Ts>
void f(Ts...args)
{
    const int size = sizeof...(args);
    obj objs[size] = { args... };

    for(int i=0;i<size;i++)
        objects.push_back(objs[i]);
}

int main()
{
    obj obj1(1), obj2(2), obj3(3);
    f(obj1, obj2, obj3);
    return 0;
}


答:
You can use array_filter to find just those keys matching your condition:

```<code>$matches = array_filter(
    $array,
    function ($key) { return false !== strpos($key, 'dex'); },
    ARRAY_FILTER_USE_KEY
);
</code>```

See it live on 3v4l.org.

Tweak the logic inside the closure to match the specific need. In this example, if the key does not contain 'dex', consider the key a match. Per the comment, to search for a key that contains a sub-string, or a key that itself is a sub-string, you can use:

```<code>function array_search_by_partial_key(array $array, $partial) {
    return array_filter(
        $array,
        function ($key) use ($partial) {
            return false !== strpos($key, $partial) || false !== strpos($partial, $key);
        },
        ARRAY_FILTER_USE_KEY
    );
}
</code>```

This is just an elaboration the direct answer, made a bit more easy to use by wrapping in a function. See it live on 3v4l.org.

Title: how to get value if index contains certain value php

Body:
You can use array_filter to find just those keys matching your condition:

$matches = array_filter(
    $array,
    function ($key) { return false !== strpos($key, 'dex'); },
    ARRAY_FILTER_USE_KEY
);

See it live on 3v4l.org.

Tweak the logic inside the closure to match the specific need. In this example, if the key does not contain 'dex', consider the key a match. Per the comment, to search for a key that contains a sub-string, or a key that itself is a sub-string, you can use:

function array_search_by_partial_key(array $array, $partial) {
    return array_filter(
        $array,
        function ($key) use ($partial) {
            return false !== strpos($key, $partial) || false !== strpos($partial, $key);
        },
        ARRAY_FILTER_USE_KEY
    );
}

This is just an elaboration the direct answer, made a bit more easy to use by wrapping in a function. See it live on 3v4l.org.


问:
Access API returns JSON array
I am using Javascript to decode a vehicles VIN number via an API. The returned message looks like this:

```<code>{Count: 116, Message: "Results returned successfully", SearchCriteria: "VIN(s): 60540kjhkjhkj5885", Results: Array(1)}
</code>```

I need to know how to access the returned array in results.

This is my current Javascript:

```<code>   // Decode VIN Number
function post_VIN_decode() {
    var vinNumber = $('#id_vin_number').val();
    console.log("VIN Decode Sent") // sanity check
    $.ajax({
        url : "https://vpic.nhtsa.dot.gov/api/vehicles/decodevinvalues/" + vinNumber + "?format=json", // the endpoint
        type : "GET", // http method

        // handle a successful response
        success : function(json) {
            console.log(json); // log the returned json to the console
        },

        // handle a non-successful response
        error : function(xhr,errmsg,err) {
            $('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
                " <a href='#' class='close'>×</a></div>"); // add the error to the dom
            console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
        }
    });
};

$('#id_vin_number').keyup(function(e){
    if($("#id_vin_number").val().length >= 17){
        event.preventDefault();
        console.log("VIN Decode started")  // sanity check
        post_VIN_decode();
    }
});
</code>```

Any help is appreciated.

答:
Inside your success try:</p>

```<code>success : function(json) {
    console.log(json); // log the returned json to the console

    $.each(json.Results, function( index, value ) {
        console.log( index + ": " + value );
    });

    console.log("Or just the first index: " + json.Results[0]);
},
</code>```

Title: Access API returns JSON array

Body:
I am using Javascript to decode a vehicles VIN number via an API. The returned message looks like this:

{Count: 116, Message: "Results returned successfully", SearchCriteria: "VIN(s): 60540kjhkjhkj5885", Results: Array(1)}

I need to know how to access the returned array in results.

This is my current Javascript:

   // Decode VIN Number
function post_VIN_decode() {
    var vinNumber = $('#id_vin_number').val();
    console.log("VIN Decode Sent") // sanity check
    $.ajax({
        url : "https://vpic.nhtsa.dot.gov/api/vehicles/decodevinvalues/" + vinNumber + "?format=json", // the endpoint
        type : "GET", // http method

        // handle a successful response
        success : function(json) {
            console.log(json); // log the returned json to the console
        },

        // handle a non-successful response
        error : function(xhr,errmsg,err) {
            $('#results').html("
Oops! We have encountered an error: "+errmsg+
                " ×
"); // add the error to the dom
            console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
        }
    });
};

$('#id_vin_number').keyup(function(e){
    if($("#id_vin_number").val().length >= 17){
        event.preventDefault();
        console.log("VIN Decode started")  // sanity check
        post_VIN_decode();
    }
});

Any help is appreciated.

Body:
Inside your success try:

success : function(json) {
    console.log(json); // log the returned json to the console

    $.each(json.Results, function( index, value ) {
        console.log( index + ": " + value );
    });

    console.log("Or just the first index: " + json.Results[0]);
},


答:
The first problem is the extra set of parens.  Second, one of the values is presumably a date (as opposed to a string).  I would suggest:

```<code>INSERT INTO Booking (id, price, date1, c_id)
    VALUES (1, 1235.01, DATE '2016-10-11', 1);
</code>```

The DATE keyword interprets the following string as a date.

This will still fail, because price has six digits, instead of four.  Either lower the price or increase the size of the price column.

Title: Not able to insert data into oracle Table

Body:
The first problem is the extra set of parens.  Second, one of the values is presumably a date (as opposed to a string).  I would suggest:

INSERT INTO Booking (id, price, date1, c_id)
    VALUES (1, 1235.01, DATE '2016-10-11', 1);

The DATE keyword interprets the following string as a date.

This will still fail, because price has six digits, instead of four.  Either lower the price or increase the size of the price column.