问:
How to have different filters for different request paths on spring security?
I have two filters and I want to apply one on "/relatorios/**" and another for the rest.

How to do it?

Here is my (not working) version:

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.antMatcher("/relatorios/**")
                    .csrf()
                    .disable()
                    .sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                    .and()
                    .addFilter(relatoriosFilter)
                    .addFilterBefore(new ExceptionTranslationFilter(new Http403ForbiddenEntryPoint()),
                                     relatoriosFilter.getClass())
                    .authorizeRequests()
                    .and()
                    .antMatcher("/**")
                    .csrf()
                    .disable()
                    .sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                    .and()
                    .addFilter(authHeaderTokenFilter)
                    .addFilterBefore(new ExceptionTranslationFilter(new Http403ForbiddenEntryPoint()),
                                     authHeaderTokenFilter.getClass())
                    .authorizeRequests()
                    .anyRequest()
                    .authenticated();
    }
```

UPDATE:

With this version, when I call any request path, both filters are called. I want "/relatorios/**" to call one filter and everything else to call another filter.

答:
Here are two ways to define the URL paths that filters are applied on.

Firstly, you should be aware that creating a bean of a filter class implementing the Filter interface, the filter is then automatically registered to all endpoints. Since you are trying to achieve different filters for different paths, remove this if you are doing so in your code.

Now you may register your filters in one of the two following methods.

Method 1 - Register Filters with FilterRegistrationBean

In this method, your defined security chain should not define your customer filters, so remove both the addFilter methods from there. You will be setting the paths not via the chain, but rather via registration beans.

```<code>@Configuration
public class FilterConfiguration {

    @Bean
    public FilterRegistrationBean<RelatoriosFilter> relatoriosFilter(){
        FilterRegistrationBean<RelatoriosFilter> registrationBean
                = new FilterRegistrationBean<>();

        registrationBean.setFilter(new RelatoriosFilter());
        registrationBean.addUrlPattern("/relatorios/*");
        registrationBean.setOrder(ORDERED.HIGHEST_PRECEDENCE);

        return registrationBean;
    }

    @Bean
    public FilterRegistrationBean<AuthHeaderTokenFilter> filter2(){
        FilterRegistrationBean<AuthHeaderTokenFilter> registrationBean
                = new FilterRegistrationBean<>();

        registrationBean.setFilter(new AuthHeaderTokenFilter());
        registrationBean.addUrlPattern("/*");
        registrationBean.setOrder(ORDERED.HIGHEST_PRECEDENCE);

        return registrationBean;
    }

}
</code>```

In this manner, you should also control the order of filters by calling setOrder method and giving a lower number for a higher precedence in the filtering chain. The necessary order will depend on the version of Spring you are using and in which part of the chain you are interested to inject in the chain. In my example, it will be the first filter.

Method 2 - Splitting the WebSecurityConfigurerAdapter configurations

A WebSecurityConfigurerAdapter chain cannot define two different filter configurations by path matching. This is one of various limitations of this chain.

This can be solved easily by creating an additional configuration, so that each configuration matches a different path and applies a different filter. You will end up with two configurations.

Configuration 1

```<code>@Configuration
@Order(1)
public class RelatoriosSecurity extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .authorizeRequests()
                .and()
                .antMatcher("/relatorios/**")
                .addFilterBefore(new RelatoriosFilter(), ChannelProcessingFilter.class)
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests().anyRequest().authenticated();
    }

}
</code>```

Configuration 2

```<code>@Configuration
@Order(2)
public class GeneralSecurity extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .antMatcher("/**")
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .addFilterBefore(new AuthHeaderTokenFilter(), ChannelProcessingFilter.class)
                .authorizeRequests().anyRequest().authenticated();
    }

}
</code>```

In this method, @Order annotation defines the order of execution of the chains, so much like your original solution, the RelatoriosSecurity chain will be executed before GeneralSecurity chain.
Also, the addFilterBefore will define before which filter the supplied filter will run. The class of the of the filter to come before will depend on your Spring version, but in mine ChannelProcessingFilter is the first, therefore our supplied filter will be executed first, before ChannelProcessingFilter.

Body:
I have two filters and I want to apply one on "/relatorios/**" and another for the rest.

How to do it?

Here is my (not working) version:

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.antMatcher("/relatorios/**")
                    .csrf()
                    .disable()
                    .sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                    .and()
                    .addFilter(relatoriosFilter)
                    .addFilterBefore(new ExceptionTranslationFilter(new Http403ForbiddenEntryPoint()),
                                     relatoriosFilter.getClass())
                    .authorizeRequests()
                    .and()
                    .antMatcher("/**")
                    .csrf()
                    .disable()
                    .sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                    .and()
                    .addFilter(authHeaderTokenFilter)
                    .addFilterBefore(new ExceptionTranslationFilter(new Http403ForbiddenEntryPoint()),
                                     authHeaderTokenFilter.getClass())
                    .authorizeRequests()
                    .anyRequest()
                    .authenticated();
    }

UPDATE:

With this version, when I call any request path, both filters are called. I want "/relatorios/**" to call one filter and everything else to call another filter.

Body:
Here are two ways to define the URL paths that filters are applied on.

Firstly, you should be aware that creating a bean of a filter class implementing the Filter interface, the filter is then automatically registered to all endpoints. Since you are trying to achieve different filters for different paths, remove this if you are doing so in your code.

Now you may register your filters in one of the two following methods.

Method 1 - Register Filters with FilterRegistrationBean

In this method, your defined security chain should not define your customer filters, so remove both the addFilter methods from there. You will be setting the paths not via the chain, but rather via registration beans.

@Configuration
public class FilterConfiguration {

    @Bean
    public FilterRegistrationBean<RelatoriosFilter> relatoriosFilter(){
        FilterRegistrationBean<RelatoriosFilter> registrationBean
                = new FilterRegistrationBean<>();

        registrationBean.setFilter(new RelatoriosFilter());
        registrationBean.addUrlPattern("/relatorios/*");
        registrationBean.setOrder(ORDERED.HIGHEST_PRECEDENCE);

        return registrationBean;
    }

    @Bean
    public FilterRegistrationBean<AuthHeaderTokenFilter> filter2(){
        FilterRegistrationBean<AuthHeaderTokenFilter> registrationBean
                = new FilterRegistrationBean<>();

        registrationBean.setFilter(new AuthHeaderTokenFilter());
        registrationBean.addUrlPattern("/*");
        registrationBean.setOrder(ORDERED.HIGHEST_PRECEDENCE);

        return registrationBean;
    }

}

In this manner, you should also control the order of filters by calling setOrder method and giving a lower number for a higher precedence in the filtering chain. The necessary order will depend on the version of Spring you are using and in which part of the chain you are interested to inject in the chain. In my example, it will be the first filter.

Method 2 - Splitting the WebSecurityConfigurerAdapter configurations

A WebSecurityConfigurerAdapter chain cannot define two different filter configurations by path matching. This is one of various limitations of this chain.

This can be solved easily by creating an additional configuration, so that each configuration matches a different path and applies a different filter. You will end up with two configurations.

Configuration 1

@Configuration
@Order(1)
public class RelatoriosSecurity extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .authorizeRequests()
                .and()
                .antMatcher("/relatorios/**")
                .addFilterBefore(new RelatoriosFilter(), ChannelProcessingFilter.class)
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests().anyRequest().authenticated();
    }

}

Configuration 2

@Configuration
@Order(2)
public class GeneralSecurity extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .antMatcher("/**")
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .addFilterBefore(new AuthHeaderTokenFilter(), ChannelProcessingFilter.class)
                .authorizeRequests().anyRequest().authenticated();
    }

}

In this method, @Order annotation defines the order of execution of the chains, so much like your original solution, the RelatoriosSecurity chain will be executed before GeneralSecurity chain.
Also, the addFilterBefore will define before which filter the supplied filter will run. The class of the of the filter to come before will depend on your Spring version, but in mine ChannelProcessingFilter is the first, therefore our supplied filter will be executed first, before ChannelProcessingFilter.


来源: stackexchange

问:
Why does visual basic copy a last empty Column when exporting a DataGridView to Clipboard
Thank you for looking at my problem. ^^
I have a small project with a "Copy to Clipboard" button which doesn't work as intended.
I want to copy all 11 Columns and all 10 Rows but it always adds a 12th empty Column, when I subtract a Column from dgvRandom.ColumnCount than the last Column which is supposed to have content is empty. (Picture to clarify - Green is my intention - Red is the actual state) https://i.stack.imgur.com/zvqpr.png
The code I'm referring to is this:

```<code>Private Sub btnExport_Click(sender As Object, e As EventArgs) Handles btnExport.Click
    Dim sb As New StringBuilder

    For row As Integer = 0 To dgvRandom.RowCount - 1
        For col As Integer = 0 To dgvRandom.ColumnCount - 1
            sb.Append(dgvRandom(col, row).Value?.ToString)
            sb.Append(ControlChars.Tab)
        Next
        sb.Append(ControlChars.NewLine)
    Next

    Clipboard.SetDataObject(New DataObject(sb.ToString.Trim))
    MsgBox("Copied to Clipboard", MsgBoxStyle.OkOnly)
End Sub
</code>```

答:
I think it's the final TAB before your line break.  To remove it, try changing

```<code>sb.Append(ControlChars.Tab)
</code>```

to

```<code>If col<dgvRandom.ColumnCount - 1 then sb.Append(ControlChars.Tab)
</code>```

or even

```<code> If col<dgvRandom.ColumnCount - 1 then
    sb.Append(ControlChars.Tab)
 else
    sb.Append(ControlChars.NewLine)
 end if
</code>```

and then delete the sb.Append(ControlChars.NewLine) after the loop

ContentLicense: CC BY-SA 4.0

Body:
Thank you for looking at my problem. ^^
I have a small project with a "Copy to Clipboard" button which doesn't work as intended.
I want to copy all 11 Columns and all 10 Rows but it always adds a 12th empty Column, when I subtract a Column from dgvRandom.ColumnCount than the last Column which is supposed to have content is empty. (Picture to clarify - Green is my intention - Red is the actual state) https://i.stack.imgur.com/zvqpr.png
The code I'm referring to is this:

Private Sub btnExport_Click(sender As Object, e As EventArgs) Handles btnExport.Click
    Dim sb As New StringBuilder

    For row As Integer = 0 To dgvRandom.RowCount - 1
        For col As Integer = 0 To dgvRandom.ColumnCount - 1
            sb.Append(dgvRandom(col, row).Value?.ToString)
            sb.Append(ControlChars.Tab)
        Next
        sb.Append(ControlChars.NewLine)
    Next

    Clipboard.SetDataObject(New DataObject(sb.ToString.Trim))
    MsgBox("Copied to Clipboard", MsgBoxStyle.OkOnly)
End Sub

Body:
I think it's the final TAB before your line break.  To remove it, try changing

sb.Append(ControlChars.Tab)

to

If col<dgvRandom.ColumnCount - 1 then sb.Append(ControlChars.Tab)

or even

 If col<dgvRandom.ColumnCount - 1 then
    sb.Append(ControlChars.Tab)
 else
    sb.Append(ControlChars.NewLine)
 end if

and then delete the sb.Append(ControlChars.NewLine) after the loop


问:
Add/Remove class to child component div from parent component using refs
I want to add/remove class of child component's outer div from Parent Component on click of sidebar menu  button(in parent component).
On click of SidNav toggle button ,expand the nav and add class to the Child Component's outer div so that the content gets pushed to right.

Tried : passing ref as props -  I am getting the reference but actual child dom doesnot update when class applied from Parent Component.

Any suggestions would be helpful.

Snippet :

Parent Component :

```<code>return(<Child ref={this.ref} navigation={navigation} searchParams={parsedQuery} />)
</code>```

child component :

```<code>function render() {
  const { navigation, classlg2, ref } = this.props;
  return (
    <div className="bx--grid page-content--wrapper">
      <div className="bx--row">
        <div
          ref={ref}
          className={
            navigation.length > 0
              ? "bx--col-lg-2 bx--col-lg-14"
              : "bx--col-lg-16"
          }
        >
          {routeComponentsElements}
        </div>
      </div>
    </div>
  );
}
</code>```

bx--col-lg-2 is the class that I need to add and remove on toggle of SideNav.

If states are used to handle the className,then the content rerenders..
Example : there is ajax call in child component, when menubutton is clicked it rerenders the page going back to its home page.

答:
Do something like this.

Parent component

```<code>this.state = {
  childClass: false
}

toggleChildClass = () => {
  this.setState(prevState =>({
    childClass: !prevstate.childClass
  }))
}

render(){
  const {childClass} = this.state;

  return(
    <>
        <button onClick={this.toggleChildClass}>Toggle Class</button>
        <ChildComponent childClass={childClass} />
    </>
  )
}
</code>```

Child Component

```<code>render(){
    const { childClass } = this.props;
    return(
        <div
            className={childClass ? "bx--col-lg-2 bx--col-lg-14"
                                  : 'bx--col-lg-16'}>
          {routeComponentsElements}
        </div>
     )
 }
</code>```

Body:
I want to add/remove class of child component's outer div from Parent Component on click of sidebar menu  button(in parent component).
On click of SidNav toggle button ,expand the nav and add class to the Child Component's outer div so that the content gets pushed to right.

Tried : passing ref as props -  I am getting the reference but actual child dom doesnot update when class applied from Parent Component.

Any suggestions would be helpful.

Snippet :

Parent Component :

return(<Child ref={this.ref} navigation={navigation} searchParams={parsedQuery} />)

child component :

function render() {
  const { navigation, classlg2, ref } = this.props;
  return (

 0
              ? "bx--col-lg-2 bx--col-lg-14"
              : "bx--col-lg-16"
          }
        >
          {routeComponentsElements}

  );
}

bx--col-lg-2 is the class that I need to add and remove on toggle of SideNav.

If states are used to handle the className,then the content rerenders..
Example : there is ajax call in child component, when menubutton is clicked it rerenders the page going back to its home page.

Body:
Do something like this.

Parent component

this.state = {
  childClass: false
}

toggleChildClass = () => {
  this.setState(prevState =>({
    childClass: !prevstate.childClass
  }))
}

render(){
  const {childClass} = this.state;

  return(
    <>
        <button onClick={this.toggleChildClass}>Toggle Class</button>
        <ChildComponent childClass={childClass} />
    </>
  )
}

Child Component

render(){
    const { childClass } = this.props;
    return(
        <div
            className={childClass ? "bx--col-lg-2 bx--col-lg-14"
                                  : 'bx--col-lg-16'}>
          {routeComponentsElements}
        </div>
     )
 }


问:
Prevent calling a function more than once if the parameters have been used before
I would like a way to limit the calling of a function to once per values of parameters.

For example

```<code>def unique_func(x):
    return x

>>> unique_func([1])
[1]
>>> unique_func([1])
*** wont return anything ***
>>> unique_func([2])
[2]
</code>```

Any suggestions? I've looked into using memoization but not established a solution just yet.

This is not solved by the suggested Prevent a function from being called twice in a row since that only solves when the previous func call had them parameters.

答:
Memoization uses a mapping of arguments to return values. Here, you just want a mapping of arguments to None, which can be handled with a simple set.

```<code>def idempotize(f):
    cache = set()
    def _(x):
        if x in cache:
            return
        cache.add(x)
        return f(x)
    return _

@idempotize
def unique_fun(x):
    ...
</code>```

With some care, this can be generalized to handle functions with multiple arguments, as long as they are hashable.

```<code>def idempotize(f):
    cache = set()
    def _(*args, **kwargs):
        k = (args, frozenset(kwargs.items()))
        if k in cache:
            return
        return f(*args, **kwargs)
    return _
</code>```

Body:
I would like a way to limit the calling of a function to once per values of parameters.

For example

def unique_func(x):
    return x

>>> unique_func([1])
[1]
>>> unique_func([1])
*** wont return anything ***
>>> unique_func([2])
[2]

Any suggestions? I've looked into using memoization but not established a solution just yet.

This is not solved by the suggested Prevent a function from being called twice in a row since that only solves when the previous func call had them parameters.

Body:
Memoization uses a mapping of arguments to return values. Here, you just want a mapping of arguments to None, which can be handled with a simple set.

def idempotize(f):
    cache = set()
    def _(x):
        if x in cache:
            return
        cache.add(x)
        return f(x)
    return _

@idempotize
def unique_fun(x):
    ...

With some care, this can be generalized to handle functions with multiple arguments, as long as they are hashable.

def idempotize(f):
    cache = set()
    def _(*args, **kwargs):
        k = (args, frozenset(kwargs.items()))
        if k in cache:
            return
        return f(*args, **kwargs)
    return _


问:
Move a column based in his colname after a column based in his colname in R
I would like to be able to move columns to some desired position based solely on the name of the columns, I would like to move a column by name to the desired position after a column with a defined name.

You could use the data iris as an example.

Example:

```<code>data(iris)
</code>```

Actual columns order:

```<code>> colnames(iris)
[1] "Sepal.Length" "Sepal.Width"  "Petal.Length" "Petal.Width"  "Species"
</code>```

i would like to put "Petal.Width" after "Sepal.Length" by colnames using code and avoid putting manual inputs like selecting solutions with dplyr.

Thank you very much in advance.

答:
If I understand you correctly, you can achieve what you want using select, by manipulating the vector of column names.

First you need a function that takes a vector of names (assumed to be unique), and two specific entries a and b and move a behind b. I think this function does the trick (even if it is a little clumsy looking).

```<code>move <- function(names, a, b) {
  names_without_a <- names[which(names != a)]
  b_pos <- which(names_without_a == b)
  c(names_without_a[1:b_pos],
    a,
    names_without_a[(b_pos+1):length(names_without_a)])
}
</code>```

Now you can use select, like so

```<code>df <-
  iris %>%
  select(move(colnames(iris), 'Petal.Width', 'Sepal.Length'))
</code>```

Body:
I would like to be able to move columns to some desired position based solely on the name of the columns, I would like to move a column by name to the desired position after a column with a defined name.

You could use the data iris as an example.

Example:

data(iris)

Actual columns order:

> colnames(iris)
[1] "Sepal.Length" "Sepal.Width"  "Petal.Length" "Petal.Width"  "Species"

i would like to put "Petal.Width" after "Sepal.Length" by colnames using code and avoid putting manual inputs like selecting solutions with dplyr.

Thank you very much in advance.

Body:
If I understand you correctly, you can achieve what you want using select, by manipulating the vector of column names.

First you need a function that takes a vector of names (assumed to be unique), and two specific entries a and b and move a behind b. I think this function does the trick (even if it is a little clumsy looking).

move <- function(names, a, b) {
  names_without_a <- names[which(names != a)]
  b_pos <- which(names_without_a == b)
  c(names_without_a[1:b_pos],
    a,
    names_without_a[(b_pos+1):length(names_without_a)])
}

Now you can use select, like so

df <-
  iris %>%
  select(move(colnames(iris), 'Petal.Width', 'Sepal.Length'))


答:
So far you've managed to create a string array $output2 with all the space-separated string values from the json document - so far, so good!

We can now split the two "columns" into separate strings with the -split operator:

```<code>$results = $output2 |ForEach-Object {
    $ts,$value = -split $_

    [pscustomobject]@{
        TIMESTAMP = $ts
        VALUE = $value
    }
}
</code>```

Now we've got an array of objects with the two values separated into appropriately named properties TIMESTAMP and VALUE, we can use Export-Csv:

```<code>$results |Export-Csv .\results.csv -NoTypeInformation
</code>```

Title: Convert JSON to Csv columns in Powershell

Body:
I would like to convert my JSON into the below CSV output. I'm struggling to parse the "results" data into two columns.

CSV output:

TIMESTAMP, VALUE,
1581292800000, 270,
1581292860000, 347

My JSON output is as follows:

$JSON =
        {
        "value":  [
                      {
                          "fields":  [
                                         "@{label=DateTime; field=eventTimestamp; type=date; aggregation=series}",
                                         "@{label=Count; field=metrics.End User Response Time (ms); type=integer; aggregation=count}"
                                     ],
                          "results":  [
                                          "1581292800000 270",
                                          "1581292860000 347",
                                          "1581292920000 348",
                                          "1581292980000 401",
                                          "1581293040000 435",
                                          "1581293100000 413",
                                          "1581293160000 466",
                                          "1581293220000 445",
                                          "1581293280000 450",
                                          "1581293340000 488",
                                          "1581293400000 470",
                                          "1581293460000 450",
                                          "1581293520000 440",
                                          "1581293580000 435",
                                          "1581293640000 403",
                                          "1581293700000 472",
                                          "1581293760000 392",
                                          "1581293820000 398",
                                          "1581293880000 357",
                                          "1581293940000 356",
                                          "1581294000000 361",
                                          "1581294060000 339",
                                          "1581294120000 373",
                                          "1581294180000 340",
                                          "1581294240000 329",
                                          "1581294300000 327",
                                          "1581294360000 307",
                                          "1581294420000 282",
                                          "1581294480000 315"
                                      ],
                          "moreData":  false,
                          "schema":  "browserrecord"
                      }
                  ],
        "Count":  1
    }

The following code extracts the results, however the TIMESTAMP and VALUE are both in the same column.

$Output1 = ConvertTo-Json $JSON
$Output2 = ConvertFrom-Json $Outage2 | Select -ExpandProperty 'value' |  Select -ExpandProperty 'results'

Any help would be much appreciated.

Cheers!

Body:
So far you've managed to create a string array $output2 with all the space-separated string values from the json document - so far, so good!

We can now split the two "columns" into separate strings with the -split operator:

$results = $output2 |ForEach-Object {
    $ts,$value = -split $_

    [pscustomobject]@{
        TIMESTAMP = $ts
        VALUE = $value
    }
}

Now we've got an array of objects with the two values separated into appropriately named properties TIMESTAMP and VALUE, we can use Export-Csv:

$results |Export-Csv .\results.csv -NoTypeInformation


问:
Fire JS after functions in loop when other function is complete
I have this function function copy(){ // do some stuff }, this function is triggerd by

```<code><input type="text" id="calc_inkoop_std" name="calc_inkoop_std" value="" onkeyup="copy()">
</code>```

After this function I need to have another function triggerd, but since this is an loop I can't just simple use validate(selectVeld, nr)

How can I run through all lines of function validate(selectVeld, nr) { // do some stuff }

Complete JS

```<code>    function copy()
    {
        // Kopieer materiaalkosten
        var i, totaal = 0;
        var elems = document.getElementsByName('calc_inkoop_std_copy[]');
        var l = elems.length;
        for(i=0; i<l; i++)
        {
            elems[i].value = document.getElementById('calc_inkoop_std').value;
        }

        validate();
    }

    function validate(selectVeld, nr)
    {
        // Materiaalkosten
        if(document.getElementById('calc_inkoop['+nr+'][]').value > 0)
        {
            document.getElementById('calc_materiaalkost['+nr+'][]').value  = ((document.getElementById('calc_gewicht_stk['+nr+'][]').value * (document.getElementById('calc_inkoop['+nr+'][]').value / 1000)) * ((document.getElementById('calc_afval_perc['+nr+'][]').value / 100) + (1 * 1))).toFixed( 2 );
        }
        else
        {
            document.getElementById('calc_materiaalkost['+nr+'][]').value  = ((document.getElementById('calc_gewicht_stk['+nr+'][]').value * (document.getElementById('calc_inkoop_std_copy['+nr+'][]').value / 1000)) * ((document.getElementById('calc_afval_perc['+nr+'][]').value / 100) + (1 * 1))).toFixed( 2 );
        }
    }
</code>```

The other JS is triggerd in an loop:

```<code>while($row_table_3 = mysqli_fetch_array($res_table_3)){ $y++;
echo'
      <tr>
        <td>
            <input type="number" id="calc_aantal['.$y.'][]" name="calc_aantal[]" value="" onkeyup="validate(this, '.$y.')">
        </td>
      </tr>';
} echo '
</code>```

If I am using this code only line 5 is updated of validate. But [i] should be the number of the line?

```<code>var i, totaal = 0;
var elems = document.getElementsByName('calc_inkoop_std_copy[]');
var l = elems.length;
for(i=0; i<l; i++)
{
    elems[i].value = document.getElementById('calc_inkoop_std').value;

    validate([i], 5);
}
</code>```

答:
In my HTML structure $y starts at 1 at it's first occurrence.
In the JS loop i starts as 0 at it's first occurrence.

Now I have this solution:

```<code>var i, totaal = 0;
var elems = document.getElementsByName('calc_inkoop_std_copy[]');
var l = elems.length;

var z;
z=0;

for(i=0; i<l; i++)
{
    elems[i].value = document.getElementById('calc_inkoop_std').value;

    z++;
    validate([i], [z]);
}
</code>```

Body:
I have this function function copy(){ // do some stuff }, this function is triggerd by

<input type="text" id="calc_inkoop_std" name="calc_inkoop_std" value="" onkeyup="copy()">

After this function I need to have another function triggerd, but since this is an loop I can't just simple use validate(selectVeld, nr)

How can I run through all lines of function validate(selectVeld, nr) { // do some stuff }

Complete JS

    function copy()
    {
        // Kopieer materiaalkosten
        var i, totaal = 0;
        var elems = document.getElementsByName('calc_inkoop_std_copy[]');
        var l = elems.length;
        for(i=0; i<l; i++)
        {
            elems[i].value = document.getElementById('calc_inkoop_std').value;
        }

        validate();
    }

    function validate(selectVeld, nr)
    {
        // Materiaalkosten
        if(document.getElementById('calc_inkoop['+nr+'][]').value > 0)
        {
            document.getElementById('calc_materiaalkost['+nr+'][]').value  = ((document.getElementById('calc_gewicht_stk['+nr+'][]').value * (document.getElementById('calc_inkoop['+nr+'][]').value / 1000)) * ((document.getElementById('calc_afval_perc['+nr+'][]').value / 100) + (1 * 1))).toFixed( 2 );
        }
        else
        {
            document.getElementById('calc_materiaalkost['+nr+'][]').value  = ((document.getElementById('calc_gewicht_stk['+nr+'][]').value * (document.getElementById('calc_inkoop_std_copy['+nr+'][]').value / 1000)) * ((document.getElementById('calc_afval_perc['+nr+'][]').value / 100) + (1 * 1))).toFixed( 2 );
        }
    }

The other JS is triggerd in an loop:

while($row_table_3 = mysqli_fetch_array($res_table_3)){ $y++;
echo'

            <input type="number" id="calc_aantal['.$y.'][]" name="calc_aantal[]" value="" onkeyup="validate(this, '.$y.')">

';
} echo '

If I am using this code only line 5 is updated of validate. But [i] should be the number of the line?

var i, totaal = 0;
var elems = document.getElementsByName('calc_inkoop_std_copy[]');
var l = elems.length;
for(i=0; i<l; i++)
{
    elems[i].value = document.getElementById('calc_inkoop_std').value;

    validate([i], 5);
}

Body:
In my HTML structure $y starts at 1 at it's first occurrence.
In the JS loop i starts as 0 at it's first occurrence.

Now I have this solution:

var i, totaal = 0;
var elems = document.getElementsByName('calc_inkoop_std_copy[]');
var l = elems.length;

var z;
z=0;

for(i=0; i<l; i++)
{
    elems[i].value = document.getElementById('calc_inkoop_std').value;

    z++;
    validate([i], [z]);
}


问:
Redirect user to original url after login in asp net mvc
i want to redirect original page after login

```<code> public ActionResult UnAuthorize(string ReturnUrl)
            {
                return Redirect("/Account/SignIn?ReturnUrl=" + ReturnUrl);
            }
</code>```

url : http://localhost:18908/Account/SignIn?ReturnUrl=/Customer/Index

```<code> public JsonResult SignIn(SignInModel model, string returnUrl)
        {
            try
            {
  return Redirect(returnUrl);

               }
</code>```

But returnUrl return value of null or empty

答:
```<code>using System;
using System.Web.Mvc;

namespace WebApplication1.Controllers
{
    public class SignInModel
    {
       public string Name { get; set; }
    }

    public class AccountController : Controller
    {
         public ActionResult UnAuthorize(string ReturnUrl)
         {
              return Redirect("/Account/SignIn?ReturnUrl=" + ReturnUrl);
          }

       [HttpGet]
       public ActionResult SignIn(string returnUrl)
       {
           ViewBag.ReturnUrl = returnUrl;
           return View();
       }

        [HttpPost]
        public ActionResult SignIn(SignInModel model, string returnUrl)
        {
            try
            {
                return Redirect(returnUrl);

            }
            catch (Exception ex)
            {
                throw;
            }
        }
    }
}
</code>```

SignIn view

```<code>@model WebApplication1.Controllers.SignInModel

@{
    ViewBag.Title = "View";
}

<h2>View</h2>

@using (Html.BeginForm("SignIn", "Account", new { ReturnUrl = ViewBag.ReturnUrl }))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>SignInModel</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>
</code>```

Customer Index View

```<code>@{
    ViewBag.Title = "Customers";
}

    <h2>Customer</h2>
</code>```

Focus on HttpGet SingIn action and SignIn view.

try: http://localhost:18908/Account/UnAuthorize?ReturnUrl=/Customer/Index

Body:
i want to redirect original page after login

 public ActionResult UnAuthorize(string ReturnUrl)
            {
                return Redirect("/Account/SignIn?ReturnUrl=" + ReturnUrl);
            }

url : http://localhost:18908/Account/SignIn?ReturnUrl=/Customer/Index

 public JsonResult SignIn(SignInModel model, string returnUrl)
        {
            try
            {
  return Redirect(returnUrl);

               }

But returnUrl return value of null or empty

Body:
using System;
using System.Web.Mvc;

namespace WebApplication1.Controllers
{
    public class SignInModel
    {
       public string Name { get; set; }
    }

    public class AccountController : Controller
    {
         public ActionResult UnAuthorize(string ReturnUrl)
         {
              return Redirect("/Account/SignIn?ReturnUrl=" + ReturnUrl);
          }

       [HttpGet]
       public ActionResult SignIn(string returnUrl)
       {
           ViewBag.ReturnUrl = returnUrl;
           return View();
       }

        [HttpPost]
        public ActionResult SignIn(SignInModel model, string returnUrl)
        {
            try
            {
                return Redirect(returnUrl);

            }
            catch (Exception ex)
            {
                throw;
            }
        }
    }
}

SignIn view

@model WebApplication1.Controllers.SignInModel

@{
    ViewBag.Title = "View";
}

<h2>View</h2>

@using (Html.BeginForm("SignIn", "Account", new { ReturnUrl = ViewBag.ReturnUrl }))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>SignInModel</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

Customer Index View

@{
    ViewBag.Title = "Customers";
}

    <h2>Customer</h2>

Focus on HttpGet SingIn action and SignIn view.

try: http://localhost:18908/Account/UnAuthorize?ReturnUrl=/Customer/Index


问:
Supervisor child vs plain spawn_link
I have a hierarchy of processes called "monitor_node". Each of these monitor_nodes is supervised by one supervisor.

Now, each of these nodes may have a complex inner structure. Meaning, it may (or may not) have some subprocesses that are needed for it to operate properly. Example: process sending keep-alive messages. So far I have been using plain spawn_link to create these "internal"
processes.

However, I have realized that spawning them in init function of monitor_node (which is being supervised) sometimes causes this function to fail (and therefore whole supervisor tree fails). My question is: would it be a good solution to attach these internal processes to supervisor tree? I am thinking about changing monitor_node to a supervisor that supervises it's internal processes.

My doubts are:

I would have to supervise quite significant number of very small processes. I am not sure if this is a good practice.

I may not know in advance that given "internal" process is a simple process or has some internal structure (also spawns other processes). If the latter is the case then I probably should attach these "inner-inner" processes to the supervisor tree.

I hope I have not confused you too much. Looking forward for an answer.

EDIT:

A very similar (if not the same) problem is discusses here (3rd post). The solution given is pretty much the same as the one that I  GIVE CRAP ANSWERS gave.

答:
Supervisors:

There is a trick here, which includes the use of two supervisors. Your tree goes like:

```<code>main_sup -> worker
main_sup -> attached_pool_sup

attached_pool_sup -> workers
</code>```

main sup is one_for_all, so if the worker or the pool supervisor dies, then the tree is done for and killed off. The pool supervisor is a simple_one_for_one which are suitable for having hundreds or thousands of workers.

Init:

Don't do too much work in your init callback. The supervisor will wait until the init completes and you can set a timeout (which you can increase in your case) if it takes longer than normal.

A trick is to quickly timeout (return with a timeout of 0 from init) and then handle additional setup in the handle_info timeout callback. That way you won't be stopping up the main supervisor. Beware of races here!

ContentLicense: CC BY-SA 3.0

Title: Supervisor child vs plain spawn_link

Body:
Supervisors:

There is a trick here, which includes the use of two supervisors. Your tree goes like:

main_sup -> worker
main_sup -> attached_pool_sup

attached_pool_sup -> workers

main sup is one_for_all, so if the worker or the pool supervisor dies, then the tree is done for and killed off. The pool supervisor is a simple_one_for_one which are suitable for having hundreds or thousands of workers.

Init:

Don't do too much work in your init callback. The supervisor will wait until the init completes and you can set a timeout (which you can increase in your case) if it takes longer than normal.

A trick is to quickly timeout (return with a timeout of 0 from init) and then handle additional setup in the handle_info timeout callback. That way you won't be stopping up the main supervisor. Beware of races here!


问:
First, second and third element individually with only CSS
I'm looking for a way to target only 1, only 2 and only 3 of a given element - I know there are better ways, but this is more of a challenge to see if it's possible to easily target selectors at such a vague accuracy with only CSS.

```<code><div class="members-of">
    <h4 class="widget-title">Members of</h4>
    <ul>
        <li>
            <img src="image0.png" alt="">
        </li>
    </ul>
    <ul>
        <li>
            <img src="image1.png" alt="">
        </li>
    </ul>
    <ul>
        <li>
            <img src="image3.png" alt="">
        </li>
    </ul>
    <div class="clear"></div>
</div>
</code>```

How would you tackle it with highest efficiency if all you could use was CSS?

```<code>/* Member 1 */
.members-of ul img:first-child {}
/* Member 2 */
.members-of ul img:nth-of-type... {}
/* Member 3 */
.members-of ul img:eq(@_o) {}
</code>```

答:
Have a look at this selector:

/* First 3 span elements */
.members-of ul span:nth-of-type(-n+3) {
   width: 25px;
   height: 25px;
   background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="members-of">
    <h4 class="widget-title">Members of</h4>
    <ul>
        <li>
            <span>span 1</span>
        </li>
    </ul>
    <ul>
        <li>
            <span>span 2</span>
        </li>
    </ul>
    <ul>
        <li>
            <span>span 3</span>
        </li>
    </ul>
    <div class="clear"></div>
</div></code>```

Body:
I'm looking for a way to target only 1, only 2 and only 3 of a given element - I know there are better ways, but this is more of a challenge to see if it's possible to easily target selectors at such a vague accuracy with only CSS.

Members of

How would you tackle it with highest efficiency if all you could use was CSS?

/* Member 1 */
.members-of ul img:first-child {}
/* Member 2 */
.members-of ul img:nth-of-type... {}
/* Member 3 */
.members-of ul img:eq(@_o) {}

Body:
Have a look at this selector:

/* First 3 span elements */
.members-of ul span:nth-of-type(-n+3) {
   width: 25px;
   height: 25px;
   background: red;
}

<div class="members-of">
    <h4 class="widget-title">Members of</h4>
    <ul>
        <li>
            <span>span 1</span>
        </li>
    </ul>
    <ul>
        <li>
            <span>span 2</span>
        </li>
    </ul>
    <ul>
        <li>
            <span>span 3</span>
        </li>
    </ul>
    <div class="clear"></div>
</div>


答:
You may use :nth-of-type (or :nth-child) applied to the lists. In your specific example both the pseudoclasses will work.

.members-of ul:nth-of-type(1) img {
  /* 1st image */
  border: 1px red solid;
}
.members-of ul:nth-of-type(2) img {
  /* 2nd image */
  border: 1px blue solid;
}
.members-of ul:nth-of-type(3) img {
  /* 3rd image */
  border: 1px yellowgreen solid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="members-of">
    <h4 class="widget-title">Members of</h4>
    <ul>
        <li>
            <img src="image0.png" alt="">
        </li>
    </ul>
    <ul>
        <li>
            <img src="image1.png" alt="">
        </li>
    </ul>
    <ul>
        <li>
            <img src="image3.png" alt="">
        </li>
    </ul>
    <div class="clear"></div>
</div></code>```

Title: First, second and third element individually with only CSS

Body:
You may use :nth-of-type (or :nth-child) applied to the lists. In your specific example both the pseudoclasses will work.

.members-of ul:nth-of-type(1) img {
  /* 1st image */
  border: 1px red solid;
}
.members-of ul:nth-of-type(2) img {
  /* 2nd image */
  border: 1px blue solid;
}
.members-of ul:nth-of-type(3) img {
  /* 3rd image */
  border: 1px yellowgreen solid;
}

<div class="members-of">
    <h4 class="widget-title">Members of</h4>
    <ul>
        <li>
            <img src="image0.png" alt="">
        </li>
    </ul>
    <ul>
        <li>
            <img src="image1.png" alt="">
        </li>
    </ul>
    <ul>
        <li>
            <img src="image3.png" alt="">
        </li>
    </ul>
    <div class="clear"></div>
</div>


问:
Strange issue with System.Net.Http 4.2.0.0 not found
I have a strange issue, which drives me crazy…

I have a simple Class Library Project (Full .NET Framework, 4.6.1) with a wrapper class for functionality around Cosmos DB. Therefore I have added the “Microsoft.Azure.DocumentDB” NuGet Package 1.19.1 to this project. Other than that, I have a reference to the “Newtonsoft.Json” NuGet Package 10.0.3, as well as to a couple of "Microsoft.Diagnostics.EventFlow.*" NuGet Packages.

So far, everything compiles without any error.

But as soon as I hit my wrapper class – consumed from a simple Service Fabric Stateless Service (Full .NET Framework 4.6.1) – and try to execute the following line of code:

```<code>_docClient = new DocumentClient(new Uri(cosmosDbEndpointUrl), cosmosDbAuthKey);
</code>```

I get this strange error at runtime:

System.IO.FileNotFoundException occurred   HResult=0x80070002

Message=Could not load file or assembly 'System.Net.Http,
Version=4.2.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or
one of its dependencies. The system cannot find the file specified.

Source=   StackTrace:    at
Microsoft.Azure.Documents.Client.DocumentClient.Initialize(Uri
serviceEndpoint, ConnectionPolicy connectionPolicy, Nullable1 desiredConsistencyLevel)    at Microsoft.Azure.Documents.Client.DocumentClient..ctor(Uri serviceEndpoint, String authKeyOrResourceToken, ConnectionPolicy connectionPolicy, Nullable1 desiredConsistencyLevel)

Inner Exception 1: FileNotFoundException: Could not load file or
assembly 'System.Net.Http, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The
system cannot find the file specified.

I have absolutely no clue, why the System.Net.Http assembly is not found at all – there is even a assembly reference in my class library project to the .Net Framework Assembly “System.Net.Http 4.0.0.0”.

What I also do not understand is, that there is this weird binding redirect to 4.2.0.0 – where is that one coming from?
To get around this one, I tried to add the following redirect to the app.config of the Service Fabric Service (which is consuming the class library):

But still no difference, I still get the error at runtime.

Anybody having a clue? Anybody having seen such issue?

答:
The answer of Andrei U lead to my salvation. However, the reasoning didn't match with my case.
For people who are in the same scenario as me:

It was a runtime error (not build time), where the build succeeded, but would work on one computer, but not the server.
Solution:
- Added System.Net.Http package.
- Rename file: C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.7.2\System.Net.Http.dll (eg rename to: System.Net.Http.dll.BAK) on the build server.

I didn't have and still don't have assembly redirects for this dll

Body:
I have a strange issue, which drives me crazy…

I have a simple Class Library Project (Full .NET Framework, 4.6.1) with a wrapper class for functionality around Cosmos DB. Therefore I have added the “Microsoft.Azure.DocumentDB” NuGet Package 1.19.1 to this project. Other than that, I have a reference to the “Newtonsoft.Json” NuGet Package 10.0.3, as well as to a couple of "Microsoft.Diagnostics.EventFlow.*" NuGet Packages.

So far, everything compiles without any error.

But as soon as I hit my wrapper class – consumed from a simple Service Fabric Stateless Service (Full .NET Framework 4.6.1) – and try to execute the following line of code:

_docClient = new DocumentClient(new Uri(cosmosDbEndpointUrl), cosmosDbAuthKey);

I get this strange error at runtime:

System.IO.FileNotFoundException occurred   HResult=0x80070002

Message=Could not load file or assembly 'System.Net.Http,
Version=4.2.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or
one of its dependencies. The system cannot find the file specified.

Source=   StackTrace:    at
Microsoft.Azure.Documents.Client.DocumentClient.Initialize(Uri
serviceEndpoint, ConnectionPolicy connectionPolicy, Nullable1 desiredConsistencyLevel)    at Microsoft.Azure.Documents.Client.DocumentClient..ctor(Uri serviceEndpoint, String authKeyOrResourceToken, ConnectionPolicy connectionPolicy, Nullable1 desiredConsistencyLevel)

Inner Exception 1: FileNotFoundException: Could not load file or
assembly 'System.Net.Http, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The
system cannot find the file specified.

I have absolutely no clue, why the System.Net.Http assembly is not found at all – there is even a assembly reference in my class library project to the .Net Framework Assembly “System.Net.Http 4.0.0.0”.

What I also do not understand is, that there is this weird binding redirect to 4.2.0.0 – where is that one coming from?
To get around this one, I tried to add the following redirect to the app.config of the Service Fabric Service (which is consuming the class library):

But still no difference, I still get the error at runtime.

Anybody having a clue? Anybody having seen such issue?


问:
Google Cloud Logging Authentication / permissions
I am using the Golang library cloud.google.com/go/logging and want to send runtime logging.

Already have a GOOGLE_APPLICATION_CREDENTIALS .json file - and am using google storage and firebase - so I know the credentials are working.

With logging, I get an error "Error 403: The caller does not have permission, forbidden"

The account in the application credentials is a service account and I have been looking at the IAM permissions.  There is not an obvious permission for logging (there are other stackdriver permissions, for debug, trace etc but these don't seem to work).

So assuming I am in the right place so far - what permissions does the service account need in order to send logging data to stackdriver logging?

答:
If we look at the API for writing entries to a log we find that the IAM permission logging.logEntries.create is required.

A more detailed article can be found at Access control guide.

This describes a variety of roles including:

roles/logging.logWriter


问:
browser specific css attributes
Where can I find a complete "browser specific css attributes" reference?

I mean some attributes such as -moz-border-radius that is just for Firefox or -webkit-min-device-pixel-ratio. These examples work just in a specified web browser. I want a complete reference for these attributes.

答: Check out css3files. It's a site that talks about all popular css3 functions, in what browsers they work and what code you need to use.</p>

Title: browser specific css attributes


问:
Why does itoa expect a signed character instead of an unsigned?
Learning embedded C while working in MPLAB X with a PIC24FJ128GB204.

So far, I've mostly heard that you should use unsigned types as much as possible (especially?) on embedded devices, so I've started to use uint8_t arrays to hold strings. However, if I call itoa from stdlib.h, it expects a pointer to a signed char (int8_t) array:

extern char *    itoa(char * buf, int val, int base);

This is made specifically clear when I try to compile after using itoa on an unsigned array:

```<code>main.c:317:9: warning: pointer targets in passing argument 1 of 'itoa' differ in signedness
c:\program files (x86)\microchip\xc16\v1.36\bin\bin\../..\include/stdlib.h:131:15: note: expected 'char *' but argument is of type 'unsigned char *'
</code>```

Searching for implementations of itoa on other platforms, that seems to be the common case.

Why is that?

(I've also noticed that most implementations expect value/pointer/radix whereas -for some reason- the stdlib.h from Microchip expects the pointer first. It took me a while to realize this.)

答:
So far, I've mostly heard that you should use unsigned types as much
  as possible

Firstly  - it is not the truth at all - you should use the correct type. What is the correct type? It is the type which suits the best your needs. How can I know which type is best for me? That depends what you are use it for. It should have a type to store all possible values your program might want to store in it.

So you should not listen this person anymore.

Body:
Learning embedded C while working in MPLAB X with a PIC24FJ128GB204.

So far, I've mostly heard that you should use unsigned types as much as possible (especially?) on embedded devices, so I've started to use uint8_t arrays to hold strings. However, if I call itoa from stdlib.h, it expects a pointer to a signed char (int8_t) array:

extern char *    itoa(char * buf, int val, int base);

This is made specifically clear when I try to compile after using itoa on an unsigned array:

main.c:317:9: warning: pointer targets in passing argument 1 of 'itoa' differ in signedness
c:\program files (x86)\microchip\xc16\v1.36\bin\bin\../..\include/stdlib.h:131:15: note: expected 'char *' but argument is of type 'unsigned char *'

Searching for implementations of itoa on other platforms, that seems to be the common case.

Why is that?

(I've also noticed that most implementations expect value/pointer/radix whereas -for some reason- the stdlib.h from Microchip expects the pointer first. It took me a while to realize this.)


问:
How to display decimal values in Apex Oracle using PL/SQL Code
I'm trying to display decimal values after the user selects input from a list of values on a drop down table, then divide it with 3 to get the decimal output I want. It's working out well except when for values greater than 30 - it's not providing decimal output.

Here's my code:

```<code>declare

  x number(5);
  y number(5);
  Z float(5);

begin
  x:= :P7_HOURS;--page item with selected value
  y:=3;
  z:=x/y;
  --dbms_output.put_line('Sum is '||z);
return z;
end;
</code>```

答: If it is a display item set it's format mask (item -> appearance -> format mask) so that it displays decimal positions (for example: 999G999G999G999G990D00). If that doesn't work try returning as : return to_char(z, '999G999G999G990D00')</p>

Body:
I'm trying to display decimal values after the user selects input from a list of values on a drop down table, then divide it with 3 to get the decimal output I want. It's working out well except when for values greater than 30 - it's not providing decimal output.

Here's my code:

declare

  x number(5);
  y number(5);
  Z float(5);

begin
  x:= :P7_HOURS;--page item with selected value
  y:=3;
  z:=x/y;
  --dbms_output.put_line('Sum is '||z);
return z;
end;


问:
Is there a way to apply different configmap for each pod generated by damonset?
I am using filebeat as a daemonset and I would like each generated pod to export to a single port for the logstash.

Is there an approach to be used for this?

答:
As you can read here:

A DaemonSet ensures that all (or some) Nodes run a copy of a Pod.

...a copy of Pod based on a single template and this is the reason why you cannot specify different ConfigMaps to be used by different Pods managed by DaemonSet Controller.

As an alternative you can configure many different DaemonSets where each one will be responsible for running copy of a Pod specified in the template only on specific node.

Another alternative is using static pods:

It is possible to create Pods by writing a file to a certain directory
  watched by Kubelet. These are called static pods. Unlike DaemonSet,
  static Pods cannot be managed with kubectl or other Kubernetes API
  clients. Static Pods do not depend on the apiserver, making them
  useful in cluster bootstrapping cases. Also, static Pods may be
  deprecated in the future.

The whole procedure of creation a static Pod is described here.

I hope it helps.


问:
Git commit opens blank text file, for what?
In all the Git tutorials I've read they say that you can do:

```<code>git init
git add .
git commit
</code>```

When I do that I get a big text file opened up. None of the tutorials seem to address this, so I don't know what to do with the file or what to put in it if anything.

答:
The -m option to commit lets you enter a commit message on the command line:

```<code>git commit -m "my first commit"
</code>```

OwnerDisplayName: Alex

LastEditorDisplayName: Baishampayan Ghose

Body:
In all the Git tutorials I've read they say that you can do:

git init
git add .
git commit

When I do that I get a big text file opened up. None of the tutorials seem to address this, so I don't know what to do with the file or what to put in it if anything.

Body:
The -m option to commit lets you enter a commit message on the command line:

git commit -m "my first commit"

OwnerDisplayName: Greg Hewgill

ContentLicense: CC BY-SA 2.5


问:
Batch renaming files with Bash
How can Bash rename a series of packages to remove their version numbers? I've been toying around with both expr and %%, to no avail.

Examples:

Xft2-2.1.13.pkg becomes Xft2.pkg

jasper-1.900.1.pkg becomes jasper.pkg

xorg-libXrandr-1.2.3.pkg becomes xorg-libXrandr.pkg

答:
If all files are in the same directory the sequence

```<code>ls |
sed -n 's/\(.*\)\(-[0-9.]*\.pkg\)/mv "\1\2" "\1.pkg"/p' |
sh
</code>```

will do your job.  The sed command will create a sequence of mv commands, which you can then pipe into the shell.  It's best to first run the pipeline without the trailing | sh so as to verify that the command does what you want.

To recurse through multiple directories use something like

```<code>find . -type f |
sed -n 's/\(.*\)\(-[0-9.]*\.pkg\)/mv "\1\2" "\1.pkg"/p' |
sh
</code>```

Note that in sed the regular expression grouping sequence is brackets preceded by a backslash,  \( and \), rather than single brackets ( and ).

OwnerDisplayName: Nerdling

Title: Batch renaming files with Bash

Body:
If all files are in the same directory the sequence

ls |
sed -n 's/\(.*\)\(-[0-9.]*\.pkg\)/mv "\1\2" "\1.pkg"/p' |
sh

will do your job.  The sed command will create a sequence of mv commands, which you can then pipe into the shell.  It's best to first run the pipeline without the trailing | sh so as to verify that the command does what you want.

To recurse through multiple directories use something like

find . -type f |
sed -n 's/\(.*\)\(-[0-9.]*\.pkg\)/mv "\1\2" "\1.pkg"/p' |
sh

Note that in sed the regular expression grouping sequence is brackets preceded by a backslash,  \( and \), rather than single brackets ( and ).

OwnerDisplayName: Diomidis Spinellis


问:
View Not Updating Immediately From Service with element.classList.add()
I am adding a css class to elements from a service, but the changes do not happen immediately. The changes take about a second to update the view. I need the changes to happen immediately with no delay. I have tried an ApplicaionRef and calling this.applicationRef.tick() in the service, but that did not work. I tried running the service's method in NgZone's this.zone.run, but that also did not work.

```<code>@Component({
  selector: 'calling',
  templateUrl: './calling.component.html',
  styleUrls: ['./calling.component.scss']
})
export class CallingComponent {
 constructor(private hidingService: HidingService) {}

 callHide() {
  this.hidingService.hide();
 }
}
</code>```

```<code>@Injectable({
  providedIn: 'root'
})
export class HidingService {
 constructor() {}

 hide() {
  const elements = document.querySelectorAll('.hideable-field');
  elements.forEach(element => {
    element.classList.add('hide');
  });
 }
}
</code>```

Here's the CSS that's in styles.css (accessible from all components) for reference, but this part is working. Adding this 'hide' class hides the field with this CSS:

```<code>.hideable-field {
  &.hide {
    visibility: hidden !important;
  }
}
</code>```

If I use this hiding logic in the Component, it works. The fields are hidden immediately. If I use this hidden logic in the service it takes a moment.

答:
The solution turned out to be waiting for the UI to be updated before returning. There is a method called requestAnimationFrame() that allows you to do this.</p>

```<code>export class HidingService {
 constructor() {}

 hide(): Observable<{}> {
  const elements = document.querySelectorAll('.hideable-field');
  elements.forEach(element => {
    element.classList.add('hide');
  });

  const subject = new Subject();
  requestAnimationFrame( () => {
    // Fields will hide in this frame
    requestAnimationFrame( () => {
      // Fields are hidden
      subject.next();
    });
  });
  return subject.pipe();
 }
}
</code>```

Body:
I am adding a css class to elements from a service, but the changes do not happen immediately. The changes take about a second to update the view. I need the changes to happen immediately with no delay. I have tried an ApplicaionRef and calling this.applicationRef.tick() in the service, but that did not work. I tried running the service's method in NgZone's this.zone.run, but that also did not work.

@Component({
  selector: 'calling',
  templateUrl: './calling.component.html',
  styleUrls: ['./calling.component.scss']
})
export class CallingComponent {
 constructor(private hidingService: HidingService) {}

 callHide() {
  this.hidingService.hide();
 }
}

@Injectable({
  providedIn: 'root'
})
export class HidingService {
 constructor() {}

 hide() {
  const elements = document.querySelectorAll('.hideable-field');
  elements.forEach(element => {
    element.classList.add('hide');
  });
 }
}

Here's the CSS that's in styles.css (accessible from all components) for reference, but this part is working. Adding this 'hide' class hides the field with this CSS:

.hideable-field {
  &.hide {
    visibility: hidden !important;
  }
}

If I use this hiding logic in the Component, it works. The fields are hidden immediately. If I use this hidden logic in the service it takes a moment.

Body:
The solution turned out to be waiting for the UI to be updated before returning. There is a method called requestAnimationFrame() that allows you to do this.

export class HidingService {
 constructor() {}

 hide(): Observable<{}> {
  const elements = document.querySelectorAll('.hideable-field');
  elements.forEach(element => {
    element.classList.add('hide');
  });

  const subject = new Subject();
  requestAnimationFrame( () => {
    // Fields will hide in this frame
    requestAnimationFrame( () => {
      // Fields are hidden
      subject.next();
    });
  });
  return subject.pipe();
 }
}


问:
how to round up a double value in dart/flutter
Is there anyway to round up a double value?

I want result always rounded up.

```<code>int offSet = (totalRecords / 10).round();
</code>```

答:
Now you have something like you want. I choose sup to 5 to round up, you can change if you want</p>

```<code>num offSet = (totalRecords / 10);
var eval = offSet.toStringAsFixed(1).split('.');
var res =
    int.parse(eval[1]) > 5 ? int.parse(eval[0]) + 1 : int.parse(eval[0]);
print(res);
</code>```

Body:
Is there anyway to round up a double value?

I want result always rounded up.

int offSet = (totalRecords / 10).round();

Body:
Now you have something like you want. I choose sup to 5 to round up, you can change if you want

num offSet = (totalRecords / 10);
var eval = offSet.toStringAsFixed(1).split('.');
var res =
    int.parse(eval[1]) > 5 ? int.parse(eval[0]) + 1 : int.parse(eval[0]);
print(res);


问:
AWS CLI - No JSON object could be decoded
Im using the CLI for AWS to create a cluster and use the parameters from a json file. Here is the CLI command string Im using:

```<code>aws emr create-cluster --name "Big Matrix Re Run 1" --ami-version 3.1.0 --steps file://Segmentgroup1.json --release-label --instance-groups InstanceGroupType=MASTER,InstanceCount=1,InstanceType=m3.xlarge InstanceGroupType=CORE,InstanceCount=2,InstanceType=m3.xlarge --auto-terminate
</code>```

My json file (Segmentgroup1.json) is in the same folder in which Im running the AWS command string from, but I keep getting the following error:

```<code>No JSON object could be decoded
</code>```

Based on what Ive found its not finding the json file. Any ideas?

答:
The problem that you are facing here is because of the way AWS CLI commands are exposed. They can either take JSON (as a string) directly from the command line or as a JSON file.

If you don't explicitly specify your intention by providing the file path in the URI format (prefixed with file://), the command treats the file path itself as a JSON string and gives you this error.

Body:
Im using the CLI for AWS to create a cluster and use the parameters from a json file. Here is the CLI command string Im using:

aws emr create-cluster --name "Big Matrix Re Run 1" --ami-version 3.1.0 --steps file://Segmentgroup1.json --release-label --instance-groups InstanceGroupType=MASTER,InstanceCount=1,InstanceType=m3.xlarge InstanceGroupType=CORE,InstanceCount=2,InstanceType=m3.xlarge --auto-terminate

My json file (Segmentgroup1.json) is in the same folder in which Im running the AWS command string from, but I keep getting the following error:

No JSON object could be decoded

Based on what Ive found its not finding the json file. Any ideas?


问:
Mozilla addon loading too late to block a resource
I'm trying to cancel requests from studio.code.org to www.google.com/jsapi to help page loads go faster. In my locale, google is blocked, but the browser waits for 75 seconds before giving up. I'd like to prevent the delay by blocking the request (and the page seems to work fine without jsapi).

I followed the example from https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest/onBeforeRequest, installed the addon. I included a console.log statement to see that my code is called, but it only shows up after the browser waits another 75 seconds trying to load the resource that I hoped to block.

I'm open to other approaches if this isn't going to work.

manifest.json:

```<code>{
  "manifest_version": 2,
  "name": "cancel-google",
  "version": "1.0",

  "permissions": [
    "webRequest",
    "webRequestBlocking"
  ],

  "content_scripts": [
    {
      "matches": ["https://studio.code.org/*"],
      "js": ["cancel-google.js"]
    }
  ]
}
</code>```

cancel-google.js:

```<code>// match pattern for the URLs to block
var pattern = "*www.google.com/jsapi";
console.log("cancelator script loaded");

// cancel function returns an object
// which contains a property `cancel` set to `true`
function cancel(requestDetails) {
  console.log("Cancelling: " + requestDetails.url);
  return {cancel: true};
}

// add the listener,
// passing the filter argument and "blocking"
browser.webRequest.onBeforeRequest.addListener(
  cancel,
  {urls: [pattern]},
  ["blocking"]
);
</code>```

答:
cancel-google.js should be loaded as a background script, which is true for most of the WebExtension APIs.

```<code>{
    "name": "Your Addon",
    "manifest_version": 2,
    "background": {
        "scripts": ["cancel-google.js"]
    }
}
</code>```

Then it should work.

Body:
I'm trying to cancel requests from studio.code.org to www.google.com/jsapi to help page loads go faster. In my locale, google is blocked, but the browser waits for 75 seconds before giving up. I'd like to prevent the delay by blocking the request (and the page seems to work fine without jsapi).

I followed the example from https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest/onBeforeRequest, installed the addon. I included a console.log statement to see that my code is called, but it only shows up after the browser waits another 75 seconds trying to load the resource that I hoped to block.

I'm open to other approaches if this isn't going to work.

manifest.json:

{
  "manifest_version": 2,
  "name": "cancel-google",
  "version": "1.0",

  "permissions": [
    "webRequest",
    "webRequestBlocking"
  ],

  "content_scripts": [
    {
      "matches": ["https://studio.code.org/*"],
      "js": ["cancel-google.js"]
    }
  ]
}

cancel-google.js:

// match pattern for the URLs to block
var pattern = "*www.google.com/jsapi";
console.log("cancelator script loaded");

// cancel function returns an object
// which contains a property `cancel` set to `true`
function cancel(requestDetails) {
  console.log("Cancelling: " + requestDetails.url);
  return {cancel: true};
}

// add the listener,
// passing the filter argument and "blocking"
browser.webRequest.onBeforeRequest.addListener(
  cancel,
  {urls: [pattern]},
  ["blocking"]
);

Body:
cancel-google.js should be loaded as a background script, which is true for most of the WebExtension APIs.

{
    "name": "Your Addon",
    "manifest_version": 2,
    "background": {
        "scripts": ["cancel-google.js"]
    }
}

Then it should work.


问:
Observing database object changes made from the background thread
I've met an issue with observing data in my app.

For the testing purposes, I have an activity with a single text view where I show the user's name. This is the code:

```<code>@Entity(tableName = "User")
data class User(
    var name: String,
    var surname: String,
    @PrimaryKey(autoGenerate = true)
    val internalID: Long = 0)
</code>```

in the dao I've got just one method:

```<code>@Query("SELECT * FROM User WHERE surname LIKE :surname")
abstract suspend fun getUserForSurname(surname: String): User
</code>```

in the activity onCreate's method:

```<code>override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    val binding: ActivityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
    val model = ViewModelProvider(this).get(MainViewModel::class.java)
    binding.viewmodel = model
    model.user.observe(this, Observer {
        binding.textTest.setText(it.name)
    })
}
</code>```

and finally, view model:

```<code>class MainViewModel(application: Application) : AndroidViewModel(application) {

    private val surname = "Doe"
    val user: MutableLiveData<User> = MutableLiveData()
    private val userDao: UserDao =
        MyRoomDatabase.getDatabase(application).clientDao()

    init {
        viewModelScope.launch {
            user.value = userDao.getUserForSurname(surname)
        }
    }
}
</code>```

That specific user's name is changed in the background thread. When I check for the value in db itself, the name is indeed different. After restarting activity, the text view is changed too. In other words: the db value is changed but the observer is never called. I know that I am asking for the value only once during viewmodel's init method and it may be a problem. Is it possible to see the actual change without restarting activity?

答:
I suggest you have a look at this Codelab

Room exposes different wrappers around the returned Entities such as:

RxJava

Flow Coroutines

LiveData

So you can changed your Dao as such:

```<code>@Query("SELECT * FROM User WHERE surname LIKE :surname")
abstract fun getUserForSurname(surname: String): LiveData<User>
</code>```

The above means that any changes to the user entry will emit an observation to the listeners of the LiveData.

ViewModel

```<code>class MainViewModel(application: Application) : AndroidViewModel(application) {

    private val surname = "Doe"
    lateinit val client: LiveData<User>
    private val userDao: UserDao =
        MyRoomDatabase.getDatabase(application).clientDao()

    init {
        viewModelScope.launch {
            user = userDao.getUserForSurname(surname)
        }
    }
}
</code>```

Read more at:
- https://developer.android.com/training/data-storage/room/index.html

Disclaimer: Didn't test the above solution but it should give you an idea.

EDIT: Ideally LiveData should only be used in your view model as they were designed for such cases and not to observe DB transactions. I will suggest to replace the Dao's with Coroutine's Flow and use the extension to convert to LiveData.

Body:
I've met an issue with observing data in my app.

For the testing purposes, I have an activity with a single text view where I show the user's name. This is the code:

@Entity(tableName = "User")
data class User(
    var name: String,
    var surname: String,
    @PrimaryKey(autoGenerate = true)
    val internalID: Long = 0)

in the dao I've got just one method:

@Query("SELECT * FROM User WHERE surname LIKE :surname")
abstract suspend fun getUserForSurname(surname: String): User

in the activity onCreate's method:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    val binding: ActivityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
    val model = ViewModelProvider(this).get(MainViewModel::class.java)
    binding.viewmodel = model
    model.user.observe(this, Observer {
        binding.textTest.setText(it.name)
    })
}

and finally, view model:

class MainViewModel(application: Application) : AndroidViewModel(application) {

    private val surname = "Doe"
    val user: MutableLiveData<User> = MutableLiveData()
    private val userDao: UserDao =
        MyRoomDatabase.getDatabase(application).clientDao()

    init {
        viewModelScope.launch {
            user.value = userDao.getUserForSurname(surname)
        }
    }
}

That specific user's name is changed in the background thread. When I check for the value in db itself, the name is indeed different. After restarting activity, the text view is changed too. In other words: the db value is changed but the observer is never called. I know that I am asking for the value only once during viewmodel's init method and it may be a problem. Is it possible to see the actual change without restarting activity?

Body:
I suggest you have a look at this Codelab

Room exposes different wrappers around the returned Entities such as:

RxJava

Flow Coroutines

LiveData

So you can changed your Dao as such:

@Query("SELECT * FROM User WHERE surname LIKE :surname")
abstract fun getUserForSurname(surname: String): LiveData<User>

The above means that any changes to the user entry will emit an observation to the listeners of the LiveData.

ViewModel

class MainViewModel(application: Application) : AndroidViewModel(application) {

    private val surname = "Doe"
    lateinit val client: LiveData<User>
    private val userDao: UserDao =
        MyRoomDatabase.getDatabase(application).clientDao()

    init {
        viewModelScope.launch {
            user = userDao.getUserForSurname(surname)
        }
    }
}

Read more at:
- https://developer.android.com/training/data-storage/room/index.html

Disclaimer: Didn't test the above solution but it should give you an idea.

EDIT: Ideally LiveData should only be used in your view model as they were designed for such cases and not to observe DB transactions. I will suggest to replace the Dao's with Coroutine's Flow and use the extension to convert to LiveData.


问:
Angular Material Dialog closes immediately
I try to open a Angular Material dialog from my component. But the dialog closes immediately after it opens.

I know there are some similar questions on Stackoverflow, but their answers don't seem to work for me. Not sure if calling the dialog function out of the complete part of the subscription is the problem.

ExampleDialogComponent.ts

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

  inputVal1: string;
  inputVal2: string;

  constructor(public dialogRef: MatDialogRef<ExampleDialogComponent>,
              @Inject(MAT_DIALOG_DATA) public data: any, private formBuilder: FormBuilder) {
    this.inputVal1 = data.inputVal1;
    this.inputVal2 = data.inputVal2;
  }

  ngOnInit() {
    this.firstFormGroup = this.formBuilder.group({
      firstCtrl: ['', Validators.required]
    });
    this.secondFormGroup = this.formBuilder.group({
      secondCtrl: ['', Validators.required]
    });
  }

  onCloseConfirm() {
    setTimeout(() => {
      this.dialogRef.close({
      message: 'Confirm',
      outputVal1: this.inputVal1,
      outputVal2: this.inputVal2,
      });
    }, 0);
  }
}
</code>```

ExampleDialogComponent.html

```<code><mat-step>
      <ng-template matStepLabel>last step</ng-template>
      <mat-dialog-actions>
        <button mat-button [mat-dialog-close]="onCloseConfirm()">add</button>
        <button mat-button mat-dialog-close>close</button>
      </mat-dialog-actions>
</mat-step>
</code>```

MainCompontent.ts

```<code>openModal() {
    this.inputs = [];
    this.http.getInputs().subscribe(
      data => {
        data.forEach(element => this.inputs.push(element));
      },
      (err) => {
        console.log(err);
      },
      () => {
        this.openAddDialog();
      });
  }

  openAddDialog() {
    const dialogConfig = new MatDialogConfig();

    dialogConfig.disableClose = true;
    dialogConfig.autoFocus = true;
    dialogConfig.data = {
      inputValue1: 'test 1',
      inputValue2: 'test 2',
    };

    const dialogRef = this.dialog.open(ExampleDialogComponent, dialogConfig);

    dialogRef.afterClosed().subscribe(result => {
      console.log('Dialog was closed');
      console.log('result: ' + result);

      this.http.createResultinDB(result);
        .subscribe(subData => console.log(subData), error => console.log(error));
    });
  }

  getDeliveryPackageList(): Observable<any> {
    return this.http.get(`${this.baseUrl}`);
  }
</code>```

Thanks a lot for your help.

答:
This line is causing the issue:

```<code><button mat-button [mat-dialog-close]="onCloseConfirm()">add</button>
</code>```

The onCloseConfirm function is getting called immediately when the dialog opens, because of how angular binding works.

You have a couple options. You can use a click handler on the button to call your function:

```<code><button mat-button (click)="onCloseConfirm()">add</button>
</code>```

You or you can continue using [mat-dialog-close], and not use your onCloseConfirm function:

```<code><button mat-button [mat-dialog-close]="[inputVal1, inputVal2]">add</button>
</code>```

Body:
I try to open a Angular Material dialog from my component. But the dialog closes immediately after it opens.

I know there are some similar questions on Stackoverflow, but their answers don't seem to work for me. Not sure if calling the dialog function out of the complete part of the subscription is the problem.

ExampleDialogComponent.ts

export class ExampleDialogComponent implements OnInit {

  inputVal1: string;
  inputVal2: string;

  constructor(public dialogRef: MatDialogRef<ExampleDialogComponent>,
              @Inject(MAT_DIALOG_DATA) public data: any, private formBuilder: FormBuilder) {
    this.inputVal1 = data.inputVal1;
    this.inputVal2 = data.inputVal2;
  }

  ngOnInit() {
    this.firstFormGroup = this.formBuilder.group({
      firstCtrl: ['', Validators.required]
    });
    this.secondFormGroup = this.formBuilder.group({
      secondCtrl: ['', Validators.required]
    });
  }

  onCloseConfirm() {
    setTimeout(() => {
      this.dialogRef.close({
      message: 'Confirm',
      outputVal1: this.inputVal1,
      outputVal2: this.inputVal2,
      });
    }, 0);
  }
}

ExampleDialogComponent.html

<mat-step>
      <ng-template matStepLabel>last step</ng-template>
      <mat-dialog-actions>
        <button mat-button [mat-dialog-close]="onCloseConfirm()">add</button>
        <button mat-button mat-dialog-close>close</button>
      </mat-dialog-actions>
</mat-step>

MainCompontent.ts

openModal() {
    this.inputs = [];
    this.http.getInputs().subscribe(
      data => {
        data.forEach(element => this.inputs.push(element));
      },
      (err) => {
        console.log(err);
      },
      () => {
        this.openAddDialog();
      });
  }

  openAddDialog() {
    const dialogConfig = new MatDialogConfig();

    dialogConfig.disableClose = true;
    dialogConfig.autoFocus = true;
    dialogConfig.data = {
      inputValue1: 'test 1',
      inputValue2: 'test 2',
    };

    const dialogRef = this.dialog.open(ExampleDialogComponent, dialogConfig);

    dialogRef.afterClosed().subscribe(result => {
      console.log('Dialog was closed');
      console.log('result: ' + result);

      this.http.createResultinDB(result);
        .subscribe(subData => console.log(subData), error => console.log(error));
    });
  }

  getDeliveryPackageList(): Observable<any> {
    return this.http.get(`${this.baseUrl}`);
  }

Thanks a lot for your help.

Body:
This line is causing the issue:

<button mat-button [mat-dialog-close]="onCloseConfirm()">add</button>

The onCloseConfirm function is getting called immediately when the dialog opens, because of how angular binding works.

You have a couple options. You can use a click handler on the button to call your function:

<button mat-button (click)="onCloseConfirm()">add</button>

You or you can continue using [mat-dialog-close], and not use your onCloseConfirm function:

<button mat-button [mat-dialog-close]="[inputVal1, inputVal2]">add</button>


问:
Selenium check element presence if using FindBy annotation
Trying to use the @FindBy annotation my feeling is there is no perfect way to check the presence of an element.

There are similar discussions here or here, but I see only workarounds and nothing like

```<code>@FindBy (id = "abc")
private WebElement TestElement;

if (TestElement.isPresent) {...};
</code>```

I found solutions with @FindBys, but this way I have to implement an additional @FindBys for every element I would check the presence within DOM? Not really nice.

Every alternative solution with ExpectedConditions.presenceOf... or anything using FindElement needs a locator as parameter instead of a WebElement, correct?

Sure I can build workarounds using e.g. ExpectedConditions.elementToBeClickable(WebElement) within a try/catch and raise an org.junit.jupiter.api.Assertions.fail, but this is not a real DOM check.

To me it seems I'm more flexible with classic By definitions of Page Objects (e.g. private By searchInput = By.xpath("\\input[@class='input_search']");) instead of using @FindBy. Using @FindBy I always deal with the WebElement itself and there is no chance to check the presence before, right?

What are best pratice solutions to check the DOM presence of elements in context of page objects using @FindBy? Or should I stay with By to be safe.

答:
This may not be the best solution but you can use findBy and return a list:

```<code>List<WebElement> TestElement = driver.findElements(By.id(...));
</code>```

and check the size of the list elelement each time (in a while loop) to see if it is not empty.

Body:
Trying to use the @FindBy annotation my feeling is there is no perfect way to check the presence of an element.

There are similar discussions here or here, but I see only workarounds and nothing like

@FindBy (id = "abc")
private WebElement TestElement;

if (TestElement.isPresent) {...};

I found solutions with @FindBys, but this way I have to implement an additional @FindBys for every element I would check the presence within DOM? Not really nice.

Every alternative solution with ExpectedConditions.presenceOf... or anything using FindElement needs a locator as parameter instead of a WebElement, correct?

Sure I can build workarounds using e.g. ExpectedConditions.elementToBeClickable(WebElement) within a try/catch and raise an org.junit.jupiter.api.Assertions.fail, but this is not a real DOM check.

To me it seems I'm more flexible with classic By definitions of Page Objects (e.g. private By searchInput = By.xpath("\\input[@class='input_search']");) instead of using @FindBy. Using @FindBy I always deal with the WebElement itself and there is no chance to check the presence before, right?

What are best pratice solutions to check the DOM presence of elements in context of page objects using @FindBy? Or should I stay with By to be safe.

Body:
This may not be the best solution but you can use findBy and return a list:

List<WebElement> TestElement = driver.findElements(By.id(...));

and check the size of the list elelement each time (in a while loop) to see if it is not empty.


问:
How can we do object filtering in Entity Framework?
When defining an object context, using code first in entity framework, for example:

```<code>public class DomainContext : DbContext
{
    public DomainContext() { }
    public virtual DbSet<News> News { get; set; }
}
</code>```

We all know that you can query "News" doing something like (for example, to get all news that were published today):

```<code>var ctx = new DomainContext();
ctx.News.Where(x => x.PublishedDate == DateTime.Now.Date)
</code>```

But, and this is the question: Is there a way to apply a pre-defined filtering/condition to all queries that pass through ctx.News? Say that I wanted that all queries on ctx.News to have the "Published Today" filtering implicit applied?

答:
There is no way to add automatic condition (filter) to querying news. All posted examples work but only if you query News directly. If you for example loads navigation property pointing to News examples will fail.

EDMX solve this by conditional mapping but this leads to other very bad disadvantages. Conditional mapping is fixed (cannot be changed without rebuilding model) and you can have only single condition for each type - it is like TPH degraded to single entity type. Moreover conditions defined in conditional mapping probably cannot work with "Today". Conditional mapping is not available in code-first approach.

Body:
When defining an object context, using code first in entity framework, for example:

public class DomainContext : DbContext
{
    public DomainContext() { }
    public virtual DbSet<News> News { get; set; }
}

We all know that you can query "News" doing something like (for example, to get all news that were published today):

var ctx = new DomainContext();
ctx.News.Where(x => x.PublishedDate == DateTime.Now.Date)

But, and this is the question: Is there a way to apply a pre-defined filtering/condition to all queries that pass through ctx.News? Say that I wanted that all queries on ctx.News to have the "Published Today" filtering implicit applied?


问:
SlideAnimation Not Starting Again After Calling SetState()
I made a simple class for animating a widget into the screen:

```<code>class CustomSlideAnimation extends StatefulWidget {
  static const String FROM_LEFT = 'FROM_LEFT';
  static const String FROM_RIGHT = 'FROM_RIGHT';
  final String from;
  final Widget child;

  const CustomSlideAnimation(
      {Key key, this.from = FROM_LEFT, @required this.child})
      : super(key: key);

  @override
  _CustomSlideAnimationState createState() => _CustomSlideAnimationState();
}

class _CustomSlideAnimationState extends State<CustomSlideAnimation>
    with SingleTickerProviderStateMixin {
  Animation<Offset> _offsetAnimation;
  AnimationController _animationController;

  @override
  void initState() {
    super.initState();
    _animationController =
        AnimationController(vsync: this, duration: Duration(milliseconds: 300));
    _offsetAnimation = widget.from == CustomSlideAnimation.FROM_LEFT
        ? Tween<Offset>(
            begin: Offset(-1.0, 0.0),
            end: Offset.zero,
          ).animate(CurvedAnimation(
            curve: Curves.linear,
            parent: _animationController,
          ))
        : Tween<Offset>(
            begin: Offset(1.0, 0.0),
            end: Offset.zero,
          ).animate(CurvedAnimation(
            curve: Curves.linear,
            parent: _animationController,
          ));
    _animationController.forward();
  }

  @override
  void dispose() {
    super.dispose();
    _animationController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SlideTransition(
      position: _offsetAnimation,
      child: widget.child,
    );
  }
}
</code>```

And a simple app to demonstrate the problem:

```<code>void main() => runApp(Test());

class Test extends StatefulWidget {
  @override
  _TestState createState() => _TestState();
}

class _TestState extends State<Test> {
  bool widget1 = true;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: widget1
              ? CustomSlideAnimation(
                  child: InkWell(
                    child: Text('widget1'),
                    onTap: () {
                      setState(() {
                        widget1 = false;
                      });
                    },
                  ),
                  from: CustomSlideAnimation.FROM_LEFT,
                )
              : CustomSlideAnimation(
                  child: InkWell(
                    child: Text('widget2'),
                    onTap: () {
                      setState(() {
                        widget1 = true;
                      });
                    },
                  ),
                  from: CustomSlideAnimation.FROM_LEFT,
                ),
        ),
      ),
    );
  }
}
</code>```

When I start the app for first time the Text widget as expected slides in to the screen,
but then I tap it and thus calling setState() the second Text widget just appears suddenly into the screen and no slide transition happens.

I printed the times when build get called in all the classes and I see that setState() is triggering builds in Test and CustomSlideTransition classes but not triggering initState() in the CustomSlideTransition.

EDIT for more clarification: even putting controller.forward() inside the build() method didn't work.

So what am I missing?

答:
I figured it out, the reason is in the keys and widget trees as explained in this video.
When the setState was called without CustomSlideTransition having a unique  key, then the framework did not recreate the State object of this class again and it instead used the State object of the previous widget which had the AnimationStatus as completed

But now with keys each time the framework creates a new State object and calls initState() where the controller is reset and the animation starts normally.

I also found a workaround but I don't know if it is as efficient as the "keys" solution:

Without adding a key to the CustomSlideTransition widget,I can, in the build() method of this widget, do these two commands:

```<code>_animationController.reset();
_animationController.forward();
</code>```

and remove the call to _animationController.forward(); in initState().

Body:
I made a simple class for animating a widget into the screen:

class CustomSlideAnimation extends StatefulWidget {
  static const String FROM_LEFT = 'FROM_LEFT';
  static const String FROM_RIGHT = 'FROM_RIGHT';
  final String from;
  final Widget child;

  const CustomSlideAnimation(
      {Key key, this.from = FROM_LEFT, @required this.child})
      : super(key: key);

  @override
  _CustomSlideAnimationState createState() => _CustomSlideAnimationState();
}

class _CustomSlideAnimationState extends State<CustomSlideAnimation>
    with SingleTickerProviderStateMixin {
  Animation<Offset> _offsetAnimation;
  AnimationController _animationController;

  @override
  void initState() {
    super.initState();
    _animationController =
        AnimationController(vsync: this, duration: Duration(milliseconds: 300));
    _offsetAnimation = widget.from == CustomSlideAnimation.FROM_LEFT
        ? Tween<Offset>(
            begin: Offset(-1.0, 0.0),
            end: Offset.zero,
          ).animate(CurvedAnimation(
            curve: Curves.linear,
            parent: _animationController,
          ))
        : Tween<Offset>(
            begin: Offset(1.0, 0.0),
            end: Offset.zero,
          ).animate(CurvedAnimation(
            curve: Curves.linear,
            parent: _animationController,
          ));
    _animationController.forward();
  }

  @override
  void dispose() {
    super.dispose();
    _animationController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SlideTransition(
      position: _offsetAnimation,
      child: widget.child,
    );
  }
}

And a simple app to demonstrate the problem:

void main() => runApp(Test());

class Test extends StatefulWidget {
  @override
  _TestState createState() => _TestState();
}

class _TestState extends State<Test> {
  bool widget1 = true;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: widget1
              ? CustomSlideAnimation(
                  child: InkWell(
                    child: Text('widget1'),
                    onTap: () {
                      setState(() {
                        widget1 = false;
                      });
                    },
                  ),
                  from: CustomSlideAnimation.FROM_LEFT,
                )
              : CustomSlideAnimation(
                  child: InkWell(
                    child: Text('widget2'),
                    onTap: () {
                      setState(() {
                        widget1 = true;
                      });
                    },
                  ),
                  from: CustomSlideAnimation.FROM_LEFT,
                ),
        ),
      ),
    );
  }
}

When I start the app for first time the Text widget as expected slides in to the screen,
but then I tap it and thus calling setState() the second Text widget just appears suddenly into the screen and no slide transition happens.

I printed the times when build get called in all the classes and I see that setState() is triggering builds in Test and CustomSlideTransition classes but not triggering initState() in the CustomSlideTransition.

EDIT for more clarification: even putting controller.forward() inside the build() method didn't work.

So what am I missing?

Body:
I figured it out, the reason is in the keys and widget trees as explained in this video.
When the setState was called without CustomSlideTransition having a unique  key, then the framework did not recreate the State object of this class again and it instead used the State object of the previous widget which had the AnimationStatus as completed

But now with keys each time the framework creates a new State object and calls initState() where the controller is reset and the animation starts normally.

I also found a workaround but I don't know if it is as efficient as the "keys" solution:

Without adding a key to the CustomSlideTransition widget,I can, in the build() method of this widget, do these two commands:

_animationController.reset();
_animationController.forward();

and remove the call to _animationController.forward(); in initState().


问:
Resolving Git conflicts in Visual Studio to have a commit after a bug at linking source and the server
Suddenly my local git repository bugged in a way that it didn't response to git commands,
So with the help of a great professional here was able to reset, re-link it to the remote address at DevOps server.

Link to the previous topic:
Previous topic

Now having some conflicts when trying to Cherry Commit my local repository changes to its DevOps location.

Used this:

```<code>git cherry-pick theversion
</code>```

now it seems pending.

Please have a look at the below image:

Don't know what should I do now. I want all the current changes and files apply as it is in the local working project.
Blame? Stage? Resolve? Should I select each individually?
If those 14 in the below section are the conflicts, why I cannot point that I want to prioritize everything I have here to the remote version?

Considering this:

Resolve merge conflicts

I know that I didn't do a merge, but why here there is no "Take Source button" like what it said?
It can be a similar situation.

答:
It seems like the commit you are cherry-picking and your local commits have a conflict (you both changed the same files, and git is asking how to handle the conflicts).

If you want to take the changes from the cherry-pick commit, while discarding your changes, run these commands in the command line for all the files:

git checkout --theirs

git add < filename >

After running this for all files, run:

git cherry-pick --continue

Source: checkout cherry pick

Body:
Suddenly my local git repository bugged in a way that it didn't response to git commands,
So with the help of a great professional here was able to reset, re-link it to the remote address at DevOps server.

Link to the previous topic:
Previous topic

Now having some conflicts when trying to Cherry Commit my local repository changes to its DevOps location.

Used this:

git cherry-pick theversion

now it seems pending.

Please have a look at the below image:

Don't know what should I do now. I want all the current changes and files apply as it is in the local working project.
Blame? Stage? Resolve? Should I select each individually?
If those 14 in the below section are the conflicts, why I cannot point that I want to prioritize everything I have here to the remote version?

Considering this:

Resolve merge conflicts

I know that I didn't do a merge, but why here there is no "Take Source button" like what it said?
It can be a similar situation.