问:
15 slide puzzle game: Segmentation fault (core dumped) error
My first time trying to ask for help in here so my bad if my question is poorly explained/written. I'm writing code for the magic-15 puzzle game, however I think that I have an error with my update_board function that keeps resulting in a segmentation fault (core dumped) runtime error. Any feedback or help would be appreciated. Sorry for the excessive amount of code, I'm just fairly new to programming and I'm not 100% sure where my error is so I just put the whole thing in there.

Just to clarify, this is the game: https://www.youtube.com/watch?v=EtXE08bOVZM

```<code>#include <stdio.h>
#include <math.h>
#include <string.h>

//fn that allows user input at game start
void scan_board(int board[4][4]){
    printf("Enter initial board state:\n");

    for (int i = 0; i <= 3; i++){
        scanf("%d %d %d %d", &board[i][0], &board[i][1], &board[i][2], &board[i][3]);
    }
}

//fn that prints the user inputted starting board
void print_board(int board[4][4]){
    for (int i = 0; i <= 3; i++){
        for (int j = 0; j<= 3; j++){
            if (board[i][j] == -1){
                printf("%-2s ", "_");
            }else{
                printf("%-2d ", board[i][j]);
            }
        }
        printf("\n");
    }
}

//fn that updates the game board after the user makes a move and also tells user if their move is invalid
int update_board(const char command[100], int board[4][4]){
    //char up[3] = "up";
    //char down[5] = "down";
    //char left[5] = "left";
    //char right[6] = "right";
    int x, y;
    int check = 1;
    for (int i = 0; i <= 3; i++){
        for (int j = 0; j <= 3; j++){
            if (board[i][j] == -1){
                x = i;
                y = j;
                check = 0;
                break;
            }
        }
        if (check == 0){
            break;
        }
    }
    if (strcmp(command, "up\0" == 0)){
        if (x == 0){
            printf("invalid move\n");
        }else{
            board[x][y] = board[x + 1][y];
            board[x + 1][y] = -1;
        }
    }else if (strcmp(command, "down\0" == 0)){
        if (x == 3){
            printf("invalid move\n");
        }else{
            board[x][y] = board[x - 1][y];
            board[x - 1][y] = -1;
        }
    }else if (strcmp(command, "left\0" == 0)){
        if (y == 0){
            printf("invalid move\n");
        }else{
            board[x][y] = board[x][y - 1];
            board[x][y - 1] = -1;
        }
    }else if (strcmp(command, "right\0" == 0)){
        if (y == 3){
            printf("invalid move\n");
        }else{
            board[x][y] = board[x][y + 1];
            board[x][y + 1] = -1;
        }
    }else{
        printf("invalid command\n");
    }
}

//fn that checks how many tiles are in the wrong place
int check_state(int board[4][4]){
    int num = 1;
    int count = 0;
    for (int i = 0; i <= 3; i++){
        for (int j = 0; j <= 3; j++){
            if (board[i][j] != num){
                count++;
            }
            num++;
        }
    }
    count--;
    if (count == 0){
        return 0;
    }else{
        return count;
    }
}

//main fn
int main(void){
    int board[4][4];
    char command[100];
    scan_board(board);
    printf("\n");
    //print_board(board);
    //int state = check_state(board);
    //printf("number of tiles out of position: %d\n\n", state);
    int state = check_state(board);
    while (state > 0){
        print_board(board);
        printf("number of tiles out of position: %d\n\n", state);
        printf("make a move: ");
        gets(command);
        printf("%s\n", command);
        update_board(command, board);
        state = check_state(board);
    }
    printf("final board state\n\n");
    print_board(board);
    printf("you won!");

    return 0;
}
</code>```

答:
Like I was pointing you in my comments you should fix all those strcmp calls.

Another problem, you need to declare update_board as void because it does not return anything.

And last replace gets because is deprecated with fgets or scanf(), like this:
fgets(command, 100, stdin);

Inside void scan_board(int board[4][4]) you should use a second loop instead of using this line:

```<code>scanf("%d %d %d %d", &board[i][0], &board[i][1], &board[i][2], &board[i][3]);
</code>```

and also to check scanf for errors:

```<code>void scan_board(int board[4][4]){
    printf("Enter initial board state:\n");

    for (int i = 0; i < 4; i++){
        for (int j = 0 ; j < 4 ; j++){
            if ( scanf("%d", &board[i][j] ) != 1 ){
                printf("Error, scanf\n");
            }
        }
    }
}
</code>```

After you do that it should look like this:

```<code>#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>

//fn that allows user input at game start
void scan_board(int board[4][4]);
void scan_board(int board[4][4]){
    printf("Enter initial board state:\n");

    for (int i = 0; i < 4; i++){
        for (int j = 0 ; j < 4 ; j++){
            if ( scanf("%d", &board[i][j] ) != 1 ){
                printf("Error, scanf\n");
                exit(EXIT_FAILURE);
            }
        }
    }
}

//fn that prints the user inputted starting board
void print_board(int board[4][4]);
void print_board(int board[4][4]){
    for (int i = 0; i <= 3; i++){
        for (int j = 0; j<= 3; j++){
            if (board[i][j] == -1){
                printf("%-2s ", "_");
            }else{
                printf("%-2d ", board[i][j]);
            }
        }
        printf("\n");
    }
}

//fn that updates the game board after the user makes a move and also tells user if their move is invalid
void update_board(const char command[100], int board[4][4]);
void update_board(const char command[100], int board[4][4]){
    //char up[3] = "up";
    //char down[5] = "down";
    //char left[5] = "left";
    //char right[6] = "right";
    int x, y;
    int check = 1;
    for (int i = 0; i <= 3; i++){
        for (int j = 0; j <= 3; j++){
            if (board[i][j] == -1){
                x = i;
                y = j;
                check = 0;
                break;
            }
        }
        printf("Y = %d\n", y);
        if (check == 0){
            break;
        }
    }
    if (strcmp(command, "up") == 0){
        if (x == 0){
            printf("invalid move\n");
        }else{
            board[x][y] = board[x + 1][y];
            board[x + 1][y] = -1;
        }
    }else if (strcmp(command, "down") == 0){
        if (x == 3){
            printf("invalid move\n");
        }else{
            board[x][y] = board[x - 1][y];
            board[x - 1][y] = -1;
        }
    }else if (strcmp(command, "left") == 0){
        if (y == 0){
            printf("invalid move\n");
        }else{
            board[x][y] = board[x][y - 1];
            board[x][y - 1] = -1;
        }
    }else if (strcmp(command, "right") == 0){
        if (y == 3){
            printf("invalid move\n");
        }else{
            board[x][y] = board[x][y + 1];
            board[x][y + 1] = -1;
        }
    }else{
        printf("invalid command\n");
    }
}

//fn that checks how many tiles are in the wrong place
int check_state(int board[4][4]);
int check_state(int board[4][4]){
    int num = 1;
    int count = 0;
    for (int i = 0; i <= 3; i++){
        for (int j = 0; j <= 3; j++){
            if (board[i][j] != num){
                count++;
            }
            num++;
        }
    }
    count--;
    if (count == 0){
        return 0;
    }else{
        return count;
    }
}

//main fn
int main(void){
    int board[4][4];
    char command[100];
    scan_board(board);

    printf("\n");
    //print_board(board);
    //int state = check_state(board);
    //printf("number of tiles out of position: %d\n\n", state);
    int state = check_state(board);
    while (state > 0){
        print_board(board);
        printf("number of tiles out of position: %d\n\n", state);
        printf("make a move: ");

        if ( scanf("%99s", command) != 1){
            printf("error scanf, again\n");
            exit(EXIT_FAILURE);
        }

        update_board(command, board);
        state = check_state(board);
    }
    printf("final board state\n\n");
    print_board(board);
    printf("you won!");

    return 0;
}
</code>```

Output:

```<code>Enter initial board state:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

final board state

1  2  3  4
5  6  7  8
9  10 11 12
13 14 15 16
you won!
</code>```

I do not know how should your program behave, but at least you can compile and test it.

Body:
My first time trying to ask for help in here so my bad if my question is poorly explained/written. I'm writing code for the magic-15 puzzle game, however I think that I have an error with my update_board function that keeps resulting in a segmentation fault (core dumped) runtime error. Any feedback or help would be appreciated. Sorry for the excessive amount of code, I'm just fairly new to programming and I'm not 100% sure where my error is so I just put the whole thing in there.

Just to clarify, this is the game: https://www.youtube.com/watch?v=EtXE08bOVZM

#include <stdio.h>
#include <math.h>
#include <string.h>

//fn that allows user input at game start
void scan_board(int board[4][4]){
    printf("Enter initial board state:\n");

    for (int i = 0; i <= 3; i++){
        scanf("%d %d %d %d", &board[i][0], &board[i][1], &board[i][2], &board[i][3]);
    }
}

//fn that prints the user inputted starting board
void print_board(int board[4][4]){
    for (int i = 0; i <= 3; i++){
        for (int j = 0; j<= 3; j++){
            if (board[i][j] == -1){
                printf("%-2s ", "_");
            }else{
                printf("%-2d ", board[i][j]);
            }
        }
        printf("\n");
    }
}

//fn that updates the game board after the user makes a move and also tells user if their move is invalid
int update_board(const char command[100], int board[4][4]){
    //char up[3] = "up";
    //char down[5] = "down";
    //char left[5] = "left";
    //char right[6] = "right";
    int x, y;
    int check = 1;
    for (int i = 0; i <= 3; i++){
        for (int j = 0; j <= 3; j++){
            if (board[i][j] == -1){
                x = i;
                y = j;
                check = 0;
                break;
            }
        }
        if (check == 0){
            break;
        }
    }
    if (strcmp(command, "up\0" == 0)){
        if (x == 0){
            printf("invalid move\n");
        }else{
            board[x][y] = board[x + 1][y];
            board[x + 1][y] = -1;
        }
    }else if (strcmp(command, "down\0" == 0)){
        if (x == 3){
            printf("invalid move\n");
        }else{
            board[x][y] = board[x - 1][y];
            board[x - 1][y] = -1;
        }
    }else if (strcmp(command, "left\0" == 0)){
        if (y == 0){
            printf("invalid move\n");
        }else{
            board[x][y] = board[x][y - 1];
            board[x][y - 1] = -1;
        }
    }else if (strcmp(command, "right\0" == 0)){
        if (y == 3){
            printf("invalid move\n");
        }else{
            board[x][y] = board[x][y + 1];
            board[x][y + 1] = -1;
        }
    }else{
        printf("invalid command\n");
    }
}

//fn that checks how many tiles are in the wrong place
int check_state(int board[4][4]){
    int num = 1;
    int count = 0;
    for (int i = 0; i <= 3; i++){
        for (int j = 0; j <= 3; j++){
            if (board[i][j] != num){
                count++;
            }
            num++;
        }
    }
    count--;
    if (count == 0){
        return 0;
    }else{
        return count;
    }
}

//main fn
int main(void){
    int board[4][4];
    char command[100];
    scan_board(board);
    printf("\n");
    //print_board(board);
    //int state = check_state(board);
    //printf("number of tiles out of position: %d\n\n", state);
    int state = check_state(board);
    while (state > 0){
        print_board(board);
        printf("number of tiles out of position: %d\n\n", state);
        printf("make a move: ");
        gets(command);
        printf("%s\n", command);
        update_board(command, board);
        state = check_state(board);
    }
    printf("final board state\n\n");
    print_board(board);
    printf("you won!");

    return 0;
}

Body:
Like I was pointing you in my comments you should fix all those strcmp calls.

Another problem, you need to declare update_board as void because it does not return anything.

And last replace gets because is deprecated with fgets or scanf(), like this:
fgets(command, 100, stdin);

Inside void scan_board(int board[4][4]) you should use a second loop instead of using this line:

scanf("%d %d %d %d", &board[i][0], &board[i][1], &board[i][2], &board[i][3]);

and also to check scanf for errors:

void scan_board(int board[4][4]){
    printf("Enter initial board state:\n");

    for (int i = 0; i < 4; i++){
        for (int j = 0 ; j < 4 ; j++){
            if ( scanf("%d", &board[i][j] ) != 1 ){
                printf("Error, scanf\n");
            }
        }
    }
}

After you do that it should look like this:

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>

//fn that allows user input at game start
void scan_board(int board[4][4]);
void scan_board(int board[4][4]){
    printf("Enter initial board state:\n");

    for (int i = 0; i < 4; i++){
        for (int j = 0 ; j < 4 ; j++){
            if ( scanf("%d", &board[i][j] ) != 1 ){
                printf("Error, scanf\n");
                exit(EXIT_FAILURE);
            }
        }
    }
}

//fn that prints the user inputted starting board
void print_board(int board[4][4]);
void print_board(int board[4][4]){
    for (int i = 0; i <= 3; i++){
        for (int j = 0; j<= 3; j++){
            if (board[i][j] == -1){
                printf("%-2s ", "_");
            }else{
                printf("%-2d ", board[i][j]);
            }
        }
        printf("\n");
    }
}

//fn that updates the game board after the user makes a move and also tells user if their move is invalid
void update_board(const char command[100], int board[4][4]);
void update_board(const char command[100], int board[4][4]){
    //char up[3] = "up";
    //char down[5] = "down";
    //char left[5] = "left";
    //char right[6] = "right";
    int x, y;
    int check = 1;
    for (int i = 0; i <= 3; i++){
        for (int j = 0; j <= 3; j++){
            if (board[i][j] == -1){
                x = i;
                y = j;
                check = 0;
                break;
            }
        }
        printf("Y = %d\n", y);
        if (check == 0){
            break;
        }
    }
    if (strcmp(command, "up") == 0){
        if (x == 0){
            printf("invalid move\n");
        }else{
            board[x][y] = board[x + 1][y];
            board[x + 1][y] = -1;
        }
    }else if (strcmp(command, "down") == 0){
        if (x == 3){
            printf("invalid move\n");
        }else{
            board[x][y] = board[x - 1][y];
            board[x - 1][y] = -1;
        }
    }else if (strcmp(command, "left") == 0){
        if (y == 0){
            printf("invalid move\n");
        }else{
            board[x][y] = board[x][y - 1];
            board[x][y - 1] = -1;
        }
    }else if (strcmp(command, "right") == 0){
        if (y == 3){
            printf("invalid move\n");
        }else{
            board[x][y] = board[x][y + 1];
            board[x][y + 1] = -1;
        }
    }else{
        printf("invalid command\n");
    }
}

//fn that checks how many tiles are in the wrong place
int check_state(int board[4][4]);
int check_state(int board[4][4]){
    int num = 1;
    int count = 0;
    for (int i = 0; i <= 3; i++){
        for (int j = 0; j <= 3; j++){
            if (board[i][j] != num){
                count++;
            }
            num++;
        }
    }
    count--;
    if (count == 0){
        return 0;
    }else{
        return count;
    }
}

//main fn
int main(void){
    int board[4][4];
    char command[100];
    scan_board(board);

    printf("\n");
    //print_board(board);
    //int state = check_state(board);
    //printf("number of tiles out of position: %d\n\n", state);
    int state = check_state(board);
    while (state > 0){
        print_board(board);
        printf("number of tiles out of position: %d\n\n", state);
        printf("make a move: ");

        if ( scanf("%99s", command) != 1){
            printf("error scanf, again\n");
            exit(EXIT_FAILURE);
        }

        update_board(command, board);
        state = check_state(board);
    }
    printf("final board state\n\n");
    print_board(board);
    printf("you won!");

    return 0;
}

Output:

Enter initial board state:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

final board state

1  2  3  4
5  6  7  8
9  10 11 12
13 14 15 16
you won!

I do not know how should your program behave, but at least you can compile and test it.


来源: stackexchange

问:
powershell:how to catch the error cause by invoke-sqlcmd?
I want to catch the invoke-sql if there is anything wrong. But when I run the following command, and if the $sql is invalid, it can't be caught. How to catch this exception?</p>

```<code> try {
     Invoke-Sqlcmd -Query $sql -ServerInstance t1 -database db -QueryTimeout 65535 -ErrorAction 'Stop'
   } catch{
      "error when running sql $sql"
   }
</code>```

答:
I have no issue, using a script called test.ps1

```<code>add-pssnapin SqlServerCmdletSnapin100
get-host
$sql = "selects * from syscomments"
$server = ""
$database = ""
$username = ""
$password = ""
try {
    Invoke-Sqlcmd -Query $sql -ServerInstance $server -database $database -QueryTimeout 65535 -ErrorAction 'Stop' -username $username -password $password
} catch {
  "error when running sql $sql"
  Write-Host($error)
}
</code>```

And the output

```<code>PS C:\> .\test.ps1
Name             : ConsoleHost
Version          : 2.0
InstanceId       : 9ac019da-97bd-45d1-bfa5-65fb4d376dc6
UI               : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture   : en-AU
CurrentUICulture : en-US
PrivateData      : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
IsRunspacePushed : False
Runspace         : System.Management.Automation.Runspaces.LocalRunspace

error when running sql selects * from syscomments

Incorrect syntax near '*'.
</code>```

what input parameters are you using, are you using powershell 1 or 2?

ContentLicense: CC BY-SA 2.5

Body:
I want to catch the invoke-sql if there is anything wrong. But when I run the following command, and if the $sql is invalid, it can't be caught. How to catch this exception?

 try {
     Invoke-Sqlcmd -Query $sql -ServerInstance t1 -database db -QueryTimeout 65535 -ErrorAction 'Stop'
   } catch{
      "error when running sql $sql"
   }

Body:
I have no issue, using a script called test.ps1

add-pssnapin SqlServerCmdletSnapin100
get-host
$sql = "selects * from syscomments"
$server = ""
$database = ""
$username = ""
$password = ""
try {
    Invoke-Sqlcmd -Query $sql -ServerInstance $server -database $database -QueryTimeout 65535 -ErrorAction 'Stop' -username $username -password $password
} catch {
  "error when running sql $sql"
  Write-Host($error)
}

And the output

PS C:\> .\test.ps1
Name             : ConsoleHost
Version          : 2.0
InstanceId       : 9ac019da-97bd-45d1-bfa5-65fb4d376dc6
UI               : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture   : en-AU
CurrentUICulture : en-US
PrivateData      : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
IsRunspacePushed : False
Runspace         : System.Management.Automation.Runspaces.LocalRunspace

error when running sql selects * from syscomments

Incorrect syntax near '*'.

what input parameters are you using, are you using powershell 1 or 2?


问:
Many to many to many relationship query
I got 3 main table.

Table A
Table B
Table C

Table A has many to many relationships with Table B
so they have a pivot table ab

Table B has also many to many relationships with Table C
so they also have a pivot table bc

So because of this Table A has many to many through, relationship with Table C.

So what is the MySQL query if I wanted to get all rows of Table C that is related to Table A?

答:
You work backwards:</p>

```<code>$tableAID = 1;

TableC::whereHas('tableB', function($q) use ($tableAID) {
    $q->whereHas('tableA', function($q) use ($tableAID) {
        $q->where('id', $tableAID);
    });
})->get();
</code>```

ContentLicense: CC BY-SA 3.0

Title: Many to many to many relationship query

Body:
You work backwards:

$tableAID = 1;

TableC::whereHas('tableB', function($q) use ($tableAID) {
    $q->whereHas('tableA', function($q) use ($tableAID) {
        $q->where('id', $tableAID);
    });
})->get();


问:
How to stage a form in Kentico when it doesn't show up in the staging list?
Pretty much what the title says. We have a form that we've created and we want to sync it over to our staging server but it's not showing up in the staging list. At all. Do we have gremlins, is this a known issue, or is there something else amok here?

Edit: The problem might be a permissions issue but it's weird. If the user who created the form syncs it, it goes into a black hole - I understand he doesn't have permission to create forms on our staging server. When I cloned the form and synced the cloned form to staging, they both showed up.

答: You can just edit the form and resave it, this will generate a staging task.</p>


问:
C# Static property in non-static class as indicator of main object of this class
I have class Important and some objects of this class created. I want allow user to choose main object of this class. Have a look at code below:

```<code>public class Program
{
    public static void Main(string[] args)
    {
       Important imp1 = new Important("Important 1");
       Important imp2 = new Important("Important 2");
       Important imp3 = new Important("Important 3");

       imp2.SetMostImportant();

       Console.Write(Important.MostImportant.Name);
    }

    public class Important
    {
        public Important(string name)
        {
            Name = name;
            if(MostImportant == null)
                SetMostImportant();
        }

        public string Name { get; private set; }
        public static Important MostImportant { get; private set; }

        public void SetMostImportant()
        {
            MostImportant = this;
        }
    }
 }
</code>```

Is it good solution? If not, please tell me why not.

Before, to achieve this kind of things I just created boolean field named e.g. IsMainObject and, when I wanted to change main object, I iterated through all objects (or group of object) of specific class except element that I want to be main, and changed boolean to false, in my new candidate I simply set flag to true. Example below:

```<code>public class Program
{
    public static void Main(string[] args)
    {
       Important imp1 = new Important("Important 1");
       Important imp2 = new Important("Important 2");
       Important imp3 = new Important("Important 3");
       List<Important> list = new List<Important> { imp1, imp2, imp3 };

       foreach(var item in list.Where(x => x.Name != "Important 2"))
       {
           item.SetMostImportant(false);
       }

       imp2.SetMostImportant(true);
       Console.Write(list.FirstOrDefault(x => x.MostImportant == true).Name);
    }

    public class Important
    {
        public Important(string name)
        {
            Name = name;
        }

        public string Name { get; private set; }
        public bool MostImportant { get; private set; }

        public void SetMostImportant(bool val)
        {
            MostImportant = val;
        }
    }
}
</code>```

I don't like this solution because:

I don't know if MostImportant is true for more than one objects without iterating.

I need to write extra-code to handle much more cases.

I don't have possibility to always iterate through all instances of specific class (groups not always are enough).

... and much more, but you got the idea.

答:
```<code>public static Important MostImportant { get; private set; }
</code>```

is a fine solution, and much better than

```<code>public bool MostImportant { get; private set; }
</code>```

It's not uncommon to have a static property of the type that it's inside of when implementing "singleton" classes. I've written code that resembles this:

```<code>class MyClass
{
    public static MyClass Instance { get; private set; }
    public MyClass()
    {
        if (Instance == null)
        {
            Instance = this;
        }
        else
        {
            throw new Exception("MyClass already instantiated.");
        }
    }
}
</code>```

Body:
I have class Important and some objects of this class created. I want allow user to choose main object of this class. Have a look at code below:

public class Program
{
    public static void Main(string[] args)
    {
       Important imp1 = new Important("Important 1");
       Important imp2 = new Important("Important 2");
       Important imp3 = new Important("Important 3");

       imp2.SetMostImportant();

       Console.Write(Important.MostImportant.Name);
    }

    public class Important
    {
        public Important(string name)
        {
            Name = name;
            if(MostImportant == null)
                SetMostImportant();
        }

        public string Name { get; private set; }
        public static Important MostImportant { get; private set; }

        public void SetMostImportant()
        {
            MostImportant = this;
        }
    }
 }

Is it good solution? If not, please tell me why not.

Before, to achieve this kind of things I just created boolean field named e.g. IsMainObject and, when I wanted to change main object, I iterated through all objects (or group of object) of specific class except element that I want to be main, and changed boolean to false, in my new candidate I simply set flag to true. Example below:

public class Program
{
    public static void Main(string[] args)
    {
       Important imp1 = new Important("Important 1");
       Important imp2 = new Important("Important 2");
       Important imp3 = new Important("Important 3");
       List<Important> list = new List<Important> { imp1, imp2, imp3 };

       foreach(var item in list.Where(x => x.Name != "Important 2"))
       {
           item.SetMostImportant(false);
       }

       imp2.SetMostImportant(true);
       Console.Write(list.FirstOrDefault(x => x.MostImportant == true).Name);
    }

    public class Important
    {
        public Important(string name)
        {
            Name = name;
        }

        public string Name { get; private set; }
        public bool MostImportant { get; private set; }

        public void SetMostImportant(bool val)
        {
            MostImportant = val;
        }
    }
}

I don't like this solution because:

I don't know if MostImportant is true for more than one objects without iterating.

I need to write extra-code to handle much more cases.

I don't have possibility to always iterate through all instances of specific class (groups not always are enough).

... and much more, but you got the idea.

Body:
public static Important MostImportant { get; private set; }

is a fine solution, and much better than

public bool MostImportant { get; private set; }

It's not uncommon to have a static property of the type that it's inside of when implementing "singleton" classes. I've written code that resembles this:

class MyClass
{
    public static MyClass Instance { get; private set; }
    public MyClass()
    {
        if (Instance == null)
        {
            Instance = this;
        }
        else
        {
            throw new Exception("MyClass already instantiated.");
        }
    }
}


问:
Alternate of rename() and remove() in C++
I am trying to implement same functionality for File rename() and remove() for my winCE device.
but i guess the these function are not there in wince. as its there in cstdio header for C++.

Please suggest me the alternate for this.

答: #include <fstream> contains std::remove() and std::rename().


问:
AlamofireObjectMapper Generic parameter 'T' could not be inferred
i'm trying to have a system where all my api requests path through one function and map them to the corresponding object

```<code>func sendApi<T>(url : String , httpMethod : HTTPMethod = .get,
                 parameters: Parameters? = nil,
                 encoding: ParameterEncoding = URLEncoding.default,
                 headers: HTTPHeaders? = nil , callbackSuccess : @escaping (T) -> () , callbackFailure : @escaping (T) -> ()) where T : Mappable {

    Alamofire.request(url, method: httpMethod, parameters: parameters , encoding: encoding, headers: headers).responseObject{(response: (DataResponse<T>))in

            switch response.result {

            case .success :
                let result  = Mapper<T>().map(JSONObject: response.value)!
                callbackSuccess(result)
                break;
            case .failure(let error):
                if((error as NSError).code == ErrorResponse.noInternetConnection){
                    //  errorCallBack(ErrorResponse.noInternetConnectionString)
                }
                // errorCallBack(error.localizedDescription)
                print(error.localizedDescription)
                break;
            }
    }
}
</code>```

but when i try to call the function inside a get method for example

```<code> func testApiGet(url: String , packageId : Int ,callback :@escaping (myObject) -> Void , errorCallBack : @escaping (String) -> Void ){

        let token = spm.getUserToken()
        let headers = ["X-Auth-Token" : token]
        let newUrl = url + "?packageId=" + String(packageId)

        sendApi(url: url, httpMethod: HTTPMethod.get , parameters: nil, encoding: JSONEncoding.default, headers: headers, callbackSuccess: {(jsonObject) in

        } , callbackFailure:{ (jsonObject)in

        })
    }
</code>```

i get the error "Generic parameter 'T' could not be inferred"

of course i can set the type of the object

```<code>(response: (DataResponse<myObject>)
</code>```

and the error will go.

my question is how solve this error to make it fully generic

答:
It does not make sense that your error handler and your success handler have the same type T: Mappable.  You are only going to get a mapped object in the success handler.  The error handler should be something like (Error) -> ().

Secondly your function is generic with respect to the parameter type of the closure arguments, but when you are calling the function you are not specifying the type:

```<code> sendApi(url: url, httpMethod: HTTPMethod.get , parameters: nil, encoding: JSONEncoding.default, headers: headers, callbackSuccess: {(jsonObject) in

        } , callbackFailure:{ (jsonObject)in

        })
</code>```

The compiler therefore has no idea what type you are expecting and thats why its complaining that it cannot infer the type here.  You need to explicitly provide the parameter type because that is what determines what version of the generic gets  invoked:

```<code> sendApi(url: url, httpMethod: HTTPMethod.get , parameters: nil, encoding: JSONEncoding.default, headers: headers, callbackSuccess: {(jsonObject: MyMappableType) in

        } , callbackFailure:{ (error: Error)in

        })
</code>```

Body:
i'm trying to have a system where all my api requests path through one function and map them to the corresponding object

func sendApi<T>(url : String , httpMethod : HTTPMethod = .get,
                 parameters: Parameters? = nil,
                 encoding: ParameterEncoding = URLEncoding.default,
                 headers: HTTPHeaders? = nil , callbackSuccess : @escaping (T) -> () , callbackFailure : @escaping (T) -> ()) where T : Mappable {

    Alamofire.request(url, method: httpMethod, parameters: parameters , encoding: encoding, headers: headers).responseObject{(response: (DataResponse<T>))in

            switch response.result {

            case .success :
                let result  = Mapper<T>().map(JSONObject: response.value)!
                callbackSuccess(result)
                break;
            case .failure(let error):
                if((error as NSError).code == ErrorResponse.noInternetConnection){
                    //  errorCallBack(ErrorResponse.noInternetConnectionString)
                }
                // errorCallBack(error.localizedDescription)
                print(error.localizedDescription)
                break;
            }
    }
}

but when i try to call the function inside a get method for example

 func testApiGet(url: String , packageId : Int ,callback :@escaping (myObject) -> Void , errorCallBack : @escaping (String) -> Void ){

        let token = spm.getUserToken()
        let headers = ["X-Auth-Token" : token]
        let newUrl = url + "?packageId=" + String(packageId)

        sendApi(url: url, httpMethod: HTTPMethod.get , parameters: nil, encoding: JSONEncoding.default, headers: headers, callbackSuccess: {(jsonObject) in

        } , callbackFailure:{ (jsonObject)in

        })
    }

i get the error "Generic parameter 'T' could not be inferred"

of course i can set the type of the object

(response: (DataResponse<myObject>)

and the error will go.

my question is how solve this error to make it fully generic

Body:
It does not make sense that your error handler and your success handler have the same type T: Mappable.  You are only going to get a mapped object in the success handler.  The error handler should be something like (Error) -> ().

Secondly your function is generic with respect to the parameter type of the closure arguments, but when you are calling the function you are not specifying the type:

 sendApi(url: url, httpMethod: HTTPMethod.get , parameters: nil, encoding: JSONEncoding.default, headers: headers, callbackSuccess: {(jsonObject) in

        } , callbackFailure:{ (jsonObject)in

        })

The compiler therefore has no idea what type you are expecting and thats why its complaining that it cannot infer the type here.  You need to explicitly provide the parameter type because that is what determines what version of the generic gets  invoked:

 sendApi(url: url, httpMethod: HTTPMethod.get , parameters: nil, encoding: JSONEncoding.default, headers: headers, callbackSuccess: {(jsonObject: MyMappableType) in

        } , callbackFailure:{ (error: Error)in

        })


问:
JQuery Issue Code, Trying To click a button programmatically but it isn't work - No id/class
Heres my current attempt:

```<code><div class="links">
    <a href="/login">Login</a>
    <a href="/register">Register</a>
</div>
</code>```

My JQuery For This Attempt Is:

```<code>setTimeout (
  function()
  {
    alert("Clicking Now");
    $('.links a:contains("Register")').trigger('click');
  }, 2000);
</code>```

This doesn't seem to click the href link after 2 seconds... Any help please?

答:
jQuery has a built in function $(el).click() try using that first.

Certain browsers limit your ability to do actions that would typically have to be taken by the user (click, copy, paste), but you can still trigger/broadcast the events so that anything triggered by an eventListener can pick it up.

For this particular goal, I think it would be more appropriate to redirect the user to your login page, using something like window.location.href = '/login'

Body:
Heres my current attempt:

    Login
    Register

My JQuery For This Attempt Is:

setTimeout (
  function()
  {
    alert("Clicking Now");
    $('.links a:contains("Register")').trigger('click');
  }, 2000);

This doesn't seem to click the href link after 2 seconds... Any help please?


问:
Provide arguments with a method
Is there a way in Java to create a method that would return the list of parameters of another method such that I am able to call

```<code>anotherMethod(method())
</code>```

where anotherMethod has arbitrary arguments like

```<code>public void anotherMethod(int a, int b, String c)
</code>```

And what is if the types stay the same, like with

```<code>public int add(int a, int b, int c)
</code>```

If there is no such way, how could I model the list of parameters such that it would work? Is it a List or an array or something else?

答:
There is not direct way to pass multiple values in the way you want. But you can use a indirect way to pass a group of values of different type. I can think of two ways but their can be more.

Firs - Use a map, just insert the values you want to pass in the collection and pass the collection to the second method.

Second - Create a bean (Java POJO) to pass as parameter to the consuming method.

A small sample code.

```<code> class Sample{
    private int a;
    private String b;
    private int c;

    Sample(int a,String b,int c){
        this.a = a;
        this.b = b;
        this.c = c;
    }
    public int getA() {
        return a;
    }
    public void setA(int a) {
        this.a = a;
    }
    public String getB() {
        return b;
    }
    public void setB(String b) {
        this.b = b;
    }
    public int getC() {
        return c;
    }
    public void setC(int c) {
        this.c = c;
    }
}
    public class PassingExample {
    public void consumerofInputs (Map<Integer, Object> input)/*(int a, String b, int c)*/{
        System.out.println("I use three different inputs : int, string and int");
        for (Map.Entry<Integer, Object> entry : input.entrySet()) {
            System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
        }

    }

    public Map producingInput() {
        Map<Integer, Object> input = new HashMap<Integer, Object>();
        input.put(1, 10);
        input.put(2, "input");
        input.put(3, 89);
        return input;
    }

    public Sample createClassAsInput(){
        Sample input = new Sample(10,"class-input",30);
        return input;

    }

    public void useSampleAsInput(Sample input){
        System.out.println("\nUsing Class as input \nInt::"+input.getA()+"\nString::"+input.getB()+"\nInt::"+input.getC());
    }

    public static void main(String[] args) {
        PassingExample example = new PassingExample();
        example.consumerofInputs(example.producingInput());
        example.useSampleAsInput(example.createClassAsInput());
    }
}
</code>```

Title: Provide arguments with a method

Body:
Is there a way in Java to create a method that would return the list of parameters of another method such that I am able to call

anotherMethod(method())

where anotherMethod has arbitrary arguments like

public void anotherMethod(int a, int b, String c)

And what is if the types stay the same, like with

public int add(int a, int b, int c)

If there is no such way, how could I model the list of parameters such that it would work? Is it a List or an array or something else?

Body:
There is not direct way to pass multiple values in the way you want. But you can use a indirect way to pass a group of values of different type. I can think of two ways but their can be more.

Firs - Use a map, just insert the values you want to pass in the collection and pass the collection to the second method.

Second - Create a bean (Java POJO) to pass as parameter to the consuming method.

A small sample code.

 class Sample{
    private int a;
    private String b;
    private int c;

    Sample(int a,String b,int c){
        this.a = a;
        this.b = b;
        this.c = c;
    }
    public int getA() {
        return a;
    }
    public void setA(int a) {
        this.a = a;
    }
    public String getB() {
        return b;
    }
    public void setB(String b) {
        this.b = b;
    }
    public int getC() {
        return c;
    }
    public void setC(int c) {
        this.c = c;
    }
}
    public class PassingExample {
    public void consumerofInputs (Map<Integer, Object> input)/*(int a, String b, int c)*/{
        System.out.println("I use three different inputs : int, string and int");
        for (Map.Entry<Integer, Object> entry : input.entrySet()) {
            System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
        }

    }

    public Map producingInput() {
        Map<Integer, Object> input = new HashMap<Integer, Object>();
        input.put(1, 10);
        input.put(2, "input");
        input.put(3, 89);
        return input;
    }

    public Sample createClassAsInput(){
        Sample input = new Sample(10,"class-input",30);
        return input;

    }

    public void useSampleAsInput(Sample input){
        System.out.println("\nUsing Class as input \nInt::"+input.getA()+"\nString::"+input.getB()+"\nInt::"+input.getC());
    }

    public static void main(String[] args) {
        PassingExample example = new PassingExample();
        example.consumerofInputs(example.producingInput());
        example.useSampleAsInput(example.createClassAsInput());
    }
}


问:
Php sessions don't work after htaccess rewriterule
I have a booking system that i'm trying to set up. I want to use the same functions for all customers. I have set up htaccess rewriterule to make it look like all the files are run from
www.mydomain.com/web-book/customerX/index.php
, but in fact the files are located in the web-book folder. This is just for nice displaying and for giving each customer an easy link to their bookings.

```<code>RewriteRule ^([a-zA-Z]+)/([_a-zA-Z-]+)\.php$ /web-book/$2.php?site=$1
</code>```

I'm also moving my css/images with the same technique working fine. javascripts working fine. Everything is good except the php Sessions.

THE PROBLEM: The php $_Session variables won't work, meaning i can't log in or do anything involving sessions.
There must be something that i'm missing? I wan't my session vars to the accessible all over mydomain.com if possible???

答:
Check if don't have a conflicting php.ini file located at the root folder.

I unintentionally copied the php.ini file from my local server to the remote server and this prevent $_SESSION to be shared between my root directory and the sub directories.

Body:
I have a booking system that i'm trying to set up. I want to use the same functions for all customers. I have set up htaccess rewriterule to make it look like all the files are run from
www.mydomain.com/web-book/customerX/index.php
, but in fact the files are located in the web-book folder. This is just for nice displaying and for giving each customer an easy link to their bookings.

RewriteRule ^([a-zA-Z]+)/([_a-zA-Z-]+)\.php$ /web-book/$2.php?site=$1

I'm also moving my css/images with the same technique working fine. javascripts working fine. Everything is good except the php Sessions.

THE PROBLEM: The php $_Session variables won't work, meaning i can't log in or do anything involving sessions.
There must be something that i'm missing? I wan't my session vars to the accessible all over mydomain.com if possible???


问:
VBA Loop to Conditionally Format showing Type Mismatch bug
I have an excel sheet with 4 columns, and I want to loop through the column and if (Column D/Column C) <> (Column B/Column A), highlight all 4 cells. I'm getting a Type Mismatch running the following and not sure why?</p>

```<code>Sub Check()

Dim ValA as Variant
Dim ValB as Variant
Dim ValC as Variant
Dim ValD as Variant
Dim ColA as Long
Dim ColB as Long
Dim ColC as Long
Dim ColD as Long

Set ValA = ActiveSheet.Rows(1).Find("A", lookat:=xlWhole)
ColA = ValA.Column

 Set ValB = ActiveSheet.Rows(1).Find("B", lookat:=xlWhole)
ColB = ValB.Column

 Set ValC = ActiveSheet.Rows(1).Find("C", lookat:=xlWhole)
ColC = ValC.Column

 Set ValD = ActiveSheet.Rows(1).Find("D", lookat:=xlWhole)
ColD = ValD.Column

LastRow = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row

'Loop

For i = 2 to LastRow
    If ActiveSheet.Cells(i,ColD).Value/ActiveSheet.Cells(i,ColC).Value <> ActiveSheet.Cells(i, ColB).Value/ActiveSheet(i, ColA).Value Then
        ActiveSheet.Cells(i, ColA).Interior.ColorIndex = 3
        ActiveSheet.Cells(i, ColB).Interior.ColorIndex = 3
        ActiveSheet.Cells(i, ColC).Interior.ColorIndex = 3
        ActiveSheet.Cells(i, ColD).Interior.ColorIndex = 3
    End If
Next i
End Sub
</code>```

答:
With Dim ColA, ColB, ColC, ColD as Long only the last is a Long and the others are implicitly variants. You would need to declare each as Long.

Also, ValA etc are Ranges and you want to access the Column property of the Range object.

```<code>Dim ValA As Range
Dim ValB As Range
Dim ValC As Range
Dim ValD as Range
Dim ColA As Long
Dim ColB As Long
Dim ColC As Long
Dim ColD as Long
</code>```

You will also need some error handling in case Find doesn't return a match object.

For example, If "A" not found in row 1 then ValA is Nothing and you will get an error when trying to access the column so handle this with a If Not ValA Is Nothing:

```<code>Set ValA = ActiveSheet.Rows(1).Find("A", lookat:=xlWhole)

If Not ValA Is Nothing Then
    ColA = ValA.Column
End If
</code>```

Something like (and i haven't tested this):

```<code>Option Explicit

Public Sub test()

Dim ValA As Range
Dim ValB As Variant
Dim ValC As Variant
Dim ValD As Variant
Dim ColA As Long
Dim ColB As Long
Dim ColC As Long
Dim ColD As Long
Dim i As Long
Dim lastRow As Long

Set ValA = ActiveSheet.Rows(1).Find("A", lookat:=xlWhole)

If Not ValA Is Nothing Then
    ColA = ValA.Column
End If

Set ValB = ActiveSheet.Rows(1).Find("B", lookat:=xlWhole)

If Not ValB Is Nothing Then
    ColB = ValB.Column
End If

Set ValC = ActiveSheet.Rows(1).Find("C", lookat:=xlWhole)

If Not ValC Is Nothing Then
    ColC = ValC.Column
End If

Set ValD = ActiveSheet.Rows(1).Find("D", lookat:=xlWhole)

If Not ValD Is Nothing Then
    ColD = ValD.Column
End If

lastRow = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row

'Loop

If ColA > 0 And ColB > 0 And ColC > 0 And ColD > 0 Then

    For i = 2 To lastRow

        If ActiveSheet.Cells(i, ColD).Value / ActiveSheet.Cells(i, ColC).Value <> ActiveSheet.Cells(i, ColB).Value / ActiveSheet(i, ColA).Value Then

            ActiveSheet.Cells(i, ColA).Interior.ColorIndex = 3
            ActiveSheet.Cells(i, ColB).Interior.ColorIndex = 3
            ActiveSheet.Cells(i, ColC).Interior.ColorIndex = 3
            ActiveSheet.Cells(i, ColD).Interior.ColorIndex = 3

        End If

    Next i

 Else

     MsgBox "Matches weren't found for A,B,C and D in row 1."

End If

End Sub
</code>```

Option Explicit at the top forces you to declare all your variables and checks the type. Great for catching errors early.

How you choose to handle values not being found is up to you. I have given examples of how to handle the Range object being nothing when Find isn't successful and therefore the associated Column value being 0.

You will want additional error handling for divide by 0 errors e.g. at this part

```<code>/ActiveSheet.Cells(i, ColC).Value
</code>```

And this

```<code>/ActiveSheet(i, ColA).Value
</code>```

Again, how you handle it is up to you.

You might choose a default value, to warn the user, to exit the sub, to On Error Resume Next to skip to the next line, to have a test before the division such

```<code>If ActiveSheet(i, ColA).Value = 0 Or ActiveSheet.Cells(i, ColC).Value  = 0 Then Exit Sub
</code>```

Body:
I have an excel sheet with 4 columns, and I want to loop through the column and if (Column D/Column C) <> (Column B/Column A), highlight all 4 cells. I'm getting a Type Mismatch running the following and not sure why?

Sub Check()

Dim ValA as Variant
Dim ValB as Variant
Dim ValC as Variant
Dim ValD as Variant
Dim ColA as Long
Dim ColB as Long
Dim ColC as Long
Dim ColD as Long

Set ValA = ActiveSheet.Rows(1).Find("A", lookat:=xlWhole)
ColA = ValA.Column

 Set ValB = ActiveSheet.Rows(1).Find("B", lookat:=xlWhole)
ColB = ValB.Column

 Set ValC = ActiveSheet.Rows(1).Find("C", lookat:=xlWhole)
ColC = ValC.Column

 Set ValD = ActiveSheet.Rows(1).Find("D", lookat:=xlWhole)
ColD = ValD.Column

LastRow = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row

'Loop

For i = 2 to LastRow
    If ActiveSheet.Cells(i,ColD).Value/ActiveSheet.Cells(i,ColC).Value <> ActiveSheet.Cells(i, ColB).Value/ActiveSheet(i, ColA).Value Then
        ActiveSheet.Cells(i, ColA).Interior.ColorIndex = 3
        ActiveSheet.Cells(i, ColB).Interior.ColorIndex = 3
        ActiveSheet.Cells(i, ColC).Interior.ColorIndex = 3
        ActiveSheet.Cells(i, ColD).Interior.ColorIndex = 3
    End If
Next i
End Sub

Body:
With Dim ColA, ColB, ColC, ColD as Long only the last is a Long and the others are implicitly variants. You would need to declare each as Long.

Also, ValA etc are Ranges and you want to access the Column property of the Range object.

Dim ValA As Range
Dim ValB As Range
Dim ValC As Range
Dim ValD as Range
Dim ColA As Long
Dim ColB As Long
Dim ColC As Long
Dim ColD as Long

You will also need some error handling in case Find doesn't return a match object.

For example, If "A" not found in row 1 then ValA is Nothing and you will get an error when trying to access the column so handle this with a If Not ValA Is Nothing:

Set ValA = ActiveSheet.Rows(1).Find("A", lookat:=xlWhole)

If Not ValA Is Nothing Then
    ColA = ValA.Column
End If

Something like (and i haven't tested this):

Option Explicit

Public Sub test()

Dim ValA As Range
Dim ValB As Variant
Dim ValC As Variant
Dim ValD As Variant
Dim ColA As Long
Dim ColB As Long
Dim ColC As Long
Dim ColD As Long
Dim i As Long
Dim lastRow As Long

Set ValA = ActiveSheet.Rows(1).Find("A", lookat:=xlWhole)

If Not ValA Is Nothing Then
    ColA = ValA.Column
End If

Set ValB = ActiveSheet.Rows(1).Find("B", lookat:=xlWhole)

If Not ValB Is Nothing Then
    ColB = ValB.Column
End If

Set ValC = ActiveSheet.Rows(1).Find("C", lookat:=xlWhole)

If Not ValC Is Nothing Then
    ColC = ValC.Column
End If

Set ValD = ActiveSheet.Rows(1).Find("D", lookat:=xlWhole)

If Not ValD Is Nothing Then
    ColD = ValD.Column
End If

lastRow = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row

'Loop

If ColA > 0 And ColB > 0 And ColC > 0 And ColD > 0 Then

    For i = 2 To lastRow

        If ActiveSheet.Cells(i, ColD).Value / ActiveSheet.Cells(i, ColC).Value <> ActiveSheet.Cells(i, ColB).Value / ActiveSheet(i, ColA).Value Then

            ActiveSheet.Cells(i, ColA).Interior.ColorIndex = 3
            ActiveSheet.Cells(i, ColB).Interior.ColorIndex = 3
            ActiveSheet.Cells(i, ColC).Interior.ColorIndex = 3
            ActiveSheet.Cells(i, ColD).Interior.ColorIndex = 3

        End If

    Next i

 Else

     MsgBox "Matches weren't found for A,B,C and D in row 1."

End If

End Sub

Option Explicit at the top forces you to declare all your variables and checks the type. Great for catching errors early.

How you choose to handle values not being found is up to you. I have given examples of how to handle the Range object being nothing when Find isn't successful and therefore the associated Column value being 0.

You will want additional error handling for divide by 0 errors e.g. at this part

/ActiveSheet.Cells(i, ColC).Value

And this

/ActiveSheet(i, ColA).Value

Again, how you handle it is up to you.

You might choose a default value, to warn the user, to exit the sub, to On Error Resume Next to skip to the next line, to have a test before the division such

If ActiveSheet(i, ColA).Value = 0 Or ActiveSheet.Cells(i, ColC).Value  = 0 Then Exit Sub


问:
PHP Storm 2017.1 SFTP connection error
I am on MAC OS using PHP STORM 2017.1 upon trying to connect in any form using SFTP I get the error 385. I have tried connecting using FileZilla and successful. Any help would be amazing.

Regards.

答: I've faced the same issue. Check what do you have in ~/Library/Logs/PyCharm2017.1/idea.log. My issue was in malformed ~/.ssh/known_hosts file</p>

Title: PHP Storm 2017.1 SFTP connection error


问:
Redraw image on canvas on touch event?
I am trying to redraw an image on the canvas on an onTouch event. I am able to draw the image on the canvas, but I want the image to redraw at a particular x,y.

```<code>protected void onDraw(Canvas canvas)

{

     mBitmap1   = BitmapFactory.decodeResource(getResources(), R.drawable.ab);
 mBitmap2   = BitmapFactory.decodeResource(getResources(), R.drawable.ab);
 this.canvas=canvas;

     Paint p = new Paint();
    p.setColor(Color.parseColor("#FFFFFF"));

    canvas.drawLine(x1, y1, x2 , y2, p);
    canvas.drawBitmap(mBitmap1, 70, 60, null);
    canvas.drawBitmap(mBitmap1, 185, 60, null);
}

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        final int x=(int)event.getX();
        Log.i("***********xPos","="+x);
        final int y=(int)event.getY();
        Log.i("***********yPos","="+y);

        if(event.getAction()==MotionEvent.ACTION_UP)
        {

        }
        if(event.getAction()==MotionEvent.ACTION_DOWN)
        {
            canvas.drawBitmap(mBitmap1,50+x,60,null );
            this.postInvalidate();

        }
        if(event.getAction()==MotionEvent.ACTION_MOVE)
        {

        }
        return false;
    }
</code>```

答:
I think I understand your problem. You are calling postinvalidate() method each time when action.down is called, so it calls ultimately call ondraw(). So it will redraw it on bitmap for particular setted value at which you put in ondraw again.

So you looks that it remain unchanged.

Follow these steps:

use some public variables for drawing bitmaps in ondraw method for x and y axis, lets say initx and inity

then on touch event:update this value by adding your x and y value to initx and inity resp.

```<code>like:initx=initx+x;
inity=inity+y;
</code>```

And last in cation down event just call post.invalidate or ondraw method.

Title: Redraw image on canvas on touch event?

Body:
I am trying to redraw an image on the canvas on an onTouch event. I am able to draw the image on the canvas, but I want the image to redraw at a particular x,y.

protected void onDraw(Canvas canvas)

{

     mBitmap1   = BitmapFactory.decodeResource(getResources(), R.drawable.ab);
 mBitmap2   = BitmapFactory.decodeResource(getResources(), R.drawable.ab);
 this.canvas=canvas;

     Paint p = new Paint();
    p.setColor(Color.parseColor("#FFFFFF"));

    canvas.drawLine(x1, y1, x2 , y2, p);
    canvas.drawBitmap(mBitmap1, 70, 60, null);
    canvas.drawBitmap(mBitmap1, 185, 60, null);
}

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        final int x=(int)event.getX();
        Log.i("***********xPos","="+x);
        final int y=(int)event.getY();
        Log.i("***********yPos","="+y);

        if(event.getAction()==MotionEvent.ACTION_UP)
        {

        }
        if(event.getAction()==MotionEvent.ACTION_DOWN)
        {
            canvas.drawBitmap(mBitmap1,50+x,60,null );
            this.postInvalidate();

        }
        if(event.getAction()==MotionEvent.ACTION_MOVE)
        {

        }
        return false;
    }

Body:
I think I understand your problem. You are calling postinvalidate() method each time when action.down is called, so it calls ultimately call ondraw(). So it will redraw it on bitmap for particular setted value at which you put in ondraw again.

So you looks that it remain unchanged.

Follow these steps:

use some public variables for drawing bitmaps in ondraw method for x and y axis, lets say initx and inity

then on touch event:update this value by adding your x and y value to initx and inity resp.

like:initx=initx+x;
inity=inity+y;

And last in cation down event just call post.invalidate or ondraw method.

ContentLicense: CC BY-SA 4.0


问:
RequireJS - define function is not returning dependencies correctly
I'm using RequireJS and when I define a new module using the function "define" I see the dependencies were resolved but the objects are not the modules I defined.

All the modules are defined in AMD format, setting a name, array of dependencies and a function. The exportation is done by return an object.

The dependencies resolved by "define" have these properties: exports, id, packaged, and uri. If I then call require function the dependencies are set correctly.

UPDATE: I created a test example with the described issue

HTML:

```<code><!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Test</title>
    <script src="/Scripts/require.js" data-main="../Scripts/main"></script>
    <script src="/Scripts/module.js"></script>
</head>
<body>
    <div>
    </div>
</body>
</html>
</code>```

main.js:

```<code>require(["module"], function (module) {
    module.test();
});
</code>```

module.js:

```<code>define([], function () {

    function test() {
        return "a";
    }

    return {
        test: test
    };
});
</code>```

Console:
Uncaught TypeError: module.test is not a function

This happens because module is not resolved to the real module but to an object with properties:

-config { arguments: null, caller: null, length: 0, name: "config" }

-exports { id: "@r5", uri: "../Scripts/@r5.js" }

Setting a module name in the define function has the same result.

NOTE: in the example there was an issue detected by @Louis. A module cannot be named "module". This helped me fixed the example but didn't fix my real issue. Below I describe the solution.

SOLUTION:

My issue was related to a library called Ace (HTML editor). This is the link that helped me solve it: https://github.com/josdejong/jsoneditor/issues/173

答:
Ok, so after reading

properties: exports, id, packaged, and uri.

I'm guessing, like @Louis said we would, that the example in the OP's question is not the example in the OP's (test-)project.

When defining a module, there are 2 (and lots of more) general ways of doing so.

On of them is explained in the docs titled CommonJS.

If a module is defined with

```<code>define(function(require, exports, module) {

   console.log(module);

});
</code>```

then the 3rd argument module will indeed contain exports, id and uri as in.

```<code>{
   config: function config()
   exports: Object {  }
   id: "js/modules/handgrip/index.js?bust=1512509846564"
   uri: "js/modules/handgrip/index.js?bust=1512509846564&bust=1512509846564"
}
</code>```

In order to "return" your module in the given context, you can export it with

```<code>define(function(require, exports, module) {

   // require a depedency already loaded in context
   var someDep = require('someDep1');

   module.exports = {
      // whatever this module is about ..
   }
});
</code>```

Only if you define the module with a name, followed by dependencies, as in

```<code>define('thename', [ 'someDep1', 'seomDep2', 'etc..' ], function(dep1, dep2, ..) {

   // the arguments in this context are those listed in order as defined in the array (parameters)

}
</code>```

you get your expected results ..

-- update after edit

Was in a Scrum-meeting, sorry ;) So it's quite clear, as @Louis wrote.

module, exports and require are reserved words.

The following have the same results

```<code>define(['require', 'exports', 'module'], function(require, exports, module) {
  console.log(module);
});

define(function(require, exports, module) {
  console.log(module);
});
</code>```

Body:
I'm using RequireJS and when I define a new module using the function "define" I see the dependencies were resolved but the objects are not the modules I defined.

All the modules are defined in AMD format, setting a name, array of dependencies and a function. The exportation is done by return an object.

The dependencies resolved by "define" have these properties: exports, id, packaged, and uri. If I then call require function the dependencies are set correctly.

UPDATE: I created a test example with the described issue

HTML:

<!DOCTYPE html>

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

main.js:

require(["module"], function (module) {
    module.test();
});

module.js:

define([], function () {

    function test() {
        return "a";
    }

    return {
        test: test
    };
});

Console:
Uncaught TypeError: module.test is not a function

This happens because module is not resolved to the real module but to an object with properties:

-config { arguments: null, caller: null, length: 0, name: "config" }

-exports { id: "@r5", uri: "../Scripts/@r5.js" }

Setting a module name in the define function has the same result.

NOTE: in the example there was an issue detected by @Louis. A module cannot be named "module". This helped me fixed the example but didn't fix my real issue. Below I describe the solution.

SOLUTION:

My issue was related to a library called Ace (HTML editor). This is the link that helped me solve it: https://github.com/josdejong/jsoneditor/issues/173

Body:
Ok, so after reading

properties: exports, id, packaged, and uri.

I'm guessing, like @Louis said we would, that the example in the OP's question is not the example in the OP's (test-)project.

When defining a module, there are 2 (and lots of more) general ways of doing so.

On of them is explained in the docs titled CommonJS.

If a module is defined with

define(function(require, exports, module) {

   console.log(module);

});

then the 3rd argument module will indeed contain exports, id and uri as in.

{
   config: function config()
   exports: Object {  }
   id: "js/modules/handgrip/index.js?bust=1512509846564"
   uri: "js/modules/handgrip/index.js?bust=1512509846564&bust=1512509846564"
}

In order to "return" your module in the given context, you can export it with

define(function(require, exports, module) {

   // require a depedency already loaded in context
   var someDep = require('someDep1');

   module.exports = {
      // whatever this module is about ..
   }
});

Only if you define the module with a name, followed by dependencies, as in

define('thename', [ 'someDep1', 'seomDep2', 'etc..' ], function(dep1, dep2, ..) {

   // the arguments in this context are those listed in order as defined in the array (parameters)

}

you get your expected results ..

-- update after edit

Was in a Scrum-meeting, sorry ;) So it's quite clear, as @Louis wrote.

module, exports and require are reserved words.

The following have the same results

define(['require', 'exports', 'module'], function(require, exports, module) {
  console.log(module);
});

define(function(require, exports, module) {
  console.log(module);
});


问:
Expand JSON from DataFrame column
I'd like to expand the JSON data in a DataFrame to have individual columns per KV pair.

```<code>                                                events
0     {u'category': u'8052', u'username': u'NULL', u...
1     {u'category': u'8052', u'username': u'NULL', u...
2     {u'category': u'8052', u'username': u'NULL', u...
3     {u'category': u'8052', u'username': u'NULL', u...
</code>```

I tried a lot of things with map, but none of them did the trick. Mostly because the functions expect strings.

On a related note I get the JSON in one single columns from Python (2.7) requests. The reply had the JSON data, and I read it.

From the function:

```<code>results = requests.get(api_url + "/" + search_id + '/results',
                                  headers=aheaders, verify=False, auth=bauth).text.decode('utf-8')
return json.loads(results)
</code>```

And from the actual call:

```<code>results = pd.DataFrame.from_dict(
            ariel_query(server_ip, usern, passw, token)
)
</code>```

Since expanding the column seems to be quite complex, there might be a simpler approach.

答:
I used json_normalize with a parameter called record_path. As you saw in the listing the column was called events, which is the supplemented value. json_normalize will then return a DataFrame with columns.

```<code>results = json_normalize(
        requests.get(qradar_api_url + "/" + search_id + '/results',
                                  headers=aheaders, verify=False, auth=bauth).json(), record_path=keyword)
</code>```

This is for Python 2.7 (requests is a little different for 3.x)

Title: Expand JSON from DataFrame column

Body:
I'd like to expand the JSON data in a DataFrame to have individual columns per KV pair.

                                                events
0     {u'category': u'8052', u'username': u'NULL', u...
1     {u'category': u'8052', u'username': u'NULL', u...
2     {u'category': u'8052', u'username': u'NULL', u...
3     {u'category': u'8052', u'username': u'NULL', u...

I tried a lot of things with map, but none of them did the trick. Mostly because the functions expect strings.

On a related note I get the JSON in one single columns from Python (2.7) requests. The reply had the JSON data, and I read it.

From the function:

results = requests.get(api_url + "/" + search_id + '/results',
                                  headers=aheaders, verify=False, auth=bauth).text.decode('utf-8')
return json.loads(results)

And from the actual call:

results = pd.DataFrame.from_dict(
            ariel_query(server_ip, usern, passw, token)
)

Since expanding the column seems to be quite complex, there might be a simpler approach.

Body:
I used json_normalize with a parameter called record_path. As you saw in the listing the column was called events, which is the supplemented value. json_normalize will then return a DataFrame with columns.

results = json_normalize(
        requests.get(qradar_api_url + "/" + search_id + '/results',
                                  headers=aheaders, verify=False, auth=bauth).json(), record_path=keyword)

This is for Python 2.7 (requests is a little different for 3.x)


问:
Barplots with grouping by multiple factors
I want to make a plot that looks like this in ggplot2:

Here's a dummy dataset:

```<code>set.seed(1)
dat <- data.frame(x = exp(rnorm(6)),
                  f1 = factor(c("a","b","c","c","d","d")),
                  f2 = factor(c("","","1","2","1","2")))
</code>```

And a non-working example:

```<code>ggplot(data=dat, aes(x=f1, y=x, fill= f2)) +
  geom_bar(stat="identity", width=0.9)+
  scale_fill_manual(values=c("red", "blue", rep("green",4)))
</code>```

I could do this by brute force in base graphics, but I'm unsure how to go about it in ggplot2, and I need to use ggplot2 so as to keep this plot consistent with the theme I'm using throughout the project.

So how do I make the factors 1 and 2 go side by side?  And how do I center the labels like I have in the drawing?  And how do I make the colors behave?

答:
You are trying to make a barplot with grouped bars, a question that was answered  here: Grouped bar plot in ggplot

fill only determines the colors, not the grouping, this is why you get blue and green bars for c and d.

Body:
I want to make a plot that looks like this in ggplot2:

Here's a dummy dataset:

set.seed(1)
dat <- data.frame(x = exp(rnorm(6)),
                  f1 = factor(c("a","b","c","c","d","d")),
                  f2 = factor(c("","","1","2","1","2")))

And a non-working example:

ggplot(data=dat, aes(x=f1, y=x, fill= f2)) +
  geom_bar(stat="identity", width=0.9)+
  scale_fill_manual(values=c("red", "blue", rep("green",4)))

I could do this by brute force in base graphics, but I'm unsure how to go about it in ggplot2, and I need to use ggplot2 so as to keep this plot consistent with the theme I'm using throughout the project.

So how do I make the factors 1 and 2 go side by side?  And how do I center the labels like I have in the drawing?  And how do I make the colors behave?


问:
Create a matrix where each value depends on it's own indices
I want to create a n*n matrix with entries Aij = 5/(i + 2j -1).

It's easy enough with a couple of for loops but I just wondered if there was a built in functionality that could do this?

答:
Another possibility, even if less elegant and simple of the one proposed by @bla:

```<code>x=5./(bsxfun(@plus,2:2:n*2,(0:n-1)'))
</code>```

The denominator of the first row is 2:2:n*2, the other rows are simply the previous row +1.

Body:
Another possibility, even if less elegant and simple of the one proposed by @bla:

x=5./(bsxfun(@plus,2:2:n*2,(0:n-1)'))

The denominator of the first row is 2:2:n*2, the other rows are simply the previous row +1.


问:
NSInvalidArgumentException between Swift & Objective-C
I am working on a project that's using both Objective-C and swift.  We're using the bridge to connect them together.

I have a swift class that needs to call a delegate function, but I keep getting NSInvalidArgumentExceptions when I try to call the Objective-C function.

View (Swift):

```<code>// the-view.swift
//...
@objc public protocol YMUReceiptsContainerViewDelegate: Any {
    func receiptsContainerView(view: YMUReceiptsContainerView, didOpenAuthViewWithURL: NSString)
}
//...

func triggerUpdate() {
    // Calling this "triggerUpdate" function throws NSInvalidArgumentException
   // NOTE: self.delegate is the controller-view

    self.delegate?.receiptsContainerView(view:self, didOpenAuthViewWithURL:NSString(string: "https://yahoo.com"))
}
</code>```

Delegate (Objective-C):

```<code>// the-view-controller.m
//...
- (void)receiptsContainerView: (YMUReceiptsContainerView *)view didOpenAuthViewWithURL:(NSString *)url {
    //do stuff...
}
//...
</code>```

When I call the "triggerUpdate()" function from Swift, I get the NSInvalidArgumentException.  Is it clear to anyone what I'm doing wrong?  I can't seem to get the arguments to play nicely between Swift & Objective-C.

答:
I got the answer... The way that I defined the arguments in my protocol was wrong.  I needed to change the first parameter in the protocol to not require a label.  Adding "_" before the first parameter fixed the problem.

```<code>// the-view.swift
//...
@objc public protocol YMUReceiptsContainerViewDelegate: Any {
    // Adding the "_" before "view" makes the parameter not require a label.
    func receiptsContainerView(_ view: YMUReceiptsContainerView,
         didOpenAuthViewWithURL: NSString)
    }
//...

func triggerUpdate() {
    // Removed the "view" label when calling the function too...

    self.delegate?.receiptsContainerView(self,
        didOpenAuthViewWithURL:NSString(string: "https://yahoo.com"))
}
</code>```

With just that one small change, everything works.  The crux of the problem was that when I defined the function in Objective-C, the first parameter doesn't have a label.  Then, in my delegate, I was defining the param with a label.  So, the arguments weren't being passed correctly from Swift to Obj-C.  Adding the "_" before the first param in the protocol made params map correctly.

Body:
I am working on a project that's using both Objective-C and swift.  We're using the bridge to connect them together.

I have a swift class that needs to call a delegate function, but I keep getting NSInvalidArgumentExceptions when I try to call the Objective-C function.

View (Swift):

// the-view.swift
//...
@objc public protocol YMUReceiptsContainerViewDelegate: Any {
    func receiptsContainerView(view: YMUReceiptsContainerView, didOpenAuthViewWithURL: NSString)
}
//...

func triggerUpdate() {
    // Calling this "triggerUpdate" function throws NSInvalidArgumentException
   // NOTE: self.delegate is the controller-view

    self.delegate?.receiptsContainerView(view:self, didOpenAuthViewWithURL:NSString(string: "https://yahoo.com"))
}

Delegate (Objective-C):

// the-view-controller.m
//...
- (void)receiptsContainerView: (YMUReceiptsContainerView *)view didOpenAuthViewWithURL:(NSString *)url {
    //do stuff...
}
//...

When I call the "triggerUpdate()" function from Swift, I get the NSInvalidArgumentException.  Is it clear to anyone what I'm doing wrong?  I can't seem to get the arguments to play nicely between Swift & Objective-C.

Body:
I got the answer... The way that I defined the arguments in my protocol was wrong.  I needed to change the first parameter in the protocol to not require a label.  Adding "_" before the first parameter fixed the problem.

// the-view.swift
//...
@objc public protocol YMUReceiptsContainerViewDelegate: Any {
    // Adding the "_" before "view" makes the parameter not require a label.
    func receiptsContainerView(_ view: YMUReceiptsContainerView,
         didOpenAuthViewWithURL: NSString)
    }
//...

func triggerUpdate() {
    // Removed the "view" label when calling the function too...

    self.delegate?.receiptsContainerView(self,
        didOpenAuthViewWithURL:NSString(string: "https://yahoo.com"))
}

With just that one small change, everything works.  The crux of the problem was that when I defined the function in Objective-C, the first parameter doesn't have a label.  Then, in my delegate, I was defining the param with a label.  So, the arguments weren't being passed correctly from Swift to Obj-C.  Adding the "_" before the first param in the protocol made params map correctly.


问:
Android Studio, SDK adb.exe
In Android Studio 1.3.2

Android SDK adb.exe missing(AVG flagged adb.exe,
tried copying only adb.exe from externally downloaded source to Android\sdk\platform-tools... but it says you have no permission and I can't bypass the permission),

gives me this error when trying to install Android SDK Platform-tools from sdk manager,

"revision 23.0.1 Stopping ADB server failed (code -1). Unzip failed: C:\Users\Personal\AppData\Local\Android\sdk\platform-tools\adb.exe (Access is denied) Done. Nothing was installed."

答:
This happened to me just now with Android Studio 3.0.1 right after I updated it to test programs on my physical phone instead of a virtual one. It's made me a bit paranoid.

To get "instant run" to work I had to download a bunch of files having to do with my phone's OS (6.0.1 Marshmallow).  I think this was the cause of the problem.

Title: Android Studio, SDK adb.exe


问:
How do I check if an image:tag exists in gitlab container registry
I know that this can be done with dockerhub. I want to know if there is something similar available for gitlab registry.

The use case is that, I have written a fabric script to revert a deployment to a particular tag provided by the user. Before actually pulling in the images, I want to know whether an image with the specified tag exists in the registry and warn the user accordingly.

I've searched in their documentation, but couldn't find anything.

Note: User here is the person who is deploying the code.

答:
Unless the GitLab Container Registry supports the kind of curl dockerhub does (with v1/repositories/$1/tags/$2), I doubt it offers that feature.

For instance, issue 26866 "GitLab Registry available images list/search" is still open after 10 months.

Update for GitLab 12.2 (April 2019, 18 months later)

After working through the implementation, it made sense to create two endpoints:

GET /groups/:id/registry/repositories - Returns a list of all Docker container repositories for all projects within the group, similar to GET /projects/:id/registry/repositories

and

GET /groups/:id/registry/repositories/tags - Returns a list of all Docker container repositories for all projects within the group including all tags for each container repository. The response will look something like this:

So that could help checking if an image:tag exists.

Update GitLab 13.0 (May 2020)

Use search to quickly find and discover images hosted in the GitLab Container Registry

When you or someone on your team publishes an image to the GitLab Container Registry, you need a way to quickly find it and ensure the image was built properly.

If you’re using GitLab CI/CD to publish images with each build, it’s been very difficult to find an image efficiently within the current user interface. Instead, you’ve relied on the command line or the API.

We are excited to announce that in 13.0, we’ve added search functionality to the GitLab Container Registry.

Simply navigate to your project or group’s registry and enter an image name to see a list of all your images.

See documentation and issue.

See also GitLab 14.7 (January 2022)

Sort Docker tags in the Container Registry browser

You can now sort the list of tags in the Container Registry tag details page by name.

Previously, there was no sort functionality. This sometimes required you to scroll through many pages to find a specific tag.

By default, the tags list is now sorted by name in ascending order. You may also change the sort order to descending.

See this issue to track any further work on tag sorting.

See Documentation and Issue.


问:
How do you extract the lat and lon from a GeoPt property?
I'm extending the GeoModel to store locations in the datastore so I can do geo-based searches more efficiently and I assumed I could use the GeoPt property to store latitude and longitude. And the storage has worked fine. But I'm at a complete loss as to how to extract the lat and lon from an entity.

I must be missing something simple but I can't actually find the documentation for the GeoPt type so I'm looking for help on supported methods.

```<code>class StopLocation(GeoModel):
    stopID = db.StringProperty()

def create(stopID,lat,lon):
    stop = StopLocation()
    stop.stopID = stopID
    stop.location = GeoPt(lat,lon)

latitude = stop.location???
</code>```

答:
```<code>latitude = stop.location.lat
longitude = stop.location.lon
</code>```

Does that not work?

Body:
I'm extending the GeoModel to store locations in the datastore so I can do geo-based searches more efficiently and I assumed I could use the GeoPt property to store latitude and longitude. And the storage has worked fine. But I'm at a complete loss as to how to extract the lat and lon from an entity.

I must be missing something simple but I can't actually find the documentation for the GeoPt type so I'm looking for help on supported methods.

class StopLocation(GeoModel):
    stopID = db.StringProperty()

def create(stopID,lat,lon):
    stop = StopLocation()
    stop.stopID = stopID
    stop.location = GeoPt(lat,lon)

latitude = stop.location???

Body:
latitude = stop.location.lat
longitude = stop.location.lon

Does that not work?


问:
How do I make sure there are no repeated numbers when using random()?
I have this code that displays 100 random numbers, then adds a break for every 10 numbers. How would I ensure that these 100 random numbers do not have repeats? I know maybe there's something to do with more if statements?

Thanks,
J

<!DOCTYPE html>

Random Numbers and Breaks (for loops)

This will display 100 numbers and insert a break in 10-number intervals:

```

答:
You can use Fischer yates algorithm for shuffling an array and shuffle an array from 1 to 100.</p>

```<code>// Returns num size random array from 1 to num
function getRandomArray(num) {
  const arr = [];

  for (let i = 0; i < num; i++) {
    arr.push(i+1);
  }
  let temp, rIndex;
  // swap random element
  for (i = num - 1; i >= 0; i--) {
    rIndex = Math.floor(Math.random()*i);
    temp = arr[i];
    arr[i] = arr[rIndex];
    arr[rIndex] = temp;
  }

  return arr;
}

let text = '';
getRandomArray(100).forEach(function(item, index){
  text += item + " <br />";
  text += (index + 1)%10 === 0 ? "<br />" : "";
});
document.getElementById("demo").innerHTML = text;
</code>```

Body:
You can use Fischer yates algorithm for shuffling an array and shuffle an array from 1 to 100.

// Returns num size random array from 1 to num
function getRandomArray(num) {
  const arr = [];

  for (let i = 0; i < num; i++) {
    arr.push(i+1);
  }
  let temp, rIndex;
  // swap random element
  for (i = num - 1; i >= 0; i--) {
    rIndex = Math.floor(Math.random()*i);
    temp = arr[i];
    arr[i] = arr[rIndex];
    arr[rIndex] = temp;
  }

  return arr;
}

let text = '';
getRandomArray(100).forEach(function(item, index){
  text += item + " <br />";
  text += (index + 1)%10 === 0 ? "<br />" : "";
});
document.getElementById("demo").innerHTML = text;


问:
I've deleted all the files in my directory. How can I get them back?
I'm new to Perforce and, to be honest, I'm hating it.
I had about 20 files in my c:\workspaces\perforce directory and I selected all of them and hit the delete key.
They were all checked in before I deleted them.
I've been pulling my hair out trying to figure out how to get them back (Perforce is sooooo unintuitive) but there's nothing that stands out to a n00b like me to.

How can I get the latest revisions back into the directory from Perforce?

答:
In my case I tried everything and I couldn't get all of my files to revert, so I tried deleting them and then I couldn't get all of them back. I restarted my pc, and tried numerous solutions found online. In the end my problem was solved by one or all of the following: upgrading to the latest P4V application, running the application with elevated permissions, and going to lunch after forcing get latest.

If you wasted half of a day. You may want to try the above.


问:
HTML Event: how to handle "click" and "text selection" event separately in dojo dgrid-row?
I am using dojo dgrid for table representation. I have handled a row click event with grid.on('.dgrid-content .dgrid-row:click', function(){ // Open a Dialog}). But the problem I am facing here is: while user is trying to select any text on the row with a hope to copy, the event eventually ends up opening the dialog.

As per my knowledge, HTML5 has the support of ondrag event, but that is not working in my case. What are the other ways to separate these two events and handle accordingly?

Thanks in advance.

答:
You can distinguish select from click in following way inside of your click handler:</p>

```<code>clickHandler: function () {
            var collapsed = window.getSelection().isCollapsed;
            if (collapsed) {
                console.log("Clicked");
                //Open dialog
            } else {
                console.log("Selected");
                //Do something else
            }
        }
</code>```

Body:
You can distinguish select from click in following way inside of your click handler:

clickHandler: function () {
            var collapsed = window.getSelection().isCollapsed;
            if (collapsed) {
                console.log("Clicked");
                //Open dialog
            } else {
                console.log("Selected");
                //Do something else
            }
        }


问:
Django ImageField save to locations
I'm able to upload photos to the media folder just fine. My problem is I can't save them to a specific folder on upload. I want the image to be saved in a unique folder based on an id being passed into the django view. Below is the code that throws the following error:

views.py", line 90, in orderdetails
      settings.MEDIA_ROOT + '/orders/' + str(orderid) + '/' + image)
  TypeError: coercing to Unicode: need string or buffer, InMemoryUploadedFile found

```<code>if request.method == 'POST':
    # Loop through our files in the files list uploaded
    if not os.path.exists(settings.MEDIA_ROOT + '/orders/' + str(orderid)):
        os.makedirs(settings.MEDIA_ROOT + '/orders/' + str(orderid))
    for image in request.FILES.getlist('files[]'):
        # Create a new entry in our database
        new_image = UploadedImages(client_order=client, image=image.name)
        # Save the image using the model's ImageField settings
        filename, ext = os.path.splitext(image.name)
        new_image.image.save("%s-%s%s" % (filename, datetime.datetime.now(), ext),
                             settings.MEDIA_ROOT + '/orders/' + str(orderid) + '/' + image)
        new_image.save()
</code>```

If i just use image it saves just find in the media folder. Which is the code below. I know I set a folder inside my model with upload_to. Even with that I'm unsure how to set it to a folder based off of the ordierid.

```<code>if request.method == 'POST':
    # Loop through our files in the files list uploaded
    if not os.path.exists(settings.MEDIA_ROOT + '/orders/' + str(orderid)):
        os.makedirs(settings.MEDIA_ROOT + '/orders/' + str(orderid))
    for image in request.FILES.getlist('files[]'):
        # Create a new entry in our database
        new_image = UploadedImages(client_order=client, image=image.name)
        # Save the image using the model's ImageField settings
        filename, ext = os.path.splitext(image.name)
        new_image.image.save("%s-%s%s" % (filename, datetime.datetime.now(), ext), image)
        new_image.save()
</code>```

答:
You're trying to concatenate a string and a file object '/' + image

You probably want the name of the file here, so try '/' + image.name

That may return some additional path information, so you would have to strip that out to get just the file name.

Title: Django ImageField save to locations

Body:
I'm able to upload photos to the media folder just fine. My problem is I can't save them to a specific folder on upload. I want the image to be saved in a unique folder based on an id being passed into the django view. Below is the code that throws the following error:

views.py", line 90, in orderdetails
      settings.MEDIA_ROOT + '/orders/' + str(orderid) + '/' + image)
  TypeError: coercing to Unicode: need string or buffer, InMemoryUploadedFile found

if request.method == 'POST':
    # Loop through our files in the files list uploaded
    if not os.path.exists(settings.MEDIA_ROOT + '/orders/' + str(orderid)):
        os.makedirs(settings.MEDIA_ROOT + '/orders/' + str(orderid))
    for image in request.FILES.getlist('files[]'):
        # Create a new entry in our database
        new_image = UploadedImages(client_order=client, image=image.name)
        # Save the image using the model's ImageField settings
        filename, ext = os.path.splitext(image.name)
        new_image.image.save("%s-%s%s" % (filename, datetime.datetime.now(), ext),
                             settings.MEDIA_ROOT + '/orders/' + str(orderid) + '/' + image)
        new_image.save()

If i just use image it saves just find in the media folder. Which is the code below. I know I set a folder inside my model with upload_to. Even with that I'm unsure how to set it to a folder based off of the ordierid.

if request.method == 'POST':
    # Loop through our files in the files list uploaded
    if not os.path.exists(settings.MEDIA_ROOT + '/orders/' + str(orderid)):
        os.makedirs(settings.MEDIA_ROOT + '/orders/' + str(orderid))
    for image in request.FILES.getlist('files[]'):
        # Create a new entry in our database
        new_image = UploadedImages(client_order=client, image=image.name)
        # Save the image using the model's ImageField settings
        filename, ext = os.path.splitext(image.name)
        new_image.image.save("%s-%s%s" % (filename, datetime.datetime.now(), ext), image)
        new_image.save()


问:
Enum Naming Convention - Plural
I'm asking this question despite having read similar but not exactly what I want at C# naming convention for enum and matching property

I found I have a tendency to name enums in plural and then 'use' them as singular, example:

```<code>public enum EntityTypes {
  Type1, Type2
}

public class SomeClass {
  /*
    some codes
  */

  public EntityTypes EntityType {get; set;}

}
</code>```

Of course it works and this is my style, but can anyone find potential problem with such convention? I do have an "ugly" naming with the word "Status" though:

```<code>public enum OrderStatuses {
  Pending, Fulfilled, Error, Blah, Blah
}

public class SomeClass {
  /*
    some codes
  */

  public OrderStatuses OrderStatus {get; set;}

}
</code>```

Additional Info:
Maybe my question wasn't clear enough. I often have to think hard when naming the variables of the my defined enum types. I know the best practice, but it doesn't help to ease my job of naming those variables.

I can't possibly expose all my enum properties (say "Status") as "MyStatus".

My question: Can anyone find potential problem with my convention described above? It is NOT about best practice.

Question rephrase:

Well, I guess I should ask the question this way: Can someone come out a good generic way of naming the enum type such that when used, the naming of the enum 'instance' will be pretty straightforward?

答:
This is one of the few places that I disagree with the convention enough to go against it. TBH, I HATE that the definition of an enum and the instance of it can have the same name. I postfix all of my Enums with "Enum" specifically because it makes it clear what the context of it is in any given usage. IMO it makes the code much more readable.

```<code>public enum PersonTypesEnum {
    smart,
    sad,
    funny,
    angry
}

public class Person {
    public PersonTypesEnum PersonType {get; set;}
}
</code>```

Nobody will ever confuse what is the enum and what is the instance of it.

Title: Enum Naming Convention - Plural

Body:
I'm asking this question despite having read similar but not exactly what I want at C# naming convention for enum and matching property

I found I have a tendency to name enums in plural and then 'use' them as singular, example:

public enum EntityTypes {
  Type1, Type2
}

public class SomeClass {
  /*
    some codes
  */

  public EntityTypes EntityType {get; set;}

}

Of course it works and this is my style, but can anyone find potential problem with such convention? I do have an "ugly" naming with the word "Status" though:

public enum OrderStatuses {
  Pending, Fulfilled, Error, Blah, Blah
}

public class SomeClass {
  /*
    some codes
  */

  public OrderStatuses OrderStatus {get; set;}

}

Additional Info:
Maybe my question wasn't clear enough. I often have to think hard when naming the variables of the my defined enum types. I know the best practice, but it doesn't help to ease my job of naming those variables.

I can't possibly expose all my enum properties (say "Status") as "MyStatus".

My question: Can anyone find potential problem with my convention described above? It is NOT about best practice.

Question rephrase:

Well, I guess I should ask the question this way: Can someone come out a good generic way of naming the enum type such that when used, the naming of the enum 'instance' will be pretty straightforward?

Body:
This is one of the few places that I disagree with the convention enough to go against it. TBH, I HATE that the definition of an enum and the instance of it can have the same name. I postfix all of my Enums with "Enum" specifically because it makes it clear what the context of it is in any given usage. IMO it makes the code much more readable.

public enum PersonTypesEnum {
    smart,
    sad,
    funny,
    angry
}

public class Person {
    public PersonTypesEnum PersonType {get; set;}
}

Nobody will ever confuse what is the enum and what is the instance of it.


问:
Chai logs error into console instead of failing the test
I have the following test code that verifies that after calling a function that returns a promise, the resulting array is the same as the stubbed one.

```<code>it('Should return locations', () => {
  const result = loginSvc.getLocations()

  expect(result).to.eventually.eql(['location1', 'asd', 'location3', 'location4', 'location5'])
})
</code>```

loginSvc.getLocations() is just a function that is mocked and returns an array: ['location1', 'location2', 'location3', 'location4', 'location5']

When I run the test it doesn't fail as it should or even succeed as a false positive, and in the console I get this:

ERROR LOG: 'Unhandled promise rejection', AssertionError{message: 'expected [ Array(5) ] to have the same members as [ Array(5) ]', showDiff: true, actual: ['location1', 'location2', 'location3', 'location4', 'location5'], expected: ['location1', 'asd', 'location3', 'location4', 'location5'], stack: 'AssertionError@http://localhost:9000/base/node_modules/chai/chai.js?40e7aa72e9665366bfd82579520de4fb0754dfae:9320:24
  assert@http://localhost:9000/base/node_modules/chai/chai.js?40e7aa72e9665366bfd82579520de4fb0754dfae:239:31
  somethingMethod@http://localhost:9000/base/node_modules/chai-things/lib/chai-things.js?da5f13ef7d7d30f512b1cd8c3a12b3ed43cd7d31:97:30
  overwritingMethodWrapper@http://localhost:9000/base/node_modules/chai/chai.js?40e7aa72e9665366bfd82579520de4fb0754dfae:8932:38
  allMethod@http://localhost:9000/base/node_modules/chai-things/lib/chai-things.js?da5f13ef7d7d30f512b1cd8c3a12b3ed43cd7d31:165:30
  overwritingMethodWrapper@http://localhost:9000/base/node_modules/chai/chai.js?40e7aa72e9665366bfd82579520de4fb0754dfae:8932:38
  http://localhost:9000/base/node_modules/chai/chai.js?40e7aa72e9665366bfd82579520de4fb0754dfae:3379:16
  methodWrapper@http://localhost:9000/base/node_modules/chai/chai.js?40e7aa72e9665366bfd82579520de4fb0754dfae:7709:30
  http://localhost:9000/base/node_modules/chai-as-promised/lib/chai-as-promised.js?ac71de40b7ca85a0488f7d3c971a22ddd0e149a8:308:31
  run@http://localhost:9000/base/spec.js?20bf9e1ddf32e8fc2bfe38226be11b7e65336abf:72447:29
  http://localhost:9000/base/spec.js?20bf9e1ddf32e8fc2bfe38226be11b7e65336abf:72460:33
  flush@http://localhost:9000/base/spec.js?20bf9e1ddf32e8fc2bfe38226be11b7e65336abf:72685:11', line: 243, sourceURL: 'http://localhost:9000/base/node_modules/chai/chai.js?40e7aa72e9665366bfd82579520de4fb0754dfae'}

But the test passes

答:
I believe I found a solution, or rather a workaround:</p>

```<code>it('Should return locations', done => {
  loginSvc.getLocations()
    .then(locations => {
      expect(locations ).to.eql(['location1', 'asd', 'location3', 'location4', 'location5'])
      done()
    })
    .catch(done)
})
</code>```

Body:
I have the following test code that verifies that after calling a function that returns a promise, the resulting array is the same as the stubbed one.

it('Should return locations', () => {
  const result = loginSvc.getLocations()

  expect(result).to.eventually.eql(['location1', 'asd', 'location3', 'location4', 'location5'])
})

loginSvc.getLocations() is just a function that is mocked and returns an array: ['location1', 'location2', 'location3', 'location4', 'location5']

When I run the test it doesn't fail as it should or even succeed as a false positive, and in the console I get this:

ERROR LOG: 'Unhandled promise rejection', AssertionError{message: 'expected [ Array(5) ] to have the same members as [ Array(5) ]', showDiff: true, actual: ['location1', 'location2', 'location3', 'location4', 'location5'], expected: ['location1', 'asd', 'location3', 'location4', 'location5'], stack: 'AssertionError@http://localhost:9000/base/node_modules/chai/chai.js?40e7aa72e9665366bfd82579520de4fb0754dfae:9320:24
  assert@http://localhost:9000/base/node_modules/chai/chai.js?40e7aa72e9665366bfd82579520de4fb0754dfae:239:31
  somethingMethod@http://localhost:9000/base/node_modules/chai-things/lib/chai-things.js?da5f13ef7d7d30f512b1cd8c3a12b3ed43cd7d31:97:30
  overwritingMethodWrapper@http://localhost:9000/base/node_modules/chai/chai.js?40e7aa72e9665366bfd82579520de4fb0754dfae:8932:38
  allMethod@http://localhost:9000/base/node_modules/chai-things/lib/chai-things.js?da5f13ef7d7d30f512b1cd8c3a12b3ed43cd7d31:165:30
  overwritingMethodWrapper@http://localhost:9000/base/node_modules/chai/chai.js?40e7aa72e9665366bfd82579520de4fb0754dfae:8932:38
  http://localhost:9000/base/node_modules/chai/chai.js?40e7aa72e9665366bfd82579520de4fb0754dfae:3379:16
  methodWrapper@http://localhost:9000/base/node_modules/chai/chai.js?40e7aa72e9665366bfd82579520de4fb0754dfae:7709:30
  http://localhost:9000/base/node_modules/chai-as-promised/lib/chai-as-promised.js?ac71de40b7ca85a0488f7d3c971a22ddd0e149a8:308:31
  run@http://localhost:9000/base/spec.js?20bf9e1ddf32e8fc2bfe38226be11b7e65336abf:72447:29
  http://localhost:9000/base/spec.js?20bf9e1ddf32e8fc2bfe38226be11b7e65336abf:72460:33
  flush@http://localhost:9000/base/spec.js?20bf9e1ddf32e8fc2bfe38226be11b7e65336abf:72685:11', line: 243, sourceURL: 'http://localhost:9000/base/node_modules/chai/chai.js?40e7aa72e9665366bfd82579520de4fb0754dfae'}

But the test passes

Body:
I believe I found a solution, or rather a workaround:

it('Should return locations', done => {
  loginSvc.getLocations()
    .then(locations => {
      expect(locations ).to.eql(['location1', 'asd', 'location3', 'location4', 'location5'])
      done()
    })
    .catch(done)
})


问:
Application not opened in android
I developed the LWUIT based android application.
But that application could not opened in emulator.
I used eclipse 3.6.1 and android 2.2.
Can anyone tell me the proper steps for developing the LWUIT based android application?</p>

答: I used LWUITActivity class for Android application. LWUIT framework having own activity class for developing Android application. For more info see this link.</p>

Title: Application not opened in android


问:
Apollo GraphQL map list entities from multiple sources
There is an entity list that has data from two sources. Dimensions like id, name, label, ... and metrics like games played, wins and so on.
Those are stored in different endpoints. I want to query filtered data from one source and having ids ask for data from another source at once, not by one entity by one of all entities? A primary set of the list can be queried from both or resources depending on sort options.</p>

答:
You could define a query that accepts one or a list of arguments. The resolver would make the two requests and when the responses come back, merge them and return the merged list.

Check out this launchpad for an example of what I'm saying.