问:
Select data from database via AJAX (ASP.NET MVC)
I have database with tables Companies, Vacancies, Interview and QuestionBlocks.

Here is scheme of it

So Vacancy is connected to Company, Interview connected to Vacancy and Question blocks connected to Interview.

I realize DropdownLists for Company and when I select company Vacancy dropdown list updates.

Here is code for View

```<code><div style="width: 100%; margin-left: 20px;height: 15%;padding-top: 20px;">
    @Html.DropDownList("Company", ViewBag.Companies as SelectList, "Компания", new { @class = "greeting", @style = "width:30%; margin-left:20px;" })
    <select class="greeting" id="vacancy" name="id"  style="width:30%; margin-left:150px;" data-url="@Url.Action("Vacancies","Questions")">
        <option value="" disabled selected>Вакансия</option>
    </select>
</div>
</code>```

And Ajax call

```<code><script>
    $(function () {
        $("#Company").change(function (e) {
            var $vacancy = $("#vacancy");
            var url = $vacancy.data("url") + '?companyId=' + $(this).val();
            $.getJSON(url, function (items) {
                $.each(items, function (a, b) {
                    $vacancy.append('<option value="' + b.Value + '">' + b.Text + '</option>');
                });
            });
        });
    });
</script>
</code>```

I have View like this

So what I need.

I need to make request to controller and find QuestionBlock  that related to VacancyId.

So as I understood I need to pass VacancyId from dropdownlist to controller make some sql operations and return JSON?

Or how I can do this?

UPDATE

Thank's for answer @CuriousDev, It works well for select item.

I need one more thing, I need to display Question1-Question10 like this.

Here is my Action method

```<code>public ActionResult QuestionBlocks(int vacancyId)
{
    var items = db.QuestionBlocks
        .Where(x => x.Interview.VacancyId == vacancyId)
        .Select(x => new
        {
            ID = x.Block_ID.ToString(),
            Question1 = x.Question1,
            Question2 = x.Question2,
            Question3 = x.Question3,
            Question4 = x.Question4,
            Question5 = x.Question5,
            Question6 = x.Question6,
            Question7 = x.Question7,
            Question8 = x.Question8,
            Question9 = x.Question9,
            Question10 = x.Question10,
        })
        .ToList();
    return Json(items, JsonRequestBehavior.AllowGet);
}
</code>```

How I need to write ajax call to back -end and display data in div?

答:
Below is ajax call to get json from Action Method it could be on dropdown change or some other events you wants on Success create your table structure and append it to the body as you wants below if just sample code

```<code>    $.ajax({
            url: '@Url.Action("QuestionBlocks","YourController")',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(model),
            type: 'Get',
            dataType: 'json',
            processData: false
        })
        .success(function (result) {
           // Here do some stuff with your JSON to bind that in Table
         var trHTML = '';

         $.each(data.Countries, function (i, item) {

          trHTML += 'Your Table Structure';
         });

          $('#YourID').append(trHTML);
        })
        .error(function (xhr, status) {
        alert("error");
     });
</code>```

Body:
I have database with tables Companies, Vacancies, Interview and QuestionBlocks.

Here is scheme of it

So Vacancy is connected to Company, Interview connected to Vacancy and Question blocks connected to Interview.

I realize DropdownLists for Company and when I select company Vacancy dropdown list updates.

Here is code for View

    @Html.DropDownList("Company", ViewBag.Companies as SelectList, "Компания", new { @class = "greeting", @style = "width:30%; margin-left:20px;" })
    <select class="greeting" id="vacancy" name="id"  style="width:30%; margin-left:150px;" data-url="@Url.Action("Vacancies","Questions")">
        <option value="" disabled selected>Вакансия</option>
    </select>

And Ajax call

I have View like this

So what I need.

I need to make request to controller and find QuestionBlock  that related to VacancyId.

So as I understood I need to pass VacancyId from dropdownlist to controller make some sql operations and return JSON?

Or how I can do this?

UPDATE

Thank's for answer @CuriousDev, It works well for select item.

I need one more thing, I need to display Question1-Question10 like this.

Here is my Action method

public ActionResult QuestionBlocks(int vacancyId)
{
    var items = db.QuestionBlocks
        .Where(x => x.Interview.VacancyId == vacancyId)
        .Select(x => new
        {
            ID = x.Block_ID.ToString(),
            Question1 = x.Question1,
            Question2 = x.Question2,
            Question3 = x.Question3,
            Question4 = x.Question4,
            Question5 = x.Question5,
            Question6 = x.Question6,
            Question7 = x.Question7,
            Question8 = x.Question8,
            Question9 = x.Question9,
            Question10 = x.Question10,
        })
        .ToList();
    return Json(items, JsonRequestBehavior.AllowGet);
}

How I need to write ajax call to back -end and display data in div?

Body:
Below is ajax call to get json from Action Method it could be on dropdown change or some other events you wants on Success create your table structure and append it to the body as you wants below if just sample code

    $.ajax({
            url: '@Url.Action("QuestionBlocks","YourController")',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(model),
            type: 'Get',
            dataType: 'json',
            processData: false
        })
        .success(function (result) {
           // Here do some stuff with your JSON to bind that in Table
         var trHTML = '';

         $.each(data.Countries, function (i, item) {

          trHTML += 'Your Table Structure';
         });

          $('#YourID').append(trHTML);
        })
        .error(function (xhr, status) {
        alert("error");
     });


来源: stackexchange

问:
EF builds EntityCollection, but I (think I) want IQueryable
I have an entity A with a simple navigation property B.  For any given instance of A, we expect several related thousand instances of B.

There is no case where I call something like:

```<code>foreach(var x in A.B) { ... }
</code>```

Instead, I'm only interested in doing aggregate operations such as

```<code>var statY = A.B.Where(o => o.Property == "Y");
var statZ = A.B.Where(o => o.CreateDate > DateTime.Now.AddDays(-1));
</code>```

As far as I can tell, EF instantiates thousands of references to B and does these operations in memory.  This is because navigation properties use EntityCollection.  Instead, I'd like it to perform these queries at the SQL level if possible.

My current hunch is that Navigation Properties may not be the right way to go.  I'm not attached to EF, so I am open to other approaches.  But I'd be very interested to know the right way to do this under EF if possible.

(I'm using EF4.)

答:
CreateSourceQuery seems to do the trick.

So my examples would now be:

```<code>var statY = A.B.CreateSourceQuery().Where(o => o.Property == "Y");
var statZ = A.B.CreateSourceQuery().Where(o => o.CreateDate > DateTime.Now.AddDays(-1));
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have an entity A with a simple navigation property B.  For any given instance of A, we expect several related thousand instances of B.

There is no case where I call something like:

foreach(var x in A.B) { ... }

Instead, I'm only interested in doing aggregate operations such as

var statY = A.B.Where(o => o.Property == "Y");
var statZ = A.B.Where(o => o.CreateDate > DateTime.Now.AddDays(-1));

As far as I can tell, EF instantiates thousands of references to B and does these operations in memory.  This is because navigation properties use EntityCollection.  Instead, I'd like it to perform these queries at the SQL level if possible.

My current hunch is that Navigation Properties may not be the right way to go.  I'm not attached to EF, so I am open to other approaches.  But I'd be very interested to know the right way to do this under EF if possible.

(I'm using EF4.)

Body:
CreateSourceQuery seems to do the trick.

So my examples would now be:

var statY = A.B.CreateSourceQuery().Where(o => o.Property == "Y");
var statZ = A.B.CreateSourceQuery().Where(o => o.CreateDate > DateTime.Now.AddDays(-1));


问:
Start an external activity to scan barcode
I want to start the barcode scanner from my app and get the tag

Here is what I have so far :

scan.h

```<code>class DecodeBarCode : public QObject
{
    Q_OBJECT

    BarCodeReceiver *m_receiver;

public:
    explicit DecodeBarCode(QObject *parent = 0);
    ~DecodeBarCode();

    Q_INVOKABLE void useZXingApp();

signals:
    void tagFound(QString tag);
};

class BarCodeReceiver : public QAndroidActivityResultReceiver
{
    DecodeBarCode *m_decoder;
public:
    BarCodeReceiver(DecodeBarCode *decoder) : m_decoder(decoder) {}

    virtual void handleActivityResult(int receiverRequestCode, int resultCode, const QAndroidJniObject &data) {
        emit m_decoder->tagFound("Receiver worked");
    }

};
</code>```

scan.cpp

```<code>DecodeBarCode::DecodeBarCode(QObject *parent) : QObject(parent)
{
    m_receiver = new BarCodeReceiver(this);
}

DecodeBarCode::~DecodeBarCode()
{
    delete m_receiver;
}

void DecodeBarCode::useZXingApp()
{
    QAndroidJniObject intent = QAndroidJniObject::fromString("com/google/zxing/client/android/SCAN");
    if (intent.isValid()) {
        QtAndroid::startActivity(intent,0,m_receiver); // CRASH HERE
    } else {
        emit tagFound("Invalid"); // TEMP
    }
}
</code>```

That is the first time I use JNI, never used it in java nor c++/Qt

There must be something very wrong, what is it ?

答:
I finally got it to work, here is the full code :

decodebarcode.h

```<code>#ifndef DECODEBARCODE_H
#define DECODEBARCODE_H

#include <QObject>
#ifdef Q_OS_ANDROID
#include <QtAndroidExtras/QtAndroid>
#include <QtAndroidExtras/QAndroidJniObject>
#include <QtAndroidExtras/QAndroidJniEnvironment>
#include <QtAndroidExtras/QAndroidActivityResultReceiver>
#endif

class BarCodeReceiver;

class DecodeBarCode : public QObject
{
    Q_OBJECT

    BarCodeReceiver *m_receiver;

public:
    explicit DecodeBarCode(QObject *parent = 0);
    ~DecodeBarCode();

    Q_INVOKABLE void useZXingApp();

signals:
    void tagFound(QString tag);
};

#ifdef Q_OS_ANDROID
class BarCodeReceiver : public QAndroidActivityResultReceiver
{
    DecodeBarCode *m_decoder;
public:
    BarCodeReceiver(DecodeBarCode *decoder);

    virtual void handleActivityResult(int receiverRequestCode, int resultCode, const QAndroidJniObject &data);

};
#else
class BarCodeReceiver
{
public:
    BarCodeReceiver(DecodeBarCode *decoder) {Q_UNUSED(decoder)};
};
#endif

#endif // DECODEBARCODE_H
</code>```

decodebarcode.cpp

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

DecodeBarCode::DecodeBarCode(QObject *parent) : QObject(parent)
{
    m_receiver = new BarCodeReceiver(this);
}

DecodeBarCode::~DecodeBarCode()
{
    delete m_receiver;
}

void DecodeBarCode::useZXingApp()
{
#ifdef Q_OS_ANDROID
    QAndroidJniObject action = QAndroidJniObject::fromString("com.google.zxing.client.android.SCAN");

    // Intent intent = new Intent(action)
    QAndroidJniObject intent("android/content/Intent","(Ljava/lang/String;)V", action.object<jstring>());

    jint flagCategorieDefault = QAndroidJniObject::getStaticField<jint>("android/content/Intent", "CATEGORY_DEFAULT");
    jint flagActivityClearTop = QAndroidJniObject::getStaticField<jint>("android/content/Intent", "FLAG_ACTIVITY_CLEAR_TOP");
    jint flagActivityClearTaskReset = QAndroidJniObject::getStaticField<jint>("android/content/Intent", "FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET");

    // intentScan.addCategory(Intent.CATEGORY_DEFAULT);
    intent.callObjectMethod("addCategory", "(I)V", flagCategorieDefault);

    //intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.callObjectMethod("addFlags", "(I)V", flagActivityClearTop);

    //intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
    intent.callObjectMethod("addFlags", "(I)V", flagActivityClearTaskReset);

    QtAndroid::startActivity(intent, 0, m_receiver);
#endif
}

#ifdef Q_OS_ANDROID
BarCodeReceiver::BarCodeReceiver(DecodeBarCode *decoder)
    : m_decoder(decoder)
{

}

void BarCodeReceiver::handleActivityResult(int receiverRequestCode, int resultCode, const QAndroidJniObject &data)
{
    QAndroidJniObject stringExtraScanResult = QAndroidJniObject::fromString("SCAN_RESULT");
    QAndroidJniObject scanResult = data.callObjectMethod("getStringExtra", "(Ljava/lang/String;)Ljava/lang/String;", stringExtraScanResult.object<jstring>());
    emit m_decoder->tagFound(scanResult.toString());
}
#endif
</code>```

If you have the same problem, I hope that help

ContentLicense: CC BY-SA 3.0

Body:
I want to start the barcode scanner from my app and get the tag

Here is what I have so far :

scan.h

class DecodeBarCode : public QObject
{
    Q_OBJECT

    BarCodeReceiver *m_receiver;

public:
    explicit DecodeBarCode(QObject *parent = 0);
    ~DecodeBarCode();

    Q_INVOKABLE void useZXingApp();

signals:
    void tagFound(QString tag);
};

class BarCodeReceiver : public QAndroidActivityResultReceiver
{
    DecodeBarCode *m_decoder;
public:
    BarCodeReceiver(DecodeBarCode *decoder) : m_decoder(decoder) {}

    virtual void handleActivityResult(int receiverRequestCode, int resultCode, const QAndroidJniObject &data) {
        emit m_decoder->tagFound("Receiver worked");
    }

};

scan.cpp

DecodeBarCode::DecodeBarCode(QObject *parent) : QObject(parent)
{
    m_receiver = new BarCodeReceiver(this);
}

DecodeBarCode::~DecodeBarCode()
{
    delete m_receiver;
}

void DecodeBarCode::useZXingApp()
{
    QAndroidJniObject intent = QAndroidJniObject::fromString("com/google/zxing/client/android/SCAN");
    if (intent.isValid()) {
        QtAndroid::startActivity(intent,0,m_receiver); // CRASH HERE
    } else {
        emit tagFound("Invalid"); // TEMP
    }
}

That is the first time I use JNI, never used it in java nor c++/Qt

There must be something very wrong, what is it ?

Body:
I finally got it to work, here is the full code :

decodebarcode.h

#ifndef DECODEBARCODE_H
#define DECODEBARCODE_H

#include <QObject>
#ifdef Q_OS_ANDROID
#include <QtAndroidExtras/QtAndroid>
#include <QtAndroidExtras/QAndroidJniObject>
#include <QtAndroidExtras/QAndroidJniEnvironment>
#include <QtAndroidExtras/QAndroidActivityResultReceiver>
#endif

class BarCodeReceiver;

class DecodeBarCode : public QObject
{
    Q_OBJECT

    BarCodeReceiver *m_receiver;

public:
    explicit DecodeBarCode(QObject *parent = 0);
    ~DecodeBarCode();

    Q_INVOKABLE void useZXingApp();

signals:
    void tagFound(QString tag);
};

#ifdef Q_OS_ANDROID
class BarCodeReceiver : public QAndroidActivityResultReceiver
{
    DecodeBarCode *m_decoder;
public:
    BarCodeReceiver(DecodeBarCode *decoder);

    virtual void handleActivityResult(int receiverRequestCode, int resultCode, const QAndroidJniObject &data);

};
#else
class BarCodeReceiver
{
public:
    BarCodeReceiver(DecodeBarCode *decoder) {Q_UNUSED(decoder)};
};
#endif

#endif // DECODEBARCODE_H

decodebarcode.cpp

#include "decodebarcode.h"

DecodeBarCode::DecodeBarCode(QObject *parent) : QObject(parent)
{
    m_receiver = new BarCodeReceiver(this);
}

DecodeBarCode::~DecodeBarCode()
{
    delete m_receiver;
}

void DecodeBarCode::useZXingApp()
{
#ifdef Q_OS_ANDROID
    QAndroidJniObject action = QAndroidJniObject::fromString("com.google.zxing.client.android.SCAN");

    // Intent intent = new Intent(action)
    QAndroidJniObject intent("android/content/Intent","(Ljava/lang/String;)V", action.object<jstring>());

    jint flagCategorieDefault = QAndroidJniObject::getStaticField<jint>("android/content/Intent", "CATEGORY_DEFAULT");
    jint flagActivityClearTop = QAndroidJniObject::getStaticField<jint>("android/content/Intent", "FLAG_ACTIVITY_CLEAR_TOP");
    jint flagActivityClearTaskReset = QAndroidJniObject::getStaticField<jint>("android/content/Intent", "FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET");

    // intentScan.addCategory(Intent.CATEGORY_DEFAULT);
    intent.callObjectMethod("addCategory", "(I)V", flagCategorieDefault);

    //intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.callObjectMethod("addFlags", "(I)V", flagActivityClearTop);

    //intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
    intent.callObjectMethod("addFlags", "(I)V", flagActivityClearTaskReset);

    QtAndroid::startActivity(intent, 0, m_receiver);
#endif
}

#ifdef Q_OS_ANDROID
BarCodeReceiver::BarCodeReceiver(DecodeBarCode *decoder)
    : m_decoder(decoder)
{

}

void BarCodeReceiver::handleActivityResult(int receiverRequestCode, int resultCode, const QAndroidJniObject &data)
{
    QAndroidJniObject stringExtraScanResult = QAndroidJniObject::fromString("SCAN_RESULT");
    QAndroidJniObject scanResult = data.callObjectMethod("getStringExtra", "(Ljava/lang/String;)Ljava/lang/String;", stringExtraScanResult.object<jstring>());
    emit m_decoder->tagFound(scanResult.toString());
}
#endif

If you have the same problem, I hope that help


问:
how does SEO index pages with ajax loaded content
i'm a little confused about how search engines will treat this two cases:

i have a page "all articles" which has previews of recent articles( some text plus read more) and a page for each article, will this be considered as duplicate content by search engines?

when a search engine indexes a page does it index also the content on the page that is loaded via ajax? (in my case the page "all articles" load the previews of articles via ajax.

Thank you.

答:
For your first question, no it will not be treated as duplicate content, those are just previews.

For the second one , search engines DO index Ajax content if they are crawlable.

You can make sure they are crawlable by ensuring your site has theese tags:

https://developers.google.com/webmasters/ajax-crawling/docs/learn-more


问:
Delphi 5 component that will automatically add "db.pas" unit to uses clause?
I'm writing my own component, and I wish it to add "db" unit to the interface uses clause when ever I drop it on the form, since it has a published event like:

```<code>TMyDBEvent = procedure(Sender: TObject; DataSet: TDataSet) of object;
</code>```

TDataSet is declared in db.pas, and I need to add this unit manually, which I want to avoid.

I have seen this solution:

How are Delphi units automatically added when a component is added to a form?

And this:

Can I make a custom Delphi component add multiple units to the uses clause?

That use RegisterSelectionEditor, but Delphi 5 (I know...) seems to not have this unit.

What are my options?

答:
You can alias the type within your component's unit using an identical name:

```<code>type
  TDataSet = Db.TDataSet;
</code>```

Whenever you drop your component on a form, Delphi should add its unit to the uses clause. Then whether or not you use Db in that form, there's a valid TDataSet equivalent to the one from Db.

Could there be any side effects/implications/conflicts issues to such type aliasing?

From a language perspective, no.

Generally it's ill-advised to have types with the same name as this can cause problems when 2 pieces of code (sometimes even within the same unit) seem to use the same type, but they are actually different types internally. However, in this case the types are actually the same.

From an IDE perspective, not much.

A minor issue is that "Find Declaration" in the IDE will require an extra step to reach the underlying type.

The other issue is related to code completion. I have experienced that some versions of Delphi would occasionally struggle with code completion when this slightly unusual referencing technique <unit-name>.<type-name> is used. (I don't recall how (or even if) Delphi 5 was affected though.)

Are there any other known components that uses this trick?

I don't know of any components using the technique. But I've used aliasing for various reasons on quite a few occasions. Primarily just to avoid forcing knock-on dependencies on client units.

Body:
I'm writing my own component, and I wish it to add "db" unit to the interface uses clause when ever I drop it on the form, since it has a published event like:

TMyDBEvent = procedure(Sender: TObject; DataSet: TDataSet) of object;

TDataSet is declared in db.pas, and I need to add this unit manually, which I want to avoid.

I have seen this solution:

How are Delphi units automatically added when a component is added to a form?

And this:

Can I make a custom Delphi component add multiple units to the uses clause?

That use RegisterSelectionEditor, but Delphi 5 (I know...) seems to not have this unit.

What are my options?

Body:
You can alias the type within your component's unit using an identical name:

type
  TDataSet = Db.TDataSet;

Whenever you drop your component on a form, Delphi should add its unit to the uses clause. Then whether or not you use Db in that form, there's a valid TDataSet equivalent to the one from Db.

Could there be any side effects/implications/conflicts issues to such type aliasing?

From a language perspective, no.

Generally it's ill-advised to have types with the same name as this can cause problems when 2 pieces of code (sometimes even within the same unit) seem to use the same type, but they are actually different types internally. However, in this case the types are actually the same.

From an IDE perspective, not much.

A minor issue is that "Find Declaration" in the IDE will require an extra step to reach the underlying type.

The other issue is related to code completion. I have experienced that some versions of Delphi would occasionally struggle with code completion when this slightly unusual referencing technique <unit-name>.<type-name> is used. (I don't recall how (or even if) Delphi 5 was affected though.)

Are there any other known components that uses this trick?

I don't know of any components using the technique. But I've used aliasing for various reasons on quite a few occasions. Primarily just to avoid forcing knock-on dependencies on client units.


问:
How to obtain string date from xml and convert in a correct format in ax?
I am trying to obtain a date from an XML file that is in this format:

2016-10-27

however, the field I am trying to put it in is in this format:

mm/dd/yyyy

is there a code for this in dynamics ax 2012? I tried str2date but it doesn't output anything.

SOLVED: Just to let you guys know  even though you are obtaining a string that has a format like mine 2016-10-27 AX automatically formats it to the default format to 10/27/2016 just input the sequence correctly. (THIS IS NOT PART OF THE ANSWER I AM JUST EXPLAINING MY FINDINGS)

答: You will need to use str2date(string _date, int _sequence). Specify the related format in sequence. Your desired format will be 213</p>


问:
Hapi.js auth not working
This is my code now the problem here is when I am running this with hapi version 14.x.x or below it works for me perfectly fine but when I am running this with hapi version 15.0.1 or greater it gives me following error.

Is there any change in authentication process?

```<code>throw new Error(msgs.join(' ') || 'Unknown error');
    ^

    Error: Unknown authentication strategy UserAuth in /api/user/loginDetails
        at Object.exports.unique.exports.contain.exports.reachTemplate.exports.assert.condition [as assert] (F:\cbl\projects\lawn-mower\node_modules\hapi\node_modules\hoek\lib\index.js:736
    :11)
        at internals.Auth.test.internals.Auth._setupRoute (F:\cbl\projects\lawn-mower\node_modules\hapi\lib\auth.js:144:14)
</code>```

Sample route that I am using

```<code>  {
        method: 'POST',
        path: '/api/user/loginDetails',
        config: {
            auth: 'UserAuth',
            handler: function (request, reply) {
            },
            validate: {
                payload: {

                },
                headers: UniversalFunctions.authorizationHeaderObj,
                failAction: UniversalFunctions.failActionFunction
            },
            plugins: {
                'hapi-swagger': {
                    payloadType : 'form',
                    responses:Config.APP_CONSTANTS.swaggerDefaultResponseMessages
                }
            }
        }
    }
</code>```

strategy I am using

```<code>server.register(require('hapi-auth-bearer-token'), function (err) {
    console.log("aaaaa");
    server.auth.strategy('UserAuth', 'bearer-access-token', {
        allowQueryToken: false,
        allowMultipleHeaders: true,
        accessTokenName: 'accessToken',
        validateFunc: function (token, callback) {

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

答:
You have only defined strategy, not scheme. So define your scheme like below code .

You should try this:

```<code> var userFunc=function (server, options) {
     return {
        authenticate: function (request, reply) {
            console.log('UserAuth');
            return reply.continue({ credentials: { user: 'UserAuth'        } });
        }
    };
};

  server.auth.scheme('UserAuthScheme', userFunc);      // here
  server.auth.strategy('UserAuth', 'UserAuthScheme');  // here

  server.route([{
          method: 'POST',
          path: '/api/user/loginDetails',
          config: {
            auth: 'UserAuth',
            handler: function (request, reply) {
              reply('/api/user/loginDetails');
            },
            validate: {
              payload: {

              },
              headers: UniversalFunctions.authorizationHeaderObj,
              failAction: UniversalFunctions.failActionFunction
            },
            plugins: {
              'hapi-swagger': {
                payloadType: 'form',
                responses: Config.APP_CONSTANTS.swaggerDefaultResponseMessages
              }
            }
          }
        }]);
</code>```

Title: Hapi.js auth not working

Body:
This is my code now the problem here is when I am running this with hapi version 14.x.x or below it works for me perfectly fine but when I am running this with hapi version 15.0.1 or greater it gives me following error.

Is there any change in authentication process?

throw new Error(msgs.join(' ') || 'Unknown error');
    ^

    Error: Unknown authentication strategy UserAuth in /api/user/loginDetails
        at Object.exports.unique.exports.contain.exports.reachTemplate.exports.assert.condition [as assert] (F:\cbl\projects\lawn-mower\node_modules\hapi\node_modules\hoek\lib\index.js:736
    :11)
        at internals.Auth.test.internals.Auth._setupRoute (F:\cbl\projects\lawn-mower\node_modules\hapi\lib\auth.js:144:14)

Sample route that I am using

  {
        method: 'POST',
        path: '/api/user/loginDetails',
        config: {
            auth: 'UserAuth',
            handler: function (request, reply) {
            },
            validate: {
                payload: {

                },
                headers: UniversalFunctions.authorizationHeaderObj,
                failAction: UniversalFunctions.failActionFunction
            },
            plugins: {
                'hapi-swagger': {
                    payloadType : 'form',
                    responses:Config.APP_CONSTANTS.swaggerDefaultResponseMessages
                }
            }
        }
    }

strategy I am using

server.register(require('hapi-auth-bearer-token'), function (err) {
    console.log("aaaaa");
    server.auth.strategy('UserAuth', 'bearer-access-token', {
        allowQueryToken: false,
        allowMultipleHeaders: true,
        accessTokenName: 'accessToken',
        validateFunc: function (token, callback) {

        }
    });
});

Body:
You have only defined strategy, not scheme. So define your scheme like below code .

You should try this:

 var userFunc=function (server, options) {
     return {
        authenticate: function (request, reply) {
            console.log('UserAuth');
            return reply.continue({ credentials: { user: 'UserAuth'        } });
        }
    };
};

  server.auth.scheme('UserAuthScheme', userFunc);      // here
  server.auth.strategy('UserAuth', 'UserAuthScheme');  // here

  server.route([{
          method: 'POST',
          path: '/api/user/loginDetails',
          config: {
            auth: 'UserAuth',
            handler: function (request, reply) {
              reply('/api/user/loginDetails');
            },
            validate: {
              payload: {

              },
              headers: UniversalFunctions.authorizationHeaderObj,
              failAction: UniversalFunctions.failActionFunction
            },
            plugins: {
              'hapi-swagger': {
                payloadType: 'form',
                responses: Config.APP_CONSTANTS.swaggerDefaultResponseMessages
              }
            }
          }
        }]);


问:
Mapping through an array of objects in javascript
i have an array of objects like this:

```<code>[{side: Buy, price: 100}, {side: Buy, price: 110}, {side: Sell, price: 200}, {side: Buy, price: 150} ]
</code>```

Now i want to calculate for this array the total sum of the Buy and Sell side and for each side the average sum of the prices. To be more specific i want my output to be something like this:
Buy = 3  AvgPrice for Buy = 120
Sell = 1 AvgPrice for Sell = 200
I'm new to javascript and react so i have some difficulties. Thanks !:)

答:
Probably easiest to just iterate the array and keep a rolling average for each side.

```<code>var data = [{side: 'Buy', price: 100}, {side: 'Buy', price: 110}, {side: 'Sell', price: 200}, {side: 'Buy', price: 150} ];

var tally = { Buy: { count: 0, total: 0 }, Sell: { count: 0, total: 0 } };

data.forEach(item => {
    tally[item.side].count = tally[item.side].count + 1;
    tally[item.side].total = tally[item.side].total + item.price;
})

console.log("AvgPrice for Buy = " + (tally.Buy.total / tall.Buy.count) + " Sell = 1 AvgPrice for Sell = " + (tally.Sell.total / tall.Sell.count));
</code>```

Body:
i have an array of objects like this:

[{side: Buy, price: 100}, {side: Buy, price: 110}, {side: Sell, price: 200}, {side: Buy, price: 150} ]

Now i want to calculate for this array the total sum of the Buy and Sell side and for each side the average sum of the prices. To be more specific i want my output to be something like this:
Buy = 3  AvgPrice for Buy = 120
Sell = 1 AvgPrice for Sell = 200
I'm new to javascript and react so i have some difficulties. Thanks !:)

Body:
Probably easiest to just iterate the array and keep a rolling average for each side.

var data = [{side: 'Buy', price: 100}, {side: 'Buy', price: 110}, {side: 'Sell', price: 200}, {side: 'Buy', price: 150} ];

var tally = { Buy: { count: 0, total: 0 }, Sell: { count: 0, total: 0 } };

data.forEach(item => {
    tally[item.side].count = tally[item.side].count + 1;
    tally[item.side].total = tally[item.side].total + item.price;
})

console.log("AvgPrice for Buy = " + (tally.Buy.total / tall.Buy.count) + " Sell = 1 AvgPrice for Sell = " + (tally.Sell.total / tall.Sell.count));


问:
SQL Novice - subquery
Hi everybody this is my first question so go easy on me - need some help in extracting some data.

These are the two tables I am working with:
Enquiries table:

```<code>+---------------------------------------------------------------------+
| ID (Primary Key) | Author | threadid | created     | Comments       |
+---------------------------------------------------------------------+
| 1                |   C    | 237      | 2016-07-24  | Hi there...    |
| 2                |   T    | 421      | 2015-06-07  | Hello, ..      |
| 3                |   C    | 421      | 2015-06-08  | Hi,...         |
| 4                |   C    | 327      | 2017-03-13  | Hey there..    |
+---------------------------------------------------------------------+
</code>```

Where T stands for company sending an enquiry to a customer and C if a customer sends an enquiry to the company.

Enquirythreads Table:

```<code>+----------------------------------+
| ID (Primary Key) |  created      |
+----------------------------------+
| 421              | 2016-07-24    |
| 237              | 2016-07-24    |
| 327              | 2015-06-08    |
+----------------------------------+
</code>```

The output I would like is:

```<code>+---------+
| ID      |
+---------+
|  421    |
+---------+
</code>```

I want all the enquirythread ids such that the first enquiry associated with it is made by author T.

This is my code but isn't working:

```<code>SELECT enquirythreads.id
FROM enquirythreads
JOIN enquiries on enquirythreads.id = enquiries.threadid
WHERE enquiries.threadid IN
    ( SELECT enquiries.threadid as enqid
      FROM
            ( SELECT enquiries.threadid, min(enquiries.created) as mincreated
            FROM enquiries
            WHERE enquiries.author = 'T'
            GROUP BY enquiries.threadid ) x

     )
</code>```

答:
One method uses aggregation and having:

```<code>select e.threadid
from enquiries e
group by e.threadid
having min(e.created) = min(case when e.author = 'T' then e.created end)
</code>```

This says:  "check that the earliest created date is the same as the earliest date for 'T'".

Another method uses a correlated subquery in the where clause:

```<code>select et.threadid
from enquirythreads et
where (select e2.author
       from enquiries e2
       where e2.threadid = et.threadid
       order by e2.created asc
       fetch first 1 row only
      ) = 'T';
</code>```

ContentLicense: CC BY-SA 4.0

Title: SQL Novice - subquery

Body:
Hi everybody this is my first question so go easy on me - need some help in extracting some data.

These are the two tables I am working with:
Enquiries table:

+---------------------------------------------------------------------+
| ID (Primary Key) | Author | threadid | created     | Comments       |
+---------------------------------------------------------------------+
| 1                |   C    | 237      | 2016-07-24  | Hi there...    |
| 2                |   T    | 421      | 2015-06-07  | Hello, ..      |
| 3                |   C    | 421      | 2015-06-08  | Hi,...         |
| 4                |   C    | 327      | 2017-03-13  | Hey there..    |
+---------------------------------------------------------------------+

Where T stands for company sending an enquiry to a customer and C if a customer sends an enquiry to the company.

Enquirythreads Table:

+----------------------------------+
| ID (Primary Key) |  created      |
+----------------------------------+
| 421              | 2016-07-24    |
| 237              | 2016-07-24    |
| 327              | 2015-06-08    |
+----------------------------------+

The output I would like is:

+---------+
| ID      |
+---------+
|  421    |
+---------+

I want all the enquirythread ids such that the first enquiry associated with it is made by author T.

This is my code but isn't working:

SELECT enquirythreads.id
FROM enquirythreads
JOIN enquiries on enquirythreads.id = enquiries.threadid
WHERE enquiries.threadid IN
    ( SELECT enquiries.threadid as enqid
      FROM
            ( SELECT enquiries.threadid, min(enquiries.created) as mincreated
            FROM enquiries
            WHERE enquiries.author = 'T'
            GROUP BY enquiries.threadid ) x

     )

Body:
One method uses aggregation and having:

select e.threadid
from enquiries e
group by e.threadid
having min(e.created) = min(case when e.author = 'T' then e.created end)

This says:  "check that the earliest created date is the same as the earliest date for 'T'".

Another method uses a correlated subquery in the where clause:

select et.threadid
from enquirythreads et
where (select e2.author
       from enquiries e2
       where e2.threadid = et.threadid
       order by e2.created asc
       fetch first 1 row only
      ) = 'T';


问:
No package called rodbc
I am using R Studio where I have installed RODBC successfully as it works fine when I run a .r script. However, when I use the very same code in an .Rmd file I get an error saying

Error in library("rodbc") : there is no package called 'rodbc'
  Calls:  ... withCallingHandlers -> withVisible -> eval -> eval -> library"

答:
Please note that R is case sensitive. You have written in lowercase thats the reason you are getting error.

You can write like:

```<code>library("RODBC")
</code>```

or

```<code>library(RODBC)
</code>```

Title: No package called rodbc

Body:
Please note that R is case sensitive. You have written in lowercase thats the reason you are getting error.

You can write like:

library("RODBC")

or

library(RODBC)


问:
Concatenate StringVector with Rcpp
I can not figure out how to concatenate 2 strings with Rcpp; and the documentation did not help me while I suspect there is an obvious answer.

http://gallery.rcpp.org/articles/working-with-Rcpp-StringVector/

http://gallery.rcpp.org/articles/strings_with_rcpp/

```<code>StringVector concatenate(StringVector a, StringVector b)
{
 StringVector c;
 c= ??;
 return c;
}
</code>```

I would expect this output :

```<code>a=c("a","b"); b=c("c","d");
concatenate(a,b)
[1] "ac" "bd"
</code>```

答:
There are probably a few different ways to approach this, but here's one option with std::transform:

#include <Rcpp.h>
using namespace Rcpp;

struct Functor {
    std::string
    operator()(const std::string& lhs, const internal::string_proxy<STRSXP>& rhs) const
    {
        return lhs + rhs;
    }
};

// [[Rcpp::export]]
CharacterVector paste2(CharacterVector lhs, CharacterVector rhs)
{
    std::vector<std::string> res(lhs.begin(), lhs.end());
    std::transform(
        res.begin(), res.end(),
        rhs.begin(), res.begin(),
        Functor()
    );
    return wrap(res);
}

/*** R

lhs <- letters[1:2]; rhs <- letters[3:4]

paste(lhs, rhs, sep = "")
# [1] "ac" "bd"

paste2(lhs, rhs)
# [1] "ac" "bd"

*/
```

<hr>

<p>The reason for first copying the left hand expression into a <code>std::vector<std::string></code> is that the <code>internal::string_proxy<></code> class  provides <code>operator+</code> with the signature </p>

<pre class="lang-cpp prettyprint-override"><code>std::string operator+(const std::string& x, const internal::string_proxy<STRSXP>& y)
</code>```

rather than, e.g.

operator+(const internal::string_proxy<STRSXP>& x, const internal::string_proxy<STRSXP>& y)
```

<hr>

<p>If your compiler supports C++11, this can be done slightly cleaner: </p>

<pre class="lang-cpp prettyprint-override"><code>// [[Rcpp::plugins(cpp11)]]
#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
CharacterVector paste3(CharacterVector lhs, CharacterVector rhs)
{
    using proxy_t = internal::string_proxy<STRSXP>;

    std::vector<std::string> res(lhs.begin(), lhs.end());
    std::transform(res.begin(), res.end(), rhs.begin(), res.begin(),
        [&](const std::string& x, const proxy_t& y) {
            return x + y;
        }
    );

    return wrap(res);
}

/*** R

lhs <- letters[1:2]; rhs <- letters[3:4]

paste(lhs, rhs, sep = "")
# [1] "ac" "bd"

paste3(lhs, rhs)
# [1] "ac" "bd"

*/
</code>```

Title: Concatenate StringVector with Rcpp

Body:
I can not figure out how to concatenate 2 strings with Rcpp; and the documentation did not help me while I suspect there is an obvious answer.

http://gallery.rcpp.org/articles/working-with-Rcpp-StringVector/

http://gallery.rcpp.org/articles/strings_with_rcpp/

StringVector concatenate(StringVector a, StringVector b)
{
 StringVector c;
 c= ??;
 return c;
}

I would expect this output :

a=c("a","b"); b=c("c","d");
concatenate(a,b)
[1] "ac" "bd"

Body:
There are probably a few different ways to approach this, but here's one option with std::transform:

#include <Rcpp.h>
using namespace Rcpp;

struct Functor {
    std::string
    operator()(const std::string& lhs, const internal::string_proxy<STRSXP>& rhs) const
    {
        return lhs + rhs;
    }
};

// [[Rcpp::export]]
CharacterVector paste2(CharacterVector lhs, CharacterVector rhs)
{
    std::vector<std::string> res(lhs.begin(), lhs.end());
    std::transform(
        res.begin(), res.end(),
        rhs.begin(), res.begin(),
        Functor()
    );
    return wrap(res);
}

/*** R

lhs <- letters[1:2]; rhs <- letters[3:4]

paste(lhs, rhs, sep = "")
# [1] "ac" "bd"

paste2(lhs, rhs)
# [1] "ac" "bd"

*/

The reason for first copying the left hand expression into a std::vector<std::string> is that the internal::string_proxy<> class  provides operator+ with the signature

std::string operator+(const std::string& x, const internal::string_proxy<STRSXP>& y)

rather than, e.g.

operator+(const internal::string_proxy<STRSXP>& x, const internal::string_proxy<STRSXP>& y)

If your compiler supports C++11, this can be done slightly cleaner:

// [[Rcpp::plugins(cpp11)]]
#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
CharacterVector paste3(CharacterVector lhs, CharacterVector rhs)
{
    using proxy_t = internal::string_proxy<STRSXP>;

    std::vector<std::string> res(lhs.begin(), lhs.end());
    std::transform(res.begin(), res.end(), rhs.begin(), res.begin(),
        [&](const std::string& x, const proxy_t& y) {
            return x + y;
        }
    );

    return wrap(res);
}

/*** R

lhs <- letters[1:2]; rhs <- letters[3:4]

paste(lhs, rhs, sep = "")
# [1] "ac" "bd"

paste3(lhs, rhs)
# [1] "ac" "bd"

*/


问:
Nat Punchthrough understanding P2P concept
So, i have been reading up on NAT-Punchthrough. I seem to be getting the idea, but i have a hard time implementing it, and i feel that i am missing a step here.
Testing this functionality is kind of hard because i have little control over the environment when it comes to a internet based connection.

I have a SQL server to run as my "facilitator" it keeps the external address of both server and client, and their port as seen by the outside.

Here are steps so far:
 - I connect to my SQL server through a web request (PHP script) that stores server/client IP/PORT
 - When both are known, both client and server attempt connecting (server hosts on a set port, client connects over a set port)
 - Nothing significant happens

There are 2 unknowns here, and i would like to check one with you.
Is it true that NAT-Punchthrough requires that i do the first step with the exact (internal/LAN) port i plan to connect with in the step after that?

If so, i don't know how exactly my server works underwater, so it might need more ports then my initial given static port to connect over, but that at least gives me a hint.

If anyone has more documentation on this then me, please let me know.

Sources:

Programming P2P application

http://www.mindcontrol.org/~hplus/nat-punch.html

答:
NAT punch through works on the principle of educated guesswork. It is usually used to create connections with devices that do IP Masquerading. This is the technology used in most home internet modems to the point that NAT has become interchangeably used to refer to IP Masquerading.

When you connect out from a device which is behind a NAT system like a home modem. You have no control of the port that will be used for the outbound connection to the Internet. However many of these devices allocate ports using specific patterns. For example, incremental numbers.

NAT punch through involves trying to directly connect two source systems that are both behind independent NAT devices. A third system, your "facilitator" acts as a detector for the origin port numbers currently being assigned by both NAT devices on outbound connections. The origin port number, along with the IP address is then sent to the other parties.

So now the clever bit to answer your question. Both systems that want to directly connect, start trying to communicate to the other. They try connecting to a range of ports, around the known port number detected by the facilitator. This is the guesswork.

It is important that both source systems start trying to connect as this will establish NAT sessions in the local devices that allow traffic from the Internet in. If either source device correctly guesses one of those NAT session port numbers, then a connection is established.

In reality, engineers from organisations that have use for NAT punch through have probably spent some time examining the more popular NAT port allocation algorithms and tuning their software. If you have control of connections through your NAT devices, then it would be fairly easy to set up some tests and see how the port numbers change between connections to different servers.


问:
How to bind data from ajax to chosen jquery?
I have used chosen jquery from

```<code>https://github.com/harvesthq/chosen/releases
</code>```

I binding data from ajax webservices , seem it's not working.Data not load in select.

  $(".cb_bu_info").chosen({
                no_results_text: "Oops, nothing found!",
                width: "50%",
                source: function () {
                    $.ajax({
                        type: "POST",
                        url: "../BUS/WebService.asmx/LIST_BU",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        //beforeSend: function () { $('ul.cb_bu_info').empty(); },
                        success: function (data) {
                            $("#cb_bu_info").html('');
                            $.each($.parseJSON(data.d), function (idx, obj) {
                                $("#cb_bu_info").append('<option value="' + obj.BU_ID + '">' + obj.BU_NAME + '</option>');
                            });
                        },
                        error: function (data) {
                            console.log(data.d);
                            alert("An error occurred !");
                        }
                    });
                }
            });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select class="cb_bu_info"></select></code>```

Thank guys.

答:
You can use this example once the page loads, then load it with countries in select list.

Make sure you have added references.

```<code><select id='CountryName'>
<option> </option>
</select>
</code>```

```<code>$(document).ready(function () {
    var frontDropdown = "";
    $.ajax({
        url: baseUrl + "GetBPCountriesCombo",
        type: "GET",
        async: true,
        success: function (result) {
            frontDropdown += "<option value='null'> Select Country </option>";
            $.each(result, function (i, data) {
                frontDropdown += "<option " + " value=" + data.CountryId + ">" + data.CountryName + "</option>";
            })
            $('#CountryName').append(frontDropdown).trigger('chosen:updated').css("width", "auto");;
        },
        error: function () {
            alert("An error occurred !");
        }
    });
});
</code>```

Body:
I have used chosen jquery from

https://github.com/harvesthq/chosen/releases

I binding data from ajax webservices , seem it's not working.Data not load in select.

  $(".cb_bu_info").chosen({
                no_results_text: "Oops, nothing found!",
                width: "50%",
                source: function () {
                    $.ajax({
                        type: "POST",
                        url: "../BUS/WebService.asmx/LIST_BU",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        //beforeSend: function () { $('ul.cb_bu_info').empty(); },
                        success: function (data) {
                            $("#cb_bu_info").html('');
                            $.each($.parseJSON(data.d), function (idx, obj) {
                                $("#cb_bu_info").append('<option value="' + obj.BU_ID + '">' + obj.BU_NAME + '</option>');
                            });
                        },
                        error: function (data) {
                            console.log(data.d);
                            alert("An error occurred !");
                        }
                    });
                }
            });

<select class="cb_bu_info"></select>

Thank guys.

Body:
You can use this example once the page loads, then load it with countries in select list.

Make sure you have added references.

<select id='CountryName'>
<option> </option>
</select>

$(document).ready(function () {
    var frontDropdown = "";
    $.ajax({
        url: baseUrl + "GetBPCountriesCombo",
        type: "GET",
        async: true,
        success: function (result) {
            frontDropdown += "<option value='null'> Select Country </option>";
            $.each(result, function (i, data) {
                frontDropdown += "<option " + " value=" + data.CountryId + ">" + data.CountryName + "</option>";
            })
            $('#CountryName').append(frontDropdown).trigger('chosen:updated').css("width", "auto");;
        },
        error: function () {
            alert("An error occurred !");
        }
    });
});


问:
How to find a functions address to hook/detour in an EXE file?
I drove against a wall again and need your help with some low-level stuff. I already succeeded in hooking exported DLL-Functions (with this code btw.) by injecting them into my target process (e.g. I can easily detour MessageBoxW from user32.dll). Unfortunately I aim for a different scenario: I have to detour a function defined inside the executable I'm injecting my code into. The application is Open-Source so I know everything about the function I'd need for hooking it, but the binary is signed with a certificate so I can not compile my own version. Is it possible to fetch the functions' address at runtime or detour it with another technique? The target is a "normal" 32bit Windows binary btw. nothing special I thought ;)

Yours,
Nefarius

EDIT: maybe due to my lame English I was not detailed enough, so here a little sample code:

```<code>int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd )
{
    foo();
}

BOOL foo(char* someData)
{
    return printf("%s", someData);
}
</code>```

Now I want to detour the function foo() which does not exist in a dynamic library. This is my problem. I don't know how and I'm not sure if this works like I think it does.

EDIT: Now I know it is possible, so the important question changed to: how? How do I get the information I need; the functions address?

答: If this is for something that is more than a one time debugging jaunt, look into Microsoft Detours, an API for hooking functions.</p>

Body:
I drove against a wall again and need your help with some low-level stuff. I already succeeded in hooking exported DLL-Functions (with this code btw.) by injecting them into my target process (e.g. I can easily detour MessageBoxW from user32.dll). Unfortunately I aim for a different scenario: I have to detour a function defined inside the executable I'm injecting my code into. The application is Open-Source so I know everything about the function I'd need for hooking it, but the binary is signed with a certificate so I can not compile my own version. Is it possible to fetch the functions' address at runtime or detour it with another technique? The target is a "normal" 32bit Windows binary btw. nothing special I thought ;)

Yours,
Nefarius

EDIT: maybe due to my lame English I was not detailed enough, so here a little sample code:

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd )
{
    foo();
}

BOOL foo(char* someData)
{
    return printf("%s", someData);
}

Now I want to detour the function foo() which does not exist in a dynamic library. This is my problem. I don't know how and I'm not sure if this works like I think it does.

EDIT: Now I know it is possible, so the important question changed to: how? How do I get the information I need; the functions address?


问:
How to secure HTTPS on Django using Pythonanywhere?
I'd like to be able to have a securee site (https) with the green padlock. I followed this tutorial from pythonanywhere's help center a month ago, https://help.pythonanywhere.com/pages/LetsEncrypt/ and I set up everything correctly :

```<code>git clone https://github.com/lukas2511/dehydrated.git ~/dehydrated
mkdir -p ~/letsencrypt/wellknown
cd ~/letsencrypt
WELLKNOWN=/home/YOURUSERNAME/letsencrypt/wellknown
~/dehydrated/dehydrated --cron --domain www.yourdomain.com --out . --challenge http-01
</code>```

The problem is that when I enter my site using https I get a message and cannot access my site since Google warns me of the risk of the site. I tried to use www.whynopadlock.com to find what was wrong and here is what it gives :

SSL verification issue (Possibly mis-matched URL or bad intermediate cert.). Details:
  ERROR: no certificate subject alternative name matches SSL verification issue (Possibly mis-matched URL or bad intermediate cert.). Details:
  ERROR: no certificate subject alternative name matches.

Have anyone set up an HTTPS using Pythonanywhere ? What are the steps to set up correctly so the green padlock is there.

答: It looks like you missed out the last step on the instructions: "To get your certificate installed email support@pythonanywhere.com to let us know that you want us to install your certificate. Include your username, the directory path to the certificates, and the domain name and we'll do the rest." </p>

Body:
I'd like to be able to have a securee site (https) with the green padlock. I followed this tutorial from pythonanywhere's help center a month ago, https://help.pythonanywhere.com/pages/LetsEncrypt/ and I set up everything correctly :

git clone https://github.com/lukas2511/dehydrated.git ~/dehydrated
mkdir -p ~/letsencrypt/wellknown
cd ~/letsencrypt
WELLKNOWN=/home/YOURUSERNAME/letsencrypt/wellknown
~/dehydrated/dehydrated --cron --domain www.yourdomain.com --out . --challenge http-01

The problem is that when I enter my site using https I get a message and cannot access my site since Google warns me of the risk of the site. I tried to use www.whynopadlock.com to find what was wrong and here is what it gives :

SSL verification issue (Possibly mis-matched URL or bad intermediate cert.). Details:
  ERROR: no certificate subject alternative name matches SSL verification issue (Possibly mis-matched URL or bad intermediate cert.). Details:
  ERROR: no certificate subject alternative name matches.

Have anyone set up an HTTPS using Pythonanywhere ? What are the steps to set up correctly so the green padlock is there.


问:
Prevent form subscription in ReactJS input element
I have an HTML form in my project, which is partially written with React (Don't ask me why. Historical issues.) Consider it to look like this:

<form>
<input type="text" name="name" />

</form>

```

<p>Then the react code, effectively like this:</p>

<pre class="lang-javascript prettyprint-override"><code>ReactDOM.render(
  <div>
    <input type="text" />
  </div>,
  app // consider this is the #app element
);
</code>```

How can I stop the form from submitting with "enter" key by just changing the input element in my React component? Or is it possible?

答: Put an onKeydown handler on the input accepting the event parameter as e and, in the handler, if e.which is 13, call e.preventDefault to prevent the default action.

Body:
I have an HTML form in my project, which is partially written with React (Don't ask me why. Historical issues.) Consider it to look like this:

<form>
<input type="text" name="name" />

</form>

Then the react code, effectively like this:

ReactDOM.render(

    <input type="text" />

,
  app // consider this is the #app element
);

How can I stop the form from submitting with "enter" key by just changing the input element in my React component? Or is it possible?


问:
C# class parameter
```<code> namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            A a = new A();
            B b = new B(a);
            C c = new C(a);

            Console.WriteLine(a.intval + " " +a.strval);
            Console.ReadLine();
        }
    }

    class A
    {
        public int intval { get; set; }
        public string strval { get; set; }
    }
    class B
    {
        public A _a;
        public B(A a)
        {
            _a = a;
            _a.intval += 100;
            _a.strval += "From B;";
        }
    }
    class C
    {
        A _a;
        public C(A a)
        {
            _a = a;
            _a.intval += 1000;
            _a.strval += "From C;";
        }
    }
}
</code>```

In above code, why the instance "b" and “c” could set value to instance "a"?

In my guess, the Class B and C have their own variables "a", when we call "B b = new B(a);" or "C c = new C(a);", the value should be changed on their own fields and the variable "a" in Main would be impacted?

But, i'm wrong. Could you please help me understand the result? Thank you very much.

答:
You create the object of class A as -

```<code> A a = new A();
</code>```

mean you have allocated a memory block that can be referenced as instance a and now you are passing same memory block address(a) to both class B and C.

```<code> B b = new B(a);
 C c = new C(a);
</code>```

mean here now both memory block b and memory block c points to the same memory block a, so either instance b or c change the value it will be reflected in same memory block allocated to instance a and then you are trying to get the value from instance a, so you will have updated value by both B and C

Title: C# class parameter

Body:
 namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            A a = new A();
            B b = new B(a);
            C c = new C(a);

            Console.WriteLine(a.intval + " " +a.strval);
            Console.ReadLine();
        }
    }

    class A
    {
        public int intval { get; set; }
        public string strval { get; set; }
    }
    class B
    {
        public A _a;
        public B(A a)
        {
            _a = a;
            _a.intval += 100;
            _a.strval += "From B;";
        }
    }
    class C
    {
        A _a;
        public C(A a)
        {
            _a = a;
            _a.intval += 1000;
            _a.strval += "From C;";
        }
    }
}

In above code, why the instance "b" and “c” could set value to instance "a"?

In my guess, the Class B and C have their own variables "a", when we call "B b = new B(a);" or "C c = new C(a);", the value should be changed on their own fields and the variable "a" in Main would be impacted?

But, i'm wrong. Could you please help me understand the result? Thank you very much.

Body:
You create the object of class A as -

 A a = new A();

mean you have allocated a memory block that can be referenced as instance a and now you are passing same memory block address(a) to both class B and C.

 B b = new B(a);
 C c = new C(a);

mean here now both memory block b and memory block c points to the same memory block a, so either instance b or c change the value it will be reflected in same memory block allocated to instance a and then you are trying to get the value from instance a, so you will have updated value by both B and C


问:
SUMIFs in Google sheets with 2 filters on same criteria range
I have looked at various answers but all use filters on different columns. I need an OR type filter like this:

=SUMIFs(B2:B22,C2:C22,"Incurred",C2:C22,"Expected")

Where C2:C22 specifies if the cell in B is an incurred or expected or deferred expense.

How do I do this? Note the filters are on the same set of cells in column C.

答:
You may try this...</p>

```<code>=SUMPRODUCT(((C2:C22="Incurred")+(C2:C22="Expected")+(C2:C22="Deferred"))*B2:B22)
</code>```

Body:
You may try this...

=SUMPRODUCT(((C2:C22="Incurred")+(C2:C22="Expected")+(C2:C22="Deferred"))*B2:B22)


问:
condition to button for members and visitors
how can i add a condition to a button ? for visitors it will be LOGIN for logged in it will be changed to LOGOUT

another button will appear if member log in and disappear if he logged out

its a wordpress website and iam newbie in coding so please clarify where to put the code exactly

iam using button plugin for this button and i will put these buttons in the header area (above the navigation menu)
enter image description here

答:
For LOGGED in user you will maintain some flag either in session or cookies.
If this flag is set show the button as "Logout" & write the logout functionality on click of the button, & if flag is "OFF" then show "Login" button </p>


问:
Jenkins "Console Output" log location in filesystem
I want to access and grep Jenkins Console Output as a post build step in the same job that creates this output. Redirecting logs with >> log.txt is not a solution since this is not supported by my build steps.

Build:

```<code>echo "This is log"
</code>```

Post build step:

```<code>grep "is" path/to/console_output
</code>```

Where is the specific log file created in filesystem?

答:
I found the console output of my job in the browser at the following location:

http://[Jenkins URL]/job/[Job Name]/default/[Build Number]/console

Body:
I want to access and grep Jenkins Console Output as a post build step in the same job that creates this output. Redirecting logs with >> log.txt is not a solution since this is not supported by my build steps.

Build:

echo "This is log"

Post build step:

grep "is" path/to/console_output

Where is the specific log file created in filesystem?


问:
What is the difference between arrayListOf and mutableListOf , which one is better?
I am trying to use collections in Kotlin and got confused between arrayListOf and mutableListOf, which one should we use and why?</p>

答:
Either is fine, the only difference between calling the two is expressing your intent.

ArrayList is a concrete implementation of MutableList, and mutableListOf, as of Kotlin 1.1, also returns an ArrayList.

Do you know you specifically want an ArrayList because you have made the conscious decision that this is the right choice for your application? You probably want arrayListOf (or a direct call to the ArrayList constructor, if that interface works better for you).

Do you just want a MutableList of some sort, and are fine with getting whatever the implementation defines as the right choice? Just use mutableListOf instead.


问:
Laravel 5.2 Validation Error not appearing in blade
I want to show validation Error in View page while user giving wrong input. It's Ok that it's not saving anything in database while a user giving wrong input. But there is no error message in user view page. If anyone find the error, please help me out.

Here is the controller:

```<code>public function saveUser(Request $request){
        $this->validate($request,[
            'name' => 'required|max:120',
            'email' => 'required|email|unique:users',
            'phone' => 'required|min:11|numeric',
            'course_id'=>'required'
            ]);

        $user = new User();
        $user->name=  $request->Input(['name']);
        $user->email=  $request->Input(['email']);
        $user->phone=  $request->Input(['phone']);
        $user->date = date('Y-m-d');
        $user->completed_status = '0';
        $user->course_id=$request->Input(['course_id']);
        $user->save();
       return redirect('success');
    }
</code>```

Here is the route:

```<code>Route::group(['middleware' => 'web'], function () {

    Route::get('/', function () {
        return view('index');
    })->name('main');

      Route::post('/saveUser',[
        'uses' => 'AppController@saveUser',
        'as'=>'saveUser',
        ]);
    });
</code>```

Here is the blade view page:

```<code>@extends('layouts.master')
@section('title')
Create User
@endsection
@section('content')
@include('partials.message-block')
        <div class="container" >

            <h3> Student Register </h3>

        {!! Form::open(array('route' => 'saveUser','class'=>'form-horizontal','method'=>'POST'))  !!}
      {!! Form::token(); !!}
      {!!   csrf_field() ; !!}

        <div class="form-group">
          <label>Name</label>
          <input type="text" name="name" class="form-control" required placeholder="Name">
        </div>

        <div class="form-group">
          <label>Email</label>
          <input type="email" name="email" class="form-control" required placeholder="email">
        </div>

        <div class="form-group">
          <label>Phone Number</label>
          <input type="text" name="phone" class="form-control" required placeholder="phone">
        </div>

        <div class="form-group">
            <label for="">Class</label>
            <select class="form-control input-sm" name="course_id" >
            @foreach($input as $row)
            <option value="{{$row->id}}">{{$row->name}}</option>
            @endforeach
            </select>
        </div>

        <button type="submit" class="btn btn-default">Submit</button>
    {!! Form::close() !!}
        </div>

@endsection
</code>```

And here is the error-message block:

```<code>@if(count($errors) > 0)
    <div class="row">
        <div class="col-md-4 col-md-offset-4 error">
            <ul>
                @foreach($errors->all() as $error)
                    <li>{{$error}}</li>
                @endforeach
            </ul>
        </div>
    </div>
@endif
@if(Session::has('message'))
<div class="row">
    <div class="col-md-4 col-md--offset-4 success">
        {{Session::get('message')}}
    </div>
</div>

@endif
</code>```

答:
Use Below line in your controller

use Validator;

Add below code in your controller function where your request is sent.

```<code>$validator  =   Validator::make($request->all(), [
     'fname'     =>  'required|max:20|min:4',
     'uemail'    =>  'required|email',
     'message'   =>  'required',
 ]);
if ($validator->fails()) {
       $messages = $validator->messages();
       return Redirect::back()->withErrors($messages)->withInput($request->all());
 }
</code>```

In your view page

```<code> @if ($errors->any())
   <label for="fname" class="error">{{ $errors->first('fname') }}</label>
 @endif
</code>```

For display individual field wise error.

Body:
I want to show validation Error in View page while user giving wrong input. It's Ok that it's not saving anything in database while a user giving wrong input. But there is no error message in user view page. If anyone find the error, please help me out.

Here is the controller:

public function saveUser(Request $request){
        $this->validate($request,[
            'name' => 'required|max:120',
            'email' => 'required|email|unique:users',
            'phone' => 'required|min:11|numeric',
            'course_id'=>'required'
            ]);

        $user = new User();
        $user->name=  $request->Input(['name']);
        $user->email=  $request->Input(['email']);
        $user->phone=  $request->Input(['phone']);
        $user->date = date('Y-m-d');
        $user->completed_status = '0';
        $user->course_id=$request->Input(['course_id']);
        $user->save();
       return redirect('success');
    }

Here is the route:

Route::group(['middleware' => 'web'], function () {

    Route::get('/', function () {
        return view('index');
    })->name('main');

      Route::post('/saveUser',[
        'uses' => 'AppController@saveUser',
        'as'=>'saveUser',
        ]);
    });

Here is the blade view page:

@extends('layouts.master')
@section('title')
Create User
@endsection
@section('content')
@include('partials.message-block')

 Student Register

        {!! Form::open(array('route' => 'saveUser','class'=>'form-horizontal','method'=>'POST'))  !!}
      {!! Form::token(); !!}
      {!!   csrf_field() ; !!}

          Name
          <input type="text" name="name" class="form-control" required placeholder="Name">

          Email
          <input type="email" name="email" class="form-control" required placeholder="email">

          Phone Number
          <input type="text" name="phone" class="form-control" required placeholder="phone">

            Class
            <select class="form-control input-sm" name="course_id" >
            @foreach($input as $row)
            <option value="{{$row->id}}">{{$row->name}}</option>
            @endforeach
            </select>

        <button type="submit" class="btn btn-default">Submit</button>
    {!! Form::close() !!}

@endsection

And here is the error-message block:

@if(count($errors) > 0)

                @foreach($errors->all() as $error)

{{$error}}

                @endforeach

@endif
@if(Session::has('message'))

        {{Session::get('message')}}

@endif

Body:
Use Below line in your controller

use Validator;

Add below code in your controller function where your request is sent.

$validator  =   Validator::make($request->all(), [
     'fname'     =>  'required|max:20|min:4',
     'uemail'    =>  'required|email',
     'message'   =>  'required',
 ]);
if ($validator->fails()) {
       $messages = $validator->messages();
       return Redirect::back()->withErrors($messages)->withInput($request->all());
 }

In your view page

 @if ($errors->any())
   <label for="fname" class="error">{{ $errors->first('fname') }}</label>
 @endif

For display individual field wise error.


问:
Getting started with SableCC
I am a total beginner in programming and for school i have to make a little SableCC project. However im not sure how to use SableCC properly.

I have downloaded it from sablecc.org and i did what was said in the readme to install it.

So after installing with the java -jar lib/sablecc.jar command the console tells me how the usage works,
like for example

```<code>sablecc --license
</code>```

or to use

```<code>sablecc [-d destination]
</code>```

to where i want sablecc to work (i guess).

However, when i use anything from this list it just says:

Sablecc is not recognized as an internal or external command

What have i done wrong? Thanks!

答:
I followed also the instruction of [README.html][1] for ANT and it worked fine for me.

edit: I put some commands here in case the link is unavailable some time.

After downloading, follow the next steps:

Decompress the file sablecc-3.2.tar.gz or sablecc-3.2.zip:
tar -xzvf sablecc-3.2.tar.gz or jar -xvf sablecc-3.2.zip

Go to the created directory:
cd sablecc-3.2

You will find an executable sablecc.jar file in the lib directory:
java -jar lib/sablecc.jar

This is it.

If you have Ant installed on your system, you can install SableCC with the command:

```<code>ant -Dinstall.dir=destination install
</code>```

Title: Getting started with SableCC

Body:
I am a total beginner in programming and for school i have to make a little SableCC project. However im not sure how to use SableCC properly.

I have downloaded it from sablecc.org and i did what was said in the readme to install it.

So after installing with the java -jar lib/sablecc.jar command the console tells me how the usage works,
like for example

sablecc --license

or to use

sablecc [-d destination]

to where i want sablecc to work (i guess).

However, when i use anything from this list it just says:

Sablecc is not recognized as an internal or external command

What have i done wrong? Thanks!

Body:
I followed also the instruction of [README.html][1] for ANT and it worked fine for me.

edit: I put some commands here in case the link is unavailable some time.

After downloading, follow the next steps:

Decompress the file sablecc-3.2.tar.gz or sablecc-3.2.zip:
tar -xzvf sablecc-3.2.tar.gz or jar -xvf sablecc-3.2.zip

Go to the created directory:
cd sablecc-3.2

You will find an executable sablecc.jar file in the lib directory:
java -jar lib/sablecc.jar

This is it.

If you have Ant installed on your system, you can install SableCC with the command:

ant -Dinstall.dir=destination install


问:
CMake and slow MSVC compilation

CMake generate project for MSVC 10 (2010) and build time are relativly low, ie. after I click build for given project it start compiling in like seconds, which is expected.

For Qt Creator I choose CodeBlocks - NMake Makefiles as CMake generator, set build configuration to use the same target as above. When I click build I see

cmake --build . --target name

and silence for like 2 minutes. Then
Scanning dependencies for ...
 and 1,5 minutes more of silence.
To make things even worse - later compilation use only 1 thread. So compilation time is ... unacceptably long.

How should I configure project to achieve comparable, short compilation times as from under MSVC? I've tried Qt Creator 4.3 Beta and beside

答:
CMake per default does not multiprocessor builds. So its up to you to force it to...

You can specify the /MP flag when you configure your project with cmake.

cmake -G "<MSVC-Generator>" -DCMAKE_CXX_FLAGS="/MP" <target_dir>

I do this for all my cmake projects in the file CMakeLists.txt itself so the client does not have to:

```<code>if(MSVC)
 target_compile_options(<target> PRIVATE "/MP")
endif()
</code>```

Title: CMake and slow MSVC compilation

Body:
CMake per default does not multiprocessor builds. So its up to you to force it to...

You can specify the /MP flag when you configure your project with cmake.

cmake -G "<MSVC-Generator>" -DCMAKE_CXX_FLAGS="/MP" <target_dir>

I do this for all my cmake projects in the file CMakeLists.txt itself so the client does not have to:

if(MSVC)
 target_compile_options(<target> PRIVATE "/MP")
endif()


问:
How to split real-time video into image?
By using opencv on python. I recorded video and then split it into pictures but it took a long time so I want to split video into pictures immediately when I'm recording video. I found code on internet but it can capture only 1 pic.

```<code>import cv2

def main():
    cam = cv2.VideoCapture(0)
    frame = cam.read()[1]
    cv2.imwrite(filename='img%d.jpg',img=frame)

if __name__== '__main__':
    main()
</code>```

Can anyone help me? I'm very new with python and opencv.

答:
You didn't increase file name, so it get overwritten again and again. Also, you need a while loop. Try:

```<code>import cv2

def main():
    cam = cv2.VideoCapture(0)
    frameNum = 0
    isCaptured = True
    while True:
        isCapture, frame = cam.read()
        if not isCapture:
            # no more frame, exit loop
            break
        frameNum = frameNum + 1
        fileName = 'img{:d}.jpg'.format(frameNum)
        cv2.imwrite(filename=fileName,img=frame)

if __name__== '__main__':
    main()
</code>```

Body:
By using opencv on python. I recorded video and then split it into pictures but it took a long time so I want to split video into pictures immediately when I'm recording video. I found code on internet but it can capture only 1 pic.

import cv2

def main():
    cam = cv2.VideoCapture(0)
    frame = cam.read()[1]
    cv2.imwrite(filename='img%d.jpg',img=frame)

if __name__== '__main__':
    main()

Can anyone help me? I'm very new with python and opencv.

Body:
You didn't increase file name, so it get overwritten again and again. Also, you need a while loop. Try:

import cv2

def main():
    cam = cv2.VideoCapture(0)
    frameNum = 0
    isCaptured = True
    while True:
        isCapture, frame = cam.read()
        if not isCapture:
            # no more frame, exit loop
            break
        frameNum = frameNum + 1
        fileName = 'img{:d}.jpg'.format(frameNum)
        cv2.imwrite(filename=fileName,img=frame)

if __name__== '__main__':
    main()


问:
I want to retrieve pdf file display on web browser
I had created database with 2 fields filename and path
filename as dwm.pdf and path as C:\xampp\htdocs\p1\testing.
I just want to display pdf file on link click with the help of path store in database.

```<code><?php
$con = mysqli_connect("localhost","root","billa","pdf_trial") or die
("Couldn't connect");
echo "Connected";
$q = "SELECT path FROM pdffiles WHERE filename =dwm"
$r = mysqli_query($q);
$row = mysqli_fetch_assoc($r);
header('Content-type: application/pdf');

?>
</code>```

i want to display pdf file on web by accessing path which i has store in mysql.
how i can do this

答:
Use an Iframe to link your pdf</p>

```<code><iframe src="http://docs.google.com/gview?url=http://path.com/to/your/pdf.pdf&embedded=true"
style="width:600px; height:500px;" frameborder="0"></iframe>
</code>```

Body:
I had created database with 2 fields filename and path
filename as dwm.pdf and path as C:\xampp\htdocs\p1\testing.
I just want to display pdf file on link click with the help of path store in database.

<?php
$con = mysqli_connect("localhost","root","billa","pdf_trial") or die
("Couldn't connect");
echo "Connected";
$q = "SELECT path FROM pdffiles WHERE filename =dwm"
$r = mysqli_query($q);
$row = mysqli_fetch_assoc($r);
header('Content-type: application/pdf');

?>

i want to display pdf file on web by accessing path which i has store in mysql.
how i can do this

Body:
Use an Iframe to link your pdf

<iframe src="http://docs.google.com/gview?url=http://path.com/to/your/pdf.pdf&embedded=true"
style="width:600px; height:500px;" frameborder="0"></iframe>


问:
Why does GCC seem much more verbose in Ubuntu 10?
I have recently made a cp clone (for University) and I happened to discover something I had never got the chance to.

This applies at least to GCC compiling a C source.

I did the main development of this specific C program in a Mac OS X (10.6.4), builds with Apple's /usr/bin/gcc --version

```<code>i686-apple-darwin10-gcc-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5664)
Copyright (C) 2007 Free Software Foundation, Inc.
</code>```

However, I ran the tests in an Arch Linux virtual machine within the Mac, with the latest gcc (no additions, no customizations, no mods like Apple's)

```<code>gcc (GCC) 4.5.1
Copyright (C) 2010 Free Software Foundation, Inc.
</code>```

And we had to build it in the class in the Ubuntu 10.04.1 LTS that we have there.

My Makefile was something like:

```<code>CC=gcc
#CFLAGS=-O0 -g -Wall
CFLAGS=-O3 -Wall -finline-functions
EXE=copy

compile:
    $(CC) $(CFLAGS) -o $(EXE) main.c
</code>```

So, I was always running (in every OS) gcc with -Wall enabled.
Mac and Arch never showed any warning.

Ubuntu printed two warnings, with and without -Wall

```<code>do_copy.c: In function 'do_copy_file2file':
do_copy.c:27: warning: ignoring return value of 'realpath', declared with attribute warn_unused_result
do_copy.c: In function 'do_copy_symlink2file':
do_copy.c:117: warning: ignoring return value of 'symlink', declared with attribute warn_unused_result
</code>```

Ubuntu's GCC version is the default for the distribution:
gcc (Ubuntu 4.4.3-ubuntu5) 4.4.3

Why does that happen?

Why don't I see any warnings in the other two OSs and in Ubuntu I do?

答: Ubuntu enforces some CFLAGS as you can see here</p>

Body:
I have recently made a cp clone (for University) and I happened to discover something I had never got the chance to.

This applies at least to GCC compiling a C source.

I did the main development of this specific C program in a Mac OS X (10.6.4), builds with Apple's /usr/bin/gcc --version

i686-apple-darwin10-gcc-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5664)
Copyright (C) 2007 Free Software Foundation, Inc.

However, I ran the tests in an Arch Linux virtual machine within the Mac, with the latest gcc (no additions, no customizations, no mods like Apple's)

gcc (GCC) 4.5.1
Copyright (C) 2010 Free Software Foundation, Inc.

And we had to build it in the class in the Ubuntu 10.04.1 LTS that we have there.

My Makefile was something like:

CC=gcc
#CFLAGS=-O0 -g -Wall
CFLAGS=-O3 -Wall -finline-functions
EXE=copy

compile:
    $(CC) $(CFLAGS) -o $(EXE) main.c

So, I was always running (in every OS) gcc with -Wall enabled.
Mac and Arch never showed any warning.

Ubuntu printed two warnings, with and without -Wall

do_copy.c: In function 'do_copy_file2file':
do_copy.c:27: warning: ignoring return value of 'realpath', declared with attribute warn_unused_result
do_copy.c: In function 'do_copy_symlink2file':
do_copy.c:117: warning: ignoring return value of 'symlink', declared with attribute warn_unused_result

Ubuntu's GCC version is the default for the distribution:
gcc (Ubuntu 4.4.3-ubuntu5) 4.4.3

Why does that happen?

Why don't I see any warnings in the other two OSs and in Ubuntu I do?


问:
Xcode8.3 constantly crashes after update
After update Xcode 8.3 is crashing constantly. At start it was 30 to 40 minutes but today it is crashing after just 10 seconds. Any help will be highly appreciated. Below is crash report.</p>

```<code>Process:               Xcode [555]
Path:                  /Applications/Xcode.app/Contents/MacOS/Xcode
Identifier:            com.apple.dt.Xcode
Version:               8.3 (12169)
Build Info:            IDEFrameworks-12169000000000000~2
App Item ID:           497799835
App External ID:       821487965
Code Type:             X86-64 (Native)
Parent Process:        ??? [1]
Responsible:           Xcode [555]
User ID:               501

Date/Time:             2017-03-29 17:52:50.427 +0500
OS Version:            Mac OS X 10.12.4 (16E195)
Report Version:        12
Anonymous UUID:        C95FFD88-0B61-915D-E373-1F31A265D400

Time Awake Since Boot: 250 seconds

System Integrity Protection: enabled

Crashed Thread:        0  Dispatch queue: com.apple.main-thread

Exception Type:        EXC_CRASH (SIGABRT)
Exception Codes:       0x0000000000000000, 0x0000000000000000
Exception Note:        EXC_CORPSE_NOTIFY

Application Specific Information:
MainQueue: _compat_sourcekitd_set_notification_handler_block_invoke_2
ProductBuildVersion: 8E162
ASSERTION FAILURE in /Library/Caches/com.apple.xbs/Sources/DVTFrameworks/DVTFrameworks-12150/DVTFoundation/FilePaths/DVTFilePath.m:905
Details:  Path must be absolute but is not: <built-in>
Object:   <DVTFilePath>
Method:   +filePathForPathString:
Thread:   <NSThread: 0x7fc33ae02970>{number = 1, name = main}
</code>```

答: I have the same problem. I've notice that if you clean project (CMD + SHIFT + K) Xcode doesn't crash anymore.</p>

Body:
After update Xcode 8.3 is crashing constantly. At start it was 30 to 40 minutes but today it is crashing after just 10 seconds. Any help will be highly appreciated. Below is crash report.

Process:               Xcode [555]
Path:                  /Applications/Xcode.app/Contents/MacOS/Xcode
Identifier:            com.apple.dt.Xcode
Version:               8.3 (12169)
Build Info:            IDEFrameworks-12169000000000000~2
App Item ID:           497799835
App External ID:       821487965
Code Type:             X86-64 (Native)
Parent Process:        ??? [1]
Responsible:           Xcode [555]
User ID:               501

Date/Time:             2017-03-29 17:52:50.427 +0500
OS Version:            Mac OS X 10.12.4 (16E195)
Report Version:        12
Anonymous UUID:        C95FFD88-0B61-915D-E373-1F31A265D400

Time Awake Since Boot: 250 seconds

System Integrity Protection: enabled

Crashed Thread:        0  Dispatch queue: com.apple.main-thread

Exception Type:        EXC_CRASH (SIGABRT)
Exception Codes:       0x0000000000000000, 0x0000000000000000
Exception Note:        EXC_CORPSE_NOTIFY

Application Specific Information:
MainQueue: _compat_sourcekitd_set_notification_handler_block_invoke_2
ProductBuildVersion: 8E162
ASSERTION FAILURE in /Library/Caches/com.apple.xbs/Sources/DVTFrameworks/DVTFrameworks-12150/DVTFoundation/FilePaths/DVTFilePath.m:905
Details:  Path must be absolute but is not: <built-in>
Object:   <DVTFilePath>
Method:   +filePathForPathString:
Thread:   <NSThread: 0x7fc33ae02970>{number = 1, name = main}


问:
Display a preview image from a video swift
I have a folder in my documents directory containing images and videos, In my app i have a collection view that displays the images in each cell.

I have accomplished this with a load image function that returns a UIImage

```<code>    // Get the UI Image from the path passed in
    let image = UIImage(contentsOfFile: path)

    if image == nil
    {
        print("No Image at this path");
    }
    else
    {
        return image
    }
</code>```

However I can't seem to find something equivalent for videos, Ideally I want it to show as the video player thing like in photo album where you see a still of the video with a little play button on it that when clicked plays the video.

Failing that purely being able to get a still from the video at the specified path I have to be returned as a UIImage I can display would be ok.

I am new to iOS stuff so just wondering if there is some equivalent type like UIImage for videos that means I can just load and display it on the collection view.

答:
For swift 3.0</p>

```<code>func generateThumbnailForVideoAtURL(filePathLocal: NSString) -> UIImage? {

let vidURL = NSURL(fileURLWithPath:filePathLocal as String)
    let asset = AVURLAsset(url: vidURL as URL)
    let generator = AVAssetImageGenerator(asset: asset)
    generator.appliesPreferredTrackTransform = true

let timestamp = CMTime(seconds: 1, preferredTimescale: 60)

do {
    let imageRef = try generator.copyCGImage(at: timestamp, actualTime: nil)
    return UIImage(cgImage: imageRef)
}
catch let error as NSError
{
    print("Image generation failed with error \(error)")
    return nil
}

}
</code>```

Body:
I have a folder in my documents directory containing images and videos, In my app i have a collection view that displays the images in each cell.

I have accomplished this with a load image function that returns a UIImage

    // Get the UI Image from the path passed in
    let image = UIImage(contentsOfFile: path)

    if image == nil
    {
        print("No Image at this path");
    }
    else
    {
        return image
    }

However I can't seem to find something equivalent for videos, Ideally I want it to show as the video player thing like in photo album where you see a still of the video with a little play button on it that when clicked plays the video.

Failing that purely being able to get a still from the video at the specified path I have to be returned as a UIImage I can display would be ok.

I am new to iOS stuff so just wondering if there is some equivalent type like UIImage for videos that means I can just load and display it on the collection view.

Body:
For swift 3.0

func generateThumbnailForVideoAtURL(filePathLocal: NSString) -> UIImage? {

let vidURL = NSURL(fileURLWithPath:filePathLocal as String)
    let asset = AVURLAsset(url: vidURL as URL)
    let generator = AVAssetImageGenerator(asset: asset)
    generator.appliesPreferredTrackTransform = true

let timestamp = CMTime(seconds: 1, preferredTimescale: 60)

do {
    let imageRef = try generator.copyCGImage(at: timestamp, actualTime: nil)
    return UIImage(cgImage: imageRef)
}
catch let error as NSError
{
    print("Image generation failed with error \(error)")
    return nil
}

}


问:
Can ELMAH work with Oracle.ManagedDataAccess?
I have ASP.NET MVC project which connects to Oracle database using Oracle.ManagedDataAccess.dll, so I do not need to install Oracle client on any machine where application is deployed. Is there any option to configure ELMAH to use Oracle.ManagedDataAccess.dll?
In other way, as I understand, ELMAH can use only Oracle client?</p>

答:
The newest version of the Oracle error logger for ELMAH, actually supports both Oracle Client and Oracles own .NET client:

https://github.com/elmah/Elmah/blob/master/src/Elmah.Oracle/OracleErrorLog.cs#L429

There's no 2.x NuGet package of ELMAH, containing this error logger yet. You can clone the ELMAH repository from GitHub and distribute it through source control, internel NuGet server or MyGet. Alternatively, you can create your own error log implementation: Writing custom error loggers for ELMAH.


问:
How create GPS Tools?
I try display Google Maps inside my Fragment. The problem is when I run my project I do not see this maps. The additional information is this fragments belongs to Pager View.

This is my sample of code:

```<code>public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        thisContext = inflater.getContext();
        View view = inflater.inflate(R.layout.tab_fragment_2, container, false);
        loadMap();
       // initializeMap();

        locationManager = (LocationManager) thisContext.getSystemService(Context.LOCATION_SERVICE);

        if (ActivityCompat.checkSelfPermission(thisContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(thisContext, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return null;
        }
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 1, this);

        return view;

    }

    private void initializeMap() {
        if (map == null) {
            SupportMapFragment mapFrag = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
            mapFrag.getMapAsync(this);
        }
    }

    private void loadMap() {
        SupportMapFragment mSupportMapFragment;

        mSupportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
        if (mSupportMapFragment == null) {
            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            mSupportMapFragment = SupportMapFragment.newInstance();
            fragmentTransaction.replace(R.id.map, mSupportMapFragment).commit();
        }

        if (mSupportMapFragment != null) {
            mSupportMapFragment.getMapAsync(new OnMapReadyCallback() {
                @Override
                public void onMapReady(GoogleMap googleMap) {
                    if (googleMap != null) {

                        googleMap.getUiSettings().setAllGesturesEnabled(true);

                        // -> marker_latlng // MAKE THIS WHATEVER YOU WANT

                        //CameraPosition cameraPosition = new CameraPosition.Builder().target(marker_latlng).zoom(15.0f).build();
                        // CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(cameraPosition);
                        // googleMap.moveCamera(cameraUpdate);

                    }

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

答:
The problem is when I run my project I do not see this maps.

You can use the default 'new Activity' wizard to create Google maps activity.
It includes all the information you need. See the 7th item in the following screenshot.

Title: How create GPS Tools?

Body:
I try display Google Maps inside my Fragment. The problem is when I run my project I do not see this maps. The additional information is this fragments belongs to Pager View.

This is my sample of code:

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        thisContext = inflater.getContext();
        View view = inflater.inflate(R.layout.tab_fragment_2, container, false);
        loadMap();
       // initializeMap();

        locationManager = (LocationManager) thisContext.getSystemService(Context.LOCATION_SERVICE);

        if (ActivityCompat.checkSelfPermission(thisContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(thisContext, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return null;
        }
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 1, this);

        return view;

    }

    private void initializeMap() {
        if (map == null) {
            SupportMapFragment mapFrag = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
            mapFrag.getMapAsync(this);
        }
    }

    private void loadMap() {
        SupportMapFragment mSupportMapFragment;

        mSupportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
        if (mSupportMapFragment == null) {
            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            mSupportMapFragment = SupportMapFragment.newInstance();
            fragmentTransaction.replace(R.id.map, mSupportMapFragment).commit();
        }

        if (mSupportMapFragment != null) {
            mSupportMapFragment.getMapAsync(new OnMapReadyCallback() {
                @Override
                public void onMapReady(GoogleMap googleMap) {
                    if (googleMap != null) {

                        googleMap.getUiSettings().setAllGesturesEnabled(true);

                        // -> marker_latlng // MAKE THIS WHATEVER YOU WANT

                        //CameraPosition cameraPosition = new CameraPosition.Builder().target(marker_latlng).zoom(15.0f).build();
                        // CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(cameraPosition);
                        // googleMap.moveCamera(cameraUpdate);

                    }

                }
            });
        }
    }


问:
Content sent through jQuery ajax is getting cut off
I am trying to send html via jQuery's $.ajax() method, and then dump the html into a new .html file, but the content is getting cut off for some reason.

I have set up a test case:

```<code><html>

<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script >
$(document).ready(function(){
      var contents = $('html').html();
      var filename = "test/000.html";
      $.ajax({
         type: "POST",
         url: "/file.php",
         data: "content="+contents+"&fn="+filename,
         dataType: "html",
         success: function(msg, ts, xh){
             console.log(msg);
             console.log(ts);
             console.log(xh);
             alert("success");
         },
         processData: false,
         error: function(X, textStatus, error){
             alert("Error saving... please try again now.")
         }
     });
});
</script>

</head>

<body>

<div id="rteContainer" class="dev">
  <div id="textEditor">
    <form>
    <textarea name="balh" id="balh" rows="25" cols="103"></textarea>
    <input type="button" id="updateContent" value="Update Changes">
    <input type="button" id="closeEditor" value="Close Without Saving">
    </form>
  </div>
</div>

</body>
</html>
</code>```

the file.php file is:

```<code><?php
header("Content-type:text/html;charset:UTF-8");
$content = "<html>".stripslashes(urldecode($_POST["content"]))."</html>";
$dump_file = $_POST["fn"];
$fp = fopen($dump_file, 'w');
fclose($fp);
echo $content;
?>
</code>```

Why is is getting cut off? I'm guessing it's come encoding problem, but I can't figure this out.

答:
The html string, contents, has to be url-encoded before you POST it. Javascript provides the escape() function, just for this purpose.

Pass $('html').html() to escape() and assign it to contents, like so:

```<code>var contents = escape($('html').html());
</code>```

Body:
I am trying to send html via jQuery's $.ajax() method, and then dump the html into a new .html file, but the content is getting cut off for some reason.

I have set up a test case:

    <form>
    <textarea name="balh" id="balh" rows="25" cols="103"></textarea>
    <input type="button" id="updateContent" value="Update Changes">
    <input type="button" id="closeEditor" value="Close Without Saving">
    </form>

the file.php file is:

<?php
header("Content-type:text/html;charset:UTF-8");
$content = "".stripslashes(urldecode($_POST["content"]))."";
$dump_file = $_POST["fn"];
$fp = fopen($dump_file, 'w');
fclose($fp);
echo $content;
?>

Why is is getting cut off? I'm guessing it's come encoding problem, but I can't figure this out.

Body:
The html string, contents, has to be url-encoded before you POST it. Javascript provides the escape() function, just for this purpose.

Pass $('html').html() to escape() and assign it to contents, like so:

var contents = escape($('html').html());


问:
This code work in local development system and local IIS but not working fine in Application server
Why is this code not working in my production server? This code is correctly working in local development system. Do I need to change any settings in my production server?</p>

```<code>$(function() {
  alert('working fine');

  $.connection.hub.logging = true;
    var con = $.connection.hitCount;
    var message = 'hai';
    var name = 'suresh';

    con.client.onHitRecorded = function(i) {
        alert('not working'); // not firing
    };

    $.connection.hub.start().done(function() {

        con.server.send(message, name);
        alert('working fine');

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

答: This is not a problem in code. actually this is not a code error. If you want solve this add redis dll to your application. if you add this it will work fine.</p>

Body:
Why is this code not working in my production server? This code is correctly working in local development system. Do I need to change any settings in my production server?

$(function() {
  alert('working fine');

  $.connection.hub.logging = true;
    var con = $.connection.hitCount;
    var message = 'hai';
    var name = 'suresh';

    con.client.onHitRecorded = function(i) {
        alert('not working'); // not firing
    };

    $.connection.hub.start().done(function() {

        con.server.send(message, name);
        alert('working fine');

    });
})


问:
What exactly does "next" mean in package.json dependencies?
What exactly does next mean in package.json dependencies?

```<code>"dependencies": {
  "react": "^15.4.2",
  "react-dom": "^15.4.2",
  "react-router-dom": "next"
}
</code>```

答:
The next tag is used by some projects to identify the upcoming version.By default, other than latest, no tag has any special significance to npm itself.

NPM Documentation

Body:
What exactly does next mean in package.json dependencies?

"dependencies": {
  "react": "^15.4.2",
  "react-dom": "^15.4.2",
  "react-router-dom": "next"
}