问:
How to copy entire row based on Percentage comparison of 2 Cells
I'm trying to copy an entire row to another sheet if a cell is greater than 2% of another cell in the same row. This is what I'm stuck, getting an IF Greater based off a formula comparing 2 cells:

```<code>Sub Filtration()

For Each Cell In Sheets(1).Range("R:R")
    If Formula = "(R1 / P1)" > 0.021 Then
        matchRow = Cell.Row
        Rows(matchRow & ":" & matchRow).Select
        Selection.Copy

        Sheets("Sheet2").Select
        ActiveSheet.Rows(matchRow).Select
        Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
        Sheets("Sheet1").Select
    End If
Next
</code>```

EDIT: Thanks to @JNevil & @ShaiRado and the help they provide, I think I'm only stuck on the Macro returning an Overflow. I think that the percentage = Cell.Value / Cell.Offset(, -2).Value is being confused/conflicted some how and believes that percentage = 0 always. There is also the issue that my Sheet1 contains blank lines, a header, and possible negative numbers on future updates. The full code is as follows:

```<code>Sub Filtration()

Dim writeRow As Integer
Dim percentage As Double

For Each Cell In Sheets(1).Range("R:R")

    'because we don't want to do this for every cell in Column R (There are one million), then exit the loop when we need to
    If Cell.Value = "" Or Cell.Value <= 0 Then

    'Lets make sure we won't be dividing by zero. If we are then set the result to 0
    If Cell.Offset(, -2).Value < 0 Then
        percentage = 0
    Else

        percentage = Cell.Value / Cell.Offset(, -2).Value

    End If

    'divide the current cell's value by the the cell one column over's value and compare
    If percentage > 0.021 Then

        'Write this out to the writeRow variable in the other sheet and increment that number by 1 after writing
        Sheet1.Rows(Cell.Row).Copy Destination:=Sheet2.Cells(writeRow, 1).Paste
        writeRow = writeRow + 1
    End If
    End If
Next
    End Sub
</code>```

答:
For having only been writing VBA for a week, you are doing a pretty good job here. Most people avoid For loops like the plague when they are learning.

A couple of things.

Avoid .select that is a user interface thing. VBA doesn't need to "Select" anything. You just point it at a range or a cell or a object and do what you need it to do.

Avoid activesheet and activeworkbook. When you are a couple hundred lines of code down don't risk assuming that you know what will be the active sheet or active workbook at that point in time. Don't trust it. Be explicit ThisWorkbook.Sheets("mysheetname") or similar.

Do the math in VBA. Don't call formula or whatever. VBA is good at it.

Something like the following should get you in the ballpark:

```<code>Sub Filtration()

    For Each Cell In Sheets(1).Range("R:R")
        'divide the current cell's value by the the cell one column over's value and compare
        If cell.value/cell.offset(,-2).value > .021 Then
            Sheet1.Rows(cell.row).Copy Destination:=Sheet2.Cells(cell.row, 1)
            'because we don't want to do this for every cell in Column R (There are one million), then exit the loop when we need to
            If cell.value = "" Then Exit For
        End If
    Next
</code>```

You may want to write to the other sheet without jumping rows. In that case you can employ a variable to track which row to write to:

```<code>Sub Filtration()
    Dim writeRow as integer

    For Each Cell In Sheets(1).Range("R:R")

        'because we don't want to do this for every cell in Column R (There are one million), then exit the loop when we need to
        If cell.value = "" Then Exit For

        'divide the current cell's value by the the cell one column over's value and compare
        If cell.value/cell.offset(,-2).value > .021 Then

            'Write this out to the writeRow variable in the other sheet and increment that number by 1 after writing
            Sheet1.Rows(cell.row).Copy Destination:=Sheet2.Cells(writeRow, 1)
            writeRow = writeRow + 1

        End If
    Next
</code>```

Because dividing by zero will cause this code to fail, it may be a good idea to do your division before you check the result in the if statement. You can use a variable to capture the value for later comparison:

```<code>Sub Filtration()
    Dim writeRow as integer
    Dim percentage as double

    For Each Cell In Sheets(1).Range("R:R")

        'because we don't want to do this for every cell in Column R (There are one million), then exit the loop when we need to
        If cell.value = "" Then Exit For

        'Lets make sure we won't be dividing by zero. If we are then set the result to 0
        if cell.offset(,-2).value = 0 Then
            percentage = 0
        else
            percentage=cell.value/cell.offset(,-2).value
        end if

        'divide the current cell's value by the the cell one column over's value and compare
        If  percentage > .021 Then

            'Write this out to the writeRow variable in the other sheet and increment that number by 1 after writing
            Sheet1.Rows(cell.row).Copy Destination:=Sheet2.Cells(writeRow, 1)
            writeRow = writeRow + 1

        End If
    Next
</code>```

Body:
I'm trying to copy an entire row to another sheet if a cell is greater than 2% of another cell in the same row. This is what I'm stuck, getting an IF Greater based off a formula comparing 2 cells:

Sub Filtration()

For Each Cell In Sheets(1).Range("R:R")
    If Formula = "(R1 / P1)" > 0.021 Then
        matchRow = Cell.Row
        Rows(matchRow & ":" & matchRow).Select
        Selection.Copy

        Sheets("Sheet2").Select
        ActiveSheet.Rows(matchRow).Select
        Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
        Sheets("Sheet1").Select
    End If
Next

EDIT: Thanks to @JNevil & @ShaiRado and the help they provide, I think I'm only stuck on the Macro returning an Overflow. I think that the percentage = Cell.Value / Cell.Offset(, -2).Value is being confused/conflicted some how and believes that percentage = 0 always. There is also the issue that my Sheet1 contains blank lines, a header, and possible negative numbers on future updates. The full code is as follows:

Sub Filtration()

Dim writeRow As Integer
Dim percentage As Double

For Each Cell In Sheets(1).Range("R:R")

    'because we don't want to do this for every cell in Column R (There are one million), then exit the loop when we need to
    If Cell.Value = "" Or Cell.Value <= 0 Then

    'Lets make sure we won't be dividing by zero. If we are then set the result to 0
    If Cell.Offset(, -2).Value < 0 Then
        percentage = 0
    Else

        percentage = Cell.Value / Cell.Offset(, -2).Value

    End If

    'divide the current cell's value by the the cell one column over's value and compare
    If percentage > 0.021 Then

        'Write this out to the writeRow variable in the other sheet and increment that number by 1 after writing
        Sheet1.Rows(Cell.Row).Copy Destination:=Sheet2.Cells(writeRow, 1).Paste
        writeRow = writeRow + 1
    End If
    End If
Next
    End Sub

Body:
For having only been writing VBA for a week, you are doing a pretty good job here. Most people avoid For loops like the plague when they are learning.

A couple of things.

Avoid .select that is a user interface thing. VBA doesn't need to "Select" anything. You just point it at a range or a cell or a object and do what you need it to do.

Avoid activesheet and activeworkbook. When you are a couple hundred lines of code down don't risk assuming that you know what will be the active sheet or active workbook at that point in time. Don't trust it. Be explicit ThisWorkbook.Sheets("mysheetname") or similar.

Do the math in VBA. Don't call formula or whatever. VBA is good at it.

Something like the following should get you in the ballpark:

Sub Filtration()

    For Each Cell In Sheets(1).Range("R:R")
        'divide the current cell's value by the the cell one column over's value and compare
        If cell.value/cell.offset(,-2).value > .021 Then
            Sheet1.Rows(cell.row).Copy Destination:=Sheet2.Cells(cell.row, 1)
            'because we don't want to do this for every cell in Column R (There are one million), then exit the loop when we need to
            If cell.value = "" Then Exit For
        End If
    Next

You may want to write to the other sheet without jumping rows. In that case you can employ a variable to track which row to write to:

Sub Filtration()
    Dim writeRow as integer

    For Each Cell In Sheets(1).Range("R:R")

        'because we don't want to do this for every cell in Column R (There are one million), then exit the loop when we need to
        If cell.value = "" Then Exit For

        'divide the current cell's value by the the cell one column over's value and compare
        If cell.value/cell.offset(,-2).value > .021 Then

            'Write this out to the writeRow variable in the other sheet and increment that number by 1 after writing
            Sheet1.Rows(cell.row).Copy Destination:=Sheet2.Cells(writeRow, 1)
            writeRow = writeRow + 1

        End If
    Next

Because dividing by zero will cause this code to fail, it may be a good idea to do your division before you check the result in the if statement. You can use a variable to capture the value for later comparison:

Sub Filtration()
    Dim writeRow as integer
    Dim percentage as double

    For Each Cell In Sheets(1).Range("R:R")

        'because we don't want to do this for every cell in Column R (There are one million), then exit the loop when we need to
        If cell.value = "" Then Exit For

        'Lets make sure we won't be dividing by zero. If we are then set the result to 0
        if cell.offset(,-2).value = 0 Then
            percentage = 0
        else
            percentage=cell.value/cell.offset(,-2).value
        end if

        'divide the current cell's value by the the cell one column over's value and compare
        If  percentage > .021 Then

            'Write this out to the writeRow variable in the other sheet and increment that number by 1 after writing
            Sheet1.Rows(cell.row).Copy Destination:=Sheet2.Cells(writeRow, 1)
            writeRow = writeRow + 1

        End If
    Next


来源: stackexchange

问:
Create a constant variable link to year and quarter
Hi i am a stata user and i am trying to pass my codes to R. I have a panel data as shown below, and i am looking for a command that can create a constant variable according to which year and quarter the row is located. In stata such command would be reproduced by gen new_variable = yq(year, quarter)

My dataframe look like this

```<code>id     year    quarter
 1    2007          1
 1    2007          2
 1    2007          3
 1    2007          4
 1    2008          1
 1    2008          2
 1    2008          3
 1    2008          4
 1    2009          1
 1    2009          2
 1    2009          3
 1    2009          4
 2    2007          1
 2    2007          2
 2    2007          3
 2    2007          4
 2    2008          1
 2    2008          2
 2    2008          3
 2    2008          4
 3    2009          2
 3    2009          3
 3    2010          2
 3    2010          3
</code>```

I my expected output should look like this: (Values inside new_variable are arbitrary, just looking for a constant value the would be always the same for each year and quarter)

```<code>id     year    quarter   new_variable
 1    2007          1     220
 1    2007          2     221
 1    2007          3     222
 1    2007          4     223
 1    2008          1     224
 1    2008          2     225
 1    2008          3     226
 1    2008          4     227
 1    2009          1     228
 1    2009          2     229
 1    2009          3     230
 1    2009          4     231
 2    2007          1     220
 2    2007          2     221
 2    2007          3     222
 2    2007          4     223
 2    2008          1     224
 2    2008          2     225
 2    2008          3     226
 2    2008          4     227
 3    2009          2     229
 3    2009          3     230
 3    2010          2     233
 3    2010          3     234
</code>```

答:
Any of these will work:</p>

```<code># basic: just concatenate year and quarter
df$new_variable = paste(df$year, df$quarter)

# made for this, has additional options around
# ordering of the categories and including unobserved combos
df$new_variable = interaction(df$year, df$quarter)

# for an integer value, 1 to the number of combos
df$new_variable = as.integer(factor(paste(df$year, df$quarter)))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Hi i am a stata user and i am trying to pass my codes to R. I have a panel data as shown below, and i am looking for a command that can create a constant variable according to which year and quarter the row is located. In stata such command would be reproduced by gen new_variable = yq(year, quarter)

My dataframe look like this

id     year    quarter
 1    2007          1
 1    2007          2
 1    2007          3
 1    2007          4
 1    2008          1
 1    2008          2
 1    2008          3
 1    2008          4
 1    2009          1
 1    2009          2
 1    2009          3
 1    2009          4
 2    2007          1
 2    2007          2
 2    2007          3
 2    2007          4
 2    2008          1
 2    2008          2
 2    2008          3
 2    2008          4
 3    2009          2
 3    2009          3
 3    2010          2
 3    2010          3

I my expected output should look like this: (Values inside new_variable are arbitrary, just looking for a constant value the would be always the same for each year and quarter)

id     year    quarter   new_variable
 1    2007          1     220
 1    2007          2     221
 1    2007          3     222
 1    2007          4     223
 1    2008          1     224
 1    2008          2     225
 1    2008          3     226
 1    2008          4     227
 1    2009          1     228
 1    2009          2     229
 1    2009          3     230
 1    2009          4     231
 2    2007          1     220
 2    2007          2     221
 2    2007          3     222
 2    2007          4     223
 2    2008          1     224
 2    2008          2     225
 2    2008          3     226
 2    2008          4     227
 3    2009          2     229
 3    2009          3     230
 3    2010          2     233
 3    2010          3     234

Body:
Any of these will work:

# basic: just concatenate year and quarter
df$new_variable = paste(df$year, df$quarter)

# made for this, has additional options around
# ordering of the categories and including unobserved combos
df$new_variable = interaction(df$year, df$quarter)

# for an integer value, 1 to the number of combos
df$new_variable = as.integer(factor(paste(df$year, df$quarter)))


问:
Can HDFS block size be changed during job run? Custom Split and Variant Size
I am using hadoop 1.0.3. Can the input split/block be changed (increase/decrease) during run time based on some constraints. Is there a class to override to accomplish this mechanism like FileSplit/InputTextFormat? Can we have variant size blocks in HDFS depending on logical constraint in one job?</p>

答:
If you want to change block size only for a particular run or application you can do by overriding "-D dfs.block.size=134217728" .It helps you to change block size for your application instead of changing overall block size in hdfs-site.xml.

-D dfs.block.size=134217728


问:
Avoiding default basic-error-controller from swagger api
I'm using swagger2 in my spring boot project. It's working well, but I need to exclude the basic-error-controller from the api. Currently I'm using the following code using regex. It's working but is there any perfect way to do this.

CODE :

```<code>@Bean
public Docket demoApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.any())
            .paths(PathSelectors.regex('(?!/error.*).*'))
            .build()
}
</code>```

答:
The best way I found of limiting the endpoints that are displayed by the swagger documentation is doing this:

```<code>@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.any())
            .paths(paths())
            .build().apiInfo(metadata());
}

private Predicate<String> paths() {
    return or(
            regex("/firstContext.*"),
            regex("/secondContext.*"));
}

private ApiInfo metadata() {
    return new ApiInfoBuilder()
            .title("SomeTitle")
            .description("SomeDescription")
            .build();
}
</code>```

So each endpoint that does not start with the paths() method contexts will not be rendered by swagger

Body:
I'm using swagger2 in my spring boot project. It's working well, but I need to exclude the basic-error-controller from the api. Currently I'm using the following code using regex. It's working but is there any perfect way to do this.

CODE :

@Bean
public Docket demoApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.any())
            .paths(PathSelectors.regex('(?!/error.*).*'))
            .build()
}

Body:
The best way I found of limiting the endpoints that are displayed by the swagger documentation is doing this:

@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.any())
            .paths(paths())
            .build().apiInfo(metadata());
}

private Predicate<String> paths() {
    return or(
            regex("/firstContext.*"),
            regex("/secondContext.*"));
}

private ApiInfo metadata() {
    return new ApiInfoBuilder()
            .title("SomeTitle")
            .description("SomeDescription")
            .build();
}

So each endpoint that does not start with the paths() method contexts will not be rendered by swagger


问:
PERL How to skip error in while loop
I have this script which automates a process of like on Instagram.
It does exactly what it should do except for one thing. Within the while loop, if a user does not exist the script dies.
In this case, the error should be ignored and the script should continue processing the other users of the list.

This is the error i get:

Error GETing https://www.instagram.com/usernamethatdoesntexist/?__
a=1: Not Found at instagram-post-liker.pl line 29

Thanks for any help

```<code>use WWW::Mechanize;
use JSON;

my $filename = 'data.txt';
open(my $fh, '<:encoding(UTF-8)', $filename)
  or die "Could not open file '$filename' $!";

my $mech_get = WWW::Mechanize->new(agent => 'Mozilla/5.0 (Windows NT 6.0; rv:2.0) Gecko/20100101 Firefox/4.0 Opera 12.14');

my $mecho = WWW::Mechanize->new(agent => 'Mozilla/5.0 (Linux; U; Android 2.2; de-de; HTC Desire HD 1.18.161.2 Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1');

$mecho->get('https://www.instagram.com/');

$mecho->add_header('Accept-Encoding' => 'gzip, deflate', 'X-Instagram-AJAX' => '1', 'Accept-Language' => 'de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4,pl;q=0.2,nl;q=0.2' ,'X-Requested-With' => 'XMLHttpRequest', 'X-CSRFToken' => getcsrf($mecho));

my $post_data = {
    username    =>  'username',
    password    =>  'password'
};

$mecho->post('https://www.instagram.com/accounts/login/ajax/', $post_data);

  while (my $row = <$fh>) {
  chomp $row;
  print "getting user $row\n";

    $mech_get->get('https://www.instagram.com/'.$row.'/?__a=1');

    my $decoded_json = decode_json( $mech_get->response()->decoded_content() );

     print "Found Post \n";

    $mech_get->get('https://api.instagram.com/oembed/?url=https://www.instagram.com/p/'.$decoded_json->{user}->{media}->{nodes}[0]->{code}.'/');

    my $decoded_json2 = decode_json( $mech_get->response()->decoded_content() );

    print "Linking Post by Id";
    my $post;

    if($decoded_json2->{media_id} =~ /^([^_]*);*)   {
        $post = $1;
    }

    $mecho->add_header('Accept-Encoding' => 'gzip, deflate', 'X-Instagram-AJAX' => '1', 'Accept-Language' => 'de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4,pl;q=0.2,nl;q=0.2' ,'X-Requested-With' => 'XMLHttpRequest', 'X-CSRFToken' => getcsrf($mecho));

    $mecho->post('https://www.instagram.com/web/likes/'.$post.'/like/');

}

sub getcsrf {

    my ($somemech) = @_;

    my $cookies2  = $somemech->response->header('Set-Cookie');

    my $csrf_token2;
    if ($cookies2 =~ /csrftoken=([^;]+);/i){
        return $1;
    }
    else {
        die "Unable to find csrftoken in cookie headers, did something change?";

        }

};
</code>```

答:
Disable WWW::Mechanize's automatic error handling

WWW::Mechanize by default does automatic error checking, which dies on errors (http://search.cpan.org/~oalders/WWW-Mechanize-1.86/lib/WWW/Mechanize.pm#new()). You can add autocheck => 0 to the constructor to disable this behaviour. You then have to check manually after each request, either by checking the return of the request method

```<code>my $response = $mech->get($url);
unless ($response->is_success) {
    ### add your error handling here
}
</code>```

or by using WWW::Mechanize's shortcut:

```<code>$mech->get($url);
unless ($mech->success) {
    ### add your error handling here
}
</code>```

Title: PERL How to skip error in while loop

Body:
I have this script which automates a process of like on Instagram.
It does exactly what it should do except for one thing. Within the while loop, if a user does not exist the script dies.
In this case, the error should be ignored and the script should continue processing the other users of the list.

This is the error i get:

Error GETing https://www.instagram.com/usernamethatdoesntexist/?__
a=1: Not Found at instagram-post-liker.pl line 29

Thanks for any help

use WWW::Mechanize;
use JSON;

my $filename = 'data.txt';
open(my $fh, '<:encoding(UTF-8)', $filename)
  or die "Could not open file '$filename' $!";

my $mech_get = WWW::Mechanize->new(agent => 'Mozilla/5.0 (Windows NT 6.0; rv:2.0) Gecko/20100101 Firefox/4.0 Opera 12.14');

my $mecho = WWW::Mechanize->new(agent => 'Mozilla/5.0 (Linux; U; Android 2.2; de-de; HTC Desire HD 1.18.161.2 Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1');

$mecho->get('https://www.instagram.com/');

$mecho->add_header('Accept-Encoding' => 'gzip, deflate', 'X-Instagram-AJAX' => '1', 'Accept-Language' => 'de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4,pl;q=0.2,nl;q=0.2' ,'X-Requested-With' => 'XMLHttpRequest', 'X-CSRFToken' => getcsrf($mecho));

my $post_data = {
    username    =>  'username',
    password    =>  'password'
};

$mecho->post('https://www.instagram.com/accounts/login/ajax/', $post_data);

  while (my $row = <$fh>) {
  chomp $row;
  print "getting user $row\n";

    $mech_get->get('https://www.instagram.com/'.$row.'/?__a=1');

    my $decoded_json = decode_json( $mech_get->response()->decoded_content() );

     print "Found Post \n";

    $mech_get->get('https://api.instagram.com/oembed/?url=https://www.instagram.com/p/'.$decoded_json->{user}->{media}->{nodes}[0]->{code}.'/');

    my $decoded_json2 = decode_json( $mech_get->response()->decoded_content() );

    print "Linking Post by Id";
    my $post;

    if($decoded_json2->{media_id} =~ /^([^_]*);*)   {
        $post = $1;
    }

    $mecho->add_header('Accept-Encoding' => 'gzip, deflate', 'X-Instagram-AJAX' => '1', 'Accept-Language' => 'de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4,pl;q=0.2,nl;q=0.2' ,'X-Requested-With' => 'XMLHttpRequest', 'X-CSRFToken' => getcsrf($mecho));

    $mecho->post('https://www.instagram.com/web/likes/'.$post.'/like/');

}

sub getcsrf {

    my ($somemech) = @_;

    my $cookies2  = $somemech->response->header('Set-Cookie');

    my $csrf_token2;
    if ($cookies2 =~ /csrftoken=([^;]+);/i){
        return $1;
    }
    else {
        die "Unable to find csrftoken in cookie headers, did something change?";

        }

};

Body:
Disable WWW::Mechanize's automatic error handling

WWW::Mechanize by default does automatic error checking, which dies on errors (http://search.cpan.org/~oalders/WWW-Mechanize-1.86/lib/WWW/Mechanize.pm#new()). You can add autocheck => 0 to the constructor to disable this behaviour. You then have to check manually after each request, either by checking the return of the request method

my $response = $mech->get($url);
unless ($response->is_success) {
    ### add your error handling here
}

or by using WWW::Mechanize's shortcut:

$mech->get($url);
unless ($mech->success) {
    ### add your error handling here
}


问:
What does 'synchronized' mean?
I have some questions regarding the usage and significance of the synchronized keyword.

What is the significance of the synchronized keyword?

When should methods be synchronized?

What does it mean programmatically and logically?

答:
synchronized means that in a multi threaded environment, an object having  synchronized method(s)/block(s) does not let two threads to access the synchronized method(s)/block(s) of code at the same time. This means that one thread can't read while another thread updates it.

The second thread will instead wait until the first thread completes its execution. The overhead is speed, but the advantage is guaranteed consistency of data.

If your application is single threaded though, synchronized blocks does not provide benefits.

Title: What does 'synchronized' mean?


问:
Install libs Pycharm
I try to install numpy in pycharm 2017.2. But when I choose numpy in Settings -> Project Interpreter, I'm getting error:

Make sure that you use the correct version of 'pip' installed for your Python interpreter located at '/usr/bin/python3.5'

Error: Python packaging tool 'pip' not found

What should I do to avoid it?

答:
Go to:

Preferences -> Project Interpreter -> press plus "+" button it will open Available packages window -> search pip and choose the first one -> press Install Packages.

More info: https://www.jetbrains.com/help/pycharm/installing-uninstalling-and-upgrading-packages.html

Title: Install libs Pycharm


问:
Android apk with expansion file on play store
I had uploaded apk(created using unity) with its expansion file on play store.after publishing the apk,play store download large expansion file (additional file) firstthen small apk file. why ?Actually I want to change the order of downloading for my app, how can I change that?</p>

答:
No, you can't change it.

And I don't see why it matters. The APK needs the expansion file to work, so it downloads the data first and then the executable. What order it's downloaded in doesn't matter.

However, if you for whatever reason want to download it in the apk-> expansion file order, you have to download it from a self-hosted server from the APK. You cannot change the order in which it's downloaded from google play


问:
C string arrays

Possible Duplicates:

  string literal in c

  Assigning strings to arrays of characters

I got the following code:

```<code>char result[3][4];

result[0] = "horse";
result[1] = "pig";
result[2] = "chicken";
</code>```

It won't compile saying Incompatible types in assignment. What am I doing wrong?

答:
Arrays are non-modifiable lvalues i.e you cannot assign to them.

You need to use array of pointers. Change char result[3][4]; to char * result[3]

ContentLicense: CC BY-SA 2.5

Title: C string arrays

Body:
Possible Duplicates:

  string literal in c

  Assigning strings to arrays of characters

I got the following code:

char result[3][4];

result[0] = "horse";
result[1] = "pig";
result[2] = "chicken";

It won't compile saying Incompatible types in assignment. What am I doing wrong?


问:
Error : Property [uploads] does not exist on this collection instance - one to many relationship
I am trying to make a one to many relationship between my Users table and my Uploads table.

To do so I did the following :

Added this function to my User table :

```<code>public function uploads(){
        return $this->belongsTo('App\Upload');
    }
</code>```

And this to my Upload table :

```<code>public function user(){
        return $this->belongsTo('App\User');
    }
</code>```

Then I added this simple function to my UploadController :

```<code>   public function uploads()
{
    $user_id = auth()->user('id');
    $user = User::find($user_id);
    return view('uploads')->with('uploads',$user->uploads);
}
</code>```

My Uploads view is looking like this :

```<code> @extends('layouts.app')
@section('content')
    <h1>Uploads</h1>
    @if(count($uploads)>0)
@foreach($uploads as $upload)
    <div class="well">
        <h3><a href="/uploads/{{$upload->id}}">{{$upload->name}}</a> </h3>
        <small>Written on {{$upload->created_at}}</small>

    </div>
        @endforeach
             {{$uploads->links()}}
    @else
    <p>No uploads found</p>
    @endif

@endsection
</code>```

When I try to go to myproject.dev/uploads I'm getting the following error :

Property [uploads] does not exist on this collection instance.

Since I am new to laravel, as far as I am aware I don't have to run a migration after I make something like this. But still it doesn't work and I just don't see what am I doing wrong? I just followed the documentation....

答:
You need to eager load User model uploads. To do so just add this in your Eloquent query:

```<code>$user = User::whereId($user_id)->with('uploads')->first();
</code>```

And also in your User model, you have an error in eloquent relationship. You need to say that this User has many uploads and upload belongs to User.

```<code>public function uploads()
{
    return $this->hasMany(Upload::class)
}
</code>```

Body:
I am trying to make a one to many relationship between my Users table and my Uploads table.

To do so I did the following :

Added this function to my User table :

public function uploads(){
        return $this->belongsTo('App\Upload');
    }

And this to my Upload table :

public function user(){
        return $this->belongsTo('App\User');
    }

Then I added this simple function to my UploadController :

   public function uploads()
{
    $user_id = auth()->user('id');
    $user = User::find($user_id);
    return view('uploads')->with('uploads',$user->uploads);
}

My Uploads view is looking like this :

 @extends('layouts.app')
@section('content')

Uploads

    @if(count($uploads)>0)
@foreach($uploads as $upload)

id}}">{{$upload->name}}

        Written on {{$upload->created_at}}

        @endforeach
             {{$uploads->links()}}
    @else

No uploads found

    @endif

@endsection

When I try to go to myproject.dev/uploads I'm getting the following error :

Property [uploads] does not exist on this collection instance.

Since I am new to laravel, as far as I am aware I don't have to run a migration after I make something like this. But still it doesn't work and I just don't see what am I doing wrong? I just followed the documentation....

Body:
You need to eager load User model uploads. To do so just add this in your Eloquent query:

$user = User::whereId($user_id)->with('uploads')->first();

And also in your User model, you have an error in eloquent relationship. You need to say that this User has many uploads and upload belongs to User.

public function uploads()
{
    return $this->hasMany(Upload::class)
}


问:
PHP Client to Node js Server. Connection never "ends"
I have a simple webpage that is supposed to submit a "csv" like string to a server. For this I require an API to receive the data string and save the string as a text file.

The page is using PHP and the Server is Node js

Code examples:

PHP:

```<code>$ch = curl_init();
$path = '/test.txt';
$url = "http://none.of.your.business.com:8280/";

$data = array('filePath' => $path,
      'message' => $csv);
$data_string = json_encode($string);

curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string))
);

$result = curl_exec($ch);
echo $result;
curl_close($ch);
</code>```

Node Server:

```<code>var net = require('net');

var HOST = '0.0.0.0';
var PORT = 8280;

net.createServer(function(sock) {

                var body = "";

                console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);

                sock.on('data', function (data) {
                                body += data;
                                console.log("Partial body: " + body);
                                });

                sock.on('end', function () {

                                console.log("ENDED");
                                console.log("Body: " + body);
                                });

}).listen(PORT, HOST);

console.log('Server listening on ' + HOST +':'+ PORT);
</code>```

With this code (and other alternatives) the "end" event is never called and the connection never closed. Resulting in a 300 second timeout on the PHP script. I reckon its something fairly simple, am I supposed to send something back to the PHP to say "done"?, but I'm inexperienced with TCP connections. I get the  following "console.log'ged" on the server:

```<code>[root@xxxxxxxxx fileWriter]# node index.js
Server listening on 0.0.0.0:8280
CONNECTED: xxx.xxx.xxx.xxx:52766
Partial body: POST / HTTP/1.1
Host: xxx.xxx.xxx.com:8280
Accept: */*
Content-Type: application/json
Content-Length: 440

{"filePath":"/test.txt","message":"\"WORKFLOWID\",\"PARENTWORKFLOWID\",\"SOURCEINSTANCEID\",\"WORKFLOWTYPECODE\",\"DATECREATED\",\"DATEUPDATED\",\"ASSETID\",\"PVN\",\"IVN\",\"PROVIDERID\",\"TITLE\",\"SERIESTITLE\",\"OFFERDATE\",\"LASTOFFERDATE\",\"REGION\",\"RELEASEPHASE\",\"WORKFLOWSTATUSID\",\"DURATIONMILLIS\"\\n\"\",\"\",\"\",\"\",\"\",\"04-Dec-17 14.55.05.000000 PM\",\"TITL0\",\"0\",\"0\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"-1\",\"\"\n"}
</code>```

答:
Following code on the server side (Node.js) has solved my issues. Seems sending a response closed the connection.</p>

```<code>const http = require('http');
const fs = require('fs');
http.createServer((request, response) => {
                const { headers, method, url } = request;
                let body = [];
                request.on('error', (err) => {
                                console.error(err);
                                }).on('data', (chunk) => {
                                        body.push(chunk);
                                        }).on('end', () => {
                                                body = Buffer.concat(body).toString();

                                                var json = JSON.parse(body);
                                                response.on('error', (err) => {
                                                                console.error(err);
                                                                });

                                                response.statusCode = 200;
                                                response.setHeader('Content-Type', 'application/json');

                                                const responseBody = { headers, method, url, body };
                                                fs.appendFileSync(json.filePath,json.message);
                                                response.write("Succesfully written " + json.filePath);
                                        //      response.write(JSON.stringify(responseBody));
                                                response.end();

                                });
}).listen(8280);
</code>```

Body:
I have a simple webpage that is supposed to submit a "csv" like string to a server. For this I require an API to receive the data string and save the string as a text file.

The page is using PHP and the Server is Node js

Code examples:

PHP:

$ch = curl_init();
$path = '/test.txt';
$url = "http://none.of.your.business.com:8280/";

$data = array('filePath' => $path,
      'message' => $csv);
$data_string = json_encode($string);

curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string))
);

$result = curl_exec($ch);
echo $result;
curl_close($ch);

Node Server:

var net = require('net');

var HOST = '0.0.0.0';
var PORT = 8280;

net.createServer(function(sock) {

                var body = "";

                console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);

                sock.on('data', function (data) {
                                body += data;
                                console.log("Partial body: " + body);
                                });

                sock.on('end', function () {

                                console.log("ENDED");
                                console.log("Body: " + body);
                                });

}).listen(PORT, HOST);

console.log('Server listening on ' + HOST +':'+ PORT);

With this code (and other alternatives) the "end" event is never called and the connection never closed. Resulting in a 300 second timeout on the PHP script. I reckon its something fairly simple, am I supposed to send something back to the PHP to say "done"?, but I'm inexperienced with TCP connections. I get the  following "console.log'ged" on the server:

[root@xxxxxxxxx fileWriter]# node index.js
Server listening on 0.0.0.0:8280
CONNECTED: xxx.xxx.xxx.xxx:52766
Partial body: POST / HTTP/1.1
Host: xxx.xxx.xxx.com:8280
Accept: */*
Content-Type: application/json
Content-Length: 440

{"filePath":"/test.txt","message":"\"WORKFLOWID\",\"PARENTWORKFLOWID\",\"SOURCEINSTANCEID\",\"WORKFLOWTYPECODE\",\"DATECREATED\",\"DATEUPDATED\",\"ASSETID\",\"PVN\",\"IVN\",\"PROVIDERID\",\"TITLE\",\"SERIESTITLE\",\"OFFERDATE\",\"LASTOFFERDATE\",\"REGION\",\"RELEASEPHASE\",\"WORKFLOWSTATUSID\",\"DURATIONMILLIS\"\\n\"\",\"\",\"\",\"\",\"\",\"04-Dec-17 14.55.05.000000 PM\",\"TITL0\",\"0\",\"0\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"-1\",\"\"\n"}

Body:
Following code on the server side (Node.js) has solved my issues. Seems sending a response closed the connection.

const http = require('http');
const fs = require('fs');
http.createServer((request, response) => {
                const { headers, method, url } = request;
                let body = [];
                request.on('error', (err) => {
                                console.error(err);
                                }).on('data', (chunk) => {
                                        body.push(chunk);
                                        }).on('end', () => {
                                                body = Buffer.concat(body).toString();

                                                var json = JSON.parse(body);
                                                response.on('error', (err) => {
                                                                console.error(err);
                                                                });

                                                response.statusCode = 200;
                                                response.setHeader('Content-Type', 'application/json');

                                                const responseBody = { headers, method, url, body };
                                                fs.appendFileSync(json.filePath,json.message);
                                                response.write("Succesfully written " + json.filePath);
                                        //      response.write(JSON.stringify(responseBody));
                                                response.end();

                                });
}).listen(8280);


问:
Call to a different macro at a certain line
Is it possible to use the call feature to call a macro at a specific line? I ask as the macro i am coding does this - First it runs half of the code, then based upon user choices it opens up a custom UserForm, and runs the UserForm command buttons. After this I need a command button to go back to the code the line after the UserForm was used. The UserForm works as intended and many different stats calculations can be run. It has a button that returns the user back to the rest of the code, but I can't get that to work. </p>

<p>I have tried using  both GoTo statements and the Call feature (The most promising solution) but have had no success so far. </p>

答:
There are several ways to achieve it, I will show one of them.

You can modify your procedure (macro) asking for a value as optional.

```<code>Sub MyMacro(Optional Answer As Boolean)

   If Answer = True then
       'Do some stuff
   Else
       'Do some stuff
   End If

End Sub
</code>```

As Answer is optional you can call your Macro with or without arguments.
Suppose you call your Macro from your user form:

```<code>Call MyMacro(True)
</code>```

Hope this give you some hints.

Body:
Is it possible to use the call feature to call a macro at a specific line? I ask as the macro i am coding does this - First it runs half of the code, then based upon user choices it opens up a custom UserForm, and runs the UserForm command buttons. After this I need a command button to go back to the code the line after the UserForm was used. The UserForm works as intended and many different stats calculations can be run. It has a button that returns the user back to the rest of the code, but I can't get that to work.

I have tried using  both GoTo statements and the Call feature (The most promising solution) but have had no success so far.

Body:
There are several ways to achieve it, I will show one of them.

You can modify your procedure (macro) asking for a value as optional.

Sub MyMacro(Optional Answer As Boolean)

   If Answer = True then
       'Do some stuff
   Else
       'Do some stuff
   End If

End Sub

As Answer is optional you can call your Macro with or without arguments.
Suppose you call your Macro from your user form:

Call MyMacro(True)

Hope this give you some hints.


问:
Angular application in IIS vs Node server
we have developed a Angular 4 application.

I have windows server 2012 R2 as production box

should i use node server to host the angular application, or IIS can also be used without any issue ?

i do not have any background experience so please suggest

答:
I USUALLY USE IIS without any probs .. Node.js usually for developing purpose (with angular cli and webpack dev server) .. but then in production and in PrePRod (so on my servers) i usuall use IIS...

just check the webconfig file...

for example ..
1 -  set default page as Index.html

2 - set rewrite rules for redirect on Index.html ..

..

and the be sure to have installed the URL REWRITE MODULE on IIS

Hope it helps you!


问:
AngularJS - Sorting data ascending / descending when column is clicked
I have the following view code:

```<code><tr ng-repeat="c in clients | orderBy:'code'">
    <td>{{c.firstname}} {{c.lastname}}</td>
    <td>{{c.telephone}}</td>
    <td>{{c.location}}</td>
    <td>{{c.code}}</td>
</tr>
</code>```

I want to change the orderBy:'code' when column is clicked, assume that the user clicked on the column location, i want the orderBy condition to change to 'location' instead of code, and to be in this form

```<code><tr ng-repeat="c in clients | orderBy:'location'">
</code>```

答:
Use datatables.js for automate sorting
https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css

https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js

Body:
I have the following view code:

    {{c.firstname}} {{c.lastname}}
    {{c.telephone}}
    {{c.location}}
    {{c.code}}

I want to change the orderBy:'code' when column is clicked, assume that the user clicked on the column location, i want the orderBy condition to change to 'location' instead of code, and to be in this form


问:
Python - I zip some folders with subfolders but it zips twice.
I have written a script. It finds the current path and changes the path and zips. Then I want that it just find the zip file copy it to another directory and at the end removes the content of the folder. But it zips once and zips again the whole folders and zip-file. The intial situation is as in Figure 1.

The script is like this:

```<code>import os
import zipfile
import shutil
import glob

Pfad = os.getcwd()
newPfad = 'D'+ Pfad[1:]
Zip_name=os.path.basename(os.path.normpath(Pfad))
shutil.make_archive(Zip_name, 'zip', Pfad)

if not os.path.exists(newPfad):
    os.makedirs(newPfad)

dest_dir=newPfad
files = glob.iglob(os.path.join(Pfad, "*.zip"))
for file in files:
    if os.path.isfile(file):
        shutil.copy2(file, dest_dir)

shutil.rmtree(Pfad)
</code>```

And finally the result is illustrated in the following figure.

The batch file is just for running the python script.

How can I get the following desired situation?

答:
The issue is that zip file is created prior to listing the directory contents, therefore empty zip file is added to. Create archive in the parent directory and then move it. Moving a file or directory is cheap and atomic.</p>

```<code>import os
import shutil

cwd = os.path.abspath(os.path.curdir)
zip_target = os.path.join(cwd, os.path.basename(cwd)) + '.zip'
zip_source = shutil.make_archive(cwd, 'zip')
os.rename(zip_source, zip_target)
</code>```

Body:
I have written a script. It finds the current path and changes the path and zips. Then I want that it just find the zip file copy it to another directory and at the end removes the content of the folder. But it zips once and zips again the whole folders and zip-file. The intial situation is as in Figure 1.

The script is like this:

import os
import zipfile
import shutil
import glob

Pfad = os.getcwd()
newPfad = 'D'+ Pfad[1:]
Zip_name=os.path.basename(os.path.normpath(Pfad))
shutil.make_archive(Zip_name, 'zip', Pfad)

if not os.path.exists(newPfad):
    os.makedirs(newPfad)

dest_dir=newPfad
files = glob.iglob(os.path.join(Pfad, "*.zip"))
for file in files:
    if os.path.isfile(file):
        shutil.copy2(file, dest_dir)

shutil.rmtree(Pfad)

And finally the result is illustrated in the following figure.

The batch file is just for running the python script.

How can I get the following desired situation?

Body:
The issue is that zip file is created prior to listing the directory contents, therefore empty zip file is added to. Create archive in the parent directory and then move it. Moving a file or directory is cheap and atomic.

import os
import shutil

cwd = os.path.abspath(os.path.curdir)
zip_target = os.path.join(cwd, os.path.basename(cwd)) + '.zip'
zip_source = shutil.make_archive(cwd, 'zip')
os.rename(zip_source, zip_target)


问:
Is there an intelligent editor for ReST files?
I'm just learning Sphinx, and I need to edit ReST files. Is there an intelligent editor for it? Like, an editor that gives me code coloration, easy indentation, code completion (hopefully), etc.</p>

答:
A while ago I tried the Atom Editor https://atom.io/. It has the benefits of even displaying a preview showing possible images and renders the sections correctly, even formulas are displayed. The syntax highlighting is supported, but there is not much to highlight in ReST anyway.

In order to make it work you have to install pandoc and the atom packages language-restructuredtext and rst-preview-pandoc. You activate the preview with CTRL-SHIFT-E.

Another possibility is Visual Studio Code, which I didn't tried.

But after a while I'm relying on simple NotePad++, as there is not so much benefit in an nice editor, as ReST is already so simple.


答:
The synchronized keyword prevents concurrent access to a block of code or object by multiple threads. All the methods of Hashtable are synchronized, so only one thread can execute any of them at a time.

When using non-synchronized constructs like HashMap, you must build thread-safety features in your code to prevent consistency errors.

Title: What does 'synchronized' mean?

Body:
I have some questions regarding the usage and significance of the synchronized keyword.

What is the significance of the synchronized keyword?

When should methods be synchronized?

What does it mean programmatically and logically?

ContentLicense: CC BY-SA 4.0


问:
How to generate random IP with groovy
How to generate random IP with groovy :
I can generate a string, but can't figure out a fast way to IP.
org.apache.commons.lang.RandomStringUtils.random </p>

答:
If you just need random IP addresses, why not just something simple like:

```<code>def random = new Random()

(0..3).collect { random.nextInt(255) }.join('.')
</code>```

You will end up with something like:

```<code>10.222.40.74
</code>```

Title: How to generate random IP with groovy

Body:
If you just need random IP addresses, why not just something simple like:

def random = new Random()

(0..3).collect { random.nextInt(255) }.join('.')

You will end up with something like:

10.222.40.74


问:
How do I refresh branches (local/remote) in Visual Studio when using Git?

Update

Upgrading to Visual Studio 2019 16.8.X has a new git workflow. This also includes a fetch button.

Summary

I am learning how to use Git with Visual Studio.  I recently did a pull request where the feature branch was deleted after the merge.  The feature branch still shows up in my local and remote branches in Visual Studio.  I know how to right click and delete the branch, this is a workaround as others on the team may complete a pull request on a branch that I have without me knowing it.  If they delete the branch afterwards I would not know they did so.

Question

How do you refresh Visual Studio branches with what is on Git?

What I expect

I would expect a button, link, or right click feature that on click checks for differences, if any are found it asks, "This branch no longer exists, would you like to remove it from Visual Studio?".

Tech Specs

I am using Visual Studio 2015 Enterprise (still seems to be a symptom of VS 2019 for versions lower than 16.8)

Additional Example

This could be another question, but it fits so well here.  I just noticed that if I create a branch (say in one VM and look at the same repo with another), Visual Studio does not have a git fetch option to update the branch list.  The refresh button at the top does not seem to do anything.  As soon as I run git fetch in a bash, visual studio has the new branch.  I would expect the refresh to take care of this.

答:
VS 2017 appears to have support configurable in Team Explorer:

Team Explorer Home
Settings
Git > Global Settings
Prune Remote Branches During Fetch: Unset, True, or False


问:
number as a result in select in mysql database

I run query:

```<code>SELECT ifnull(TIME_TO_SEC( TIMEDIFF( a.ending, a.begining ))/60,0)
FROM visits` a
</code>```

and I wouls like  NUMBER as a result

but i recived like this

```<code>0.0000
50.0000
50.0000
0.0000
0.0000
50.0000
</code>```

I expect as below:

```<code>0
50
50
0
0
50
</code>```

or 50,00

it means I need return number

答:
ok but somthing wrong with round

if I divide 50/50 result is 0,99
why ?

something wrong is with type?

Body:
I run query:

SELECT ifnull(TIME_TO_SEC( TIMEDIFF( a.ending, a.begining ))/60,0)
FROM visits` a

and I wouls like  NUMBER as a result

but i recived like this

0.0000
50.0000
50.0000
0.0000
0.0000
50.0000

I expect as below:

0
50
50
0
0
50

or 50,00

it means I need return number


问:
Dataframe for textfile Spark
I'm trying to create a data frame on a text file. For a sample input (Input1)
 below Code is working fine

Input1

```<code>1,5

2,6

3,7

4,8
</code>```

Output1

```<code>+---+----+
| id|name|
+---+----+
|  1|   5|
|  2|   6|
|  3|   7|
|  4|   8|
+---+----+
</code>```

However when I changed the input(Input2), I'm not getting any output.

Input2

```<code>1,"a,b,c"

2,"d,e,f"

3,"a,b,c"

4,"a,d,f"
</code>```

Output2

```<code>+---+----+
| id|name|
+---+----+
+---+----+
</code>```

Code

```<code>    {
        val input = sc.textFile(inputFile).map(x=>x.split(",")).collect {
                            case Array(id,name) => Record(id.toInt, name)
                    }
                    input.toDF().show()
    }
case class Record(id: Int, name: String)
</code>```

Expected output format for Input2

```<code>+---+-----+------+-----+
| id|name1| name2|name3|
+---+-----+------+-----+
|  1|    a|     b|    c|
|  2|    d|     e|    d|
|  3|    a|     b|    c|
|  4|    a|     d|    f|
+---+-----+------+-----+
</code>```

I should make changes to the code and case class as well so that compiler understands the data format for Input2, but I'm not getting what changes I need to do.  Please advice.

答:
You are trying to make the first digit as id column and rest of the comma separated chars inside inverted comma as name column. For that you have to change a little bit of your logic and you should be fine as below

```<code>val input = sc.textFile(inputFile).map(x=>x.split(",")).map(x => Record(x.head.toInt, x.tail.mkString(",")))
input.toDF().show()
</code>```

and of course case class is as you have

```<code>case class Record(id: Int, name: String)
</code>```

You should have following dataframe

```<code>+---+-------+
| id|   name|
+---+-------+
|  1|"a,b,c"|
|  2|"d,e,f"|
|  3|"a,b,c"|
|  4|"a,d,f"|
+---+-------+
</code>```

If you don't want the inverted comma you can add replace api as

```<code>val input = sc.textFile(inputFile).map(x=>x.replace("\"", "").split(",")).map(x => Record(x.head.toInt, x.tail.mkString(",")))
input.toDF().show()
</code>```

you should have

```<code>+---+-----+
| id| name|
+---+-----+
|  1|a,b,c|
|  2|d,e,f|
|  3|a,b,c|
|  4|a,d,f|
+---+-----+
</code>```

I hope the answer is helpful.

By the way its better to use sqlContext to read such files where you want to ignore the commas inside inverted commas.

```<code>sqlContext.read.format(inputFile).toDF("id", "name").show(false)
</code>```

you should have above output dataframe

Title: Dataframe for textfile Spark

Body:
I'm trying to create a data frame on a text file. For a sample input (Input1)
 below Code is working fine

Input1

1,5

2,6

3,7

4,8

Output1

+---+----+
| id|name|
+---+----+
|  1|   5|
|  2|   6|
|  3|   7|
|  4|   8|
+---+----+

However when I changed the input(Input2), I'm not getting any output.

Input2

1,"a,b,c"

2,"d,e,f"

3,"a,b,c"

4,"a,d,f"

Output2

+---+----+
| id|name|
+---+----+
+---+----+

Code

    {
        val input = sc.textFile(inputFile).map(x=>x.split(",")).collect {
                            case Array(id,name) => Record(id.toInt, name)
                    }
                    input.toDF().show()
    }
case class Record(id: Int, name: String)

Expected output format for Input2

+---+-----+------+-----+
| id|name1| name2|name3|
+---+-----+------+-----+
|  1|    a|     b|    c|
|  2|    d|     e|    d|
|  3|    a|     b|    c|
|  4|    a|     d|    f|
+---+-----+------+-----+

I should make changes to the code and case class as well so that compiler understands the data format for Input2, but I'm not getting what changes I need to do.  Please advice.

Body:
You are trying to make the first digit as id column and rest of the comma separated chars inside inverted comma as name column. For that you have to change a little bit of your logic and you should be fine as below

val input = sc.textFile(inputFile).map(x=>x.split(",")).map(x => Record(x.head.toInt, x.tail.mkString(",")))
input.toDF().show()

and of course case class is as you have

case class Record(id: Int, name: String)

You should have following dataframe

+---+-------+
| id|   name|
+---+-------+
|  1|"a,b,c"|
|  2|"d,e,f"|
|  3|"a,b,c"|
|  4|"a,d,f"|
+---+-------+

If you don't want the inverted comma you can add replace api as

val input = sc.textFile(inputFile).map(x=>x.replace("\"", "").split(",")).map(x => Record(x.head.toInt, x.tail.mkString(",")))
input.toDF().show()

you should have

+---+-----+
| id| name|
+---+-----+
|  1|a,b,c|
|  2|d,e,f|
|  3|a,b,c|
|  4|a,d,f|
+---+-----+

I hope the answer is helpful.

By the way its better to use sqlContext to read such files where you want to ignore the commas inside inverted commas.

sqlContext.read.format(inputFile).toDF("id", "name").show(false)

you should have above output dataframe


问:
Using a java library from python
I have a python app and java app. The python app generates input for the java app and invokes it on the command line.

I'm sure there must be a more elegant solution to this; just like using JNI to invoke C code from Java.

Any pointers?
(FYI I'm v. new to Python)

Clarification (at the cost of a long question: apologies)
The py app (which I don't own) takes user input in the form of a number of configuration files. It then interprits these and farms work off to a number of (hidden) tools via a plugin mechanism. I'm looking to add support for the functionality provided by the legacy Java app.

So it doesn't make sense to call the python app from the java app and I can't run the py app in a jython environment (on the JVM).

Since there is no obvious mechanism for this I think the simple CL invocation is the best solution.

答: Take a look at Jython. It's kind of like JNI, but replace C with Python, i.e. you can call Python from Java and vice versa. It's not totally clear what you're trying to do or why your current approach isn't what you want.</p>

OwnerDisplayName: Jim

Title: Using a java library from python

LastEditorDisplayName: Jim

OwnerDisplayName: Dave Ray


问:
Error: No FileSystem for scheme: hdfs (Docker)
I am receiving the error: No FileSystem for scheme: hdfs in a Docker container when trying to run hadoop fs -ls

I am volume mounting my local machine's /etc/hadoop/conf directory so the configurations are the same.  I have no problems running the hadoop fs -ls command on my local machine.

Similar answers are not helpful because they do not address the host/docker issue.

I am running on CentOS 7.

答:
I was able to fix.  The issue was because the directories:

/usr/lib/hadoop-0.20-mapreduce
/usr/lib/hadoop-hdfs
/usr/lib/hadoop-mapreduce
/usr/lib/hadoop-yarn were not present in the Docker container.  Once I volume mounted those directories into my container, it worked perfectly.


问:
Kubernetes pod can't reach overlay network on a specific node
I have a k8s cluster deployed on premise on ubuntu 16.04.3 VMs.
Cluster is composed by one master and 3 nodes. Overlay network is flannel.

```<code>   # kubectl get no
   NAME       STATUS                     ROLES     AGE       VERSION
   buru       Ready                      <none>    70d       v1.8.4
   fraser     Ready,SchedulingDisabled   <none>    2h        v1.8.4
   tasmania   Ready                      <none>    1d        v1.8.4
   whiddy     Ready,SchedulingDisabled   master    244d      v1.8.4
</code>```

Despite being configured exactly the same way, 2 of my nodes (buru and tasmania) work correctly, while the third one (fraser) simply doesn't want to collaborate.

If I ssh in the fraser server, I can correctly reach the overlay network:

```<code>root@fraser:~# ifconfig flannel.1
flannel.1 Link encap:Ethernet  HWaddr 52:4a:da:84:8a:7b
          inet addr:10.244.3.0  Bcast:0.0.0.0  Mask:255.255.255.255
          inet6 addr: fe80::504a:daff:fe84:8a7b/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1450  Metric:1
          RX packets:11 errors:0 dropped:0 overruns:0 frame:0
          TX packets:11 errors:0 dropped:8 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:756 (756.0 B)  TX bytes:756 (756.0 B)

root@fraser:~# ping 10.244.0.1
PING 10.244.0.1 (10.244.0.1) 56(84) bytes of data.
64 bytes from 10.244.0.1: icmp_seq=1 ttl=64 time=0.764 ms
^C
--- 10.244.0.1 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.764/0.764/0.764/0.000 ms
root@fraser:~# ping 10.244.0.1
PING 10.244.0.1 (10.244.0.1) 56(84) bytes of data.
64 bytes from 10.244.0.1: icmp_seq=1 ttl=64 time=0.447 ms
64 bytes from 10.244.0.1: icmp_seq=2 ttl=64 time=1.20 ms
64 bytes from 10.244.0.1: icmp_seq=3 ttl=64 time=0.560 ms
^C
--- 10.244.0.1 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2000ms
rtt min/avg/max/mdev = 0.447/0.736/1.203/0.334 ms
</code>```

But the pods cannot reach the overlay network apparently:

```<code># kubectl --all-namespaces=true get po -o wide | grep fraser
kube-system                  test-fraser                                                 1/1       Running            0          20m       10.244.3.7       fraser

# kubectl -n kube-system exec -ti test-fraser ash
/ # ping 10.244.0.1
PING 10.244.0.1 (10.244.0.1): 56 data bytes
^C
--- 10.244.0.1 ping statistics ---
12 packets transmitted, 0 packets received, 100% packet loss
</code>```

The test-fraser pod is just an alpine static pod I am using for troubleshooting.

The same pod, deployed the same way in another node (buru) works just fine.

Since overlay network works on the host itself, I'd say that flannel is working just fine here.
For some reason, though, networking inside pods isn't working.

Other notes

All server have no firewall enabled

Docker version is the same (1.13.1)

All nodes are up to date in terms of ubuntu updates

Can anybody help me troubleshoot this problem?

edit

```<code>kubectl describe no fraser
Name:               fraser
Roles:              <none>
Labels:             beta.kubernetes.io/arch=amd64
                    beta.kubernetes.io/os=linux
                    kubernetes.io/hostname=fraser
Annotations:        flannel.alpha.coreos.com/backend-data={"VtepMAC":"52:4a:da:84:8a:7b"}
                    flannel.alpha.coreos.com/backend-type=vxlan
                    flannel.alpha.coreos.com/kube-subnet-manager=true
                    flannel.alpha.coreos.com/public-ip=80.211.157.110
                    node.alpha.kubernetes.io/ttl=0
                    volumes.kubernetes.io/controller-managed-attach-detach=true
Taints:             <none>
CreationTimestamp:  Thu, 07 Dec 2017 12:51:22 +0100
Conditions:
  Type             Status  LastHeartbeatTime                 LastTransitionTime                Reason                       Message
  ----             ------  -----------------                 ------------------                ------                       -------
  OutOfDisk        False   Thu, 07 Dec 2017 15:27:27 +0100   Thu, 07 Dec 2017 12:51:22 +0100   KubeletHasSufficientDisk     kubelet has sufficient disk space available
  MemoryPressure   False   Thu, 07 Dec 2017 15:27:27 +0100   Thu, 07 Dec 2017 14:47:57 +0100   KubeletHasSufficientMemory   kubelet has sufficient memory available
  DiskPressure     False   Thu, 07 Dec 2017 15:27:27 +0100   Thu, 07 Dec 2017 14:47:57 +0100   KubeletHasNoDiskPressure     kubelet has no disk pressure
  Ready            True    Thu, 07 Dec 2017 15:27:27 +0100   Thu, 07 Dec 2017 14:48:07 +0100   KubeletReady                 kubelet is posting ready status. AppArmor enabled
Addresses:
  InternalIP:  80.211.157.110
  Hostname:    fraser
Capacity:
 cpu:     4
 memory:  8171244Ki
 pods:    110
Allocatable:
 cpu:     4
 memory:  8068844Ki
 pods:    110
System Info:
 Machine ID:                 cb102c57fd539a2fb8ffab52578f27bd
 System UUID:                423E50F4-C4EF-23F0-F300-B568F4B4B8B1
 Boot ID:                    ca80d640-380a-4851-bab0-ee1fffd20bb2
 Kernel Version:             4.4.0-92-generic
 OS Image:                   Ubuntu 16.04.3 LTS
 Operating System:           linux
 Architecture:               amd64
 Container Runtime Version:  docker://1.13.1
 Kubelet Version:            v1.8.4
 Kube-Proxy Version:         v1.8.4
PodCIDR:                     10.244.3.0/24
ExternalID:                  fraser
Non-terminated Pods:         (5 in total)
  Namespace                  Name                                         CPU Requests  CPU Limits  Memory Requests  Memory Limits
  ---------                  ----                                         ------------  ----------  ---------------  -------------
  kube-system                filebeat-mghqx                               100m (2%)     0 (0%)      100Mi (1%)       200Mi (2%)
  kube-system                kube-flannel-ds-gvw4s                        0 (0%)        0 (0%)      0 (0%)           0 (0%)
  kube-system                kube-proxy-62vts                             0 (0%)        0 (0%)      0 (0%)           0 (0%)
  kube-system                test-fraser                                  0 (0%)        0 (0%)      0 (0%)           0 (0%)
  prometheus                 prometheus-prometheus-node-exporter-mwq67    0 (0%)        0 (0%)      0 (0%)           0 (0%)
Allocated resources:
  (Total limits may be over 100 percent, i.e., overcommitted.)
  CPU Requests  CPU Limits  Memory Requests  Memory Limits
  ------------  ----------  ---------------  -------------
  100m (2%)     0 (0%)      100Mi (1%)       200Mi (2%)
Events:
  Type    Reason                   Age                From                Message
  ----    ------                   ----               ----                -------
  Normal  Starting                 48m                kubelet, fraser     Starting kubelet.
  Normal  NodeAllocatableEnforced  48m                kubelet, fraser     Updated Node Allocatable limit across pods
  Normal  NodeHasSufficientDisk    48m                kubelet, fraser     Node fraser status is now: NodeHasSufficientDisk
  Normal  NodeHasSufficientMemory  48m                kubelet, fraser     Node fraser status is now: NodeHasSufficientMemory
  Normal  NodeHasNoDiskPressure    48m                kubelet, fraser     Node fraser status is now: NodeHasNoDiskPressure
  Normal  NodeNotReady             48m                kubelet, fraser     Node fraser status is now: NodeNotReady
  Normal  NodeNotSchedulable       48m                kubelet, fraser     Node fraser status is now: NodeNotSchedulable
  Normal  NodeReady                48m                kubelet, fraser     Node fraser status is now: NodeReady
  Normal  NodeNotSchedulable       48m                kubelet, fraser     Node fraser status is now: NodeNotSchedulable
  Normal  NodeAllocatableEnforced  48m                kubelet, fraser     Updated Node Allocatable limit across pods
  Normal  NodeHasSufficientDisk    48m                kubelet, fraser     Node fraser status is now: NodeHasSufficientDisk
  Normal  NodeHasSufficientMemory  48m                kubelet, fraser     Node fraser status is now: NodeHasSufficientMemory
  Normal  Starting                 48m                kubelet, fraser     Starting kubelet.
  Normal  NodeNotReady             48m                kubelet, fraser     Node fraser status is now: NodeNotReady
  Normal  NodeHasNoDiskPressure    48m                kubelet, fraser     Node fraser status is now: NodeHasNoDiskPressure
  Normal  NodeReady                48m                kubelet, fraser     Node fraser status is now: NodeReady
  Normal  Starting                 39m                kubelet, fraser     Starting kubelet.
  Normal  NodeAllocatableEnforced  39m                kubelet, fraser     Updated Node Allocatable limit across pods
  Normal  NodeHasSufficientDisk    39m                kubelet, fraser     Node fraser status is now: NodeHasSufficientDisk
  Normal  NodeHasSufficientMemory  39m (x2 over 39m)  kubelet, fraser     Node fraser status is now: NodeHasSufficientMemory
  Normal  NodeHasNoDiskPressure    39m (x2 over 39m)  kubelet, fraser     Node fraser status is now: NodeHasNoDiskPressure
  Normal  NodeNotReady             39m                kubelet, fraser     Node fraser status is now: NodeNotReady
  Normal  NodeNotSchedulable       39m                kubelet, fraser     Node fraser status is now: NodeNotSchedulable
  Normal  NodeReady                39m                kubelet, fraser     Node fraser status is now: NodeReady
  Normal  Starting                 39m                kube-proxy, fraser  Starting kube-proxy.
</code>```

答:
The issue has been answered in the comment sections.

for debugging k8s Node, we need to make sure following components (Kubelet,Docker,Kube-proxy and IPtables) work perfectly.

we can get comprehensive information by the following command

```<code>kubectl get nodes
kubectl describe nodes NODE-NAME
</code>```

By the comprehensive result, we can check kube-proxy, kubelet , docker and CNI plugin (flannel) are running perfectly.

If its networking issues we will check IPtables

```<code>iptables -L -v
</code>```

Body:
I have a k8s cluster deployed on premise on ubuntu 16.04.3 VMs.
Cluster is composed by one master and 3 nodes. Overlay network is flannel.

   # kubectl get no
   NAME       STATUS                     ROLES     AGE       VERSION
   buru       Ready                      <none>    70d       v1.8.4
   fraser     Ready,SchedulingDisabled   <none>    2h        v1.8.4
   tasmania   Ready                      <none>    1d        v1.8.4
   whiddy     Ready,SchedulingDisabled   master    244d      v1.8.4

Despite being configured exactly the same way, 2 of my nodes (buru and tasmania) work correctly, while the third one (fraser) simply doesn't want to collaborate.

If I ssh in the fraser server, I can correctly reach the overlay network:

root@fraser:~# ifconfig flannel.1
flannel.1 Link encap:Ethernet  HWaddr 52:4a:da:84:8a:7b
          inet addr:10.244.3.0  Bcast:0.0.0.0  Mask:255.255.255.255
          inet6 addr: fe80::504a:daff:fe84:8a7b/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1450  Metric:1
          RX packets:11 errors:0 dropped:0 overruns:0 frame:0
          TX packets:11 errors:0 dropped:8 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:756 (756.0 B)  TX bytes:756 (756.0 B)

root@fraser:~# ping 10.244.0.1
PING 10.244.0.1 (10.244.0.1) 56(84) bytes of data.
64 bytes from 10.244.0.1: icmp_seq=1 ttl=64 time=0.764 ms
^C
--- 10.244.0.1 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.764/0.764/0.764/0.000 ms
root@fraser:~# ping 10.244.0.1
PING 10.244.0.1 (10.244.0.1) 56(84) bytes of data.
64 bytes from 10.244.0.1: icmp_seq=1 ttl=64 time=0.447 ms
64 bytes from 10.244.0.1: icmp_seq=2 ttl=64 time=1.20 ms
64 bytes from 10.244.0.1: icmp_seq=3 ttl=64 time=0.560 ms
^C
--- 10.244.0.1 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2000ms
rtt min/avg/max/mdev = 0.447/0.736/1.203/0.334 ms

But the pods cannot reach the overlay network apparently:

# kubectl --all-namespaces=true get po -o wide | grep fraser
kube-system                  test-fraser                                                 1/1       Running            0          20m       10.244.3.7       fraser

# kubectl -n kube-system exec -ti test-fraser ash
/ # ping 10.244.0.1
PING 10.244.0.1 (10.244.0.1): 56 data bytes
^C
--- 10.244.0.1 ping statistics ---
12 packets transmitted, 0 packets received, 100% packet loss

The test-fraser pod is just an alpine static pod I am using for troubleshooting.

The same pod, deployed the same way in another node (buru) works just fine.

Since overlay network works on the host itself, I'd say that flannel is working just fine here.
For some reason, though, networking inside pods isn't working.

Other notes

All server have no firewall enabled

Docker version is the same (1.13.1)

All nodes are up to date in terms of ubuntu updates

Can anybody help me troubleshoot this problem?

edit

kubectl describe no fraser
Name:               fraser
Roles:              <none>
Labels:             beta.kubernetes.io/arch=amd64
                    beta.kubernetes.io/os=linux
                    kubernetes.io/hostname=fraser
Annotations:        flannel.alpha.coreos.com/backend-data={"VtepMAC":"52:4a:da:84:8a:7b"}
                    flannel.alpha.coreos.com/backend-type=vxlan
                    flannel.alpha.coreos.com/kube-subnet-manager=true
                    flannel.alpha.coreos.com/public-ip=80.211.157.110
                    node.alpha.kubernetes.io/ttl=0
                    volumes.kubernetes.io/controller-managed-attach-detach=true
Taints:             <none>
CreationTimestamp:  Thu, 07 Dec 2017 12:51:22 +0100
Conditions:
  Type             Status  LastHeartbeatTime                 LastTransitionTime                Reason                       Message
  ----             ------  -----------------                 ------------------                ------                       -------
  OutOfDisk        False   Thu, 07 Dec 2017 15:27:27 +0100   Thu, 07 Dec 2017 12:51:22 +0100   KubeletHasSufficientDisk     kubelet has sufficient disk space available
  MemoryPressure   False   Thu, 07 Dec 2017 15:27:27 +0100   Thu, 07 Dec 2017 14:47:57 +0100   KubeletHasSufficientMemory   kubelet has sufficient memory available
  DiskPressure     False   Thu, 07 Dec 2017 15:27:27 +0100   Thu, 07 Dec 2017 14:47:57 +0100   KubeletHasNoDiskPressure     kubelet has no disk pressure
  Ready            True    Thu, 07 Dec 2017 15:27:27 +0100   Thu, 07 Dec 2017 14:48:07 +0100   KubeletReady                 kubelet is posting ready status. AppArmor enabled
Addresses:
  InternalIP:  80.211.157.110
  Hostname:    fraser
Capacity:
 cpu:     4
 memory:  8171244Ki
 pods:    110
Allocatable:
 cpu:     4
 memory:  8068844Ki
 pods:    110
System Info:
 Machine ID:                 cb102c57fd539a2fb8ffab52578f27bd
 System UUID:                423E50F4-C4EF-23F0-F300-B568F4B4B8B1
 Boot ID:                    ca80d640-380a-4851-bab0-ee1fffd20bb2
 Kernel Version:             4.4.0-92-generic
 OS Image:                   Ubuntu 16.04.3 LTS
 Operating System:           linux
 Architecture:               amd64
 Container Runtime Version:  docker://1.13.1
 Kubelet Version:            v1.8.4
 Kube-Proxy Version:         v1.8.4
PodCIDR:                     10.244.3.0/24
ExternalID:                  fraser
Non-terminated Pods:         (5 in total)
  Namespace                  Name                                         CPU Requests  CPU Limits  Memory Requests  Memory Limits
  ---------                  ----                                         ------------  ----------  ---------------  -------------
  kube-system                filebeat-mghqx                               100m (2%)     0 (0%)      100Mi (1%)       200Mi (2%)
  kube-system                kube-flannel-ds-gvw4s                        0 (0%)        0 (0%)      0 (0%)           0 (0%)
  kube-system                kube-proxy-62vts                             0 (0%)        0 (0%)      0 (0%)           0 (0%)
  kube-system                test-fraser                                  0 (0%)        0 (0%)      0 (0%)           0 (0%)
  prometheus                 prometheus-prometheus-node-exporter-mwq67    0 (0%)        0 (0%)      0 (0%)           0 (0%)
Allocated resources:
  (Total limits may be over 100 percent, i.e., overcommitted.)
  CPU Requests  CPU Limits  Memory Requests  Memory Limits
  ------------  ----------  ---------------  -------------
  100m (2%)     0 (0%)      100Mi (1%)       200Mi (2%)
Events:
  Type    Reason                   Age                From                Message
  ----    ------                   ----               ----                -------
  Normal  Starting                 48m                kubelet, fraser     Starting kubelet.
  Normal  NodeAllocatableEnforced  48m                kubelet, fraser     Updated Node Allocatable limit across pods
  Normal  NodeHasSufficientDisk    48m                kubelet, fraser     Node fraser status is now: NodeHasSufficientDisk
  Normal  NodeHasSufficientMemory  48m                kubelet, fraser     Node fraser status is now: NodeHasSufficientMemory
  Normal  NodeHasNoDiskPressure    48m                kubelet, fraser     Node fraser status is now: NodeHasNoDiskPressure
  Normal  NodeNotReady             48m                kubelet, fraser     Node fraser status is now: NodeNotReady
  Normal  NodeNotSchedulable       48m                kubelet, fraser     Node fraser status is now: NodeNotSchedulable
  Normal  NodeReady                48m                kubelet, fraser     Node fraser status is now: NodeReady
  Normal  NodeNotSchedulable       48m                kubelet, fraser     Node fraser status is now: NodeNotSchedulable
  Normal  NodeAllocatableEnforced  48m                kubelet, fraser     Updated Node Allocatable limit across pods
  Normal  NodeHasSufficientDisk    48m                kubelet, fraser     Node fraser status is now: NodeHasSufficientDisk
  Normal  NodeHasSufficientMemory  48m                kubelet, fraser     Node fraser status is now: NodeHasSufficientMemory
  Normal  Starting                 48m                kubelet, fraser     Starting kubelet.
  Normal  NodeNotReady             48m                kubelet, fraser     Node fraser status is now: NodeNotReady
  Normal  NodeHasNoDiskPressure    48m                kubelet, fraser     Node fraser status is now: NodeHasNoDiskPressure
  Normal  NodeReady                48m                kubelet, fraser     Node fraser status is now: NodeReady
  Normal  Starting                 39m                kubelet, fraser     Starting kubelet.
  Normal  NodeAllocatableEnforced  39m                kubelet, fraser     Updated Node Allocatable limit across pods
  Normal  NodeHasSufficientDisk    39m                kubelet, fraser     Node fraser status is now: NodeHasSufficientDisk
  Normal  NodeHasSufficientMemory  39m (x2 over 39m)  kubelet, fraser     Node fraser status is now: NodeHasSufficientMemory
  Normal  NodeHasNoDiskPressure    39m (x2 over 39m)  kubelet, fraser     Node fraser status is now: NodeHasNoDiskPressure
  Normal  NodeNotReady             39m                kubelet, fraser     Node fraser status is now: NodeNotReady
  Normal  NodeNotSchedulable       39m                kubelet, fraser     Node fraser status is now: NodeNotSchedulable
  Normal  NodeReady                39m                kubelet, fraser     Node fraser status is now: NodeReady
  Normal  Starting                 39m                kube-proxy, fraser  Starting kube-proxy.

Body:
The issue has been answered in the comment sections.

for debugging k8s Node, we need to make sure following components (Kubelet,Docker,Kube-proxy and IPtables) work perfectly.

we can get comprehensive information by the following command

kubectl get nodes
kubectl describe nodes NODE-NAME

By the comprehensive result, we can check kube-proxy, kubelet , docker and CNI plugin (flannel) are running perfectly.

If its networking issues we will check IPtables

iptables -L -v


问:
Java how to respond to HttpExchange
I am new to Java. I used write server in Golang. I need to send response to the HttpExchange. Here is my code:

```<code>public static void main(String[] args) throws IOException
{
  Server = HttpServer.create(new InetSocketAddress(8000),0);
  Server.createContext("/login", new SimpleHandler());
  Server.setExecutor(null);
  Server.start();
}
class SimpleHandler implements HttpHandler
{
    @Override
    public void handle(HttpExchange request) throws IOException
    {
     //Here I need to do like request.Response.Write(200,"DONE");
    }
}
</code>```

答:
Handle method in your case should looks like: </p>

```<code>    public void handle(HttpExchange request) throws IOException
    {
        byte[] response = "DONE".getBytes();
        e.sendResponseHeaders(200, response.length);
        OutputStream os = e.getResponseBody();
        os.write(response);
        os.close();
   }
</code>```

Title: Java how to respond to HttpExchange

Body:
I am new to Java. I used write server in Golang. I need to send response to the HttpExchange. Here is my code:

public static void main(String[] args) throws IOException
{
  Server = HttpServer.create(new InetSocketAddress(8000),0);
  Server.createContext("/login", new SimpleHandler());
  Server.setExecutor(null);
  Server.start();
}
class SimpleHandler implements HttpHandler
{
    @Override
    public void handle(HttpExchange request) throws IOException
    {
     //Here I need to do like request.Response.Write(200,"DONE");
    }
}

Body:
Handle method in your case should looks like:

    public void handle(HttpExchange request) throws IOException
    {
        byte[] response = "DONE".getBytes();
        e.sendResponseHeaders(200, response.length);
        OutputStream os = e.getResponseBody();
        os.write(response);
        os.close();
   }


问:
How to parse this json in java? I want to fetch the keypad details that too with keypad id = 1,how can i achieve this?
{
    "Pump Details": {
        "Pump Configuration": "DUO",
        "Keypad": [{
            "Keypad AssetID ": 0,
            "Keypad SHASignature": null,
            "KeyPad Software Version": null,
            "Keypad CheckSum": null,
            "Keypad Unique ID": null,
            "Keypad FuelingPontID": "1",
            "Keypad ID": "1"
        }, {
            "Keypad AssetID ": 0,
            "Keypad SHASignature": null,
            "KeyPad Software Version": null,
            "Keypad CheckSum": null,
            "Keypad Unique ID": null,
            "Keypad FuelingPontID": "2",
            "Keypad ID": "2"
        }],
        "Cpu": [{
            "CpuAssetID ": 0,
            "CpuSHASignature": null,
            "CpuCheckSum": null,
            "CpuUnique ID": null,
            "CpuSoftware Version": null
        }],
        "Pump Serial Number": "194719471951",
        "Pulser": [{
            "Pulser Unique ID": null,
            "Pulser SHASignature": null,
            "Pulser Software Version": null,
            "Pulser AssetID ": 0,
            "Pulser ID": "1",
            "Pulser FuelingPontID": "1",
            "Pulser CheckSum": null
        }, {
            "Pulser Unique ID": null,
            "Pulser SHASignature": null,
            "Pulser Software Version": null,
            "Pulser AssetID ": 0,
            "Pulser ID": "2",
            "Pulser FuelingPontID": "2",
            "Pulser CheckSum": null
        }],
        "Display": [{
            "Display FuelingPontID": "1",
            "Display SHASignature": null,
            "Display CheckSum": null,
            "Display ID": "1",
            "Display Unique ID": null,
            "Display AssetID ": 0,
            "Display Software Version": null
        }, {
            "Display FuelingPontID": "2",
            "Display SHASignature": null,
            "Display CheckSum": null,
            "Display ID": "2",
            "Display Unique ID": null,
            "Display AssetID ": 0,
            "Display Software Version": null
        }]
    }
}</p>

答:
You can make it with Gson liike that.(You make all object types.You should check parameter types.)</p>

```<code>class Keypad{
@SerializedName("Keypad AssetID") public int AssetID;
@SerializedName("Keypad SHASignature") public String SHASignature;
@SerializedName("KeyPad Software Version") public String SoftwareVersion;
@SerializedName("Keypad CheckSum") public String CheckSum;
@SerializedName("Keypad Unique ID") public String UniqueID;
@SerializedName("Keypad FuelingPontID") public String FuelingPontID;
@SerializedName("Keypad ID") public String ID;
}
</code>```

Body:
You can make it with Gson liike that.(You make all object types.You should check parameter types.)

class Keypad{
@SerializedName("Keypad AssetID") public int AssetID;
@SerializedName("Keypad SHASignature") public String SHASignature;
@SerializedName("KeyPad Software Version") public String SoftwareVersion;
@SerializedName("Keypad CheckSum") public String CheckSum;
@SerializedName("Keypad Unique ID") public String UniqueID;
@SerializedName("Keypad FuelingPontID") public String FuelingPontID;
@SerializedName("Keypad ID") public String ID;
}


问:
Socket Io client creates multiple listener on Vue Componet
I am Using Vue.js as the front-end framework.

I am adding the socket.io listener on a component using created life-cycle hook.

```<code>created () {
    // socket listener
    this.$socket.on('event', (response) => { .... })
}
</code>```

Now if the component is unmounted and later remounted then two listener are created.

I tried using "once" in place of "on" but same problem.

How Can I make sure that only one Listener is active?

Note: The socket component is added to Vue as Instance Property.

答:
You don't say what $socket is, but the way you handle this is to remove the listener when the component is destroyed.

```<code>methods:{
  handleEvent(response) { ... }
},
created(){
  this.$socket.on('event', this.handleEvent)
},
beforeDestroy(){
  // using "removeListener" here, but this should be whatever $socket provides
  // for removing listeners
  this.$socket.removeListener('event', this.handleEvent)
}
</code>```

I based the method removeListener off of this answer but it may be some other method for removing listeners depending on your library.

Body:
I am Using Vue.js as the front-end framework.

I am adding the socket.io listener on a component using created life-cycle hook.

created () {
    // socket listener
    this.$socket.on('event', (response) => { .... })
}

Now if the component is unmounted and later remounted then two listener are created.

I tried using "once" in place of "on" but same problem.

How Can I make sure that only one Listener is active?

Note: The socket component is added to Vue as Instance Property.

Body:
You don't say what $socket is, but the way you handle this is to remove the listener when the component is destroyed.

methods:{
  handleEvent(response) { ... }
},
created(){
  this.$socket.on('event', this.handleEvent)
},
beforeDestroy(){
  // using "removeListener" here, but this should be whatever $socket provides
  // for removing listeners
  this.$socket.removeListener('event', this.handleEvent)
}

I based the method removeListener off of this answer but it may be some other method for removing listeners depending on your library.


问:
Create a constant variable link to year and quarter
Hi i am a stata user and i am trying to pass my codes to R. I have a panel data as shown below, and i am looking for a command that can create a constant variable according to which year and quarter the row is located. In stata such command would be reproduced by gen new_variable = yq(year, quarter)

My dataframe look like this

```<code>id     year    quarter
 1    2007          1
 1    2007          2
 1    2007          3
 1    2007          4
 1    2008          1
 1    2008          2
 1    2008          3
 1    2008          4
 1    2009          1
 1    2009          2
 1    2009          3
 1    2009          4
 2    2007          1
 2    2007          2
 2    2007          3
 2    2007          4
 2    2008          1
 2    2008          2
 2    2008          3
 2    2008          4
 3    2009          2
 3    2009          3
 3    2010          2
 3    2010          3
</code>```

I my expected output should look like this: (Values inside new_variable are arbitrary, just looking for a constant value the would be always the same for each year and quarter)

```<code>id     year    quarter   new_variable
 1    2007          1     220
 1    2007          2     221
 1    2007          3     222
 1    2007          4     223
 1    2008          1     224
 1    2008          2     225
 1    2008          3     226
 1    2008          4     227
 1    2009          1     228
 1    2009          2     229
 1    2009          3     230
 1    2009          4     231
 2    2007          1     220
 2    2007          2     221
 2    2007          3     222
 2    2007          4     223
 2    2008          1     224
 2    2008          2     225
 2    2008          3     226
 2    2008          4     227
 3    2009          2     229
 3    2009          3     230
 3    2010          2     233
 3    2010          3     234
</code>```

Body:
Hi i am a stata user and i am trying to pass my codes to R. I have a panel data as shown below, and i am looking for a command that can create a constant variable according to which year and quarter the row is located. In stata such command would be reproduced by gen new_variable = yq(year, quarter)

My dataframe look like this

id     year    quarter
 1    2007          1
 1    2007          2
 1    2007          3
 1    2007          4
 1    2008          1
 1    2008          2
 1    2008          3
 1    2008          4
 1    2009          1
 1    2009          2
 1    2009          3
 1    2009          4
 2    2007          1
 2    2007          2
 2    2007          3
 2    2007          4
 2    2008          1
 2    2008          2
 2    2008          3
 2    2008          4
 3    2009          2
 3    2009          3
 3    2010          2
 3    2010          3

I my expected output should look like this: (Values inside new_variable are arbitrary, just looking for a constant value the would be always the same for each year and quarter)

id     year    quarter   new_variable
 1    2007          1     220
 1    2007          2     221
 1    2007          3     222
 1    2007          4     223
 1    2008          1     224
 1    2008          2     225
 1    2008          3     226
 1    2008          4     227
 1    2009          1     228
 1    2009          2     229
 1    2009          3     230
 1    2009          4     231
 2    2007          1     220
 2    2007          2     221
 2    2007          3     222
 2    2007          4     223
 2    2008          1     224
 2    2008          2     225
 2    2008          3     226
 2    2008          4     227
 3    2009          2     229
 3    2009          3     230
 3    2010          2     233
 3    2010          3     234

Body:
Here are two options:

library(dplyr) # with dplyr
df %>% mutate(new_variable = group_indices(., year, quarter))

library(data.table) # with data.table
setDT(df)[, new_variable := .GRP, .(year, quarter)]

Data

df <- structure(list(id = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L), year = c(2007L,
2007L, 2007L, 2007L, 2008L, 2008L, 2008L, 2008L, 2009L, 2009L,
2009L, 2009L, 2007L, 2007L, 2007L, 2007L, 2008L, 2008L, 2008L,
2008L, 2009L, 2009L, 2010L, 2010L), quarter = c(1L, 2L, 3L, 4L,
1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L,
2L, 3L, 2L, 3L)), .Names = c("id", "year", "quarter"), class = "data.frame", row.names = c(NA,
-24L))


问:
Laravel Sold Items Count
I want count the Sold items for every Seller.
I try to change this Code:

```<code><?php $count = DB::table('purchases')->whereIn('seller_id', [4])->count(); echo $count; ?>
</code>```

Can i add an other $DB command in it?

```<code>{{$product->seller->id}}
</code>```

Like this for example instead of [4]:

```<code><?php $count = DB::table('purchases')->whereIn('seller_id', [{{$product->seller->id}}])->count(); echo $count; ?>
</code>```

答:
If you want to get a count for a group of users, you can use whereIn with an array of seller ids.

But if you want a count for each seller, you should use grouping

```<code>->groupBy('seller_id')
</code>```

so that your query could look like:

```<code>$user_info = DB::table('purchases')
             ->select('seller_id', DB::raw('count(*) as total'))
             ->groupBy('seller_id')
             ->get();
</code>```

Title: Laravel Sold Items Count

Body:
I want count the Sold items for every Seller.
I try to change this Code:

<?php $count = DB::table('purchases')->whereIn('seller_id', [4])->count(); echo $count; ?>

Can i add an other $DB command in it?

{{$product->seller->id}}

Like this for example instead of [4]:

<?php $count = DB::table('purchases')->whereIn('seller_id', [{{$product->seller->id}}])->count(); echo $count; ?>

Body:
If you want to get a count for a group of users, you can use whereIn with an array of seller ids.

But if you want a count for each seller, you should use grouping

->groupBy('seller_id')

so that your query could look like:

$user_info = DB::table('purchases')
             ->select('seller_id', DB::raw('count(*) as total'))
             ->groupBy('seller_id')
             ->get();


问:
Does localStorage or sessionStorage affect Website accessibility?
I would like to use localStorage/sessionStorage to store essential information during a commerce process, which includes site reloads/redirects. Forms are not an option.

That implies, that the user has to have JavaScript enabled. That fact and the usage of these techniques, could it affect accessibility tools, for instance screen readers?

I could not found any information in the WAI-ARIA specification.

答:
This is no longer considered as being a problem.

This is documented in the WCAG FAQ : Can I meet WCAG 2.0 with Javascript/Ajax, Flash, PDF, Silverlight, and other technologies?

More information can be read in the conformance claim chapter

Javascript is considered nowadays as being "Accessibility Supported" but you would have to explicity state that this technology is "relied upon" in any conformance claim you may establish.


问:
progressive web app OCR SDK (JavaScript)
We have developed a web-application which uses OCR technology. We use a paid API-service for that which works pretty well.
Our backend/server uses a Ruby/Rails based API and our frontend/client uses VUE.js.
Now the OCR tech was server side but we want to grow into the offline/PWA (progressive web app) market as well and are currently developing an offline-version of our app. Since the OCR-part of our app has to run in the client, we'd move the OCR tech also client side which means we have to use some sort of PWA compatible OCR tech, e.g. a JavaScript SDK

I have probably searched the whole internet but there does not really seem to be a solution. It all came down to two major providers:

tesseract / the probably biggest OCR project (open source). They offer a JS SDK (tesseract.js) -> http://tesseract.projectnaptha.com/ but this works pretty bad. We have compared results to the API that we're using and the results are terrible. Hence, we cannot use it.

ABBYY which is probably the most well known OCR provider in the web and they offer OCR scanning for reasonable prices. After calling them they unfortunately also do not provide any solution for PWAs, only for native apps

multiple other small projects which use everything except JS libraries unfortunately

Before giving up and consider developing a native app (which will be quote cost intensive for us) I considered to ask here if any known OCR solution for PWAs is known which I did not consider yet. Thx

答:
You can use the ocrad.js open source javascript OCR library: http://antimatter15.com/ocrad.js/demo.html | https://github.com/antimatter15/ocrad.js

It's 3mb size but it's working well on lots of examples.