问:
Change/swap values one after another in pandas dataframe for selected rows
Dataframe:

```<code>col1 col2
  A    0
  A    1
  A    nan
  B    0
  B    1
  C    and so on...
</code>```

I am trying to change 1 to 0, 0 to 1 and nan stays as such in col2 wherever col1=='A'.

Code so far:

```<code>df.loc[(df.col1=='A') & (df.col2==0),'col2'] = 2
df.loc[(df.col1=='A') & (df.col2==1),'col2'] = 0
df.loc[(df.col1=='A') & (df.col2==2),'col2'] = 1

# Hope you understand why I am converting 0 to 2 first then to 1.
# Because if I convert all zeroes to 1 then all 1's will be converted to
# 0 in subsequent conversion.
</code>```

Unique values in col2 are 0,1 and nan.
Is there a correct/better way of doing this?
Also, is there a way to directly swap these numbers instead of assignment operators?

答:
One solution using Series.where and astype(bool) with ~ (NOT operator) and then back to astype(int). Then use loc with boolean indexing to assign back to DataFrame:

```<code>df.loc[df.col1.eq('A'), 'col2'] = df.col2.where(df.col2.isna(),
                                               (~df.col2.astype(bool)).astype(int))
</code>```

[out]

```<code>  col1  col2
0    A   1.0
1    A   0.0
2    A   NaN
3    B   0.0
4    B   1.0
5    C   NaN
</code>```

Body:
Dataframe:

col1 col2
  A    0
  A    1
  A    nan
  B    0
  B    1
  C    and so on...

I am trying to change 1 to 0, 0 to 1 and nan stays as such in col2 wherever col1=='A'.

Code so far:

df.loc[(df.col1=='A') & (df.col2==0),'col2'] = 2
df.loc[(df.col1=='A') & (df.col2==1),'col2'] = 0
df.loc[(df.col1=='A') & (df.col2==2),'col2'] = 1

# Hope you understand why I am converting 0 to 2 first then to 1.
# Because if I convert all zeroes to 1 then all 1's will be converted to
# 0 in subsequent conversion.

Unique values in col2 are 0,1 and nan.
Is there a correct/better way of doing this?
Also, is there a way to directly swap these numbers instead of assignment operators?

Body:
One solution using Series.where and astype(bool) with ~ (NOT operator) and then back to astype(int). Then use loc with boolean indexing to assign back to DataFrame:

df.loc[df.col1.eq('A'), 'col2'] = df.col2.where(df.col2.isna(),
                                               (~df.col2.astype(bool)).astype(int))

[out]

  col1  col2
0    A   1.0
1    A   0.0
2    A   NaN
3    B   0.0
4    B   1.0
5    C   NaN


来源: stackexchange

问:
Given Time in minutes, print it in hours and minutes
In Question,  Given Time is in minutes that requires to be converted into hours and minutes.

Sample :

Input - 53
Output - 0 53

```<code>num = int(input())
if num < 60:
    print('0'+" "+str(num))
else:
    if num>=60:
        time = num*(1/60)
        time1 = (format(time, '.2f'))
        print(str(time1).replace('.',' '))
</code>```

答:
The easiest way to do this is using integer division (//) and modulo (%):

```<code>def printAsHoursAndMinutes(timeInMinutes):
    hours = timeInMinutes // 60
    minutes = timeInMinutes % 60
    print("{} {}".format(hours, minutes)) #edited to match the requested output format
</code>```

// will return the integer part of the devision, % returns the rest. With 130 as input, the above code will print "2 10", for 5 as input, it prints "0 5".

[Edit:] This works for any nonegative integer. If you want to support negative integers too, add the following condition just before the print:

```<code>if(timeInMinutes < 0):
    hours = hours + 1
    minutes = 60 - minutes
</code>```

This allows us to handle inputs like -65 to print "-1 5".

For floating point numbers, things migth get a bit ugly because % is not 100% acurate (e.g. 60.1 results in 1.0 0.10000000000000142). This even happenes when using divmod as mentioned by @CristiFati in the comments to the question, so there is no real way around it and we'd need a more advanced handling or a custom modulo method but that is off-topic here.

ContentLicense: CC BY-SA 4.0

Body:
In Question,  Given Time is in minutes that requires to be converted into hours and minutes.

Sample :

Input - 53
Output - 0 53

num = int(input())
if num < 60:
    print('0'+" "+str(num))
else:
    if num>=60:
        time = num*(1/60)
        time1 = (format(time, '.2f'))
        print(str(time1).replace('.',' '))

Body:
The easiest way to do this is using integer division (//) and modulo (%):

def printAsHoursAndMinutes(timeInMinutes):
    hours = timeInMinutes // 60
    minutes = timeInMinutes % 60
    print("{} {}".format(hours, minutes)) #edited to match the requested output format

// will return the integer part of the devision, % returns the rest. With 130 as input, the above code will print "2 10", for 5 as input, it prints "0 5".

[Edit:] This works for any nonegative integer. If you want to support negative integers too, add the following condition just before the print:

if(timeInMinutes < 0):
    hours = hours + 1
    minutes = 60 - minutes

This allows us to handle inputs like -65 to print "-1 5".

For floating point numbers, things migth get a bit ugly because % is not 100% acurate (e.g. 60.1 results in 1.0 0.10000000000000142). This even happenes when using divmod as mentioned by @CristiFati in the comments to the question, so there is no real way around it and we'd need a more advanced handling or a custom modulo method but that is off-topic here.


问:
Is there an array function which produces more elements than it receives?
If we use map on array - we will get the same number of elements.

If we want less elements - we can use filter, find or reduce, depending on situation.

Is there a build in function which would work the other way?

For example, let's say I have an array like this:

```<code>myArray = [
  {nodes: Array(5)}, // some array with 5 elements
  {nodes: Array(3)},
  {nodes: Array(3)}
]
</code>```

I want to split every array with more than 3 elements into array which maximum 3 elements. So in the end I want to get:

```<code>splittedArray = [
  {nodes: Array(3)},
  {nodes: Array(2)},
  {nodes: Array(3)},
  {nodes: Array(3)}
]
</code>```

I know how to achive this with looping over myArray with forEach and pushing items to some new array, but is there some ready-to-go function for it?

答:
but is there some ready-to-go function for it?

Unfortunately not. Other languages (Kotlin for example) , do have a chunk method.

However this could be achieved with .flatMap, but "good old for loops" work way better here:

```<code> const result = [], size = 3;

 for(const { nodes } of myArray) {
    for(let i = 0; i < nodes.length; i += size)
      result.push({ nodes: nodes.slice(i, i + size) });
 }
</code>```

Body:
If we use map on array - we will get the same number of elements.

If we want less elements - we can use filter, find or reduce, depending on situation.

Is there a build in function which would work the other way?

For example, let's say I have an array like this:

myArray = [
  {nodes: Array(5)}, // some array with 5 elements
  {nodes: Array(3)},
  {nodes: Array(3)}
]

I want to split every array with more than 3 elements into array which maximum 3 elements. So in the end I want to get:

splittedArray = [
  {nodes: Array(3)},
  {nodes: Array(2)},
  {nodes: Array(3)},
  {nodes: Array(3)}
]

I know how to achive this with looping over myArray with forEach and pushing items to some new array, but is there some ready-to-go function for it?

Body:
but is there some ready-to-go function for it?

Unfortunately not. Other languages (Kotlin for example) , do have a chunk method.

However this could be achieved with .flatMap, but "good old for loops" work way better here:

 const result = [], size = 3;

 for(const { nodes } of myArray) {
    for(let i = 0; i < nodes.length; i += size)
      result.push({ nodes: nodes.slice(i, i + size) });
 }


问:
Adding +1 to multiple values in one cell via excel formula
I got an excel file with a data source sheet. To be able to parse the data at the next step I need to add 1 to every value and get it into a new sheet. The thing is, that there are multiple values per cell, each separated by comma, and this number is not static. Adding the +1 at a later point is sadly not an option so I need to do this in excel.</p>

```<code>  Source sheet              Prepared data sheet

| MyValues   |             | MyValues + 1 |
|------------|             |--------------|
| 0,1,2,3    |             |  1,2,3,4     |
| 3          |   ----->    |  4           |
| 2,4,6      |             |  3,5,7       |
| 1          |             |  2           |
</code>```

答:
Here is one way doing this (assuming Excel 2016 with TEXTJOIN()):

Formula in B1:

```<code>=IFERROR(TRIM(MID(SUBSTITUTE($A1,",",REPT(" ",LEN($A1))),(COLUMN()-2)*LEN($A1)+1,LEN($A1)))+1,"")
</code>```

Drag down and sideways (could be 15 columns if need be)

Formula in G1:

```<code>=TEXTJOIN(",",TRUE,B1:E1)
</code>```

Drag down

You don't need a VBA solution but in your case a UDF could also be a nice way to do this, for example like so:

```<code>Function AddVal(RNG As Range, VAL As Double) As String

Dim ARR1() As String, ARR2() As String, X As Double
If RNG.Cells.Count = 1 Then
    ARR = Split(RNG.Value, ",")
    For X = LBound(ARR) To UBound(ARR)
        ReDim Preserve ARR2(X)
        ARR2(X) = ARR(X) + VAL
    Next X
    If IsEmpty(ARR2) Then
        AddVal = "No hits"
    Else
        AddVal = Join(ARR2, ",")
    End If
Else
    AddVal = "No valid range"
End If

End Function
</code>```

Call through =AddVal(A1;1)

You can change the 1 for another number if you want to add more than just 1.

Body:
I got an excel file with a data source sheet. To be able to parse the data at the next step I need to add 1 to every value and get it into a new sheet. The thing is, that there are multiple values per cell, each separated by comma, and this number is not static. Adding the +1 at a later point is sadly not an option so I need to do this in excel.

  Source sheet              Prepared data sheet

| MyValues   |             | MyValues + 1 |
|------------|             |--------------|
| 0,1,2,3    |             |  1,2,3,4     |
| 3          |   ----->    |  4           |
| 2,4,6      |             |  3,5,7       |
| 1          |             |  2           |

Body:
Here is one way doing this (assuming Excel 2016 with TEXTJOIN()):

Formula in B1:

=IFERROR(TRIM(MID(SUBSTITUTE($A1,",",REPT(" ",LEN($A1))),(COLUMN()-2)*LEN($A1)+1,LEN($A1)))+1,"")

Drag down and sideways (could be 15 columns if need be)

Formula in G1:

=TEXTJOIN(",",TRUE,B1:E1)

Drag down

You don't need a VBA solution but in your case a UDF could also be a nice way to do this, for example like so:

Function AddVal(RNG As Range, VAL As Double) As String

Dim ARR1() As String, ARR2() As String, X As Double
If RNG.Cells.Count = 1 Then
    ARR = Split(RNG.Value, ",")
    For X = LBound(ARR) To UBound(ARR)
        ReDim Preserve ARR2(X)
        ARR2(X) = ARR(X) + VAL
    Next X
    If IsEmpty(ARR2) Then
        AddVal = "No hits"
    Else
        AddVal = Join(ARR2, ",")
    End If
Else
    AddVal = "No valid range"
End If

End Function

Call through =AddVal(A1;1)

You can change the 1 for another number if you want to add more than just 1.


问:
Comparing two columns and if it matches both the columns should be highlighted
I have two columns J and L.

If the value of J column matches with the corresponding value of L column, both the cells should be highlighted in red.

I am new to this Excel. I am not able to develop this macro.

I tried the below code but it is highlighting J, K and L column if it matches I want only the J and K column to be highlighted and also this macro should start checking from J11 and L11

```<code>Sub test()
    Dim LastRow As Long, i As Long
    Dim arr As Variant

    With ThisWorkbook.Worksheets("Sheet1")
        LastRow = .Cells(.Rows.Count, "J").End(xlUp).Row
        arr = .Range("J2" & ":L" & LastRow)

        For i = LBound(arr) To UBound(arr)
            If arr(i, 1) = arr(i, 3) Then
                .Range("J" & i + 1 & ":L" & i + 1).Interior.Color = vbRed
            End If
        Next i
    End With
End Sub
</code>```

答:
Select the range with data

Home - Styles - Conditional Formatting

New Rule - Use a formula to determine which cells to format

Format values where this formula is true:

=$J1=$L1

Format - Fill - select your color

Change Applies to (the area where the formatting will apply)

Rule:

Results:

Body:
I have two columns J and L.

If the value of J column matches with the corresponding value of L column, both the cells should be highlighted in red.

I am new to this Excel. I am not able to develop this macro.

I tried the below code but it is highlighting J, K and L column if it matches I want only the J and K column to be highlighted and also this macro should start checking from J11 and L11

Sub test()
    Dim LastRow As Long, i As Long
    Dim arr As Variant

    With ThisWorkbook.Worksheets("Sheet1")
        LastRow = .Cells(.Rows.Count, "J").End(xlUp).Row
        arr = .Range("J2" & ":L" & LastRow)

        For i = LBound(arr) To UBound(arr)
            If arr(i, 1) = arr(i, 3) Then
                .Range("J" & i + 1 & ":L" & i + 1).Interior.Color = vbRed
            End If
        Next i
    End With
End Sub


问:
Prevent redirection to root url
i am trying to access a webpage. I manage to get the redirect webpage session id as shown:
http://www.sbstransit.com.sg/mobileiris/(tqkjtlnqkh2lw5v4rz4yurzf)/mobresult_svclist.aspx?stopcode=16101

I added mobresult_svclist.aspx?stopcode=16101 after the session id to retrieve the information.

However, i could not access the page and keep been redirected to the root url: http://www.sbstransit.com.sg/mobileiris/(tqkjtlnqkh2lw5v4rz4yurzf)/index_nextbus.aspx?__redir=1.

Do anyone know how to prevent that redirection to the root url using php or any other codes? Thanks.

答: You would like to have access to data the webmaster doesn't want you to have. Just contact the webmaster and ask for it to achieve this in a proper way.</p>

ContentLicense: CC BY-SA 3.0

Title: Prevent redirection to root url


答:
Disclaimer: the proper way to check would have been to run your code through a profiler, which I did not do (as it would require faking input data with somewhat plausible lengths etc.).

Looking at the body of the for loop, the only line that can plausibly increase in execution time is

```<code>train = train.append(train_tmp)
</code>```

The doc says specifically to avoid this (probably because of a Schlemiel the painter situation):

Iteratively appending rows to a DataFrame can be more computationally intensive than a single concatenate. A better solution is to append those rows to a list and then concatenate the list with the original DataFrame all at once.

Title: Why the time cost is more and more larger when reading .mat file and processing it

Body:
I get 6500 mat flies about ECG.

And I want to read it from these files and do some processes about it, but I find the time cost is more and more than what I thought and tqdm estimated before.

So it puzzles me if there is anything wrong with my code.

Here is the mat file example:

# the number of each array are given same for convience, in fact they are totally not same
mat1 = scipy.io.loadmat('Train/TRAIN0001.mat')
mat1
{'I': array([[-0.02928, -0.02928, -0.02928, ... , 0.46848, 0.53192, 0.5856]]),
 'II': array([[-0.02928, -0.02928, -0.02928, ... , 0.46848, 0.53192, 0.5856]]),
 'III': array([[-0.02928, -0.02928, -0.02928, ... , 0.46848, 0.53192, 0.5856]]),
 'V1': array([[-0.02928, -0.02928, -0.02928, ... , 0.46848, 0.53192, 0.5856]]),
 'V2': array([[-0.02928, -0.02928, -0.02928, ... , 0.46848, 0.53192, 0.5856]]),
 'V3': array([[-0.02928, -0.02928, -0.02928, ... , 0.46848, 0.53192, 0.5856]]),
 'V4': array([[-0.02928, -0.02928, -0.02928, ... , 0.46848, 0.53192, 0.5856]]),
 'V5': array([[-0.02928, -0.02928, -0.02928, ... , 0.46848, 0.53192, 0.5856]]),
 'V6': array([[-0.02928, -0.02928, -0.02928, ... , 0.46848, 0.53192, 0.5856]]),
 '__globals__': [],
 '__header__': b'MATLAB 5.0 MAT-file Platform: nt, Created on: Mon May 6 16:56:48 2019',
 '__version__': '1.0',
 'aVF': array([[-0.02928, -0.02928, -0.02928, ... , 0.46848, 0.53192, 0.5856]]),
 'aVL': array([[-0.02928, -0.02928, -0.02928, ... , 0.46848, 0.53192, 0.5856]]),
 'aVR': array([[-0.02928, -0.02928, -0.02928, ... , 0.46848, 0.53192, 0.5856]]),
 'age': array([[63]], dtype=int32),
 'sex': array(['FEMALE'], dtype='<U6'),
}

Here is the code:

def read_mat(mat_path, index):
    mat = scipy.io.loadmat(mat_path)
    mat_df = pd.DataFrame({
                            'I_' + str(index): mat['I'][0],
                            'II_' + str(index): mat['II'][0],
                            'III_' + str(index): mat['III'][0],
                            'V1_' + str(index): mat['V1'][0],
                            'V2_' + str(index): mat['V2'][0],
                            'V3_' + str(index): mat['V3'][0],
                            'V4_' + str(index): mat['V4'][0],
                            'V5_' + str(index): mat['V5'][0],
                            'V6_' + str(index): mat['V6'][0],
                            'aVF_' + str(index): mat['aVF'][0],
                            'aVL_' + str(index): mat['aVL'][0],
                            'aVR_' + str(index): mat['aVR'][0]
    })

    age = pd.DataFrame({'age': mat['age'][0]})
    sex = pd.DataFrame({'sex': mat['sex']})
    sex['sex'] = sex['sex'].apply(lambda x: 1 if x == 'male' (0 if x == 'female' else 2))

    return mat_df, age, sex

def read_data():

    # target.csv save the label of every people
    tar = pd.read_csv('target.csv')

    # ECG has collected 5000 samples of each people, so I want to treat every sample as a feature
    train = pd.DataFrame(columns=[i for i in range(0, 5000)])
    for i in tqdm(range(1, 6501)):
        tmp_filename = 'TRAIN' + str(i).zfill(4)
        train_tmp, age, sex = read_mat('Train/' + tmp_filename, i)
        train_tmp = train_tmp.transpose()
        train_tmp['age'] = age['age'][0]
        train_tmp['sex'] = sex['sex'][0]
        train_tmp['target'] = tar['label'][i-1]

        # add 5000 samples of each mat file into train DataFrame
        train = train.append(train_tmp)
        del train_tmp, age, sex

    target = pd.Series()
    target = train['target']

    return train, target, tar

Here is the time cost:

0%         | 11/6500 [00:00<01:01, 105.36it/s]

  0%         | 19/6500
  [00:00<01:08, 94.25it/s]

  ...

   ...

   10%        | 636/6500 [02:14<39:37,
  2.47it/s]

   10%        | 640/6500 [02:15<39:52, 2.45it/s]

   ...

   ...

   20%        | 1322/6500 [09:25<1:12:56, 1.18it/s]

   20%        | 1328/6500
  [09:30<1:13:27, 1.17it/s]

   ...

   ...

   30%        | 1918/6500
  [20:02<1:13:53, 1.23s/it]

   ...

   ...

   40%        | 2586/6500
  [35:52<1:44:42, 1.61s/it]

   ...

   ...

   50%        | 3237/6500
  [2:08:11<10:58:41, 12.09s/it]

When I have read 50% mat files, it estimates that it will cost more than 10 hours.

AND I am wondering that is there anything wrong with my code so it will cost too much time.

Could anyone give me some hints on my code?

Thanks in advance.

Body:
Disclaimer: the proper way to check would have been to run your code through a profiler, which I did not do (as it would require faking input data with somewhat plausible lengths etc.).

Looking at the body of the for loop, the only line that can plausibly increase in execution time is

train = train.append(train_tmp)

The doc says specifically to avoid this (probably because of a Schlemiel the painter situation):

Iteratively appending rows to a DataFrame can be more computationally intensive than a single concatenate. A better solution is to append those rows to a list and then concatenate the list with the original DataFrame all at once.


问:
Dynamically create time from 00:00:00 to 23:30:00( half hour difference with time format HH::mm:ss) in Angular
I'm Setting up a dropdown of time dynamically, with format(HH:mm:ss),starting from 00:00:00 to 23:30:00. Is there any method to get this time format. Linq query is too appreciated.

Expected Result- 00:00:00, 00:30:00, 01:00:00, 01:30:00 to 11:30:00

enter image description here

答:
I used Kendo time picker for this, which indeed have the format.

```<code>import { Component } from '@angular/core';

@Component({
    selector: 'my-app',
    template: `
        <div class="example-wrapper">
            <p>Select a date:</p>
            <kendo-timepicker
                [format]="'HH:mm:ss'"
                [steps]="steps"
                [value]="value"
            ></kendo-timepicker>
            <p>(↑ to increment and ↓ to decrement the value)</p>
        </div>
    `
})
export class AppComponent {
    public steps: any = { hour: 0, minute: 30, second: 00 };
    public value: Date = new Date(2000, 2, 10, 10, 30);
}
</code>```

for further info: Check this link: https://www.telerik.com/kendo-angular-ui/components/dateinputs/timepicker/incremental-steps/

Body:
I used Kendo time picker for this, which indeed have the format.

import { Component } from '@angular/core';

@Component({
    selector: 'my-app',
    template: `
        <div class="example-wrapper">
            <p>Select a date:</p>
            <kendo-timepicker
                [format]="'HH:mm:ss'"
                [steps]="steps"
                [value]="value"
            ></kendo-timepicker>
            <p>(↑ to increment and ↓ to decrement the value)</p>
        </div>
    `
})
export class AppComponent {
    public steps: any = { hour: 0, minute: 30, second: 00 };
    public value: Date = new Date(2000, 2, 10, 10, 30);
}

for further info: Check this link: https://www.telerik.com/kendo-angular-ui/components/dateinputs/timepicker/incremental-steps/


问:
dplyr sample_n by one variable through another one
I have a data frame with a "grouping" variable season and another variable year which is repeated for each month.

```<code>df <- data.frame(month = as.character(sapply(month.name,function(x)rep(x,4))),
                  season = c(rep("winter",8),rep("spring",12),rep("summer",12),rep("autumn",12),rep("winter",4)),
                  year = rep(2021:2024,12))
</code>```

I would like to use dplyr::sample_n or something similar to choose 2 months in the data frame for each season and keep the same months for all the years, for example:

```<code>     month        season     year
1     January     winter     2021
2     January     winter     2022
3     January     winter     2023
4     January     winter     2024
5     February    winter     2021
6     February    winter     2022
7     February    winter     2023
8     February    winter     2024
9     March       spring     2021
10    March       spring     2022
11    March       spring     2023
12    March       spring     2024
13    May         spring     2021
14    May         spring     2022
15    May         spring     2023
16    May         spring     2024
17    June        summer     2021
18    June        summer     2022
19    June        summer     2023
20    June        summer     2024
21    July        summer     2021
22    July        summer     2022
23    July        summer     2023
24    July        summer     2024
25    October     autumn     2021
26    October     autumn     2022
27    October     autumn     2023
28    October     autumn     2024
29    November    autumn     2021
30    November    autumn     2022
31    November    autumn     2023
32    November    autumn     2024

</code>```

I cannot make df %>% group_by(season,year) %>% sample_n(2) since it chooses different months for each year.

Thanks!

答:
We can randomly sample 2 values from month and filter them by group.

```<code>library(dplyr)

df %>%
  group_by(season) %>%
  filter(month %in% sample(unique(month),2))

#   month    season  year
#   <chr>    <chr>  <int>
# 1 January  winter  2021
# 2 January  winter  2022
# 3 January  winter  2023
# 4 January  winter  2024
# 5 February winter  2021
# 6 February winter  2022
# 7 February winter  2023
# 8 February winter  2024
# 9 March    spring  2021
#10 March    spring  2022
# … with 22 more rows
</code>```

If for certain groups there are less than 2 unique values we can select minimum between 2 and unique values in the group to sample.

```<code>df %>%
  group_by(season) %>%
  filter(month %in% sample(unique(month),min(2, n_distinct(month))))
</code>```

Using the same logic with base R, we can use ave

```<code>df[as.logical(with(df, ave(month, season,
             FUN = function(x) x %in% sample(unique(x),2)))), ]
</code>```

Body:
I have a data frame with a "grouping" variable season and another variable year which is repeated for each month.

df <- data.frame(month = as.character(sapply(month.name,function(x)rep(x,4))),
                  season = c(rep("winter",8),rep("spring",12),rep("summer",12),rep("autumn",12),rep("winter",4)),
                  year = rep(2021:2024,12))

I would like to use dplyr::sample_n or something similar to choose 2 months in the data frame for each season and keep the same months for all the years, for example:

     month        season     year
1     January     winter     2021
2     January     winter     2022
3     January     winter     2023
4     January     winter     2024
5     February    winter     2021
6     February    winter     2022
7     February    winter     2023
8     February    winter     2024
9     March       spring     2021
10    March       spring     2022
11    March       spring     2023
12    March       spring     2024
13    May         spring     2021
14    May         spring     2022
15    May         spring     2023
16    May         spring     2024
17    June        summer     2021
18    June        summer     2022
19    June        summer     2023
20    June        summer     2024
21    July        summer     2021
22    July        summer     2022
23    July        summer     2023
24    July        summer     2024
25    October     autumn     2021
26    October     autumn     2022
27    October     autumn     2023
28    October     autumn     2024
29    November    autumn     2021
30    November    autumn     2022
31    November    autumn     2023
32    November    autumn     2024

I cannot make df %>% group_by(season,year) %>% sample_n(2) since it chooses different months for each year.

Thanks!

Body:
We can randomly sample 2 values from month and filter them by group.

library(dplyr)

df %>%
  group_by(season) %>%
  filter(month %in% sample(unique(month),2))

#   month    season  year
#   <chr>    <chr>  <int>
# 1 January  winter  2021
# 2 January  winter  2022
# 3 January  winter  2023
# 4 January  winter  2024
# 5 February winter  2021
# 6 February winter  2022
# 7 February winter  2023
# 8 February winter  2024
# 9 March    spring  2021
#10 March    spring  2022
# … with 22 more rows

If for certain groups there are less than 2 unique values we can select minimum between 2 and unique values in the group to sample.

df %>%
  group_by(season) %>%
  filter(month %in% sample(unique(month),min(2, n_distinct(month))))

Using the same logic with base R, we can use ave

df[as.logical(with(df, ave(month, season,
             FUN = function(x) x %in% sample(unique(x),2)))), ]


问:
Multiple build variants with cpu architectures in Android Studio
I'm setting up Product Flavor in Android Studio ,there is created multiple build variants in studio

like

FlavourDebug1-armeabi-v7a

FlavourDebug1-arm64-v8a

FlavourDebug1-x86

FlavourDebug1-x86_64

FlavourRelease1-armeabi-v7a

FlavourRelease1-arm64-v8a

FlavourRelease1-x86

FlavourRelease1-x86_64

=============

How to remove that and only get

Debug

Release

```<code>android {
compileSdkVersion 28
defaultConfig {
    applicationId "com.xxx.smart.xx.launcher"
    minSdkVersion 21
    targetSdkVersion 28
    versionCode 1
    versionName "1.0"
    multiDexEnabled true
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    externalNativeBuild {
        cmake {
            cppFlags "-std=c++14"
        }
    }
    ndk {
        abiFilters "armeabi-v7a", "arm64-v8a", "x86", "x86_64"
    }
    javaCompileOptions {
        annotationProcessorOptions {
            arguments = ['objectbox.debug': 'true']
        }
    }
}

buildTypes {
    debug {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}
externalNativeBuild {
    cmake {
        path "src/main/cpp/CMakeLists.txt"
    }
}
compileOptions {
    sourceCompatibility = '1.8'
    targetCompatibility = '1.8'
}

flavorDimensions "version"
productFlavors {
    ChoiceIPTVFlavour {
        applicationId 'com.xxx.smart.xx.launcher'
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        vectorDrawables.useSupportLibrary = true
        multiDexEnabled true

    }
    PurpleIPTVFlavour {
        minSdkVersion 21
        applicationId 'com.xxx.smart.xx.launcher'
        targetSdkVersion 28
        versionCode 1
        versionName '1.0'
        vectorDrawables.useSupportLibrary = true
        multiDexEnabled true

    }
}
</code>```

答:
remove code like this from your gradle

```<code> splits {
        abi {
            enable true
            reset()

            // Specifies a list of ABIs that Gradle should create APKs for.
            include "x86", "x86_64", "armeabi-v7a", "arm64-v8a", "armeabi", "mips", "mips64"
            universalApk true //generate an additional APK that contains all the ABIs
        }
    }
</code>```

Body:
I'm setting up Product Flavor in Android Studio ,there is created multiple build variants in studio

like

FlavourDebug1-armeabi-v7a

FlavourDebug1-arm64-v8a

FlavourDebug1-x86

FlavourDebug1-x86_64

FlavourRelease1-armeabi-v7a

FlavourRelease1-arm64-v8a

FlavourRelease1-x86

FlavourRelease1-x86_64

=============

How to remove that and only get

Debug

Release

android {
compileSdkVersion 28
defaultConfig {
    applicationId "com.xxx.smart.xx.launcher"
    minSdkVersion 21
    targetSdkVersion 28
    versionCode 1
    versionName "1.0"
    multiDexEnabled true
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    externalNativeBuild {
        cmake {
            cppFlags "-std=c++14"
        }
    }
    ndk {
        abiFilters "armeabi-v7a", "arm64-v8a", "x86", "x86_64"
    }
    javaCompileOptions {
        annotationProcessorOptions {
            arguments = ['objectbox.debug': 'true']
        }
    }
}

buildTypes {
    debug {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}
externalNativeBuild {
    cmake {
        path "src/main/cpp/CMakeLists.txt"
    }
}
compileOptions {
    sourceCompatibility = '1.8'
    targetCompatibility = '1.8'
}

flavorDimensions "version"
productFlavors {
    ChoiceIPTVFlavour {
        applicationId 'com.xxx.smart.xx.launcher'
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        vectorDrawables.useSupportLibrary = true
        multiDexEnabled true

    }
    PurpleIPTVFlavour {
        minSdkVersion 21
        applicationId 'com.xxx.smart.xx.launcher'
        targetSdkVersion 28
        versionCode 1
        versionName '1.0'
        vectorDrawables.useSupportLibrary = true
        multiDexEnabled true

    }
}

Body:
remove code like this from your gradle

 splits {
        abi {
            enable true
            reset()

            // Specifies a list of ABIs that Gradle should create APKs for.
            include "x86", "x86_64", "armeabi-v7a", "arm64-v8a", "armeabi", "mips", "mips64"
            universalApk true //generate an additional APK that contains all the ABIs
        }
    }


问:
EJB Timer Service error
I'm trying to use the EJB timer service, I have a class named TimerBean which carries the methods to schedule a timer and handle the timeout, this implements TimerBeanRemote an interface class.

In another session bean I have the following:

```<code>TimerBeanRemote service = (TimerBeanRemote) new InitialContext().lookup("TimerBean/remote");
</code>```

When I try to run it on the server I get the error:

javax.naming.NamingException: Lookup failed for 'TimerBean/remote' in SerialContext  [Root exception is javax.naming.NameNotFoundException: TimerBean]

Any ideas as to why it can't find it? Thanks!

答:
Following from your comments -if you are trying to access TimerBeanRemote within the same container then you can inject the @Remote ejb in your servlet or JSF Backing Bean else you can locate your EJB through a JNDI lookup.

Suppose your TimerBean is: com.mypackage.timer.TimerBeanRemote
then as per explanation above you can either inject or lookup:

Injection

public class MyServlet ...{

@EJB

com.mypackage.timer.TimerBeanRemote timerBean;

}

JNDI lookup:

    Properties props = new Properties();

    props.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.enterprise.naming.SerialInitContextFactory");

    String[] serverDetails = server.split(":");

    props.setProperty("org.omg.CORBA.ORBInitialHost", MyHost);

    props.setProperty("org.omg.CORBA.ORBInitialPort", MyPort);

```<code>InitialContext ic = new InitialContext(props);<br>
TimerBeanRemote timerBean = (TimerBeanRemote)ic.lookup("com.mypackage.timer.TimerBeanRemote");
</code>```

You can read the following articles for further details:
http://download.oracle.com/javaee/1.4/tutorial/doc/Session5.html

http://www.javabeat.net/articles/3-ejb-30-timer-services-an-overview-1.html

Title: EJB Timer Service error

Body:
I'm trying to use the EJB timer service, I have a class named TimerBean which carries the methods to schedule a timer and handle the timeout, this implements TimerBeanRemote an interface class.

In another session bean I have the following:

TimerBeanRemote service = (TimerBeanRemote) new InitialContext().lookup("TimerBean/remote");

When I try to run it on the server I get the error:

javax.naming.NamingException: Lookup failed for 'TimerBean/remote' in SerialContext  [Root exception is javax.naming.NameNotFoundException: TimerBean]

Any ideas as to why it can't find it? Thanks!

Body:
Following from your comments -if you are trying to access TimerBeanRemote within the same container then you can inject the @Remote ejb in your servlet or JSF Backing Bean else you can locate your EJB through a JNDI lookup.

Suppose your TimerBean is: com.mypackage.timer.TimerBeanRemote
then as per explanation above you can either inject or lookup:

Injection

public class MyServlet ...{

@EJB

com.mypackage.timer.TimerBeanRemote timerBean;

}

JNDI lookup:

    Properties props = new Properties();

    props.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.enterprise.naming.SerialInitContextFactory");

    String[] serverDetails = server.split(":");

    props.setProperty("org.omg.CORBA.ORBInitialHost", MyHost);

    props.setProperty("org.omg.CORBA.ORBInitialPort", MyPort);

InitialContext ic = new InitialContext(props);<br>
TimerBeanRemote timerBean = (TimerBeanRemote)ic.lookup("com.mypackage.timer.TimerBeanRemote");

You can read the following articles for further details:
http://download.oracle.com/javaee/1.4/tutorial/doc/Session5.html

http://www.javabeat.net/articles/3-ejb-30-timer-services-an-overview-1.html


问:
Spaces and columns in command output not preserved in flask response
Here is my simple flask api endpoint:

 # -*- coding: utf-8 -*-

 from flask import Flask, render_template
 from subprocess import PIPE, Popen

 app = Flask(__name__)

 @app.route('/', methods=['GET'])
 def main():
     cmd = Popen(['vmstat', '-a', '-w'], stdout=PIPE, stderr=PIPE)
     output, err = cmd.communicate()
     output = output.splitlines()
     return render_template('stats_template.html', output=output)

 if __name__ == '__main__':
     app.run(port=54321, host='0.0.0.0')
```

<p>The template looks like this:</p>

<pre class="lang-html prettyprint-override"><code> <ul>
  {% for l in output %}
    <p>{{ l }}</p>
  {% endfor %}
 </ul>
</code>```

The program runs fine, however the line breaks, columns are not preserved and the output in browser is not so readable:

```<code>b'procs -----------------------memory---------------------- ---swap-- -----io---- -system-- --------cpu--------'

b' r b swpd free inact active si so bi bo in cs us sy id wa st'

b' 1 0 13068 1599088 560976 790220 0 0 36 73 139 597 21 41 38 0 0'
</code>```

Have been trying to get rid of the b' along with having the output exactly as seen in linux shell.

Appreciate any insight.

Edit1: Adding output of vmstat as reference. As you can see, the response from flask did not preserve the spaces and columns.

$ vmstat -a -w
procs -----------------------memory---------------------- ---swap-- -----io---- -system-- --------cpu--------
 r  b         swpd         free        inact       active   si   so    bi    bo   in   cs  us  sy  id  wa  st
 1  0        13068      1611488       563132       776448    0    0    35    73  159  693  21  42  37   0   0
```

答:
This required html ```</code> tag in jinja2 template to get expected output.</p>

<p>Final template:</p>

```

    {% for line in output %}
      ```{{ line }}```
    {% endfor %}

```

<p>Final flask snippet:</p>

```# -*- coding: utf-8 -*-

from flask import Flask, render_template
from subprocess import PIPE, Popen

application = Flask(__name__)

@application.route('/', methods=['GET'])
def vmstat():
    cmd = Popen(['/usr/bin/vmstat', '-a', '-w'], shell = False, stdout=PIPE, stderr=PIPE)
    output, err = cmd.communicate()
    output = str(output, 'utf-8').splitlines()
    return render_template('stats_template.html', output=output)

if __name__ == '__main__':
    application.run(port=54321, host='0.0.0.0')
```

<p>And browser shows:</p>

```procs -----------------------memory---------------------- ---swap-- -----io---- -system-- --------cpu--------
 r  b         swpd         free        inact       active   si   so    bi    bo   in   cs  us  sy  id  wa  st
 0  0            0     14368716       639576       955400    0    0     8     1    1    1   0   0 100   0   0
```

Body:
Here is my simple flask api endpoint:

 # -*- coding: utf-8 -*-

 from flask import Flask, render_template
 from subprocess import PIPE, Popen

 app = Flask(__name__)

 @app.route('/', methods=['GET'])
 def main():
     cmd = Popen(['vmstat', '-a', '-w'], stdout=PIPE, stderr=PIPE)
     output, err = cmd.communicate()
     output = output.splitlines()
     return render_template('stats_template.html', output=output)

 if __name__ == '__main__':
     app.run(port=54321, host='0.0.0.0')

The template looks like this:

  {% for l in output %}

{{ l }}

  {% endfor %}

The program runs fine, however the line breaks, columns are not preserved and the output in browser is not so readable:

b'procs -----------------------memory---------------------- ---swap-- -----io---- -system-- --------cpu--------'

b' r b swpd free inact active si so bi bo in cs us sy id wa st'

b' 1 0 13068 1599088 560976 790220 0 0 36 73 139 597 21 41 38 0 0'

Have been trying to get rid of the b' along with having the output exactly as seen in linux shell.

Appreciate any insight.

Edit1: Adding output of vmstat as reference. As you can see, the response from flask did not preserve the spaces and columns.

$ vmstat -a -w
procs -----------------------memory---------------------- ---swap-- -----io---- -system-- --------cpu--------
 r  b         swpd         free        inact       active   si   so    bi    bo   in   cs  us  sy  id  wa  st
 1  0        13068      1611488       563132       776448    0    0    35    73  159  693  21  42  37   0   0

Body:
This required html <pre> tag in jinja2 template to get expected output.

Final template:

<div>
  <ul>
    {% for line in output %}
      <pre>{{ line }}</pre>
    {% endfor %}
  </ul>
</div>

Final flask snippet:

# -*- coding: utf-8 -*-

from flask import Flask, render_template
from subprocess import PIPE, Popen

application = Flask(__name__)

@application.route('/', methods=['GET'])
def vmstat():
    cmd = Popen(['/usr/bin/vmstat', '-a', '-w'], shell = False, stdout=PIPE, stderr=PIPE)
    output, err = cmd.communicate()
    output = str(output, 'utf-8').splitlines()
    return render_template('stats_template.html', output=output)

if __name__ == '__main__':
    application.run(port=54321, host='0.0.0.0')

And browser shows:

procs -----------------------memory---------------------- ---swap-- -----io---- -system-- --------cpu--------
 r  b         swpd         free        inact       active   si   so    bi    bo   in   cs  us  sy  id  wa  st
 0  0            0     14368716       639576       955400    0    0     8     1    1    1   0   0 100   0   0


问:
Using JPA with stored procedures that return multiple result sets
Is it possible to handle multiple result sets having different columns from a stored procedure in SQL Server using JPA?  What is a way (or the best way) to do this?

I am currently working with Hibernate 4.3.5 Final and JPA 2.1, SqlServer 2008.

The saga of my current approach can be found here: Hibernate JPA, inheritance and Stored Procedure returning multiple result sets

but it apparently not the right approach.  If anyone knows how to make this work, please let me know.  Thanks!!

答: when each result set returns a different column, you can create different DTOs to collect the results and make all DTOs to implement an interface or extend an abstract class (the abstract class should contain columns common to all result sets). Then return type should be the implemented interface/abstract class. This works in my experience.</p>


问:
Spring boot JSP configuration not working
I followed the sample Git setup here: https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-web-jsp.

When I load the home page it displays resource could not be found. Even when I've cross-checked my configuration and the only difference between the two projects is that one is multi-module, while the other is single module.

And it worked, but for my multi-module maven project the same configuration seems to not be working... is there any explanation to this? I'm also kind of new to maven so I'm assuming it has something to do with the way I have my maven setup configured. The link to my GitHub repo is: https://github.com/diljotr/storm.net.

Relevant links to look at are:

https://github.com/diljotr/storm.net/blob/master/storm.net.app/src/main/java/storm/net/Application.java
https://github.com/diljotr/storm.net/blob/master/storm.net.web/src/main/java/storm/net/controller/HomeController.java
https://github.com/diljotr/storm.net/blob/master/storm.net.web/src/main/java/storm/net/WebApplication.java

Setup outlined below

Parent POM:

```<code>    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>storm.net</groupId>
    <artifactId>storm.net</artifactId>
    <packaging>pom</packaging>
    <version>1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.0.1.RELEASE</version>
    </parent>

    <modules>
        <module>storm.net.api</module>
        <module>storm.net.core</module>
        <module>storm.net.web</module>
        <module>storm.net.app</module>
    </modules>

    <properties>
        <spring.version>4.0.3.RELEASE</spring.version>
        <tomcat.version>7.0.53</tomcat.version>

        <!-- Spring Boot build configuration -->
        <java.version>1.7</java.version>
        <start-class>storm.net.Application</start-class>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <configuration>
                    <createDependencyReducedPom>false</createDependencyReducedPom>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

Web Child POM:

```<code>    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>storm.net</artifactId>
        <groupId>storm.net</groupId>
        <version>1.0</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>storm.net.web</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/webapp</directory>
            </resource>
        </resources>
    </build>

</project>
</code>```

App POM that wraps the entire library together

```<code>    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>storm.net</artifactId>
        <groupId>storm.net</groupId>
        <version>1.0</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>storm.net.app</artifactId>

    <dependencies>
        <dependency>
            <groupId>storm.net</groupId>
            <artifactId>storm.net.core</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>storm.net</groupId>
            <artifactId>storm.net.web</artifactId>
            <version>${project.version}</version>
        </dependency>
    </dependencies>

</project>
</code>```

答:
Follow below Configuration  :

In Intellij:
    Go to Run Menu -> Edit Configuration  -> Working directory: $MODULE_WORKING_DIR$

spring.mvc.view.prefix: /WEB-INF/jsp/
spring.mvc.view.suffix: .jsp

Body:
I followed the sample Git setup here: https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-web-jsp.

When I load the home page it displays resource could not be found. Even when I've cross-checked my configuration and the only difference between the two projects is that one is multi-module, while the other is single module.

And it worked, but for my multi-module maven project the same configuration seems to not be working... is there any explanation to this? I'm also kind of new to maven so I'm assuming it has something to do with the way I have my maven setup configured. The link to my GitHub repo is: https://github.com/diljotr/storm.net.

Relevant links to look at are:

https://github.com/diljotr/storm.net/blob/master/storm.net.app/src/main/java/storm/net/Application.java
https://github.com/diljotr/storm.net/blob/master/storm.net.web/src/main/java/storm/net/controller/HomeController.java
https://github.com/diljotr/storm.net/blob/master/storm.net.web/src/main/java/storm/net/WebApplication.java

Setup outlined below

Parent POM:

    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>storm.net</groupId>
    <artifactId>storm.net</artifactId>
    <packaging>pom</packaging>
    <version>1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.0.1.RELEASE</version>
    </parent>

    <modules>
        <module>storm.net.api</module>
        <module>storm.net.core</module>
        <module>storm.net.web</module>
        <module>storm.net.app</module>
    </modules>

    <properties>
        <spring.version>4.0.3.RELEASE</spring.version>
        <tomcat.version>7.0.53</tomcat.version>

        <java.version>1.7</java.version>
        <start-class>storm.net.Application</start-class>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <configuration>
                    <createDependencyReducedPom>false</createDependencyReducedPom>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Web Child POM:

    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>storm.net</artifactId>
        <groupId>storm.net</groupId>
        <version>1.0</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>storm.net.web</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/webapp</directory>
            </resource>
        </resources>
    </build>

</project>

App POM that wraps the entire library together

    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>storm.net</artifactId>
        <groupId>storm.net</groupId>
        <version>1.0</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>storm.net.app</artifactId>

    <dependencies>
        <dependency>
            <groupId>storm.net</groupId>
            <artifactId>storm.net.core</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>storm.net</groupId>
            <artifactId>storm.net.web</artifactId>
            <version>${project.version}</version>
        </dependency>
    </dependencies>

</project>


问:
Why does multimap allow duplicate key-value pairs?
EDIT: Please note, I'm NOT asking why multimap can't contain duplicate keys.

What's the rationale behind multimap allowing duplicate key-value pairs? (not keys)

```<code>#include <map>
#include <string>
#include <iostream>

int
main(int argc, char** argv)
{
    std::multimap<std::string, std::string> m;
    m.insert(std::make_pair("A", "B"));
    m.insert(std::make_pair("A", "B"));
    m.insert(std::make_pair("A", "C"));
    std::cout << m.size() << std::endl;
    return 0;
}
</code>```

This printed 3, which somewhat surprised me, I expected multimap to behave like a set of pairs, so I was expecting 2.

Intuitively, it's not consistent with C++ std::map behaviour, where insert does not always change the map (as opposed to operator[]).

Is there a rationale behind it, or it's just arbitrary?

答: "multimap" is meant to support 'multiple' keys unlike simple "map". Since it allows multiple keys, it won't bother for their values, so it shows 3 elements in your example. The other difference is, one can not have operator [] for multimap.

Body:
EDIT: Please note, I'm NOT asking why multimap can't contain duplicate keys.

What's the rationale behind multimap allowing duplicate key-value pairs? (not keys)

#include <map>
#include <string>
#include <iostream>

int
main(int argc, char** argv)
{
    std::multimap<std::string, std::string> m;
    m.insert(std::make_pair("A", "B"));
    m.insert(std::make_pair("A", "B"));
    m.insert(std::make_pair("A", "C"));
    std::cout << m.size() << std::endl;
    return 0;
}

This printed 3, which somewhat surprised me, I expected multimap to behave like a set of pairs, so I was expecting 2.

Intuitively, it's not consistent with C++ std::map behaviour, where insert does not always change the map (as opposed to operator[]).

Is there a rationale behind it, or it's just arbitrary?


问:
Error in facebook login from mobile browser
I am trying to login by Facebook using "react-facebook-login" and "passport-facebook-token" in nodejs.
I logged successfully in the web browser but i am getting an error "URL Bloocked" in mobile browser.
When i am switching to desktop mode on my phone its successfully login.

```<code>const module.exports = passport => {
passport.use(
"facebookStrategy",
new FacebookStrategy(
  {
    clientID: *****,
    clientSecret: "*****",
  },
  (accessToken, refreshToken, profile, done) => {
    User.findOne({ email: profile.emails[0].value })
      .then(user => {
        if (user) {
          return done(null, user);
        } else {
          //create new profile
          const newProfile = new Profile({
            user: newUser.id,
            username: profile.displayName,
            email: profile.emails[0].value,
            profilepic: profile.photos[0].value
          });
          newProfile
            .save()
            .catch(err =>
              console.log("Error in creating new profile " + err)
            );
          return done(null, newProfile);
        }
      })
      .catch(err => console.log(err));
  }
)
</code>```

);
};

答:
This is common issue among mobile browsers and you will find that it would also be in some android devices.

For precaution it is under best practice to build flow of login manually. Go here
https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow

So yes, you will need to go with manual integration. But, it will be full-proof integration without doubts.

Body:
I am trying to login by Facebook using "react-facebook-login" and "passport-facebook-token" in nodejs.
I logged successfully in the web browser but i am getting an error "URL Bloocked" in mobile browser.
When i am switching to desktop mode on my phone its successfully login.

const module.exports = passport => {
passport.use(
"facebookStrategy",
new FacebookStrategy(
  {
    clientID: *****,
    clientSecret: "*****",
  },
  (accessToken, refreshToken, profile, done) => {
    User.findOne({ email: profile.emails[0].value })
      .then(user => {
        if (user) {
          return done(null, user);
        } else {
          //create new profile
          const newProfile = new Profile({
            user: newUser.id,
            username: profile.displayName,
            email: profile.emails[0].value,
            profilepic: profile.photos[0].value
          });
          newProfile
            .save()
            .catch(err =>
              console.log("Error in creating new profile " + err)
            );
          return done(null, newProfile);
        }
      })
      .catch(err => console.log(err));
  }
)

);
};


问:
How to disable wi-fi on Android device in Appium?
In our test case: I need to disable Wi-Fi at some specific point/action.

I have verified:

```<code>driver[deviceIndex].setConnection(Connection.NONE);
assertEquals(Connection.ALL, driver[deviceIndex].getConnection());
</code>```

But it's not doing anything.

My expectation is "turning OFF wi-fi" and keeping Mobile Data ON.

Current code is doing no action.

答:
You need to add Apache common langs to your project.
https://mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.9</p>

Body:
In our test case: I need to disable Wi-Fi at some specific point/action.

I have verified:

driver[deviceIndex].setConnection(Connection.NONE);
assertEquals(Connection.ALL, driver[deviceIndex].getConnection());

But it's not doing anything.

My expectation is "turning OFF wi-fi" and keeping Mobile Data ON.

Current code is doing no action.


问:
MapBox GL JS marker offset
I'm using MapBox GL JS to create a map with a custom marker:

```<code>var marker = new mapboxgl.Marker(container)
    .setLngLat([
        datacenters[country][city].coordinates.lng,
        datacenters[country][city].coordinates.lat
    ])
    .addTo(map);
</code>```

However, I seem to have some kind of offset problem with the marker. The thing is: when zoomed out a bit, the bottom of the marker is not really pointing to the exact location:

When I'm zooming in a bit further it reaches its destination and it's pointing to the exact spot.

I really love MapBox GL, but this particular problem is bugging me and I'd love to know how to solve it. When this is fixed my implementation is far more superior to the original mapping software I was using.

答:
New solution for mapbox-gl.js v1.0.0 - Marker objects now have an anchor option to set the position to align to the marker's Lat/Lng: https://docs.mapbox.com/mapbox-gl-js/api/#marker

```<code>var marker = new mapboxgl.Marker(container, {anchor: 'bottom');
</code>```

This should cover most cases and is more reliable than a pixel offset in my experience.

Title: MapBox GL JS marker offset

Body:
I'm using MapBox GL JS to create a map with a custom marker:

var marker = new mapboxgl.Marker(container)
    .setLngLat([
        datacenters[country][city].coordinates.lng,
        datacenters[country][city].coordinates.lat
    ])
    .addTo(map);

However, I seem to have some kind of offset problem with the marker. The thing is: when zoomed out a bit, the bottom of the marker is not really pointing to the exact location:

When I'm zooming in a bit further it reaches its destination and it's pointing to the exact spot.

I really love MapBox GL, but this particular problem is bugging me and I'd love to know how to solve it. When this is fixed my implementation is far more superior to the original mapping software I was using.

Body:
New solution for mapbox-gl.js v1.0.0 - Marker objects now have an anchor option to set the position to align to the marker's Lat/Lng: https://docs.mapbox.com/mapbox-gl-js/api/#marker

var marker = new mapboxgl.Marker(container, {anchor: 'bottom');

This should cover most cases and is more reliable than a pixel offset in my experience.


问:
Regex not to allow to consecutive dot characters and more
I am trying to make a JavaScript Regex which satisfies the following conditions

a-z are possible

0-9 are possible

dash, underscore, apostrophe, period are possible

ampersand, bracket, comma, plus are not possible

consecutive periods are not possible

period cannot be located in the start and the end

max 64 characters

Till now, I have come to following regex

```<code>^[^.][a-zA-Z0-9-_\.']+[^.]$
</code>```

However, this allows consecutive dot characters in the middle and does not check for length.
Could anyone guide me how to add these 2 conditions?

答:
Here comes my idea. Used \w (short for word character).

```<code>^(?!.{65})[\w'-]+(?:\.[\w'-]+)*$
</code>```

^ at start (?!.{65}) look ahead for not more than 64 characters

followed by [\w'-]+ one or more of [a-zA-Z0-9_'-]

followed by (?:\.?[\w'-]+)* any amount of non capturing group containing a period . followed by one or more [a-zA-Z0-9_'-] until $ end

And the demo at regex101 for trying

Body:
I am trying to make a JavaScript Regex which satisfies the following conditions

a-z are possible

0-9 are possible

dash, underscore, apostrophe, period are possible

ampersand, bracket, comma, plus are not possible

consecutive periods are not possible

period cannot be located in the start and the end

max 64 characters

Till now, I have come to following regex

^[^.][a-zA-Z0-9-_\.']+[^.]$

However, this allows consecutive dot characters in the middle and does not check for length.
Could anyone guide me how to add these 2 conditions?

Body:
Here comes my idea. Used \w (short for word character).

^(?!.{65})[\w'-]+(?:\.[\w'-]+)*$

^ at start (?!.{65}) look ahead for not more than 64 characters

followed by [\w'-]+ one or more of [a-zA-Z0-9_'-]

followed by (?:\.?[\w'-]+)* any amount of non capturing group containing a period . followed by one or more [a-zA-Z0-9_'-] until $ end

And the demo at regex101 for trying


问:
read csv with escape characters
I have a csv file with some text, among others. I want to tokenize (split into a list of words) this text and am having problems with how pd.read_csv interprets escape characters.

My csv file looks like this:

```<code>text, number
one line\nother line, 12
</code>```

and the code is like follows:

```<code>df = pd.read_csv('test.csv')
word_tokenize(df.iloc[0,0])
</code>```

output is:

```<code>['one', 'line\\nother', 'line']
</code>```

while what I want is:

```<code>['one', 'line', 'other', 'line']
</code>```

The problem is pd.read_csv() is not interpreting the \n as a newline character but as two characters (\ and n).

I've tried setting the escapechar argument to '\' and to '\\' but both just remove the slash from the string without doing any interpretation of a newline character, i.e. the string becomes on one linenon other line.

If I explicitly set df.iloc[0,0] = 'one line\nother line', word_tokenize works just fine, because \n is actually interpreted as a newline character this time.

Ideally I would do this simply changing the way pd.read_csv() interprets the file, but other solutions are also ok.

答:
The question is a bit poorly worded.  I guess pandas escaping the \ in the string is confusing nltk.word_tokenize.  pandas.read_csv can only use one separator (or a regex, but I doubt you want that), so it will always read the text column as "one line\nother line", and escape the backslash to preserve it.  If you want to further parse and format it, you could use converters.  Here's an example:

```<code>import pandas as pd
import re

df = pd.read_csv(
         "file.csv", converters={"text":lambda s: re.split("\\\\n| ", s)}
)
</code>```

The above results to:

```<code>                       text   number
0  [one, line, other, line]       12
</code>```

Edit: In case you need to use nltk to do the splitting (say the splitting depends on the language model), you would need to unescape the string before passing on to word_tokenize; try something like this:

```<code>lambda s: word_tokenize(s.encode('utf-8').decode('unicode_escape')
</code>```

Note: Matching lists in queries is incredibly tricky, so you might want to convert them to tuples by altering the lambda like this:

```<code>lambda s: tuple(re.split("\\\\n| ", s))
</code>```

Title: read csv with escape characters

Body:
I have a csv file with some text, among others. I want to tokenize (split into a list of words) this text and am having problems with how pd.read_csv interprets escape characters.

My csv file looks like this:

text, number
one line\nother line, 12

and the code is like follows:

df = pd.read_csv('test.csv')
word_tokenize(df.iloc[0,0])

output is:

['one', 'line\\nother', 'line']

while what I want is:

['one', 'line', 'other', 'line']

The problem is pd.read_csv() is not interpreting the \n as a newline character but as two characters (\ and n).

I've tried setting the escapechar argument to '\' and to '\\' but both just remove the slash from the string without doing any interpretation of a newline character, i.e. the string becomes on one linenon other line.

If I explicitly set df.iloc[0,0] = 'one line\nother line', word_tokenize works just fine, because \n is actually interpreted as a newline character this time.

Ideally I would do this simply changing the way pd.read_csv() interprets the file, but other solutions are also ok.

Body:
The question is a bit poorly worded.  I guess pandas escaping the \ in the string is confusing nltk.word_tokenize.  pandas.read_csv can only use one separator (or a regex, but I doubt you want that), so it will always read the text column as "one line\nother line", and escape the backslash to preserve it.  If you want to further parse and format it, you could use converters.  Here's an example:

import pandas as pd
import re

df = pd.read_csv(
         "file.csv", converters={"text":lambda s: re.split("\\\\n| ", s)}
)

The above results to:

                       text   number
0  [one, line, other, line]       12

Edit: In case you need to use nltk to do the splitting (say the splitting depends on the language model), you would need to unescape the string before passing on to word_tokenize; try something like this:

lambda s: word_tokenize(s.encode('utf-8').decode('unicode_escape')

Note: Matching lists in queries is incredibly tricky, so you might want to convert them to tuples by altering the lambda like this:

lambda s: tuple(re.split("\\\\n| ", s))


问:
How to send variable with the guzzle post method
I have an API and I need to send some data to it and I am using guzzle for handling it so here is my code:

```<code>$amount = $request->get('amount');
    $client = new \GuzzleHttp\Client();
    $requestapi = $client->post('http://192.168.150.16:7585/api/v1/Transaction/GetTransactionNumber', [
        'headers' => ['Content-Type' => 'application/json'],
        'body' => '{
        "Amount":"i want to send $amount here",
        "something":"1",
        "Description":"desc",
        }'
    ]);
</code>```

so every thing is fine and static data is being send but I want to know how can I send a variable.

答:
You can bind the data in form_params parameter like

```<code>$client = new \GuzzleHttp\Client();
$amount = $request->get('amount');
$requestapi = $client->post('http://192.168.150.16:7585/api/v1/Transaction/GetTransactionNumber', [
                   'form_params' => [
                        "Amount" => "i want to send $amount here",
                        "something" => "1",
                        "Description" => "desc",
                   ]
             ]);
</code>```

Hope this works for you.

Body:
I have an API and I need to send some data to it and I am using guzzle for handling it so here is my code:

$amount = $request->get('amount');
    $client = new \GuzzleHttp\Client();
    $requestapi = $client->post('http://192.168.150.16:7585/api/v1/Transaction/GetTransactionNumber', [
        'headers' => ['Content-Type' => 'application/json'],
        'body' => '{
        "Amount":"i want to send $amount here",
        "something":"1",
        "Description":"desc",
        }'
    ]);

so every thing is fine and static data is being send but I want to know how can I send a variable.

Body:
You can bind the data in form_params parameter like

$client = new \GuzzleHttp\Client();
$amount = $request->get('amount');
$requestapi = $client->post('http://192.168.150.16:7585/api/v1/Transaction/GetTransactionNumber', [
                   'form_params' => [
                        "Amount" => "i want to send $amount here",
                        "something" => "1",
                        "Description" => "desc",
                   ]
             ]);

Hope this works for you.


问:
difference between 2 different implementations of declaring structures
```<code>gcc 4.4.4
c89
</code>```

I am wondering what is the real difference between the following 2 implementations of defining structures?

```<code>channel.h file

struct channel_tag;

struct channel_tag* init_channel(size_t channel_id);
void dispose_channels(struct channel_tag *channel);

channel.c file

typedef struct channel_tag {
    size_t channel_id;
} channel_t;
</code>```

=================== Second implemenation ===============

```<code>channel.h file

typedef struct channel_tag channel;

channel* init_channel(size_t channel_id);
void dispose_channels(channel *channel);

channel.c file

struct channel_tag {
    size_t channel_id;
};
</code>```

Many thanks for any suggestions,

答: In the first case you have one data type, and the second you have two (where the 2nd is typedef'ed to the first). There is no difference in the generated code. Its for many people just more convenient to read/write code that omits the extra struct keyword.

Body:
gcc 4.4.4
c89

I am wondering what is the real difference between the following 2 implementations of defining structures?

channel.h file

struct channel_tag;

struct channel_tag* init_channel(size_t channel_id);
void dispose_channels(struct channel_tag *channel);

channel.c file

typedef struct channel_tag {
    size_t channel_id;
} channel_t;

=================== Second implemenation ===============

channel.h file

typedef struct channel_tag channel;

channel* init_channel(size_t channel_id);
void dispose_channels(channel *channel);

channel.c file

struct channel_tag {
    size_t channel_id;
};

Many thanks for any suggestions,


问:
Changing Button Color using Listbox
I need to change background color of Button using ListBox. I have 3 ListBoxItems for 3 colors ( green, yellow and red). I am not sure how to do this. Any help will be greatly appreciated.</p>

```<code><StackPanel Grid.Column="1" Grid.Row="3">
  <ToggleButton Height="50" Content="Change!" Name="button">
   </ToggleButton>
    <Popup  IsOpen="{Binding IsChecked, ElementName=button}"   StaysOpen="False">
     <Border Background="LightYellow">
       <ListBox>
        <ListBoxItem>Green</ListBoxItem>
         <ListBoxItem>Yellow</ListBoxItem>
        <ListBoxItem>Red</ListBoxItem>
      </ListBox>
    </Border>
  </Popup>
</StackPanel>
</code>```

答:
Use SelectionChanged event handler  in ListBox control as like below,

```<code>    private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var listBoxItem = ((sender as ListBox).SelectedItem as ListBoxItem);
        button.Background = (SolidColorBrush)new BrushConverter().ConvertFromString(listBoxItem.Content.ToString());
    }
</code>```

Title: Changing Button Color using Listbox

Body:
I need to change background color of Button using ListBox. I have 3 ListBoxItems for 3 colors ( green, yellow and red). I am not sure how to do this. Any help will be greatly appreciated.

<StackPanel Grid.Column="1" Grid.Row="3">
  <ToggleButton Height="50" Content="Change!" Name="button">
   </ToggleButton>
    <Popup  IsOpen="{Binding IsChecked, ElementName=button}"   StaysOpen="False">
     <Border Background="LightYellow">
       <ListBox>
        <ListBoxItem>Green</ListBoxItem>
         <ListBoxItem>Yellow</ListBoxItem>
        <ListBoxItem>Red</ListBoxItem>
      </ListBox>
    </Border>
  </Popup>
</StackPanel>

Body:
Use SelectionChanged event handler  in ListBox control as like below,

    private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var listBoxItem = ((sender as ListBox).SelectedItem as ListBoxItem);
        button.Background = (SolidColorBrush)new BrushConverter().ConvertFromString(listBoxItem.Content.ToString());
    }


问:
How to get columns that are repeating in different tables in a database inside SQL Server
I've a database with huge number of tables. From these tables I want to list out all the column names that are appearing in more than one table along with the their table names.

I tried google search to find any suitable article that can explain how to achieve the results that I've described in the problem section.

No code snippets

No error messages.

答:
This will return the column names and the table names:</p>

```<code>select distinct
TABLE_NAME,
COLUMN_NAME
from INFORMATION_SCHEMA.COLUMNS where COLUMN_NAME in(
    select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS
    group by COLUMN_NAME
    having count(*) > 1
)
order by TABLE_NAME, COLUMN_NAME
</code>```

Body:
This will return the column names and the table names:

select distinct
TABLE_NAME,
COLUMN_NAME
from INFORMATION_SCHEMA.COLUMNS where COLUMN_NAME in(
    select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS
    group by COLUMN_NAME
    having count(*) > 1
)
order by TABLE_NAME, COLUMN_NAME


问:
Using multiple OR LIKE statements
I have a database and I want to filter for some entries. This is how the filter looks like:

```<code>SELECT * FROM Item WHERE 1=1  AND Favorite = 1 AND (  DocType = ?  OR  DocType = ?  OR  DocType = ?  OR  DocType = ? )  AND (Title Like ? OR Location LIKE ? OR DocType LIKE ? OR ProType LIKE ?)
</code>```

The filter almost works. I want to focus on the last part:

```<code>AND (Title Like ? OR Location LIKE ? OR DocType LIKE ? OR ProType LIKE ?)
</code>```

Because it seems like

```<code> OR DocType LIKE ? OR ProType LIKE ?
</code>```

is ignored. When switching Location with DocType for example:

```<code>AND (Title Like ? OR DocType LIKE ? OR Location LIKE ? OR ProType LIKE ?)
</code>```

I can find anything related to DocType. Location can't be found anymore (just as ProType). So I guess I wrote it down wrong.

How would I need to write it down so I can filter for Title, Location, DocType and ProType?

答:
You have two checks against the DocType column, one with = and one with LIKE and since you have added % to your search string the = will most likely return false so nothing will be returned since the two checks are grouped with an AND so your WHERE condition will become (shortened)

```<code>WHERE DocType = '%ABC%' AND DocType LIKE '%ABC'
</code>```

I think you should simply remove the part directly before the AND in your query

```<code>WHERE 1=1 AND Favorite = 1 AND (Title Like ? OR Location LIKE ? OR DocType LIKE ? OR ProType LIKE ?)
</code>```

Title: Using multiple OR LIKE statements

Body:
I have a database and I want to filter for some entries. This is how the filter looks like:

SELECT * FROM Item WHERE 1=1  AND Favorite = 1 AND (  DocType = ?  OR  DocType = ?  OR  DocType = ?  OR  DocType = ? )  AND (Title Like ? OR Location LIKE ? OR DocType LIKE ? OR ProType LIKE ?)

The filter almost works. I want to focus on the last part:

AND (Title Like ? OR Location LIKE ? OR DocType LIKE ? OR ProType LIKE ?)

Because it seems like

 OR DocType LIKE ? OR ProType LIKE ?

is ignored. When switching Location with DocType for example:

AND (Title Like ? OR DocType LIKE ? OR Location LIKE ? OR ProType LIKE ?)

I can find anything related to DocType. Location can't be found anymore (just as ProType). So I guess I wrote it down wrong.

How would I need to write it down so I can filter for Title, Location, DocType and ProType?

Body:
You have two checks against the DocType column, one with = and one with LIKE and since you have added % to your search string the = will most likely return false so nothing will be returned since the two checks are grouped with an AND so your WHERE condition will become (shortened)

WHERE DocType = '%ABC%' AND DocType LIKE '%ABC'

I think you should simply remove the part directly before the AND in your query

WHERE 1=1 AND Favorite = 1 AND (Title Like ? OR Location LIKE ? OR DocType LIKE ? OR ProType LIKE ?)


问:
looping a training model over model classes and changing dataframe name by model class
I am trying to automate a training pipeline and having some troubles to rename the input dataframes over changing model classes.

```<code>sample_train = [9]
sample_test = [18]
model_class = [0]

for i in sample_train:
    for j in model_class:
        # Define the training datasets -Filter the datasets with model selections
        trainX_M[j] = mldata_pd[(mldata_pd.sample_id == i) & (mldata_pd.training_set_band == j)].drop(
            ['conv_gv_band', 'sample_id', 'training_set_band'], axis=1)
        trainy_M[j] = mldata_pd[(mldata_pd.sample_id == i) & (
            mldata_pd.training_set_band == j)].iloc[:, mldata_pd.columns == 'conv_gv_band']

    trainX_M0, testX, trainy_M0, testy = train_test_split(trainX_M0, trainy_M0,
                                                          test_size=0.2,
                                                          random_state=42)
</code>```

I expect to have trainX_M0 when model_class=0 but receive the error:

NameError: name 'trainX_M' is not defined

答:
You try to set the value at position j in trainX_M[j] =, same with trainY_M[j] =, and from the error you can read that the array trainX_M is not defined before. In your posted code snipped I also can not see a definition. Are you sure there is one and it is spelled the same way?

If there is none, you could initialize the array trainX_M like that (I guess equal size as model_class):

```<code>trainX_M = [None] * len(model_class)
</code>```

Body:
I am trying to automate a training pipeline and having some troubles to rename the input dataframes over changing model classes.

sample_train = [9]
sample_test = [18]
model_class = [0]

for i in sample_train:
    for j in model_class:
        # Define the training datasets -Filter the datasets with model selections
        trainX_M[j] = mldata_pd[(mldata_pd.sample_id == i) & (mldata_pd.training_set_band == j)].drop(
            ['conv_gv_band', 'sample_id', 'training_set_band'], axis=1)
        trainy_M[j] = mldata_pd[(mldata_pd.sample_id == i) & (
            mldata_pd.training_set_band == j)].iloc[:, mldata_pd.columns == 'conv_gv_band']

    trainX_M0, testX, trainy_M0, testy = train_test_split(trainX_M0, trainy_M0,
                                                          test_size=0.2,
                                                          random_state=42)

I expect to have trainX_M0 when model_class=0 but receive the error:

NameError: name 'trainX_M' is not defined

Body:
You try to set the value at position j in trainX_M[j] =, same with trainY_M[j] =, and from the error you can read that the array trainX_M is not defined before. In your posted code snipped I also can not see a definition. Are you sure there is one and it is spelled the same way?

If there is none, you could initialize the array trainX_M like that (I guess equal size as model_class):

trainX_M = [None] * len(model_class)


问:
How to use the WebP image format in DotNetNuke?
I am trying to add the following code to my DotNetNuke website to improve site performance, but it seems like .WebP format images do not render for some reason, It will show the broken Image icon. I doubled checked the image paths and everything is correct. I had to download a plugin for Photoshop CC so that I can export images to .WebP.

Is there a web.config setting I have to configure?

```<code><picture>
<source srcset="img/awesomeWebPImage.webp" type="image/webp">
<source srcset="img/creakyOldJPEG.jpg" type="image/jpeg">
<img src="img/creakyOldJPEG.jpg" alt="Alt Text!">
</picture>
</code>```

答:
This is more a problem of your IIS configuration than related to DNN. You have to add a corresponding MIME type, either in IIS manager or manually in the web.config like</p>

```<code><system.webServer>
   <staticContent>
      ...
      <mimeMap fileExtension=".webp" mimeType="image/webp" />
      ...
</code>```

Body:
I am trying to add the following code to my DotNetNuke website to improve site performance, but it seems like .WebP format images do not render for some reason, It will show the broken Image icon. I doubled checked the image paths and everything is correct. I had to download a plugin for Photoshop CC so that I can export images to .WebP.

Is there a web.config setting I have to configure?

<picture>
<source srcset="img/awesomeWebPImage.webp" type="image/webp">
<source srcset="img/creakyOldJPEG.jpg" type="image/jpeg">

</picture>

Body:
This is more a problem of your IIS configuration than related to DNN. You have to add a corresponding MIME type, either in IIS manager or manually in the web.config like

<system.webServer>
   <staticContent>
      ...
      <mimeMap fileExtension=".webp" mimeType="image/webp" />
      ...


问:
Which approach is better - comment attribute in each table vs one comment table
Currently, I have a bunch of tables in my system which need to store one comment per row (not by content type or anything else - just simple one comment per row and no history tracking). Is there any advantage to creating a comment table and having a FK to it from all other tables which need comments as opposed to just directly creating a comment column in each of those tables?

Is there any advantage on the physical DB side - in terms of database performance for these 2 approaches?

答: Having a separate table, and rely on joins, can be a performance issue. Unless the same comment goes to multiple tables, there is no reason to have this separate.</p>


问:
Copy PCL Point Cloud while preserving organization or Ransac + Surface Normal Calculation
I have a point cloud

```<code>pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGBA>);
</code>```

that I want to copy into

```<code>pcl::PointCloud<pcl::PointXYZRGBA>::Ptr finalcloud (new pcl::PointCloud<pcl::PointXYZRGBA>);
</code>```

while filtering based on some inliers calculated using ransac.

```<code>std::vector<int> inliers;
</code>```

I am currently doing this as

```<code>pcl::copyPointCloud<pcl::PointXYZRGBA>(*cloud, inliers, *finalcloud);
</code>```

Problem:

Since I want to find the normals for this cloud, I need the organization to be maintained. The copyPointCloud function makes the new point cloud height = 1 (see line 188 of PCL io.hpp ).

Has anyone been able to find normals after performing ransac on a pcl?

答:
I think this answer is too late and API might changes from 2015.. but I'll answer it.

The normal estimation will work with both organized cloud and unorganized cloud.

Unorganized Cloud

I'm copying the code from http://pointclouds.org/documentation/tutorials/normal_estimation.php
In this code, the KdTree will be used to estimate the neighbours.

#include <pcl/point_types.h>
#include <pcl/features/normal_3d.h>

{
  pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>);

  ... read, pass in or create a point cloud ...

  // Create the normal estimation class, and pass the input dataset to it
  pcl::NormalEstimation<pcl::PointXYZ, pcl::Normal> ne;
  ne.setInputCloud (cloud);

  // Create an empty kdtree representation, and pass it to the normal estimation object.
  // Its content will be filled inside the object, based on the given input dataset (as no other search surface is given).
  pcl::search::KdTree<pcl::PointXYZ>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZ> ());
  ne.setSearchMethod (tree);

  // Output datasets
  pcl::PointCloud<pcl::Normal>::Ptr cloud_normals (new pcl::PointCloud<pcl::Normal>);

  // Use all neighbors in a sphere of radius 3cm
  ne.setRadiusSearch (0.03);

  // Compute the features
  ne.compute (*cloud_normals);

  // cloud_normals->points.size () should have the same size as the input cloud->points.size ()*
}
```

<h2>Organized Cloud</h2>

<p>I am copying the code from http://www.pointclouds.org/documentation/tutorials/normal_estimation_using_integral_images.php#normal-estimation-using-integral-images</p>

<pre class="lang-cpp prettyprint-override"><code>// load point cloud
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>);
pcl::io::loadPCDFile ("table_scene_mug_stereo_textured.pcd", *cloud);

// estimate normals
pcl::PointCloud<pcl::Normal>::Ptr normals (new pcl::PointCloud<pcl::Normal>);

pcl::IntegralImageNormalEstimation<pcl::PointXYZ, pcl::Normal> ne;
ne.setNormalEstimationMethod (ne.AVERAGE_3D_GRADIENT);
ne.setMaxDepthChangeFactor(0.02f);
ne.setNormalSmoothingSize(10.0f);
ne.setInputCloud(cloud);
ne.compute(*normals);
</code>```

Body:
I have a point cloud

pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGBA>);

that I want to copy into

pcl::PointCloud<pcl::PointXYZRGBA>::Ptr finalcloud (new pcl::PointCloud<pcl::PointXYZRGBA>);

while filtering based on some inliers calculated using ransac.

std::vector<int> inliers;

I am currently doing this as

pcl::copyPointCloud<pcl::PointXYZRGBA>(*cloud, inliers, *finalcloud);

Problem:

Since I want to find the normals for this cloud, I need the organization to be maintained. The copyPointCloud function makes the new point cloud height = 1 (see line 188 of PCL io.hpp ).

Has anyone been able to find normals after performing ransac on a pcl?

Body:
I think this answer is too late and API might changes from 2015.. but I'll answer it.

The normal estimation will work with both organized cloud and unorganized cloud.

Unorganized Cloud

I'm copying the code from http://pointclouds.org/documentation/tutorials/normal_estimation.php
In this code, the KdTree will be used to estimate the neighbours.

#include <pcl/point_types.h>
#include <pcl/features/normal_3d.h>

{
  pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>);

  ... read, pass in or create a point cloud ...

  // Create the normal estimation class, and pass the input dataset to it
  pcl::NormalEstimation<pcl::PointXYZ, pcl::Normal> ne;
  ne.setInputCloud (cloud);

  // Create an empty kdtree representation, and pass it to the normal estimation object.
  // Its content will be filled inside the object, based on the given input dataset (as no other search surface is given).
  pcl::search::KdTree<pcl::PointXYZ>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZ> ());
  ne.setSearchMethod (tree);

  // Output datasets
  pcl::PointCloud<pcl::Normal>::Ptr cloud_normals (new pcl::PointCloud<pcl::Normal>);

  // Use all neighbors in a sphere of radius 3cm
  ne.setRadiusSearch (0.03);

  // Compute the features
  ne.compute (*cloud_normals);

  // cloud_normals->points.size () should have the same size as the input cloud->points.size ()*
}

Organized Cloud

I am copying the code from http://www.pointclouds.org/documentation/tutorials/normal_estimation_using_integral_images.php#normal-estimation-using-integral-images

// load point cloud
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>);
pcl::io::loadPCDFile ("table_scene_mug_stereo_textured.pcd", *cloud);

// estimate normals
pcl::PointCloud<pcl::Normal>::Ptr normals (new pcl::PointCloud<pcl::Normal>);

pcl::IntegralImageNormalEstimation<pcl::PointXYZ, pcl::Normal> ne;
ne.setNormalEstimationMethod (ne.AVERAGE_3D_GRADIENT);
ne.setMaxDepthChangeFactor(0.02f);
ne.setNormalSmoothingSize(10.0f);
ne.setInputCloud(cloud);
ne.compute(*normals);


问:
How to have a final jar with the dependency inside that jar in the jar format?
I need a configuration for Maven where all the libraries inside the project are in the final jar in the jar format... So i need to have jars inside the final jar. For that i can only use maven. I already tried without success with plugins like one-jar.
Thanks</p>

答:
Not sure for nested jar because I haven't tried yet.

But I have created .jar file with all project dependencies(specified in pom file)

Try following mvn command in terminal...

mvn org.apache.maven.plugins:maven-assembly-plugin:2.6:assembly -DdescriptorId=jar-with-dependencies package


问:
my second double-click function not working
When clicking on a specific div, I want another div to create a new p style with text in it. </p>

<p>The first function created worked fine- whoever the second one seems to overrule the first one. I've tried changing the names of basically everything but it still seems to overrule. How could I solve this? </p>

```<code>  var para = document.createElement("P");
  para.innerHTML = "The Siamese crocodiles share one stomach, yet they fight over food.";
  document.getElementById("information").appendChild(para);
}
    window.onload = function() {
        document.getElementById("i29").ondblclick = function i29i() {
            i29();
        }
    }

function i3() {
  var para = document.createElement("P");
  para.innerHTML = "When you climb a good tree, you are given a push.";
  document.getElementById("information").appendChild(para);
}

    window.onload = function() {
        document.getElementById("i3").ondblclick = function i3i() {
            i3();
        }
    }```
</code>```

答:
You coud do it like this:

HTML:

```<code><div onClick="firstClick()">First</div>
<div onClick="secondClick()">Second</div>

<div id="information"></div>
</code>```

JS:

```<code>    function firstClick(){
        var para1 = document.createElement("P");
        para1.innerHTML = "The Siamese crocodiles share one stomach, yet they fight over food.";
        document.getElementById("information").appendChild(para1);
        }
    function secondClick(){
        var para2 = document.createElement("P");
        para2.innerHTML = "When you climb a good tree, you are given a push.";
        document.getElementById("information").appendChild(para2);
    }
</code>```

Body:
When clicking on a specific div, I want another div to create a new p style with text in it.

The first function created worked fine- whoever the second one seems to overrule the first one. I've tried changing the names of basically everything but it still seems to overrule. How could I solve this?

  var para = document.createElement("P");
  para.innerHTML = "The Siamese crocodiles share one stomach, yet they fight over food.";
  document.getElementById("information").appendChild(para);
}
    window.onload = function() {
        document.getElementById("i29").ondblclick = function i29i() {
            i29();
        }
    }

function i3() {
  var para = document.createElement("P");
  para.innerHTML = "When you climb a good tree, you are given a push.";
  document.getElementById("information").appendChild(para);
}

    window.onload = function() {
        document.getElementById("i3").ondblclick = function i3i() {
            i3();
        }
    }```

Body:
You coud do it like this:

HTML:

<div onClick="firstClick()">First</div>
<div onClick="secondClick()">Second</div>

<div id="information"></div>

JS:

    function firstClick(){
        var para1 = document.createElement("P");
        para1.innerHTML = "The Siamese crocodiles share one stomach, yet they fight over food.";
        document.getElementById("information").appendChild(para1);
        }
    function secondClick(){
        var para2 = document.createElement("P");
        para2.innerHTML = "When you climb a good tree, you are given a push.";
        document.getElementById("information").appendChild(para2);
    }


问:
Import Table (IT) vs Import Address Table (IAT)
I've been trying to parse/display the information in the Import Address Table (IAT) of a process after it is loaded and running. I understand API calls in programs jump to the relevant point in the IAT, which then jumps to the actual function in the loaded DLL's.

Is it correct that the IAT can be found by reading the PE header and following the OptionalHeader.DataDirectory[1] pointer, to the array of IMAGE_IMPORT_DESCRIPTORs. Then following the FirstThunk pointers. Whereas the  OriginalFirstThunk pointers here, will give you the original Import Table (IT)?

I have also tried following the OptionalHeader.DataDirectory[12] pointer in the PE header, but this was even less successful.

I've been testing this by trying to parse this structure for notepad.exe (32bit), using ReadProcessMemory from another process.

Here's the rough C-psuedocode for what I'm doing:

```<code>char buf[128];

// get first import descriptor
readMemory(&import, procImgBase + DataDirectory[1].VirtualAddress, sizeof(IMAGE_IMPORT_DESCRIPTOR));

// get dll name
readMemory(buf, import.Name + procImgBase, 127);
printf("libname: %s\n", buf);

// get first function name
DWORD iltAddress = 0;
readMemory(&iltAddress, import.FirstThunk + procImgBase, 4);
readMemory(buf, iltAddress + procImgBase, 127);
printf("fname: %s\n", libName + 2); // <-- the +2 for the 2byte 'hint' of import lookup table entries
</code>```

If, on the 3rd to last line, i replace it with import.OriginalFirstThunk instead of FirstThunk, it will print everything as expected. I must be missing something conceptually, and so I was wondering if anyone could clarify what this is, for me?

Many thanks!

答:
It looks like you're heading the right direction. Some notes:

The DataDirectory gives you an offset
to an array of
IMAGE_IMPORT_DESCRIPTOR which is
terminated by an entry of all zeros.
There will be one
IMAGE_IMPORT_DESCRIPTOR for each DLL
that is imported

The
IMAGE_IMPORT_DESCRIPTOR has offsets
to 2 arrays of IMAGE_THUNK_DATA, one
that maintains offsets to the names
of the imported functions
(OriginalFirstThunk) and another that
now has the actual addresses of the
functions (FirstThunk)

Since your executable is running, the IAT should contain the actual address of the function rather than an RVA to a name entry.

You could do something like this instead:

```<code>DWORD rva_to_name_of_function = 0;
DWORD address_of_function = 0;

// get the RVA of the IMAGE_IMPORT_BY_NAME entry
readMemory(&rva_to_name, import.OriginalFirstThunk + procImgBase, 4);

// copy the name of the import
readMemory(buf, rva_to_name + procImgBase + 2, 127);

// get the actual address that was filled in by the loader
readMemory(&address_of_function, import.FirstThunk + procImgBase, 4);

printf("fname: %s address: %X", buf, address_of_function);
</code>```

Take a look at this article for some helpful details:
http://msdn.microsoft.com/en-us/magazine/cc301808.aspx

Body:
I've been trying to parse/display the information in the Import Address Table (IAT) of a process after it is loaded and running. I understand API calls in programs jump to the relevant point in the IAT, which then jumps to the actual function in the loaded DLL's.

Is it correct that the IAT can be found by reading the PE header and following the OptionalHeader.DataDirectory[1] pointer, to the array of IMAGE_IMPORT_DESCRIPTORs. Then following the FirstThunk pointers. Whereas the  OriginalFirstThunk pointers here, will give you the original Import Table (IT)?

I have also tried following the OptionalHeader.DataDirectory[12] pointer in the PE header, but this was even less successful.

I've been testing this by trying to parse this structure for notepad.exe (32bit), using ReadProcessMemory from another process.

Here's the rough C-psuedocode for what I'm doing:

char buf[128];

// get first import descriptor
readMemory(&import, procImgBase + DataDirectory[1].VirtualAddress, sizeof(IMAGE_IMPORT_DESCRIPTOR));

// get dll name
readMemory(buf, import.Name + procImgBase, 127);
printf("libname: %s\n", buf);

// get first function name
DWORD iltAddress = 0;
readMemory(&iltAddress, import.FirstThunk + procImgBase, 4);
readMemory(buf, iltAddress + procImgBase, 127);
printf("fname: %s\n", libName + 2); // <-- the +2 for the 2byte 'hint' of import lookup table entries

If, on the 3rd to last line, i replace it with import.OriginalFirstThunk instead of FirstThunk, it will print everything as expected. I must be missing something conceptually, and so I was wondering if anyone could clarify what this is, for me?

Many thanks!

Body:
It looks like you're heading the right direction. Some notes:

The DataDirectory gives you an offset
to an array of
IMAGE_IMPORT_DESCRIPTOR which is
terminated by an entry of all zeros.
There will be one
IMAGE_IMPORT_DESCRIPTOR for each DLL
that is imported

The
IMAGE_IMPORT_DESCRIPTOR has offsets
to 2 arrays of IMAGE_THUNK_DATA, one
that maintains offsets to the names
of the imported functions
(OriginalFirstThunk) and another that
now has the actual addresses of the
functions (FirstThunk)

Since your executable is running, the IAT should contain the actual address of the function rather than an RVA to a name entry.

You could do something like this instead:

DWORD rva_to_name_of_function = 0;
DWORD address_of_function = 0;

// get the RVA of the IMAGE_IMPORT_BY_NAME entry
readMemory(&rva_to_name, import.OriginalFirstThunk + procImgBase, 4);

// copy the name of the import
readMemory(buf, rva_to_name + procImgBase + 2, 127);

// get the actual address that was filled in by the loader
readMemory(&address_of_function, import.FirstThunk + procImgBase, 4);

printf("fname: %s address: %X", buf, address_of_function);

Take a look at this article for some helpful details:
http://msdn.microsoft.com/en-us/magazine/cc301808.aspx