问:
Class must either be declared abstract or implement abstract method toArray
I have a Foo class that extends AbstractList and implements List. This class implements some of the List methods, but some just throw UnsupportedOperationException.

toArray is one of the later and while the compiler doesn't complain about other not really implemented methods, it complains about the toArray with error:

Class must either be declared abstract or implement abstract method toArray(T[]) in List.

```<code>public class Foo extends AbstractList implementst List  {
    ...
     public <T> T[] toArray(T[] a) throws UnsupportedOperationException {
        throw new UnsupportedOperationException(error);
    }
}
</code>```

What is wrong here and why the compiler still thinks the toArray(T[]) method is not implemented?

答:
This code compiles :

```<code>import java.util.AbstractList;
import java.util.List;

public class Foo extends AbstractList implements List  {

    @Override
    public Object[] toArray(Object[] a) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Object get(int index) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public int size() {
        // TODO Auto-generated method stub
        return 0;
    }
}
</code>```

If you use java.util package.

Body:
I have a Foo class that extends AbstractList and implements List. This class implements some of the List methods, but some just throw UnsupportedOperationException.

toArray is one of the later and while the compiler doesn't complain about other not really implemented methods, it complains about the toArray with error:

Class must either be declared abstract or implement abstract method toArray(T[]) in List.

public class Foo extends AbstractList implementst List  {
    ...
     public <T> T[] toArray(T[] a) throws UnsupportedOperationException {
        throw new UnsupportedOperationException(error);
    }
}

What is wrong here and why the compiler still thinks the toArray(T[]) method is not implemented?

Body:
This code compiles :

import java.util.AbstractList;
import java.util.List;

public class Foo extends AbstractList implements List  {

    @Override
    public Object[] toArray(Object[] a) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Object get(int index) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public int size() {
        // TODO Auto-generated method stub
        return 0;
    }
}

If you use java.util package.


来源: stackexchange

问:
R: sqlAppendTable only works with numbers?
I am unable to get the R language DBI::sqlAppendTable function to work with anything other than numbers. Below is a bit of code illustrating the problem. I suspect the problem is that sqlAppendTable does not quote data. Any fix or workaround would be greatly appreciated.</p>

```<code>num = data.frame(matrix(1:26, ncol=2))
let = data.frame(matrix(letters, ncol=2))

test.sqlAppendTable = function(dfr) {
    #dfr: A data frame.
    conx <- dbConnect(RSQLite::SQLite(), ":memory:")
    on.exit(dbDisconnect(conx))
    dbWriteTable(conx, "temp", dfr[1:5, ])
    temp = dbReadTable(conx, 'temp')
    print(temp)
    sat = sqlAppendTable(conx, 'temp', dfr[6:10, ])
    print(sat)
    rs = dbExecute(conx, sat)
    cat('Result set (rs): ')
    print(rs)
    temp = dbReadTable(conx, 'temp')
    print(temp)
}

test.sqlAppendTable(num) #Runs fine.
test.sqlAppendTable(let) #Generates error:
#Error in rsqlite_send_query(conn@ptr, statement) : no such column: j
</code>```

答:
This looks like a deficiency in the RSQLite package; values should be quoted indeed. Note that the quotes are added in the following example:

DBI::sqlAppendTable(DBI::ANSI(), table = "test", data.frame(a = 1, b = "2"))
#> <SQL> INSERT INTO "test"
#>   ("a", "b")
#> VALUES
#>   (1, '2')
```

See also the corresponding GitHub issue.

ContentLicense: CC BY-SA 3.0

Body:
I am unable to get the R language DBI::sqlAppendTable function to work with anything other than numbers. Below is a bit of code illustrating the problem. I suspect the problem is that sqlAppendTable does not quote data. Any fix or workaround would be greatly appreciated.

num = data.frame(matrix(1:26, ncol=2))
let = data.frame(matrix(letters, ncol=2))

test.sqlAppendTable = function(dfr) {
    #dfr: A data frame.
    conx <- dbConnect(RSQLite::SQLite(), ":memory:")
    on.exit(dbDisconnect(conx))
    dbWriteTable(conx, "temp", dfr[1:5, ])
    temp = dbReadTable(conx, 'temp')
    print(temp)
    sat = sqlAppendTable(conx, 'temp', dfr[6:10, ])
    print(sat)
    rs = dbExecute(conx, sat)
    cat('Result set (rs): ')
    print(rs)
    temp = dbReadTable(conx, 'temp')
    print(temp)
}

test.sqlAppendTable(num) #Runs fine.
test.sqlAppendTable(let) #Generates error:
#Error in rsqlite_send_query(conn@ptr, statement) : no such column: j

Body:
This looks like a deficiency in the RSQLite package; values should be quoted indeed. Note that the quotes are added in the following example:

DBI::sqlAppendTable(DBI::ANSI(), table = "test", data.frame(a = 1, b = "2"))
#> <SQL> INSERT INTO "test"
#>   ("a", "b")
#> VALUES
#>   (1, '2')

See also the corresponding GitHub issue.


问:
SQL Command for removing characters like '!' or '*' from data in a MySQL column
I suspect this to be a relatively easy fix for someone with a greater grasp on SQL.

Some of the data in the 'Name' field of my db have a '!' or '*' in the name, usually at the beginning of the name. I want to remove those unnecessary characters.

Is there an SQL command that will achieve such a lofty goal with alacrity and simplicity?

Thanks in advance.

答:
```<code>SELECT REPLACE(REPLACE(column,'!',''),'*','')
</code>```

perhaps? See http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_replace

ContentLicense: CC BY-SA 2.5

Body:
SELECT REPLACE(REPLACE(column,'!',''),'*','')

perhaps? See http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_replace


问:
How to Forward Values using excel formula
I am making one excel drawsheet for tennis.

As you can see Federer has won 6-2 against opponent, so as I update score player whose value is max should be moved forward to where I have written formula goes here.

I also want the formula to check if the opponent value is Bye. Then the player should be moved to next round as in case 2 Nadal should be forwarded.

I am trying from past 3 days, but I am still not able to get the solution.

Please help.

答:
Hey Ankita just try this,, I've created 2 formula you can use either one,

=if(or(B51<>"Bye", B54<>"Bye"), if(C52>C53, B51, B54)

=IF (and(B51<>"Bye", C52>C53) B51,B54)

Here B51 & B54 carries Name C52 & C53 Score of B51 & B54.

Change cell addresses as you need.


问:
Pointer to device array inside host struct
I'm trying to create a struct that will hold both the host and device arrays in one place and should reside on the host. I later intend expand it to be a element of a linked list. The basic struct looks like this:

```<code>typedef struct Data{
    double *h;
    double *d;
} Data;
</code>```

Where *h points to an array of doubles on the host and *d points to an array of doubles on the device.

There are various answers on SO about copying whole structs to the the device (CUDA cudaMemcpy Struct of Arrays) but none of them quite do what I need. I have the following code but keep getting illegal memory access errors.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "cuda.h"

/*
* CUDA Error stuff
*/

static void HandleError( cudaError_t err,
                         const char *file,
                         int line ) {
    if (err != cudaSuccess) {
        printf( "%s in %s at line %d\n", cudaGetErrorString( err ),
                file, line );
        exit( EXIT_FAILURE );
    }
}
#define HANDLE_ERROR( err ) (HandleError( err, __FILE__, __LINE__ ))

#define HANDLE_NULL( a ) {if (a == NULL) { \
                            printf( "Host memory failed in %s at line %d\n", \
                                    __FILE__, __LINE__ ); \
                            exit( EXIT_FAILURE );}}

//malloc error code
int errMsg(const char *message, int errorCode)
{
    printf("%s\n", message);
    return errorCode;
}

typedef struct Data{
    double *h;
    double *d;
} Data;

__global__ void kernel(Data *d)
{
    int tid = blockIdx.x * blockDim.x + threadIdx.x;
    if(tid<100){
        d->d[tid] = 2;
    }

}

int main()
{
    Data *d;
    d = (Data*)malloc(sizeof(Data));

    d->h = (double*)malloc(sizeof(double)*100);
    HANDLE_ERROR( cudaMalloc((void**) &(d->d), 100*sizeof(double)) );

    for(int i=0; i<100; i++){
        d->h[i] = i;
    }

    HANDLE_ERROR( cudaMemcpy(d->d, d->h, 100*sizeof(double), cudaMemcpyHostToDevice) );

    printf("%f\n", d->h[1]);

    kernel<<<1, 102>>>(d);

    printf("done\n");

    {
    cudaError_t cudaerr = cudaDeviceSynchronize();
    if (cudaerr != cudaSuccess)
        printf("kernel launch failed with error \"%s\"->\n",
               cudaGetErrorString(cudaerr));
    }

    HANDLE_ERROR( cudaMemcpy(d->h, d->d, 100*sizeof(double), cudaMemcpyDeviceToHost) );
    printf("%f\n", d->h[99]);

    return 0;
}
</code>```

The output I get is:

```<code>1.000000
done
kernel launch failed with error "an illegal memory access was encountered"->
an illegal memory access was encountered in linkedListGPU.cu at line 77
</code>```

I suspect I have just messed up my pointers a bit. The error handling code is from the Wiley introduction to CUDA book, if there code is not allowed on here I'll remove it.

Thanks.

答:
The problem is d itself is a pointer to a host-allocated struct (where the d and h pointers are contained.  When you pass the d struct pointer to the kernel like so:

```<code>kernel<<<1, 102>>>(d);
                   ^
                   this is a pointer to memory on the host
</code>```

and then attempt to dereference that pointer in device code here:

```<code>    d->...;
     ^
     This operator dereferences the pointer to the left of it
</code>```

you get an illegal memory access.

There are at least 2 obvious ways to fix this:

Pass the struct by value instead of by pointer.

Here is an example:

```<code>$ cat t1311.cu
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "cuda.h"

/*
* CUDA Error stuff
*/

static void HandleError( cudaError_t err,
                         const char *file,
                         int line ) {
    if (err != cudaSuccess) {
        printf( "%s in %s at line %d\n", cudaGetErrorString( err ),
                file, line );
        exit( EXIT_FAILURE );
    }
}
#define HANDLE_ERROR( err ) (HandleError( err, __FILE__, __LINE__ ))

#define HANDLE_NULL( a ) {if (a == NULL) { \
                            printf( "Host memory failed in %s at line %d\n", \
                                    __FILE__, __LINE__ ); \
                            exit( EXIT_FAILURE );}}

//malloc error code
int errMsg(const char *message, int errorCode)
{
    printf("%s\n", message);
    return errorCode;
}

typedef struct Data{
    double *h;
    double *d;
} Data;

__global__ void kernel(Data d)
{
    int tid = blockIdx.x * blockDim.x + threadIdx.x;
    if(tid<100){
        d.d[tid] = 2;
    }

}

int main()
{
    Data d;

    d.h = (double*)malloc(sizeof(double)*100);
    HANDLE_ERROR( cudaMalloc((void**) &(d.d), 100*sizeof(double)) );

    for(int i=0; i<100; i++){
        d.h[i] = i;
    }

    HANDLE_ERROR( cudaMemcpy(d.d, d.h, 100*sizeof(double), cudaMemcpyHostToDevice) );

    printf("%f\n", d.h[1]);

    kernel<<<1, 102>>>(d);

    printf("done\n");

    {
    cudaError_t cudaerr = cudaDeviceSynchronize();
    if (cudaerr != cudaSuccess)
        printf("kernel launch failed with error \"%s\"->\n",
               cudaGetErrorString(cudaerr));
    }

    HANDLE_ERROR( cudaMemcpy(d.h, d.d, 100*sizeof(double), cudaMemcpyDeviceToHost) );
    printf("%f\n", d.h[99]);

    return 0;
}
$ nvcc -arch=sm_35 -o t1311 t1311.cu
$ cuda-memcheck ./t1311
========= CUDA-MEMCHECK
1.000000
done
2.000000
========= ERROR SUMMARY: 0 errors
$
</code>```

Make a device copy of the struct that the d host pointer points to:

Here is an example:

```<code>$ cat t1311.cu
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "cuda.h"

/*
* CUDA Error stuff
*/

static void HandleError( cudaError_t err,
                         const char *file,
                         int line ) {
    if (err != cudaSuccess) {
        printf( "%s in %s at line %d\n", cudaGetErrorString( err ),
                file, line );
        exit( EXIT_FAILURE );
    }
}
#define HANDLE_ERROR( err ) (HandleError( err, __FILE__, __LINE__ ))

#define HANDLE_NULL( a ) {if (a == NULL) { \
                            printf( "Host memory failed in %s at line %d\n", \
                                    __FILE__, __LINE__ ); \
                            exit( EXIT_FAILURE );}}

//malloc error code
int errMsg(const char *message, int errorCode)
{
    printf("%s\n", message);
    return errorCode;
}

typedef struct Data{
    double *h;
    double *d;
} Data;

__global__ void kernel(Data *d)
{
    int tid = blockIdx.x * blockDim.x + threadIdx.x;
    if(tid<100){
        d->d[tid] = 2;
    }

}

int main()
{
    Data *d, *dev_d;
    d = (Data*)malloc(sizeof(Data));
    HANDLE_ERROR(cudaMalloc(&dev_d, sizeof(Data)));
    d->h = (double*)malloc(sizeof(double)*100);
    HANDLE_ERROR( cudaMalloc((void**) &(d->d), 100*sizeof(double)) );

    for(int i=0; i<100; i++){
        d->h[i] = i;
    }

    HANDLE_ERROR( cudaMemcpy(d->d, d->h, 100*sizeof(double), cudaMemcpyHostToDevice) );
    HANDLE_ERROR(cudaMemcpy(dev_d, d, sizeof(Data), cudaMemcpyHostToDevice));
    printf("%f\n", d->h[1]);

    kernel<<<1, 102>>>(dev_d);

    printf("done\n");

    {
    cudaError_t cudaerr = cudaDeviceSynchronize();
    if (cudaerr != cudaSuccess)
        printf("kernel launch failed with error \"%s\"->\n",
               cudaGetErrorString(cudaerr));
    }

    HANDLE_ERROR( cudaMemcpy(d->h, d->d, 100*sizeof(double), cudaMemcpyDeviceToHost) );
    printf("%f\n", d->h[99]);

    return 0;
}
$ nvcc -arch=sm_35 -o t1311 t1311.cu
$ cuda-memcheck ./t1311
========= CUDA-MEMCHECK
1.000000
done
2.000000
========= ERROR SUMMARY: 0 errors
$
</code>```

As an aside, you can follow the method outlined here to carry your debug process a bit farther.

Body:
I'm trying to create a struct that will hold both the host and device arrays in one place and should reside on the host. I later intend expand it to be a element of a linked list. The basic struct looks like this:

typedef struct Data{
    double *h;
    double *d;
} Data;

Where *h points to an array of doubles on the host and *d points to an array of doubles on the device.

There are various answers on SO about copying whole structs to the the device (CUDA cudaMemcpy Struct of Arrays) but none of them quite do what I need. I have the following code but keep getting illegal memory access errors.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "cuda.h"

/*
* CUDA Error stuff
*/

static void HandleError( cudaError_t err,
                         const char *file,
                         int line ) {
    if (err != cudaSuccess) {
        printf( "%s in %s at line %d\n", cudaGetErrorString( err ),
                file, line );
        exit( EXIT_FAILURE );
    }
}
#define HANDLE_ERROR( err ) (HandleError( err, __FILE__, __LINE__ ))

#define HANDLE_NULL( a ) {if (a == NULL) { \
                            printf( "Host memory failed in %s at line %d\n", \
                                    __FILE__, __LINE__ ); \
                            exit( EXIT_FAILURE );}}

//malloc error code
int errMsg(const char *message, int errorCode)
{
    printf("%s\n", message);
    return errorCode;
}

typedef struct Data{
    double *h;
    double *d;
} Data;

__global__ void kernel(Data *d)
{
    int tid = blockIdx.x * blockDim.x + threadIdx.x;
    if(tid<100){
        d->d[tid] = 2;
    }

}

int main()
{
    Data *d;
    d = (Data*)malloc(sizeof(Data));

    d->h = (double*)malloc(sizeof(double)*100);
    HANDLE_ERROR( cudaMalloc((void**) &(d->d), 100*sizeof(double)) );

    for(int i=0; i<100; i++){
        d->h[i] = i;
    }

    HANDLE_ERROR( cudaMemcpy(d->d, d->h, 100*sizeof(double), cudaMemcpyHostToDevice) );

    printf("%f\n", d->h[1]);

    kernel<<<1, 102>>>(d);

    printf("done\n");

    {
    cudaError_t cudaerr = cudaDeviceSynchronize();
    if (cudaerr != cudaSuccess)
        printf("kernel launch failed with error \"%s\"->\n",
               cudaGetErrorString(cudaerr));
    }

    HANDLE_ERROR( cudaMemcpy(d->h, d->d, 100*sizeof(double), cudaMemcpyDeviceToHost) );
    printf("%f\n", d->h[99]);

    return 0;
}

The output I get is:

1.000000
done
kernel launch failed with error "an illegal memory access was encountered"->
an illegal memory access was encountered in linkedListGPU.cu at line 77

I suspect I have just messed up my pointers a bit. The error handling code is from the Wiley introduction to CUDA book, if there code is not allowed on here I'll remove it.

Thanks.

Body:
The problem is d itself is a pointer to a host-allocated struct (where the d and h pointers are contained.  When you pass the d struct pointer to the kernel like so:

kernel<<<1, 102>>>(d);
                   ^
                   this is a pointer to memory on the host

and then attempt to dereference that pointer in device code here:

    d->...;
     ^
     This operator dereferences the pointer to the left of it

you get an illegal memory access.

There are at least 2 obvious ways to fix this:

Pass the struct by value instead of by pointer.

Here is an example:

$ cat t1311.cu
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "cuda.h"

/*
* CUDA Error stuff
*/

static void HandleError( cudaError_t err,
                         const char *file,
                         int line ) {
    if (err != cudaSuccess) {
        printf( "%s in %s at line %d\n", cudaGetErrorString( err ),
                file, line );
        exit( EXIT_FAILURE );
    }
}
#define HANDLE_ERROR( err ) (HandleError( err, __FILE__, __LINE__ ))

#define HANDLE_NULL( a ) {if (a == NULL) { \
                            printf( "Host memory failed in %s at line %d\n", \
                                    __FILE__, __LINE__ ); \
                            exit( EXIT_FAILURE );}}

//malloc error code
int errMsg(const char *message, int errorCode)
{
    printf("%s\n", message);
    return errorCode;
}

typedef struct Data{
    double *h;
    double *d;
} Data;

__global__ void kernel(Data d)
{
    int tid = blockIdx.x * blockDim.x + threadIdx.x;
    if(tid<100){
        d.d[tid] = 2;
    }

}

int main()
{
    Data d;

    d.h = (double*)malloc(sizeof(double)*100);
    HANDLE_ERROR( cudaMalloc((void**) &(d.d), 100*sizeof(double)) );

    for(int i=0; i<100; i++){
        d.h[i] = i;
    }

    HANDLE_ERROR( cudaMemcpy(d.d, d.h, 100*sizeof(double), cudaMemcpyHostToDevice) );

    printf("%f\n", d.h[1]);

    kernel<<<1, 102>>>(d);

    printf("done\n");

    {
    cudaError_t cudaerr = cudaDeviceSynchronize();
    if (cudaerr != cudaSuccess)
        printf("kernel launch failed with error \"%s\"->\n",
               cudaGetErrorString(cudaerr));
    }

    HANDLE_ERROR( cudaMemcpy(d.h, d.d, 100*sizeof(double), cudaMemcpyDeviceToHost) );
    printf("%f\n", d.h[99]);

    return 0;
}
$ nvcc -arch=sm_35 -o t1311 t1311.cu
$ cuda-memcheck ./t1311
========= CUDA-MEMCHECK
1.000000
done
2.000000
========= ERROR SUMMARY: 0 errors
$

Make a device copy of the struct that the d host pointer points to:

Here is an example:

$ cat t1311.cu
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "cuda.h"

/*
* CUDA Error stuff
*/

static void HandleError( cudaError_t err,
                         const char *file,
                         int line ) {
    if (err != cudaSuccess) {
        printf( "%s in %s at line %d\n", cudaGetErrorString( err ),
                file, line );
        exit( EXIT_FAILURE );
    }
}
#define HANDLE_ERROR( err ) (HandleError( err, __FILE__, __LINE__ ))

#define HANDLE_NULL( a ) {if (a == NULL) { \
                            printf( "Host memory failed in %s at line %d\n", \
                                    __FILE__, __LINE__ ); \
                            exit( EXIT_FAILURE );}}

//malloc error code
int errMsg(const char *message, int errorCode)
{
    printf("%s\n", message);
    return errorCode;
}

typedef struct Data{
    double *h;
    double *d;
} Data;

__global__ void kernel(Data *d)
{
    int tid = blockIdx.x * blockDim.x + threadIdx.x;
    if(tid<100){
        d->d[tid] = 2;
    }

}

int main()
{
    Data *d, *dev_d;
    d = (Data*)malloc(sizeof(Data));
    HANDLE_ERROR(cudaMalloc(&dev_d, sizeof(Data)));
    d->h = (double*)malloc(sizeof(double)*100);
    HANDLE_ERROR( cudaMalloc((void**) &(d->d), 100*sizeof(double)) );

    for(int i=0; i<100; i++){
        d->h[i] = i;
    }

    HANDLE_ERROR( cudaMemcpy(d->d, d->h, 100*sizeof(double), cudaMemcpyHostToDevice) );
    HANDLE_ERROR(cudaMemcpy(dev_d, d, sizeof(Data), cudaMemcpyHostToDevice));
    printf("%f\n", d->h[1]);

    kernel<<<1, 102>>>(dev_d);

    printf("done\n");

    {
    cudaError_t cudaerr = cudaDeviceSynchronize();
    if (cudaerr != cudaSuccess)
        printf("kernel launch failed with error \"%s\"->\n",
               cudaGetErrorString(cudaerr));
    }

    HANDLE_ERROR( cudaMemcpy(d->h, d->d, 100*sizeof(double), cudaMemcpyDeviceToHost) );
    printf("%f\n", d->h[99]);

    return 0;
}
$ nvcc -arch=sm_35 -o t1311 t1311.cu
$ cuda-memcheck ./t1311
========= CUDA-MEMCHECK
1.000000
done
2.000000
========= ERROR SUMMARY: 0 errors
$

As an aside, you can follow the method outlined here to carry your debug process a bit farther.


问:
facebook unity sdk 7.9.4, unity 5.4.1, Error building APK, Error: Fail to repackage resources
I'm using UNITY 5.4.1 and Unity Facebook SDK 7.9.4, but however, unable to build APK.</p>

```<code>ERROR: Command Invocation failure: failed to repackage resources.
CommandInvokationFailure: Failed to re-package resources.
/Users/pb036local/Desktop/build-tools/25.0.2/aapt package --auto-add-overlay -v -f -m -J gen -M AndroidManifest.xml -S "res" -I "/Users/pb036local/Desktop/platforms/android-25/android.jar" -F bin/resources.ap_ --extra-packages android.support.graphics.drawable.animated:android.support.v7.appcompat:android.support.v7.cardview:android.support.customtabs:com.facebook:com.facebook.android:android.support.v4:android.support.graphics.drawable -S "
</code>```

答:
Check for a possible error in your App-ID in Facebook->edit settings -> App ID
In my case, it was a blank space at the end of the appID causing the same problem.faulty app key</p>

Body:
I'm using UNITY 5.4.1 and Unity Facebook SDK 7.9.4, but however, unable to build APK.

ERROR: Command Invocation failure: failed to repackage resources.
CommandInvokationFailure: Failed to re-package resources.
/Users/pb036local/Desktop/build-tools/25.0.2/aapt package --auto-add-overlay -v -f -m -J gen -M AndroidManifest.xml -S "res" -I "/Users/pb036local/Desktop/platforms/android-25/android.jar" -F bin/resources.ap_ --extra-packages android.support.graphics.drawable.animated:android.support.v7.appcompat:android.support.v7.cardview:android.support.customtabs:com.facebook:com.facebook.android:android.support.v4:android.support.graphics.drawable -S "


答:
Use MySQL REPLACE function in a UPDATE query without any WHERE clause like this:

```<code>UPDATE tablename SET Name = REPLACE(Name, '!', '');
UPDATE tablename SET Name = REPLACE(Name, '*', '');
</code>```

To do it in a single query, you can use this:

```<code>UPDATE tablename SET Name = REPLACE(REPLACE(Name, '*', ''), '!', '');
</code>```

Title: SQL Command for removing characters like '!' or '*' from data in a MySQL column

Body:
I suspect this to be a relatively easy fix for someone with a greater grasp on SQL.

Some of the data in the 'Name' field of my db have a '!' or '*' in the name, usually at the beginning of the name. I want to remove those unnecessary characters.

Is there an SQL command that will achieve such a lofty goal with alacrity and simplicity?

Thanks in advance.

Body:
Use MySQL REPLACE function in a UPDATE query without any WHERE clause like this:

UPDATE tablename SET Name = REPLACE(Name, '!', '');
UPDATE tablename SET Name = REPLACE(Name, '*', '');

To do it in a single query, you can use this:

UPDATE tablename SET Name = REPLACE(REPLACE(Name, '*', ''), '!', '');


问:
QThread threadpool
I am trying to write thread poll with QThread.

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

public:
    ThreadPool(int maxThreads);
    void addTask(MyTask *task);
private:
    int maxThreads;
    QMutex mutex;
    QVector<QPair<bool, QThread>> threads;
    QThread *getFreeThread();
public slots:
   void freeThread();
};

void ThreadPool::addTask(MyTask* task)
{
    QThread *thread = getFreeThread();
    task->moveToThread(thread);
    connect(thread, SIGNAL(started()), task, SLOT(doWork()));
    connect(task, SIGNAL(workFinished()), thread, SLOT(quit()));
    connect(thread, SIGNAL(finished()), task, SLOT(deleteLater()));
    connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
    connect(thread, SIGNAL(finished()), this, SLOT(freeThread()));
    thread->start();
}
</code>```

I am creating a limited number of threads in which I want to perform tasks.
However, I do not understand how to get the number of the freed thread.
I know about QThreadPool and Qtconcurrent, but I dont want to use it.
Perhaps, it is worth noting at each thread in QPair's vector is it free or not.

答:
you do not really need a QVector<QPair<bool, QThread>> to keep track of all the threads in your Pool, instead use a QList< QThread* > which holds only the pointers to the free threads.

```<code>private:
     QList<QThread*> freeThreads; // only free threads
     QList<QThread*> allThreads; // just to count the number of all threads
</code>```

In the slot freeThread() use the sender() method from QObject to get the pointer of the signal sender, which in this case will be the QThread, that has become free

```<code>void ThreadPool::freeThread()
{
     // get the pointer to the thread that sent the signal:
     QObject* threadFreed = QObject::sender();
     if( ! freeThreads.contains( threadFreed ) )
     {
          // save the thread pointer in list
          freeThreads << threadFreed;
     }
}
</code>```

Finally getFreeThread() can look like this:

```<code>QThread* getFreeThread()
{
     if( ! freeThreads.isEmpty() )
     {
          // take the first free thread
          return freeThreads.takeFirst();
     }
     else
     {
          if(allThreads.size() < maxThreads )
          {
             // create a new thread
             QThread* thread = new QThread(this);
             allThreads << thread;
             return thread;
          }
          else
          {
            // Maximum number of threads exceeded
            // and no free thread is available
             return NULL;
          }
     }

}
</code>```

Also you should handle the case when a NULL pointer is returned in addTask:

```<code>void ThreadPool::addTask(MyTask* task)
{
    QThread *thread = getFreeThread();
    if( ! thread )
    {
        // do something else
        return;
    }
    // proceed with thread execution ...
}
</code>```

Title: QThread threadpool

Body:
I am trying to write thread poll with QThread.

class ThreadPool: public QObject
{
    Q_OBJECT

public:
    ThreadPool(int maxThreads);
    void addTask(MyTask *task);
private:
    int maxThreads;
    QMutex mutex;
    QVector<QPair<bool, QThread>> threads;
    QThread *getFreeThread();
public slots:
   void freeThread();
};

void ThreadPool::addTask(MyTask* task)
{
    QThread *thread = getFreeThread();
    task->moveToThread(thread);
    connect(thread, SIGNAL(started()), task, SLOT(doWork()));
    connect(task, SIGNAL(workFinished()), thread, SLOT(quit()));
    connect(thread, SIGNAL(finished()), task, SLOT(deleteLater()));
    connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
    connect(thread, SIGNAL(finished()), this, SLOT(freeThread()));
    thread->start();
}

I am creating a limited number of threads in which I want to perform tasks.
However, I do not understand how to get the number of the freed thread.
I know about QThreadPool and Qtconcurrent, but I dont want to use it.
Perhaps, it is worth noting at each thread in QPair's vector is it free or not.

Body:
you do not really need a QVector<QPair<bool, QThread>> to keep track of all the threads in your Pool, instead use a QList< QThread* > which holds only the pointers to the free threads.

private:
     QList<QThread*> freeThreads; // only free threads
     QList<QThread*> allThreads; // just to count the number of all threads

In the slot freeThread() use the sender() method from QObject to get the pointer of the signal sender, which in this case will be the QThread, that has become free

void ThreadPool::freeThread()
{
     // get the pointer to the thread that sent the signal:
     QObject* threadFreed = QObject::sender();
     if( ! freeThreads.contains( threadFreed ) )
     {
          // save the thread pointer in list
          freeThreads << threadFreed;
     }
}

Finally getFreeThread() can look like this:

QThread* getFreeThread()
{
     if( ! freeThreads.isEmpty() )
     {
          // take the first free thread
          return freeThreads.takeFirst();
     }
     else
     {
          if(allThreads.size() < maxThreads )
          {
             // create a new thread
             QThread* thread = new QThread(this);
             allThreads << thread;
             return thread;
          }
          else
          {
            // Maximum number of threads exceeded
            // and no free thread is available
             return NULL;
          }
     }

}

Also you should handle the case when a NULL pointer is returned in addTask:

void ThreadPool::addTask(MyTask* task)
{
    QThread *thread = getFreeThread();
    if( ! thread )
    {
        // do something else
        return;
    }
    // proceed with thread execution ...
}


问:
How i can use functions in multiple files, c++
I have a little problem with using multiple files.
I have a task to use three files: function.h, function.cpp, prog.cpp.

In function.h I defined each function.

In function.cpp I put the code of each function.

In prog.cpp I have to call the functions. There i don't have anything defined.

I have these errors:

```<code>"void __cdecl randInt(int *,int)" (?randInt@@YAXPAHH@Z) already defined in function.obj

"void __cdecl showInt(int *,int)" (?showInt@@YAXPAHH@Z) already defined in function.obj

One or more multiply defined symbols found
</code>```

function.cpp:

```<code>#include <iostream>
using namespace std;

void randInt(int *arr, int size) {
    for (int *i = arr; i < arr + size; i++) {
        *i = rand() % 10;
    }

}
void showInt(int *arr, int size) {
    cout << "Int Massive" << endl;
    for (int *i = arr; i < arr + size; i++) {
        cout << *i << ", ";
    }
    cout << endl;
}
</code>```

function.h:

```<code>#pragma once
void randInt(int *, int);
void showInt(int *, int);
</code>```

prog.cpp:

```<code>#include <iostream>
#include <ctime>;
using namespace std;
#include "function.h"
#include "function.cpp"

int main()
{
    srand(time(0));
    int n = 10;
    int *arrInt = new int[10];
    randInt(&arrInt[0], n);
    showInt(&arrInt[0], n);
    return 0;
}
</code>```

答:
You should edit your file in this way

function.h

```<code>    #pragma once
    void randInt(int *, int);
    void showInt(int *, int);
</code>```

fuction.cpp

```<code>    #include <iostream>
    #include "function.h"
    using namespace std;

    void randInt(int *arr, int size) {
        for (int *i = arr; i < arr + size; i++) {
            *i = rand() % 10;
        }

    }
    void showInt(int *arr, int size) {
        cout << "Int Massive" << endl;
        for (int *i = arr; i < arr + size; i++) {
            cout << *i << ", ";
        }
        cout << endl;
    }
</code>```

prg.cpp

```<code>    #include <iostream>
    #include <ctime>;
    #include "function.h"
    using namespace std;

    int main()
    {
        srand(time(0));
        int n = 10;
        int *arrInt = new int[10];
        randInt(&arrInt[0], n);
        showInt(&arrInt[0], n);
        return 0;
     }
</code>```

Then you can compile your program by linking the prg.cpp with your function.cpp file. If your are using g++ compiler you can do so in way given below.

```<code>    g++ prg.cpp fuction.cpp
</code>```

Body:
I have a little problem with using multiple files.
I have a task to use three files: function.h, function.cpp, prog.cpp.

In function.h I defined each function.

In function.cpp I put the code of each function.

In prog.cpp I have to call the functions. There i don't have anything defined.

I have these errors:

"void __cdecl randInt(int *,int)" (?randInt@@YAXPAHH@Z) already defined in function.obj

"void __cdecl showInt(int *,int)" (?showInt@@YAXPAHH@Z) already defined in function.obj

One or more multiply defined symbols found

function.cpp:

#include <iostream>
using namespace std;

void randInt(int *arr, int size) {
    for (int *i = arr; i < arr + size; i++) {
        *i = rand() % 10;
    }

}
void showInt(int *arr, int size) {
    cout << "Int Massive" << endl;
    for (int *i = arr; i < arr + size; i++) {
        cout << *i << ", ";
    }
    cout << endl;
}

function.h:

#pragma once
void randInt(int *, int);
void showInt(int *, int);

prog.cpp:

#include <iostream>
#include <ctime>;
using namespace std;
#include "function.h"
#include "function.cpp"

int main()
{
    srand(time(0));
    int n = 10;
    int *arrInt = new int[10];
    randInt(&arrInt[0], n);
    showInt(&arrInt[0], n);
    return 0;
}

Body:
You should edit your file in this way

function.h

    #pragma once
    void randInt(int *, int);
    void showInt(int *, int);

fuction.cpp

    #include <iostream>
    #include "function.h"
    using namespace std;

    void randInt(int *arr, int size) {
        for (int *i = arr; i < arr + size; i++) {
            *i = rand() % 10;
        }

    }
    void showInt(int *arr, int size) {
        cout << "Int Massive" << endl;
        for (int *i = arr; i < arr + size; i++) {
            cout << *i << ", ";
        }
        cout << endl;
    }

prg.cpp

    #include <iostream>
    #include <ctime>;
    #include "function.h"
    using namespace std;

    int main()
    {
        srand(time(0));
        int n = 10;
        int *arrInt = new int[10];
        randInt(&arrInt[0], n);
        showInt(&arrInt[0], n);
        return 0;
     }

Then you can compile your program by linking the prg.cpp with your function.cpp file. If your are using g++ compiler you can do so in way given below.

    g++ prg.cpp fuction.cpp


问:
Combine two classes in Java?
I don't know what the right way to ask this but I have two classes I get back from the API that both have name as the thing in common but also have another field that is separate from each other. What is the best way to "combine" them where my User class can get the name but can also get their own variables.

How would my User class look? I'm looking for the User class to have name in-common, the Alien class have alienVariable and the Human class have the humanVariable

My example of two classes

Alien

```<code>@AutoValue
public abstract class Alien implements Parcelable {
    public static Alien create(String alienVariable) {
        return new AutoValue_Alien(alienVariable);
    }

    public static Alien create(String name, String alienVariable) {
        return new AutoValue_Alien(name, alienVariable);
    }

    public static TypeAdapter<Alien> typeAdapter(Gson gson) {
        return new AutoValue_Alien.GsonTypeAdapter(gson);
    }

    @SerializedName("name")
    public abstract String name();

    @Nullable
    @SerializedName("alien_variable")
    public abstract String alienVariable();
}
</code>```

Human

```<code>@AutoValue
public abstract class Human implements Parcelable {
    public static Human create(String humanVariable) {
        return new AutoValue_Human(humanVariable);
    }

    public static Human create(String name, String humanVariable) {
        return new AutoValue_Human(name, humanVariable);
    }

    public static TypeAdapter<Human> typeAdapter(Gson gson) {
        return new AutoValue_Human.GsonTypeAdapter(gson);
    }

    @SerializedName("name")
    public abstract String name();

    @Nullable
    @SerializedName("human_variable")
    public abstract String humanVariable();
}
</code>```

User?

答:
use an interface with name() method in it.

Generally speaking if you have some common properties its better to have a super class rather than interfaces but if fulfill the super class slot then your only choice is interface.

Title: Combine two classes in Java?

Body:
I don't know what the right way to ask this but I have two classes I get back from the API that both have name as the thing in common but also have another field that is separate from each other. What is the best way to "combine" them where my User class can get the name but can also get their own variables.

How would my User class look? I'm looking for the User class to have name in-common, the Alien class have alienVariable and the Human class have the humanVariable

My example of two classes

Alien

@AutoValue
public abstract class Alien implements Parcelable {
    public static Alien create(String alienVariable) {
        return new AutoValue_Alien(alienVariable);
    }

    public static Alien create(String name, String alienVariable) {
        return new AutoValue_Alien(name, alienVariable);
    }

    public static TypeAdapter<Alien> typeAdapter(Gson gson) {
        return new AutoValue_Alien.GsonTypeAdapter(gson);
    }

    @SerializedName("name")
    public abstract String name();

    @Nullable
    @SerializedName("alien_variable")
    public abstract String alienVariable();
}

Human

@AutoValue
public abstract class Human implements Parcelable {
    public static Human create(String humanVariable) {
        return new AutoValue_Human(humanVariable);
    }

    public static Human create(String name, String humanVariable) {
        return new AutoValue_Human(name, humanVariable);
    }

    public static TypeAdapter<Human> typeAdapter(Gson gson) {
        return new AutoValue_Human.GsonTypeAdapter(gson);
    }

    @SerializedName("name")
    public abstract String name();

    @Nullable
    @SerializedName("human_variable")
    public abstract String humanVariable();
}

User?


问:
Very slow postgresql query with deep hierarchy
I have a query where I want to get all transactions for a specific user(owner table) in my database. The database is pretty normalized, so getting from transaction to owner traverses many tables. My tables with relevant foreign keys are as follows:

```<code>**owners**
-------
id

**store_shops**
-----------
id
owner_id

**service_shops**
-------------
id
owner_id

**products**
-------------
id
store_shop_id

**services**
------------
id
service_shop_id

**order_services**
------------------
id
service_id
order_id

**order_products**
------------------
id
product_id
order_id

**orders**
----------
id
transaction_id

**transactions**
----------------
id
refund_transaction_id
amount
</code>```

I have the following query:

```<code>SELECT DISTINCT ON (sales.id) sales.id, sales.amount FROM transactions sales
LEFT OUTER JOIN transactions refunds ON refunds.id = sales.refund_transaction_id
LEFT OUTER JOIN orders ON orders.transaction_id = trans.id OR orders.transaction_id = refunds.id
LEFT OUTER JOIN order_services ON order_services.order_id = orders.id
LEFT OUTER JOIN order_products ON order_products.order_id = orders.id
LEFT OUTER JOIN products ON  products.id = order_products.product_id
LEFT OUTER JOIN services ON services.id = order_services.service_id
LEFT OUTER JOIN service_shops ON service_shops.id = services.service_shop_id
LEFT OUTER JOIN store_shops ON store_shops.id = products.store_shop_id
LEFT OUTER JOIN owners service_shop_owners ON service_shop_owners.id = service_shops.owner_id
LEFT OUTER JOIN owners store_shop_owners ON store_shop_owners.id = store_shops.owner_id
WHERE (service_shop_owners.id = 26930 OR store_shop_owners.id = 26930)
</code>```

This gives me the desired results. Only trouble is that on a dataset of hundreds of thousands of records, it becomes unusably slow.

I'm not very advanced when it comes to SQL, but I realize all the LEFT OUTER JOINs isn't very efficient.

Is there a better way for me to handle this query? Or am I going to have to denormalize the database a bit and store more info in the transaction table?

UPDATE
Using Wyzard's answer below, I now have this query:

```<code>SELECT trans.id, trans.amount, refunds.id
FROM
  service_shops
  JOIN services ON services.service_shop_id = service_shop.id
  JOIN order_services ON order_services.service_id = services_id
  JOIN orders ON orders.id = order_services.order_id
  JOIN transactions trans ON trans.id = orders.transaction_id
  LEFT JOIN transactions refunds ON refunds.id = trans.refund_transaction_id
WHERE service_shops.owner_id = 26930
UNION
SELECT trans.id, trans.amount, refunds.id
FROM
  store_shops
  JOIN products ON store_shops.id = products.store_shop_id
  JOIN order_products ON order_products.product_id = products.id
  JOIN orders ON orders.id = order_products.order_id
  JOIN transactions trans ON trans.id = orders.transaction_id
  LEFT JOIN transactions refunds ON refunds.id = trans.refund_transaction_id
WHERE store_shops.owner_id = 2693
</code>```

This is very fast and a big improvement. Only problem now is that the two LEFT JOIN transactions refunds ON refunds.id = trans.refund_transaction_id do not seem to be grabbing associated refund transactions. I'm assuming this is because they do not have an order associated directly with them, so the WHERE clause filters them out.

答:
First of all, EXPLAIN is your friend: it tells you about the query plan that the database will use to run the query, so you can see where the bottlenecks are.  The output can be difficult to understand at first, but if you use pgAdmin, its EXPLAIN menu command command gives you a nice graphical visualization that's much more intuitive.

Second, the values used in your WHERE clause are at the end of a long chain of outer joins, which is inefficient because the database probably has to do all the joins and produce every candidate row just to get the owner IDs, only to discard most of the rows because the owner IDs don't match the WHERE condition.

It looks like you've structured the query this way because there are two separate paths from a sale to an owner: via products, or via services.  This means you're basically doing two different queries at once, in a way that forces the database to process the product-related join conditions on rows that actually came from services, and vice versa.  It'll probably be much more efficient to actually do two separate queries using UNION, and start each one from the table that you're using for filtering:

```<code>SELECT col1, col2, etc
FROM
  owners
  JOIN service_shops ON service_shops.owner_id = owners.id
  JOIN services ON services.service_shop_id = service_shop.id
  ...etc...
WHERE owners.id = 26930
UNION
SELECT col1, col2, etc
FROM
  owners
  JOIN store_shops ON store_shops.owner_id = owners.id
  JOIN products ON store_shops.id = products.store_shop_id
  ...etc...
WHERE owners.id = 26930
</code>```

This should allow the database to quickly look up the owner using an index, then quickly look up the associated shops using another index, and so on.  (That's assuming you have indexes on your FK columns, like service_shops.owner_id.  If not, you should.)

Note that I've written JOIN instead of LEFT OUTER JOIN.  Since you're not mixing both product data and service data in the same query, you won't have product-related rows that can't be joined to a service-related table, or vice versa, so you probably don't need outer joins at all.

Also, if you don't need any attributes from the owners table besides the ID, you can leave that table out of the query.  Just do WHERE store_shops.owner_id = 26930.

Third, I've found that it helps to structure the FROM clause to use outer joins only where they're actually needed.  Suppose you've written:

```<code>FROM
  foo
  LEFT JOIN bar ON bar.foo_id = foo.id
  LEFT JOIN baz ON baz.bar_id = bar.id
</code>```

Let's suppose that you need to get the foo data even if it has no associated bar, but you don't need the bar data if it has no associated baz — or maybe you know there'll never be a bar without an associated baz.  In that case you can rewrite the query like this:

```<code>FROM
  foo
  LEFT JOIN (
    bar
    JOIN baz ON baz.bar_id = bar.id
  ) ON bar.foo_id = foo.id
</code>```

In my experience, this tends to be more efficient in PostgreSQL.  (I don't know about other databases.)

Body:
I have a query where I want to get all transactions for a specific user(owner table) in my database. The database is pretty normalized, so getting from transaction to owner traverses many tables. My tables with relevant foreign keys are as follows:

**owners**
-------
id

**store_shops**
-----------
id
owner_id

**service_shops**
-------------
id
owner_id

**products**
-------------
id
store_shop_id

**services**
------------
id
service_shop_id

**order_services**
------------------
id
service_id
order_id

**order_products**
------------------
id
product_id
order_id

**orders**
----------
id
transaction_id

**transactions**
----------------
id
refund_transaction_id
amount

I have the following query:

SELECT DISTINCT ON (sales.id) sales.id, sales.amount FROM transactions sales
LEFT OUTER JOIN transactions refunds ON refunds.id = sales.refund_transaction_id
LEFT OUTER JOIN orders ON orders.transaction_id = trans.id OR orders.transaction_id = refunds.id
LEFT OUTER JOIN order_services ON order_services.order_id = orders.id
LEFT OUTER JOIN order_products ON order_products.order_id = orders.id
LEFT OUTER JOIN products ON  products.id = order_products.product_id
LEFT OUTER JOIN services ON services.id = order_services.service_id
LEFT OUTER JOIN service_shops ON service_shops.id = services.service_shop_id
LEFT OUTER JOIN store_shops ON store_shops.id = products.store_shop_id
LEFT OUTER JOIN owners service_shop_owners ON service_shop_owners.id = service_shops.owner_id
LEFT OUTER JOIN owners store_shop_owners ON store_shop_owners.id = store_shops.owner_id
WHERE (service_shop_owners.id = 26930 OR store_shop_owners.id = 26930)

This gives me the desired results. Only trouble is that on a dataset of hundreds of thousands of records, it becomes unusably slow.

I'm not very advanced when it comes to SQL, but I realize all the LEFT OUTER JOINs isn't very efficient.

Is there a better way for me to handle this query? Or am I going to have to denormalize the database a bit and store more info in the transaction table?

UPDATE
Using Wyzard's answer below, I now have this query:

SELECT trans.id, trans.amount, refunds.id
FROM
  service_shops
  JOIN services ON services.service_shop_id = service_shop.id
  JOIN order_services ON order_services.service_id = services_id
  JOIN orders ON orders.id = order_services.order_id
  JOIN transactions trans ON trans.id = orders.transaction_id
  LEFT JOIN transactions refunds ON refunds.id = trans.refund_transaction_id
WHERE service_shops.owner_id = 26930
UNION
SELECT trans.id, trans.amount, refunds.id
FROM
  store_shops
  JOIN products ON store_shops.id = products.store_shop_id
  JOIN order_products ON order_products.product_id = products.id
  JOIN orders ON orders.id = order_products.order_id
  JOIN transactions trans ON trans.id = orders.transaction_id
  LEFT JOIN transactions refunds ON refunds.id = trans.refund_transaction_id
WHERE store_shops.owner_id = 2693

This is very fast and a big improvement. Only problem now is that the two LEFT JOIN transactions refunds ON refunds.id = trans.refund_transaction_id do not seem to be grabbing associated refund transactions. I'm assuming this is because they do not have an order associated directly with them, so the WHERE clause filters them out.

Body:
First of all, EXPLAIN is your friend: it tells you about the query plan that the database will use to run the query, so you can see where the bottlenecks are.  The output can be difficult to understand at first, but if you use pgAdmin, its EXPLAIN menu command command gives you a nice graphical visualization that's much more intuitive.

Second, the values used in your WHERE clause are at the end of a long chain of outer joins, which is inefficient because the database probably has to do all the joins and produce every candidate row just to get the owner IDs, only to discard most of the rows because the owner IDs don't match the WHERE condition.

It looks like you've structured the query this way because there are two separate paths from a sale to an owner: via products, or via services.  This means you're basically doing two different queries at once, in a way that forces the database to process the product-related join conditions on rows that actually came from services, and vice versa.  It'll probably be much more efficient to actually do two separate queries using UNION, and start each one from the table that you're using for filtering:

SELECT col1, col2, etc
FROM
  owners
  JOIN service_shops ON service_shops.owner_id = owners.id
  JOIN services ON services.service_shop_id = service_shop.id
  ...etc...
WHERE owners.id = 26930
UNION
SELECT col1, col2, etc
FROM
  owners
  JOIN store_shops ON store_shops.owner_id = owners.id
  JOIN products ON store_shops.id = products.store_shop_id
  ...etc...
WHERE owners.id = 26930

This should allow the database to quickly look up the owner using an index, then quickly look up the associated shops using another index, and so on.  (That's assuming you have indexes on your FK columns, like service_shops.owner_id.  If not, you should.)

Note that I've written JOIN instead of LEFT OUTER JOIN.  Since you're not mixing both product data and service data in the same query, you won't have product-related rows that can't be joined to a service-related table, or vice versa, so you probably don't need outer joins at all.

Also, if you don't need any attributes from the owners table besides the ID, you can leave that table out of the query.  Just do WHERE store_shops.owner_id = 26930.

Third, I've found that it helps to structure the FROM clause to use outer joins only where they're actually needed.  Suppose you've written:

FROM
  foo
  LEFT JOIN bar ON bar.foo_id = foo.id
  LEFT JOIN baz ON baz.bar_id = bar.id

Let's suppose that you need to get the foo data even if it has no associated bar, but you don't need the bar data if it has no associated baz — or maybe you know there'll never be a bar without an associated baz.  In that case you can rewrite the query like this:

FROM
  foo
  LEFT JOIN (
    bar
    JOIN baz ON baz.bar_id = bar.id
  ) ON bar.foo_id = foo.id

In my experience, this tends to be more efficient in PostgreSQL.  (I don't know about other databases.)


问:
What does Apache Cave solve
I currently use karaf with artifactory as my osgi jar repository. This works well. I have come across the Apache Cave tool for Karaf which very much looks like a repository except that it can also be stored in a database or other datasource instead of a filesystem.

What value does this provide. What are some of the usecases that can be solved using Cave

答:
Disclaimer: I'm not involved in development of OSGi specs or Apache Cave. Everything below is only my conclusions based on personal experience.

Apache Cave is reference implementation of OSGi Repository spec. The latter in turn solves problems of OSGi bundles provisioning. It is supposed to work in the following way: it provides a repository descriptor, which defines a set of resources (usually they are bundles), capabilities they provide, and requirements they require. This meta-information is used to automatically provision dependencies when you deploy some resource.

Details are explained in the specification https://osgi.org/download/r6/osgi.cmpn-6.0.0.pdf, section 132.

Situation around OSGi repository seems quite shady for me. Apache Cave is a provider of OSGi repository, but I didn't found any suitable client for it. My question, Karaf Cave vs org.apache.felix.bundlerepository, still remain unanswered.

There are several alternatives. Apache Felix has its own implementation (org.apache.felix.bundlerepository), which is very similar by concept, but not fully compatible with the spec (info may be outdated and needs check). Karaf solves the same problem with Features facility.

Title: What does Apache Cave solve


问:
can't access camera parameters as the class is deprecated
it  may look like duplicate question but there is no code available to access camera or flashlight. whatever code available is old camera(android.hardware.Camera) class which is deprecated now.there is no new code for accessing the new camera class(android.hardware.camera2).so if anyone can help,it would be of great help for me.</p>

答:
There is a chance as you say but I think the old code will work and you are facing issues because of Android runtime permission from Marshmallow and above.

Try using runtime permission and tell if the error occurs.


问:
Alternatives to the Turing Test
So we learned a bit about the Turing Test in my AI class.  This got me thinking about it.  I can see a few limitations with it:

It's limited to a certain context.  What if I'm not designing an AI to converse with humans?

It favors acting humanly over acting rationally.  For example, if I'm designing an AI to control nuclear missiles, do I really want it to act human?  Granted, this is an extreme example, but you get the idea.

It could be influenced by factors that don't indicate that the computer can think humanly.  For example, suppose I ask what 2334 * 321 is.  I could tell if the device is a computer because it will probably answer me fairly quickly while a human would have to figure it out.  The solution?  Make the computer pause.

Now, I'm sure that the Turing Test still has its place in determining machine intelligence.  But I see it as being fairly limited in scope.  Are there any alternatives?  For that matter, am I wrong as to what I perceive to be its limitations?

EDIT:  Let me be clear:  I'm not suggesting that the Turing Test should be abandoned.  I'm just curious if there are any other tests that overcome its limitations (probably trading them for other limitations).

答:
There should be alternatives, in a way the Turing test measures AI up against "human intelligence" which isn't the only possible type. We're mostly intelligent, but often just barely ahead of creatures like dogs, who have their own type of "intelligence" and their own form of "logic". If you questioned an AI that could pass the Turning test long enough, you'd expect like any other human that it would be wrong about a few things. None of us is perfect, that is intrinsically built into our existence (Turing tests can fail from both sides).

The following post might be interesting: The Necessity of Determinism, since it questions the underlying need for artificial intelligence anyways.

As for an alternative, it would be interesting to have a test that compares some "intelligent" behavior at various different levels, such as insects, dogs, humans and above. The real issue is how the intelligence behaves at it's edges. It's the dynamic behavior of humans to be able to work their way through things, even when they don't have enough information that is one of our defining properties. You'd notice the computer by the way it screws up, not by the way it works (which is trying to mimic people).

So if you're really looking for intelligence, it becomes an issue of how dynamically the system works when the system is dysfunctional. If you'd can't tell what the error conditions are, then it is dynamic enough to handle an infinitely large amount of input. If there is some input that causes an obvious change in output, then it's not dynamic enough.

Beyond being dynamic, you could measure the quality of the "thinking" itself. As the "thought" is more logical and rational, it moves up to a higher-order existence that spans insects, dogs, people, Vulcans (yes, from Star Trek), to pure math. We're not the only intelligent beings, we're just way more logical and rational than the other creatures. Turing presumed we were at the peak, but I that is easily debatable. A good test could show the true level of intelligence.

Paul.

OwnerDisplayName: Jason Baker

Title: Alternatives to the Turing Test

LastEditorDisplayName: Rob

OwnerDisplayName: Paul W Homer


问:
Win32 registry key writable by Everyone?
Is there a Registry key which is allowed for write access to any users and is shared among them?

I need to store some machine-specific data in my application, but this piece of data must be machine-dependent, not logged-user-depended. HKEY_LOCAL_MACHINE is only writable by Administrator. HKEY_CURRENT_USER is allowed for write, but is not shared with other users.

I think that in Windows filesystem folder C:\ProgramData (environment variable %ALLUSERSPROFILE%) is writable for anyone and is shared, but does Registry has something similar?

答: Nope.  There are only two persistent hives: HKLM and HKU.  As there are no shared hives under HKU you would have to store shared data somewhere under HKLM.  You can create your key and give it a security descriptor allowing Everyone full access.</p>


问:
How to extract portion of a line in ruby?
I have a line say

line = "start running at Sat April 1 07:30:37 2017"

and I want to extract

"Sat April 1 07:30:37 2017"

I tried this...

```<code>line = "start running at Sat April 1 07:30:37 2017"
if (line =~ /start running at/)
   line.split("start running at ").last
end
</code>```

... but is there any other way of doing this?

答:
Here's another (as it turns out, slightly faster) option using #partition:

```<code># will return empty string if there is no match, instead of raising an exception like split.last will
line.partition('start running at ').last
</code>```

I was interested how this performs against regexp match, so here's a quick benchmark with 1 million executions each:

```<code>line.sub(/start running at (.*)/, '\1')
# => @real=1.7465

line.partition('start running at ').last
# => @real=0.712406
# => this is faster, but you'd need to be calling this quite a bit for it to make a significant difference
</code>```

Bonus: it also makes it really easy to cater for a more general case e.g. if you have lines that start with "start running at" and others that start with "stop running at". Then something like line.partition(' at ').last will cater for both (and actually run slightly faster).

Body:
I have a line say

line = "start running at Sat April 1 07:30:37 2017"

and I want to extract

"Sat April 1 07:30:37 2017"

I tried this...

line = "start running at Sat April 1 07:30:37 2017"
if (line =~ /start running at/)
   line.split("start running at ").last
end

... but is there any other way of doing this?

Body:
Here's another (as it turns out, slightly faster) option using #partition:

# will return empty string if there is no match, instead of raising an exception like split.last will
line.partition('start running at ').last

I was interested how this performs against regexp match, so here's a quick benchmark with 1 million executions each:

line.sub(/start running at (.*)/, '\1')
# => @real=1.7465

line.partition('start running at ').last
# => @real=0.712406
# => this is faster, but you'd need to be calling this quite a bit for it to make a significant difference

Bonus: it also makes it really easy to cater for a more general case e.g. if you have lines that start with "start running at" and others that start with "stop running at". Then something like line.partition(' at ').last will cater for both (and actually run slightly faster).


问:
Presto create table with 'with' queries
typically to create a table in Presto (from existing db tables), I do:

```<code>create table abc as (
select...
)
</code>```

But to make my code simple, I've broken out subqueries like this:

```<code>with sub1 as (
select...
),

sub2 as (
select...
),

sub3 as (
select...
)

select
from sub1 join sub2 on ...
          join sub3 on ...
</code>```

Where do I put the create table statement here? The actual query is more complex than the above so I am trying to avoid having to put the subqueries within the main query.

答:
Syntax is just as if you prepend create table .. as to the select. E.g. the following worked for me on Presto 0.170:

```<code>create table memory.default.a as
with w as (
    select * from (values 1) t(x)
)
select * from w;
</code>```

(I use experimental memory connector so that this is copy-pastable to try it out.)

Title: Presto create table with 'with' queries

Body:
typically to create a table in Presto (from existing db tables), I do:

create table abc as (
select...
)

But to make my code simple, I've broken out subqueries like this:

with sub1 as (
select...
),

sub2 as (
select...
),

sub3 as (
select...
)

select
from sub1 join sub2 on ...
          join sub3 on ...

Where do I put the create table statement here? The actual query is more complex than the above so I am trying to avoid having to put the subqueries within the main query.

Body:
Syntax is just as if you prepend create table .. as to the select. E.g. the following worked for me on Presto 0.170:

create table memory.default.a as
with w as (
    select * from (values 1) t(x)
)
select * from w;

(I use experimental memory connector so that this is copy-pastable to try it out.)


问:
heroku: run this app correctly?
I am recently using the rubymine(ruby on rails 4) to create web pages and once I have finished some functions and run correctly,I push my code to heroku, so I can directly run the app on the heroku.

The problem is that every function could run correctly on the heroku just like running it at local except one: There is a link in one page called "calendar" to a calendar function,I can run it correctly at local, but on heroku, it goes wrong saying "we are sorry but something went wrong"

enter image description here

someone can explain to me how could it happen? Is it a bug of the heroku system, like a compatibility issue? I have push my code to heroku and run correctly many times and it won't be wrong in the push process.

here is my heroku link: https://dashboard.heroku.com/apps/clients-to-horse

答:
Sugession

I will recommend you, please run your application on local in production mode(environment) after assets precompile, if everything will work properly then I am sure on Heroku will run also.

After deploy on Heroku make sure for migration and assets precompile for Heroku.

You are saying error as "we are sorry but something went wrong", this always comes when we miss something from our side or code bug in the application.

Title: heroku: run this app correctly?


问:
GIT Ignore and GIT Hook - File is replaced after a commit-push
My GIT repository is located /var/repo/myRepo.git. I set a GIT hook post-receive* to copy the files from my repository to the folder of my project

git --work-tree=/var/www/laravel --git-dir=/var/repo/myRepo.git checkout -f

Each time I commit and push something on the server, the file var/www/laravel/config/services.php is replaced and the modification I did on the server is replaced by my local copy.

For instance, if I manually modify the following file like this on the server (by ssh session)

var/www/laravel/config/services.php

This is the modified content of this file

It will be like that after a commit and push

var/www/laravel/config/services.php

This is the default content of this file

I tried to add /config/services.php to my .gitignore but it does not seem to work.

.gitignore

```<code>/node_modules
/public/storage
/public/hot
/storage/*.key
/vendor
/.idea
Homestead.json
Homestead.yaml
.env
/config/services.php
</code>```

What should I do so this file is not replaced each time I commit something on my server ?

答:
What should I do so this file is not replaced each time I commit something on my server?

You have only two options:

don't check it in, or

don't check it out.

Your git checkout -f command means "get me the latest commit, overwriting everything."  If the latest commit has a new version of a file, that overwrites the old version of the file.

(Moreover, a .gitignore file does not mean what you think it means.  It's not a list of files to ignore.  It's a list of files—or name patterns—not to complain about.  Usually most important, it lets you declare to Git: "Yes, I know these are in my work-tree and not in my index; don't tell me that."  That's on the input side—i.e., the "don't check it in" part.)

This leads to a general rule about configurable software, where the software itself is maintained in Git, or indeed any version control system: Do not put the configuration into the version control system.  The configuration is not part of the software.

Consider Git itself, for instance.  You must configure Git to tell it your user.name and user.email in order to make commits with your user-name and email address.  Now imagine Git came with its configuration file built into the software, that said your user name is Fred and your email is fred@fred.fred.  Every time you updated Git to a new version, it would change your name back to "Fred <fred@fred.fred>".  That's not very friendly, is it?

Git stores your configuration outside of the Git software.  There are, to be sure, default configuration entries, but anything you set, is kept elsewhere.  Updating Git does not touch this.  This is not specific to Git, or even version-control systems: any system that provides upgrades must not store its configuration in a file that is destroyed by the upgrade.

So, stop doing that.

Body:
My GIT repository is located /var/repo/myRepo.git. I set a GIT hook post-receive* to copy the files from my repository to the folder of my project

git --work-tree=/var/www/laravel --git-dir=/var/repo/myRepo.git checkout -f

Each time I commit and push something on the server, the file var/www/laravel/config/services.php is replaced and the modification I did on the server is replaced by my local copy.

For instance, if I manually modify the following file like this on the server (by ssh session)

var/www/laravel/config/services.php

This is the modified content of this file

It will be like that after a commit and push

var/www/laravel/config/services.php

This is the default content of this file

I tried to add /config/services.php to my .gitignore but it does not seem to work.

.gitignore

/node_modules
/public/storage
/public/hot
/storage/*.key
/vendor
/.idea
Homestead.json
Homestead.yaml
.env
/config/services.php

What should I do so this file is not replaced each time I commit something on my server ?


问:
How to add images in GUI using Eclipse? This code is not showing images
Here is the code where I want to import pictures and I want to display them on Java GUI.</p>

```<code>AddingImages(){
    setLayout(new FlowLayout());

    image1 = new ImageIcon(getClass().getResource("Capture1.PNG"));

    label1 = new JLabel("Image 1");
    add(label1);

    image2= new ImageIcon(getClass().getResource("Capture1.PNG"));

    label2 = new JLabel("Image 2");
    add(label2);
}

    public static void main(String[] args){
    AddingImages ai = new AddingImages();
    ai.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    ai.setVisible(true);
    ai.pack();
    ai.setTitle("Adding Images in GUI");
}
}
</code>```

答:
```<code>image1 = new ImageIcon(getClass().getResource("Capture1.PNG"));
label1 = new JLabel("Image 1");
add(label1);
</code>```

Where do you actually add the Icon to the JLabel?

The Code should be:

```<code>label1 = new JLabel("Image 1");
label1.setIcon( image1 );
</code>```

Body:
Here is the code where I want to import pictures and I want to display them on Java GUI.

AddingImages(){
    setLayout(new FlowLayout());

    image1 = new ImageIcon(getClass().getResource("Capture1.PNG"));

    label1 = new JLabel("Image 1");
    add(label1);

    image2= new ImageIcon(getClass().getResource("Capture1.PNG"));

    label2 = new JLabel("Image 2");
    add(label2);
}

    public static void main(String[] args){
    AddingImages ai = new AddingImages();
    ai.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    ai.setVisible(true);
    ai.pack();
    ai.setTitle("Adding Images in GUI");
}
}

Body:
image1 = new ImageIcon(getClass().getResource("Capture1.PNG"));
label1 = new JLabel("Image 1");
add(label1);

Where do you actually add the Icon to the JLabel?

The Code should be:

label1 = new JLabel("Image 1");
label1.setIcon( image1 );


问:
Printing out a 2D array in matrix format
How can I print out a simple int[][] in the matrix box format like the format in which we handwrite matrices in. A simple run of loops doesn't apparently work. If it helps I'm trying to compile this code in a linux ssh terminal.

for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
        System.out.println(matrix[i][j] + " ");
    }
    System.out.println();
}
```

答:
Here's my efficient approach for displaying 2D integer array using a StringBuilder array.

public static void printMatrix(int[][] arr) {
    if (null == arr || arr.length == 0) {
        // empty or null matrix
        return;
    }

    int idx = -1;
    StringBuilder[] sbArr = new StringBuilder[arr.length];

    for (int[] row : arr) {
        sbArr[++idx] = new StringBuilder("(\t");

        for (int elem : row) {
            sbArr[idx].append(elem + "\t");
        }

        sbArr[idx].append(")");
    }

    for (int i = 0; i < sbArr.length; i++) {
        System.out.println(sbArr[i]);
    }
    System.out.println("\nDONE\n");
}
```
<p>Output:</p>
```(   1   2   3   )
(   4   5   6   )
(   7   8   9   )
(   10  11  12  )

DONE
```

ContentLicense: CC BY-SA 4.0

Body:
Here's my efficient approach for displaying 2D integer array using a StringBuilder array.

public static void printMatrix(int[][] arr) {
    if (null == arr || arr.length == 0) {
        // empty or null matrix
        return;
    }

    int idx = -1;
    StringBuilder[] sbArr = new StringBuilder[arr.length];

    for (int[] row : arr) {
        sbArr[++idx] = new StringBuilder("(\t");

        for (int elem : row) {
            sbArr[idx].append(elem + "\t");
        }

        sbArr[idx].append(")");
    }

    for (int i = 0; i < sbArr.length; i++) {
        System.out.println(sbArr[i]);
    }
    System.out.println("\nDONE\n");
}

Output:

(   1   2   3   )
(   4   5   6   )
(   7   8   9   )
(   10  11  12  )

DONE


问:
Distinct values from while loop
I have a database with a field called part_name.
with the values:

```<code>Front Control Arm, Rear Control Arm
</code>```

I need to echo out only Control Arm, once only.
As of now what i'm getting on the while loop results is

```<code>Control Arm, Control Arm.
</code>```

Need to echo out distinct values from while loop results. I can't do it on the SQL query SELECT DISTINCT because i'm preg replacing the value from the row that i'm queering on the database.

```<code>while ($rowsparts = mysql_fetch_array($displayparts))    {
     $part=''.$rowsparts['part_name'].'';
     $part = preg_replace('/\bFront\b/u', '', $part);
     $part = preg_replace('/\bRear\b/u', '', $part);
     echo '<li>'.$part.'</li>';
}
</code>```

I need to echo out the $part variable distinct values, only once per part name.

Control Arm only.

答:
This might work if you want to only display the part name once:

```<code>$lastpart = '';
while ($rowsparts = mysql_fetch_array($displayparts)) {
    $part = $rowsparts['part_name'];
    $part = trim(str_replace('Rear','',str_replace('Front','',$part)));
    if($lastpart != $part) {
        $lastpart = $part;
        echo "<li>".$part."</li>\n";
    } else {
        echo "<li>Part name duplicate: $part, lastpart: $lastpart</li>\n";
    }
}
</code>```

I added the else for debugging. It will show the two vars that are used to detect duplicates. You would remove it after testing.

This might work if you want to only display the part name once when the part names are not in order.
It builds a list of part names, and checks each part names against the list, showing
only the ones not found in the list.

```<code>$part_list = array();
while ($rowsparts = mysql_fetch_array($displayparts)) {
    $part = $rowsparts['part_name'];
    $part = trim(str_replace('Rear','',str_replace('Front','',$part)));
    if(!isset($part_list[$part])) {
        $part_list[$part] = 1;
        echo "<li>".$part."</li>\n";
    }
}
</code>```

Title: Distinct values from while loop

Body:
I have a database with a field called part_name.
with the values:

Front Control Arm, Rear Control Arm

I need to echo out only Control Arm, once only.
As of now what i'm getting on the while loop results is

Control Arm, Control Arm.

Need to echo out distinct values from while loop results. I can't do it on the SQL query SELECT DISTINCT because i'm preg replacing the value from the row that i'm queering on the database.

while ($rowsparts = mysql_fetch_array($displayparts))    {
     $part=''.$rowsparts['part_name'].'';
     $part = preg_replace('/\bFront\b/u', '', $part);
     $part = preg_replace('/\bRear\b/u', '', $part);
     echo '
'.$part.'
';
}

I need to echo out the $part variable distinct values, only once per part name.

Control Arm only.

Body:
This might work if you want to only display the part name once:

$lastpart = '';
while ($rowsparts = mysql_fetch_array($displayparts)) {
    $part = $rowsparts['part_name'];
    $part = trim(str_replace('Rear','',str_replace('Front','',$part)));
    if($lastpart != $part) {
        $lastpart = $part;
        echo "<li>".$part."</li>\n";
    } else {
        echo "<li>Part name duplicate: $part, lastpart: $lastpart</li>\n";
    }
}

I added the else for debugging. It will show the two vars that are used to detect duplicates. You would remove it after testing.

This might work if you want to only display the part name once when the part names are not in order.
It builds a list of part names, and checks each part names against the list, showing
only the ones not found in the list.

$part_list = array();
while ($rowsparts = mysql_fetch_array($displayparts)) {
    $part = $rowsparts['part_name'];
    $part = trim(str_replace('Rear','',str_replace('Front','',$part)));
    if(!isset($part_list[$part])) {
        $part_list[$part] = 1;
        echo "<li>".$part."</li>\n";
    }
}


问:
how are swap! and the mmap function working here?
This is a snippet from the Reagent project. Looking at complete-all and clear-done, I understand the point is to swap out the modified map. I don't understand how it's being done. The definition of mmap calls for 3 parameters — and complete-all seems to be calling it with two, namely map and #(assoc-in % [1 :done] v). clear-done calls with remove and #(get-in % [1 :done]). I tried using the repl to experiment but couldn't get the requires to work out.

```<code>   (ns todomvc.core
      (:require [reagent.core :as r]))

    (defonce todos (r/atom (sorted-map)))

    (defonce counter (r/atom 0))

    (defn add-todo [text]
      (let [id (swap! counter inc)]
        (swap! todos assoc id {:id id :title text :done false})))

    (defn toggle [id] (swap! todos update-in [id :done] not))
    (defn save [id title] (swap! todos assoc-in [id :title] title))
    (defn delete [id] (swap! todos dissoc id))

    (defn mmap [m f a] (->> m (f a) (into (empty m))))
    (defn complete-all [v] (swap! todos mmap map #(assoc-in % [1 :done] v)))
    (defn clear-done [] (swap! todos mmap remove #(get-in % [1 :done])))
</code>```

答: The existing map is passed as the first argument to the function. When all else fails...</p>

Body:
This is a snippet from the Reagent project. Looking at complete-all and clear-done, I understand the point is to swap out the modified map. I don't understand how it's being done. The definition of mmap calls for 3 parameters — and complete-all seems to be calling it with two, namely map and #(assoc-in % [1 :done] v). clear-done calls with remove and #(get-in % [1 :done]). I tried using the repl to experiment but couldn't get the requires to work out.

   (ns todomvc.core
      (:require [reagent.core :as r]))

    (defonce todos (r/atom (sorted-map)))

    (defonce counter (r/atom 0))

    (defn add-todo [text]
      (let [id (swap! counter inc)]
        (swap! todos assoc id {:id id :title text :done false})))

    (defn toggle [id] (swap! todos update-in [id :done] not))
    (defn save [id title] (swap! todos assoc-in [id :title] title))
    (defn delete [id] (swap! todos dissoc id))

    (defn mmap [m f a] (->> m (f a) (into (empty m))))
    (defn complete-all [v] (swap! todos mmap map #(assoc-in % [1 :done] v)))
    (defn clear-done [] (swap! todos mmap remove #(get-in % [1 :done])))


问:
How to setInfoWindowAdapter for particular markers only
I'm trying to use the 'setInfoWindowAdapter' propery within my map view for a particular marker, but with 'Marker 2' there appears to be some unwanted space appearing underneath the title for some reason (Marker 2) (see attached screenshots). What can be done in order to prevent this from happening?

FragmentCustomMapview.java

```<code>public class FragmentCustomMapview extends android.support.v4.app.Fragment implements OnMapReadyCallback {

    public FragmentCustomMapview() {
        // Required empty constructor
    }

    GoogleMap mGoogleMap;
    MapView mMapView;
    SwitchCompat swt;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_custommapview, container, false);

        mMapView = (MapView) v.findViewById(R.id.map_custommapview);
        mMapView.onCreate(savedInstanceState);
        mMapView.getMapAsync(this); //this is important

        swt = (SwitchCompat) v.findViewById(R.id.switch_map_custommapview);

        return v;
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mGoogleMap = googleMap;
        mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
        mGoogleMap.setBuildingsEnabled(true);
        mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

        swt.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                initMap(isChecked);
            }
        });

        initMap(swt.isChecked());

        // Add markers and move the camera
        LatLng marker1 = new LatLng(51.510256, -0.135106);
        mGoogleMap.addMarker(new MarkerOptions()
                .position(marker1)
                .title("Lorem ipsum dolor")
                .snippet("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.")
        );

        LatLng marker2 = new LatLng(51.509793, -0.134961);
        mGoogleMap.addMarker(new MarkerOptions()
                .position(marker2)
                .title("Marker 2")
        );

        mGoogleMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
            @Override
            public View getInfoWindow(Marker arg0) {
                return null;
            }

            @Override
            public View getInfoContents(Marker marker) {

                Context mContext = getActivity();

                LinearLayout info = new LinearLayout(mContext);
                info.setOrientation(LinearLayout.VERTICAL);

                TextView title = new TextView(mContext);
                title.setTextColor(Color.BLACK);
                title.setGravity(Gravity.CENTER);
                title.setTypeface(null, Typeface.BOLD);
                title.setText(marker.getTitle());
                title.setSingleLine(false);

                TextView snippet = new TextView(mContext);
                snippet.setTextColor(Color.GRAY);
                snippet.setText(marker.getSnippet());
                snippet.setMultiline(false)

                info.addView(title);
                info.addView(snippet);

                return info;
            }
        });

        // Updates the location and zoom level of the MapView
        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(51.509932, -0.134720), 18);
        mGoogleMap.animateCamera(cameraUpdate);
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

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

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mMapView.onLowMemory();
    }

    private void initMap(boolean isChecked){
        if (isChecked) {
            mGoogleMap.setMapStyle(new MapStyleOptions(getResources().getString(R.string.style_json)));
        } else {
            mGoogleMap.setMapStyle(null);
        }
    }
}
</code>```

1st marker

2nd marker

答:
Don't add your TextView snippet to your LinearLayout info if your Marker has no snippet:

```<code>@Override
public View getInfoContents(Marker marker) {

    Context mContext = getActivity();

    LinearLayout info = new LinearLayout(mContext);
    info.setOrientation(LinearLayout.VERTICAL);

    TextView title = new TextView(mContext);
    title.setTextColor(Color.BLACK);
    title.setGravity(Gravity.CENTER);
    title.setTypeface(null, Typeface.BOLD);
    title.setText(marker.getTitle());
    title.setSingleLine(false);

    info.addView(title);

    if (marker.getSnippet() != null) {
        TextView snippet = new TextView(mContext);
        snippet.setTextColor(Color.GRAY);
        snippet.setText(marker.getSnippet());
        snippet.setSingleLine(false);

        info.addView(snippet);
    }

    return info;
}
</code>```

Body:
I'm trying to use the 'setInfoWindowAdapter' propery within my map view for a particular marker, but with 'Marker 2' there appears to be some unwanted space appearing underneath the title for some reason (Marker 2) (see attached screenshots). What can be done in order to prevent this from happening?

FragmentCustomMapview.java

public class FragmentCustomMapview extends android.support.v4.app.Fragment implements OnMapReadyCallback {

    public FragmentCustomMapview() {
        // Required empty constructor
    }

    GoogleMap mGoogleMap;
    MapView mMapView;
    SwitchCompat swt;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_custommapview, container, false);

        mMapView = (MapView) v.findViewById(R.id.map_custommapview);
        mMapView.onCreate(savedInstanceState);
        mMapView.getMapAsync(this); //this is important

        swt = (SwitchCompat) v.findViewById(R.id.switch_map_custommapview);

        return v;
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mGoogleMap = googleMap;
        mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
        mGoogleMap.setBuildingsEnabled(true);
        mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

        swt.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                initMap(isChecked);
            }
        });

        initMap(swt.isChecked());

        // Add markers and move the camera
        LatLng marker1 = new LatLng(51.510256, -0.135106);
        mGoogleMap.addMarker(new MarkerOptions()
                .position(marker1)
                .title("Lorem ipsum dolor")
                .snippet("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.")
        );

        LatLng marker2 = new LatLng(51.509793, -0.134961);
        mGoogleMap.addMarker(new MarkerOptions()
                .position(marker2)
                .title("Marker 2")
        );

        mGoogleMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
            @Override
            public View getInfoWindow(Marker arg0) {
                return null;
            }

            @Override
            public View getInfoContents(Marker marker) {

                Context mContext = getActivity();

                LinearLayout info = new LinearLayout(mContext);
                info.setOrientation(LinearLayout.VERTICAL);

                TextView title = new TextView(mContext);
                title.setTextColor(Color.BLACK);
                title.setGravity(Gravity.CENTER);
                title.setTypeface(null, Typeface.BOLD);
                title.setText(marker.getTitle());
                title.setSingleLine(false);

                TextView snippet = new TextView(mContext);
                snippet.setTextColor(Color.GRAY);
                snippet.setText(marker.getSnippet());
                snippet.setMultiline(false)

                info.addView(title);
                info.addView(snippet);

                return info;
            }
        });

        // Updates the location and zoom level of the MapView
        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(51.509932, -0.134720), 18);
        mGoogleMap.animateCamera(cameraUpdate);
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

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

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mMapView.onLowMemory();
    }

    private void initMap(boolean isChecked){
        if (isChecked) {
            mGoogleMap.setMapStyle(new MapStyleOptions(getResources().getString(R.string.style_json)));
        } else {
            mGoogleMap.setMapStyle(null);
        }
    }
}

1st marker

2nd marker

Body:
Don't add your TextView snippet to your LinearLayout info if your Marker has no snippet:

@Override
public View getInfoContents(Marker marker) {

    Context mContext = getActivity();

    LinearLayout info = new LinearLayout(mContext);
    info.setOrientation(LinearLayout.VERTICAL);

    TextView title = new TextView(mContext);
    title.setTextColor(Color.BLACK);
    title.setGravity(Gravity.CENTER);
    title.setTypeface(null, Typeface.BOLD);
    title.setText(marker.getTitle());
    title.setSingleLine(false);

    info.addView(title);

    if (marker.getSnippet() != null) {
        TextView snippet = new TextView(mContext);
        snippet.setTextColor(Color.GRAY);
        snippet.setText(marker.getSnippet());
        snippet.setSingleLine(false);

        info.addView(snippet);
    }

    return info;
}


问:
Label ranges and colors in Python plot
In the following I'm trying to plot points with color and label that changes for every j. What I'm getting is different color and one label in the legend for every couple (i, j):

```<code>import itertools
import numpy as np
import matplotlib.pyplot as plt

color_list = ["blue", "brown", "red", "black"]
g = itertools.cycle(color_list)

primes = (139,149,151,157,163,167)
for j in range(50, 300, 10):
    col = next(g)
    for k in (primes):
        for l in range(10000, 20000, 500):
            start = time.time()
            generator(j, k, l)
            end = time.time()
            plt.plot(l, end - start, linewidth = 2, marker='o', color=col)
</code>```

Edit: Updated the code with my original problem as I couldn't figure out if the solution from Ernest + Arya can work in this case.

答:
you can use sin or cos functions to control color choice and add a variable that changes only when j changes to control whether you plot a new label

```<code>import numpy as np
import matplotlib.pyplot as plt
import math

last_j = -1
z = 5
for j in range (0, z):
    color = ((math.sin(j)+1)/2,(math.cos(j+1)+1)/2,(math.cos(j)+1)/2)
    for i in range (0, 10, 2):
        if j == last_j:
            plt.plot(i + 0.5, j + 0.5, c=color, linewidth = 2, marker='o')
        else:
            plt.plot(i + 0.5, j + 0.5, c=color, linewidth = 2, marker='o',
                label='$n = {j}$'.format(j=j))
        last_j = j

ax = plt.gca()
legend = ax.legend(loc = 'center right', shadow=True)

plt.show()
</code>```

Title: Label ranges and colors in Python plot

Body:
In the following I'm trying to plot points with color and label that changes for every j. What I'm getting is different color and one label in the legend for every couple (i, j):

import itertools
import numpy as np
import matplotlib.pyplot as plt

color_list = ["blue", "brown", "red", "black"]
g = itertools.cycle(color_list)

primes = (139,149,151,157,163,167)
for j in range(50, 300, 10):
    col = next(g)
    for k in (primes):
        for l in range(10000, 20000, 500):
            start = time.time()
            generator(j, k, l)
            end = time.time()
            plt.plot(l, end - start, linewidth = 2, marker='o', color=col)

Edit: Updated the code with my original problem as I couldn't figure out if the solution from Ernest + Arya can work in this case.

Body:
you can use sin or cos functions to control color choice and add a variable that changes only when j changes to control whether you plot a new label

import numpy as np
import matplotlib.pyplot as plt
import math

last_j = -1
z = 5
for j in range (0, z):
    color = ((math.sin(j)+1)/2,(math.cos(j+1)+1)/2,(math.cos(j)+1)/2)
    for i in range (0, 10, 2):
        if j == last_j:
            plt.plot(i + 0.5, j + 0.5, c=color, linewidth = 2, marker='o')
        else:
            plt.plot(i + 0.5, j + 0.5, c=color, linewidth = 2, marker='o',
                label='$n = {j}$'.format(j=j))
        last_j = j

ax = plt.gca()
legend = ax.legend(loc = 'center right', shadow=True)

plt.show()