问:
wxDEV+OpenCV error : Undefined reference to `cvLoadImage''
Hello everyone, I am trying to use OpenCV library in wxDev C++, and it couldn't compiler correctly. (OpenCV version: 2.4.13.4)

These are the errors:

```<code>[Linker Error] undefined reference to `cvLoadImage'
[Linker Error] undefined reference to `cvShowImage'
[Linker Error] undefined reference to `cvWaitKey'
[Linker Error] undefined reference to `cvReleaseImage'
ld returned 1 exit status
</code>```

These are the codes:

```<code>#include "opencv2/opencv.hpp"
int main()
    {
    IplImage *srcImg = NULL;

    srcImg = cvLoadImage( "temp.jpg", 1);
    if( srcImg == NULL ){
    return -1;
    }

    cvShowImage( "Source", srcImg );
    cvWaitKey(0);
    cvReleaseImage( &srcImg );
    }
</code>```

These are the setting of wxDev:
wxDev Compiler Options

It seems that wxDev can't recognize those methods which I included from the library. What should I do?

//------------------------------------------------------------------------------

[12/4 update] I forgot to say that I've tried to use a different version of OpenCV(3.3.1) as well, so the settings in the screenshot have a little bug. "D:\OpenCV\2.4\opencv\build" is for 2.4.13.4. "D:\OpenCV\opencv\build" is for 3.3.1. I have included both of them in the setting but still doesn't work out. I don't know what is the differences between 3.3.1 and 2.4.1.3, but they are the newest update then.

I've tried to change the way I named the libraries, but it didn't work. For instance, "-opencv_core", "-lopencv_core", "-opencv_core.lib", "-lopencv_core.lib", "-lopencv_core.a".

//------------------------------------------------------------------------------

[12/5 update#1] It seems that there is something wrong with the libraries. So, instead of using the newer version of OpenCV, I tried using the older one, the OpenCV2.2. Fortunately, it worked pretty well! I did exactly the same thing but came out a different result. I assumed that the methods of the software have been modified somehow in the latest version. Hopefully, someone could provide a later tutorial for the recent version of OpenCV.

[12/5 update#2] After successfully compiler this program, I started running another OpenCV example. The same issues occurred.

Example Code:

```<code>#include <cstdio>
#include <opencv2/opencv.hpp>
using namespace cv;

int main(){
    Mat img = imread("lena.jpg",CV_LOAD_IMAGE_GRAYSCALE);
    imwrite("output.jpg",img);

    namedWindow("Display window", WINDOW_AUTOSIZE);
    imshow("Display window", img);
    waitKey(0);

    return 0;
}
</code>```

Some of those errors:

```<code>[Linker Error] undefined reference to `cv::imread(std::string const&, int)
[Linker Error] undefined reference to `cv::namedWindow(std::string const&, int)
[Linker Error] undefined reference to `cv::_InputArray::_InputArray(cv::Mat const&)
[Linker Error] undefined reference to `cv::fastFree(void*)'
</code>```

The same problem just keep happening, still looking for savior.

//------------------------------------------------------------------------------

[12/6 update] After several attempts, I downgraded OpenCV into version 2.0. The program successfully worked. The only difference compared to the other versions is the library's direction which was included.

The other version won't work if I write #include <opencv2/opencv.hpp>.
Version 2.0 will work if I write #include <cv.h>, #include <highgui.h>.
(Version 2.0 doesn't have the file, opencv2, so I have to include the direction.) I have no idea why it ends up like this.

The solution is to use the version 2.0 and also not using #include <opencv2/opencv.hpp>. It can run perfectly well in most of the examples so far. Although I could start working on my project now, I still try to figure out how to use the latest version of OpenCV.

//------------------------------------------------------------------------------

Respond to Mark Setchell-
These are the screenshots of the files and settings so far:

The lib files and its directions

OpenCV 2.2.0 settings and directions

OpenCV 2.4.11 settings and directions

I have tried different versions of OpenCV to run the program, the details of the process written in "12/5 update". By the way, I did change the compiler before running the program. Thanks for helping!

答:
According to you source code, you forgot to use the opencv namespace.

If your librarys are all linked correctly, try to add using namespace cv;

```<code>#include "opencv2/opencv.hpp"
using namespace cv;

int main()
{
    IplImage *srcImg = NULL;

    srcImg = cvLoadImage( "temp.jpg", 1);
    if( srcImg == NULL ){
        return -1;
    }

    cvShowImage( "Source", srcImg );
    cvWaitKey(0);
    cvReleaseImage( &srcImg );
}
</code>```

or use it explicitly:

```<code>#include "opencv2/opencv.hpp"
int main()
{
    cv::IplImage *srcImg = NULL;

    srcImg = cv::cvLoadImage( "temp.jpg", 1);
    if( srcImg == NULL ){
        return -1;
    }

    cv::cvShowImage( "Source", srcImg );
    cv::cvWaitKey(0);
    cv::cvReleaseImage( &srcImg );
}
</code>```

Hope this helps

Body:
Hello everyone, I am trying to use OpenCV library in wxDev C++, and it couldn't compiler correctly. (OpenCV version: 2.4.13.4)

These are the errors:

[Linker Error] undefined reference to `cvLoadImage'
[Linker Error] undefined reference to `cvShowImage'
[Linker Error] undefined reference to `cvWaitKey'
[Linker Error] undefined reference to `cvReleaseImage'
ld returned 1 exit status

These are the codes:

#include "opencv2/opencv.hpp"
int main()
    {
    IplImage *srcImg = NULL;

    srcImg = cvLoadImage( "temp.jpg", 1);
    if( srcImg == NULL ){
    return -1;
    }

    cvShowImage( "Source", srcImg );
    cvWaitKey(0);
    cvReleaseImage( &srcImg );
    }

These are the setting of wxDev:
wxDev Compiler Options

It seems that wxDev can't recognize those methods which I included from the library. What should I do?

//------------------------------------------------------------------------------

[12/4 update] I forgot to say that I've tried to use a different version of OpenCV(3.3.1) as well, so the settings in the screenshot have a little bug. "D:\OpenCV\2.4\opencv\build" is for 2.4.13.4. "D:\OpenCV\opencv\build" is for 3.3.1. I have included both of them in the setting but still doesn't work out. I don't know what is the differences between 3.3.1 and 2.4.1.3, but they are the newest update then.

I've tried to change the way I named the libraries, but it didn't work. For instance, "-opencv_core", "-lopencv_core", "-opencv_core.lib", "-lopencv_core.lib", "-lopencv_core.a".

//------------------------------------------------------------------------------

[12/5 update#1] It seems that there is something wrong with the libraries. So, instead of using the newer version of OpenCV, I tried using the older one, the OpenCV2.2. Fortunately, it worked pretty well! I did exactly the same thing but came out a different result. I assumed that the methods of the software have been modified somehow in the latest version. Hopefully, someone could provide a later tutorial for the recent version of OpenCV.

[12/5 update#2] After successfully compiler this program, I started running another OpenCV example. The same issues occurred.

Example Code:

#include <cstdio>
#include <opencv2/opencv.hpp>
using namespace cv;

int main(){
    Mat img = imread("lena.jpg",CV_LOAD_IMAGE_GRAYSCALE);
    imwrite("output.jpg",img);

    namedWindow("Display window", WINDOW_AUTOSIZE);
    imshow("Display window", img);
    waitKey(0);

    return 0;
}

Some of those errors:

[Linker Error] undefined reference to `cv::imread(std::string const&, int)
[Linker Error] undefined reference to `cv::namedWindow(std::string const&, int)
[Linker Error] undefined reference to `cv::_InputArray::_InputArray(cv::Mat const&)
[Linker Error] undefined reference to `cv::fastFree(void*)'

The same problem just keep happening, still looking for savior.

//------------------------------------------------------------------------------

[12/6 update] After several attempts, I downgraded OpenCV into version 2.0. The program successfully worked. The only difference compared to the other versions is the library's direction which was included.

The other version won't work if I write #include <opencv2/opencv.hpp>.
Version 2.0 will work if I write #include <cv.h>, #include <highgui.h>.
(Version 2.0 doesn't have the file, opencv2, so I have to include the direction.) I have no idea why it ends up like this.

The solution is to use the version 2.0 and also not using #include <opencv2/opencv.hpp>. It can run perfectly well in most of the examples so far. Although I could start working on my project now, I still try to figure out how to use the latest version of OpenCV.

//------------------------------------------------------------------------------

Respond to Mark Setchell-
These are the screenshots of the files and settings so far:

The lib files and its directions

OpenCV 2.2.0 settings and directions

OpenCV 2.4.11 settings and directions

I have tried different versions of OpenCV to run the program, the details of the process written in "12/5 update". By the way, I did change the compiler before running the program. Thanks for helping!

Body:
According to you source code, you forgot to use the opencv namespace.

If your librarys are all linked correctly, try to add using namespace cv;

#include "opencv2/opencv.hpp"
using namespace cv;

int main()
{
    IplImage *srcImg = NULL;

    srcImg = cvLoadImage( "temp.jpg", 1);
    if( srcImg == NULL ){
        return -1;
    }

    cvShowImage( "Source", srcImg );
    cvWaitKey(0);
    cvReleaseImage( &srcImg );
}

or use it explicitly:

#include "opencv2/opencv.hpp"
int main()
{
    cv::IplImage *srcImg = NULL;

    srcImg = cv::cvLoadImage( "temp.jpg", 1);
    if( srcImg == NULL ){
        return -1;
    }

    cv::cvShowImage( "Source", srcImg );
    cv::cvWaitKey(0);
    cv::cvReleaseImage( &srcImg );
}

Hope this helps


来源: stackexchange

问:
error: no matching function for call to at c++
I get this error in g++;

error: no matching function for call to ‘CudnnRun::cudnnAddTensor_run(float [1][2][3][3], float [1][2][3][3], const int&, const int&, const int&)’

i wrote in cpp file, like this.

const int mb_size = 1;
const int feature_num = 2;
const int in_size = 3;

float in_data[mb_size][feature_num][in_size][in_size] = {
   {
     { { 0, 1, 0 }, { 0, 1, 0 }, { 0, 1, 0 } },
     { { 1, 1, 1 }, { 1, 1, 1 }, { 1, 1, 1 } }
   }
  };
float out_data[mb_size][feature_num][in_size][in_size] = {
  {
    { { 3, 1, 1 }, { 0, 1, 0 }, { 0, 1, 0 } },
    { { 10, 1, 1 }, { 1, 1, 1 }, { 1, 1, 1 } }
  }
};

CudnnRun m1;
m1.cudnnAddTensor_run(in_data,out_data,mb_size,feature_num,in_size);
```

<p>in header file ,</p>

<pre class="lang-cpp prettyprint-override"><code>class CudnnRun
{
  public:
    void cudnnAddTensor_run(float *in_data,float *out_data,int mb_size,int feature_num,int in_size);
};
</code>```

I intend to match the type of the argument of the function,Why does such an error occur?

答:
in_data and out_data are four dimensional data blocks! To that end, your initialisation statements look arbitrary to me.

Pointer decay at the function call site essentially collapses the outermost dimension. Bearing in mind that C++ does not support variable length arrays, your function prototype for the class member function needs to be

```<code>void cudnnAddTensor_run(
    float(*in_data)[1][2][3],
    float (*out_data)[1][2][3],
    int mb_size,
    int feature_num,
    int in_size
);
</code>```

and the final 3 parameters appear to be redundant here.

Can you not reduce the problem to a single contiguous one dimensional array, and use clever indexing to get the element you want?

ContentLicense: CC BY-SA 3.0

Body:
I get this error in g++;

error: no matching function for call to ‘CudnnRun::cudnnAddTensor_run(float [1][2][3][3], float [1][2][3][3], const int&, const int&, const int&)’

i wrote in cpp file, like this.

const int mb_size = 1;
const int feature_num = 2;
const int in_size = 3;

float in_data[mb_size][feature_num][in_size][in_size] = {
   {
     { { 0, 1, 0 }, { 0, 1, 0 }, { 0, 1, 0 } },
     { { 1, 1, 1 }, { 1, 1, 1 }, { 1, 1, 1 } }
   }
  };
float out_data[mb_size][feature_num][in_size][in_size] = {
  {
    { { 3, 1, 1 }, { 0, 1, 0 }, { 0, 1, 0 } },
    { { 10, 1, 1 }, { 1, 1, 1 }, { 1, 1, 1 } }
  }
};

CudnnRun m1;
m1.cudnnAddTensor_run(in_data,out_data,mb_size,feature_num,in_size);

in header file ,

class CudnnRun
{
  public:
    void cudnnAddTensor_run(float *in_data,float *out_data,int mb_size,int feature_num,int in_size);
};

I intend to match the type of the argument of the function,Why does such an error occur?

Body:
in_data and out_data are four dimensional data blocks! To that end, your initialisation statements look arbitrary to me.

Pointer decay at the function call site essentially collapses the outermost dimension. Bearing in mind that C++ does not support variable length arrays, your function prototype for the class member function needs to be

void cudnnAddTensor_run(
    float(*in_data)[1][2][3],
    float (*out_data)[1][2][3],
    int mb_size,
    int feature_num,
    int in_size
);

and the final 3 parameters appear to be redundant here.

Can you not reduce the problem to a single contiguous one dimensional array, and use clever indexing to get the element you want?


问:
PowerShell - get process ID of called application
I need to call an external application (i.e. & 'Notepad' )
and then get the process ID of the called application.

Get-Process Notepad  = will return all Notepad processes

I want to do something like:

```<code>$objApp = & 'c:\Notepad.exe'

WHILE (get-process -ID $objApp.id | select -property Responding) {
  Start-Sleep -s 10
  Echo "STILL WAITING"
}
Echo "Done!!"
</code>```

答:
Use Start-Process with the -PassThru argument like  this:

```<code>$app = Start-Process notepad -passthru
Wait-Process $app.Id
</code>```

Body:
I need to call an external application (i.e. & 'Notepad' )
and then get the process ID of the called application.

Get-Process Notepad  = will return all Notepad processes

I want to do something like:

$objApp = & 'c:\Notepad.exe'

WHILE (get-process -ID $objApp.id | select -property Responding) {
  Start-Sleep -s 10
  Echo "STILL WAITING"
}
Echo "Done!!"

Body:
Use Start-Process with the -PassThru argument like  this:

$app = Start-Process notepad -passthru
Wait-Process $app.Id

ContentLicense: CC BY-SA 2.5


问:
Retrofit can't parse body correctly
I am not being able to parse correctly the response of my web service using Retrofit2 + Gson.
I have implemented similar responses and all of them work correctly. The problem occurs when the response body returns an array of custom objects.

I have read many responses from stackoverflow and I made my classes using http://www.jsonschema2pojo.org/ but no way...

I paste all my code. Hope you can help me. Thanks!

Webservice response

```<code>    {
    "code": "SUCCESS",
    "errorMessage": null,
    "data": [
        {
            "nickname": "David",
            "tiempoMiliseg": 49745,
            "fecha": "2017-07-14T13:59:12.000Z"
        },
        {
            "nickname": "kart 13",
            "tiempoMiliseg": 54034,
            "fecha": "2017-07-14T17:50:51.000Z"
        },
        {
            "nickname": "kart 26",
            "tiempoMiliseg": 54728,
            "fecha": "2017-07-14T17:50:51.000Z"
        },
        {
            "nickname": "kart 16",
            "tiempoMiliseg": 54845,
            "fecha": "2017-07-14T17:50:51.000Z"
        },
        {
            "nickname": "jonathan",
            "tiempoMiliseg": 55061,
            "fecha": "2017-07-14T19:12:57.000Z"
        },
        {
            "nickname": "kart 20",
            "tiempoMiliseg": 55187,
            "fecha": "2017-07-14T17:50:51.000Z"
        },
        {
            "nickname": "kart 5",
            "tiempoMiliseg": 55584,
            "fecha": "2017-07-14T15:51:53.000Z"
        },
        {
            "nickname": "kart 5",
            "tiempoMiliseg": 55926,
            "fecha": "2017-07-14T15:21:30.000Z"
        },
        {
            "nickname": "kart 19",
            "tiempoMiliseg": 56025,
            "fecha": "2017-07-14T18:34:01.000Z"
        },
        {
            "nickname": "kart 11",
            "tiempoMiliseg": 56403,
            "fecha": "2017-07-14T18:34:01.000Z"
        },
        {
            "nickname": "kart 22",
            "tiempoMiliseg": 56458,
            "fecha": "2017-07-14T15:51:53.000Z"
        },
        {
            "nickname": "kart 28",
            "tiempoMiliseg": 56467,
            "fecha": "2017-07-14T18:10:08.000Z"
        },
        {
            "nickname": "kart 2",
            "tiempoMiliseg": 56548,
            "fecha": "2017-07-14T18:10:08.000Z"
        },
        {
            "nickname": "kart 27",
            "tiempoMiliseg": 56620,
            "fecha": "2017-07-14T15:51:53.000Z"
        },
        {
            "nickname": "kart 27",
            "tiempoMiliseg": 56629,
            "fecha": "2017-07-14T18:34:01.000Z"
        },
        {
            "nickname": "kart 20",
            "tiempoMiliseg": 56827,
            "fecha": "2017-07-14T18:34:01.000Z"
        },
        {
            "nickname": "kart 26",
            "tiempoMiliseg": 56846,
            "fecha": "2017-07-14T18:56:31.000Z"
        },
        {
            "nickname": "kart 28",
            "tiempoMiliseg": 57071,
            "fecha": "2017-07-14T18:34:01.000Z"
        },
        {
            "nickname": "kart 26",
            "tiempoMiliseg": 57088,
            "fecha": "2017-07-14T18:34:01.000Z"
        },
        {
            "nickname": "kart 29",
            "tiempoMiliseg": 57143,
            "fecha": "2017-07-14T18:34:01.000Z"
        }
    ]
}
</code>```

Retrofit Response class

```<code>public class RankingResponse {

@SerializedName("code")
@Expose
private String code;
@SerializedName("errorMessage")
@Expose
private Object errorMessage;
@SerializedName("data")
@Expose
private List<Datum> data = null;

public String getCode() {
    return code;
}

public void setCode(String code) {
    this.code = code;
}

public Object getErrorMessage() {
    return errorMessage;
}

public void setErrorMessage(Object errorMessage) {
    this.errorMessage = errorMessage;
}

public List<Datum> getData() {
    return data;
}

public void setData(List<Datum> data) {
    this.data = data;
}

@Override
public String toString() {
    return "RankingResponse{" +
            "code='" + code + '\'' +
            ", errorMessage=" + errorMessage +
            ", data=" + data +
            '}';
}

public class Datum {
    @SerializedName("nickname")
    @Expose
    private String nickname;
    @SerializedName("tiempoMiliseg")
    @Expose
    private Integer tiempoMiliseg;
    @SerializedName("fecha")
    @Expose
    private String fecha;

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public Integer getTiempoMiliseg() {
        return tiempoMiliseg;
    }

    public void setTiempoMiliseg(Integer tiempoMiliseg) {
        this.tiempoMiliseg = tiempoMiliseg;
    }

    public String getFecha() {
        return fecha;
    }

    public void setFecha(String fecha) {
        this.fecha = fecha;
    }

    @Override
    public String toString() {
        return "Datum{" +
                "nickname='" + nickname + '\'' +
                ", tiempoMiliseg=" + tiempoMiliseg +
                ", fecha='" + fecha + '\'' +
                '}';
    }
}
</code>```

}

Retrofit client

```<code>public class RetrofitClient {

    private static Retrofit retrofit = null;

    public static Retrofit getClient(String baseUrl) {
        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}
</code>```

Retrofit response

答:
In your RankingResponse class replace following:

```<code>@SerializedName("data")
@Expose
private List<Datum> data = null;
</code>```

with:

```<code>@SerializedName("data")
private List<Datum> data =  new ArrayList<Datum>();
</code>```

Title: Retrofit can't parse body correctly

Body:
I am not being able to parse correctly the response of my web service using Retrofit2 + Gson.
I have implemented similar responses and all of them work correctly. The problem occurs when the response body returns an array of custom objects.

I have read many responses from stackoverflow and I made my classes using http://www.jsonschema2pojo.org/ but no way...

I paste all my code. Hope you can help me. Thanks!

Webservice response

    {
    "code": "SUCCESS",
    "errorMessage": null,
    "data": [
        {
            "nickname": "David",
            "tiempoMiliseg": 49745,
            "fecha": "2017-07-14T13:59:12.000Z"
        },
        {
            "nickname": "kart 13",
            "tiempoMiliseg": 54034,
            "fecha": "2017-07-14T17:50:51.000Z"
        },
        {
            "nickname": "kart 26",
            "tiempoMiliseg": 54728,
            "fecha": "2017-07-14T17:50:51.000Z"
        },
        {
            "nickname": "kart 16",
            "tiempoMiliseg": 54845,
            "fecha": "2017-07-14T17:50:51.000Z"
        },
        {
            "nickname": "jonathan",
            "tiempoMiliseg": 55061,
            "fecha": "2017-07-14T19:12:57.000Z"
        },
        {
            "nickname": "kart 20",
            "tiempoMiliseg": 55187,
            "fecha": "2017-07-14T17:50:51.000Z"
        },
        {
            "nickname": "kart 5",
            "tiempoMiliseg": 55584,
            "fecha": "2017-07-14T15:51:53.000Z"
        },
        {
            "nickname": "kart 5",
            "tiempoMiliseg": 55926,
            "fecha": "2017-07-14T15:21:30.000Z"
        },
        {
            "nickname": "kart 19",
            "tiempoMiliseg": 56025,
            "fecha": "2017-07-14T18:34:01.000Z"
        },
        {
            "nickname": "kart 11",
            "tiempoMiliseg": 56403,
            "fecha": "2017-07-14T18:34:01.000Z"
        },
        {
            "nickname": "kart 22",
            "tiempoMiliseg": 56458,
            "fecha": "2017-07-14T15:51:53.000Z"
        },
        {
            "nickname": "kart 28",
            "tiempoMiliseg": 56467,
            "fecha": "2017-07-14T18:10:08.000Z"
        },
        {
            "nickname": "kart 2",
            "tiempoMiliseg": 56548,
            "fecha": "2017-07-14T18:10:08.000Z"
        },
        {
            "nickname": "kart 27",
            "tiempoMiliseg": 56620,
            "fecha": "2017-07-14T15:51:53.000Z"
        },
        {
            "nickname": "kart 27",
            "tiempoMiliseg": 56629,
            "fecha": "2017-07-14T18:34:01.000Z"
        },
        {
            "nickname": "kart 20",
            "tiempoMiliseg": 56827,
            "fecha": "2017-07-14T18:34:01.000Z"
        },
        {
            "nickname": "kart 26",
            "tiempoMiliseg": 56846,
            "fecha": "2017-07-14T18:56:31.000Z"
        },
        {
            "nickname": "kart 28",
            "tiempoMiliseg": 57071,
            "fecha": "2017-07-14T18:34:01.000Z"
        },
        {
            "nickname": "kart 26",
            "tiempoMiliseg": 57088,
            "fecha": "2017-07-14T18:34:01.000Z"
        },
        {
            "nickname": "kart 29",
            "tiempoMiliseg": 57143,
            "fecha": "2017-07-14T18:34:01.000Z"
        }
    ]
}

Retrofit Response class

public class RankingResponse {

@SerializedName("code")
@Expose
private String code;
@SerializedName("errorMessage")
@Expose
private Object errorMessage;
@SerializedName("data")
@Expose
private List<Datum> data = null;

public String getCode() {
    return code;
}

public void setCode(String code) {
    this.code = code;
}

public Object getErrorMessage() {
    return errorMessage;
}

public void setErrorMessage(Object errorMessage) {
    this.errorMessage = errorMessage;
}

public List<Datum> getData() {
    return data;
}

public void setData(List<Datum> data) {
    this.data = data;
}

@Override
public String toString() {
    return "RankingResponse{" +
            "code='" + code + '\'' +
            ", errorMessage=" + errorMessage +
            ", data=" + data +
            '}';
}

public class Datum {
    @SerializedName("nickname")
    @Expose
    private String nickname;
    @SerializedName("tiempoMiliseg")
    @Expose
    private Integer tiempoMiliseg;
    @SerializedName("fecha")
    @Expose
    private String fecha;

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public Integer getTiempoMiliseg() {
        return tiempoMiliseg;
    }

    public void setTiempoMiliseg(Integer tiempoMiliseg) {
        this.tiempoMiliseg = tiempoMiliseg;
    }

    public String getFecha() {
        return fecha;
    }

    public void setFecha(String fecha) {
        this.fecha = fecha;
    }

    @Override
    public String toString() {
        return "Datum{" +
                "nickname='" + nickname + '\'' +
                ", tiempoMiliseg=" + tiempoMiliseg +
                ", fecha='" + fecha + '\'' +
                '}';
    }
}

}

Retrofit client

public class RetrofitClient {

    private static Retrofit retrofit = null;

    public static Retrofit getClient(String baseUrl) {
        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

Retrofit response

Body:
In your RankingResponse class replace following:

@SerializedName("data")
@Expose
private List<Datum> data = null;

with:

@SerializedName("data")
private List<Datum> data =  new ArrayList<Datum>();


问:
Ionic testing - asynchronous look for a change in ionViewDidLoad
I have troubles trying to test the value of a variable that change inside the ionViewDidLoad method

welcomepage.ts

```<code>@Component({...})
export class WelcomePage {

    test: number = 0;

    constructor(){}

    ionViewDidLoad(){
        this.test = 1;
    }

}
</code>```

welcomepage.spec.ts

```<code>    it('test should equal be equal to 1', () => {
        fixture.detectChanges();
        expect(component.test).toBe(1)
    });
</code>```

But this test is not succeeding. If I do the change inside the constructor function (this.test = 1) then it is working.

======== UPDATE ========

It seems that it is a problem with ionViewDidLoad function triggered by ionic, it is working as usual by running ionic but not in the test.

答:
Your variable is not setting because you have done it in wrong way. Your variable name is test and you are setting value in variable type which is number. Please see the following snippet, hope it helps.

```<code>@Component({...})
export class WelcomePage {

   test: number = 0;

   constructor(){}

   ionViewDidLoad(){
       this.test = 1;
   }
}
</code>```

Body:
I have troubles trying to test the value of a variable that change inside the ionViewDidLoad method

welcomepage.ts

@Component({...})
export class WelcomePage {

    test: number = 0;

    constructor(){}

    ionViewDidLoad(){
        this.test = 1;
    }

}

welcomepage.spec.ts

    it('test should equal be equal to 1', () => {
        fixture.detectChanges();
        expect(component.test).toBe(1)
    });

But this test is not succeeding. If I do the change inside the constructor function (this.test = 1) then it is working.

======== UPDATE ========

It seems that it is a problem with ionViewDidLoad function triggered by ionic, it is working as usual by running ionic but not in the test.

Body:
Your variable is not setting because you have done it in wrong way. Your variable name is test and you are setting value in variable type which is number. Please see the following snippet, hope it helps.

@Component({...})
export class WelcomePage {

   test: number = 0;

   constructor(){}

   ionViewDidLoad(){
       this.test = 1;
   }
}


问:
ngx-chart: Show live data, angular 4.3

i want to visualize some live data in the ngx-chart-gauge.
 I build this up with this demo:
https://swimlane.gitbooks.io/ngx-charts/content/v/6.0.2/charts/gauge.html

I get my livedata from a Service and want to show the data in the ngx-chart-gauge. I get the data from the Service ClassdataproviderService, which saves the objects in the array 'single'.

This is my ngx-chart-gauge component:

```<code>import {Component, OnInit, OnChanges, AfterViewInit, AfterViewChecked, AfterContentChecked, AfterContentInit, NgModule} from '@angular/core';
import {NgxChartsModule} from '@swimlane/ngx-charts';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import {BrowserModule} from '@angular/platform-browser';
import {TempdatagiaService} from '../paho/tempdatagia.service';
import {ClassdataproviderService} from '../mqtt/classdataprovider.service';
import * as d3 from 'd3';

@Component({
  selector: 'app-mqtt',
  templateUrl: './mqtt.component.html',
  styleUrls: ['./mqtt.component.css']
})
export class MqttComponent implements OnChanges {

  view: any[] = [700, 400];
  data: any[];
  multi: any[];
  autoScale = true;

  constructor(private classdataproviderServie: ClassdataproviderService) {
  }

  ngOnChanges() {

      this.data = this.classdataproviderServie.single;

  }

  colorScheme = {
    domain: ['#5AA454', '#A10A28', '#C7B42C']
  };

  onSelect(event) {
    console.log(event);
  }
}
</code>```

This ist the ngx-chart-gauge.html

```<code><ngx-charts-gauge
  [view]="view"
  [scheme]="colorScheme"
  [results]="data"
  [min]="0"
  [max]="100"
  [angleSpan]="240"
  [startAngle]="-120"
  [units]="'Temperature'"
  [bigSegments]="10"
  [smallSegments]="5"
  (select)="onSelect($event)">
</ngx-charts-gauge>
</code>```

And this is my Service, where i get the data from:

```<code>import { Injectable } from '@angular/core';
import { Component, OnInit } from '@angular/core';
import {Paho} from '../../../node_modules/ng2-mqtt/mqttws31';

@Injectable()
export class ClassdataproviderService {

  public name: string;
  public value: string;

  single = [
    {
      name: '1',
      value: '15'
    },
    {
      name: '2',
      value: '20'
    }/*,
    {
      name: '3',
      value: '73'
    }*/
  ];

// Create a client instance
  client: any;
  packet: any;

  constructor() {

    // this.client = new Paho.MQTT.Client('broker.mqttdashboard.com', 8000,  'clientId-FUp9rr6sZS');
    this.client = new Paho.MQTT.Client('wpsdemo.gia.rwth-aachen.de', 8080, 'Steffen');

    this.onMessage();
    this.onConnectionLost();
    // connect the client
    this.client.connect({onSuccess: this.onConnected.bind(this)});
  }

  // called when the client connects
  onConnected() {
    console.log('Connected');
    this.client.subscribe('node/m1/temperature');
    //this.sendMessage('HelloWorld');
  }

  sendMessage(message: string) {
    const packet = new Paho.MQTT.Message(message);
    packet.destinationName = 'node/m1/temperature';
    this.client.send(packet);
  }

  // called when a message arrives
  onMessage() {
    this.client.onMessageArrived = (message: Paho.MQTT.Message) => {
      console.log('Message arrived : ' + message.payloadString);
      this.single.push({name: 'test', value: message.payloadString});
      console.log(this.single);
    };
  }

  // called when the client loses its connection
  onConnectionLost() {
    this.client.onConnectionLost = (responseObject: Object) => {
      console.log('Connection lost : ' + JSON.stringify(responseObject));
    };
  }
</code>```

When i try to inject the data in the gauge with OnInit, the gauge is not updating. To solve this i tried OnChanges, but now i get the ERROR TypeError: Cannot read property 'big' of undefined...

I dont know if its possible to auto update the gauge automatically without OnChanges or how to avoid the ERR with the OnChanges lifecycle hook?

答:
Now i tried out many solutions and the most effective is by using an observable, to observe my Service where i get the data from. The Service, which injects the data in the ngx-chart-component, withe the observable, looks like:

```<code>import { Injectable } from '@angular/core';
import { Component, OnInit } from '@angular/core';
import {Paho} from '../../../node_modules/ng2-mqtt/mqttws31';
import 'rxjs/add/observable/interval';
import {AddDataService} from './datawindow/addmqtt/formmqtt/addmqtt.service';

@Injectable()
export class ClassdataproviderService {
  public name: string;
  public value: string;

  single = [
    {
      name: '',
      value: ''
    }
  ];

// Create a client instance
  client: any;
  packet: any;

  constructor() {

   this.addDataService.componentMethodCalled$.subscribe(
  () => {
    this.client = new Paho.MQTT.Client('wpsdemo.gia.rwth-aachen.de', 8080, 'Steffen');
    this.onMessage();
    this.onConnectionLost();
    // connect the client
    this.client.connect({onSuccess: this.onConnected.bind(this)});
  }}

  // called when the client connects
  onConnected() {
    console.log('Connected');
    this.client.subscribe('node/m1/temperature');
    //this.sendMessage('HelloWorld');
  }

  sendMessage(message: string) {
    const packet = new Paho.MQTT.Message(message);
    packet.destinationName = 'node/m1/temperature';
    this.client.send(packet);
  }

  // called when a message arrives
  onMessage() {
    this.client.onMessageArrived = (message: Paho.MQTT.Message) => {
      console.log('Message arrived : ' + message.payloadString);
      this.single.push({name: 'test', value: message.payloadString});
      console.log(this.single);
    };
  }

  // called when the client loses its connection
  onConnectionLost() {
    this.client.onConnectionLost = (responseObject: Object) => {
      console.log('Connection lost : ' + JSON.stringify(responseObject));
    };
  }
</code>```

Now the single array will be updatetd every time i get new data and it works perfectly with ngx-charts.
And use ngOnInit as lifecyclehook in the gauge-component.

Title: ngx-chart: Show live data, angular 4.3

Body:
i want to visualize some live data in the ngx-chart-gauge.
 I build this up with this demo:
https://swimlane.gitbooks.io/ngx-charts/content/v/6.0.2/charts/gauge.html

I get my livedata from a Service and want to show the data in the ngx-chart-gauge. I get the data from the Service ClassdataproviderService, which saves the objects in the array 'single'.

This is my ngx-chart-gauge component:

import {Component, OnInit, OnChanges, AfterViewInit, AfterViewChecked, AfterContentChecked, AfterContentInit, NgModule} from '@angular/core';
import {NgxChartsModule} from '@swimlane/ngx-charts';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import {BrowserModule} from '@angular/platform-browser';
import {TempdatagiaService} from '../paho/tempdatagia.service';
import {ClassdataproviderService} from '../mqtt/classdataprovider.service';
import * as d3 from 'd3';

@Component({
  selector: 'app-mqtt',
  templateUrl: './mqtt.component.html',
  styleUrls: ['./mqtt.component.css']
})
export class MqttComponent implements OnChanges {

  view: any[] = [700, 400];
  data: any[];
  multi: any[];
  autoScale = true;

  constructor(private classdataproviderServie: ClassdataproviderService) {
  }

  ngOnChanges() {

      this.data = this.classdataproviderServie.single;

  }

  colorScheme = {
    domain: ['#5AA454', '#A10A28', '#C7B42C']
  };

  onSelect(event) {
    console.log(event);
  }
}

This ist the ngx-chart-gauge.html

<ngx-charts-gauge
  [view]="view"
  [scheme]="colorScheme"
  [results]="data"
  [min]="0"
  [max]="100"
  [angleSpan]="240"
  [startAngle]="-120"
  [units]="'Temperature'"
  [bigSegments]="10"
  [smallSegments]="5"
  (select)="onSelect($event)">
</ngx-charts-gauge>

And this is my Service, where i get the data from:

import { Injectable } from '@angular/core';
import { Component, OnInit } from '@angular/core';
import {Paho} from '../../../node_modules/ng2-mqtt/mqttws31';

@Injectable()
export class ClassdataproviderService {

  public name: string;
  public value: string;

  single = [
    {
      name: '1',
      value: '15'
    },
    {
      name: '2',
      value: '20'
    }/*,
    {
      name: '3',
      value: '73'
    }*/
  ];

// Create a client instance
  client: any;
  packet: any;

  constructor() {

    // this.client = new Paho.MQTT.Client('broker.mqttdashboard.com', 8000,  'clientId-FUp9rr6sZS');
    this.client = new Paho.MQTT.Client('wpsdemo.gia.rwth-aachen.de', 8080, 'Steffen');

    this.onMessage();
    this.onConnectionLost();
    // connect the client
    this.client.connect({onSuccess: this.onConnected.bind(this)});
  }

  // called when the client connects
  onConnected() {
    console.log('Connected');
    this.client.subscribe('node/m1/temperature');
    //this.sendMessage('HelloWorld');
  }

  sendMessage(message: string) {
    const packet = new Paho.MQTT.Message(message);
    packet.destinationName = 'node/m1/temperature';
    this.client.send(packet);
  }

  // called when a message arrives
  onMessage() {
    this.client.onMessageArrived = (message: Paho.MQTT.Message) => {
      console.log('Message arrived : ' + message.payloadString);
      this.single.push({name: 'test', value: message.payloadString});
      console.log(this.single);
    };
  }

  // called when the client loses its connection
  onConnectionLost() {
    this.client.onConnectionLost = (responseObject: Object) => {
      console.log('Connection lost : ' + JSON.stringify(responseObject));
    };
  }

When i try to inject the data in the gauge with OnInit, the gauge is not updating. To solve this i tried OnChanges, but now i get the ERROR TypeError: Cannot read property 'big' of undefined...

I dont know if its possible to auto update the gauge automatically without OnChanges or how to avoid the ERR with the OnChanges lifecycle hook?

Body:
Now i tried out many solutions and the most effective is by using an observable, to observe my Service where i get the data from. The Service, which injects the data in the ngx-chart-component, withe the observable, looks like:

import { Injectable } from '@angular/core';
import { Component, OnInit } from '@angular/core';
import {Paho} from '../../../node_modules/ng2-mqtt/mqttws31';
import 'rxjs/add/observable/interval';
import {AddDataService} from './datawindow/addmqtt/formmqtt/addmqtt.service';

@Injectable()
export class ClassdataproviderService {
  public name: string;
  public value: string;

  single = [
    {
      name: '',
      value: ''
    }
  ];

// Create a client instance
  client: any;
  packet: any;

  constructor() {

   this.addDataService.componentMethodCalled$.subscribe(
  () => {
    this.client = new Paho.MQTT.Client('wpsdemo.gia.rwth-aachen.de', 8080, 'Steffen');
    this.onMessage();
    this.onConnectionLost();
    // connect the client
    this.client.connect({onSuccess: this.onConnected.bind(this)});
  }}

  // called when the client connects
  onConnected() {
    console.log('Connected');
    this.client.subscribe('node/m1/temperature');
    //this.sendMessage('HelloWorld');
  }

  sendMessage(message: string) {
    const packet = new Paho.MQTT.Message(message);
    packet.destinationName = 'node/m1/temperature';
    this.client.send(packet);
  }

  // called when a message arrives
  onMessage() {
    this.client.onMessageArrived = (message: Paho.MQTT.Message) => {
      console.log('Message arrived : ' + message.payloadString);
      this.single.push({name: 'test', value: message.payloadString});
      console.log(this.single);
    };
  }

  // called when the client loses its connection
  onConnectionLost() {
    this.client.onConnectionLost = (responseObject: Object) => {
      console.log('Connection lost : ' + JSON.stringify(responseObject));
    };
  }

Now the single array will be updatetd every time i get new data and it works perfectly with ngx-charts.
And use ngOnInit as lifecyclehook in the gauge-component.


问:
Gcov report import in Sonarqube-5.6.6(LTS) using CXX Community Plug-in
Our Sonar Build Environment details as follows:

```<code>SonarQube Server Version - 5.6.6 (64-Bit).
Sonar Client Build Operating System – Ubuntu 14.04.5 LTS (64-Bit).
Sonar-scanner- Version - 3.0.3.778.
sonar-cxx-plugin-0.9.7.jar
Source Code Language: C++
</code>```

Description:-

I have .gcov coverage report. Want to know is it possible to import into Sonarqube dashboard using Cxx community plugin?

If so, kindly help me with the steps. Thanks in advance.

答:
Use absolute filename path in gcovr report solved for me.

sonar config file: sonar-project.properties

```<code>sonar.projectKey=xxx
sonar.sources=src
sonar.host.url=http://xxx:xxx
sonar.login=xxx
sonar.language=c++
sonar.cxx.includeDirectories=xxx
sonar.exclusions=xxx
sonar.cxx.coverage.reportPath=gcovr_report.xml
sonar.cxx.coverage.itReportPath=gcovr_report.xml
sonar.cxx.coverage.overallReportPath=gcovr_report.xml
</code>```

gcov temp file gcda/gcno in directory /xxx/src.

create gcovr xml report: gcovr -r /xxx/src --xml-pretty > gcovr_report.xml

replace filename tag in gcovr_report.xml with absolute path.

run sonar runner: ~/sonar-scanner-3.0.3.778-linux/bin/sonar-scanner -X

ContentLicense: CC BY-SA 4.0

Body:
Our Sonar Build Environment details as follows:

SonarQube Server Version - 5.6.6 (64-Bit).
Sonar Client Build Operating System – Ubuntu 14.04.5 LTS (64-Bit).
Sonar-scanner- Version - 3.0.3.778.
sonar-cxx-plugin-0.9.7.jar
Source Code Language: C++

Description:-

I have .gcov coverage report. Want to know is it possible to import into Sonarqube dashboard using Cxx community plugin?

If so, kindly help me with the steps. Thanks in advance.

Body:
Use absolute filename path in gcovr report solved for me.

sonar config file: sonar-project.properties

sonar.projectKey=xxx
sonar.sources=src
sonar.host.url=http://xxx:xxx
sonar.login=xxx
sonar.language=c++
sonar.cxx.includeDirectories=xxx
sonar.exclusions=xxx
sonar.cxx.coverage.reportPath=gcovr_report.xml
sonar.cxx.coverage.itReportPath=gcovr_report.xml
sonar.cxx.coverage.overallReportPath=gcovr_report.xml

gcov temp file gcda/gcno in directory /xxx/src.

create gcovr xml report: gcovr -r /xxx/src --xml-pretty > gcovr_report.xml

replace filename tag in gcovr_report.xml with absolute path.

run sonar runner: ~/sonar-scanner-3.0.3.778-linux/bin/sonar-scanner -X


问:
Detect duplicate MP3 files with different bitrates and/or different ID3 tags?
How could I detect (preferably with Python) duplicate MP3 files that can be encoded with different bitrates (but they are the same song) and ID3 tags that can be incorrect?

I know I can do an MD5 checksum of the files content but that won't work for different bitrates. And I don't know if ID3 tags have influence in generating the MD5 checksum. Should I re-encode MP3 files that have a different bitrate and then I can do the checksum? What do you recommend?

答:
Re-encoding at the same bit rate won't work, in fact it may make things worse as transcoding (that is what re-encoding at different bitrates is called) is going to change the nature of the compression, you are recompressing an already compressed file is going to lead to a significantly different file.

This is a little out of my league but I would approach the problem by looking at the wave pattern of the MP3. Either by converting the MP3 to an uncompressd .wav or maybe by just running the analysis on the MP3 file itself. There should be a library out there for this. Just a word of warning, this is an expensive operation.

Another idea, use ReplayGain to scan the files. If they are the same song, they should be be tagged with the same gain. This will only work on the exact same song from the exact same album. I know of several cases were reissues are remastered at a higher volume, thus changing the replaygain.

EDIT:

You might want to check out http://www.speech.kth.se/snack/, which apparently can do spectrogram visualization. I imagine any library that can visual spectrogram can help you compare them.

This link from the official python page may also be helpful.

OwnerDisplayName: Antonio Melé

OwnerDisplayName: nemo

LastEditorDisplayName: nemo


问:
pip library is not visible with sudo
I am trying to inatall one of libraries for python (plotly). I used command:

```<code>pip install -U plotly
</code>```

to get permission denied error... okay.
so i put:

```<code>sudo pip install -U plotly
</code>```

to get:

Could not find a version that satisfies the requirement plotly (from versions: )
No matching distribution found for plotly

something is wrong with this debian setup, but I cannot figure out what. To check, I've used same commands for paramiko... all went ok.

答: try using "sudo pip install plotly" tested on ubuntu 17.1 using python 2.7</p>

Title: pip library is not visible with sudo

Body:
I am trying to inatall one of libraries for python (plotly). I used command:

pip install -U plotly

to get permission denied error... okay.
so i put:

sudo pip install -U plotly

to get:

Could not find a version that satisfies the requirement plotly (from versions: )
No matching distribution found for plotly

something is wrong with this debian setup, but I cannot figure out what. To check, I've used same commands for paramiko... all went ok.


问:
asp.net core 2.0 not getting exact path of css or view page
net core 2.0 and i have getting issue to getting full path as shown as given below if you have any idea please give me solution

```<code> string filePath = Path.Combine(Path.Combine(Path.Combine(Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugins"), "Demopath"), "Views"), "DemoViews"), "Views.cshtml");
</code>```

From this i am getting this path

```<code>D:\ILYAS\\nop4.0\Presentation\Nop.Web\bin\Debug\net461\Plugins\Demopath\Views\DemoViews\Views.cshtml
</code>```

But i don't need \bin\Debug\net461\

becuase of this extra line i am not getting my CSS and view page
Is any one have idea please inform me

thank you in advance

答:
Path seems combining proper.
Look at path

```<code>Plugins\Demopath\Views\DemoViews\Views.cshtml
</code>```

it seems merged proper.

Your issue at AppDomain.CurrentDomain.BaseDirectory

You can use store url instead of BaseDirectory or something else.

Or you can go to root directory to Nop.Web

or use direct path using Server.MapPath("YourPath").

Server.MapPath is easy to use multiple time Path.Combine.

Body:
net core 2.0 and i have getting issue to getting full path as shown as given below if you have any idea please give me solution

 string filePath = Path.Combine(Path.Combine(Path.Combine(Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugins"), "Demopath"), "Views"), "DemoViews"), "Views.cshtml");

From this i am getting this path

D:\ILYAS\\nop4.0\Presentation\Nop.Web\bin\Debug\net461\Plugins\Demopath\Views\DemoViews\Views.cshtml

But i don't need \bin\Debug\net461\

becuase of this extra line i am not getting my CSS and view page
Is any one have idea please inform me

thank you in advance

Body:
Path seems combining proper.
Look at path

Plugins\Demopath\Views\DemoViews\Views.cshtml

it seems merged proper.

Your issue at AppDomain.CurrentDomain.BaseDirectory

You can use store url instead of BaseDirectory or something else.

Or you can go to root directory to Nop.Web

or use direct path using Server.MapPath("YourPath").

Server.MapPath is easy to use multiple time Path.Combine.


问:
Java synthetic method and bridge method confusion
As stated in this Java Tutorial a bridge method implies that it is also a synthetic method. The question is, is it possible that invocation of isSynthetic method returns true but isBridge method returns false for a Method object, i.e., if a method is synthetic does it imply that it is also a bridge method?

It's not exactly the same but the source code for isSynthetic and isBridge methods looks like below:

```<code>static final int SYNTHETIC = 0x00001000;
public boolean isSynthetic() {
    return (getModifiers() & SYNTHETIC) != 0;
}

static final int BRIDGE = 0x00000040;
public boolean isBridge() {
    return (getModifiers() & BRIDGE) != 0;
}
</code>```

Why isBridge method body is not like return isSynthetic();?

答:
Bridge is synthetic but synthetic is not necessarily bridge. Example:

```<code>public class Test {

    public Test clone() {
        return null;
    }
</code>```

bytecode outline:

```<code>  // access flags 0x1041
  public synthetic bridge clone()Ljava/lang/Object; throws java/lang/CloneNotSupportedException
   L0
...
</code>```

Body:
As stated in this Java Tutorial a bridge method implies that it is also a synthetic method. The question is, is it possible that invocation of isSynthetic method returns true but isBridge method returns false for a Method object, i.e., if a method is synthetic does it imply that it is also a bridge method?

It's not exactly the same but the source code for isSynthetic and isBridge methods looks like below:

static final int SYNTHETIC = 0x00001000;
public boolean isSynthetic() {
    return (getModifiers() & SYNTHETIC) != 0;
}

static final int BRIDGE = 0x00000040;
public boolean isBridge() {
    return (getModifiers() & BRIDGE) != 0;
}

Why isBridge method body is not like return isSynthetic();?

Body:
Bridge is synthetic but synthetic is not necessarily bridge. Example:

public class Test {

    public Test clone() {
        return null;
    }

bytecode outline:

  // access flags 0x1041
  public synthetic bridge clone()Ljava/lang/Object; throws java/lang/CloneNotSupportedException
   L0
...


问:
Android SDK Ubuntu default path
I am trying to build my Android app in Unity on Ubuntu, but cannot find Android SDK.
What is Android SDK default path on Ubuntu?

答:
The Path will be like,

Linux /home/AccountName/Android/Sdk

For Linux: ~/Android/Sdk

For Mac: ~/Library/Android/sdk

For Windows: %LOCALAPPDATA%\Android\sdk

Title: Android SDK Ubuntu default path


问:
The beginners' error in TypeScript
I'm a beginner in TypeScript and wrote the following code in MVC5 application:

Controller:

```<code>public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }
}
</code>```

View:

@{
    Layout = null;
}

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <title>Index</title>

```

<p>TypeScript:</p>

```class MyClass {
    public render(divId: string, text: string) {
        var el: HTMLElement = document.getElementById(divId);
        el.innerText = text;
    }
}

window.onload = () => {
    var MyClass = new MyClass();
    MyClass.render("cont", "Hello World");
};
```

<p>tsconfig.json:</p>

```{
    "compilerOptions": {
        "noImplicitAny": false,
        "noEmitOnError": true,
        "removeComments": false,
        "sourceMap": true,
        "target": "es6",
        "outDir": "../Scripts"
    },
    "exclude": [
        "node_modules",
        "wwwroot"
    ]
}
```

I've got the following error:

TypeError: MyClass is not a constructor.

How can I run my first TypeScript?

答:
Don't use the same name for the class and the variable, as that will mean in the onload function context MyClass will refer to the variable not the class.

If you hover over the MyClass in new MyClass() you will see the tooltip tell you it is referring to the variable not the class. The reason the compiler did not catch this is that MyClass is implicitly typed to any so it can be a constructor. If you would have used let or const you would have gotten an error, also if you had used the noImplicitAny option.

Title: The beginners' error in TypeScript

Body:
I'm a beginner in TypeScript and wrote the following code in MVC5 application:

Controller:

public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }
}

View:

@{
    Layout = null;
}

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <title>Index</title>

TypeScript:

class MyClass {
    public render(divId: string, text: string) {
        var el: HTMLElement = document.getElementById(divId);
        el.innerText = text;
    }
}

window.onload = () => {
    var MyClass = new MyClass();
    MyClass.render("cont", "Hello World");
};

tsconfig.json:

{
    "compilerOptions": {
        "noImplicitAny": false,
        "noEmitOnError": true,
        "removeComments": false,
        "sourceMap": true,
        "target": "es6",
        "outDir": "../Scripts"
    },
    "exclude": [
        "node_modules",
        "wwwroot"
    ]
}

I've got the following error:

TypeError: MyClass is not a constructor.

How can I run my first TypeScript?


问:
How was this animation made?
i found an interesting effect on this site: https://iohk.io/

If you move your mouse around the effect will follow and change its colors, im really fascinated and wonder if there is a term for this kind of effect i can look into so i can learn how this was done.

While checking the source code i found the term "canvas", but its a huge topic.

Im not a developer myself and only know HTML/CSS right now, so please keep this in mind when answering.

Thanks in Advance.

答:
http://vincentgarreau.com/particles.js/

That is the site from the creator, i haven't look in to it that much but all the information you need should be there.

You can use the menu to the right to change the way it looks.

Title: How was this animation made?


问:
MISRA C-2012 Rule 11.3 violation while trying to do a typecast from char to int pointer
I am trying to get rid of Rule 11.3  from my code.

Sample code:

```<code>static int32_t
do_test(const char *cp)
{
    const char *c = cp;
    const int32_t *x;
    x = (const int32_t *)cp;

    return *x;
}
</code>```

I want the value of *c and *x to be same. Even-though the code is compiling and giving the correct value, "x = (int32_t *)cp;" causing violation of 11.3 and 11.8

Rule 11.3 violation: An object with pointer type shall not be converted to a pointer to a different object type.

I have tried with void pointer, but the result was not same as what I expected and also it resulted in additional violation.

Is there anyway to remove these violations ?

From MISRA C 2012 Document they are mentioning like there is an exception for this rule as it is permitted to convert a pointer to object type into a pointer to one of the object types char, signed char or unsigned char. The Standard guarantees that pointers to these types can be used to access the individual bytes of an object.

Ignore Dir 4.6 due to char type.

答:
You are lucky you are using MISRA-C, because this code is full of bugs. You cannot make the bugs go away with a cast.

Bug 1. The character pointer is not necessarily aligned, in which case your code invokes undefined behavior as per the C standard 6.3.2.3/7:

A pointer to an object type may be converted to a pointer to a different object type. If the resulting pointer is not correctly aligned for the referenced type, the behavior is undefined.

Bug 2. The code contains a blatant strict aliasing violation. This is always undefined behavior as per the C standard 6.5/7.

Your assumption "The Standard guarantees that pointers to these types can be used to access the individual bytes of an object." is correct: as a special exception C allows you to convert from a pointer-to-x to pointer to char and then access the data through the char poiner. But not the other way around.

Your code is not accessing individual bytes; you are going the other way around, from an array of characters to a 32 bit type. This is not allowed. See What is the strict aliasing rule?.

Correct code, that should be ok with both the C language and MISRA-C:

```<code>static int32_t do_test(const char *cp)
{
  return (int32_t) ( ((uint32_t)cp[0] << 24u) |
                     ((uint32_t)cp[1] << 16u) |
                     ((uint32_t)cp[2] <<  8u) |
                     ((uint32_t)cp[3])        );
}
</code>```

This shift version is always preferred, as it is endianess independent and therefore portable. The casts to uint32_t are necessary to prevent implicit promotions on 8/16 bit systems, plus you should never do bit shift on signed types.

Body:
I am trying to get rid of Rule 11.3  from my code.

Sample code:

static int32_t
do_test(const char *cp)
{
    const char *c = cp;
    const int32_t *x;
    x = (const int32_t *)cp;

    return *x;
}

I want the value of *c and *x to be same. Even-though the code is compiling and giving the correct value, "x = (int32_t *)cp;" causing violation of 11.3 and 11.8

Rule 11.3 violation: An object with pointer type shall not be converted to a pointer to a different object type.

I have tried with void pointer, but the result was not same as what I expected and also it resulted in additional violation.

Is there anyway to remove these violations ?

From MISRA C 2012 Document they are mentioning like there is an exception for this rule as it is permitted to convert a pointer to object type into a pointer to one of the object types char, signed char or unsigned char. The Standard guarantees that pointers to these types can be used to access the individual bytes of an object.

Ignore Dir 4.6 due to char type.

Body:
You are lucky you are using MISRA-C, because this code is full of bugs. You cannot make the bugs go away with a cast.

Bug 1. The character pointer is not necessarily aligned, in which case your code invokes undefined behavior as per the C standard 6.3.2.3/7:

A pointer to an object type may be converted to a pointer to a different object type. If the resulting pointer is not correctly aligned for the referenced type, the behavior is undefined.

Bug 2. The code contains a blatant strict aliasing violation. This is always undefined behavior as per the C standard 6.5/7.

Your assumption "The Standard guarantees that pointers to these types can be used to access the individual bytes of an object." is correct: as a special exception C allows you to convert from a pointer-to-x to pointer to char and then access the data through the char poiner. But not the other way around.

Your code is not accessing individual bytes; you are going the other way around, from an array of characters to a 32 bit type. This is not allowed. See What is the strict aliasing rule?.

Correct code, that should be ok with both the C language and MISRA-C:

static int32_t do_test(const char *cp)
{
  return (int32_t) ( ((uint32_t)cp[0] << 24u) |
                     ((uint32_t)cp[1] << 16u) |
                     ((uint32_t)cp[2] <<  8u) |
                     ((uint32_t)cp[3])        );
}

This shift version is always preferred, as it is endianess independent and therefore portable. The casts to uint32_t are necessary to prevent implicit promotions on 8/16 bit systems, plus you should never do bit shift on signed types.


问:
Laravel Ajax Login
I am trying to log in a user with Ajax. I used the following code. But the problem is I can see the validation Error but when I tried to check username & password with existing database I got following Error:

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in
  Sorry User not found

How can I successfully log in a user by avoiding above error?

Login controller:

```<code>protected function login(Request $request)
{
    $validator = Validator::make($request->all(), [
       'email' => 'required|email',
        'password' => 'required',
    ]);

    if ($validator->passes()) {
        if (auth()->attempt(array('email' => $request->input('email'),
          'password' => $request->input('password')),true))
        {
            return response()->json('success');
        }
        return response()->json(['error'=>'Sorry User not found.']);
    }

    return response()->json(['error'=>$validator->errors()->all()]);
}
</code>```

Ajax Part:

```<code>$(document).ready(function() {
    $("#loginBtn").click(function(e) {

        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        e.preventDefault();
        var email = $("input[name='user_email']").val();
        var password = $("input[name='user_password']").val();

        $.ajax({
            url: '{{ route('login') }}',
            type: 'POST',
            data: {
                email: email,
                password: password
            },
            success: function(data) {
                if ($.isEmptyObject(data.error)) {
                    alert(data.success);
                } else {
                    printErrorMsg(data.error);
                }
            }
        });

    });

    function printErrorMsg(msg) {
        $(".print-error-msg-login").find("ul").html('');
        $(".print-error-msg-login").css('display', 'block');
        $.each(msg, function(key, value) {
            $(".print-error-msg-login").find("ul").append('<li>' + value + '</li>');
        });
    }
});
</code>```

答:
Change the format of the response error from

```<code>return response()->json(['error'=>'Sorry User not found.']);
</code>```

to

```<code>return response()->json([
    'error' => [
        'email' => 'Sorry User not found.'
    ]
]);
</code>```

Title: Laravel Ajax Login

Body:
I am trying to log in a user with Ajax. I used the following code. But the problem is I can see the validation Error but when I tried to check username & password with existing database I got following Error:

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in
  Sorry User not found

How can I successfully log in a user by avoiding above error?

Login controller:

protected function login(Request $request)
{
    $validator = Validator::make($request->all(), [
       'email' => 'required|email',
        'password' => 'required',
    ]);

    if ($validator->passes()) {
        if (auth()->attempt(array('email' => $request->input('email'),
          'password' => $request->input('password')),true))
        {
            return response()->json('success');
        }
        return response()->json(['error'=>'Sorry User not found.']);
    }

    return response()->json(['error'=>$validator->errors()->all()]);
}

Ajax Part:

$(document).ready(function() {
    $("#loginBtn").click(function(e) {

        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        e.preventDefault();
        var email = $("input[name='user_email']").val();
        var password = $("input[name='user_password']").val();

        $.ajax({
            url: '{{ route('login') }}',
            type: 'POST',
            data: {
                email: email,
                password: password
            },
            success: function(data) {
                if ($.isEmptyObject(data.error)) {
                    alert(data.success);
                } else {
                    printErrorMsg(data.error);
                }
            }
        });

    });

    function printErrorMsg(msg) {
        $(".print-error-msg-login").find("ul").html('');
        $(".print-error-msg-login").css('display', 'block');
        $.each(msg, function(key, value) {
            $(".print-error-msg-login").find("ul").append('
' + value + '
');
        });
    }
});

Body:
Change the format of the response error from

return response()->json(['error'=>'Sorry User not found.']);

to

return response()->json([
    'error' => [
        'email' => 'Sorry User not found.'
    ]
]);


答:
Having looked at the page I initially thought of WebGL. On inspecting the page my suspicions were confirmed.

The page you linked to is using a ParticlesJS which looks like a library over WebGL. Given you are not a developer then this may be a little beyond you.

Title: How was this animation made?

Body:
i found an interesting effect on this site: https://iohk.io/

If you move your mouse around the effect will follow and change its colors, im really fascinated and wonder if there is a term for this kind of effect i can look into so i can learn how this was done.

While checking the source code i found the term "canvas", but its a huge topic.

Im not a developer myself and only know HTML/CSS right now, so please keep this in mind when answering.

Thanks in Advance.


问:
JAWS screen reader should read only error messages
Currently, I am refreshing the page and focusing on error messages so that jaws can read it. But it is reading all the way from error messages till bottom of the page which is default behavior. Is there any way I can restrict JAWS to read only error messages and not all the text below it?</p>

答:
When talking about accessibility, the default behavior is often the best way to do.

That being said using role=alert seems to be a better way to announce error messages.


问:
IE loads sometimes WOFF and sometimes EOT font type
I use Angular Material with Angular Material Icon.
In my index.html, I have the following tag :

```<code><link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</code>```

This line downloads a CSS file with a @font-face selector. It seems the "src" property coming from the CSS is different according the browser.

With Chrome, no issue, it downloads a WOFF2 font. But on IE11, sometimes the browser downloads a WOFF font and sometimes, a EOT font. With WOFF, icons are displayed. With EOT, they aren't.

Do you have an idea how to force browser to download WOFF font? I would like to avoid to store font-face locally.

Thank you !

答:
Well, I have finally changed the way to use Material Icon font.

I deleted the following line in my index.html file :

```<code><link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</code>```

I installed material-design-icons package via NPM and I configured the styles section of my angular-cli.json file to point on the css file like this :

```<code>"styles": [
    "<relative_path>/node_modules/material-design-icons/iconfont/material-icons.css"
]
</code>```

Now, IE11 always loads WOFF type.

Problem solved!

Body:
I use Angular Material with Angular Material Icon.
In my index.html, I have the following tag :

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

This line downloads a CSS file with a @font-face selector. It seems the "src" property coming from the CSS is different according the browser.

With Chrome, no issue, it downloads a WOFF2 font. But on IE11, sometimes the browser downloads a WOFF font and sometimes, a EOT font. With WOFF, icons are displayed. With EOT, they aren't.

Do you have an idea how to force browser to download WOFF font? I would like to avoid to store font-face locally.

Thank you !

Body:
Well, I have finally changed the way to use Material Icon font.

I deleted the following line in my index.html file :

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

I installed material-design-icons package via NPM and I configured the styles section of my angular-cli.json file to point on the css file like this :

"styles": [
    "<relative_path>/node_modules/material-design-icons/iconfont/material-icons.css"
]

Now, IE11 always loads WOFF type.

Problem solved!


问:
how to resolve Fatal error: Class 'App\Http\Controllers\Controller' not found
I am trying to submit a form to a database using Laravel 5.4 but each time I press the submit button I get this error message:

Fatal error: Class 'App\Http\Controllers\Controller' not found.

Below is my code for controller.php:

```<code><?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

class PagesController extends Controller
{
    public function index()
    {
        return view('./');
    }

    public function about()
    {
        $title='About us';
        return view('pages.about')->with('title',$title);
    }

    public function services()
    {
        $data=array(
            'title'=>'Services',
            'services'=>['Mechanic help','book a mechanic','others']
        );
        return view('pages.services')->with ($data);
    }

    public function create()
    {

    }
}
</code>```

答:
Fatal error: Class 'App\Http\Controllers\Controller' not found.

This error could only mean that you are missing this class. Make sure that you have a Controller.php in the same folder with your PagesController.php. Also, kindly check if you are using the right namespace and be strict with capitalizations.

Body:
I am trying to submit a form to a database using Laravel 5.4 but each time I press the submit button I get this error message:

Fatal error: Class 'App\Http\Controllers\Controller' not found.

Below is my code for controller.php:

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

class PagesController extends Controller
{
    public function index()
    {
        return view('./');
    }

    public function about()
    {
        $title='About us';
        return view('pages.about')->with('title',$title);
    }

    public function services()
    {
        $data=array(
            'title'=>'Services',
            'services'=>['Mechanic help','book a mechanic','others']
        );
        return view('pages.services')->with ($data);
    }

    public function create()
    {

    }
}


问:
How can I change the target framework in Visual studio for Mac?
I want to set the target framework in Visual Studio for Mac because of this problem:

The referenced component 'xxxx' not found for framework .NET Framework
  4.6.1

答: I solve the problem by make my solution target same .NET framework.Because some component use .net core2.0 ,it is higher than others</p>


问:
SQL Table Locking
I have an SQL Server locking question regarding an application we have in house. The application takes submissions of data and persists them into an SQL Server table. Each submission is also assigned a special catalog number (unrelated to the identity field in the table) which is a sequential alpha numeric number. These numbers are pulled from another table and are not generated at run time. So the steps are

Insert Data into Submission Table

Grab next Unassigned Catalog
Number from Catalog Table

Assign the Catalog Number to the
Submission in the Submission table

All these steps happen sequentially in the same stored procedure.

Its, rate but sometimes we manage to get two submission at the same second and they both get assigned the same Catalog Number which causes a localized version of the Apocalypse in our company for a small while.

What can we do to limit the over assignment of the catalog numbers?

答:
When getting your next catalog number, use row locking to protect the time between you finding it and marking it as in use, e.g.:</p>

```<code>set transaction isolation level REPEATABLE READ
begin transaction
select top 1 @catalog_number = catalog_number
  from catalog_numbers with (updlock,rowlock)
  where assigned = 0
update catalog_numbers set assigned = 1 where catalog_number = :catalog_number
commit transaction
</code>```

Title: SQL Table Locking

Body:
When getting your next catalog number, use row locking to protect the time between you finding it and marking it as in use, e.g.:

set transaction isolation level REPEATABLE READ
begin transaction
select top 1 @catalog_number = catalog_number
  from catalog_numbers with (updlock,rowlock)
  where assigned = 0
update catalog_numbers set assigned = 1 where catalog_number = :catalog_number
commit transaction


问:
Elasticsearch list indices sorted by name
How can the following query's results be sorted by index name?</p>

```<code>curl "localhost:9200/_aliases?pretty"
</code>```

答:
You can ask ES to sort the results via the s (sort) searchParameter using s=i or s=index

```<code>curl "localhost:9200/_cat/indices?pretty&s=i"
curl "localhost:9200/_cat/aliases?pretty&s=index"
</code>```

To see the column's headers, add "&v" :

```<code>curl "localhost:9200/_cat/indices?pretty&v&s=index"`.
</code>```

You can find some explanations in the cat/indices documentation

Body:
How can the following query's results be sorted by index name?

curl "localhost:9200/_aliases?pretty"

Body:
You can ask ES to sort the results via the s (sort) searchParameter using s=i or s=index

curl "localhost:9200/_cat/indices?pretty&s=i"
curl "localhost:9200/_cat/aliases?pretty&s=index"

To see the column's headers, add "&v" :

curl "localhost:9200/_cat/indices?pretty&v&s=index"`.

You can find some explanations in the cat/indices documentation


问:
Removing One String CSV elements from another CSV String in java
I am trying to remove elements from one CSV string with other CSV string :

Example:

```<code>String s1= "a,b,c,d,e,f,g,h,w,p,4,5,12,u,v"; /* Base String */

String s2="e,5,v";` /*(input string) This elements has to remove from above string S1 */
</code>```

Expected Output String s1: "a,b,c,d,f,g,h,w,p,4,12,u";

I have Tried:  For loop and remove elements and append back String.

I can to this by no. of ways, but i want to know if there is any library/method/utility available ?

答: You can use StringUtils class from apache commons Reference</p>

Body:
I am trying to remove elements from one CSV string with other CSV string :

Example:

String s1= "a,b,c,d,e,f,g,h,w,p,4,5,12,u,v"; /* Base String */

String s2="e,5,v";` /*(input string) This elements has to remove from above string S1 */

Expected Output String s1: "a,b,c,d,f,g,h,w,p,4,12,u";

I have Tried:  For loop and remove elements and append back String.

I can to this by no. of ways, but i want to know if there is any library/method/utility available ?


问:
Getting window size after the user has altered it in wxPython
I'm trying to find a way to get the horizontal length of a window, just in case the user has altered it, because if I do not do this, the text that I need to show sometimes cuts off. I am using python 3.6.1 on macOS, with the wx (wxPython) library. </p>

答:
Use GetSize() for the widget that you are interested in.

It returns (Width,Height).

Run this code and resize the window.

```<code>import wx

def size_change(event):
    width,height = event.GetSize()
    print ("Width =",width,"Height =",height)

app = wx.App()
frame = wx.Frame(None, -1, 'Get Size Test')
frame.SetSize(500,250)
frame.Bind(wx.EVT_SIZE, size_change)
frame.Show()

print ("Original Size =",frame.GetSize())

app.MainLoop()
</code>```

Body:
Use GetSize() for the widget that you are interested in.

It returns (Width,Height).

Run this code and resize the window.

import wx

def size_change(event):
    width,height = event.GetSize()
    print ("Width =",width,"Height =",height)

app = wx.App()
frame = wx.Frame(None, -1, 'Get Size Test')
frame.SetSize(500,250)
frame.Bind(wx.EVT_SIZE, size_change)
frame.Show()

print ("Original Size =",frame.GetSize())

app.MainLoop()


问:
UIViewController with ARSCNView takes significant time before presenting on screen
I have a UIViewController which uses ARSCNView and adding few elements to it via Scenekit as shown in below example. Everything is working fine except when I call present to show this view controller, it takes a significant time or delay before presenting on the screen.</p>

```<code>@IBOutlet var sceneView: ARSCNView!

override func viewDidLoad() {
    super.viewDidLoad()

    sceneView.showsStatistics =  DebugSettings.isDebugActive

    for (index, coach) in coachPositions.enumerated() {
        let coachGeometry = SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0.005)
        let coachNode = TrainEngineNode(position:  SCNVector3Make(0, Float(index) * 0.1, -0.5), geometry: coachGeometry)
        sceneView.scene.rootNode.addChildNode(coachNode)
    }

    self.sceneView.autoenablesDefaultLighting = true
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    // Create a session configuration
    let configuration = ARWorldTrackingConfiguration()

    // Run the view's session
    sceneView.session.run(configuration)
}
</code>```

答:
if your loop take a long time, you can try this:

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    // start your loading animator

    DispatchQueue.main.async {
        self.sceneView.showsStatistics =  DebugSettings.isDebugActive
        for (index, coach) in self.coachPositions.enumerated() {
            let coachGeometry = SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0.005)
            let coachNode = TrainEngineNode(position:  SCNVector3Make(0, Float(index) * 0.1, -0.5), geometry: coachGeometry)
            self.sceneView.scene.rootNode.addChildNode(coachNode)
        }
        self.sceneView.autoenablesDefaultLighting = true

        // stop loading animator

    }
}
</code>```

If don't work, you can delay time like this:

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    // start your loading animator

    let delayTimeInterval: Double = 0.1 // 0.1 second
    let delayTime = DispatchTime(uptimeNanoseconds: DispatchTime.now().uptimeNanoseconds + UInt64(delayTimeInterval * Double(NSEC_PER_SEC)))
    DispatchQueue.main.asyncAfter(deadline: delayTime) {
        self.sceneView.showsStatistics =  DebugSettings.isDebugActive
        for (index, coach) in self.coachPositions.enumerated() {
            let coachGeometry = SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0.005)
            let coachNode = TrainEngineNode(position:  SCNVector3Make(0, Float(index) * 0.1, -0.5), geometry: coachGeometry)
            self.sceneView.scene.rootNode.addChildNode(coachNode)
        }
        self.sceneView.autoenablesDefaultLighting = true

        // stop loading animator
    }
}
</code>```

Body:
I have a UIViewController which uses ARSCNView and adding few elements to it via Scenekit as shown in below example. Everything is working fine except when I call present to show this view controller, it takes a significant time or delay before presenting on the screen.

@IBOutlet var sceneView: ARSCNView!

override func viewDidLoad() {
    super.viewDidLoad()

    sceneView.showsStatistics =  DebugSettings.isDebugActive

    for (index, coach) in coachPositions.enumerated() {
        let coachGeometry = SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0.005)
        let coachNode = TrainEngineNode(position:  SCNVector3Make(0, Float(index) * 0.1, -0.5), geometry: coachGeometry)
        sceneView.scene.rootNode.addChildNode(coachNode)
    }

    self.sceneView.autoenablesDefaultLighting = true
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    // Create a session configuration
    let configuration = ARWorldTrackingConfiguration()

    // Run the view's session
    sceneView.session.run(configuration)
}

Body:
if your loop take a long time, you can try this:

override func viewDidLoad() {
    super.viewDidLoad()

    // start your loading animator

    DispatchQueue.main.async {
        self.sceneView.showsStatistics =  DebugSettings.isDebugActive
        for (index, coach) in self.coachPositions.enumerated() {
            let coachGeometry = SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0.005)
            let coachNode = TrainEngineNode(position:  SCNVector3Make(0, Float(index) * 0.1, -0.5), geometry: coachGeometry)
            self.sceneView.scene.rootNode.addChildNode(coachNode)
        }
        self.sceneView.autoenablesDefaultLighting = true

        // stop loading animator

    }
}

If don't work, you can delay time like this:

override func viewDidLoad() {
    super.viewDidLoad()

    // start your loading animator

    let delayTimeInterval: Double = 0.1 // 0.1 second
    let delayTime = DispatchTime(uptimeNanoseconds: DispatchTime.now().uptimeNanoseconds + UInt64(delayTimeInterval * Double(NSEC_PER_SEC)))
    DispatchQueue.main.asyncAfter(deadline: delayTime) {
        self.sceneView.showsStatistics =  DebugSettings.isDebugActive
        for (index, coach) in self.coachPositions.enumerated() {
            let coachGeometry = SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0.005)
            let coachNode = TrainEngineNode(position:  SCNVector3Make(0, Float(index) * 0.1, -0.5), geometry: coachGeometry)
            self.sceneView.scene.rootNode.addChildNode(coachNode)
        }
        self.sceneView.autoenablesDefaultLighting = true

        // stop loading animator
    }
}


问:
Replace "bad words" partly with asteriks, ignoring the case and retaining the old case
I have a bad words replace script for VB.net that has caused many issues. After many trial and error, the current code works but will not filter out words that have caps.

```<code>    Private Function CheckForBadWords(ByVal InputString As String) As String
        Dim r As Regex
        Dim element As String
        Dim eLength As Integer
        Dim x As Integer
        Dim AttachtoEnd As String
        For Each element In alWordList
            r = New Regex("\b" & element)
            eLength = element.Length
            For x = 3 To eLength - 1
                AttachtoEnd = AttachtoEnd & "*"
            Next
            InputString = r.Replace(InputString, element, Left(element, 3) & AttachtoEnd)
            AttachtoEnd = ""
        Next
        Return InputString
    End Function
</code>```

How do I make it check for words with caps in them? For example: phuck will get check where as Phuck or PHUCK will not get checked.

I tried following this tutorial but it's in C# and I barely know VB.net:
http://www.dreamincode.net/forums/topic/67129-creating-a-bad-word-filter-functionality-in-aspnet-wc%23/

Adding more detail: with some help this seemed to work after multiple tweaks, but the errors remain, specifically quotes and double quotes or
s.

```<code>    Private Function CheckForBadWords(ByVal InputString As String) As String
        Dim starPosition As Integer = 0
        Dim element As String
        Dim eLength As Integer
        Dim x As Integer
        Dim AttachtoEnd As String
        Dim strArray = InputString.Split(" ")
        Dim specialChars As New List(Of String)(New String() {"@", "!", ".", ",", "(", ")", "/", "#", "$", "&", "+", "-", "_", "=", ":", "'", "*", "^", "`", "<", ">", "[", "]", "{", "}", "\", "|", ControlChars.Quote})
        Dim firstChars As String = ""
        Dim LastChars As String = ""
        InputString = String.Empty
        For Each item As String In strArray
            Dim str As String = item
            firstChars = String.Empty
            LastChars = String.Empty
            For Each ch As Char In str
                If Not specialChars.Contains(ch) Then
                    Exit For
                Else
                    firstChars += ch
                End If
            Next
            For Each spChar As Char In firstChars.ToCharArray()
                str = str.Trim(spChar)
            Next
            For i As Integer = str.Length - 1 To 0 Step -1
                If Not specialChars.Contains(str(i)) Then
                    Exit For
                Else
                    LastChars = str(i) + LastChars
                End If
            Next
            For Each spChar As String In specialChars
                str = str.Trim(spChar)
            Next
            If Not String.IsNullOrWhiteSpace(str) Then
                For Each element In alWordList
                    If element.ToLower = str.ToLower Then
                        str = str.Trim()
                        eLength = element.Length
                        For x = 3 To eLength - 1
                            AttachtoEnd = AttachtoEnd & "*"
                            starPosition += 1
                        Next
                        str = str.Substring(0, str.Length - starPosition) & AttachtoEnd
                    End If
                    AttachtoEnd = ""
                    starPosition = 0
                Next
            End If
            InputString += firstChars + str + LastChars & " "
        Next
        Return InputString
    End Function
</code>```

So now I think it is best to go back to regex, which works really well just need it too handle caps.

A final note... the words to be checked are coming in as an arraylist.

答:
If your initial code works just make the Regex case-insensitive:

```<code>r = New Regex("\b" & element, RegexOptions.IgnoreCase)
</code>```

Case-insensitive means that the Regex does not care about UPPERCASE or lowercase.

For more information see the documentation for the Regular Expression Options.

Body:
I have a bad words replace script for VB.net that has caused many issues. After many trial and error, the current code works but will not filter out words that have caps.

    Private Function CheckForBadWords(ByVal InputString As String) As String
        Dim r As Regex
        Dim element As String
        Dim eLength As Integer
        Dim x As Integer
        Dim AttachtoEnd As String
        For Each element In alWordList
            r = New Regex("\b" & element)
            eLength = element.Length
            For x = 3 To eLength - 1
                AttachtoEnd = AttachtoEnd & "*"
            Next
            InputString = r.Replace(InputString, element, Left(element, 3) & AttachtoEnd)
            AttachtoEnd = ""
        Next
        Return InputString
    End Function

How do I make it check for words with caps in them? For example: phuck will get check where as Phuck or PHUCK will not get checked.

I tried following this tutorial but it's in C# and I barely know VB.net:
http://www.dreamincode.net/forums/topic/67129-creating-a-bad-word-filter-functionality-in-aspnet-wc%23/

Adding more detail: with some help this seemed to work after multiple tweaks, but the errors remain, specifically quotes and double quotes or
s.

    Private Function CheckForBadWords(ByVal InputString As String) As String
        Dim starPosition As Integer = 0
        Dim element As String
        Dim eLength As Integer
        Dim x As Integer
        Dim AttachtoEnd As String
        Dim strArray = InputString.Split(" ")
        Dim specialChars As New List(Of String)(New String() {"@", "!", ".", ",", "(", ")", "/", "#", "$", "&", "+", "-", "_", "=", ":", "'", "*", "^", "`", "<", ">", "[", "]", "{", "}", "\", "|", ControlChars.Quote})
        Dim firstChars As String = ""
        Dim LastChars As String = ""
        InputString = String.Empty
        For Each item As String In strArray
            Dim str As String = item
            firstChars = String.Empty
            LastChars = String.Empty
            For Each ch As Char In str
                If Not specialChars.Contains(ch) Then
                    Exit For
                Else
                    firstChars += ch
                End If
            Next
            For Each spChar As Char In firstChars.ToCharArray()
                str = str.Trim(spChar)
            Next
            For i As Integer = str.Length - 1 To 0 Step -1
                If Not specialChars.Contains(str(i)) Then
                    Exit For
                Else
                    LastChars = str(i) + LastChars
                End If
            Next
            For Each spChar As String In specialChars
                str = str.Trim(spChar)
            Next
            If Not String.IsNullOrWhiteSpace(str) Then
                For Each element In alWordList
                    If element.ToLower = str.ToLower Then
                        str = str.Trim()
                        eLength = element.Length
                        For x = 3 To eLength - 1
                            AttachtoEnd = AttachtoEnd & "*"
                            starPosition += 1
                        Next
                        str = str.Substring(0, str.Length - starPosition) & AttachtoEnd
                    End If
                    AttachtoEnd = ""
                    starPosition = 0
                Next
            End If
            InputString += firstChars + str + LastChars & " "
        Next
        Return InputString
    End Function

So now I think it is best to go back to regex, which works really well just need it too handle caps.

A final note... the words to be checked are coming in as an arraylist.

Body:
If your initial code works just make the Regex case-insensitive:

r = New Regex("\b" & element, RegexOptions.IgnoreCase)

Case-insensitive means that the Regex does not care about UPPERCASE or lowercase.

For more information see the documentation for the Regular Expression Options.


问:
Why does TimeSpan.FromSeconds(double) round to milliseconds?
TimeSpan.FromSeconds takes a double, and can represent values down to 100 nanoseconds, however this method inexplicably rounds the time to whole milliseconds.

Given that I've just spent half an hour to pinpoint this (documented!) behaviour, knowing why this might be the case would make it easier to put up with the wasted time.

Can anyone suggest why this seemingly counter-productive behaviour is implemented?

```<code>TimeSpan.FromSeconds(0.12345678).TotalSeconds
    // 0.123
TimeSpan.FromTicks((long)(TimeSpan.TicksPerSecond * 0.12345678)).TotalSeconds
    // 0.1234567
</code>```

答:
As you've found out yourself, it's a documented feature. It's described in the documentation of TimeSpan:

Parameters

value Type: System.Double

A number of seconds, accurate to the nearest millisecond.

The reason for this is probably because a double is not that accurate at all. It is always a good idea to do some rounding when comparing doubles, because it might just be a very tiny bit larger or smaller than you'd expect. That behaviour could actually provide you with some unexpected nanoseconds when you try to put in whole milliseconds. I think that is the reason they chose to round the value to whole milliseconds and discard the smaller digits.

Body:
TimeSpan.FromSeconds takes a double, and can represent values down to 100 nanoseconds, however this method inexplicably rounds the time to whole milliseconds.

Given that I've just spent half an hour to pinpoint this (documented!) behaviour, knowing why this might be the case would make it easier to put up with the wasted time.

Can anyone suggest why this seemingly counter-productive behaviour is implemented?

TimeSpan.FromSeconds(0.12345678).TotalSeconds
    // 0.123
TimeSpan.FromTicks((long)(TimeSpan.TicksPerSecond * 0.12345678)).TotalSeconds
    // 0.1234567


问:
Android realm can't build javax/annotation/CheckForNull.class
```<code>classpath "io.realm:realm-gradle-plugin:4.2.0"
</code>```

then

```<code>apply plugin: 'realm-android'
</code>```

then build

Error:Execution failed for task
  ':app:transformDexArchiveWithDexMergerForDebug'.

com.android.build.api.transform.TransformException: com.android.tools.r8.errors.CompilationError: Program type already
    present: javax.annotation.CheckReturnValue

more:

```<code>Caused by: java.io.IOException: Duplicate zip entry [32.jar:javax/annotation/CheckForNull.class]
    at proguard.io.JarWriter.getOutputStream(JarWriter.java:138)
    at proguard.io.FilteredDataEntryWriter.getOutputStream(FilteredDataEntryWriter.java:106)
    at proguard.io.FilteredDataEntryWriter.getOutputStream(FilteredDataEntryWriter.java:106)
    at proguard.io.FilteredDataEntryWriter.getOutputStream(FilteredDataEntryWriter.java:92)
</code>```

My Gradle

```<code>dataBinding.enabled = true

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

implementation "com.android.databinding:compiler:3.1.0-alpha04"
annotationProcessor 'com.android.databinding:compiler:3.1.0-alpha04'

implementation 'com.android.support:exifinterface:27.0.2'
implementation 'com.android.support:appcompat-v7:27.0.2'
implementation 'com.android.support:recyclerview-v7:27.0.2'
implementation 'com.android.support:cardview-v7:27.0.2'
implementation 'com.android.support:design:27.0.2'

implementation 'com.android.support.constraint:constraint-layout:1.0.2'
implementation 'com.android.support:multidex:1.0.2'

implementation 'io.reactivex.rxjava2:rxjava:2.0.0-RC2'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.0-RC1'

implementation 'com.squareup.retrofit2:retrofit:2.1.0'
implementation 'com.squareup.retrofit2:converter-scalars:2.0.0'
implementation 'com.squareup.retrofit2:converter-jackson:2.0.0'
implementation 'com.squareup.retrofit2:converter-gson:2.0.2'
implementation 'com.squareup.okhttp3:logging-interceptor:3.3.1'

implementation 'org.greenrobot:eventbus:3.0.0'
implementation 'com.github.bumptech.glide:glide:4.3.1'

implementation 'com.google.firebase:firebase-core:11.6.2'
implementation 'com.google.firebase:firebase-messaging:11.6.2'
implementation 'com.google.firebase:firebase-crash:11.6.2'

implementation 'com.jakewharton.rxbinding:rxbinding:0.4.0'
implementation 'com.wrapp.floatlabelededittext:library:0.0.6'
implementation 'com.dlazaro66.qrcodereaderview:qrcodereaderview:2.0.3'
</code>```

some info:
everything worked like a charm, before I wanted to import the Realm library to my project

答:
You have the same dependency com.android.databinding:compiler:3.1.0-alpha04 with both implementation and annotationProcessor keyword in your build.gradle

With the newer android gradle plugin version you only need to add

```<code>dataBinding {
    enabled = true
}
</code>```

In your android configuration, without adding any dependency as described in the official guide

try to remove implementation "com.android.databinding:compiler:3.1.0-alpha04" and annotationProcessor 'com.android.databinding:compiler:3.1.0-alpha04' and leave android.dataBinding = true, then Clean and Rebuild the project.

Body:
classpath "io.realm:realm-gradle-plugin:4.2.0"

then

apply plugin: 'realm-android'

then build

Error:Execution failed for task
  ':app:transformDexArchiveWithDexMergerForDebug'.

com.android.build.api.transform.TransformException: com.android.tools.r8.errors.CompilationError: Program type already
    present: javax.annotation.CheckReturnValue

more:

Caused by: java.io.IOException: Duplicate zip entry [32.jar:javax/annotation/CheckForNull.class]
    at proguard.io.JarWriter.getOutputStream(JarWriter.java:138)
    at proguard.io.FilteredDataEntryWriter.getOutputStream(FilteredDataEntryWriter.java:106)
    at proguard.io.FilteredDataEntryWriter.getOutputStream(FilteredDataEntryWriter.java:106)
    at proguard.io.FilteredDataEntryWriter.getOutputStream(FilteredDataEntryWriter.java:92)

My Gradle

dataBinding.enabled = true

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

implementation "com.android.databinding:compiler:3.1.0-alpha04"
annotationProcessor 'com.android.databinding:compiler:3.1.0-alpha04'

implementation 'com.android.support:exifinterface:27.0.2'
implementation 'com.android.support:appcompat-v7:27.0.2'
implementation 'com.android.support:recyclerview-v7:27.0.2'
implementation 'com.android.support:cardview-v7:27.0.2'
implementation 'com.android.support:design:27.0.2'

implementation 'com.android.support.constraint:constraint-layout:1.0.2'
implementation 'com.android.support:multidex:1.0.2'

implementation 'io.reactivex.rxjava2:rxjava:2.0.0-RC2'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.0-RC1'

implementation 'com.squareup.retrofit2:retrofit:2.1.0'
implementation 'com.squareup.retrofit2:converter-scalars:2.0.0'
implementation 'com.squareup.retrofit2:converter-jackson:2.0.0'
implementation 'com.squareup.retrofit2:converter-gson:2.0.2'
implementation 'com.squareup.okhttp3:logging-interceptor:3.3.1'

implementation 'org.greenrobot:eventbus:3.0.0'
implementation 'com.github.bumptech.glide:glide:4.3.1'

implementation 'com.google.firebase:firebase-core:11.6.2'
implementation 'com.google.firebase:firebase-messaging:11.6.2'
implementation 'com.google.firebase:firebase-crash:11.6.2'

implementation 'com.jakewharton.rxbinding:rxbinding:0.4.0'
implementation 'com.wrapp.floatlabelededittext:library:0.0.6'
implementation 'com.dlazaro66.qrcodereaderview:qrcodereaderview:2.0.3'

some info:
everything worked like a charm, before I wanted to import the Realm library to my project

Body:
You have the same dependency com.android.databinding:compiler:3.1.0-alpha04 with both implementation and annotationProcessor keyword in your build.gradle

With the newer android gradle plugin version you only need to add

dataBinding {
    enabled = true
}

In your android configuration, without adding any dependency as described in the official guide

try to remove implementation "com.android.databinding:compiler:3.1.0-alpha04" and annotationProcessor 'com.android.databinding:compiler:3.1.0-alpha04' and leave android.dataBinding = true, then Clean and Rebuild the project.


问:
Delete commit on gitlab
How can I delete a commit that I made on GitLab? This commit that I made is not the HEAD now.

If I can't delete it, can I edit?

When it was the HEAD, I tried:

```<code>git reset  --soft HEAD

git reset  --soft HEAD^1

git revert HEAD

git rebase -i HEAD

git rebase -i HEAD~1

git reset --hard HEAD

git reset --hard Id-Code
</code>```

I already tried to rebase it, but it still stays on the branch. Now I just removed it from the HEAD, but it is still there.

There is another command?

答:
git reset --hard CommitId

git push -f origin master

1st command will rest your head to commitid and 2nd command will delete all commit after that commit id on master branch.

Note: Don't forget to add -f in push otherwise it will be rejected.

Title: Delete commit on gitlab

Body:
How can I delete a commit that I made on GitLab? This commit that I made is not the HEAD now.

If I can't delete it, can I edit?

When it was the HEAD, I tried:

git reset  --soft HEAD

git reset  --soft HEAD^1

git revert HEAD

git rebase -i HEAD

git rebase -i HEAD~1

git reset --hard HEAD

git reset --hard Id-Code

I already tried to rebase it, but it still stays on the branch. Now I just removed it from the HEAD, but it is still there.

There is another command?