问:
Prop.test on count data with multi-level factors in R
I'm having trouble figuring out if prop.test can run this much data (See below) or if I would need to run the code for each level of the factor "Zone" individually. So far I've seen many examples written in this format, but I have many more factor levels:

```<code># Whipray "Zone"
prop.test(c(4,4,0), c(9,7,15))
</code>```

I'd like to know if there are statistically different proportions of fish with empty stomachs over the years and between locations all at once, i.e test the null that there are no differences at any point in time or place (along with a pairwise test to see where those differences are, if they exist).

Count of fish with empty stomachs

```<code>> table1 <- xtabs(empty_count ~ Zone + Year, data = df)
> table1
           Year
Zone        2016 2017 2018
  Crocodile    0    8    2
  Rankin       3   17    8
  West         7   31   17
  Whipray      4    4    0
</code>```

Count of all fish caught

```<code>> table2 <- xtabs(total_count ~ Zone + Year, data = df)
> table2
           Year
Zone        2016 2017 2018
  Crocodile    1   18    7
  Rankin      14   46   69
  West        29   67   58
  Whipray      9    7   15
</code>```

答:
I think I've managed to reverse-engineer your original data frame from the cross-tabs:

df
#>         Zone Year total_count empty_count
#> 1  Crocodile 2016           1           0
#> 2     Rankin 2016          14           3
#> 3       West 2016          29           7
#> 4    Whipray 2016           9           4
#> 5  Crocodile 2017          18           8
#> 6     Rankin 2017          46          17
#> 7       West 2017          67          31
#> 8    Whipray 2017           7           4
#> 9  Crocodile 2018           7           2
#> 10    Rankin 2018          69           8
#> 11      West 2018          58          17
#> 12   Whipray 2018          15           0
```
<p>It seems to me that rather than attempting multiple pairwise comparisons you could carry out a single logistic regression to find out where the significant differences are. Just ensure you have a "non-empty" count column, and that your years are factors:</p>
```df$non_empty_count <- df$total_count - df$empty_count
df$Year <- as.factor(df$Year)
```
<p>And your logistic regression looks like this:</p>
<pre class="lang-r prettyprint-override"><code>model <- glm(cbind(empty_count, non_empty_count) ~ Zone + Year,
             data = df, family = binomial)

summary(model)
#>
#> Call:
#> glm(formula = cbind(empty_count, non_empty_count) ~ Zone + Year,
#>     family = binomial, data = df)
#>
#> Deviance Residuals:
#>      Min        1Q    Median        3Q       Max
#> -2.47563  -0.59548   0.04512   0.56564   1.26509
#>
#> Coefficients:
#>             Estimate Std. Error z value Pr(>|z|)
#> (Intercept)  -0.9588     0.5360  -1.789   0.0737 .
#> ZoneRankin   -0.4864     0.4740  -1.026   0.3048
#> ZoneWest      0.1281     0.4552   0.281   0.7784
#> ZoneWhipray  -0.1395     0.6038  -0.231   0.8173
#> Year2017      0.7975     0.3659   2.180   0.0293 *
#> Year2018     -0.3861     0.3831  -1.008   0.3136
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#>
#> (Dispersion parameter for binomial family taken to be 1)
#>
#>     Null deviance: 39.255  on 11  degrees of freedom
#> Residual deviance: 11.800  on  6  degrees of freedom
#> AIC: 57.905
#>
#> Number of Fisher Scoring iterations: 5
</code>```

Which you can interpret as saying that while the proportion of empty stomachs didn't vary significantly between sites, there was a significantly higher proportion of fish with empty stomachs in 2017 compared to other years across all sites.

Reproducible data

df <- structure(list(Zone = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 3L,
4L, 1L, 2L, 3L, 4L), .Label = c("Crocodile", "Rankin", "West",
"Whipray"), class = "factor"), Year = c(2016, 2016, 2016, 2016,
2017, 2017, 2017, 2017, 2018, 2018, 2018, 2018), total_count = c(1L,
14L, 29L, 9L, 18L, 46L, 67L, 7L, 7L, 69L, 58L, 15L), empty_count = c(0L,
3L, 7L, 4L, 8L, 17L, 31L, 4L, 2L, 8L, 17L, 0L)), row.names = c(NA,
-12L), class = "data.frame")
```

Created on 2022-02-09 by the reprex package (v2.0.1)

Body:
I'm having trouble figuring out if prop.test can run this much data (See below) or if I would need to run the code for each level of the factor "Zone" individually. So far I've seen many examples written in this format, but I have many more factor levels:

# Whipray "Zone"
prop.test(c(4,4,0), c(9,7,15))

I'd like to know if there are statistically different proportions of fish with empty stomachs over the years and between locations all at once, i.e test the null that there are no differences at any point in time or place (along with a pairwise test to see where those differences are, if they exist).

Count of fish with empty stomachs

> table1 <- xtabs(empty_count ~ Zone + Year, data = df)
> table1
           Year
Zone        2016 2017 2018
  Crocodile    0    8    2
  Rankin       3   17    8
  West         7   31   17
  Whipray      4    4    0

Count of all fish caught

> table2 <- xtabs(total_count ~ Zone + Year, data = df)
> table2
           Year
Zone        2016 2017 2018
  Crocodile    1   18    7
  Rankin      14   46   69
  West        29   67   58
  Whipray      9    7   15

Body:
I think I've managed to reverse-engineer your original data frame from the cross-tabs:

df
#>         Zone Year total_count empty_count
#> 1  Crocodile 2016           1           0
#> 2     Rankin 2016          14           3
#> 3       West 2016          29           7
#> 4    Whipray 2016           9           4
#> 5  Crocodile 2017          18           8
#> 6     Rankin 2017          46          17
#> 7       West 2017          67          31
#> 8    Whipray 2017           7           4
#> 9  Crocodile 2018           7           2
#> 10    Rankin 2018          69           8
#> 11      West 2018          58          17
#> 12   Whipray 2018          15           0

It seems to me that rather than attempting multiple pairwise comparisons you could carry out a single logistic regression to find out where the significant differences are. Just ensure you have a "non-empty" count column, and that your years are factors:

df$non_empty_count <- df$total_count - df$empty_count
df$Year <- as.factor(df$Year)

And your logistic regression looks like this:

model <- glm(cbind(empty_count, non_empty_count) ~ Zone + Year,
             data = df, family = binomial)

summary(model)
#>
#> Call:
#> glm(formula = cbind(empty_count, non_empty_count) ~ Zone + Year,
#>     family = binomial, data = df)
#>
#> Deviance Residuals:
#>      Min        1Q    Median        3Q       Max
#> -2.47563  -0.59548   0.04512   0.56564   1.26509
#>
#> Coefficients:
#>             Estimate Std. Error z value Pr(>|z|)
#> (Intercept)  -0.9588     0.5360  -1.789   0.0737 .
#> ZoneRankin   -0.4864     0.4740  -1.026   0.3048
#> ZoneWest      0.1281     0.4552   0.281   0.7784
#> ZoneWhipray  -0.1395     0.6038  -0.231   0.8173
#> Year2017      0.7975     0.3659   2.180   0.0293 *
#> Year2018     -0.3861     0.3831  -1.008   0.3136
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#>
#> (Dispersion parameter for binomial family taken to be 1)
#>
#>     Null deviance: 39.255  on 11  degrees of freedom
#> Residual deviance: 11.800  on  6  degrees of freedom
#> AIC: 57.905
#>
#> Number of Fisher Scoring iterations: 5

Which you can interpret as saying that while the proportion of empty stomachs didn't vary significantly between sites, there was a significantly higher proportion of fish with empty stomachs in 2017 compared to other years across all sites.

Reproducible data

df <- structure(list(Zone = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 3L,
4L, 1L, 2L, 3L, 4L), .Label = c("Crocodile", "Rankin", "West",
"Whipray"), class = "factor"), Year = c(2016, 2016, 2016, 2016,
2017, 2017, 2017, 2017, 2018, 2018, 2018, 2018), total_count = c(1L,
14L, 29L, 9L, 18L, 46L, 67L, 7L, 7L, 69L, 58L, 15L), empty_count = c(0L,
3L, 7L, 4L, 8L, 17L, 31L, 4L, 2L, 8L, 17L, 0L)), row.names = c(NA,
-12L), class = "data.frame")

Created on 2022-02-09 by the reprex package (v2.0.1)


来源: stackexchange

问:
I want to hide  tag whose data-original-title="Close" after page loads but it is visible in jquery
I have a page which opens in Modal window and I want to hide  tag whose data-original-title="Close" after page loads with the following code but it doesn't work: I am using SAAS system where there is an option to open a page in MODAL window.

```<code>function startUp() {
  $("i[data-original-title='Close']").hide();
}

<body onload="startUp(); return true;">
</body>
</code>```

I tried document.addEventListener('DOMContentLoaded'... as well

答:
Given your use case and the JS code being supplied by a third party, I would recommend just using a CSS rule in your styles.css (or whatever file name) file.

```<code>.sswindow-backdrop i[data-original-title=Close] {
   display:none !important;
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: I want to hide <i> tag whose data-original-title="Close" after page loads but it is visible in jquery

Body:
I have a page which opens in Modal window and I want to hide  tag whose data-original-title="Close" after page loads with the following code but it doesn't work: I am using SAAS system where there is an option to open a page in MODAL window.

function startUp() {
  $("i[data-original-title='Close']").hide();
}

I tried document.addEventListener('DOMContentLoaded'... as well

Body:
Given your use case and the JS code being supplied by a third party, I would recommend just using a CSS rule in your styles.css (or whatever file name) file.

.sswindow-backdrop i[data-original-title=Close] {
   display:none !important;
}


问:
Indexing a 3D np array with two 1D np array
I have a 3D np.array of shape (i,j,k)and two 1D np.array contain the indexes in the j-axis and k-axis.

For example

```<code>idx = np.array([0, 1])
idy = np.array([1, 2])
array = np.arange(0, 18).reshape(2, 3, 3)
array([[[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8]],

       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]]])
</code>```

I want to have array[0,0,1], array[0,1,2], array[1,0,1] and array[1,1,2] which is np.array([1,5,10,14]).

Body:
I have a 3D np.array of shape (i,j,k)and two 1D np.array contain the indexes in the j-axis and k-axis.

For example

idx = np.array([0, 1])
idy = np.array([1, 2])
array = np.arange(0, 18).reshape(2, 3, 3)
array([[[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8]],

       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]]])

I want to have array[0,0,1], array[0,1,2], array[1,0,1] and array[1,1,2] which is np.array([1,5,10,14]).

Body:
Is this enough:

In [197]: arr[:,idx,idy]
Out[197]:
array([[ 1,  5],
       [10, 14]])
In [198]: arr[:,idx,idy].ravel()
Out[198]: array([ 1,  5, 10, 14])


问:
Dynamically created expressions
I'm creating a dynamic expression, which will order items in a list by some rule (lambda exp.). This is the code:

```<code>Expression<Func<String, String>> exp = o => o;

MethodCallExpression orderByExp = Expression.Call(typeof(Enumerable), "OrderBy",
    new Type[] { typeof(String), exp.Body.Type }, Expression.Parameter(typeof(IEnumerable<String>), "list"), exp);
</code>```

Now I want to execute previously created expression on specific data to sort it, but it fails because of some strange exceptions like "Lambda Parameter not in scope" or "Argument expression is not valid".

```<code>var data = new String[] { "asdasdasd", "asdads", "123", "xcvxcvs", "ASDSD" };

// one of attempts: doesn't work
var result = data.AsQueryable().Provider.CreateQuery<String>(orderByExp);
</code>```

Can somebody help me with this?

答:
Is there any particular reason you're not just calling:

```<code>data.AsQueryable().OrderBy(exp);
</code>```

Do you even need to use IQueryable here? I get the feeling I'm missing some of the big picture. Are you actually going to be calling this as part of LINQ to SQL (or LINQ to Entities)? If it's just within LINQ to Objects, can't you just use data.OrderBy(exp)?

Basically, some more explanation would be helpful :)

OwnerDisplayName: Kamarey

ContentLicense: CC BY-SA 2.5

Title: Dynamically created expressions

Body:
I'm creating a dynamic expression, which will order items in a list by some rule (lambda exp.). This is the code:

Expression<Func<String, String>> exp = o => o;

MethodCallExpression orderByExp = Expression.Call(typeof(Enumerable), "OrderBy",
    new Type[] { typeof(String), exp.Body.Type }, Expression.Parameter(typeof(IEnumerable<String>), "list"), exp);

Now I want to execute previously created expression on specific data to sort it, but it fails because of some strange exceptions like "Lambda Parameter not in scope" or "Argument expression is not valid".

var data = new String[] { "asdasdasd", "asdads", "123", "xcvxcvs", "ASDSD" };

// one of attempts: doesn't work
var result = data.AsQueryable().Provider.CreateQuery<String>(orderByExp);

Can somebody help me with this?

LastEditorDisplayName: mmyers

Body:
Is there any particular reason you're not just calling:

data.AsQueryable().OrderBy(exp);

Do you even need to use IQueryable here? I get the feeling I'm missing some of the big picture. Are you actually going to be calling this as part of LINQ to SQL (or LINQ to Entities)? If it's just within LINQ to Objects, can't you just use data.OrderBy(exp)?

Basically, some more explanation would be helpful :)

OwnerDisplayName: Jon Skeet


问:
General structure of classes suited for unittest
I'm working on a play app and want to improve my test coverage before going too far with the project.
So far I have quite good test coverage on the model layer, but the controllers tend to get a lot of logic in them (accumulating stuff and calculating from the model results).

Does anyone have a suggestion on how to structure my application so that all parts are easily testable? I could of course refactor all the logic out of the controller and only have one call to a different class for each controller method and then only use the render methods in the controller, but it seems a bit drastic.

Is there a way I can look at the results after a method has been run in the controller, e.g

```<code>public static void controllerMethod(String a){
    String result = doSomething();
    String calcResult = calculateSomething(a);
    render(result, calcResult)
}
</code>```

How can I test that after this method the expected result and calcResult is what I want it to be in a unittest?

All the examples on the play site is about testing the model layer. I know I can run Functional tests towards the controller, but that is a bit to shallow for what I want to test.

If you have any suggestions about how I can structure my classes in order to have an easily testable application, please let me know.

答:
Controllers task should be (mostly) control of the flow of the application (which page to show next). For that you can use the selenium tests in Play.

If you find yourself adding a lot of login in the controller, either move it to methods in the related model (if applicable) or create a middle layer (ala Services) that manages the complex parts. They will be easier to test than Controllers, and will let you reuse the logic on several controllers (for example, acess via browser of REST API call)

ContentLicense: CC BY-SA 3.0

Body:
I'm working on a play app and want to improve my test coverage before going too far with the project.
So far I have quite good test coverage on the model layer, but the controllers tend to get a lot of logic in them (accumulating stuff and calculating from the model results).

Does anyone have a suggestion on how to structure my application so that all parts are easily testable? I could of course refactor all the logic out of the controller and only have one call to a different class for each controller method and then only use the render methods in the controller, but it seems a bit drastic.

Is there a way I can look at the results after a method has been run in the controller, e.g

public static void controllerMethod(String a){
    String result = doSomething();
    String calcResult = calculateSomething(a);
    render(result, calcResult)
}

How can I test that after this method the expected result and calcResult is what I want it to be in a unittest?

All the examples on the play site is about testing the model layer. I know I can run Functional tests towards the controller, but that is a bit to shallow for what I want to test.

If you have any suggestions about how I can structure my classes in order to have an easily testable application, please let me know.


问:
How do you recenter y-axis at 0.01 using ggplot2
I am trying to make a grouped bar plot comparing the concentration of contaminants (in ug/g) from 2 different locations site comparison figure, with the y axis in log scale. I have some values that are below one but greater than zero. The y axis is centering my bars at y=1, making some of the bars look negative. Is there to make my bars start at 0.01 instead of 1?

I tried coord_cartesian( ylim=c(0.01,100), expand = FALSE ) but that didn't do it. I also tried to use coor_trans(y='log10') to log transform y axis instead of scale_y_continuous(trans='log10') but was getting the error message "Transformation introduced infinite values in y-axis" even though I have no zero values.

Any help would be much appreciated,
Thank you.

my code is below:

```<code>malcomp2 %>%
  ggplot(aes(x= contam, y= ug_values, fill= Location))+
  geom_col(data= malcomp2,
           mapping = aes(x= contam, y= ug_values, fill = Location),
           position = position_dodge(.9), #makes the bars grouped
           stat_identity(),
           colour = "black", #adds black lines around bars
           width = 0.8,
           size = 0.3)+
  ylab(expression(Concentration~(mu*g/g)))+ #adds mu character to y axis
  coord_cartesian( ylim=c(0.01,100), expand = FALSE ) +  #force bars to start at 0
  theme_classic()+ #get rid of grey grid
  scale_y_continuous(trans='log10',   #change to log scale
                     labels = c(0.01,0.1,1,10,100))+ #change axis to not sci notation
  annotation_logticks(sides = 'l')+    #add log ticks to y axis only
  scale_x_discrete(name = NULL, #no x axis label
                   limits = c('Dieldrin','Mirex','PBDEs','CHLDs','DDTs','PCBtri','PCBquad',
                            'PCBhept'),   #changes order of x axis
                   labels = c('Dieldrin','Mirex','PBDEs','CHLDs','DDTs','PCB 3','PCB 4-6','PCB7+'))+
  scale_fill_manual("Location",      #rename legend
                    values = c('turquoise2','gold'),  #change colors
                    labels = c( 'St.Andrew Bay', 'Sapelo'))+  #change names on legend
  theme(legend.title = NULL,
        legend.key.size = unit(15, "pt"),
        legend.position =   c(0.10,0.95))   #places legend in upper left corner
</code>```

答:
One hack would be to just scale your data so baseline is at 1. People have asked this question before on SO, and it seems like a more satisfactory approach might be to use geom_rect instead, like here:

Setting where y-axis bisects when using log scale in ggplot2 geom_bar

```<code>ggplot(data.frame(contam = 1:5, ug_values = 10^(-2:2)*100),
       aes(contam, ug_values)) +
  geom_col() +
  scale_y_continuous(trans = 'log10', limits = c(1,10000),
                     breaks = c(1,10,100,1000,10000),
                     labels = c(0.01,0.1,1,10,100))
</code>```

Body:
I am trying to make a grouped bar plot comparing the concentration of contaminants (in ug/g) from 2 different locations site comparison figure, with the y axis in log scale. I have some values that are below one but greater than zero. The y axis is centering my bars at y=1, making some of the bars look negative. Is there to make my bars start at 0.01 instead of 1?

I tried coord_cartesian( ylim=c(0.01,100), expand = FALSE ) but that didn't do it. I also tried to use coor_trans(y='log10') to log transform y axis instead of scale_y_continuous(trans='log10') but was getting the error message "Transformation introduced infinite values in y-axis" even though I have no zero values.

Any help would be much appreciated,
Thank you.

my code is below:

malcomp2 %>%
  ggplot(aes(x= contam, y= ug_values, fill= Location))+
  geom_col(data= malcomp2,
           mapping = aes(x= contam, y= ug_values, fill = Location),
           position = position_dodge(.9), #makes the bars grouped
           stat_identity(),
           colour = "black", #adds black lines around bars
           width = 0.8,
           size = 0.3)+
  ylab(expression(Concentration~(mu*g/g)))+ #adds mu character to y axis
  coord_cartesian( ylim=c(0.01,100), expand = FALSE ) +  #force bars to start at 0
  theme_classic()+ #get rid of grey grid
  scale_y_continuous(trans='log10',   #change to log scale
                     labels = c(0.01,0.1,1,10,100))+ #change axis to not sci notation
  annotation_logticks(sides = 'l')+    #add log ticks to y axis only
  scale_x_discrete(name = NULL, #no x axis label
                   limits = c('Dieldrin','Mirex','PBDEs','CHLDs','DDTs','PCBtri','PCBquad',
                            'PCBhept'),   #changes order of x axis
                   labels = c('Dieldrin','Mirex','PBDEs','CHLDs','DDTs','PCB 3','PCB 4-6','PCB7+'))+
  scale_fill_manual("Location",      #rename legend
                    values = c('turquoise2','gold'),  #change colors
                    labels = c( 'St.Andrew Bay', 'Sapelo'))+  #change names on legend
  theme(legend.title = NULL,
        legend.key.size = unit(15, "pt"),
        legend.position =   c(0.10,0.95))   #places legend in upper left corner

Body:
One hack would be to just scale your data so baseline is at 1. People have asked this question before on SO, and it seems like a more satisfactory approach might be to use geom_rect instead, like here:

Setting where y-axis bisects when using log scale in ggplot2 geom_bar

ggplot(data.frame(contam = 1:5, ug_values = 10^(-2:2)*100),
       aes(contam, ug_values)) +
  geom_col() +
  scale_y_continuous(trans = 'log10', limits = c(1,10000),
                     breaks = c(1,10,100,1000,10000),
                     labels = c(0.01,0.1,1,10,100))


问:
Word with special characters match via preg_match in php
Suppose I have a string like:

```<code>$str ="Model number is FM223-56/89.";
</code>```

And I want match the model number only in this string via preg_match.
I am doing it like:

```<code>$model ="FM223-56/89.";

$pattern = '/\b'.$model.'\b/';
echo preg_match($pattern, $str);
</code>```

But no luck, I want to search word that can have .-,'/" in it, Is it possible to search via preg_match?

There is no fixed pattern.

答:
You need adaptive dynamic word boundaries, i.e. only apply word boundaries if the neighboring chars are word chars:

$str ="Model number is FM223-56/89.";
$model ="FM223-56/89.";
$pattern = '/(?!\B\w)' . preg_quote($model, '/') . '(?<!\w\B)/';
echo preg_match($pattern, $str); // => 1
```

See the PHP demo.

(?!\B\w) - checks if the next char is a word char, and if it is, a word boundary is required at the current location, else, the word boundary is not required

(?<!\w\B) - checks if the previous char is a word char, and if it is, a word boundary is required at the current location, else, the word boundary is not required.

Note the preg_quote($model, '/') part: it escapes all special chars in the $model string and also the / char that is used as a regex delimiter char.

Body:
Suppose I have a string like:

$str ="Model number is FM223-56/89.";

And I want match the model number only in this string via preg_match.
I am doing it like:

$model ="FM223-56/89.";

$pattern = '/\b'.$model.'\b/';
echo preg_match($pattern, $str);

But no luck, I want to search word that can have .-,'/" in it, Is it possible to search via preg_match?

There is no fixed pattern.

Body:
You need adaptive dynamic word boundaries, i.e. only apply word boundaries if the neighboring chars are word chars:

$str ="Model number is FM223-56/89.";
$model ="FM223-56/89.";
$pattern = '/(?!\B\w)' . preg_quote($model, '/') . '(?<!\w\B)/';
echo preg_match($pattern, $str); // => 1

See the PHP demo.

(?!\B\w) - checks if the next char is a word char, and if it is, a word boundary is required at the current location, else, the word boundary is not required

(?<!\w\B) - checks if the previous char is a word char, and if it is, a word boundary is required at the current location, else, the word boundary is not required.

Note the preg_quote($model, '/') part: it escapes all special chars in the $model string and also the / char that is used as a regex delimiter char.


问:
Apache Superset error when installing locally using Docker Compose
I'm trying to install to my Ubuntu 20.04 local machine using docker-compose. When I run sudo docker-compose -f docker-compose-non-dev.yml up, I got several errors and the process keep giving errors and did not end, so I aborted. Can you please tell me what the problem is?

The errors I get during Init Step 1/4 [Starting] -- Applying DB migrations are:

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedTable) >relation "logs" does not exist

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedTable) >relation "ab_permission_view_role" does not exist

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedTable) >relation "report_schedule" does not exist

答:
I had the same issue (Mac OS Monterey) where I had an instance of docker running Postgres for one of my apps, so when Superset started, it was looking at that instance of Postgres which obviously didn't have the appropriate databases/tables/views/etc.

So just stopping that other instance and restarting the Superset containers fixed the errors and properly started Superset. #embarrassed #oops


问:
Livechart gauge value not centering
I am using a gauge chart from the livecharts package. My problem is that the value text does not seem to be centred.  The user has the option on what currency to display the value in so when they change the preference the text alignment moves. I have included screenshots. Does anyone know why the text alignment is changing

XAML

```<code><lvc:Gauge x:Name="TotalExpenseGauge" Grid.Row="2" Grid.Column="0" From="0" To="{Binding gaugeTo}" Value="{Binding gaugeValue}" Height="100" Width="180" GaugeBackground="#c1c2c2" FontSize="10" HorizontalContentAlignment="Center" VerticalAlignment="Top" HighFontSize="16" LabelFormatter="{Binding FormatterGauge}">
     <lvc:Gauge.GaugeActiveFill>
         <LinearGradientBrush>
             <GradientStop Offset="0.0" Color="#FC5C7D" />
             <GradientStop Offset="1.0" Color="#6A82FB" />
         </LinearGradientBrush>
     </lvc:Gauge.GaugeActiveFill>
</lvc:Gauge>
</code>```

Screenshots:

答:
I finally fixed this issue. I think it is due to a bug with livecharts gauges.

It seemed to be when I changed the value of my 'To' it would centre the text again. So I made sure to reset the 'To' back to 0 and then back to my original value which seemed to force a refresh on the control and fix the alignment

Title: Livechart gauge value not centering

Body:
I am using a gauge chart from the livecharts package. My problem is that the value text does not seem to be centred.  The user has the option on what currency to display the value in so when they change the preference the text alignment moves. I have included screenshots. Does anyone know why the text alignment is changing

XAML

<lvc:Gauge x:Name="TotalExpenseGauge" Grid.Row="2" Grid.Column="0" From="0" To="{Binding gaugeTo}" Value="{Binding gaugeValue}" Height="100" Width="180" GaugeBackground="#c1c2c2" FontSize="10" HorizontalContentAlignment="Center" VerticalAlignment="Top" HighFontSize="16" LabelFormatter="{Binding FormatterGauge}">
     <lvc:Gauge.GaugeActiveFill>
         <LinearGradientBrush>
             <GradientStop Offset="0.0" Color="#FC5C7D" />
             <GradientStop Offset="1.0" Color="#6A82FB" />
         </LinearGradientBrush>
     </lvc:Gauge.GaugeActiveFill>
</lvc:Gauge>

Screenshots:


问:
Angular queryParamMap is empty, then populated
I have created a new module in my app so I can separate parts that do not have to communicate and created an new.module.ts with its own routing module and components :

new-routing.module.ts:

```<code>const exportRoutes: Routes = [
  {
    path: 'export',
    component: ExportsComponent
  }
]

@NgModule({
  imports: [RouterModule.forRoot(exportRoutes)],
  exports: [RouterModule]
})
export class ExportRoutingModule {}
</code>```

new.module.ts:

```<code>import { Router } from '@angular/router'
import { BrowserModule } from '@angular/platform-browser'

// Routing Module
import { NewRoutingModule } from './new-routing.module'

@NgModule({
  imports: [..., ExportRoutingModule, ...],
  declarations: [ExportsComponent],
  bootstrap: [ExportsComponent]
})
</code>```

I have a simple index.html:

```<code><body class="app">
  <router-outlet></router-outlet> // outlet is here because I read that I needed it to be able to use activated route, I actually just want the query params
</body>
</code>```

and finally, where the problem lies, my component :

```<code>export class MyComponent implements OnInit {

constructor(private activatedRoute: ActivatedRoute) {}

ngOnInit() {this.activatedRoute.queryParamMap.subscribe(
(params: ParamMap) => console.log(params)
// Do stuff with params => error)}
</code>```

When I navigate to http://localhost:4200/export?firstParam=1.00,2.00,3.00 in my console, the params are logued twice, once empty, once populated as such :

```<code>ParamsAsMap {params: {…}}
keys:(...) // empty
params:{} // empty

core.js:3565 Angular is running in the development mode. Call enableProdMode() to enable the production mode.

ParamsAsMap {params: {…}}
keys:Array(3)
params:{firstParam: "1.00,2.00,3.00", secondParam: "bla"}
</code>```

This cause my component to throw error since I need those params to display my component and the first time they are logued they are empty so :

Why are they loggued twice ?

Why is my code executed before my params observable has a value ?

Could I get rid of the router outlet (which I don't really need since I have no routing involved with this module, I just used it because I read that I couldn't use activatedRoute without it; I just want the query params from my url

Thanks for your help

答:
The accepted answer by @Lakston does not take into account the flow when there's no query params and we need to detect it. After struggling a lot I found a real solution for those of us working with SSR (Server Side Rendering, meaning no browser global objects available for us) and in need of detecting the no query param scenario.

```<code>import { Location } from '@angular/common';
----------------------------------------------------------
constructor(private location: Location)
----------------------------------------------------------
let questionIndex = this.location.path().indexOf('?');
questionIndex = questionIndex === -1 ? Infinity : questionIndex;
const queryParams = (<any>Object).fromEntries(this.location.path().substr(questionIndex + 1).split('&').filter(str => str).map(el => el.split('=')));
</code>```

All credits to YugasVasyl, who posted this answer on: https://github.com/angular/angular/issues/12157

I already test it on my project and it works!
Blessings...

Body:
I have created a new module in my app so I can separate parts that do not have to communicate and created an new.module.ts with its own routing module and components :

new-routing.module.ts:

const exportRoutes: Routes = [
  {
    path: 'export',
    component: ExportsComponent
  }
]

@NgModule({
  imports: [RouterModule.forRoot(exportRoutes)],
  exports: [RouterModule]
})
export class ExportRoutingModule {}

new.module.ts:

import { Router } from '@angular/router'
import { BrowserModule } from '@angular/platform-browser'

// Routing Module
import { NewRoutingModule } from './new-routing.module'

@NgModule({
  imports: [..., ExportRoutingModule, ...],
  declarations: [ExportsComponent],
  bootstrap: [ExportsComponent]
})

I have a simple index.html:

  <router-outlet></router-outlet> // outlet is here because I read that I needed it to be able to use activated route, I actually just want the query params

and finally, where the problem lies, my component :

export class MyComponent implements OnInit {

constructor(private activatedRoute: ActivatedRoute) {}

ngOnInit() {this.activatedRoute.queryParamMap.subscribe(
(params: ParamMap) => console.log(params)
// Do stuff with params => error)}

When I navigate to http://localhost:4200/export?firstParam=1.00,2.00,3.00 in my console, the params are logued twice, once empty, once populated as such :

ParamsAsMap {params: {…}}
keys:(...) // empty
params:{} // empty

core.js:3565 Angular is running in the development mode. Call enableProdMode() to enable the production mode.

ParamsAsMap {params: {…}}
keys:Array(3)
params:{firstParam: "1.00,2.00,3.00", secondParam: "bla"}

This cause my component to throw error since I need those params to display my component and the first time they are logued they are empty so :

Why are they loggued twice ?

Why is my code executed before my params observable has a value ?

Could I get rid of the router outlet (which I don't really need since I have no routing involved with this module, I just used it because I read that I couldn't use activatedRoute without it; I just want the query params from my url

Thanks for your help

Body:
The accepted answer by @Lakston does not take into account the flow when there's no query params and we need to detect it. After struggling a lot I found a real solution for those of us working with SSR (Server Side Rendering, meaning no browser global objects available for us) and in need of detecting the no query param scenario.

import { Location } from '@angular/common';
----------------------------------------------------------
constructor(private location: Location)
----------------------------------------------------------
let questionIndex = this.location.path().indexOf('?');
questionIndex = questionIndex === -1 ? Infinity : questionIndex;
const queryParams = (<any>Object).fromEntries(this.location.path().substr(questionIndex + 1).split('&').filter(str => str).map(el => el.split('=')));

All credits to YugasVasyl, who posted this answer on: https://github.com/angular/angular/issues/12157

I already test it on my project and it works!
Blessings...


问:
Velocity named parameters for a macro
I have a macro taking several parameters. Some of these are optional and if a parameter is left empty it will replaced with default.

Now the question is how to make this as easy as possible for ordinary web designer. Is there any other possibity apart from my examples to handle this case?

Example 1:

The obvious problem here is the optional values.

```<code>#macro (myTag $param1 $param2 $param3)
...
#end
</code>```

Example 2:

And here the problem is a possible issue when same macro is used more than once and all variables are not set again.

```<code>#set ($param1="value1")
#set ($param2="value2")
#set ($param3="value3")

#macro (myTag)
...
#end
</code>```

答:
Here is a Velocity macro that takes two arguments, a color and a list of objects:

```<code>#macro( tablerows $color $values )
  #foreach( $value in $values )
    <tr><td bgcolor=$color>$value</td></tr>
  #end
#end
</code>```

Then you can use the macro in this way: :

```<code>#set( $greatlakes = ["Superior","Michigan","Huron","Erie","Ontario"] )
#set( $color = "blue" )

<table>
  #tablerows( $color $greatlakes )
</table>
</code>```

See full documentation here : Velocity alternative documentation

OwnerDisplayName: pepez

Title: Velocity named parameters for a macro

Body:
I have a macro taking several parameters. Some of these are optional and if a parameter is left empty it will replaced with default.

Now the question is how to make this as easy as possible for ordinary web designer. Is there any other possibity apart from my examples to handle this case?

Example 1:

The obvious problem here is the optional values.

#macro (myTag $param1 $param2 $param3)
...
#end

Example 2:

And here the problem is a possible issue when same macro is used more than once and all variables are not set again.

#set ($param1="value1")
#set ($param2="value2")
#set ($param3="value3")

#macro (myTag)
...
#end

Body:
Here is a Velocity macro that takes two arguments, a color and a list of objects:

#macro( tablerows $color $values )
  #foreach( $value in $values )
    <tr><td bgcolor=$color>$value</td></tr>
  #end
#end

Then you can use the macro in this way: :

#set( $greatlakes = ["Superior","Michigan","Huron","Erie","Ontario"] )
#set( $color = "blue" )

<table>
  #tablerows( $color $greatlakes )
</table>

See full documentation here : Velocity alternative documentation


问:
How to open mutiple tabs within a browser using Capybara?
I need to open multiple tabs within a single browser and i need switch over all the tabs.

Give me your suggestions. Thanks in advance.

答:
You can use this exact function in Ruby:

page.driver.browser.switch_to.window(page.driver.browser.window_handles.last)
```


问:
How do I use floating point number literals when using generic types?
Regular float literals do not work:

```<code>extern crate num_traits;

use num_traits::float::Float;

fn scale_float<T: Float>(x: T) -> T {
    x * 0.54
}

fn main() {
    let a: f64 = scale_float(1.23);
}
</code>```

error[E0308]: mismatched types
 --> src/main.rs:6:9
  |
6 |     x * 0.54
  |         ^^^^ expected type parameter, found floating-point variable
  |
  = note: expected type `T`
             found type `{float}`
```

答: These days the numeric_literals crate and its replace_float_literals feature can be helpful in doing the necessary substitutions on a complex piece of code.

Body:
Regular float literals do not work:

extern crate num_traits;

use num_traits::float::Float;

fn scale_float<T: Float>(x: T) -> T {
    x * 0.54
}

fn main() {
    let a: f64 = scale_float(1.23);
}

error[E0308]: mismatched types
 --> src/main.rs:6:9
  |
6 |     x * 0.54
  |         ^^^^ expected type parameter, found floating-point variable
  |
  = note: expected type `T`
             found type `{float}`


问:
Swiftui Async image not loading when frame size is below 500
Been banging my head against the wall for weeks now! This code returns a gray square, but if I change the frame size to width 500, height 500 then it works. This doesn't make any sense, I can't reproduce the error.

Any frame size below 500 will show a grey background and no image, been deleting and starting from scratch multiple times, it must be a bug?

```<code>Section {
    VStack {
        AsyncImage(url: URL(string: picture.downloadUrl)) { image in
        image
            .resizable()
            .scaledToFit()
        } placeholder: {
            Color.gray.opacity(0.1)
        }
        .frame(width: 200, height: 200)
        .cornerRadius(6)
    }
}
</code>```

答: Removing the VStack did the trick</p>

Body:
Been banging my head against the wall for weeks now! This code returns a gray square, but if I change the frame size to width 500, height 500 then it works. This doesn't make any sense, I can't reproduce the error.

Any frame size below 500 will show a grey background and no image, been deleting and starting from scratch multiple times, it must be a bug?

Section {
    VStack {
        AsyncImage(url: URL(string: picture.downloadUrl)) { image in
        image
            .resizable()
            .scaledToFit()
        } placeholder: {
            Color.gray.opacity(0.1)
        }
        .frame(width: 200, height: 200)
        .cornerRadius(6)
    }
}

Body: Removing the VStack did the trick


问:
How to remove the focus from a TextBox in WinForms?
I need to remove the focus from several TextBoxes. I tried using:

```<code>textBox1.Focused = false;
</code>```

Its ReadOnly property value is true.

I then tried setting the focus on the form, so as to remove it from all the TextBoxes, but this also fails to work:

```<code>this.Focus();
</code>```

and the function returns false when a textbox is selected.

So, how do I remove the focus from a TextBox?

答:
Kinda late to the party in 2022, however none of the solutions here worked for me (idk why) using .Net_6.0_windows, so I've come up with this solution:

```<code>Label focusoutLabel = new Label() {
    Text = "",
    Name = "somegenericplaceholdernamethatwillneverbeusedinmyprogram",
    Visible = false,
};
this.Controls.Add(focusoutLabel);
this.ActiveControl = focusoutLabel;
</code>```

^Place this code to your Form load handler^

Body:
I need to remove the focus from several TextBoxes. I tried using:

textBox1.Focused = false;

Its ReadOnly property value is true.

I then tried setting the focus on the form, so as to remove it from all the TextBoxes, but this also fails to work:

this.Focus();

and the function returns false when a textbox is selected.

So, how do I remove the focus from a TextBox?

Body:
Kinda late to the party in 2022, however none of the solutions here worked for me (idk why) using .Net_6.0_windows, so I've come up with this solution:

Label focusoutLabel = new Label() {
    Text = "",
    Name = "somegenericplaceholdernamethatwillneverbeusedinmyprogram",
    Visible = false,
};
this.Controls.Add(focusoutLabel);
this.ActiveControl = focusoutLabel;

^Place this code to your Form load handler^


问:
Can not delete a partitioned bigquery table
I have a partitioned table in bigquery which needs to be unpartitioned. It is empty at the moment so I do not need to worry about losing information.
I deleted the table by clicking on it > choosing delete > typing delete
but the table is still there even I refreshed the page or wait for 30 mins.

Then I tried the cloud shell terminal:

```<code>bq rm --table project:dataset.table_name
</code>```

then it asked me to confirm and deleted the table but the table is still there!!!

Once I want to create an unpartitioned table with the same name, it gives an error that a table with this name already exists!

I have done this many times before, not sure why the table does not get removed?

答:
Deleting partitions from Google Cloud Console is not supported. You need to execute the command bq rm with the -t shortcut in the Cloud Shell.

Before deleting the partitioned table, I suggest verifying you are going to delete the correct tables (partitions).

You can execute these commands:

```<code>for table in `bq ls --max_results=10000000 $MY_DATASET_ID | grep TABLE | grep $MY_PART_TABLE_NAME | awk '{print $1}'`; do echo $MY_DATASET_ID.$table; done
</code>```

For the variable $MY_PART_TABLE_NAME, you need to write the table name and delete the partition date/value, like in this example "table_name_20200818".

After verifying that these are the correct partitions, you need to execute this command:

```<code>for table in `bq ls --max_results=10000000 $MY_DATASET_ID | grep TABLE | grep $MY_PART_TABLE_NAME | awk '{print $1}'`; do echo $MY_DATASET_ID.$table; bq rm -f -t $MY_DATASET_ID.$table; done
</code>```

Body:
I have a partitioned table in bigquery which needs to be unpartitioned. It is empty at the moment so I do not need to worry about losing information.
I deleted the table by clicking on it > choosing delete > typing delete
but the table is still there even I refreshed the page or wait for 30 mins.

Then I tried the cloud shell terminal:

bq rm --table project:dataset.table_name

then it asked me to confirm and deleted the table but the table is still there!!!

Once I want to create an unpartitioned table with the same name, it gives an error that a table with this name already exists!

I have done this many times before, not sure why the table does not get removed?

Body:
Deleting partitions from Google Cloud Console is not supported. You need to execute the command bq rm with the -t shortcut in the Cloud Shell.

Before deleting the partitioned table, I suggest verifying you are going to delete the correct tables (partitions).

You can execute these commands:

for table in `bq ls --max_results=10000000 $MY_DATASET_ID | grep TABLE | grep $MY_PART_TABLE_NAME | awk '{print $1}'`; do echo $MY_DATASET_ID.$table; done

For the variable $MY_PART_TABLE_NAME, you need to write the table name and delete the partition date/value, like in this example "table_name_20200818".

After verifying that these are the correct partitions, you need to execute this command:

for table in `bq ls --max_results=10000000 $MY_DATASET_ID | grep TABLE | grep $MY_PART_TABLE_NAME | awk '{print $1}'`; do echo $MY_DATASET_ID.$table; bq rm -f -t $MY_DATASET_ID.$table; done


问:
How to create a unit vector of AB towards a number of degrees and calculate the angle between them?
Here you can see the Vector AB.

Goal: Make Vector AC to find out α

Problem: To find out the angle α I would first need a second vector AC that must point towards 190° and has the same length as the unit vector of AB. How do I create that Vector?

```<code>            A = (5, 10)
            B = (10, 5)

            distance = np.array([B[0] - A[0], A[1] - B[1]]) # Vector from A to B
            unit_vector = distance / np.linalg.norm(distance) # unit vector

            # Need to make Vector AC here

            # Get angle between vector AB and vector AC
            AB = unit_vector(unit_vector)
            AC = unit_vector(c)
            print(np.arccos(np.clip(np.dot(AB, AC), -1.0, 1.0)))
</code>```

答:
OK, look at this.  Given your points (5,10) and (10,5):</p>
```<code>C:\tmp>python
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import math

## Find the angle to AB using traditional 0-to-the-right axes.

>>> math.atan2(-5,5)
-0.7853981633974483

## Convert to degrees.

>>> math.atan2(-5,5) * 180 / math.pi
-45.0

## Subtract 90 to shift the 0 point to the north

>>> math.atan2(-5,5) * 180 / math.pi - 90
-135.0

## Modulo 360 to make it positive

>>> (math.atan2(-5,5) * 180 / math.pi - 90) % 360
225.0

##  Subtract 190, and we get the value for the angle alpha.

>>> (math.atan2(-5,5) * 180 / math.pi - 90) % 360 - 190
35.0
</code>```

Body:
Here you can see the Vector AB.

Goal: Make Vector AC to find out α

Problem: To find out the angle α I would first need a second vector AC that must point towards 190° and has the same length as the unit vector of AB. How do I create that Vector?

            A = (5, 10)
            B = (10, 5)

            distance = np.array([B[0] - A[0], A[1] - B[1]]) # Vector from A to B
            unit_vector = distance / np.linalg.norm(distance) # unit vector

            # Need to make Vector AC here

            # Get angle between vector AB and vector AC
            AB = unit_vector(unit_vector)
            AC = unit_vector(c)
            print(np.arccos(np.clip(np.dot(AB, AC), -1.0, 1.0)))

Body:
OK, look at this.  Given your points (5,10) and (10,5):

C:\tmp>python
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import math

## Find the angle to AB using traditional 0-to-the-right axes.

>>> math.atan2(-5,5)
-0.7853981633974483

## Convert to degrees.

>>> math.atan2(-5,5) * 180 / math.pi
-45.0

## Subtract 90 to shift the 0 point to the north

>>> math.atan2(-5,5) * 180 / math.pi - 90
-135.0

## Modulo 360 to make it positive

>>> (math.atan2(-5,5) * 180 / math.pi - 90) % 360
225.0

##  Subtract 190, and we get the value for the angle alpha.

>>> (math.atan2(-5,5) * 180 / math.pi - 90) % 360 - 190
35.0


问:
How to init provider?
The case is: i am going to use MyProvider in the following way SomeProvidersClass.get().myProvider; from this structure:

```<code>class SomeProvidersClass {
late final myProvider =
    Provider((ref) => MyProvider());

MyProvider get myProvider =>
    read(providers.myProvider);
}
</code>```

But
i heed to MyProvider be initialized via some async function;
so i tried to do it in the following way:

```<code>class MyProvider {
  late final SomeType _someVariable; // need to init in async way

  Future<void> init() async => _someVariable = await SomeType.getInstance();

  MyProvider();

  // example of content of this provider that i am going to use
  dynamic? getSmth() => _someVariable.getSmth();

}
</code>```

and i got the following error

```<code>LateInitializationError: field has not been initialized;
</code>```

Could you suggest me any approach to do it? i am new in riverpod and providers :)

答:
Try this:</p>
```<code>class MyProvider {
  SomeType? _someVariable; // need to init in async way

  Future<void> init() async => _someVariable = await SomeType.getInstance();

  MyProvider(){
    init();
  }

  // example of content of this provider that i am going to use
  dynamic? getSmth() => _someVariable?.getSmth();

}
</code>```

Title: How to init provider?

Body:
The case is: i am going to use MyProvider in the following way SomeProvidersClass.get().myProvider; from this structure:

class SomeProvidersClass {
late final myProvider =
    Provider((ref) => MyProvider());

MyProvider get myProvider =>
    read(providers.myProvider);
}

But
i heed to MyProvider be initialized via some async function;
so i tried to do it in the following way:

class MyProvider {
  late final SomeType _someVariable; // need to init in async way

  Future<void> init() async => _someVariable = await SomeType.getInstance();

  MyProvider();

  // example of content of this provider that i am going to use
  dynamic? getSmth() => _someVariable.getSmth();

}

and i got the following error

LateInitializationError: field has not been initialized;

Could you suggest me any approach to do it? i am new in riverpod and providers :)

Body:
Try this:

class MyProvider {
  SomeType? _someVariable; // need to init in async way

  Future<void> init() async => _someVariable = await SomeType.getInstance();

  MyProvider(){
    init();
  }

  // example of content of this provider that i am going to use
  dynamic? getSmth() => _someVariable?.getSmth();

}


问:
Using XML-RPC in iPhone apps
Is it possible to use XML-RPC calls in iPhone application (what approaches are the best)?
Are there any constraints with XML-RPC?

Thank you,
Paul

答:
I have recently come across this library, take a look at the description at the end.

Hope you find it useful.

https://github.com/eczarny/xmlrpc

Title: Using XML-RPC in iPhone apps


问:
Android Emulator's Overlay Occupies Area on Desktop in Linux
I've been doing development with Flutter. I was using a real hardware but wanted to use an emulator. I set it up but there's this issue.

I usually put my apps in virtual desktops and I switch between them with Ctrl+Meta+[arrow keys]. Each of them have a special purpose, usually desktop 1 is for browsing, desktop 2 is for development and desktop 4 is extra (for testing UI apps and emulator in this case).

However, after I launch Android emulator and switch to a different desktop, it results in the issue seen below:

The red area you see stays unresponsive for other apps such as browser, VSCode etc. (i.e. does not respond to clicks). That area is where the emulator is on Desktop 4. And it also keeps showing multitouch tool.

It's a bit annoying so I wanted to ask if anyone got this issue and if they have any solutions.

Thanks in advance.

Environment

Kubuntu 20.04

AMD Radeon R7 240/340

答:
Solution 1

I have, somehow in a weird way, found a workaround for this issue.

After having this issue, go to the emulator window and press the magnifying glass with a plus button icon twice.

After that, it will drop that weird multitouch state and it won't bother you even as you switch desktop.

Rebooting computer will result in the same bug, however, you have to do it again.

Solution 2

Another method that works is to simply resize the window. If you have a device frame on your emulator, you can simply hold down the Meta key and hold right click and resize your window.

Solution 3

You can also maximize the window. If you have device frame around emulator window, you can press ALT+F3, which opens up window options menu, then click "Maximize". This will get rid of it.


问:
"The selection cannot be run on any server"
I've been working on a dynamic web project in Eclipse. I am getting this error.

"The selection cannot be run on any server".

Earlier it was working fine but now I'm getting this error. I removed the server and added it again.

Project->Right Click-> Properties->Server No server is showing here and two options are there Restore Default and Apply. I am not able to add server here.

Please tell me want is the problem with this.

POM.XML

<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>try</groupId>
<artifactId>try</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>try Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
    <spring.version>3.2.0.RELEASE</spring.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.7</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.7</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>3.0.3.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <type>maven-plugin</type>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20140107</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>3.6.0.Final</version>
    </dependency>

    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>1.2.132</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>3.1.2.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>3.0.5.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>3.2.5.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>3.2.5.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-taglibs</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
    </dependency>

    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.1</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-core-asl</artifactId>
        <version>1.8.5</version>
    </dependency>
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.8.5</version>
    </dependency>

    <dependency>
        <groupId>com.googlecode.json-simple</groupId>
        <artifactId>json-simple</artifactId>
        <version>1.1</version>
    </dependency>

    <dependency>
        <groupId>org.quartz-scheduler</groupId>
        <artifactId>quartz</artifactId>
        <version>1.8.6</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.6</version>
    </dependency>

    <dependency>
        <groupId>commons-dbcp</groupId>
        <artifactId>commons-dbcp</artifactId>
        <version>1.4</version>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.8.2</version>
        <scope>test</scope>
    </dependency>
</dependencies>
<build>
    <finalName>try</finalName>
    <pluginManagement>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
            </configuration>
        </plugin>
    </plugins>
    </pluginManagement>
</build>
```

答:
I got this error when I:

Right click project in Project Explorer

Select Run As -> Run on Server

Click Finish without selecting a server

I was being lazy and thinking that since there is only one server, it would automatically pick that one, but apparently not. It seems odd that the wizard would let me do that and give such a nonsensical error message.


问:
What is the difference between activated element and selected element?
This question is about listbox.I'm not sure what's the difference between activated element and selected element.What is the point?When I select an item (with an arrow key or mouse) in a listbox,the item is both selected and activated,Which make me also question what's the point with the two seperated methods: active(index) method and selection_set(index) method?
One more question:When is active without selected,and the opposite?</p>

答: Several elements in a listbox can be selected, but only one of them can be active. The active element can deal with inputs, whether they are selected just says something about their internal state.</p>


问:
Unable to pass ADUser to a function (cannot convert Object[] to ADUser)
I'm syncing up user attributes in AD with a provided CSV file. When I try to call my SyncUser function I get the following error:

SyncUser : Cannot process argument transformation on parameter 'user'. Cannot convert the "System.Object[]" value of type "System.Object[]" to type "Microsoft.ActiveDirectory.Management.ADUser".

$user.GetType() tells me the name is ADUser with a base type of ADAccount yet the error message acts as though I'm passing an object array.  Powershell is still fairly new to me so maybe my function syntax is incorrect? I'm confused at this point.

```<code>$AD_Users = Get-ADUsers -SearchBase $adPath -LDAPFilter $filter
$UPNs = $AD_Users | ForEach-Object -Begin { $ht = @{} } _Process { $ht.add($_."userPrincipalname", $_) } -End { return $ht }

Import-Csv $file | ForEach-Object {

    $user = $UPNs[$_."userPrincipalName"]
    SyncUser($user, $_)
}

function  SyncUser{
    param([Microsoft.ActiveDirectory.Management.ADUser]$user, [System.Object]$c)

    # do stuff

}
</code>```

答:
You are not calling your function correctly. It should be:

```<code>    SyncUser $user $_
</code>```

PowerShell does not take parameters in parenthesis like that for functions. The function thinks you are trying to pass an array to the first parameter, that array being $user,$_.

Body:
I'm syncing up user attributes in AD with a provided CSV file. When I try to call my SyncUser function I get the following error:

SyncUser : Cannot process argument transformation on parameter 'user'. Cannot convert the "System.Object[]" value of type "System.Object[]" to type "Microsoft.ActiveDirectory.Management.ADUser".

$user.GetType() tells me the name is ADUser with a base type of ADAccount yet the error message acts as though I'm passing an object array.  Powershell is still fairly new to me so maybe my function syntax is incorrect? I'm confused at this point.

$AD_Users = Get-ADUsers -SearchBase $adPath -LDAPFilter $filter
$UPNs = $AD_Users | ForEach-Object -Begin { $ht = @{} } _Process { $ht.add($_."userPrincipalname", $_) } -End { return $ht }

Import-Csv $file | ForEach-Object {

    $user = $UPNs[$_."userPrincipalName"]
    SyncUser($user, $_)
}

function  SyncUser{
    param([Microsoft.ActiveDirectory.Management.ADUser]$user, [System.Object]$c)

    # do stuff

}

Body:
You are not calling your function correctly. It should be:

    SyncUser $user $_

PowerShell does not take parameters in parenthesis like that for functions. The function thinks you are trying to pass an array to the first parameter, that array being $user,$_.


答:
A listbox with selectmode "multiple" or "extended" can have any number of "selected" items, and at most one "active" item. Most keyboard bindings operate on the "active" item. For instance, the up and down arrow keys change the "active" item, and the spacebar toggles whether the active item is selected or not.

With selectmode "browse" (the default), the active item is always the (sole) selected item, and since listboxes don't acquire the keyboard focus by default, you won't see a location cursor unless you traverse to the listbox with . So the "active" item frequently isn't visually distinguishable.

The distinction is easiest to see with a listbox that has keyboard focus and selectmode multiple.

Example to distinguish both:

```<code>from tkinter import *

# Create the root window
root = Tk()
root.geometry('180x200')

# Create a listbox
listbox = Listbox(root, width=40, height=10, selectmode=MULTIPLE)

# Inserting the listbox items
listbox.insert(1, "Topic A")
listbox.insert(2, "Topic B")
listbox.insert(3, "Topic C")
listbox.insert(4, "Topic D")
listbox.insert(5, "Topic E")

# Function for printing the
# selected listbox value(s)
def selected_item():
    print("Selected")
    for i in listbox.curselection():
        print(listbox.get(i))
    print("")

# active listbox value
def active_item():
    print("Active")
    print(listbox.get(ACTIVE))
    print("")

btn = Button(root, text='Print Selected', command=selected_item)
btn2 = Button(root, text="Print Active", command=active_item)

# Placing the button and listbox
btn.pack(side='bottom')
btn2.pack(side='bottom')
listbox.pack()

root.mainloop()
</code>```

Title: What is the difference between activated element and selected element?

Body:
This question is about listbox.I'm not sure what's the difference between activated element and selected element.What is the point?When I select an item (with an arrow key or mouse) in a listbox,the item is both selected and activated,Which make me also question what's the point with the two seperated methods: active(index) method and selection_set(index) method?
One more question:When is active without selected,and the opposite?

Body:
A listbox with selectmode "multiple" or "extended" can have any number of "selected" items, and at most one "active" item. Most keyboard bindings operate on the "active" item. For instance, the up and down arrow keys change the "active" item, and the spacebar toggles whether the active item is selected or not.

With selectmode "browse" (the default), the active item is always the (sole) selected item, and since listboxes don't acquire the keyboard focus by default, you won't see a location cursor unless you traverse to the listbox with . So the "active" item frequently isn't visually distinguishable.

The distinction is easiest to see with a listbox that has keyboard focus and selectmode multiple.

Example to distinguish both:

from tkinter import *

# Create the root window
root = Tk()
root.geometry('180x200')

# Create a listbox
listbox = Listbox(root, width=40, height=10, selectmode=MULTIPLE)

# Inserting the listbox items
listbox.insert(1, "Topic A")
listbox.insert(2, "Topic B")
listbox.insert(3, "Topic C")
listbox.insert(4, "Topic D")
listbox.insert(5, "Topic E")

# Function for printing the
# selected listbox value(s)
def selected_item():
    print("Selected")
    for i in listbox.curselection():
        print(listbox.get(i))
    print("")

# active listbox value
def active_item():
    print("Active")
    print(listbox.get(ACTIVE))
    print("")

btn = Button(root, text='Print Selected', command=selected_item)
btn2 = Button(root, text="Print Active", command=active_item)

# Placing the button and listbox
btn.pack(side='bottom')
btn2.pack(side='bottom')
listbox.pack()

root.mainloop()


问:
Flexbox Gallery With Wrapping
I am trying to create a responsive image gallery for my website using a flexbox. However, I am trying to make it wrap to the next line and stay in order, which I am having trouble with. For example:

Desktop

1,2,3

4,5,6 etc

Tablet

1,2

3,4 etc

Mobile

1

2 etc

Please see the example code I included.

.row {
  display: flex;
  flex-wrap: wrap;
}

.column {
  flex: 33%;
  max-width: 33%;
}

.column img {
  vertical-align: middle;
  width: 100%;
}

@media screen and (max-width: 800px) {
  .column {
    flex: 50%;
    max-width: 50%;
  }
}

@media screen and (max-width: 600px) {
  .column {
    flex: 100%;
    max-width: 100%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <div class="column">
    <figure>
      <img src="https://img.webnots.com/2014/04/112.png">
      <figcaption>Caption 1</figcaption>
    </figure>
    <figure>
      <img src="https://img.webnots.com/2014/04/42.png">
      <figcaption>Caption 4</figcaption>
    </figure>
  </div>
  <div class="column">
    <figure>
      <img src="https://img.webnots.com/2014/04/22.png">
      <figcaption>Caption 2</figcaption>
    </figure>
    <figure>
      <img src="https://img.webnots.com/2014/04/52.png">
      <figcaption>Caption 5</figcaption>
    </figure>
  </div>
  <div class="column">
    <figure>
      <img src="https://img.webnots.com/2014/04/32.png">
      <figcaption>Caption 3</figcaption>
    </figure>
    <figure>
      <img src="https://img.webnots.com/2014/04/62.png">
      <figcaption>Caption 6</figcaption>
    </figure>
  </div>
</div></code>```

答:
The first thing I would do is nest it in a container. Flex works in order of the markup so I switched your order back to the correct numerical order. Then, what I would do is nest each of your figure's in their own div. I just used your column div to demonstrate.  Then remove the media queries and let flex do its thing.

The main issue was you were trying to split them up in rows of 3 but had 2 nested per div, and were trying to set max-width to the div. To have a row of 3 they should be nested in their own div's with width: 33%;

EDIT ~ I made the min-width: 200px;because your image renders at about 160px. 200px would be a good breaking point on mobile devices. Check your dev tools for mobile.

.row {
  display: flex;
  flex-wrap: wrap;
}

.column {
  min-width: 200px;
  width: 33.33%;
}

.container {
  margin: auto;
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="row">
    <div class="column">
      <figure>
        <img src="https://img.webnots.com/2014/04/112.png">
        <figcaption>Caption 1</figcaption>
      </figure>
    </div>
    <div class="column">
      <figure>
        <img src="https://img.webnots.com/2014/04/42.png">
        <figcaption>Caption 2</figcaption>
      </figure>
    </div>
    <div class="column">
      <figure>
        <img src="https://img.webnots.com/2014/04/22.png">
        <figcaption>Caption 3</figcaption>
      </figure>
    </div>
    <div class="column">
      <figure>
        <img src="https://img.webnots.com/2014/04/52.png">
        <figcaption>Caption 4</figcaption>
      </figure>
    </div>
    <div class="column">
      <figure>
        <img src="https://img.webnots.com/2014/04/32.png">
        <figcaption>Caption 5</figcaption>
      </figure>
    </div>
    <div class="column">
      <figure>
        <img src="https://img.webnots.com/2014/04/62.png">
        <figcaption>Caption 6</figcaption>
      </figure>
    </div>
  </div>
</div></code>```

Title: Flexbox Gallery With Wrapping

Body:
I am trying to create a responsive image gallery for my website using a flexbox. However, I am trying to make it wrap to the next line and stay in order, which I am having trouble with. For example:

Desktop

1,2,3

4,5,6 etc

Tablet

1,2

3,4 etc

Mobile

1

2 etc

Please see the example code I included.

.row {
  display: flex;
  flex-wrap: wrap;
}

.column {
  flex: 33%;
  max-width: 33%;
}

.column img {
  vertical-align: middle;
  width: 100%;
}

@media screen and (max-width: 800px) {
  .column {
    flex: 50%;
    max-width: 50%;
  }
}

@media screen and (max-width: 600px) {
  .column {
    flex: 100%;
    max-width: 100%;
  }
}

Caption 1

Caption 4

Caption 2

Caption 5

Caption 3

Caption 6

Body:
The first thing I would do is nest it in a container. Flex works in order of the markup so I switched your order back to the correct numerical order. Then, what I would do is nest each of your figure's in their own div. I just used your column div to demonstrate.  Then remove the media queries and let flex do its thing.

The main issue was you were trying to split them up in rows of 3 but had 2 nested per div, and were trying to set max-width to the div. To have a row of 3 they should be nested in their own div's with width: 33%;

EDIT ~ I made the min-width: 200px;because your image renders at about 160px. 200px would be a good breaking point on mobile devices. Check your dev tools for mobile.

.row {
  display: flex;
  flex-wrap: wrap;
}

.column {
  min-width: 200px;
  width: 33.33%;
}

.container {
  margin: auto;
  width: 100%;
}

<div class="container">
  <div class="row">
    <div class="column">
      <figure>
        <img src="https://img.webnots.com/2014/04/112.png">
        <figcaption>Caption 1</figcaption>
      </figure>
    </div>
    <div class="column">
      <figure>
        <img src="https://img.webnots.com/2014/04/42.png">
        <figcaption>Caption 2</figcaption>
      </figure>
    </div>
    <div class="column">
      <figure>
        <img src="https://img.webnots.com/2014/04/22.png">
        <figcaption>Caption 3</figcaption>
      </figure>
    </div>
    <div class="column">
      <figure>
        <img src="https://img.webnots.com/2014/04/52.png">
        <figcaption>Caption 4</figcaption>
      </figure>
    </div>
    <div class="column">
      <figure>
        <img src="https://img.webnots.com/2014/04/32.png">
        <figcaption>Caption 5</figcaption>
      </figure>
    </div>
    <div class="column">
      <figure>
        <img src="https://img.webnots.com/2014/04/62.png">
        <figcaption>Caption 6</figcaption>
      </figure>
    </div>
  </div>
</div>


问:
Capture characters from standard input without waiting for enter to be pressed
I can never remember how I do this because it comes up so infrequently for me. But in C or C++, what is the best way to read a character from standard input without waiting for a newline (press enter).

Also ideally it wouldn't echo the input character to the screen. I just want to capture keystrokes with out effecting the console screen.

答:
I was running into this same issue.  Here is a small solution for windows console using cygwin g++ with if(GetKeyState(keycode) & bitANDcompare){};.

```<code>#include <windows.h>
#include <fstream>
#include <iostream>

using namespace std;
void clear() {
    COORD topLeft  = { 0, 0 };
    HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_SCREEN_BUFFER_INFO screen;
    DWORD written;

    GetConsoleScreenBufferInfo(console, &screen);
    FillConsoleOutputCharacterA(
        console, ' ', screen.dwSize.X * screen.dwSize.Y, topLeft, &written
    );
    FillConsoleOutputAttribute(
        console, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE,
        screen.dwSize.X * screen.dwSize.Y, topLeft, &written
    );
    SetConsoleCursorPosition(console, topLeft);
}

class Keyclick{
    private:
    int key;
    char id;
    public:
    bool keydown = false;
    Keyclick(int key1, char id1){
        key=key1;
        id=id1;
    };
    void watch(){
        if(keydown==false){
            if(GetKeyState(key) & 0x8000 ){
                cout << id;
                cout << "  pressed.\r\n";
                keydown = true;
            }
        }
        if(keydown == true){
            if(!(GetKeyState(key) & 0x8000)) {
                cout << "released!!!!!!!!!!\r\n";
                keydown = false;
                clear();
            }
        }
    };
};

int main()
{
    bool primaryloop =true;
    Keyclick keysp(VK_SPACE,'S');
    Keyclick keyw(0x57,'w');
    Keyclick keya(0x41,'a');
    Keyclick keys(0x53,'s');
    Keyclick keyd(0x44,'d');
    Keyclick keyesc(VK_ESCAPE,'E');

    while(primaryloop){
        keysp.watch();
        keyw.watch();
        keya.watch();
        keys.watch();
        keyd.watch();
        keyesc.watch();

        if(keyesc.keydown){
            primaryloop=false;
        };
    }
    return 0;
}
</code>```

https://github.com/wark77/windows_console_keypoller/blob/main/getkeystate_SOLUTION01.cpp

OwnerDisplayName: Adam

Body:
I was running into this same issue.  Here is a small solution for windows console using cygwin g++ with if(GetKeyState(keycode) & bitANDcompare){};.

#include <windows.h>
#include <fstream>
#include <iostream>

using namespace std;
void clear() {
    COORD topLeft  = { 0, 0 };
    HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_SCREEN_BUFFER_INFO screen;
    DWORD written;

    GetConsoleScreenBufferInfo(console, &screen);
    FillConsoleOutputCharacterA(
        console, ' ', screen.dwSize.X * screen.dwSize.Y, topLeft, &written
    );
    FillConsoleOutputAttribute(
        console, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE,
        screen.dwSize.X * screen.dwSize.Y, topLeft, &written
    );
    SetConsoleCursorPosition(console, topLeft);
}

class Keyclick{
    private:
    int key;
    char id;
    public:
    bool keydown = false;
    Keyclick(int key1, char id1){
        key=key1;
        id=id1;
    };
    void watch(){
        if(keydown==false){
            if(GetKeyState(key) & 0x8000 ){
                cout << id;
                cout << "  pressed.\r\n";
                keydown = true;
            }
        }
        if(keydown == true){
            if(!(GetKeyState(key) & 0x8000)) {
                cout << "released!!!!!!!!!!\r\n";
                keydown = false;
                clear();
            }
        }
    };
};

int main()
{
    bool primaryloop =true;
    Keyclick keysp(VK_SPACE,'S');
    Keyclick keyw(0x57,'w');
    Keyclick keya(0x41,'a');
    Keyclick keys(0x53,'s');
    Keyclick keyd(0x44,'d');
    Keyclick keyesc(VK_ESCAPE,'E');

    while(primaryloop){
        keysp.watch();
        keyw.watch();
        keya.watch();
        keys.watch();
        keyd.watch();
        keyesc.watch();

        if(keyesc.keydown){
            primaryloop=false;
        };
    }
    return 0;
}

https://github.com/wark77/windows_console_keypoller/blob/main/getkeystate_SOLUTION01.cpp


问:
How to measure process migration time from one core to another on linux?
On linux we can make a cpu core offline by the command :

```<code>echo 0 > /sys/devices/system/cpu/<core num>/online.
</code>```

This causes the processes running on that core to be migrated to other cores.
What I need to do is to measure the time it takes to migrate a process from one
core to another. How should I do this ?

答:
Migration time of a process from one core to another core is equal to the time needed to take the process state from one core and write this architectural state back to the new core. This is equal to the time of a context switch. You can find many samples, e.g. this one, to measure the context switch time of a process in Linux. </p>

<p>p.s. Changing the affinity is a better way to migrate a process to another core instead of making the core online or offline. </p>

Body:
On linux we can make a cpu core offline by the command :

echo 0 > /sys/devices/system/cpu/<core num>/online.

This causes the processes running on that core to be migrated to other cores.
What I need to do is to measure the time it takes to migrate a process from one
core to another. How should I do this ?

Body:
Migration time of a process from one core to another core is equal to the time needed to take the process state from one core and write this architectural state back to the new core. This is equal to the time of a context switch. You can find many samples, e.g. this one, to measure the context switch time of a process in Linux.

p.s. Changing the affinity is a better way to migrate a process to another core instead of making the core online or offline.


问:
How do I compare an entity in my local context with the one in the database in EF Core?
EF Core 6 and .NET 6.

Suppose all my entities have a LastUpdateAt property, which is a DateTime that gets updated every time an entity is added or modified.

I get an entity from the context and show it to the user (web page, WPF window, whatever). At some point, the user clicks a Save button.

Before I save, I want to check if the entity has been updated by someone else since I got my copy. However, I'm struggling to see how to do this.

If I query the context, it just gives me back the entity I already have (including any changes my user has made).

If I refresh the entity, it overwrites the one in my context, losing my user's changes.

How do I check if the database version has a newer time stamp than the one in my context?

Thanks

答:
Moving the discussion here since I need to paste longer text. In this article it's said, during SaveChanges(), if the DATABASE version was modified in the mean time it will throw DbUpdateConcurrencyException. In that exception you have all 3 values and YOU can decide on how to resolve the conflict:

Resolving a concurrency conflict involves merging the pending changes from the current DbContext with the values in the database. What values get merged will vary based on the application and may be directed by user input.

There are three sets of values available to help resolve a concurrency conflict:

Current values are the values that the application was attempting to write to the database.
Original values are the values that were originally retrieved from the database, before any edits were made.
Database values are the values currently stored in the database.


问:
Angular conditional confirm dialog - How to avoid writing redundant code?
I need a simple confirm dialog where the user has to either click "Yes" or "No". I wrote a simple dialog component to do this with the following code:

confirmation-dialog-component.ts:

```<code>import { Component, Inject } from "@angular/core";
import { MatDialogRef, MAT_DIALOG_DATA } from "@angular/material/dialog";

@Component({
  selector: "app-confirmation-dialog",
  templateUrl: "./confirmation-dialog.component.html",
  styleUrls: ["./confirmation-dialog.component.scss"],
})
export class ConfirmationDialogComponent {
  constructor(
    public dialogRef: MatDialogRef<ConfirmationDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public text: string,
  ) {}

  onNoClick(): void {
    this.dialogRef.close(false);
  }

  onYesClick(): void {
    this.dialogRef.close(true);
  }
}
</code>```

confirmation-dialog-component.html:

```<code><div class="dialog-title">
  <h2>Confirmation</h2>
  <button mat-icon-button class="close-button" (click)="onNoClick()" tabindex="-1">
    <mat-icon>close</mat-icon>
  </button>
</div>

<div mat-dialog-content>
  <span>{{ text }}</span>
</div>

<mat-dialog-actions align="end">
  <button type="button" mat-button color="accent" (click)="onNoClick()">
    No
  </button>
  <button type="submit" mat-raised-button color="primary" (click)="onYesClick()">
    Yes
  </button>
</mat-dialog-actions>
</code>```

If I want the user to confirm something, I can use the dialog like this:

```<code>const confirmDialogRef = this.dialog.open(ConfirmationDialogComponent, {
      data: "Do you really want to do this?",
});

confirmDialogRef.afterClosed().subscribe((confirmResult) => {
  if (confirmResult === true) {
    // User confirmed the dialog
  }
});
</code>```

Now I have a situation where I only need to show the confirmation dialog under certain conditions. Back when I was still writing WinForms applications in C#, I could easily show a confirmation dialog like this:

```<code>if (MessageBox.Show("Do you really want to do this?", "Confirmation", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
{
   // User confirmed the dialog
}
</code>```

This would allow me to easily skip showing the confirmation dialog under certain conditions:

```<code>if (showConfirmationDialog == false || MessageBox.Show("Do you really want to do this?", "Confirmation", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
{
   // Continue
}
</code>```

How can I do something similar with my own confirmation dialog? I cannot just show it under certain conditions because if I have to show it, I need to move my code which should be executed if the user clicks "Yes" into the subscribe. However, if the condition is true so I do not need to show the dialog, I do not need the subscribe. This forces me to have two places in my code where I need to write what should happen after the user clicks "Yes" or if the condition is true. Is there a more elegant way to do this?

答:
One way would be to use an observable stream to track your condition and show/not show the dialog based on that.

Say, for instance, you are calling a function showDialog() that returns a boolean/promise/observable, that then decides whether or not to show the dialog, you can create an observable from that:

```<code>showDialog(): boolean{
    let showDialog = true
    // Determine whether to show
    return showDialog
}
</code>```

Then create an observable from that and pipe it down the stream.

```<code>// Imports
import {of} from 'rxjs'

// somewhere in your class implementation

of(showDialog())
  .pipe(
    mergeMap((show: boolean): [boolean, any] =>{
      if(show) return [of(show), this.openDialog()]
      else return [of(show), {}]
    })
  )
.subscribe(([dialogWasShown, result])=>{
  if(dialogWasShown){
    // do something with the result
  }
  else {
    // do something else
  }
})
</code>```

In the above case, you have your condition determining whether or not to show the dialog.

Body:
I need a simple confirm dialog where the user has to either click "Yes" or "No". I wrote a simple dialog component to do this with the following code:

confirmation-dialog-component.ts:

import { Component, Inject } from "@angular/core";
import { MatDialogRef, MAT_DIALOG_DATA } from "@angular/material/dialog";

@Component({
  selector: "app-confirmation-dialog",
  templateUrl: "./confirmation-dialog.component.html",
  styleUrls: ["./confirmation-dialog.component.scss"],
})
export class ConfirmationDialogComponent {
  constructor(
    public dialogRef: MatDialogRef<ConfirmationDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public text: string,
  ) {}

  onNoClick(): void {
    this.dialogRef.close(false);
  }

  onYesClick(): void {
    this.dialogRef.close(true);
  }
}

confirmation-dialog-component.html:

Confirmation

  <button mat-icon-button class="close-button" (click)="onNoClick()" tabindex="-1">
    <mat-icon>close</mat-icon>
  </button>

  {{ text }}

<mat-dialog-actions align="end">
  <button type="button" mat-button color="accent" (click)="onNoClick()">
    No
  </button>
  <button type="submit" mat-raised-button color="primary" (click)="onYesClick()">
    Yes
  </button>
</mat-dialog-actions>

If I want the user to confirm something, I can use the dialog like this:

const confirmDialogRef = this.dialog.open(ConfirmationDialogComponent, {
      data: "Do you really want to do this?",
});

confirmDialogRef.afterClosed().subscribe((confirmResult) => {
  if (confirmResult === true) {
    // User confirmed the dialog
  }
});

Now I have a situation where I only need to show the confirmation dialog under certain conditions. Back when I was still writing WinForms applications in C#, I could easily show a confirmation dialog like this:

if (MessageBox.Show("Do you really want to do this?", "Confirmation", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
{
   // User confirmed the dialog
}

This would allow me to easily skip showing the confirmation dialog under certain conditions:

if (showConfirmationDialog == false || MessageBox.Show("Do you really want to do this?", "Confirmation", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
{
   // Continue
}

How can I do something similar with my own confirmation dialog? I cannot just show it under certain conditions because if I have to show it, I need to move my code which should be executed if the user clicks "Yes" into the subscribe. However, if the condition is true so I do not need to show the dialog, I do not need the subscribe. This forces me to have two places in my code where I need to write what should happen after the user clicks "Yes" or if the condition is true. Is there a more elegant way to do this?

Body:
One way would be to use an observable stream to track your condition and show/not show the dialog based on that.

Say, for instance, you are calling a function showDialog() that returns a boolean/promise/observable, that then decides whether or not to show the dialog, you can create an observable from that:

showDialog(): boolean{
    let showDialog = true
    // Determine whether to show
    return showDialog
}

Then create an observable from that and pipe it down the stream.

// Imports
import {of} from 'rxjs'

// somewhere in your class implementation

of(showDialog())
  .pipe(
    mergeMap((show: boolean): [boolean, any] =>{
      if(show) return [of(show), this.openDialog()]
      else return [of(show), {}]
    })
  )
.subscribe(([dialogWasShown, result])=>{
  if(dialogWasShown){
    // do something with the result
  }
  else {
    // do something else
  }
})

In the above case, you have your condition determining whether or not to show the dialog.


问:
How to detect change to update existing values with NULL
I need to update a table if an existing record has changes. If the record exists (APK is found), then update it if ID_NUMBER has changed. The problem is when the existing TARGET value is NOT NULL and the SOURCE value IS NULL. How can I detect that condition as unequal?

Using ISNULL() can work, but the second parameter must -not- ever occur in the data. That requires profiling all of the NUMERIC data. Can it bedone without that? In this case, zero (0) can work only if it never occurs in the data.

```<code>UPDATE T SET
    T.f1 = S.f1
FROM TARGET_TABLE T
    INNER JOIN SOURCE_TABLE S
    ON T.APK = S.APK
WHERE
    ISNULL(T.ID_NUMBER,0) <> ISNULL(S.ID_NUMBER,0)
;
</code>```

Here is the possible combinations of ID_NUMBER values in TARGET and SOURCE tables.

```<code>Target      Source
======      ======
NULL        NULL
NULL        7       -- should identify as unequal
7           NULL    -- should identify as unequal, BUT DOES NOT
7           7
</code>```

The following script shows the results. Only the third statement, comparing an existing TARGET value of 7 with the incoming SOURCE value of NULL will fail. Why is that? What code will work?

```<code>SET NOCOUNT ON;
SELECT 3 WHERE ISNULL(NULL, NULL+1) <> ISNULL(NULL,NULL+1);
GO
SELECT 3 WHERE ISNULL(NULL, 7+1) <> ISNULL(7,7+1);
GO
SELECT 3 WHERE ISNULL(7, NULL+1) <> ISNULL(NULL,NULL+1); -- WHY DOES THIS NOT SEE THE INEQUALITY?
GO
SELECT 3 WHERE ISNULL(7, 7+1) <> ISNULL(7,7+1);
GO
</code>```

Example execution:

```<code>1> SET NOCOUNT ON;
2> SELECT 3 WHERE ISNULL(NULL, NULL+1) <> ISNULL(NULL,NULL+1);
3> GO

-----------
1> SELECT 3 WHERE ISNULL(NULL, 7+1) <> ISNULL(7,7+1);
2> GO

-----------
          3
1> SELECT 3 WHERE ISNULL(7, NULL+1) <> ISNULL(NULL,NULL+1); -- WHY DOES THIS NOT SEE THE INEQUALITY?
2> GO

-----------
1> SELECT 3 WHERE ISNULL(7, 7+1) <> ISNULL(7,7+1);
2> GO

-----------
1>
</code>```

答:
I highly recommend doing some reading on NULL because it represents an unknown value and as such cannot be compared or added to another value. Therefore you have to treat it as a separate case using traditional AND/OR logic.

```<code>DECLARE @Table1 TABLE (APK int, ID_NUMBER int);
DECLARE @Table2 TABLE (APK int, ID_NUMBER int);

INSERT INTO @Table1 (APK, ID_NUMBER)
  VALUES (1, null), (1, null), (1, 7), (1, 7), (1, 5);

INSERT INTO @Table2 (APK, ID_NUMBER)
  VALUES (1, null), (1, 7), (1, null), (1, 7), (1, 4);

SELECT T.APK, T.ID_NUMBER, S.ID_NUMBER
FROM @Table1 T
INNER JOIN @Table2 S ON T.APK = S.APK
WHERE T.ID_Number <> S.ID_NUMBER
    OR (T.ID_Number IS NULL AND S.ID_NUMBER IS NOT NULL)
    OR (T.ID_Number IS NOT NULL AND S.ID_NUMBER IS NULL);
</code>```

Given I suspect you have simplified your actual use-case you might find that EXCEPT can be used in your situation as EXCEPT (and INTERSECT) perform a different type of compare when it comes to NULLs. See here for more.

Body:
I need to update a table if an existing record has changes. If the record exists (APK is found), then update it if ID_NUMBER has changed. The problem is when the existing TARGET value is NOT NULL and the SOURCE value IS NULL. How can I detect that condition as unequal?

Using ISNULL() can work, but the second parameter must -not- ever occur in the data. That requires profiling all of the NUMERIC data. Can it bedone without that? In this case, zero (0) can work only if it never occurs in the data.

UPDATE T SET
    T.f1 = S.f1
FROM TARGET_TABLE T
    INNER JOIN SOURCE_TABLE S
    ON T.APK = S.APK
WHERE
    ISNULL(T.ID_NUMBER,0) <> ISNULL(S.ID_NUMBER,0)
;

Here is the possible combinations of ID_NUMBER values in TARGET and SOURCE tables.

Target      Source
======      ======
NULL        NULL
NULL        7       -- should identify as unequal
7           NULL    -- should identify as unequal, BUT DOES NOT
7           7

The following script shows the results. Only the third statement, comparing an existing TARGET value of 7 with the incoming SOURCE value of NULL will fail. Why is that? What code will work?

SET NOCOUNT ON;
SELECT 3 WHERE ISNULL(NULL, NULL+1) <> ISNULL(NULL,NULL+1);
GO
SELECT 3 WHERE ISNULL(NULL, 7+1) <> ISNULL(7,7+1);
GO
SELECT 3 WHERE ISNULL(7, NULL+1) <> ISNULL(NULL,NULL+1); -- WHY DOES THIS NOT SEE THE INEQUALITY?
GO
SELECT 3 WHERE ISNULL(7, 7+1) <> ISNULL(7,7+1);
GO

Example execution:

1> SET NOCOUNT ON;
2> SELECT 3 WHERE ISNULL(NULL, NULL+1) <> ISNULL(NULL,NULL+1);
3> GO

-----------
1> SELECT 3 WHERE ISNULL(NULL, 7+1) <> ISNULL(7,7+1);
2> GO

-----------
          3
1> SELECT 3 WHERE ISNULL(7, NULL+1) <> ISNULL(NULL,NULL+1); -- WHY DOES THIS NOT SEE THE INEQUALITY?
2> GO

-----------
1> SELECT 3 WHERE ISNULL(7, 7+1) <> ISNULL(7,7+1);
2> GO

-----------
1>

Body:
I highly recommend doing some reading on NULL because it represents an unknown value and as such cannot be compared or added to another value. Therefore you have to treat it as a separate case using traditional AND/OR logic.

DECLARE @Table1 TABLE (APK int, ID_NUMBER int);
DECLARE @Table2 TABLE (APK int, ID_NUMBER int);

INSERT INTO @Table1 (APK, ID_NUMBER)
  VALUES (1, null), (1, null), (1, 7), (1, 7), (1, 5);

INSERT INTO @Table2 (APK, ID_NUMBER)
  VALUES (1, null), (1, 7), (1, null), (1, 7), (1, 4);

SELECT T.APK, T.ID_NUMBER, S.ID_NUMBER
FROM @Table1 T
INNER JOIN @Table2 S ON T.APK = S.APK
WHERE T.ID_Number <> S.ID_NUMBER
    OR (T.ID_Number IS NULL AND S.ID_NUMBER IS NOT NULL)
    OR (T.ID_Number IS NOT NULL AND S.ID_NUMBER IS NULL);

Given I suspect you have simplified your actual use-case you might find that EXCEPT can be used in your situation as EXCEPT (and INTERSECT) perform a different type of compare when it comes to NULLs. See here for more.


问:
Considering authentication when using Ajax with Spring MVC
I am trying to use ajax in my spring mvc application. When I try a url (post/get) which is secured and needs authentication, the response is the html of login page as it is redirected behind the scenes.
What is the best approach to overcome this issue?</p>

答:
First, I would avoid displaying Ajax links to URLs needing authentication if the user is not authenticated, if possible.

If not always possible, your login page could be returned with a specific HTTP response code, (or any other way to distinguish it from a normal response) and your JavaScript callback could replace the entire body of the current page with the HTML received if this response code is received. Most AJAX libraries come with a way to define a handler to all the AJAX requests. Such a global handler could be used here.

The login page could also be adapted to only return a status code in case of an AJAX request, and the JavaScript code would then redirect to the login page (without using AJAX) if this status code is received.


问:
Is it possible to have flexible decimal_places for a model in django?
I am working in a model that i would like to use for diferent kinds of investmensts. So i am wondering if is it possíble to have flexible decimals.

For example:

This is the class

```<code>class Asset(models.Model):
    portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, default=1)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    shares_amount = models.DecimalField(max_digits=18, decimal_places=0, default=0)
    share_cost = models.DecimalField(max_digits=18, decimal_places=0, default=0)
</code>```

If i leave it blank i get the error: "DecimalFields must define a 'decimal_places' attribute."

Maybe what i am trying is not possíble, probably i need to find another solution. I am open to suggestions

I would like to know if is possíble to have this decimal places fleixible.

答:
Not sure if it is feasible to achieve what you described using a single field.
Django maps model structure to the corresponding table in the database and the exact storage implementation there might vary depending on the database type you are using. That said shares_amount field type will remain constant and could be changed only through the migration.
https://docs.djangoproject.com/en/4.0/ref/models/fields/#decimalfield

As an alternative, you could think of using a slightly different approach on how to store information. For example, have two nullable fields and fill for each category type with correct validation depending on the type. Or have a single field with the maximum possible number of the decimal places and round them to the desired precision where it is required.

Body:
I am working in a model that i would like to use for diferent kinds of investmensts. So i am wondering if is it possíble to have flexible decimals.

For example:

This is the class

class Asset(models.Model):
    portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, default=1)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    shares_amount = models.DecimalField(max_digits=18, decimal_places=0, default=0)
    share_cost = models.DecimalField(max_digits=18, decimal_places=0, default=0)

If i leave it blank i get the error: "DecimalFields must define a 'decimal_places' attribute."

Maybe what i am trying is not possíble, probably i need to find another solution. I am open to suggestions

I would like to know if is possíble to have this decimal places fleixible.