问:
Correct way to check text of button?
Correct way to check text of button

I  need to check that English text on button is "Start this".

In string.xml

```<code><string name="start">Start this</string>
</code>```

So here Espresso test:

Approach#1

```<code>private val buttonStart = viewWithId(startButton)

    @Test
    fun buttonStartText() {
        onView(withId(startButton))
                .check(matches(withText(R.string.start)))
}
</code>```

The test "buttonStartText"  success pass. Nice.

Approach#2

Check hard code text.

```<code> @Test
    fun buttonStartText() {
        onView(withId(startButton))
                .check(matches(withText("Start this")))
}
</code>```

The test "buttonStartText"  success pass. Nice.

The question is:
What approach is correct?

What I mean.
Suppose the developer made error and in string.xml change value of key "start" to "Start this 2222".
E.g.

```<code><string name="start">Start this 2222</string>
</code>```

As result the test in approach#1 is still pass. This is NOT CORRECT behavior.

But test in approach#2 is broken. This is a correct behavior.

As result I think test in approach#2 is correct way to check title/text on button.

Is I'm right?

P.S.

But if I has multi language app (e.g. 3 languages). In approach#1 nothing cha nge. But in in approach#2 I need to add two additional tests that check text in specific languages.

答:
To be honest both approach are correct.

Because approach #1 checking if there is a button with text from R.strings..

but approach #2 checking if there is exactly that text.

So You are checking two different things. Depends what You want to test.

Title: Correct way to check text of button?

Body:
Correct way to check text of button

I  need to check that English text on button is "Start this".

In string.xml

<string name="start">Start this</string>

So here Espresso test:

Approach#1

private val buttonStart = viewWithId(startButton)

    @Test
    fun buttonStartText() {
        onView(withId(startButton))
                .check(matches(withText(R.string.start)))
}

The test "buttonStartText"  success pass. Nice.

Approach#2

Check hard code text.

 @Test
    fun buttonStartText() {
        onView(withId(startButton))
                .check(matches(withText("Start this")))
}

The test "buttonStartText"  success pass. Nice.

The question is:
What approach is correct?

What I mean.
Suppose the developer made error and in string.xml change value of key "start" to "Start this 2222".
E.g.

<string name="start">Start this 2222</string>

As result the test in approach#1 is still pass. This is NOT CORRECT behavior.

But test in approach#2 is broken. This is a correct behavior.

As result I think test in approach#2 is correct way to check title/text on button.

Is I'm right?

P.S.

But if I has multi language app (e.g. 3 languages). In approach#1 nothing cha nge. But in in approach#2 I need to add two additional tests that check text in specific languages.


来源: stackexchange

问:
Reset progress bar after form submit using jQuery
I have a progress bar on a form which works fine but I need to reset its value after the file as been upload.

My code:

```<code><div class="bar-position">
  <div class="col-md-14 col-md-14 progress-container">
    <div class="progress progress-striped active">
      <div class="progress-bar progress-bar-success" style="width:0%"></div>
    </div>
  </div>
</div>
</code>```

I have tried using this after the file upload but it does not work:

```<code>$('.progress').val(0);
</code>```

Where am I going wrong? I have looked at a number of posts but I can't find a solution that will work with my code.

答:
Please check this by jQuery:</p>

```<code>$('.progress.active').val(progress); //ENTER PROGRESS BAR VARIABLE HERE
  if ($('.progress.active').val() >= 100) { //IF 100% PROGRESS
    $('.progress.active').val(0); //VALUE WILL BE RESET
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a progress bar on a form which works fine but I need to reset its value after the file as been upload.

My code:

I have tried using this after the file upload but it does not work:

$('.progress').val(0);

Where am I going wrong? I have looked at a number of posts but I can't find a solution that will work with my code.

Body:
Please check this by jQuery:

$('.progress.active').val(progress); //ENTER PROGRESS BAR VARIABLE HERE
  if ($('.progress.active').val() >= 100) { //IF 100% PROGRESS
    $('.progress.active').val(0); //VALUE WILL BE RESET
}


问:
Select 12 different columns for each record based on conditional on a column in R

So, I have the above dataset, where each row represents an advisor. The Pol_Month represents the month of first transaction.
From the month of 1st transaction, I need to track his transactions for a period of 12 months.
Ex - for Adv 'S301' , his first transaction is on the month January, hence from January_APE to FY1819_December_APE, his transactions are to be captured under Month1, Month2…. Month12
Where the first transaction month is before April, the count of 12 months starts from April.
So, basically , for each record, I need to start traversing the columns, from Pol_Month and capture the values upto the 12th month. In case Pol_Month is March, traversal starts from April.

Expected Output:

```<code>Adv_Code    Pol_Month   Month1_APE  Month2_APE  Month3_APE  Month4_APE  Month5_APE  Month6_APE  Month7_APE  Month8_APE  Month9_APE  Month10_APE Month11_APE Month12_APE
A299        March       0           0           0           0           0           0           0           0           0           0           0           0
A298        NA          0           0           0           0           0           0           0           0           0           0           0           0
S300        NA          0           0           0           0           0           0           0           0           0           0           0           0
S301        January     19101       0           0           0           0           0           19000       0           0           0           0           0
A299        March       0           0           0           0           0           0           0           0           0           0           0           0
A298        March       0           0           0           0           0           0           0           0           0           0           0           0
S300        March       0           0           0           0           0           0           0           0           0           0           0           0
S301        March       0           0           0           0           0           0           0           0           0           0           0           0
S300        March       0           0           0           0           0           0           0           0           0           0           0           0
S301        April       15413       29798       70010       20342       24521       20550       0           0           25920       0           0           0
</code>```

Can someone please help me with this?

below is the code to reproduce the df:

```<code>df <- structure(list(Adv_Code = structure(c(2L, 1L, 3L,4L,2L,1L,3L,4L,3L,4L), .Label = c("A298","A299", "S300","S301","S302","S303","S304","S305","S309"), class = "factor"),
                     #Pol_Dt = structure(c(2L,3L, 2L,2L,2L,3L,2L,3L,2L,3L), .Label = c("03/31/2017", NA, NA,"1/30/2018","3/31/2017","3/31/2017","3/31/2017","3/31/2017","3/31/2017","4/25/2017"), class = "factor"),
                     Pol_Month = structure(1:10, .Label = c("March",NA,NA,"January","March","March","March","March","March","April"), class = "factor"),
                     April_APE = c(0L, 0L, 0L,0L,0L,0L,0L,0L,0L,15413L),
                     May_APE = c(0L, 0L, 0L,0L,0L,0L,0L,0L,0L,29798L), June_APE = c(0L, 0L, 0L,0L,0L,0L,0L,0L,0L,70010L), July_APE = c(0L, 0L, 0L,0L,0L,0L,0L,0L,0L,20342L),
                     August_APE = c(0L, 0L, 0L,0L,0L,0L,0L,0L,0L,24521L), September_APE = c(0L, 0L, 0L,0L,0L,0L,0L,0L,0L,20550L), October_APE = c(0L, 0L, 0L,0L,0L,0L,0L,0L,0L,0L),
                     November_APE = c(0L, 0L, 0L,0L,0L,0L,0L,0L,0L,0L),December_APE = c(0L, 0L, 0L,0L,0L,0L,0L,0L,0L,25920L), January_APE = c(0L, 0L, 0L,19101L,0L,0L,0L,0L,0L,0L),
                     February_APE = c(0L, 0L, 0L,0L,0L,0L,0L,0L,0L,0L), March_APE = c(0L, 0L, 0L,0L,0L,0L,0L,0L,0L,0L),
                     FY1819_April_APE = c(NA,NA,NA,0L,NA,NA,NA,NA,NA,16440L),FY1819_May_APE = c(NA,NA,NA,0L,NA,NA,NA,NA,NA,16440L),
                     FY1819_June_APE = c(NA,NA,NA,0L,NA,NA,NA,NA,NA,0L),FY1819_July_APE = c(NA,NA,NA,19000L,NA,NA,NA,NA,NA,0L),
                     FY1819_August_APE = c(NA,NA,NA,0L,NA,NA,NA,NA,NA,15413L),FY1819_September_APE = c(NA,NA,NA,0L,NA,NA,NA,NA,NA,0L),
                     FY1819_October_APE = c(NA,NA,NA,0L,NA,NA,NA,NA,NA,0L),FY1819_November_APE = c(NA,NA,NA,0L,NA,NA,NA,NA,NA,0L),FY1819_December_APE = c(NA,NA,NA,0L,NA,NA,NA,NA,NA,0L),
                     FY1819_January_APE = c(NA,NA,NA,0L,NA,NA,NA,NA,NA,0L),FY1819_February_APE = c(NA,NA,NA,0L,NA,NA,NA,NA,NA,15413L),FY1819_March_APE = c(NA,NA,NA,0L,NA,NA,NA,NA,NA,0L)),
                class = "data.frame", row.names = c(NA, -10L))
</code>```

Can someone kindly help!

答:
Here is one option using apply. For every rows we return fixed first 12 values if Pol_Month column is NA, if it is not we change month_name to "April" if it is present in first 3 months else keep it as it is and select 12 values where the column with month_name value is present.

```<code>outdf <- df[1:2]

outdf[paste0("Month", 1:12, "_APE")] <- t(apply(df, 1, function(x) {
       if (is.na(x[["Pol_Month"]]))
             x[3:14]
       else {
          month_name <- if (match(x[["Pol_Month"]], month.name) < 4) "April" else x[["Pol_Month"]]
          ind <- which.max(grepl(month_name, names(df)))
          x[ind : (ind + 11)]
         }
}))

outdf[1:7]

#   Adv_Code Pol_Month Month1_APE Month2_APE Month3_APE Month4_APE Month5_APE
#1      A299     March          0          0          0          0          0
#2      A298      <NA>          0          0          0          0          0
#3      S300      <NA>          0          0          0          0          0
#4      S301   January          0          0          0          0          0
#5      A299     March          0          0          0          0          0
#6      A298     March          0          0          0          0          0
#7      S300     March          0          0          0          0          0
#8      S301     March          0          0          0          0          0
#9      S300     March          0          0          0          0          0
#10     S301     April      15413      29798      70010      20342      24521
</code>```

Here is a dplyr/tidyr version using the same logic

```<code>library(dplyr)
library(tidyr)

df %>%
   mutate(row = row_number()) %>%
   gather(key, value, -c(1:2, row)) %>%
   group_by(row) %>%
   slice(if(is.na(first(Pol_Month))) 1:12 else {ind = max(match(first(Pol_Month), month.name), 4); ind : (ind + 11) }) %>%
   mutate(key = paste0("Month", 1:12, "_APE")) %>%
   spread(key, value) %>%
   select(-row)
</code>```

Body:
So, I have the above dataset, where each row represents an advisor. The Pol_Month represents the month of first transaction.
From the month of 1st transaction, I need to track his transactions for a period of 12 months.
Ex - for Adv 'S301' , his first transaction is on the month January, hence from January_APE to FY1819_December_APE, his transactions are to be captured under Month1, Month2…. Month12
Where the first transaction month is before April, the count of 12 months starts from April.
So, basically , for each record, I need to start traversing the columns, from Pol_Month and capture the values upto the 12th month. In case Pol_Month is March, traversal starts from April.

Expected Output:

Adv_Code    Pol_Month   Month1_APE  Month2_APE  Month3_APE  Month4_APE  Month5_APE  Month6_APE  Month7_APE  Month8_APE  Month9_APE  Month10_APE Month11_APE Month12_APE
A299        March       0           0           0           0           0           0           0           0           0           0           0           0
A298        NA          0           0           0           0           0           0           0           0           0           0           0           0
S300        NA          0           0           0           0           0           0           0           0           0           0           0           0
S301        January     19101       0           0           0           0           0           19000       0           0           0           0           0
A299        March       0           0           0           0           0           0           0           0           0           0           0           0
A298        March       0           0           0           0           0           0           0           0           0           0           0           0
S300        March       0           0           0           0           0           0           0           0           0           0           0           0
S301        March       0           0           0           0           0           0           0           0           0           0           0           0
S300        March       0           0           0           0           0           0           0           0           0           0           0           0
S301        April       15413       29798       70010       20342       24521       20550       0           0           25920       0           0           0

Can someone please help me with this?

below is the code to reproduce the df:

df <- structure(list(Adv_Code = structure(c(2L, 1L, 3L,4L,2L,1L,3L,4L,3L,4L), .Label = c("A298","A299", "S300","S301","S302","S303","S304","S305","S309"), class = "factor"),
                     #Pol_Dt = structure(c(2L,3L, 2L,2L,2L,3L,2L,3L,2L,3L), .Label = c("03/31/2017", NA, NA,"1/30/2018","3/31/2017","3/31/2017","3/31/2017","3/31/2017","3/31/2017","4/25/2017"), class = "factor"),
                     Pol_Month = structure(1:10, .Label = c("March",NA,NA,"January","March","March","March","March","March","April"), class = "factor"),
                     April_APE = c(0L, 0L, 0L,0L,0L,0L,0L,0L,0L,15413L),
                     May_APE = c(0L, 0L, 0L,0L,0L,0L,0L,0L,0L,29798L), June_APE = c(0L, 0L, 0L,0L,0L,0L,0L,0L,0L,70010L), July_APE = c(0L, 0L, 0L,0L,0L,0L,0L,0L,0L,20342L),
                     August_APE = c(0L, 0L, 0L,0L,0L,0L,0L,0L,0L,24521L), September_APE = c(0L, 0L, 0L,0L,0L,0L,0L,0L,0L,20550L), October_APE = c(0L, 0L, 0L,0L,0L,0L,0L,0L,0L,0L),
                     November_APE = c(0L, 0L, 0L,0L,0L,0L,0L,0L,0L,0L),December_APE = c(0L, 0L, 0L,0L,0L,0L,0L,0L,0L,25920L), January_APE = c(0L, 0L, 0L,19101L,0L,0L,0L,0L,0L,0L),
                     February_APE = c(0L, 0L, 0L,0L,0L,0L,0L,0L,0L,0L), March_APE = c(0L, 0L, 0L,0L,0L,0L,0L,0L,0L,0L),
                     FY1819_April_APE = c(NA,NA,NA,0L,NA,NA,NA,NA,NA,16440L),FY1819_May_APE = c(NA,NA,NA,0L,NA,NA,NA,NA,NA,16440L),
                     FY1819_June_APE = c(NA,NA,NA,0L,NA,NA,NA,NA,NA,0L),FY1819_July_APE = c(NA,NA,NA,19000L,NA,NA,NA,NA,NA,0L),
                     FY1819_August_APE = c(NA,NA,NA,0L,NA,NA,NA,NA,NA,15413L),FY1819_September_APE = c(NA,NA,NA,0L,NA,NA,NA,NA,NA,0L),
                     FY1819_October_APE = c(NA,NA,NA,0L,NA,NA,NA,NA,NA,0L),FY1819_November_APE = c(NA,NA,NA,0L,NA,NA,NA,NA,NA,0L),FY1819_December_APE = c(NA,NA,NA,0L,NA,NA,NA,NA,NA,0L),
                     FY1819_January_APE = c(NA,NA,NA,0L,NA,NA,NA,NA,NA,0L),FY1819_February_APE = c(NA,NA,NA,0L,NA,NA,NA,NA,NA,15413L),FY1819_March_APE = c(NA,NA,NA,0L,NA,NA,NA,NA,NA,0L)),
                class = "data.frame", row.names = c(NA, -10L))

Can someone kindly help!

Body:
Here is one option using apply. For every rows we return fixed first 12 values if Pol_Month column is NA, if it is not we change month_name to "April" if it is present in first 3 months else keep it as it is and select 12 values where the column with month_name value is present.

outdf <- df[1:2]

outdf[paste0("Month", 1:12, "_APE")] <- t(apply(df, 1, function(x) {
       if (is.na(x[["Pol_Month"]]))
             x[3:14]
       else {
          month_name <- if (match(x[["Pol_Month"]], month.name) < 4) "April" else x[["Pol_Month"]]
          ind <- which.max(grepl(month_name, names(df)))
          x[ind : (ind + 11)]
         }
}))

outdf[1:7]

#   Adv_Code Pol_Month Month1_APE Month2_APE Month3_APE Month4_APE Month5_APE
#1      A299     March          0          0          0          0          0
#2      A298      <NA>          0          0          0          0          0
#3      S300      <NA>          0          0          0          0          0
#4      S301   January          0          0          0          0          0
#5      A299     March          0          0          0          0          0
#6      A298     March          0          0          0          0          0
#7      S300     March          0          0          0          0          0
#8      S301     March          0          0          0          0          0
#9      S300     March          0          0          0          0          0
#10     S301     April      15413      29798      70010      20342      24521

Here is a dplyr/tidyr version using the same logic

library(dplyr)
library(tidyr)

df %>%
   mutate(row = row_number()) %>%
   gather(key, value, -c(1:2, row)) %>%
   group_by(row) %>%
   slice(if(is.na(first(Pol_Month))) 1:12 else {ind = max(match(first(Pol_Month), month.name), 4); ind : (ind + 11) }) %>%
   mutate(key = paste0("Month", 1:12, "_APE")) %>%
   spread(key, value) %>%
   select(-row)


问:
Run PHP file from within vim
Is it possibly to run a PHP file from within vim? What im trying to do here is having a shortcut so whenever I need to run the file I'm editing to skip exiting vim and calling the PHP interpreter manually</p>

答:
I have this in my .vimrc

```<code>" set make command when editing php files
set makeprg=php\ -l\ %
set errorformat=%m\ in\ %f\ on\ line\ %l
</code>```

and then I map to F7 (or whatever you want) with:

```<code>:map <F7> :make <CR>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Run PHP file from within vim

Body:
I have this in my .vimrc

" set make command when editing php files
set makeprg=php\ -l\ %
set errorformat=%m\ in\ %f\ on\ line\ %l

and then I map to F7 (or whatever you want) with:

:map <F7> :make <CR>


问:
Is there any approach to migrate PostgreSQL database from Azure to AWS RDS PostgreSQL
I able to migrate from on-prem database to AWS using DMS service but couldn't able to migrate database from Azure to AWS.

Is there any better approach?

答:
A pretty low level but effective way would be to: export your Azure data as CSV using pg_dump,
copy it into an AWS S3 bucket (pretty easy with Python awscli package) and load from S3 into RDS Postgres.

Would be great if files could be moved directly from blob storage to s3, but I don't think Azure Postgres supports dumping directly to blob anyway.


问:
Cannot upgrade Angular Material with Angular 8
I did everything described in the update guide (complex app) but it was keep failing at the point of ng update @angular/material with the following error:

```<code>Package "@angular/flex-layout" has an incompatible peer dependency to "@angular/cdk" (requires "^7.0.0-rc.0", would install "8.0.0").
</code>```

答:
The root cause was that I did not install the core packages prior to the update.

ng update @angular/cli @angular/core

also, if you keep getting the error, might give a shot to --force flag to ignore peer dependency problems - but that won't necessary solve the problem.

Body:
I did everything described in the update guide (complex app) but it was keep failing at the point of ng update @angular/material with the following error:

Package "@angular/flex-layout" has an incompatible peer dependency to "@angular/cdk" (requires "^7.0.0-rc.0", would install "8.0.0").


问:
Remove specific values contained in DataFrame
I am trying to check if a specific value is contained anywhere in a certain column of my dataframe. I am using the following code, where it should clear data containing "0.0". However, it seemed like it is clearing data that does not contain "0.0" as well.

```<code>mydataset = mydataset[mydataset['Latitude'].astype(str).str.contains('0.0') == False]
</code>```

Example of the data as follows. Highlighted in red are data being removed, upon applying the above code.

答:
Here is problem . in regex is special char, so need regex=False or escape it by \, for invert mask use ~:

```<code>mydataset = mydataset[~mydataset['Latitude'].astype(str).str.contains('0.0', regex=False)]
</code>```

Or:

```<code>mydataset = mydataset[~mydataset['Latitude'].astype(str).str.contains('0\.0')]
</code>```

Body:
I am trying to check if a specific value is contained anywhere in a certain column of my dataframe. I am using the following code, where it should clear data containing "0.0". However, it seemed like it is clearing data that does not contain "0.0" as well.

mydataset = mydataset[mydataset['Latitude'].astype(str).str.contains('0.0') == False]

Example of the data as follows. Highlighted in red are data being removed, upon applying the above code.

Body:
Here is problem . in regex is special char, so need regex=False or escape it by \, for invert mask use ~:

mydataset = mydataset[~mydataset['Latitude'].astype(str).str.contains('0.0', regex=False)]

Or:

mydataset = mydataset[~mydataset['Latitude'].astype(str).str.contains('0\.0')]


问:
C#: How to add an attributes to an object at run-time?
As an entity class, I want to add an attributes at run-time, how should I do?</p>

答:
Edit: please clarify, are you talking about c# attributes or members on your class?

The only way you can add c# attributes is to generate a completely new class with the additional attributes, compile and load the new assembly to your existing AppDomain.

LastEditorDisplayName: Samuel

OwnerDisplayName: Rex M

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Rex M


问:
unable to use custom cell
I am not able to make out whatrs wrong with this piece of code all I am trying to do is use custom table cell 'AlertCell' when device is in portrait mode and 'AlertCellLandScape' if device is in 'landscape' mode.

its saying cell is undeclared and inside the condition check its saying unused cell

```<code>static NSString *CellIdentifier1 = @"Cell1";
static NSString *CellIdentifier2 = @"Cell2";
UITableViewCell *cell;

if (isPortraitMode)
{
    AlertsTableCell *cell = (AlertsTableCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
}

else {
    AlertsTableCellLandScape *cell = (AlertsTableCellLandScape *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
}

if (cell == nil) {
   // cell = [[[AlertsTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

    if (isPortraitMode) {
        cell = [[[AlertsTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier1] autorelease];
    }
    else {
        cell = [[[AlertsTableCellLandScape alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier2] autorelease];
    }
}
</code>```

Please shed some light on this.

Thanks in advance

答:
You have a scope issue. You're declaring cell inside your if/else, so it doesn't exist outside of them.

Declare cell before your if/else, then assign it inside.

Title: unable to use custom cell

Body:
I am not able to make out whatrs wrong with this piece of code all I am trying to do is use custom table cell 'AlertCell' when device is in portrait mode and 'AlertCellLandScape' if device is in 'landscape' mode.

its saying cell is undeclared and inside the condition check its saying unused cell

static NSString *CellIdentifier1 = @"Cell1";
static NSString *CellIdentifier2 = @"Cell2";
UITableViewCell *cell;

if (isPortraitMode)
{
    AlertsTableCell *cell = (AlertsTableCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
}

else {
    AlertsTableCellLandScape *cell = (AlertsTableCellLandScape *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
}

if (cell == nil) {
   // cell = [[[AlertsTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

    if (isPortraitMode) {
        cell = [[[AlertsTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier1] autorelease];
    }
    else {
        cell = [[[AlertsTableCellLandScape alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier2] autorelease];
    }
}

Please shed some light on this.

Thanks in advance


问:
How to Sign a UWP app on Azure Pipelines?
The doc about setting up Azure Pipelines for a UWP doesn't say how to sign the package. It does say that the cert file should be in the repo but it doesn't explain how to sign the package with that cert.

So my question is how do I sign a UWP package on Azure Pipelines?
Am I supposed to create a powershell script to run SignTool?

答:
Depends what you want to do with the app. I currently use signtool to sign with our in house cert.

```<code>signtool sign /a /d "{certName}" /fd sha256 /n "{publisherName}" /td sha256 /tr "http://timestamp.comodoca.com" /v "$(TargetPath)"
</code>```

Please see https://learn.microsoft.com/en-us/windows/desktop/seccrypto/using-signtool-to-sign-a-file

You can also use the WACK to verify the app and then install the cert that's produced during deploy.

https://learn.microsoft.com/en-us/windows/uwp/debug-test-perf/windows-app-certification-kit

Body:
Depends what you want to do with the app. I currently use signtool to sign with our in house cert.

signtool sign /a /d "{certName}" /fd sha256 /n "{publisherName}" /td sha256 /tr "http://timestamp.comodoca.com" /v "$(TargetPath)"

Please see https://learn.microsoft.com/en-us/windows/desktop/seccrypto/using-signtool-to-sign-a-file

You can also use the WACK to verify the app and then install the cert that's produced during deploy.

https://learn.microsoft.com/en-us/windows/uwp/debug-test-perf/windows-app-certification-kit


问:
npm build gives "Ineffective mark-compacts near heap limit Allocation failed"
I have a reactjs/typescript project, running on windows 10. Im trying to build by ts-scripts with

"rimraf ../wwwroot/* && react-scripts-ts build && copyfiles
  ./build/**/* ../wwwroot/ -u 1

This has worked ok before, but when I removed the node_modules-folder, re-run the npm install-command and then the command above I get the error message

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation
  failed - JavaScript heap out of memory

I have no idea why. After googling Ive seen

NODE_OPTIONS="–max-old-space-size=2048"
  but I dont know where to put this

Full error message

Last few GCs

```<code>[11376:0000024682F49880]    60039 ms: Mark-sweep 2034.1 (2085.2) -> 2033.7 (2085.2) MB, 1029.4 / 0.0 ms  (average mu = 0.073, current mu = 0.006) allocation failure scavenge might not succeed
[11376:0000024682F49880]    61094 ms: Mark-sweep 2034.4 (2085.2) -> 2034.1 (2085.7) MB, 1047.7 / 0.0 ms  (average mu = 0.039, current mu = 0.007) allocation failure scavenge might not succeed

 JS stacktrace
==== JS stack trace =========================================

    0: ExitFrame [pc: 000001CDF84DC5C1]
Security context: 0x007044b9e6e1 <JSObject>
    1: bindChildrenWorker(aka bindChildrenWorker) [000001AD1C0ACD59] [C:\Users\robcar\source\repos\Boost\Boost.Web\ClientApp\node_modules\typescript\lib\typescript.js:~27657] [pc=000001CDF8FA47CA](this=0x03da79d826f1 <undefined>,node=0x034b8724ab71 <NodeObject map = 000000660468F931>)
    2: bind(aka bind) [000001AD1C0AE2D9] [C:\Users\robcar\source\repos\B...

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
 1: 00007FF6B5EA121A v8::internal::GCIdleTimeHandler::GCIdleTimeHandler+4810
 2: 00007FF6B5E7A5B6 node::MakeCallback+4518
 3: 00007FF6B5E7AFA0 node_module_register+2160
 4: 00007FF6B610B3EE v8::internal::FatalProcessOutOfMemory+846
 5: 00007FF6B610B31F v8::internal::FatalProcessOutOfMemory+639
 6: 00007FF6B6649304 v8::internal::Heap::MaxHeapGrowingFactor+11476
 7: 00007FF6B663FA67 v8::internal::ScavengeJob::operator=+25543
 8: 00007FF6B663DFDC v8::internal::ScavengeJob::operator=+18748
 9: 00007FF6B6646F57 v8::internal::Heap::MaxHeapGrowingFactor+2343
10: 00007FF6B6646FD6 v8::internal::Heap::MaxHeapGrowingFactor+2470
11: 00007FF6B61E9DD7 v8::internal::Factory::NewFillerObject+55
12: 00007FF6B6281ABA v8::internal::WasmJs::Install+29530
13: 000001CDF84DC5C1
</code>```

答:
I had a similar issue, although on a Mac computer.
Setting an environment variable did the trick for me. That way, your node process will take the value and use it independently of which script you're running.

```<code>export NODE_OPTIONS=--max_old_space_size=4096
</code>```

The run your command again. Good Luck!

Body:
I have a reactjs/typescript project, running on windows 10. Im trying to build by ts-scripts with

"rimraf ../wwwroot/* && react-scripts-ts build && copyfiles
  ./build/**/* ../wwwroot/ -u 1

This has worked ok before, but when I removed the node_modules-folder, re-run the npm install-command and then the command above I get the error message

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation
  failed - JavaScript heap out of memory

I have no idea why. After googling Ive seen

NODE_OPTIONS="–max-old-space-size=2048"
  but I dont know where to put this

Full error message

Last few GCs

[11376:0000024682F49880]    60039 ms: Mark-sweep 2034.1 (2085.2) -> 2033.7 (2085.2) MB, 1029.4 / 0.0 ms  (average mu = 0.073, current mu = 0.006) allocation failure scavenge might not succeed
[11376:0000024682F49880]    61094 ms: Mark-sweep 2034.4 (2085.2) -> 2034.1 (2085.7) MB, 1047.7 / 0.0 ms  (average mu = 0.039, current mu = 0.007) allocation failure scavenge might not succeed

 JS stacktrace
==== JS stack trace =========================================

    0: ExitFrame [pc: 000001CDF84DC5C1]
Security context: 0x007044b9e6e1 <JSObject>
    1: bindChildrenWorker(aka bindChildrenWorker) [000001AD1C0ACD59] [C:\Users\robcar\source\repos\Boost\Boost.Web\ClientApp\node_modules\typescript\lib\typescript.js:~27657] [pc=000001CDF8FA47CA](this=0x03da79d826f1 <undefined>,node=0x034b8724ab71 <NodeObject map = 000000660468F931>)
    2: bind(aka bind) [000001AD1C0AE2D9] [C:\Users\robcar\source\repos\B...

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
 1: 00007FF6B5EA121A v8::internal::GCIdleTimeHandler::GCIdleTimeHandler+4810
 2: 00007FF6B5E7A5B6 node::MakeCallback+4518
 3: 00007FF6B5E7AFA0 node_module_register+2160
 4: 00007FF6B610B3EE v8::internal::FatalProcessOutOfMemory+846
 5: 00007FF6B610B31F v8::internal::FatalProcessOutOfMemory+639
 6: 00007FF6B6649304 v8::internal::Heap::MaxHeapGrowingFactor+11476
 7: 00007FF6B663FA67 v8::internal::ScavengeJob::operator=+25543
 8: 00007FF6B663DFDC v8::internal::ScavengeJob::operator=+18748
 9: 00007FF6B6646F57 v8::internal::Heap::MaxHeapGrowingFactor+2343
10: 00007FF6B6646FD6 v8::internal::Heap::MaxHeapGrowingFactor+2470
11: 00007FF6B61E9DD7 v8::internal::Factory::NewFillerObject+55
12: 00007FF6B6281ABA v8::internal::WasmJs::Install+29530
13: 000001CDF84DC5C1

Body:
I had a similar issue, although on a Mac computer.
Setting an environment variable did the trick for me. That way, your node process will take the value and use it independently of which script you're running.

export NODE_OPTIONS=--max_old_space_size=4096

The run your command again. Good Luck!


问:
windows mobile 6.5 - Motorola MC55 - strange directory names in device explorer view
On Windows XP in device explorer view while I explore the content of my connected via Active Sync Motorola MC55 device I can see strange content. Look at the attached file.

What may be wrong?
Regards

答: That looks a whole lot like the FAT is corrupted on the file store.  A bad flash driver can cause this as well, but that would typically show up immediately and on every device.  If it's a single device, or happened after time then it's likely a flash sector corruption.  Reformatting the flash will likely correct it (though how you do that on your harward I don't know).</p>


问:
Difference between Spark RDD's take(1) and first()
I used to think that rdd.take(1) and rdd.first() are exactly the same. However I began to wonder if this is really true after my colleague pointed me to Spark's officiation documentation on RDD:

first(): Return the first element in this RDD.

take(num): Take the first num elements of the RDD.
  It works by first scanning one partition, and use the results from that partition to estimate the number of additional partitions needed to satisfy the limit.

My questions are:

Is the underlying implementation of first() the same as take(1)?

Suppose rdd1 and rdd2 are constructed from the same csv, can I safely assume that rdd1.take(1) and rdd2.first() will always return the same result, i.e., the first row of the csv? What if rdd1 and rdd2 are partitioned differently?

答:
So, its seems that both are same, but we do have differences.

1.When we read data from the file, it is by default a RDD, and a RDD have both first() and take() attributes.

2.The first() attribute returns a row type object while take() returns a list type.

But
As soon as we converts our RDD to DataFrame using .toDF(), we don't have the first() attribute on that DF.

Hope it may clear the concepts further.

See the image for more clearity


问:
Javascript - Axios in for loop. Using the response of current fetch for the next iteration of fetching data
I use the the variable previous_epoch to fetch reddit posts before today in the first iteration. The next iteration previous_epoch must contain the date from the response data. Oddly enough, the date doesn't change after the first two loops

```<code>const getposts = async(user) => {
    var dataArray = [];
    var utc = new Date()
      .toJSON()
      .slice(0, 10)
      .replace(/-/g, "/");

var previous_epoch;

  for(let i=0; i <=5; i++) {
    if(i == 0) {
        console.log('i is 0');
        previous_epoch = new Date(utc).getTime() / 1000;
        console.log('p',previous_epoch); <--keeps doesn't work after second loop
    }
    else {
        // console.log('else',dataArray);
        previous_epoch = dataArray[dataArray.length-1].created_utc
        console.log('else',previous_epoch);
    }
    await getdat(user,previous_epoch).then((resp) => {
        let jsondat = resp.data.data;
                dataArray = jsondat.concat(dataArray);
    })
  }
  // console.log( dataArray);
  var result = _.map( dataArray, function( o ) {
      return o.id;
  });
/* console.log("%j",result); */
}
</code>```

Function getdat()

```<code>const getdat = (user,epoch) => {

    const sub_url = `https://api.pushshift.io/reddit/search/submission/?subreddit=${user}&limit=300&sort=desc&before=${epoch}`;
    console.log('elZK',sub_url);
  return new Promise((resolve, reject) => {
    axios.get(sub_url)
    .then(response => {
      return resolve(response)
    })
    .catch(error => {
      return reject(error.message)
    })
  })
}
</code>```

here is the fiddle

EDIT 2:
 I've changed the logic so that I get the next date from getdat function itself

```<code>const getdat = (user,epoch) => {
    let res= {};
    const sub_url = `https://api.pushshift.io/reddit/search/submission/?subreddit=${user}&limit=300&sort=desc&before=${epoch}`;
    console.log('elZK',sub_url);
  return new Promise((resolve, reject) => {
    axios.get(sub_url)
    .then(response => {
        let d = response.data.data;
        let e = d[d.length - 1].created_utc;
        console.log('e',e);
        res.data = d;
        res.epoch = e;
      return resolve(res)
    })
    .catch(error => {
      return reject(error.message)
    })
  })
}

export const getUserPosts = async(user) => {
    var dataArray = [];
    var utc = new Date()
      .toJSON()
      .slice(0, 10)
      .replace(/-/g, "/");

var previous_epoch;
var epoch;

for(let i=0; i <=5; i++) {
    if(dataArray.length === 0) {
        console.log('i is 0');
        previous_epoch = new Date(utc).getTime() / 1000;
        console.log('p',previous_epoch);
    }
    else {
        // console.log('else',dataArray);
        previous_epoch = epoch;
        console.log('else',previous_epoch);
    }
    const resp = await getdat(user,previous_epoch);
    const jsondat = resp.data;
    dataArray = jsondat.concat(dataArray);
    epoch = resp.epoch;
  }
  // console.log( dataArray);
  var result = _.map( dataArray, function( o ) {
      return o.id;
  });
console.log("%j",result);
}
</code>```

答:
Try this code</p>

```<code>const getdat = (user,epoch) => {
    const sub_url = `https://api.pushshift.io/reddit/search/submission/?subreddit=${user}&limit=10&sort=desc&before=${epoch}`;
    console.log('elZK',sub_url);
    return axios.get(sub_url);
};

const getposts = async(user) => {
    let dataArray = [];
    let previous_epoch;

    for(let i=0; i <=5; i++) {
     previous_epoch = dataArray.length>0 ? dataArray[dataArray.length-1].created_utc-1 : Math.floor(Date.now()/1000);
      const result =  await getdat(user,previous_epoch);
      dataArray = dataArray.concat(result.data.data);
    }

    console.log(dataArray.map(e => e.created_utc));
};

getposts('data');
</code>```

Body:
I use the the variable previous_epoch to fetch reddit posts before today in the first iteration. The next iteration previous_epoch must contain the date from the response data. Oddly enough, the date doesn't change after the first two loops

const getposts = async(user) => {
    var dataArray = [];
    var utc = new Date()
      .toJSON()
      .slice(0, 10)
      .replace(/-/g, "/");

var previous_epoch;

  for(let i=0; i <=5; i++) {
    if(i == 0) {
        console.log('i is 0');
        previous_epoch = new Date(utc).getTime() / 1000;
        console.log('p',previous_epoch); <--keeps doesn't work after second loop
    }
    else {
        // console.log('else',dataArray);
        previous_epoch = dataArray[dataArray.length-1].created_utc
        console.log('else',previous_epoch);
    }
    await getdat(user,previous_epoch).then((resp) => {
        let jsondat = resp.data.data;
                dataArray = jsondat.concat(dataArray);
    })
  }
  // console.log( dataArray);
  var result = _.map( dataArray, function( o ) {
      return o.id;
  });
/* console.log("%j",result); */
}

Function getdat()

const getdat = (user,epoch) => {

    const sub_url = `https://api.pushshift.io/reddit/search/submission/?subreddit=${user}&limit=300&sort=desc&before=${epoch}`;
    console.log('elZK',sub_url);
  return new Promise((resolve, reject) => {
    axios.get(sub_url)
    .then(response => {
      return resolve(response)
    })
    .catch(error => {
      return reject(error.message)
    })
  })
}

here is the fiddle

EDIT 2:
 I've changed the logic so that I get the next date from getdat function itself

const getdat = (user,epoch) => {
    let res= {};
    const sub_url = `https://api.pushshift.io/reddit/search/submission/?subreddit=${user}&limit=300&sort=desc&before=${epoch}`;
    console.log('elZK',sub_url);
  return new Promise((resolve, reject) => {
    axios.get(sub_url)
    .then(response => {
        let d = response.data.data;
        let e = d[d.length - 1].created_utc;
        console.log('e',e);
        res.data = d;
        res.epoch = e;
      return resolve(res)
    })
    .catch(error => {
      return reject(error.message)
    })
  })
}

export const getUserPosts = async(user) => {
    var dataArray = [];
    var utc = new Date()
      .toJSON()
      .slice(0, 10)
      .replace(/-/g, "/");

var previous_epoch;
var epoch;

for(let i=0; i <=5; i++) {
    if(dataArray.length === 0) {
        console.log('i is 0');
        previous_epoch = new Date(utc).getTime() / 1000;
        console.log('p',previous_epoch);
    }
    else {
        // console.log('else',dataArray);
        previous_epoch = epoch;
        console.log('else',previous_epoch);
    }
    const resp = await getdat(user,previous_epoch);
    const jsondat = resp.data;
    dataArray = jsondat.concat(dataArray);
    epoch = resp.epoch;
  }
  // console.log( dataArray);
  var result = _.map( dataArray, function( o ) {
      return o.id;
  });
console.log("%j",result);
}

Body:
Try this code

const getdat = (user,epoch) => {
    const sub_url = `https://api.pushshift.io/reddit/search/submission/?subreddit=${user}&limit=10&sort=desc&before=${epoch}`;
    console.log('elZK',sub_url);
    return axios.get(sub_url);
};

const getposts = async(user) => {
    let dataArray = [];
    let previous_epoch;

    for(let i=0; i <=5; i++) {
     previous_epoch = dataArray.length>0 ? dataArray[dataArray.length-1].created_utc-1 : Math.floor(Date.now()/1000);
      const result =  await getdat(user,previous_epoch);
      dataArray = dataArray.concat(result.data.data);
    }

    console.log(dataArray.map(e => e.created_utc));
};

getposts('data');


问:
Is it mandatory to check FileExists() before DeleteFile()?
Some time ago, I do not remember where, I read about a best practice in delphi.

Instead of this:

if FileExists(MyFile) then begin
        if not DeleteFile(MyFile) then
                ShowMessage('Unable to delete file');
end;
```

<p>write this:</p>

<pre class="lang-pascal prettyprint-override"><code>if not DeleteFile(MyFile) then
        ShowMessage('Unable to delete file');
</code>```

What are the pro and cons of he second?

答:
For the sake of clarity, I read the code in your question as a desire to delete a file, and report an error only if the file exists, and cannot be deleted.

Checking whether or not a file exists before attempting to delete it is not best practise. In fact, doing so is a classic anti pattern.

The correct pattern is to attempt to delete the file directly. If it fails then check the reason for failure. This will tell you whether or not the file exists, or if the deletion failed for some other reason. On Windows this means using the Win32 API function named DeleteFile and checking its return value for success or failure. In case of failure, call GetLastError to obtain the reason for failure.

Doing this in a cross platform way is not completely trivial, and I don't think the RTL offers such functionality.

It is also well worth pointing out that your two blocks of code are not interchangeable. They have different behaviour. The first block treats file not existing as success. The second treats that as error. If you wish to reproduce the first behaviour with only a single function call then you need to discriminate based on error codes, as described above.

Body:
Some time ago, I do not remember where, I read about a best practice in delphi.

Instead of this:

if FileExists(MyFile) then begin
        if not DeleteFile(MyFile) then
                ShowMessage('Unable to delete file');
end;

write this:

if not DeleteFile(MyFile) then
        ShowMessage('Unable to delete file');

What are the pro and cons of he second?


问:
My code isn't working when I call the methods from Retail Class
I'm trying to display the information from the following methods but its not displaying. This based on question below. Also, I changed the names of the units inventory.

Write a class named that holds data about an item in a retail store. The class should RetailItem store the following data in attributes: item description, units in inventory & price.

Once you have written the class, write a program that creates three objects and RetailItem stores the following data in them:

```<code>Description        Units in Inventory       Price Item
Item #1               Jacket                 59.95
Item #2             Designer Jeans           34.95
Item #3             Shirt 20                 24.95

class Retail_Item:
     def __init__(self, item_description, units_in_inventory, price):
        self.item_description = item_description
        self.units_in_inventory = units_in_inventory
        self.price = price

     def item_description(self):
         return self.item_description

     def units_in_inventory(self):
         return self.units_in_inventory

     def price(self):
         return self.price
import retail_items

def main():
    retail=retail_items.Retail_Item("Jacket","12","59.95")
    retail_2=retail_items.Retail_Item("GUCCI","14","34.95")
    retail_3=retail_items.Retail_Item("LEVIS","15","24.95")

    print("Description:",retail.item_description())
    print("Price:",retail.units_in_inventory())
    print("Units in Inventory:",retail.price())
    print()
    print("Description:",retail_2.item_description())
    print("Price:",retail_2.units_in_inventory())
    print("Units in Inventory:",retail_2.price())
    print()
    print("Description:",retail_3.item_description())
    print("Price:",retail_3.units_in_inventory())
    print("Units in Inventory:",retail_3.price())

main()
</code>```

答:
You get an error because, for example, the method and member variable "item_description" both have the same name. Python cannot dinstinguish both. Therefore by calling item.item_description() you try to call the member variable like a function, which is not possible (Python tells you that via "str object is not callable").

3 possible solutions:

You could rename your member variables to e.g. m_item_description. That way python can distinguish both.

Rename the Get-Method to e.g ItemDec()

Don't use a Get-Method at all, but access the member variable directly via item.item_description (don't use braces)

Body:
I'm trying to display the information from the following methods but its not displaying. This based on question below. Also, I changed the names of the units inventory.

Write a class named that holds data about an item in a retail store. The class should RetailItem store the following data in attributes: item description, units in inventory & price.

Once you have written the class, write a program that creates three objects and RetailItem stores the following data in them:

Description        Units in Inventory       Price Item
Item #1               Jacket                 59.95
Item #2             Designer Jeans           34.95
Item #3             Shirt 20                 24.95

class Retail_Item:
     def __init__(self, item_description, units_in_inventory, price):
        self.item_description = item_description
        self.units_in_inventory = units_in_inventory
        self.price = price

     def item_description(self):
         return self.item_description

     def units_in_inventory(self):
         return self.units_in_inventory

     def price(self):
         return self.price
import retail_items

def main():
    retail=retail_items.Retail_Item("Jacket","12","59.95")
    retail_2=retail_items.Retail_Item("GUCCI","14","34.95")
    retail_3=retail_items.Retail_Item("LEVIS","15","24.95")

    print("Description:",retail.item_description())
    print("Price:",retail.units_in_inventory())
    print("Units in Inventory:",retail.price())
    print()
    print("Description:",retail_2.item_description())
    print("Price:",retail_2.units_in_inventory())
    print("Units in Inventory:",retail_2.price())
    print()
    print("Description:",retail_3.item_description())
    print("Price:",retail_3.units_in_inventory())
    print("Units in Inventory:",retail_3.price())

main()


问:
Entering different cities with their population and then printing the max, min population with their respective cities
I have to input several cities and their population and have to print the max and minimum population with the name of the city.

I've figured out how to get the max and print it together with its country however, I dont know how to get the min.

```<code>n =int(input("Enter the number of municipalities "))

for i in range(n):

    city = input("Enter the municipality: ")
    population = float(input("Enter the population: "))
    #processing information to calculate sum and max, min and range
    sum += population

    if max < population:
        max = population
        maxcity = city

print("The municipality with the highest population of", max, "million was " + maxcity)
</code>```

I need the same result for the min as I do for the max. What can I add to the if loop to make this happen? I am not allowed to use the built in max(), min() functions!

答:
```<code>import sys

INT_max_population = sys.maxsize
INT_MIN = -sys.maxsize-1

max_city = ''
min_city =''

max_population = INT_MIN
min_population = INT_max_population

n =int(input("Enter the number of municipalities "))

for i in range(n):
    city = input("Enter the municipality: ")
    population = float(input("Enter the population: "))

    if max_population < population:
        max_population = population
        max_city = city

    if min_population>population:
        min_population = population
        min_city = city

print("The municipality with the highest population of {} million was {} ".format(max_population, max_city))
print("The municipality with the lowest population of {}  million was {} ".format(min_population, min_city))
</code>```

output

```<code>Enter the number of municipalities 3

Enter the municipality: a

Enter the population: 1

Enter the municipality: b

Enter the population: 2

Enter the municipality: c

Enter the population: 3
The municipality with the highest population of 3.0 million was c
The municipality with the lowest population of 1.0  million was a
</code>```

Body:
I have to input several cities and their population and have to print the max and minimum population with the name of the city.

I've figured out how to get the max and print it together with its country however, I dont know how to get the min.

n =int(input("Enter the number of municipalities "))

for i in range(n):

    city = input("Enter the municipality: ")
    population = float(input("Enter the population: "))
    #processing information to calculate sum and max, min and range
    sum += population

    if max < population:
        max = population
        maxcity = city

print("The municipality with the highest population of", max, "million was " + maxcity)

I need the same result for the min as I do for the max. What can I add to the if loop to make this happen? I am not allowed to use the built in max(), min() functions!

Body:
import sys

INT_max_population = sys.maxsize
INT_MIN = -sys.maxsize-1

max_city = ''
min_city =''

max_population = INT_MIN
min_population = INT_max_population

n =int(input("Enter the number of municipalities "))

for i in range(n):
    city = input("Enter the municipality: ")
    population = float(input("Enter the population: "))

    if max_population < population:
        max_population = population
        max_city = city

    if min_population>population:
        min_population = population
        min_city = city

print("The municipality with the highest population of {} million was {} ".format(max_population, max_city))
print("The municipality with the lowest population of {}  million was {} ".format(min_population, min_city))

output

Enter the number of municipalities 3

Enter the municipality: a

Enter the population: 1

Enter the municipality: b

Enter the population: 2

Enter the municipality: c

Enter the population: 3
The municipality with the highest population of 3.0 million was c
The municipality with the lowest population of 1.0  million was a


问:
Django 1.2.3 - Internationalization - makemessages does not detect all strings
One more question about Django concerning localization of javascript files.

Django provides a small and convenient javascript library which is used like gettext to internationalize strings in javascript files.

I set it up successfully (at least the interpolate function works) and I could generate the po file for the French language. However, not all strings are detected. I don't really know why because they all look the same. I couldn't find anything on the Django Trac and the official docs.

The javascript code is in an external file included in the template and Django apparently found it because it put two strings in the po file.

The inclusion in the HTML template :

```<code><script src="{{MEDIA_URL|default:'/media/'}}js/list.js" type="text/javascript"></script>
</code>```

The javascript code :

```<code>/* ---------------
 * Upload progress
 * --------------- */
$(document).ready(function() {
    $(function() {
        $('#upload_form').uploadProgress({
            //...

            /* function called just before starting the upload */
            start: function() {
                $("#upload_form").hide();
                filename = $("#id_file").val().split(/[\/\\]/).pop();
                fmts = gettext('Uploading %(filename)s...');
                dat = {
                    filename: filename
                };
                s = interpolate(fmts,dat,true);
                $("#progress_filename").html(s);
                $("#progress_container").show();
            },

            /* function called each time bar is updated */
            uploading: function(upload) {
                if (upload.percents >= 100) {
                    window.clearTimeout(this.timer);
                    fmts = gettext("Saving %(filename)s...");
                    dat = {
                        filename: filename
                    };
                    s = interpolate(fmts,dat,true);
                    $("#progress_filename").html(s);
                } else {
                    fmts = gettext('Uploading %(filename)s : %(percents)s%...');
                    dat = {
                        filename: filename,
                        percents: upload.percents
                    };
                    s = interpolate(fmts,dat,true);
                    $("#progress_filename").html(s);
                }
            },

            //...

        });
    });
});

/* --------------------
 * Confirmation dialogs
 * -------------------- */
function delVid(title) {
    fmts = gettext('Do you really want to delete the video "%(title)s"?');
    dat = {
        title: title
    };
    s = interpolate(fmts,dat,true);
    return confirm(s)
}

function abortVid(title) {
    fmts = gettext('Do you really want to abort the processing of the video "%(title)s"?');
    dat = {
        title: title
    };
    s = interpolate(fmts,dat,true);
    return confirm(s)
}
</code>```

The first part is a standard use of the jquery.uploadprogress module for JQuery and the second part is just two functions for confirmation popups.

The detected strings are both in the first part :

'Uploading %(filename)s...'

'Saving %(filename)s...'

I used the command "django-admin.py -d djangojs -l fr" and it generated a djangojs.po file with these two strings. I translated them. Unfortunately, they are not translated at runtime. It seems that I have two problems finally.

Any idea ?

答: Django's Javascript message parsing is quite fragile.  I've written up the details why this is so.  I also have a fix for Django 1.3 attached to Django ticket 7704, which was accepted in 2012.</p>

Body:
One more question about Django concerning localization of javascript files.

Django provides a small and convenient javascript library which is used like gettext to internationalize strings in javascript files.

I set it up successfully (at least the interpolate function works) and I could generate the po file for the French language. However, not all strings are detected. I don't really know why because they all look the same. I couldn't find anything on the Django Trac and the official docs.

The javascript code is in an external file included in the template and Django apparently found it because it put two strings in the po file.

The inclusion in the HTML template :

The javascript code :

/* ---------------
 * Upload progress
 * --------------- */
$(document).ready(function() {
    $(function() {
        $('#upload_form').uploadProgress({
            //...

            /* function called just before starting the upload */
            start: function() {
                $("#upload_form").hide();
                filename = $("#id_file").val().split(/[\/\\]/).pop();
                fmts = gettext('Uploading %(filename)s...');
                dat = {
                    filename: filename
                };
                s = interpolate(fmts,dat,true);
                $("#progress_filename").html(s);
                $("#progress_container").show();
            },

            /* function called each time bar is updated */
            uploading: function(upload) {
                if (upload.percents >= 100) {
                    window.clearTimeout(this.timer);
                    fmts = gettext("Saving %(filename)s...");
                    dat = {
                        filename: filename
                    };
                    s = interpolate(fmts,dat,true);
                    $("#progress_filename").html(s);
                } else {
                    fmts = gettext('Uploading %(filename)s : %(percents)s%...');
                    dat = {
                        filename: filename,
                        percents: upload.percents
                    };
                    s = interpolate(fmts,dat,true);
                    $("#progress_filename").html(s);
                }
            },

            //...

        });
    });
});

/* --------------------
 * Confirmation dialogs
 * -------------------- */
function delVid(title) {
    fmts = gettext('Do you really want to delete the video "%(title)s"?');
    dat = {
        title: title
    };
    s = interpolate(fmts,dat,true);
    return confirm(s)
}

function abortVid(title) {
    fmts = gettext('Do you really want to abort the processing of the video "%(title)s"?');
    dat = {
        title: title
    };
    s = interpolate(fmts,dat,true);
    return confirm(s)
}

The first part is a standard use of the jquery.uploadprogress module for JQuery and the second part is just two functions for confirmation popups.

The detected strings are both in the first part :

'Uploading %(filename)s...'

'Saving %(filename)s...'

I used the command "django-admin.py -d djangojs -l fr" and it generated a djangojs.po file with these two strings. I translated them. Unfortunately, they are not translated at runtime. It seems that I have two problems finally.

Any idea ?


问:
Tile-based movement with Lance game engine?
I'm using Lance for a game where the gameplay area is a tiled map. When a player presses the left-arrow key, their character should move one tile to the left, etc. I tried two approaches, see below, but got neither to work.

Could either approach be modified to work with tile-based movement? Or is a third approach needed? Or is Lance not suited to this kind of game?

Approach 1: Adjust the player's position directly when a key is pressed. From my GameEngine class:

```<code>if (inputData.input == 'left') {
  player.position.x -= 32;
  player.angle = 180;
}
</code>```

While this works well for a single player, it doesn't in multiplayer. When player A moves, their position is not updated on player B's screen.

Approach 2: Set the player's state when a key is pressed:

```<code>if (inputData.input == 'left') {
  player.state = 'walkLeft';
}
</code>```

Then add a postStep handler in the common GameEngine class. (Adding it to Player didn't work). This code turns the player (over many steps) to face 180 degrees and then accelerates the player in that direction:

```<code>onPostStep(event) {
  let players = this.world.queryObjects({instanceType: Player});
  players.forEach(player => {
    if (player.state == 'walkLeft') {
      if (Math.abs(player.angle - 180) > 2)
        player.turnLeft(2);
      }
      else {
        player.accelerate(1);
        player.state = '';
      }
    }
  })
}
</code>```

With this approach, if a player presses the left arrow key, their angle changes as expected at first, but the acceleration and movement is erratic. Also, Player A's position appears different on their screen vs the screen of Player B.

The Spaaace demo is the base for my project, so my project uses the same bending, physics engine, etc.

答:
The first approach is better.  The Brawler game in the sample collection does exactly what you describe.  You can look at the BrawlerGameEngine.js code in https://github.com/lance-gg/tinygames/tree/master/brawler

Make sure that the action is processed in the method
GameEngine::processInput(inputData, playerId)

Body:
I'm using Lance for a game where the gameplay area is a tiled map. When a player presses the left-arrow key, their character should move one tile to the left, etc. I tried two approaches, see below, but got neither to work.

Could either approach be modified to work with tile-based movement? Or is a third approach needed? Or is Lance not suited to this kind of game?

Approach 1: Adjust the player's position directly when a key is pressed. From my GameEngine class:

if (inputData.input == 'left') {
  player.position.x -= 32;
  player.angle = 180;
}

While this works well for a single player, it doesn't in multiplayer. When player A moves, their position is not updated on player B's screen.

Approach 2: Set the player's state when a key is pressed:

if (inputData.input == 'left') {
  player.state = 'walkLeft';
}

Then add a postStep handler in the common GameEngine class. (Adding it to Player didn't work). This code turns the player (over many steps) to face 180 degrees and then accelerates the player in that direction:

onPostStep(event) {
  let players = this.world.queryObjects({instanceType: Player});
  players.forEach(player => {
    if (player.state == 'walkLeft') {
      if (Math.abs(player.angle - 180) > 2)
        player.turnLeft(2);
      }
      else {
        player.accelerate(1);
        player.state = '';
      }
    }
  })
}

With this approach, if a player presses the left arrow key, their angle changes as expected at first, but the acceleration and movement is erratic. Also, Player A's position appears different on their screen vs the screen of Player B.

The Spaaace demo is the base for my project, so my project uses the same bending, physics engine, etc.


问:
MQTT using TC3_IoT_Communication; no connection with MQTT broker but there is no error
I had a mqtt broker running on my computer and I could connect to it with twincat. I moved the mqtt broker to a server on the same network.

I can connect with it by using Node-RED (so the hostname, hostport, username, and password must be correct), but TwinCAT does not connect to it. This is the code that I'm using to connect to my MQTT broker.

My variables:

```<code>fbMqttClient    : FB_IotMqttClient; // MQTT client
bSetParameter   : BOOL := TRUE; // set parameters once at start up
bConnect    : BOOL := TRUE; // if TRUE it will trigger MQTT client cyclically
</code>```

My code:

```<code>// set parameters once when connecting to the mqtt broker
IF bSetParameter THEN
    bSetParameter               := FALSE;
    fbMqttClient.sHostName      := '172.16.1.51';
    fbMqttClient.nHostPort      := 1883;
    fbMqttClient.sTopicPrefix   := '';
    fbMqttClient.sUserName      := 'User';
    fbMqttClient.sUserPassword  := 'TopSecret';
    fbMqttClient.ipMessageQueue := fbMessageQueue;
END_IF

// MQTT client must be triggered cyclically
fbMqttClient.Execute(bConnect);
</code>```

I expect a connection between my broker and TwinCAT. Instead I do not have a connection and I get this data from fbMqttClient:

```<code>bError = FALSE <br>
hrErrorCode = 16#00000001 <br>
eConnectionState = MQTT_ERR_NO_CONN
</code>```

I hope someone can help me to find out where this is going wrong and how to solve this problem.

答: The problem was the firewall on the server and the problem is solved. I can still not connect with public MQTT brokers but I can connect with my own MQTT broker on the server, which is what i really wanted :).</p>

Body:
I had a mqtt broker running on my computer and I could connect to it with twincat. I moved the mqtt broker to a server on the same network.

I can connect with it by using Node-RED (so the hostname, hostport, username, and password must be correct), but TwinCAT does not connect to it. This is the code that I'm using to connect to my MQTT broker.

My variables:

fbMqttClient    : FB_IotMqttClient; // MQTT client
bSetParameter   : BOOL := TRUE; // set parameters once at start up
bConnect    : BOOL := TRUE; // if TRUE it will trigger MQTT client cyclically

My code:

// set parameters once when connecting to the mqtt broker
IF bSetParameter THEN
    bSetParameter               := FALSE;
    fbMqttClient.sHostName      := '172.16.1.51';
    fbMqttClient.nHostPort      := 1883;
    fbMqttClient.sTopicPrefix   := '';
    fbMqttClient.sUserName      := 'User';
    fbMqttClient.sUserPassword  := 'TopSecret';
    fbMqttClient.ipMessageQueue := fbMessageQueue;
END_IF

// MQTT client must be triggered cyclically
fbMqttClient.Execute(bConnect);

I expect a connection between my broker and TwinCAT. Instead I do not have a connection and I get this data from fbMqttClient:

bError = FALSE

hrErrorCode = 16#00000001

eConnectionState = MQTT_ERR_NO_CONN

I hope someone can help me to find out where this is going wrong and how to solve this problem.


问:
onListItemClick, what statement do I need to get the value?
i can add to a db and list as a listview.
When I click a list item using onListItemClick, what statement do I
need to get the value?

Thanks in advance.

```<code>public class Main extends ListActivity {
private static String[] FROM = { _ID, DESCRIPTION, UN };
private static String ORDER_BY = DESCRIPTION + " ASC";
private static int[] TO = {R.id.itemrowid, R.id.itemdescription, R.id.itemun };
private EventsData events;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    events = new EventsData(this);
    try {
        Cursor cursor = getEvents();
        showEvents(cursor);
     } finally {
        events.close();
     }

**public void onListItemClick(ListView parent, View v, int position, long id) {
    // What statement to put here to get the value of _ID,DESCRIPTION, UN
    // selected**?
}

private Cursor getEvents() {
    // Perform a managed query. The Activity will handle closing
    // and re-querying the cursor when needed.
    SQLiteDatabase db = events.getReadableDatabase();
    Cursor cursor = db.query(TABLE_NAME, FROM, null, null, null,
            null, ORDER_BY);
    startManagingCursor(cursor);
    return cursor;
}

private void showEvents(Cursor cursor) {
    // Set up data binding
    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
            R.layout.item, cursor, FROM, TO);
    setListAdapter(adapter);
}
</code>```

答:
First, you need to obtain item at clicked position:

```<code>Cursor cursor = getListAdapter().getItem(position);
</code>```

Then you can get data from this cursor (I don't know what types do you use, so just for example it will be int and String):

```<code>int id = cursor.getInt(cursor.getColumnIndex(_ID));
String description = cursor.getString(cursor.getColumnIndex(DESCRIPTION));
</code>```

See documentation for Cursor's available methods.

Body:
i can add to a db and list as a listview.
When I click a list item using onListItemClick, what statement do I
need to get the value?

Thanks in advance.

public class Main extends ListActivity {
private static String[] FROM = { _ID, DESCRIPTION, UN };
private static String ORDER_BY = DESCRIPTION + " ASC";
private static int[] TO = {R.id.itemrowid, R.id.itemdescription, R.id.itemun };
private EventsData events;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    events = new EventsData(this);
    try {
        Cursor cursor = getEvents();
        showEvents(cursor);
     } finally {
        events.close();
     }

**public void onListItemClick(ListView parent, View v, int position, long id) {
    // What statement to put here to get the value of _ID,DESCRIPTION, UN
    // selected**?
}

private Cursor getEvents() {
    // Perform a managed query. The Activity will handle closing
    // and re-querying the cursor when needed.
    SQLiteDatabase db = events.getReadableDatabase();
    Cursor cursor = db.query(TABLE_NAME, FROM, null, null, null,
            null, ORDER_BY);
    startManagingCursor(cursor);
    return cursor;
}

private void showEvents(Cursor cursor) {
    // Set up data binding
    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
            R.layout.item, cursor, FROM, TO);
    setListAdapter(adapter);
}

Body:
First, you need to obtain item at clicked position:

Cursor cursor = getListAdapter().getItem(position);

Then you can get data from this cursor (I don't know what types do you use, so just for example it will be int and String):

int id = cursor.getInt(cursor.getColumnIndex(_ID));
String description = cursor.getString(cursor.getColumnIndex(DESCRIPTION));

See documentation for Cursor's available methods.


问:
MySQL 'Truncated incorrect INTEGER value'
I'm getting an odd 'Truncated incorrect INTEGER value' error when I run the following UPDATE query:

```<code>update tbl
set projectNumber = right(comments, 7)
where createdBy = 'me'
and length(CONVERT(right(comments, 7), SIGNED INTEGER)) = 7
and CONVERT(right(comments, 7), SIGNED INTEGER) > 0
and CONVERT(right(comments, 7), SIGNED INTEGER) is not null
and createdOn > '2011-01-31 12:00:00'
and projectNumber is null
</code>```

projectNumber is varchar(10).

When I run it as a straight select I do not get an error and I see results as expected.  Any ideas?  Essentially I'm trying to update the projectNumber field where the end of the comments in imported notes are 7 numeric characters (but projectNumber's are not always 7 numeric, which is why the field is varchar(10)).

答:
I found one solution, which is out of box and could easily be implemented.
The solution is much similar to SET ANSI_WARNING OFF in MS SQL Server.

In MySQL, first you need to check whether what is configurations is set for "sql_mode" by using below command:

```<code>SHOW VARIABLES LIKE 'sql_mode';
</code>```

OR else use below:

```<code>SELECT @@GLOBAL.sql_mode;
</code>```

There might have following sets of value in CSV.

ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION

Based on your error, you can remove settings and Reset it using below command:

```<code>SET GLOBAL sql_mode = 'ONLY_FULL_GROUP_BY,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';
</code>```

By using above command to reset it. It has solved similar of this problem "Truncated incorrect INTEGER value" in my case. I hope it should  be working from other user also who are facing this issue.

For more details on this "sql_mode", please refer this.

Hope this would be use full!

Body:
I'm getting an odd 'Truncated incorrect INTEGER value' error when I run the following UPDATE query:

update tbl
set projectNumber = right(comments, 7)
where createdBy = 'me'
and length(CONVERT(right(comments, 7), SIGNED INTEGER)) = 7
and CONVERT(right(comments, 7), SIGNED INTEGER) > 0
and CONVERT(right(comments, 7), SIGNED INTEGER) is not null
and createdOn > '2011-01-31 12:00:00'
and projectNumber is null

projectNumber is varchar(10).

When I run it as a straight select I do not get an error and I see results as expected.  Any ideas?  Essentially I'm trying to update the projectNumber field where the end of the comments in imported notes are 7 numeric characters (but projectNumber's are not always 7 numeric, which is why the field is varchar(10)).

Body:
I found one solution, which is out of box and could easily be implemented.
The solution is much similar to SET ANSI_WARNING OFF in MS SQL Server.

In MySQL, first you need to check whether what is configurations is set for "sql_mode" by using below command:

SHOW VARIABLES LIKE 'sql_mode';

OR else use below:

SELECT @@GLOBAL.sql_mode;

There might have following sets of value in CSV.

ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION

Based on your error, you can remove settings and Reset it using below command:

SET GLOBAL sql_mode = 'ONLY_FULL_GROUP_BY,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';

By using above command to reset it. It has solved similar of this problem "Truncated incorrect INTEGER value" in my case. I hope it should  be working from other user also who are facing this issue.

For more details on this "sql_mode", please refer this.

Hope this would be use full!


问:
Not able to override button style from app.xaml in WPF
I stuck in very strange problem and I could not find solution to it. I tried almost all the possible ways (even delete and recreate solution) to solve this.

ISSUE

I am trying to override default style of control in a WPF app. I defined all the resouces and styles in App.xaml. Problem is, a button foreground color is not getting override runtime. Suprisingly, it show overriden color (White) in VS designer but when I run app, it becomes black (may be default).

There is no other code in app that changes button style.

Additional Info : Buttons are in a Usercontrol and its loaded on MainWindow's ContentControl.

```<code><SolidColorBrush x:Key="WhiteBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="BlackBrush" Color="#000000"/>
<SolidColorBrush x:Key="ActiveBrush" Color="#3A71C5"/>
<SolidColorBrush x:Key="HoverBrush" Color="#0071C5"/>
<SolidColorBrush x:Key="PressBrush" Color="#3A8BF4"/>
<SolidColorBrush x:Key="DefaultBrush" Color="#0071F9"/>
<SolidColorBrush x:Key="DisabledBrush" Color="#F4F4F4"/>

<Style TargetType="{x:Type Button}">
    <Setter Property="Background" Value="{StaticResource ActiveBrush}"/>
    <Setter Property="Foreground" Value="{StaticResource WhiteBrush}"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Border Background="{TemplateBinding Background}" BorderBrush="Transparent" BorderThickness="0">
                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="Background" Value="{StaticResource HoverBrush}"/>
        </Trigger>
        <Trigger Property="IsPressed" Value="True">
            <Setter Property="Background" Value="{StaticResource PressBrush}"/>
        </Trigger>
        <Trigger Property="IsEnabled" Value="False">
            <Setter Property="Background" Value="{StaticResource DisabledBrush}"/>
        </Trigger>
    </Style.Triggers>

</Style>
</code>```

Buttons in VS Designer

Buttons in app runtime

答:
The issue could be that you have some other style which gets applied to some nested control of your button (e.g. TextBlock).

I pasted your snippet in a sample WPF app and wrapped a Button in a custom UserControl. I tested it and showed correctly in both design view and runtime.

Then I added the following style in App.xaml:

```

<p>and the button was showing red text.</p>

<p>So the problem could be some other style for <em>other</em> controls which is overriding some parts of your <code>Button</code> template.</p>

<hr>

<p><strong>EDIT</strong> </p>

<p>A possible solution could be to explicitly define the Button content in the control itself:</p>

<pre class="lang-xml prettyprint-override"><code><Button>
    <TextBlock Foreground="{StaticResource WhiteBrush}">Test</TextBlock>
</Button>
</code>```

There are probably more elegant ways to do this, but I couldn't come up with anything else at the moment.

Body:
I stuck in very strange problem and I could not find solution to it. I tried almost all the possible ways (even delete and recreate solution) to solve this.

ISSUE

I am trying to override default style of control in a WPF app. I defined all the resouces and styles in App.xaml. Problem is, a button foreground color is not getting override runtime. Suprisingly, it show overriden color (White) in VS designer but when I run app, it becomes black (may be default).

There is no other code in app that changes button style.

Additional Info : Buttons are in a Usercontrol and its loaded on MainWindow's ContentControl.

<SolidColorBrush x:Key="WhiteBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="BlackBrush" Color="#000000"/>
<SolidColorBrush x:Key="ActiveBrush" Color="#3A71C5"/>
<SolidColorBrush x:Key="HoverBrush" Color="#0071C5"/>
<SolidColorBrush x:Key="PressBrush" Color="#3A8BF4"/>
<SolidColorBrush x:Key="DefaultBrush" Color="#0071F9"/>
<SolidColorBrush x:Key="DisabledBrush" Color="#F4F4F4"/>

</Style>

Buttons in VS Designer

Buttons in app runtime

Body:
The issue could be that you have some other style which gets applied to some nested control of your button (e.g. TextBlock).

I pasted your snippet in a sample WPF app and wrapped a Button in a custom UserControl. I tested it and showed correctly in both design view and runtime.

Then I added the following style in App.xaml:

<Style TargetType="{x:Type TextBlock}">
     <Setter Property="Foreground" Value="Red"/>
</Style>

and the button was showing red text.

So the problem could be some other style for other controls which is overriding some parts of your Button template.

EDIT

A possible solution could be to explicitly define the Button content in the control itself:

<Button>
    <TextBlock Foreground="{StaticResource WhiteBrush}">Test</TextBlock>
</Button>

There are probably more elegant ways to do this, but I couldn't come up with anything else at the moment.


问:
SQL Grouping with Multiple Column Criteria
I have a table like below. GiverID and TakerID are both foreign keys to another table, say Person Table. GiverID and TakerID won't be same within a row.

```<code>ID  GiverPersonID  TakerPersonID  Amount
 1              1              3     100
 2              2              1     200
 3              2              3     400
 4              3              2     800
</code>```

The first row for that table means that Person with ID 1 gives 100 to Person with ID 3.

I need a query to get the result like below

```<code>PersonID     TotalAmount
       1             100
       2             200
       3            -300
</code>```

Basically, computing the final amount of each person.
For person with ID 1, he gives 100 to person with ID 3, but take 200 from person with ID 2, so his final amount is 200 - 100, which is 100.

I've reading about pivoting, but I think pivoting is not the correct step.

What is the efficient SQL to calculate that result?

答:
```<code>select user_id, sum(amount) from
(
  select TakerPersonID as user_id, sum(amount) as amount
  from stack56355221
  group by 1
  union all
  select GiverPersonID, sum(-amount)
  from stack56355221
  group by 1
) as t1
group by 1
</code>```

Output:

```<code>1 100
2 200
3 -300
</code>```

Body:
I have a table like below. GiverID and TakerID are both foreign keys to another table, say Person Table. GiverID and TakerID won't be same within a row.

ID  GiverPersonID  TakerPersonID  Amount
 1              1              3     100
 2              2              1     200
 3              2              3     400
 4              3              2     800

The first row for that table means that Person with ID 1 gives 100 to Person with ID 3.

I need a query to get the result like below

PersonID     TotalAmount
       1             100
       2             200
       3            -300

Basically, computing the final amount of each person.
For person with ID 1, he gives 100 to person with ID 3, but take 200 from person with ID 2, so his final amount is 200 - 100, which is 100.

I've reading about pivoting, but I think pivoting is not the correct step.

What is the efficient SQL to calculate that result?

Body:
select user_id, sum(amount) from
(
  select TakerPersonID as user_id, sum(amount) as amount
  from stack56355221
  group by 1
  union all
  select GiverPersonID, sum(-amount)
  from stack56355221
  group by 1
) as t1
group by 1

Output:

1 100
2 200
3 -300


问:
I cannot view crash detail of Firebase Crashlytics for android and got stuck on "Build and run your app"
I try to setup Firebase Crashlytics after done setup Firebase.

The crashes was sent successfully.

Which I can see them in firebase dashboard.

But When I enter crashlytics to see crash detail.

I got stuck on step 3 (Build and run your app , We'll be listening for your app to communicate with our servers.).

I already try uninstall-reinstall , remove fabric or firebase crash report part but not working at all.

Here is firebase,fabric,crashlytics version I use.

```<code>classpath 'com.android.tools.build:gradle:3.3.1'
classpath 'com.google.gms:google-services:4.0.2'
classpath 'io.fabric.tools:gradle:1.26.1'

implementation 'com.google.firebase:firebase-core:16.0.7'
implementation('com.crashlytics.sdk.android:crashlytics:2.9.9@aar')
{
    transitive = true;
}
</code>```

Any solution?

答:
If you have multiple apps in the project then make sure that right app is selected for communication in the Firebase crashlytics console.
I searched everything on the web, at the end I realized that I have selected the wrong app in crashlytics console.</p>

Body:
I try to setup Firebase Crashlytics after done setup Firebase.

The crashes was sent successfully.

Which I can see them in firebase dashboard.

But When I enter crashlytics to see crash detail.

I got stuck on step 3 (Build and run your app , We'll be listening for your app to communicate with our servers.).

I already try uninstall-reinstall , remove fabric or firebase crash report part but not working at all.

Here is firebase,fabric,crashlytics version I use.

classpath 'com.android.tools.build:gradle:3.3.1'
classpath 'com.google.gms:google-services:4.0.2'
classpath 'io.fabric.tools:gradle:1.26.1'

implementation 'com.google.firebase:firebase-core:16.0.7'
implementation('com.crashlytics.sdk.android:crashlytics:2.9.9@aar')
{
    transitive = true;
}

Any solution?