问:
how can i calculate the time sending data to azure service bus topic
I'm trying to calculate the time between the data sending from my device to azure service bus topic. I have azure function to listen topic. Also, the data I sent to the topic has a DateTime. In azure function, I create new DateTime and minus the DateTime from topic data. it should be give me the time between sending to receiving. However, I got lots of negative data. </p>

```<code>    try
    {
        await client.PostAsJsonAsync("api/device", device);
        releaseLoop= true;

    }
    catch (Exception e)
    {
        log.Info("Exception Message: "+e);
    }

    finally
    {
        log.Info($"{data.DeviceName} Total runing time "+(DateTime.UtcNow-data.timerInfo).Milliseconds+"ms");
    }

logInfo from azure function.
2017-11-13T04:44:36.976 3060 ipad Total runing time 412ms
2017-11-13T04:44:36.976 Function completed (Success, Id=57c528fe-589d-4edc-b285-4dfe481f2aee, Duration=119ms)
2017-11-13T04:44:37.427 Function started (Id=33469551-3873-468d-8ecf-df0b72d8e951)
2017-11-13T04:44:36.352 3049 iphone Total runing time 910ms
2017-11-13T04:44:36.352 Function completed (Success, Id=d233a8e7-1852-4d72-a8f6-5ebc9c4b3d36, Duration=130ms)
2017-11-13T04:44:36.368 Function started (Id=ed19f6e8-7db2-440c-872f-205078a6c0f5)
2017-11-13T04:44:36.477 3061 ipad Total runing time -188ms
2017-11-13T04:44:36.477 Function completed (Success, Id=ed19f6e8-7db2-440c-872f-205078a6c0f5, Duration=109ms)
2017-11-13T04:44:36.687 Function started (Id=feee0174-7461-4ab4-939d-48ca8377ae10)
2017-11-13T04:44:36.793 3064 ipad Total runing time -179ms
2017-11-13T04:44:36.793 Function completed (Success, Id=feee0174-7461-4ab4-939d-48ca8377ae10, Duration=117ms)
2017-11-13T04:44:37.191 Function started (Id=487d5657-5433-48f0-b4bb-e24e80375d5a)
2017-11-13T04:44:37.301 3069 surface pro Total runing time -181ms
2017-11-13T04:44:37.301 Function completed (Success, Id=487d5657-5433-48f0-b4bb-e24e80375d5a, Duration=108ms)
2017-11-13T04:44:36.726 3063 iphone Total runing time -143ms
</code>```

答: One approach is to setup a test with both the sender and the listener on the same machine - that avoids clock skew issues.  </p>

Body:
I'm trying to calculate the time between the data sending from my device to azure service bus topic. I have azure function to listen topic. Also, the data I sent to the topic has a DateTime. In azure function, I create new DateTime and minus the DateTime from topic data. it should be give me the time between sending to receiving. However, I got lots of negative data.

    try
    {
        await client.PostAsJsonAsync("api/device", device);
        releaseLoop= true;

    }
    catch (Exception e)
    {
        log.Info("Exception Message: "+e);
    }

    finally
    {
        log.Info($"{data.DeviceName} Total runing time "+(DateTime.UtcNow-data.timerInfo).Milliseconds+"ms");
    }

logInfo from azure function.
2017-11-13T04:44:36.976 3060 ipad Total runing time 412ms
2017-11-13T04:44:36.976 Function completed (Success, Id=57c528fe-589d-4edc-b285-4dfe481f2aee, Duration=119ms)
2017-11-13T04:44:37.427 Function started (Id=33469551-3873-468d-8ecf-df0b72d8e951)
2017-11-13T04:44:36.352 3049 iphone Total runing time 910ms
2017-11-13T04:44:36.352 Function completed (Success, Id=d233a8e7-1852-4d72-a8f6-5ebc9c4b3d36, Duration=130ms)
2017-11-13T04:44:36.368 Function started (Id=ed19f6e8-7db2-440c-872f-205078a6c0f5)
2017-11-13T04:44:36.477 3061 ipad Total runing time -188ms
2017-11-13T04:44:36.477 Function completed (Success, Id=ed19f6e8-7db2-440c-872f-205078a6c0f5, Duration=109ms)
2017-11-13T04:44:36.687 Function started (Id=feee0174-7461-4ab4-939d-48ca8377ae10)
2017-11-13T04:44:36.793 3064 ipad Total runing time -179ms
2017-11-13T04:44:36.793 Function completed (Success, Id=feee0174-7461-4ab4-939d-48ca8377ae10, Duration=117ms)
2017-11-13T04:44:37.191 Function started (Id=487d5657-5433-48f0-b4bb-e24e80375d5a)
2017-11-13T04:44:37.301 3069 surface pro Total runing time -181ms
2017-11-13T04:44:37.301 Function completed (Success, Id=487d5657-5433-48f0-b4bb-e24e80375d5a, Duration=108ms)
2017-11-13T04:44:36.726 3063 iphone Total runing time -143ms


来源: stackexchange

问:
Angular: How to update html with http get request after using http put request?
My html renders a list of cities using a http get request. I want my html to render again when I use a put request to update the list. How would I do this?

Html:

```<code><div *ngFor="let city of cityList">
  <h4>{{city}}</h4>
</div>
</code>```

TypeScript:

```<code>cityList: string[];

ngOnInit() {
    this.getCities();
  }

getCities() {
  this.cityListService.getCitiesSaved().subscribe(
    cities => {
      this.cityList = cities;
    }
  );
}
</code>```

Service:

```<code>currentCityList: string[];

getCitiesSaved(): Observable<string[]> {
  return this.http.get(this.url).map((data: Response) => {
    this.currentCityList = data.json().cityAlerts;
    return data.json().cityAlerts;
  });
}
</code>```

答: In Angular the view is updating dynamically, so all that you need is just to push new elements to cityList array and Angular will do the trick.

ContentLicense: CC BY-SA 3.0

Body:
My html renders a list of cities using a http get request. I want my html to render again when I use a put request to update the list. How would I do this?

Html:

{{city}}

TypeScript:

cityList: string[];

ngOnInit() {
    this.getCities();
  }

getCities() {
  this.cityListService.getCitiesSaved().subscribe(
    cities => {
      this.cityList = cities;
    }
  );
}

Service:

currentCityList: string[];

getCitiesSaved(): Observable<string[]> {
  return this.http.get(this.url).map((data: Response) => {
    this.currentCityList = data.json().cityAlerts;
    return data.json().cityAlerts;
  });
}


问:
Status bar color isn't changing on iPhone X to the left and right of notch
Hello I updated to new Xcode 9 and started using safeAreaLayout guide to support iphone X. From xib, I just used safeAreaLayout guide and adjusted by top and bottom constraints to safeArea.

Here is what I got

iphone X (iOS 11)

iphone 6 (iOS 11)

As you can see my custom navigation bar is down 20pxls

iphone 6 (iOS 9 and 10)

Here you can see how the navigation bar starts from 0 and status bar is merged.

Actually,

1) I want the green color to filled by notch.
2) Status Bar should not show in white color but green color as in 3 image.

I have searched many solutions. But none is working. So I need help.

Regards
Ranjit

答:
1- You should select superview for your view's top constraint (if not)

2- Double click on this constraint. If you see Margin

3- Uncheck relative to margin

4- Set constraint value to 0 again


问:
blackberry webservice
how i call a webservice in blackberry java ? </p>

答:
You can try these links:

u can try this link to get knowledge and information:

http://developerlife.com/tutorials/?p=884

http://supportforums.blackberry.com/t5/Java-Development/Connecting-your-BlackBerry-http-and-socket-connections-to-the/td-p/206242

http://www.blackberry.com/developers/docs/4.0.2api/javax/microedition/io/HttpConnection.html

A variety of such links are also available via google and also in stack overflow.
try and search  :)

Title: blackberry webservice

ContentLicense: CC BY-SA 2.5


问:
How do I add csv file data into a dictionary
me very new in programming, how do I make a dictionary that calls the Tour ID and displays the given info.(Tour, Start, End)

Tour = Tour Name

Start = Available reservations at the start

End = Amount of reservations left

csv file columns:

```<code>ID     |   Tour   | Start | End

12345  |  Italy   |  100  | 80

13579  |  China   |  50   | 30

24680  |  France  |  50   | 30
</code>```

For example if I called the ID: "12345" it would display - Italy, 100, 80

答:
You can try this:</p>

```<code>import csv
data = list(csv.reader(open('filename.csv')))
final_data = {int(i[0]):[int(b) if b.isdigit() else b for b in i[1:]] for i in data}
</code>```

Body:
me very new in programming, how do I make a dictionary that calls the Tour ID and displays the given info.(Tour, Start, End)

Tour = Tour Name

Start = Available reservations at the start

End = Amount of reservations left

csv file columns:

ID     |   Tour   | Start | End

12345  |  Italy   |  100  | 80

13579  |  China   |  50   | 30

24680  |  France  |  50   | 30

For example if I called the ID: "12345" it would display - Italy, 100, 80

Body:
You can try this:

import csv
data = list(csv.reader(open('filename.csv')))
final_data = {int(i[0]):[int(b) if b.isdigit() else b for b in i[1:]] for i in data}


问:
How can I obtain percentage frequencies in pyspark
I am trying to get percentage frequencies in pyspark. I did this in python as follows

```<code>Companies = df['Company'].value_counts(normalize = True)
</code>```

Getting the frequencies is fairly straightforward:

```<code># Dates in descending order of complaint frequency
df.createOrReplaceTempView('Comp')
CompDF = spark.sql("SELECT Company, count(*) as cnt \
                    FROM Comp \
                    GROUP BY Company \
                    ORDER BY cnt DESC")
CompDF.show()
</code>```

```<code>+--------------------+----+
|             Company| cnt|
+--------------------+----+
|BANK OF AMERICA, ...|1387|
|       EQUIFAX, INC.|1285|
|WELLS FARGO & COM...|1119|
|Experian Informat...|1115|
|TRANSUNION INTERM...|1001|
|JPMORGAN CHASE & CO.| 905|
|      CITIBANK, N.A.| 772|
|OCWEN LOAN SERVIC...| 481|
</code>```

How do I get to percent frequencies from here? I tried a bunch of things with not much luck.
Any help would be appreciated.

答:
As Suresh implies in the comments, assuming that total_count is the number of rows in dataframe Companies, you can use withColumn to add a new column named percentages in CompDF:

```<code>total_count = Companies.count()

df = CompDF.withColumn('percentage', CompDF.cnt/float(total_counts))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to get percentage frequencies in pyspark. I did this in python as follows

Companies = df['Company'].value_counts(normalize = True)

Getting the frequencies is fairly straightforward:

# Dates in descending order of complaint frequency
df.createOrReplaceTempView('Comp')
CompDF = spark.sql("SELECT Company, count(*) as cnt \
                    FROM Comp \
                    GROUP BY Company \
                    ORDER BY cnt DESC")
CompDF.show()

+--------------------+----+
|             Company| cnt|
+--------------------+----+
|BANK OF AMERICA, ...|1387|
|       EQUIFAX, INC.|1285|
|WELLS FARGO & COM...|1119|
|Experian Informat...|1115|
|TRANSUNION INTERM...|1001|
|JPMORGAN CHASE & CO.| 905|
|      CITIBANK, N.A.| 772|
|OCWEN LOAN SERVIC...| 481|

How do I get to percent frequencies from here? I tried a bunch of things with not much luck.
Any help would be appreciated.

Body:
As Suresh implies in the comments, assuming that total_count is the number of rows in dataframe Companies, you can use withColumn to add a new column named percentages in CompDF:

total_count = Companies.count()

df = CompDF.withColumn('percentage', CompDF.cnt/float(total_counts))


问:
Umbraco login from another site
I'm just getting started with Umbraco and the idea is to have a site (running under Umbraco) with documentation for another site. But the requirement is that you can't see anything on the documentaion site unless you are logged in at the main site.

So on my main site, when you login you get an .ASPXAUTH cookie. What do I need to do on the Umbraco side to be able to read that and check it's validity (really, knowing the data embedded in the cookie, for example the user's identity isn't actually important right now) and if not valid (or not present) it should redirect you to the main site to login (I don't want to recreate the same login process in Umbraco).

What's the right way to approach this? I've seen links about creating a MembershipProvdier in Umbraco, but I don't want to recreate the whole thing. I just need to know that you have the cookie and it is a legimate one created by the main site.

I can put both sites on the same domain, so all I really need the Umbraco side to do is read the cookie and confirm that it's valid and only show a certain page of content if that is true. I can create my own MembershipProvider that would let me implement ValidateUser, but I need to hook the process sooner. I need to hook into where Umbraco decides if a user is signed in or not.

Edit: I might be making some progress here, but I'm not quite there. I created a controller that inherits from RenderMvcController and added a custom AuthorizeAttribute:

```<code>public class CustomUmbracoDefaultController : Umbraco.Web.Mvc.RenderMvcController
{
    [TestAuthorize]
    public override ActionResult Index(RenderModel model)
    {
        return base.Index(model);
    }
}

public class TestAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        return base.AuthorizeCore(httpContext);
    }
}
</code>```

And I added a startup handler to set the default controller type:

```<code>public class StartupHandler : ApplicationEventHandler
{
    protected override void ApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
    {
        DefaultRenderMvcControllerResolver.Current.SetDefaultControllerType(typeof(Controller.CustomUmbracoDefaultController));
    }
}
</code>```

and then in the settings:

```<code><authentication mode="Forms">
  <forms loginUrl="http://localhost:6550/account/Login" protection="All" path="/" />
</authentication>
</code>```

Where localhost:6550 is my other application (the one that actually does the login).

When I start up my Umbraco application (http://localhost:7539) it redirects to the login page (great!) but after logging in and getting the .ASPXAUTH any attempt to go back to localhost:7539 is still going to redirect me back to the login page.

So what am I still missing? Where can I get it to see the .ASPXAUTH cookie and accept it?

Edit: Just for fun I tried this:

```<code>protected override bool AuthorizeCore(HttpContextBase httpContext)
{
    var cookie = httpContext.Request.Cookies[".ASPXAUTH"];
    if (cookie == null)
    {
        return base.AuthorizeCore(httpContext);
    }
    return true;
}
</code>```

When I first come in cookie is null as expected and you are kicked to the login page (on a different port). After login I can see the .ASPXAUTH cookie is set (still on port 6550). When I then put the port for Umbraco back in, I when it hits AuthorizeCore, the .ASPXAUTH cookie is still null? So it will loop back to the login page again. If I skip the null check and just return true, my Umbraco page loads and looking in my browser I can see the .ASPXAUTH cookie is there. So why couldn't I see it in AuthorizeCore?

答:
Ok, the missing ASPXAUTH cookie part I solved. I had to match the machineKey entries in my original project and my Umbraco project. I guess if it can't decode the cookie, it'll just be ignored.

So now is that fact that a cookie exist that is able to be decoded with my machine key enough to confirm that the user is logged in? For the Umbraco side I absolutely don't care who is logged in, just that they are logged in.

Title: Umbraco login from another site

Body:
I'm just getting started with Umbraco and the idea is to have a site (running under Umbraco) with documentation for another site. But the requirement is that you can't see anything on the documentaion site unless you are logged in at the main site.

So on my main site, when you login you get an .ASPXAUTH cookie. What do I need to do on the Umbraco side to be able to read that and check it's validity (really, knowing the data embedded in the cookie, for example the user's identity isn't actually important right now) and if not valid (or not present) it should redirect you to the main site to login (I don't want to recreate the same login process in Umbraco).

What's the right way to approach this? I've seen links about creating a MembershipProvdier in Umbraco, but I don't want to recreate the whole thing. I just need to know that you have the cookie and it is a legimate one created by the main site.

I can put both sites on the same domain, so all I really need the Umbraco side to do is read the cookie and confirm that it's valid and only show a certain page of content if that is true. I can create my own MembershipProvider that would let me implement ValidateUser, but I need to hook the process sooner. I need to hook into where Umbraco decides if a user is signed in or not.

Edit: I might be making some progress here, but I'm not quite there. I created a controller that inherits from RenderMvcController and added a custom AuthorizeAttribute:

public class CustomUmbracoDefaultController : Umbraco.Web.Mvc.RenderMvcController
{
    [TestAuthorize]
    public override ActionResult Index(RenderModel model)
    {
        return base.Index(model);
    }
}

public class TestAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        return base.AuthorizeCore(httpContext);
    }
}

And I added a startup handler to set the default controller type:

public class StartupHandler : ApplicationEventHandler
{
    protected override void ApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
    {
        DefaultRenderMvcControllerResolver.Current.SetDefaultControllerType(typeof(Controller.CustomUmbracoDefaultController));
    }
}

and then in the settings:

<authentication mode="Forms">
  <forms loginUrl="http://localhost:6550/account/Login" protection="All" path="/" />
</authentication>

Where localhost:6550 is my other application (the one that actually does the login).

When I start up my Umbraco application (http://localhost:7539) it redirects to the login page (great!) but after logging in and getting the .ASPXAUTH any attempt to go back to localhost:7539 is still going to redirect me back to the login page.

So what am I still missing? Where can I get it to see the .ASPXAUTH cookie and accept it?

Edit: Just for fun I tried this:

protected override bool AuthorizeCore(HttpContextBase httpContext)
{
    var cookie = httpContext.Request.Cookies[".ASPXAUTH"];
    if (cookie == null)
    {
        return base.AuthorizeCore(httpContext);
    }
    return true;
}

When I first come in cookie is null as expected and you are kicked to the login page (on a different port). After login I can see the .ASPXAUTH cookie is set (still on port 6550). When I then put the port for Umbraco back in, I when it hits AuthorizeCore, the .ASPXAUTH cookie is still null? So it will loop back to the login page again. If I skip the null check and just return true, my Umbraco page loads and looking in my browser I can see the .ASPXAUTH cookie is there. So why couldn't I see it in AuthorizeCore?


问:
QML/Qt3D Basic example of GeometryRenderer use
I'm looking for a basic example of how to set up an Entity with a GeometryRenderer in QML.

The code I'm using right now is shown below. If I replace geometryRenderer by a CuboidMesh then a blank cube is shown. The goal is to display a simple triangle. Is my GeometryRenderer declaration correct ?

```<code>Entity{

    Material{
      id: simpleMaterial
      effect: SimpleEffect{}
    }

    GeometryRenderer{
      id: geometryRenderer

    instanceCount: 1
    primitiveType: GeometryRenderer.Triangles
    geometry: Geometry{

            Attribute{
                attributeType: Attribute.VertexAttribute
                vertexBaseType: Attribute.Float
                vertexSize: 3
                byteOffset: 0
                byteStride: 3 * 4
                count: 3

                buffer : Buffer{
                    id: vertexBuffer
                    type: Buffer.VertexBuffer
                    data: [ 0.0, 0.0, 0.0,
                            0.0, 10.0, 0.0,
                            10.0, 10.0, 0.0]
                }
            }
        }
    }

components: [simpleMaterial, geometryRenderer]
}
</code>```

答:
The problem was the following: the data property of the Buffer object actually expects a QByteArray. However, QByteArray is not a QML type and simply writing the vertices in a list won't do the trick.

The solution is to write a C++ wrapper which is then made available to QML. This wrapper should offer at least a readable property to a QBuffer or directly a QByteArray.

It is then possible to set the wrapper's data using either C++ or QML (provided some write function, see here).

The following code is a basic example, I adapted it from this answer where it is more complete in terms of functionality.

```<code>Entity{

    property DrawData drawData

    Material{
        id: material
        ...
    }

    GeometryRenderer{
        id: geometryRenderer

        instanceCount: drawData.count
        primitiveType: GeometryRenderer.TriangleStrip

        geometry: Geometry{

            Attribute{
                name: "vertexPosition" // Name of attribute in the shader
                attributeType: Attribute.VertexAttribute
                vertexBaseType: Attribute.Float
                vertexSize: 3
                byteOffset: 0 // See OpenGL doc for details about these properties
                byteStride: 3 * 4
                count: drawData.count
                buffer : drawData.buffer // The actual QBuffer which holds the vertex data
            }
        }
    }

    components: [material, geometryRenderer]
}
</code>```

Where DrawData is defined as follows:

```<code>/*
 * This struct is not strictly necessary, it is just convenient in case more
 * vertex attributes are needed. If so, it is necessary to change the ByteStride
 * in the geometry attribute.
 */
struct DrawVBOData {
QVector3D position;
};

class DrawData : public Qt3DCore::QNode {
    Q_OBJECT
    // Make properties available in QML
    Q_PROPERTY(Qt3DRender::QBuffer *buffer READ buffer CONSTANT)
    Q_PROPERTY(int count READ count NOTIFY countChanged)

public:
    explicit DrawData (Qt3DCore::QNode *parent = 0);
    Qt3DRender::QBuffer *buffer();
    void setData(const QVector<QVector3D> &positions);
    int count() const;

signals:
    void countChanged(int count);

public slots:

private:
    QScopedPointer<Qt3DRender::QBuffer> m_buffer;
    int m_count = 0;
};
</code>```

And finally, the implementation:

```<code>DrawData::DrawData(Qt3DCore::QNode *parent)
    : Qt3DCore::QNode(parent), m_buffer(new QBuffer(QBuffer::VertexBuffer, this)){}

Qt3DRender::QBuffer *DrawData::buffer() { return m_buffer.data();}

void DrawData::setData(const QVector<QVector3D> &positions) {
    QByteArray ba;
    ba.resize(positions.size() * sizeof(DrawVBOData));
    DrawVBOData *vboData = reinterpret_cast<DrawVBOData *>(ba.data());
    for (int i = 0; i < positions.size(); i++) {
        DrawVBOData &vbo = vboData[i];
        vbo.position = positions[i];
    }
    m_buffer->setData(ba);
    m_count = positions.count();
    emit countChanged(m_count);
}

int DrawData::count() const { return m_count; }
</code>```

Body:
I'm looking for a basic example of how to set up an Entity with a GeometryRenderer in QML.

The code I'm using right now is shown below. If I replace geometryRenderer by a CuboidMesh then a blank cube is shown. The goal is to display a simple triangle. Is my GeometryRenderer declaration correct ?

Entity{

    Material{
      id: simpleMaterial
      effect: SimpleEffect{}
    }

    GeometryRenderer{
      id: geometryRenderer

    instanceCount: 1
    primitiveType: GeometryRenderer.Triangles
    geometry: Geometry{

            Attribute{
                attributeType: Attribute.VertexAttribute
                vertexBaseType: Attribute.Float
                vertexSize: 3
                byteOffset: 0
                byteStride: 3 * 4
                count: 3

                buffer : Buffer{
                    id: vertexBuffer
                    type: Buffer.VertexBuffer
                    data: [ 0.0, 0.0, 0.0,
                            0.0, 10.0, 0.0,
                            10.0, 10.0, 0.0]
                }
            }
        }
    }

components: [simpleMaterial, geometryRenderer]
}

Body:
The problem was the following: the data property of the Buffer object actually expects a QByteArray. However, QByteArray is not a QML type and simply writing the vertices in a list won't do the trick.

The solution is to write a C++ wrapper which is then made available to QML. This wrapper should offer at least a readable property to a QBuffer or directly a QByteArray.

It is then possible to set the wrapper's data using either C++ or QML (provided some write function, see here).

The following code is a basic example, I adapted it from this answer where it is more complete in terms of functionality.

Entity{

    property DrawData drawData

    Material{
        id: material
        ...
    }

    GeometryRenderer{
        id: geometryRenderer

        instanceCount: drawData.count
        primitiveType: GeometryRenderer.TriangleStrip

        geometry: Geometry{

            Attribute{
                name: "vertexPosition" // Name of attribute in the shader
                attributeType: Attribute.VertexAttribute
                vertexBaseType: Attribute.Float
                vertexSize: 3
                byteOffset: 0 // See OpenGL doc for details about these properties
                byteStride: 3 * 4
                count: drawData.count
                buffer : drawData.buffer // The actual QBuffer which holds the vertex data
            }
        }
    }

    components: [material, geometryRenderer]
}

Where DrawData is defined as follows:

/*
 * This struct is not strictly necessary, it is just convenient in case more
 * vertex attributes are needed. If so, it is necessary to change the ByteStride
 * in the geometry attribute.
 */
struct DrawVBOData {
QVector3D position;
};

class DrawData : public Qt3DCore::QNode {
    Q_OBJECT
    // Make properties available in QML
    Q_PROPERTY(Qt3DRender::QBuffer *buffer READ buffer CONSTANT)
    Q_PROPERTY(int count READ count NOTIFY countChanged)

public:
    explicit DrawData (Qt3DCore::QNode *parent = 0);
    Qt3DRender::QBuffer *buffer();
    void setData(const QVector<QVector3D> &positions);
    int count() const;

signals:
    void countChanged(int count);

public slots:

private:
    QScopedPointer<Qt3DRender::QBuffer> m_buffer;
    int m_count = 0;
};

And finally, the implementation:

DrawData::DrawData(Qt3DCore::QNode *parent)
    : Qt3DCore::QNode(parent), m_buffer(new QBuffer(QBuffer::VertexBuffer, this)){}

Qt3DRender::QBuffer *DrawData::buffer() { return m_buffer.data();}

void DrawData::setData(const QVector<QVector3D> &positions) {
    QByteArray ba;
    ba.resize(positions.size() * sizeof(DrawVBOData));
    DrawVBOData *vboData = reinterpret_cast<DrawVBOData *>(ba.data());
    for (int i = 0; i < positions.size(); i++) {
        DrawVBOData &vbo = vboData[i];
        vbo.position = positions[i];
    }
    m_buffer->setData(ba);
    m_count = positions.count();
    emit countChanged(m_count);
}

int DrawData::count() const { return m_count; }


问:
PostgreSQL connection WITH OpenS(QL)hift from a Local OS X Python Script
I'm trying to connect to OpenShift from a OS X Python Script.  OpenShift for sure works.  However, I'm looking for an "easy" way with python without downloading additional PGSQL libs to OS X.  Thanks!

Question: What is the correct domain name to use for this??  And can we keep it simple without doing an import to python?

I don't want to use any additional libraries.

the main problem I'm having is with pgsql.connect(dbname = 'orion', host = '127.7.74.2:5432', #'localhost', port = 5432, user = 'earthling', password = 'extraterrestrial')

Here is what the code file looks like "pgsql.py"...

```<code># PostgreSQL Client:
# http://www.postgresql.org/docs/current/static/reference-client.html

# PostgreSQL Server:
# http://www.postgresql.org/docs/current/static/runtime.html

# PostgreSQL Commands:
# http://www.postgresql.org/docs/current/static/reference.html

# PostgreSQL Data Types:
# http://www.postgresql.org/docs/current/static/datatype.html

conn = psycopg2.connect(dbname = 'orion',
                host = '127.7.74.2:5432', #'localhost',
                port = 5432,
                user = 'earthling',
                password = 'extraterrestrial')

sql = conn.cursor()

def CREATE_TABLE(table, text):
    sql.execute("CREATE TABLE " + table + " (" + text + ");")

def INSERT(table, url, text):
    #date = datetime.date.today()
    date = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')
    print date
    query = "INSERT INTO " + table + " (url, text, date) VALUES (%s, %s, %s);"
    params = (url, text, date,)
    sql.execute(query, params)

def SELECT(table, url):
    query = "SELECT * FROM " + table + " WHERE url = %s;"
    sql.execute(query, (url,))

def QUERY(text):
    sql.execute(text)

INSERT("main", "www.whoi.edu", "test")
print SELECT("main", "www.whoi.edu")
</code>```

Thanks for your help!

Question: This should fairly simple and shouldn't require psycopg2?

答:
Separate to the issue of client side libraries you need use port forwarding to expose the PostgreSQL database inside of OpenShift to your local computer. The IP address of the PostgreSQL service inside of OpenShift is not going to be externally visible. See the tutorial about port forwarding with OpenShift at:

https://learn.openshift.com/

Body:
I'm trying to connect to OpenShift from a OS X Python Script.  OpenShift for sure works.  However, I'm looking for an "easy" way with python without downloading additional PGSQL libs to OS X.  Thanks!

Question: What is the correct domain name to use for this??  And can we keep it simple without doing an import to python?

I don't want to use any additional libraries.

the main problem I'm having is with pgsql.connect(dbname = 'orion', host = '127.7.74.2:5432', #'localhost', port = 5432, user = 'earthling', password = 'extraterrestrial')

Here is what the code file looks like "pgsql.py"...

# PostgreSQL Client:
# http://www.postgresql.org/docs/current/static/reference-client.html

# PostgreSQL Server:
# http://www.postgresql.org/docs/current/static/runtime.html

# PostgreSQL Commands:
# http://www.postgresql.org/docs/current/static/reference.html

# PostgreSQL Data Types:
# http://www.postgresql.org/docs/current/static/datatype.html

conn = psycopg2.connect(dbname = 'orion',
                host = '127.7.74.2:5432', #'localhost',
                port = 5432,
                user = 'earthling',
                password = 'extraterrestrial')

sql = conn.cursor()

def CREATE_TABLE(table, text):
    sql.execute("CREATE TABLE " + table + " (" + text + ");")

def INSERT(table, url, text):
    #date = datetime.date.today()
    date = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')
    print date
    query = "INSERT INTO " + table + " (url, text, date) VALUES (%s, %s, %s);"
    params = (url, text, date,)
    sql.execute(query, params)

def SELECT(table, url):
    query = "SELECT * FROM " + table + " WHERE url = %s;"
    sql.execute(query, (url,))

def QUERY(text):
    sql.execute(text)

INSERT("main", "www.whoi.edu", "test")
print SELECT("main", "www.whoi.edu")

Thanks for your help!

Question: This should fairly simple and shouldn't require psycopg2?


问:
Troubleshooting php-fpm load problems
I'll start with a bit of a back-story, there's times during the day we're getting a couple thousand requests to our server over a small period of time. While this is happening it seems that something regarding PHP FPM goes wrong and we can't access any of the webpages served by nginx and as soon as we restart php it seems to be working fine again. PHP FPM hasn't really been changed, the settings are as follows:

```<code>    pm = dynamic
    pm.max_children = 5
    pm.start_servers = 2
    pm.min_spare_servers = 1
    pm.max_spare_servers = 3
    pm.max_requests = 0
    pm.process_idle_timeout = 10s
</code>```

After many of those requests are processed we start seeing this error

```<code>    connect() to unix:/run/php/php7.0-fpm.sock failed (11: Resource temporarily unavailable) while connecting to upstream, client: *.*.*.*, server: *.com, request: "GET /* HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm.sock:", host: "*.com"
</code>```

I'm not sure if I can provide any more information regarding errors, if you think I can, be sure to ask and I'll check any of the log files I can. My question is can the problem be in the PHP FPM config?

答:
increase your pm.max_children = 5 to max supported by your system
and decrease pm.process_idle_timeout = 10s to least </p>

Title: Troubleshooting php-fpm load problems

Body:
I'll start with a bit of a back-story, there's times during the day we're getting a couple thousand requests to our server over a small period of time. While this is happening it seems that something regarding PHP FPM goes wrong and we can't access any of the webpages served by nginx and as soon as we restart php it seems to be working fine again. PHP FPM hasn't really been changed, the settings are as follows:

    pm = dynamic
    pm.max_children = 5
    pm.start_servers = 2
    pm.min_spare_servers = 1
    pm.max_spare_servers = 3
    pm.max_requests = 0
    pm.process_idle_timeout = 10s

After many of those requests are processed we start seeing this error

    connect() to unix:/run/php/php7.0-fpm.sock failed (11: Resource temporarily unavailable) while connecting to upstream, client: *.*.*.*, server: *.com, request: "GET /* HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm.sock:", host: "*.com"

I'm not sure if I can provide any more information regarding errors, if you think I can, be sure to ask and I'll check any of the log files I can. My question is can the problem be in the PHP FPM config?


问:
Batch file to copy a single folder - not just the contents
I am struggling to create a batch file that I can use in any folder, which will copy the current folder and all its contents to another location. The objective is to allow me to make very quick backups of any current folder by running the batch file. Batch files are new to me, but programming isn't. Here is my code.

```<code>@echo off
title Copy This Directory
:: get current directory
 set startdir=%cd%
 echo.startdir = %startdir%
:: copy the test folder
 xcopy "%startdir%" "F:\Temp Backup\" /s /y
 pause
</code>```

This copies the files and folders that are inside the source folder to the new destination, but I want to copy the folder itself together with its contents. ie if the batch file is in a folder called "FromFolder", I want "FromFolder" to appear as a folder in "F:\Temp Backup\" and all its contents in "F:\Temp Backup\FromFolder". I've found lots of info about copying files, but nothing about copying a single directory. I can copy a single file, but when I use the same code and change the file name to a folder name, it copies the folder's contents and not the folder itself. Could someone let me know what I have missed please.

答:
```<code>@echo off

rem set destination dir
set destDir=C:\tmp\fizz bang

rem get the current dir
set currDir=%cd%

rem set current dir to parent
pushd ..

rem get the parent dir path
set parDir=%cd%

rem replace the parent path part of the dir with the destination
rem see also: https://stackoverflow.com/a/5821366
rem also note the trailing backslash to tell xcopy it's a directory
CALL set destPath=%%currDir:%parDir%=%destDir%%%\

rem copy
xcopy /e "%currDir%" "%destPath%"

rem go back where we started
popd

pause
</code>```

Body:
I am struggling to create a batch file that I can use in any folder, which will copy the current folder and all its contents to another location. The objective is to allow me to make very quick backups of any current folder by running the batch file. Batch files are new to me, but programming isn't. Here is my code.

@echo off
title Copy This Directory
:: get current directory
 set startdir=%cd%
 echo.startdir = %startdir%
:: copy the test folder
 xcopy "%startdir%" "F:\Temp Backup\" /s /y
 pause

This copies the files and folders that are inside the source folder to the new destination, but I want to copy the folder itself together with its contents. ie if the batch file is in a folder called "FromFolder", I want "FromFolder" to appear as a folder in "F:\Temp Backup\" and all its contents in "F:\Temp Backup\FromFolder". I've found lots of info about copying files, but nothing about copying a single directory. I can copy a single file, but when I use the same code and change the file name to a folder name, it copies the folder's contents and not the folder itself. Could someone let me know what I have missed please.


问:
For images, what is the benefit of using the name element? name="...."
I want to know what the difference is between alt="" and name=""

Would it be better to put the filename within the alt tag, or the description of the photo?

What makes better sense, both from SEO and validation stand-point?

答:
Using the ALT attribute is more useful in terms of search engine optimalisation. Using the NAME attribute is mainly useful for internal page anchors.

The ALT attribute is intended to provide an alternate text that describes the image for people who use screen-readers, or search engines, for example.

The name attribute is mainly used for internal anchoring, which allows you to navigate within a page using anchors.

Example usage of the name attribute:

```<code><!-- following ancor can be referenced as http://<your_url>#post-123 -->
<a name="post-123">permanent link to some post</a>
</code>```

Example usage of alt attribute:

```<code><!-- following image shows "FooBar Company Logo" when images can't be shown -->
<img src="logo.jpg" alt="FooBar Company logo" />
</code>```

For more information regarding links in general: http://www.w3.org/TR/REC-html40/struct/links.html

For more information about how and when to use the ALT attribute, see:
http://www.w3.org/QA/Tips/altAttribute.

OwnerDisplayName: Brad

Body:
Using the ALT attribute is more useful in terms of search engine optimalisation. Using the NAME attribute is mainly useful for internal page anchors.

The ALT attribute is intended to provide an alternate text that describes the image for people who use screen-readers, or search engines, for example.

The name attribute is mainly used for internal anchoring, which allows you to navigate within a page using anchors.

Example usage of the name attribute:

<!-- following ancor can be referenced as http://<your_url>#post-123 -->
<a name="post-123">permanent link to some post</a>

Example usage of alt attribute:

<!-- following image shows "FooBar Company Logo" when images can't be shown -->
<img src="logo.jpg" alt="FooBar Company logo" />

For more information regarding links in general: http://www.w3.org/TR/REC-html40/struct/links.html

For more information about how and when to use the ALT attribute, see:
http://www.w3.org/QA/Tips/altAttribute.

OwnerDisplayName: Aron Rotteveel

LastEditorDisplayName: Aron Rotteveel


问:
Security advice: SSL and API access
My API (a desktop application) communicates with my web app using basic HTTP authentication over SSL (Basically I'm just using https instead of http in the requests). My API has implemented logic that makes sure that users don't send incorrect information, but the problem I have is that someone could bypass the API and use curl to potentially post incorrect data (obtaining credentials is trivial since signing up on my web app is free).

I have thought about the following options:

Duplicate the API's logic in the web app so that even if users try to cheat the system using curl or some other tool they are presented with the same conditions.

Implement a further authentication check to make sure only my API can communicate with my web app. (Perhaps SSL client certificates?).

Encrypt the data (Base 64?)

I know I'm being a little paranoid about users spoofing my web app with curl-like tools but I'd rather be safe than sorry. Duplicating the logic is really painful and I would rather not do that. I don't know much about SSL client certificates, can I use them in conjunction with basic HTTP authentication? Will they make my requests take longer to process? What other options do I have?

Thanks in advance.

答:
You must validate the data on the server side. You can throw nasty errors back across the connection if the server-side validation fails — that's OK, they're not supposed to be tripped — but if you don't, you are totally vulnerable. (Think about it this way: it's the server's logic that you totally control, therefore it is the server's logic that has to make the definitive decisions about the validity of communications.)

Using client certificates won't really protect you much additionally from users who have permission to use the API in the first place; if nothing else, they can take apart the code to extract the client certificate (and it has to be readable to your client code to be usable at all). Nor will adding extra encryption; it makes things much more difficult for you (more things to go wrong) without adding much safety over that already provided by that SSL connection. (The scenario where adding encryption helps is when the messages sent over HTTPS have to go via untrusted proxies.)

Base-64 is not encryption. It's just a way of encoding bytes as easier-to-handle characters.

Title: Security advice: SSL and API access


问:
MySQL Access denied from command connection
So I'm connecting to an AWS EC2 Ubuntu 16.04 instance. As part of my production script I do:

mysql -u root -pmy-secret -e "source resetDb.sql;" >> lastRun.log

This resetDb.sql has the queries to create and populate the database info. Then keep on going with the app.

The thing is that mysql is rejecting my access this way by throwing

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

But if I connect with mysql -u root -p and manually enter the password, it lets me into the console, so this let's me see the password is right.

I get this output on the server

$ mysql --version
mysql  Ver 14.14 Distrib 5.7.20, for Linux (x86_64) using  EditLine wrapper
$ uname -a
Linux ip-xx.xx.xx.xx 4.4.0-1038-aws #47-Ubuntu SMP Thu Sep 28 20:05:35 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

I've seen in another questions about flushing privileges and resetting the root password, but my password is correct so it did no good to me.

Anyone has a clue? The idea is to run the script to automatically setup the whole server. Thanks in advance.

答:
Your password is using "special" characters that the command shell is interpreting. Watch out for these characters in passwords:

$ & ! \ [ ] < > `

Enclose your password in a single quote for Linux: 'my_%PATH_problem&password'. For Windows use double quotes. You can also escape problem characters using the bakslash \


问:
Group item from an array based on the date
I have the following array:

```<code>Array
(
    [0] => Array
        (
            [Date] => 2017-11-01 09:15:02
            [Country] => France
        )
    [1] => Array
        (
            [Date] => 2017-11-01 04:45:01
            [Country] => Spain
        )
    [1] => Array
        (
            [Date] => 2017-11-03 04:45:01
            [Country] => Italy
        )
    [1] => Array
        (
            [Date] => 2017-11-04 04:45:01
            [Country] => Canada
        )
)
</code>```

I need to group this array based on the date.

For example, countries with the same day (not hour) should be grouped together.

What I tried:

```<code>$array = array();
foreach ($array as $data) {
  $id = $data['Date'];
  if (isset($array[$Date])) {
     $array[$Date][] = $data;
  } else {
     $array[$Date] = array($data);
  }
}
</code>```

Could you please help me finding what I missed ?

Thanks.

答:
Try this.

```<code>foreach($array as $arr){
    $ex = explode(' ', $arr['Date']);//explode the dates via space and the first element will be the date like 2017-11-01
    $newarr[$ex[0]][] = $arr['Country'];
}
</code>```

output is

```<code>Array
(
    [2017-11-01] => Array
        (
            [0] => France
            [1] => Spain
        )
    [2017-11-03] => Array
        (
            [0] => Italy
        )
    [2017-11-04] => Array
        (
            [0] => Canada
        )

)
</code>```

I hope this helps you.

Body:
I have the following array:

Array
(
    [0] => Array
        (
            [Date] => 2017-11-01 09:15:02
            [Country] => France
        )
    [1] => Array
        (
            [Date] => 2017-11-01 04:45:01
            [Country] => Spain
        )
    [1] => Array
        (
            [Date] => 2017-11-03 04:45:01
            [Country] => Italy
        )
    [1] => Array
        (
            [Date] => 2017-11-04 04:45:01
            [Country] => Canada
        )
)

I need to group this array based on the date.

For example, countries with the same day (not hour) should be grouped together.

What I tried:

$array = array();
foreach ($array as $data) {
  $id = $data['Date'];
  if (isset($array[$Date])) {
     $array[$Date][] = $data;
  } else {
     $array[$Date] = array($data);
  }
}

Could you please help me finding what I missed ?

Thanks.

Body:
Try this.

foreach($array as $arr){
    $ex = explode(' ', $arr['Date']);//explode the dates via space and the first element will be the date like 2017-11-01
    $newarr[$ex[0]][] = $arr['Country'];
}

output is

Array
(
    [2017-11-01] => Array
        (
            [0] => France
            [1] => Spain
        )
    [2017-11-03] => Array
        (
            [0] => Italy
        )
    [2017-11-04] => Array
        (
            [0] => Canada
        )

)

I hope this helps you.


问:
Understanding apyori's output
I'm well familiar with the apriori algorithm, and the meaning of support/confidence/lift.

I'm currently using the apyori apriori implementation, and I'm not sure I understand the output of an apyori.apriori() call.

It comes out like this

```<code>> RelationRecord(items=frozenset({'item1', 'item2'}),
> support=0.15365410803449842,
> ordered_statistics=[OrderedStatistic(items_base=frozenset({'item1'}),
> items_add=frozenset({'item2'}), confidence=0.6203420891875382,
> lift=2.2233410344037092),
> OrderedStatistic(items_base=frozenset({'item2'}),
> items_add=frozenset({'item1'}), confidence=0.5507049891540131,
> lift=2.2233410344037097)])
</code>```

What is the rule? There are multiple support/confidence/lift, what each one denotes?

I'd appreciate a dictionary style explanation of each part of the output

答:
The RelationRecord reflects a subset of items, while ordered_statistics is a list of OrderedStatistics, which reflect the rules. Each OrderedStatistics' items_base is the antecedent and the items_add is the consequent. The support is stored in the RelationRecord, since it's the same for the contained rules.

In your example:

item1 -> item2 with 0.62 confidence and 2.2233410344037092x lift

item2 -> item1 with 0.55 confidence and 2.2233410344037097x lift

Both have support=0.15365410803449842.

For what it's worth, I ended up switching to using PyFIM for relative feature richness and other bundled algorithms (e.g. fp-growth).

Title: Understanding apyori's output

Body:
I'm well familiar with the apriori algorithm, and the meaning of support/confidence/lift.

I'm currently using the apyori apriori implementation, and I'm not sure I understand the output of an apyori.apriori() call.

It comes out like this

> RelationRecord(items=frozenset({'item1', 'item2'}),
> support=0.15365410803449842,
> ordered_statistics=[OrderedStatistic(items_base=frozenset({'item1'}),
> items_add=frozenset({'item2'}), confidence=0.6203420891875382,
> lift=2.2233410344037092),
> OrderedStatistic(items_base=frozenset({'item2'}),
> items_add=frozenset({'item1'}), confidence=0.5507049891540131,
> lift=2.2233410344037097)])

What is the rule? There are multiple support/confidence/lift, what each one denotes?

I'd appreciate a dictionary style explanation of each part of the output


问:
Do process supported by Java mean the same as process supported by the underlying OS?
Java supports multiprocess via Process, ProcessBuilder and Runtime.exec()...

Do process supported by Java mean the same as process supported by the underlying OS?

Or is process supported by Java a different concept from process supported by the underlying OS?

Is there some mapping between processes supported by Java and processes supported by the underlying OS?

Thanks.

答:
From the official Javadoc:

The ProcessBuilder.start() and Runtime.exec methods create a native process and return an instance of a subclass of Process that can be used to control the process and obtain information about it.

So yes, these represent native processes of the underlying OS.


问:
NSTask Launch causing crash
I have an application that can import an XML file through this terminal command :

open /path/to/main\ app.app --args myXML.xml

This works great with no issues. And i have used Applescript to launch this command through shell and it works just as well. Yet when try using Cocoa's NSTask Launcher using this code :

```<code>NSTask *task = [[NSTask alloc] init];

[task setLaunchPath:@"/usr/bin/open"];

[task setCurrentDirectoryPath:@"/Applications/MainApp/InstallData/App/"];

[task setArguments:[NSArray arrayWithObjects:[(NSURL *)foundApplicationURL path], @"--args", @"ImportP.xml", nil]];

[task launch];
</code>```

the applications will start up to the initial screen and then crash when either the next button is clicked or when trying to close the window. Ive tried using NSAppleScript with this :

```<code>NSAppleScript *script = [[NSAppleScript alloc] initWithSource:@"tell application \"Terminal\" do script \"open /Applications/MainApp/InstallData/App/Main\\\\ App.app\" end tell"];

NSDictionary *errorInfo;

[script executeAndReturnError:&errorInfo];
</code>```

This will launch the program and it will crash as well and i get this error in my Xcode debug window :

```<code>12011-01-04 17:41:28.296 LaunchAppFile[4453:a0f]
Error loading /Library/ScriptingAdditions/Adobe Unit Types.osax/Contents/MacOS/Adobe Unit Types:  dlopen(/Library/ScriptingAdditions/Adobe Unit Types.osax/Contents/MacOS/Adobe Unit Types, 262): no suitable image found.
Did find: /Library/ScriptingAdditions/Adobe Unit Types.osax/Contents/MacOS/Adobe Unit Types: no matching architecture in universal wrapper
LaunchAppFile: OpenScripting.framework - scripting addition "/Library/ScriptingAdditions/Adobe Unit Types.osax" declares no loadable handlers.
</code>```

So with research i came up with this :

```<code>NSAppleScript *script = [[NSAppleScript alloc] initWithSource:@"do shell script \"arch -i386 osascript /Applications/MainApp/InstallData/App/test.scpt\""];

NSDictionary *errorInfo;

[script executeAndReturnError:&errorInfo];
</code>```

But this causes the same results as the last command.
Any ideas on what causes this crash?

答:
Give NSTask another try with full paths only:

```<code>NSTask *task = [[NSTask alloc] init];

[task setLaunchPath:@"/usr/bin/open"];

[task setArguments:[NSArray arrayWithObjects:[ @"'/path/to/main app.app'", @"--args", @"/path/to/ImportP.xml", nil]];

[task launch];
</code>```

Another approach would be to give NSTask the following command line:

```<code>sh -c '/usr/bin/open "/path/to/main app.app" --args /path/to/myXML.xml'

...

NSTask *task = [[NSTask alloc] init];

[task setLaunchPath:@"/bin/sh"];

NSString *cmd = [NSString stringWithFormat:
         @"%@ %@ %@ %@",
         @"/usr/bin/open",
         @"'/path/to/main app.app'",
         @"--args",
         @"/path/to/myXML.xml"
];

[task setArguments:[NSArray arrayWithObjects:[ @"-c", cmd, nil]];

[task launch];
</code>```

Title: NSTask Launch causing crash

Body:
I have an application that can import an XML file through this terminal command :

open /path/to/main\ app.app --args myXML.xml

This works great with no issues. And i have used Applescript to launch this command through shell and it works just as well. Yet when try using Cocoa's NSTask Launcher using this code :

NSTask *task = [[NSTask alloc] init];

[task setLaunchPath:@"/usr/bin/open"];

[task setCurrentDirectoryPath:@"/Applications/MainApp/InstallData/App/"];

[task setArguments:[NSArray arrayWithObjects:[(NSURL *)foundApplicationURL path], @"--args", @"ImportP.xml", nil]];

[task launch];

the applications will start up to the initial screen and then crash when either the next button is clicked or when trying to close the window. Ive tried using NSAppleScript with this :

NSAppleScript *script = [[NSAppleScript alloc] initWithSource:@"tell application \"Terminal\" do script \"open /Applications/MainApp/InstallData/App/Main\\\\ App.app\" end tell"];

NSDictionary *errorInfo;

[script executeAndReturnError:&errorInfo];

This will launch the program and it will crash as well and i get this error in my Xcode debug window :

12011-01-04 17:41:28.296 LaunchAppFile[4453:a0f]
Error loading /Library/ScriptingAdditions/Adobe Unit Types.osax/Contents/MacOS/Adobe Unit Types:  dlopen(/Library/ScriptingAdditions/Adobe Unit Types.osax/Contents/MacOS/Adobe Unit Types, 262): no suitable image found.
Did find: /Library/ScriptingAdditions/Adobe Unit Types.osax/Contents/MacOS/Adobe Unit Types: no matching architecture in universal wrapper
LaunchAppFile: OpenScripting.framework - scripting addition "/Library/ScriptingAdditions/Adobe Unit Types.osax" declares no loadable handlers.

So with research i came up with this :

NSAppleScript *script = [[NSAppleScript alloc] initWithSource:@"do shell script \"arch -i386 osascript /Applications/MainApp/InstallData/App/test.scpt\""];

NSDictionary *errorInfo;

[script executeAndReturnError:&errorInfo];

But this causes the same results as the last command.
Any ideas on what causes this crash?

Body:
Give NSTask another try with full paths only:

NSTask *task = [[NSTask alloc] init];

[task setLaunchPath:@"/usr/bin/open"];

[task setArguments:[NSArray arrayWithObjects:[ @"'/path/to/main app.app'", @"--args", @"/path/to/ImportP.xml", nil]];

[task launch];

Another approach would be to give NSTask the following command line:

sh -c '/usr/bin/open "/path/to/main app.app" --args /path/to/myXML.xml'

...

NSTask *task = [[NSTask alloc] init];

[task setLaunchPath:@"/bin/sh"];

NSString *cmd = [NSString stringWithFormat:
         @"%@ %@ %@ %@",
         @"/usr/bin/open",
         @"'/path/to/main app.app'",
         @"--args",
         @"/path/to/myXML.xml"
];

[task setArguments:[NSArray arrayWithObjects:[ @"-c", cmd, nil]];

[task launch];


答:
```<code>$inputArray = array();
foreach ($inputArray as $data) {
   if (isset($array[$Date])) {
      $outputArray[date('Y-m-d', strtotime($data['Date']))][] = $data;
   }else{
      $outputArray['notSet'][] = $data;
   }
}
</code>```

Title: Group item from an array based on the date


问:
Bash script for nagios error: No output on stdout - works fine on command line
Good evening folks,

I'm trying to read the build version of an in-house built software from several remote servers and display it on Nagios

The script runs perfectly on the command line but on Nagios I'm getting this error message:

"(No output on stdout) stderr: execvp(/usr/local/nagios/libexec/chk_prg_version, ...) failed. errno is 2: No such file or directory"

Here's my script (without the original data, which is sensitive needless to say)

```<code>#!/bin/bash

#copy the file to local temp and rename it for uniqueness
sshpass -f "password" scp -r user@serverName://FileLocation/FileName /tmp/storenumber

#Scan the file and grep anything after the string Program-Version:
pversion=$(grep "Program-Version:" /tmp/MFileName | sed 's/^.*: //')

#nagios checks
if [ if the pversion matches the latest release version ]
then
    echo "OK - $pversion"
    exit 0
elif [ if the pversion is any of the previous releases ]
then
    echo "warning error message"
    exit 1
elif [ if returns a value that doesn't match any release ]
then
    echo "critical error message"
    exit 2
else
    echo "uknown"
    exit 3
fi

#delete the file
rm /tmp/storenumber
</code>```

答: I was able to figure out the answer: the command had a typo that reads the plugin. It's working absolutely fine now. </p>

Body:
Good evening folks,

I'm trying to read the build version of an in-house built software from several remote servers and display it on Nagios

The script runs perfectly on the command line but on Nagios I'm getting this error message:

"(No output on stdout) stderr: execvp(/usr/local/nagios/libexec/chk_prg_version, ...) failed. errno is 2: No such file or directory"

Here's my script (without the original data, which is sensitive needless to say)

#!/bin/bash

#copy the file to local temp and rename it for uniqueness
sshpass -f "password" scp -r user@serverName://FileLocation/FileName /tmp/storenumber

#Scan the file and grep anything after the string Program-Version:
pversion=$(grep "Program-Version:" /tmp/MFileName | sed 's/^.*: //')

#nagios checks
if [ if the pversion matches the latest release version ]
then
    echo "OK - $pversion"
    exit 0
elif [ if the pversion is any of the previous releases ]
then
    echo "warning error message"
    exit 1
elif [ if returns a value that doesn't match any release ]
then
    echo "critical error message"
    exit 2
else
    echo "uknown"
    exit 3
fi

#delete the file
rm /tmp/storenumber


问:
django count per column
I have a ORM like this

```<code>from django.db import models,

class MyObject(models.Model):

   class Meta:
       db_table = 'myobject'

   id = models.IntegerField(primary_key=True)
   name = models.CharField(max_length=48)
   status = models.CharField(max_length=48)
</code>```

Imagine I have the following entries

```<code>1 | foo | completed
2 | foo | completed
3 | bar | completed
4 | foo | failed
</code>```

What is the django ORM query that I have to make in order to get a queryset somewhat like the following

```<code>[{'name': 'foo', 'status_count': 'completed: 2, failed: 1'},
 {'name': 'bar', 'status_count': 'completed: 1'}]
</code>```

I started with the following but I don't know how to "merge" the two columns:

```<code>from django.db.models import Count
models.MyObject.objects.values(
    'name',
    'status'
).annotate(my_count=Count('id'))
</code>```

The goal of all this to get a table where I can show something like the following:

```<code>Name | completed | failed
foo  | 2         | 1
bar  | 1         | 0
</code>```

答:
This should work as expected:</p>

```<code>test = MyObject.objects.values('name').annotate(
    total_completed=Count(
        Case(
            When(
                status='completed', then=1), output_field=DecimalField()
        )
    ),
    total_failed=Count(
        Case(
            When(status='failed', then=1), output_field=DecimalField()
        )
    )
)
</code>```

Title: django count per column

Body:
I have a ORM like this

from django.db import models,

class MyObject(models.Model):

   class Meta:
       db_table = 'myobject'

   id = models.IntegerField(primary_key=True)
   name = models.CharField(max_length=48)
   status = models.CharField(max_length=48)

Imagine I have the following entries

1 | foo | completed
2 | foo | completed
3 | bar | completed
4 | foo | failed

What is the django ORM query that I have to make in order to get a queryset somewhat like the following

[{'name': 'foo', 'status_count': 'completed: 2, failed: 1'},
 {'name': 'bar', 'status_count': 'completed: 1'}]

I started with the following but I don't know how to "merge" the two columns:

from django.db.models import Count
models.MyObject.objects.values(
    'name',
    'status'
).annotate(my_count=Count('id'))

The goal of all this to get a table where I can show something like the following:

Name | completed | failed
foo  | 2         | 1
bar  | 1         | 0

Body:
This should work as expected:

test = MyObject.objects.values('name').annotate(
    total_completed=Count(
        Case(
            When(
                status='completed', then=1), output_field=DecimalField()
        )
    ),
    total_failed=Count(
        Case(
            When(status='failed', then=1), output_field=DecimalField()
        )
    )
)


问:
How to set function converted from number into html span tag
I need help with the last line in this. I need to take the current month,
picked from the getMonthText var and have it be in the

```<code><h1><span id="month_year"> </span></h1>
</code>```

Beginning of code.
My issue is at the bottom
This part turns the month number into a name.

```<code>    var getMonthText = function(currentMonth) {
        if (currentMonth === 0) { return "January"; }
        else if (currentMonth === 1) { return "February"; }
        else if (currentMonth === 2) { return "March"; }
        else if (currentMonth === 3) { return "April"; }
        else if (currentMonth === 4) { return "May"; }
        else if (currentMonth === 5) { return "June"; }
        else if (currentMonth === 6) { return "July"; }
        else if (currentMonth === 7) { return "August"; }
        else if (currentMonth === 8) { return "September"; }
        else if (currentMonth === 9) { return "October"; }
        else if (currentMonth === 10) { return "November"; }
        else if (currentMonth === 11) { return "December"; }
    };
</code>```

After that and some other code
......
This is the problem area

```<code>    $("#month-year").html(getMonthText);  <-- set it to the html ***This is the part I'm having trouble with, even though it should be simple.
</code>```

Thanks for any/all help.

答:
Ouch! This is not the way to be doing this. Just set up an array of month names and get the right name via its index. No if/else if needed.

Also, don't forget the () and the argument value after your function name so that you actually invoke the function.

Additionally, your HTML id uses an underscore, while your JQuery reference to the element attempts a hyphen. They must match up.

Finally, don't use the .html() method if you aren't passing any HTML to the element. It causes the HTML parser to parse the string and if there isn't any HTML in the string, it's a waste of resources. When you have plain text, use the .text() method, which doesn't do any parsing on the string.

var months = [
  "Januaray", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
];

function getMonthText(currentMonth) {
  return months[currentMonth];
}

$("#month_year").text(getMonthText(6));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1><span id="month_year"></span></h1></code>```

Body:
I need help with the last line in this. I need to take the current month,
picked from the getMonthText var and have it be in the

Beginning of code.
My issue is at the bottom
This part turns the month number into a name.

    var getMonthText = function(currentMonth) {
        if (currentMonth === 0) { return "January"; }
        else if (currentMonth === 1) { return "February"; }
        else if (currentMonth === 2) { return "March"; }
        else if (currentMonth === 3) { return "April"; }
        else if (currentMonth === 4) { return "May"; }
        else if (currentMonth === 5) { return "June"; }
        else if (currentMonth === 6) { return "July"; }
        else if (currentMonth === 7) { return "August"; }
        else if (currentMonth === 8) { return "September"; }
        else if (currentMonth === 9) { return "October"; }
        else if (currentMonth === 10) { return "November"; }
        else if (currentMonth === 11) { return "December"; }
    };

After that and some other code
......
This is the problem area

    $("#month-year").html(getMonthText);  <-- set it to the html ***This is the part I'm having trouble with, even though it should be simple.

Thanks for any/all help.

Body:
Ouch! This is not the way to be doing this. Just set up an array of month names and get the right name via its index. No if/else if needed.

Also, don't forget the () and the argument value after your function name so that you actually invoke the function.

Additionally, your HTML id uses an underscore, while your JQuery reference to the element attempts a hyphen. They must match up.

Finally, don't use the .html() method if you aren't passing any HTML to the element. It causes the HTML parser to parse the string and if there isn't any HTML in the string, it's a waste of resources. When you have plain text, use the .text() method, which doesn't do any parsing on the string.

var months = [
  "Januaray", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
];

function getMonthText(currentMonth) {
  return months[currentMonth];
}

$("#month_year").text(getMonthText(6));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1><span id="month_year"></span></h1>


问:
Can't connect to local MySQL server through socket
I am getting the following error

error: 'Can't connect to local MySQL
  server through socket
  '/var/lib/mysql/mysql.sock' (2)'

How can i restore the mysql.sock file?

[Edit]

I am trying to connect to mysql database from my ROR application. It was working fine till yesterday. But today I found out the mysql.sock file was missing. I don't know the reason of what led to deletion of mysql.sock file from location /var/lib/mysql/. How can i restore the mysql.file?

Thanks.....

答:
Try this:

```<code>$ mysql_config |grep -- --socket
</code>```

It should show you the socket path as compiled in to the server. If that fails, try running the mysql command and look for the socket path in the output of \s.

Body:
Try this:

$ mysql_config |grep -- --socket

It should show you the socket path as compiled in to the server. If that fails, try running the mysql command and look for the socket path in the output of \s.


问:
create an append method
I'm doing a project that requires me to create an append method.

This is what the instructions say:

These methods should create a new double array containing exactly those
elements of data followed by those of the array passed as a parameter. A reference to this array
should be assigned to data. If the parameter is null, then the method should do nothing (no new
array created)

so far this is my code:

```<code>public void append(double [] d) {

        if (data != null) {

        double[] newDataArray = new double [data.length];

        for(int i = 0; i < data.length; i++) {

            newDataArray[i] = data[i];
        }

        } else {

        }

    }
</code>```

I'm testing it using this main method:

```<code>double[]    data1   =   {};
double[]    data2   =   {   25  };
float[] data3   =   {};
float[] data4   =   {   25  };
int[]   data5   =   {};
int[]   data6   =   {   50  };
long[]  data7   =   {};
long[]  data8   =   {   12  };
Stat    stat1   =   new Stat();
stat1.append(data1);
stat1.append(data2);
stat1.append(data3);
stat1.append(data4);
stat1.append(data5);
stat1.append(data6);
stat1.append(data7);
stat1.append(data8);
data1   =   null;
stat1.append(data1);
System.out.println("stat1   data    =   " + stat1.toString());
System.out.println("stat1   min =   " + stat1.min());
System.out.println("stat1   max =   " + stat1.max());
System.out.println("stat1   average =   " + stat1.average());
System.out.println("stat1   mode    =   " + stat1.mode());
System.out.println("stat1   variance    =   " + stat1.variance());
System.out.println("stat1   standard    deviation   =   " + stat1.standardDeviation()   +   "\n");
</code>```

This is my output:

```<code>stat1   data    =   [0.0, ]
stat1   min =   0.0
stat1   max =   0.0
stat1   average =   0.0
stat1   mode    =   0.0
stat1   variance    =   0.0
stat1   standard    deviation   =   0.0
</code>```

However the output should be:

```<code>stat1   data    =   [25.0,  25.0,   50.0,   12.0]
stat1   min =   12.0
stat1   max =   50.0
stat1   average =   28.0
stat1   mode    =   25.0
stat1 variance  =   189.5
stat1   standard    deviation   =   13.765899897936205
</code>```

Can someone help me understand what I'm doing wrong?

答: data isn't defined anywhere, even though it is used in your append method; nor does it get assigned to in your method.

Title: create an append method

Body:
I'm doing a project that requires me to create an append method.

This is what the instructions say:

These methods should create a new double array containing exactly those
elements of data followed by those of the array passed as a parameter. A reference to this array
should be assigned to data. If the parameter is null, then the method should do nothing (no new
array created)

so far this is my code:

public void append(double [] d) {

        if (data != null) {

        double[] newDataArray = new double [data.length];

        for(int i = 0; i < data.length; i++) {

            newDataArray[i] = data[i];
        }

        } else {

        }

    }

I'm testing it using this main method:

double[]    data1   =   {};
double[]    data2   =   {   25  };
float[] data3   =   {};
float[] data4   =   {   25  };
int[]   data5   =   {};
int[]   data6   =   {   50  };
long[]  data7   =   {};
long[]  data8   =   {   12  };
Stat    stat1   =   new Stat();
stat1.append(data1);
stat1.append(data2);
stat1.append(data3);
stat1.append(data4);
stat1.append(data5);
stat1.append(data6);
stat1.append(data7);
stat1.append(data8);
data1   =   null;
stat1.append(data1);
System.out.println("stat1   data    =   " + stat1.toString());
System.out.println("stat1   min =   " + stat1.min());
System.out.println("stat1   max =   " + stat1.max());
System.out.println("stat1   average =   " + stat1.average());
System.out.println("stat1   mode    =   " + stat1.mode());
System.out.println("stat1   variance    =   " + stat1.variance());
System.out.println("stat1   standard    deviation   =   " + stat1.standardDeviation()   +   "\n");

This is my output:

stat1   data    =   [0.0, ]
stat1   min =   0.0
stat1   max =   0.0
stat1   average =   0.0
stat1   mode    =   0.0
stat1   variance    =   0.0
stat1   standard    deviation   =   0.0

However the output should be:

stat1   data    =   [25.0,  25.0,   50.0,   12.0]
stat1   min =   12.0
stat1   max =   50.0
stat1   average =   28.0
stat1   mode    =   25.0
stat1 variance  =   189.5
stat1   standard    deviation   =   13.765899897936205

Can someone help me understand what I'm doing wrong?


问:
Stop service and close app
My app use a background music service.
I have a button to quit my app but I can't find anything to close my app and my service.
I bind my service to my activity.

I tried:

```<code>unbindService(serviceConnection);
myService().stopSelf();
stopService(new Intent(this, MediaPlayer.class));
</code>```

and absolutely nothing works !!! The service continues.

How can I do to destroy my service and how can I do to close my app ??

Tx

EDIT:

I use this in the onCreate method

```<code>Intent intent = new Intent(this, serviceClass);
bindService(intent, serviceConnection, BIND_AUTO_CREATE);
</code>```

And in the MediaPlayer class

```<code>public class LocalBinder extends Binder {
        public MediaPlayer getService() {
            return MediaPlayer.this;
        }
    }
public IBinder onBind(Intent intent) {
    Log.i(TAG, "service bound");
    init();
    return mBinder;
}
</code>```

And that...
But I dont know if I really need to start the service. Bind the service already starts it

```<code>@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return START_NOT_STICKY;
}
</code>```

Now I did this

```<code>@Override
public void onDestroy() {
    player.stop();
    super.onDestroy();
}
</code>```

The onDestroy method works only if i unbind the service !
This doesnt work at all:

```<code>        getService().stopSelf();
       this.stopService(new Intent(this, MediaPlayer.class));
</code>```

So, how can I stop the service and how can I close the app ?

答:
This is what I do in my app. onDestroy() method from the activity will be called when you close your app.

```<code>private ServiceConnection musicServiceConnection = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        MusicService.LocalBinder binder = (MusicService.LocalBinder) service;
        musicService = binder.getService();
        musicService.setCallbacks(MainActivity.this);
        musicServiceBound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.i(TAG, "MusicService service disconnected (unbinded)");
        musicServiceBound = false;
    }
};

@Override
protected void onStart() {
    super.onStart();
    Intent intent1 = new Intent(this, MusicService.class);
    bindService(intent1, musicServiceConnection, Context.BIND_AUTO_CREATE);
}

@Override
protected void onDestroy() {
    super.onDestroy()
    if(musicServiceBound){
        musicService.stopSelf();
        unbindService(musicServiceConnection);
    }
}
</code>```

You wrote myService(), where you are creating another service using ().
For closing your app programmatically you can refer to this question.

Title: Stop service and close app

Body:
My app use a background music service.
I have a button to quit my app but I can't find anything to close my app and my service.
I bind my service to my activity.

I tried:

unbindService(serviceConnection);
myService().stopSelf();
stopService(new Intent(this, MediaPlayer.class));

and absolutely nothing works !!! The service continues.

How can I do to destroy my service and how can I do to close my app ??

Tx

EDIT:

I use this in the onCreate method

Intent intent = new Intent(this, serviceClass);
bindService(intent, serviceConnection, BIND_AUTO_CREATE);

And in the MediaPlayer class

public class LocalBinder extends Binder {
        public MediaPlayer getService() {
            return MediaPlayer.this;
        }
    }
public IBinder onBind(Intent intent) {
    Log.i(TAG, "service bound");
    init();
    return mBinder;
}

And that...
But I dont know if I really need to start the service. Bind the service already starts it

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return START_NOT_STICKY;
}

Now I did this

@Override
public void onDestroy() {
    player.stop();
    super.onDestroy();
}

The onDestroy method works only if i unbind the service !
This doesnt work at all:

        getService().stopSelf();
       this.stopService(new Intent(this, MediaPlayer.class));

So, how can I stop the service and how can I close the app ?

Body:
This is what I do in my app. onDestroy() method from the activity will be called when you close your app.

private ServiceConnection musicServiceConnection = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        MusicService.LocalBinder binder = (MusicService.LocalBinder) service;
        musicService = binder.getService();
        musicService.setCallbacks(MainActivity.this);
        musicServiceBound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.i(TAG, "MusicService service disconnected (unbinded)");
        musicServiceBound = false;
    }
};

@Override
protected void onStart() {
    super.onStart();
    Intent intent1 = new Intent(this, MusicService.class);
    bindService(intent1, musicServiceConnection, Context.BIND_AUTO_CREATE);
}

@Override
protected void onDestroy() {
    super.onDestroy()
    if(musicServiceBound){
        musicService.stopSelf();
        unbindService(musicServiceConnection);
    }
}

You wrote myService(), where you are creating another service using ().
For closing your app programmatically you can refer to this question.


问:
Starting solution automatically in VS 2017 via a batch file
I have a solution in Visual Studio 2017 with 21 coded ui test cases inside it. I can open this solution via a batch file that was created. Batch file basically changes the directory to where the solution is and starts it (start Forms.sln). Is there any way I can run all the coded ui tests inside the solution automatically from the same batch file?

Any help would be appreciated

Russ

答:
Yes. Use VSTEST.CONSOLE.exe. Check out this link
https://msdn.microsoft.com/en-us/library/jj155800.aspx</p>


问:
DebugBreak() equivalent in C#
In C# is there any statement equivalent to DebugBreak()? I want to invoke the debugger when ever a particular condition is met.

答:
Maybe Debugger.Break</p>

```<code>System.Diagnostics.Debugger.Break();
</code>```

Title: DebugBreak() equivalent in C#

Body:
Maybe Debugger.Break

System.Diagnostics.Debugger.Break();


问:
C# How to add string variables with values to the any System.Collections class and retrieve them
So I have a slightly interesting problem right here. What I'm trying to achieve is to add between 1000 to 2000 string variables to the list and later compare them with another strings. So far I can achieve this by using below code:

```<code>var list = new List<string>();
var item_1 = "USA";
var item_2 = "Canada";
var item_3 = "Cuba";
...................
var item_N = "Country_N";
list.Add(item_1);
list.Add(item_2);
list.Add(item_3);
.................
list.Add(item_N);
</code>```

And comparing them with another strings looks like below (using FluentAssertions class):

```<code>list[0].Should().Match(stringToCompare_1);
list[1].Should().Match(stringToCompare_2);
list[2].Should().Match(stringToCompare_3);
</code>```

The biggest problem that I see here is it's sort of hard to memorize what string was added to a particular index of the list (unstoppable scrolling between the code is boring). My question: is there any more elegant way to handle this situation? Something that might look like below (List class method ValueOf is fictional):

```<code>var list = new List<string>();
var item_1_USA = "USA";
var item_2_Canada = "Canada";
var item_3_Cuba = "Cuba";
list.ValueOf(item_1_USA).Should().Match(stringToCompare_1);
list.ValueOf(item_1_Canada).Should().Match(stringToCompare_2);
list.ValueOf(item_1_Cuba).Should().Match(stringToCompare_3);
</code>```

As many suggested (including @Postlagerkarte) to edit the question to clarify what I'm trying to achieve. I'm testing the web app, and while going through every step of this application (imagine booking engine), I need to capture and store different info (like user's First Name, Last Name, Email Address, Phone Number, etc). The amount of the captured info can sometimes exceed 2000 items. Currently I'm using data structure List. Later, at the final step of my application, I need to compare my stored values with what ever present on this final page. For instance: user's first name, that was captured on Step 2 of the booking engine must match with value on final step. List Contains method won't be suitable here as it can validate incorrect information. Accessing the values using list[0]....list[N] is very inconvenient, as I can forget what exactly was stored at that index. I'm solving it now by scrolling through the code to return back. Any wise navigation is appreciated.

答:
You can use a Dictionary<string, string> for this. The key of each value would be a field or info identifier: userFirstName, userAge, etc. As you process data you add it to your dictionary with whatever value you are reading.

When validating, you look up the stored value with the field identifier and compare it to whatever data shows upon your last page.

You can also consider using an enumeration as your key instead of string although if you avoid magic strings literals and use constants you should be ok.

Body:
So I have a slightly interesting problem right here. What I'm trying to achieve is to add between 1000 to 2000 string variables to the list and later compare them with another strings. So far I can achieve this by using below code:

var list = new List<string>();
var item_1 = "USA";
var item_2 = "Canada";
var item_3 = "Cuba";
...................
var item_N = "Country_N";
list.Add(item_1);
list.Add(item_2);
list.Add(item_3);
.................
list.Add(item_N);

And comparing them with another strings looks like below (using FluentAssertions class):

list[0].Should().Match(stringToCompare_1);
list[1].Should().Match(stringToCompare_2);
list[2].Should().Match(stringToCompare_3);

The biggest problem that I see here is it's sort of hard to memorize what string was added to a particular index of the list (unstoppable scrolling between the code is boring). My question: is there any more elegant way to handle this situation? Something that might look like below (List class method ValueOf is fictional):

var list = new List<string>();
var item_1_USA = "USA";
var item_2_Canada = "Canada";
var item_3_Cuba = "Cuba";
list.ValueOf(item_1_USA).Should().Match(stringToCompare_1);
list.ValueOf(item_1_Canada).Should().Match(stringToCompare_2);
list.ValueOf(item_1_Cuba).Should().Match(stringToCompare_3);

As many suggested (including @Postlagerkarte) to edit the question to clarify what I'm trying to achieve. I'm testing the web app, and while going through every step of this application (imagine booking engine), I need to capture and store different info (like user's First Name, Last Name, Email Address, Phone Number, etc). The amount of the captured info can sometimes exceed 2000 items. Currently I'm using data structure List. Later, at the final step of my application, I need to compare my stored values with what ever present on this final page. For instance: user's first name, that was captured on Step 2 of the booking engine must match with value on final step. List Contains method won't be suitable here as it can validate incorrect information. Accessing the values using list[0]....list[N] is very inconvenient, as I can forget what exactly was stored at that index. I'm solving it now by scrolling through the code to return back. Any wise navigation is appreciated.


问:
How to delete my message Discord.py
Hello I try to delete a message when my bot finish his job but I don't kwon how do that ! Can you help me ? pls This is my code : </p>

```<code>@client.command(pass_context=True)
async def chiant(ctx, *args):

    phrase = ""
    if args == None:
        await client.say("Aie tu as oublié de mettre une phrase !")
    elif len(args) != 0:
        for e in args:
            phrase = phrase +" "+ e
        #await client.say(phrase)
    else:
        await client.say("Aie tu as oublié de mettre une phrase !")

    await client.say(phrase, tts=True)

    await client.delete_message(ctx.message)
</code>```

答:
I fix my problem with : </p>

```<code>@client.command(pass_context=True)
async def chiant(ctx, *args):

    phrase = ""
    if args == None:
        await client.say("Aie tu as oublié de mettre une phrase !")
    elif len(args) != 0:
        for e in args:
            phrase = phrase +" "+ e
        #await client.say(phrase)
    else:
        await client.say("Aie tu as oublié de mettre une phrase !")

    message = await client.say(phrase, tts=True) #This line fix ALL !

    await client.delete_message(message)
</code>```

Title: How to delete my message Discord.py

Body:
Hello I try to delete a message when my bot finish his job but I don't kwon how do that ! Can you help me ? pls This is my code :

@client.command(pass_context=True)
async def chiant(ctx, *args):

    phrase = ""
    if args == None:
        await client.say("Aie tu as oublié de mettre une phrase !")
    elif len(args) != 0:
        for e in args:
            phrase = phrase +" "+ e
        #await client.say(phrase)
    else:
        await client.say("Aie tu as oublié de mettre une phrase !")

    await client.say(phrase, tts=True)

    await client.delete_message(ctx.message)

Body:
I fix my problem with :

@client.command(pass_context=True)
async def chiant(ctx, *args):

    phrase = ""
    if args == None:
        await client.say("Aie tu as oublié de mettre une phrase !")
    elif len(args) != 0:
        for e in args:
            phrase = phrase +" "+ e
        #await client.say(phrase)
    else:
        await client.say("Aie tu as oublié de mettre une phrase !")

    message = await client.say(phrase, tts=True) #This line fix ALL !

    await client.delete_message(message)


问:
How to only field names(not field values) of a particular document using node.js
I'm a beginner in both MongoDB and node.js. Actually, I'm trying to get the names of a particular document but I wonder how to do that.
Let me elaborate in detail :
if "a" is a collection which contains document named "student" and "student" contains fields like

```<code>{
    "_id: "student",
    "name": "alex",
    "roll": "3",
    "age":"13"
}
</code>```

then how to get the field names in this ["name","roll","age"] format
By trying this:

```<code>db.collection("user").find({ "_id": "student" }).toArray(function(err, result) {
    console.log(result)
})
</code>```

is giving all the fields with their values.

答:
try :

db.collection("user").find({"_id":"student"}, {name:1}).toArray(function(err, result) {console.log(result)}

if you want to exclude fields :

db.collection("user").find({"_id":"student"}, {roll:0, age:0}).toArray(function(err, result) {console.log(result)}

Body:
I'm a beginner in both MongoDB and node.js. Actually, I'm trying to get the names of a particular document but I wonder how to do that.
Let me elaborate in detail :
if "a" is a collection which contains document named "student" and "student" contains fields like

{
    "_id: "student",
    "name": "alex",
    "roll": "3",
    "age":"13"
}

then how to get the field names in this ["name","roll","age"] format
By trying this:

db.collection("user").find({ "_id": "student" }).toArray(function(err, result) {
    console.log(result)
})

is giving all the fields with their values.


问:
python appends to all dictionaries
I am using dictoinaries inside of dictionaries. Looping through a pandas dataframe, the value of the action row always matches one of the keys in the dictionary, and based on that some other values from that row are appended to a list in that dictionary. For some reason, however, the values are appended to all lists in the other dictionaries

```<code>    general_form = {
        "Percentage": np.nan, "DayPercentage": np.nan, "sample_size": np.nan, "Percentages": [], "DayPercentages": []
    }
    #get all possible action types
    action_types = self.df['Action Type'].tolist()
    action_types = list(set(action_types))

    #give every action type its own dictionary within the main dictionary
    sheetstats = {}
    for action in action_types:
        sheetstats[action] = general_form

    #push the percentage in the list inside the dictionary specified in
    #action
    for index, row in self.df.iterrows():
        percentage = row['Percentage']
        daypercentage = row['DayPercentage']
        action = row['Action Type']
        sheetstats[action]['Percentages'].append(percentage)
        sheetstats[action]["DayPercentages"].append(daypercentage)
</code>```

This will make all of the percentages identical in all dictionaries inside sheetstats. Why?

答:
You are assigning general_form on every iteration.

Could it be you want to assign the value from action_types?

sheetstats[action] = action_types[action] ?

```<code>general_form = {
        "Percentage": np.nan, "DayPercentage": np.nan, "sample_size": np.nan, "Percentages": [], "DayPercentages": []
    }
    #get all possible action types
    action_types = self.df['Action Type'].tolist()
    action_types = list(set(action_types))

    #give every action type its own dictionary within the main dictionary
    sheetstats = {}
    for action in action_types:
        sheetstats[action] = action_types[action]

    #push the percentage in the list inside the dictionary specified in
    #action
    for index, row in self.df.iterrows():
        percentage = row['Percentage']
        daypercentage = row['DayPercentage']
        action = row['Action Type']
        sheetstats[action]['Percentages'].append(percentage)
        sheetstats[action]["DayPercentages"].append(daypercentage)
</code>```

Title: python appends to all dictionaries

Body:
I am using dictoinaries inside of dictionaries. Looping through a pandas dataframe, the value of the action row always matches one of the keys in the dictionary, and based on that some other values from that row are appended to a list in that dictionary. For some reason, however, the values are appended to all lists in the other dictionaries

    general_form = {
        "Percentage": np.nan, "DayPercentage": np.nan, "sample_size": np.nan, "Percentages": [], "DayPercentages": []
    }
    #get all possible action types
    action_types = self.df['Action Type'].tolist()
    action_types = list(set(action_types))

    #give every action type its own dictionary within the main dictionary
    sheetstats = {}
    for action in action_types:
        sheetstats[action] = general_form

    #push the percentage in the list inside the dictionary specified in
    #action
    for index, row in self.df.iterrows():
        percentage = row['Percentage']
        daypercentage = row['DayPercentage']
        action = row['Action Type']
        sheetstats[action]['Percentages'].append(percentage)
        sheetstats[action]["DayPercentages"].append(daypercentage)

This will make all of the percentages identical in all dictionaries inside sheetstats. Why?

Body:
You are assigning general_form on every iteration.

Could it be you want to assign the value from action_types?

sheetstats[action] = action_types[action] ?

general_form = {
        "Percentage": np.nan, "DayPercentage": np.nan, "sample_size": np.nan, "Percentages": [], "DayPercentages": []
    }
    #get all possible action types
    action_types = self.df['Action Type'].tolist()
    action_types = list(set(action_types))

    #give every action type its own dictionary within the main dictionary
    sheetstats = {}
    for action in action_types:
        sheetstats[action] = action_types[action]

    #push the percentage in the list inside the dictionary specified in
    #action
    for index, row in self.df.iterrows():
        percentage = row['Percentage']
        daypercentage = row['DayPercentage']
        action = row['Action Type']
        sheetstats[action]['Percentages'].append(percentage)
        sheetstats[action]["DayPercentages"].append(daypercentage)


问:
Error symbol variable ShapeType not found
I have just started to learn game develpoment in libgdx
It is showing error in this line

```<code>shapeRenderer.begin(ShapeType.Point);
</code>```

error displayed is:-

Error:(80, 29) error: cannot find symbol variable ShapeType

this is my complete  class

```<code>   import com.badlogic.gdx.ApplicationAdapter;
   import com.badlogic.gdx.Gdx;
   import com.badlogic.gdx.graphics.GL20;
   import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
   import com.badlogic.gdx.math.*;
   import com.badlogic.gdx.utils.*;
   import java.util.*;
   public class Starfield extends ApplicationAdapter {

   private static final float STAR_DENSITY = 0.01f;
   ShapeRenderer shapeRenderer;
   Array<Vector2> stars;

   @Override
   public void create() {

   shapeRenderer=new ShapeRenderer();
   initStars(0.01f);

   }

   public void initStars(float density) {

   int a = Gdx.graphics.getWidth();
   int b=Gdx.graphics.getHeight();
   int count=Integer.parseInt(Float.toString(a*b*density));
   stars=new Array<Vector2>(count);
   Random random=new Random();
    for(int i=0;i<count;i++)
    {
        int x=random.nextInt(a);
        int y=random.nextInt(b);
        stars.add(new Vector2(a,b));
    }
   }

   @Override
   public void resize(int width, int height) {
    initStars(STAR_DENSITY);
    shapeRenderer = new ShapeRenderer();
   }

   @Override
   public void render() {

    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    shapeRenderer.begin(ShapeType.Point);

   for(Vector2 star : stars)
   {
   shapeRenderer.point(star.x,star.y,0);
   }

   shapeRenderer.end();
   }

   @Override
   public void dispose() {

   shapeRenderer.dispose();
    super.dispose();
 }
 }
</code>```

答:
ShapeType is an enum inside ShapeRenderer class.

Use in this way :

```<code>shapeRenderer.begin(ShapeRenderer.ShapeType.Point);
</code>```

Body:
I have just started to learn game develpoment in libgdx
It is showing error in this line

shapeRenderer.begin(ShapeType.Point);

error displayed is:-

Error:(80, 29) error: cannot find symbol variable ShapeType

this is my complete  class

   import com.badlogic.gdx.ApplicationAdapter;
   import com.badlogic.gdx.Gdx;
   import com.badlogic.gdx.graphics.GL20;
   import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
   import com.badlogic.gdx.math.*;
   import com.badlogic.gdx.utils.*;
   import java.util.*;
   public class Starfield extends ApplicationAdapter {

   private static final float STAR_DENSITY = 0.01f;
   ShapeRenderer shapeRenderer;
   Array<Vector2> stars;

   @Override
   public void create() {

   shapeRenderer=new ShapeRenderer();
   initStars(0.01f);

   }

   public void initStars(float density) {

   int a = Gdx.graphics.getWidth();
   int b=Gdx.graphics.getHeight();
   int count=Integer.parseInt(Float.toString(a*b*density));
   stars=new Array<Vector2>(count);
   Random random=new Random();
    for(int i=0;i<count;i++)
    {
        int x=random.nextInt(a);
        int y=random.nextInt(b);
        stars.add(new Vector2(a,b));
    }
   }

   @Override
   public void resize(int width, int height) {
    initStars(STAR_DENSITY);
    shapeRenderer = new ShapeRenderer();
   }

   @Override
   public void render() {

    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    shapeRenderer.begin(ShapeType.Point);

   for(Vector2 star : stars)
   {
   shapeRenderer.point(star.x,star.y,0);
   }

   shapeRenderer.end();
   }

   @Override
   public void dispose() {

   shapeRenderer.dispose();
    super.dispose();
 }
 }

Body:
ShapeType is an enum inside ShapeRenderer class.

Use in this way :

shapeRenderer.begin(ShapeRenderer.ShapeType.Point);


问:
For Integer type variable, does '=' operator equate the value or the reference?
CODE 1 :

```<code>Car car1 = new Car();
Car car2 = new Car();
car2.setColor("Green");
car2.setModel("I20");
car1 = car2;
System.out.println(car1.getColor() + " , " + car1.getModel());
System.out.println(car2.getColor() + " , " + car2.getModel());
car1.setColor("Red");
car1.setModel("I10");
System.out.println(car1.getColor() + " , " + car1.getModel());
System.out.println(car2.getColor() + " , " + car2.getModel());
</code>```

Output :

```<code>Green , I20
Green , I20
Red , I10
Red , I10
</code>```

Here the car1 = car2; make the car1 object refer to car2 object thus any further change to car1 is equivalent to changing the car2 object as both are referencing to same value.

CODE 2 :

```<code>Integer c = 5;
Integer d = 10;
System.out.println(c + ", " + d);
c = d;
System.out.println(c + ", " + d);
c = 7;
System.out.println(c + ", " + d);
</code>```

Output :

```<code>5, 10
10, 10
7, 10
</code>```

Here also after c = d; both c and d refer to the same value then why changing the value of c does not change the value of d?

答:
No because you assign value d in c not inverse.
Do you understand ?
If you desirre assing value c in d you write d = c for d recive reference of c</p>

Body:
CODE 1 :

Car car1 = new Car();
Car car2 = new Car();
car2.setColor("Green");
car2.setModel("I20");
car1 = car2;
System.out.println(car1.getColor() + " , " + car1.getModel());
System.out.println(car2.getColor() + " , " + car2.getModel());
car1.setColor("Red");
car1.setModel("I10");
System.out.println(car1.getColor() + " , " + car1.getModel());
System.out.println(car2.getColor() + " , " + car2.getModel());

Output :

Green , I20
Green , I20
Red , I10
Red , I10

Here the car1 = car2; make the car1 object refer to car2 object thus any further change to car1 is equivalent to changing the car2 object as both are referencing to same value.

CODE 2 :

Integer c = 5;
Integer d = 10;
System.out.println(c + ", " + d);
c = d;
System.out.println(c + ", " + d);
c = 7;
System.out.println(c + ", " + d);

Output :

5, 10
10, 10
7, 10

Here also after c = d; both c and d refer to the same value then why changing the value of c does not change the value of d?


问:
MVC4 Bundles returns 404
I have a project that works with bundling when you run it from within visual studio. However, after you do a deployment, the bundling handler never seems to pick up the route. It ends up going to the static file handler instead, which returns a 404 response.

Any ideas? I see the optimization assembly in the bin of the website under IIS.

It's using the 4.0 app pool and integrated mode.

I'm wondering if anyone has any ideas or suggestions?

Thanks

----- update based on questions -----

VS2012

targetFramework="4.5"

I also added some code into the view to show which modules were loaded and I can see the bundle module listed there.

BundleConfig is the default provided when using the Internet Application MVC4 project template.

The site is being deployed into the root. It's odd as when I set EnableOptimizations = true (due to running in debug mode via visual studio F5), it works perfect! I can navigate to content/css and it spits out the combined css.

I deploy it over and everything else works, but bundling!

答:
I had the same problem even with sample MVC application. I saw the default template bundles the style-sheet with css name which i guess IIS does not likes resulting in 404 error.

Changing  the bundle name from css to APPCSS will resolve the issue for me.

Title: MVC4 Bundles returns 404