问:
Homebrew update failure on mac
Upon doing a brew update, I get the following errors:

```<code>fatal: Unable to find remote helper for 'https'
Error: Fetching /usr/local failed!
fatal: Unable to find remote helper for 'https'
Error: Fetching /usr/local/Library/Taps/caskroom/homebrew-cask failed!
Already up-to-date.
</code>```

答:
I ran into this as well, and for me it was because the repo in question was cloned via ssh, and my private key is password protected.  To fix this I used ssh-agent.

```<code>eval `ssh-agent`

ssh-add
</code>```

Once I added my key and input my password, brew update succeeded.

Title: Homebrew update failure on mac

Body:
Upon doing a brew update, I get the following errors:

fatal: Unable to find remote helper for 'https'
Error: Fetching /usr/local failed!
fatal: Unable to find remote helper for 'https'
Error: Fetching /usr/local/Library/Taps/caskroom/homebrew-cask failed!
Already up-to-date.

Body:
I ran into this as well, and for me it was because the repo in question was cloned via ssh, and my private key is password protected.  To fix this I used ssh-agent.

eval `ssh-agent`

ssh-add

Once I added my key and input my password, brew update succeeded.


来源: stackexchange

问:
Tutorial teaching Ruby syntax/knowledge required to easily learn rails
I am trying to learn ROR these days and have basic knowledge of ruby, but often working with rails, I get to the point where it seems as if I don't know a bit about ruby.

Just to explain the point, in rails we use has_many keyword. I did not learn any such thing when I was going through ruby tutorials but just came to know that it has something to do with meta-programming in ruby (I have no idea what is meta programming).

So I would like to know if there is any book/tutorial which explain all the points/syntax/concepts of ruby, which a newbie would see while programming in rails.

Thanks to "Jonas Elfström", in simple words, what I am looking for is to know "how Rails uses Ruby"

Thanks.

答:
There's a tutorial called Learn Ruby the Hard Way

(written by Rob Sobers of Fog Creek Software)

ContentLicense: CC BY-SA 3.0


问:
Can't add to variable
so I have problem with basics cause my variable when i add 1 or just increment gives back nan I don't really know if it's problem with saving or it just can't add. here is code that contains that variable

let add;

if(localStorage.getItem("add")>=1){
    add=localStorage.getItem("add");
  }
  else {
    add = 1;
    localStorage.setItem("add", add);
  }

  function oncl(){

add = add++;
 localStorage.setItem("add",add);

}```

答:
nan means it is not a number because localStorage.getItem() returns a string not a number so you need to parse it into a number first then you can do numbers operations

if you are using integers use

```<code>parseInt(localStorage.getItem("add"))
//you can also use parseFloat() or Number()
</code>```

ContentLicense: CC BY-SA 4.0

Title: Can't add to variable

Body:
nan means it is not a number because localStorage.getItem() returns a string not a number so you need to parse it into a number first then you can do numbers operations

if you are using integers use

parseInt(localStorage.getItem("add"))
//you can also use parseFloat() or Number()


问:
How to make rainbow csv in vscode ignore some separators?
I have some data items that look like ["A","B"] but rainbow csv extension is color coding the ["A", and "B"] differently because of the comma. How can I stop this from happening?

Thanks

edit: and there are other data points beside each other that look like "C","D" with the "," pattern

答: In the parameters of the application you have choice to add or delete some separator (if I understand the problem correctly)</p>


问:
number orders for each year and Month
the outputhow can i output number orders for each year and Month

I have tried the code but it gives me two columns instead of 4, by each year and month

```<code>select   month (orderdate), year (orderdate)  ,
   count (orderdate) over (partition by year(orderdate) Order By year(orderdate) desc)  as countoforders
   from sales.SalesOrderHeader
   group by  year (orderdate), month (orderdate),orderdate
</code>```

sales.SalesOrderHeader.orderdateoutput

答:
Well I found the answer :</p>
```<code>Select year(o.OrderDate)  as yy , MONTH (o.OrderDate) as MM , count(CustomerID) as count
   from sales.SalesOrderHeader o
   group by year(o.OrderDate), MONTH (o.OrderDate)
   order by yy

Select MM,[2011], [2012], [2013], [2014]
     from (Select year(OrderDate)  as yy , MONTH(OrderDate) as MM , CustomerID
        from sales.SalesOrderHeader) o
        PIVOT(count(CustomerID) for yy in ([2011], [2012], [2013], [2014])) rrr
         order by MM
</code>```

Title: number orders for each year and Month

Body:
the outputhow can i output number orders for each year and Month

I have tried the code but it gives me two columns instead of 4, by each year and month

select   month (orderdate), year (orderdate)  ,
   count (orderdate) over (partition by year(orderdate) Order By year(orderdate) desc)  as countoforders
   from sales.SalesOrderHeader
   group by  year (orderdate), month (orderdate),orderdate

sales.SalesOrderHeader.orderdateoutput

Body:
Well I found the answer :

Select year(o.OrderDate)  as yy , MONTH (o.OrderDate) as MM , count(CustomerID) as count
   from sales.SalesOrderHeader o
   group by year(o.OrderDate), MONTH (o.OrderDate)
   order by yy

Select MM,[2011], [2012], [2013], [2014]
     from (Select year(OrderDate)  as yy , MONTH(OrderDate) as MM , CustomerID
        from sales.SalesOrderHeader) o
        PIVOT(count(CustomerID) for yy in ([2011], [2012], [2013], [2014])) rrr
         order by MM


问:
Inheritance of web component in js files
First component : x-input. A very simple input component who do nothins :

```<code>(function() {
    class XInput extends HTMLElement {
        static get template() {
            const template = document.createElement('template');
            template.innerHTML = `
                <style>
                    :host {
                        display: block;
                    }
                </style>

                <input id="input">
            `;
            return template;
        }

        constructor() {
            super();
            this.attachShadow({mode: 'open'});
            this.shadowRoot.appendChild(XInput.template.content.cloneNode(true));
        }
    }

    window.customElements.define('x-input', XInput);
})();
</code>```

My component is in a .js file so I don't need to use HTML Import in my client page.
Now, I need a second web component who inherit from x-input :

```<code>(function() {
    class XInputNumber extends XInput {

    }

    window.customElements.define('x-input-number', XInputNumber);
})();
</code>```

If I try to use this second element in a page -> Uncaught ReferenceError: XInput is not defined.

```<code><html>
    <head>
        <script src="/bower_components/webcomponentsjs/webcomponents-lite.js"></script>
        <script src="/bower_components/shadydom/shadydom.min.js"></script>

        <script src="/webcomponents/input/x-input.js"></script>
        <script src="/webcomponents/input/x-input-number.js"></script>
    </head>
    <body>
        <p><x-input></x-input></p>
        <p><x-input-number></x-input-number></p>
    </body>
</html>
</code>```

If i write my web components in html files, no problem, but I have to use HTML Imports (I try to do without it).

How can I achieve this ?

答:
```<code>export default class ChildComponent extends ParentComponent {
  constructor() {
    super("child template");
  }

  connectedCallback() {
    super.connectedCallback();
  }
}

customElements.define('x-child', ChildComponent);
</code>```

Parent component:

```<code>export default class ParentComponent {
  constructor(childTemplate) {
    this.appendChild('foo<div class="refChildContent"></div>bar');
    this.childTemplate = childTemplate;
  }

  connectedCallback() {
    this.querySelector('.refChildContent').innerHTML = this.childTemplate;
  }
}

customElements.define('x-parent', ParentComponent);
</code>```

Result:

```<code><x-child>
 foo
 <div class="refChildContent">
    child html
 </div>
 bar
</x-child>
</code>```

Body:
First component : x-input. A very simple input component who do nothins :

(function() {
    class XInput extends HTMLElement {
        static get template() {
            const template = document.createElement('template');
            template.innerHTML = `

                <input id="input">
            `;
            return template;
        }

        constructor() {
            super();
            this.attachShadow({mode: 'open'});
            this.shadowRoot.appendChild(XInput.template.content.cloneNode(true));
        }
    }

    window.customElements.define('x-input', XInput);
})();

My component is in a .js file so I don't need to use HTML Import in my client page.
Now, I need a second web component who inherit from x-input :

(function() {
    class XInputNumber extends XInput {

    }

    window.customElements.define('x-input-number', XInputNumber);
})();

If I try to use this second element in a page -> Uncaught ReferenceError: XInput is not defined.

<x-input></x-input>

<x-input-number></x-input-number>

If i write my web components in html files, no problem, but I have to use HTML Imports (I try to do without it).

How can I achieve this ?

Body:
export default class ChildComponent extends ParentComponent {
  constructor() {
    super("child template");
  }

  connectedCallback() {
    super.connectedCallback();
  }
}

customElements.define('x-child', ChildComponent);

Parent component:

export default class ParentComponent {
  constructor(childTemplate) {
    this.appendChild('foo<div class="refChildContent"></div>bar');
    this.childTemplate = childTemplate;
  }

  connectedCallback() {
    this.querySelector('.refChildContent').innerHTML = this.childTemplate;
  }
}

customElements.define('x-parent', ParentComponent);

Result:

<x-child>
 foo
 <div class="refChildContent">
    child html
 </div>
 bar
</x-child>


问:
In what order does CMake evaluate OR and AND in compound 'if' condition?
The CMake documentation states:

The following syntax applies to the condition argument of the if,
elseif and while() clauses.

Compound conditions are evaluated in the following order of
precedence: Innermost parentheses are evaluated first. Next come unary
tests such as EXISTS, COMMAND, and DEFINED. Then binary tests such as
EQUAL, LESS, LESS_EQUAL, GREATER, GREATER_EQUAL, STREQUAL, STRLESS,
STRLESS_EQUAL, STRGREATER, STRGREATER_EQUAL, VERSION_EQUAL,
VERSION_LESS, VERSION_LESS_EQUAL, VERSION_GREATER,
VERSION_GREATER_EQUAL, and MATCHES. Then the boolean operators in the
order NOT, AND, and finally OR.

But the following prints 'FALSE':

cmake_minimum_required(VERSION 3.22)

project(Test)

if(YES OR NO AND NO)
    message("TRUE")
else()
    message("FALSE")
endif()
```

I'd expect the expression to evaluate as YES OR (NO AND NO). What's going on?

答:
This is unfortunately not a bug in the implementation, but in the documentation. CMake is (mis)designed to evaluate AND and OR at the same precedence, and from left to right.

See the MR that will update the documentation here: https://gitlab.kitware.com/cmake/cmake/-/merge_requests/6970

Body:
The CMake documentation states:

The following syntax applies to the condition argument of the if,
elseif and while() clauses.

Compound conditions are evaluated in the following order of
precedence: Innermost parentheses are evaluated first. Next come unary
tests such as EXISTS, COMMAND, and DEFINED. Then binary tests such as
EQUAL, LESS, LESS_EQUAL, GREATER, GREATER_EQUAL, STREQUAL, STRLESS,
STRLESS_EQUAL, STRGREATER, STRGREATER_EQUAL, VERSION_EQUAL,
VERSION_LESS, VERSION_LESS_EQUAL, VERSION_GREATER,
VERSION_GREATER_EQUAL, and MATCHES. Then the boolean operators in the
order NOT, AND, and finally OR.

But the following prints 'FALSE':

cmake_minimum_required(VERSION 3.22)

project(Test)

if(YES OR NO AND NO)
    message("TRUE")
else()
    message("FALSE")
endif()

I'd expect the expression to evaluate as YES OR (NO AND NO). What's going on?


问:
itext outofmemory error while attempting to count the number of pages in a pdf file
I'm trying to execute the following code:

```<code>PdfReader reader = new PdfReader("/path/to/file.pdf");
int pages = reader.getNumberOfPages();
</code>```

It works on most files, but on one particular file, it crashes with error:

```<code>java.lang.OutOfMemoryError: Java heap space
    at java.util.Arrays.copyOf(Arrays.java:2882)
    at java.lang.AbstractStringBuilder.expandCapacity(AbstractStringBuilder.java:100)
    at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:572)
    at java.lang.StringBuffer.append(StringBuffer.java:320)
    at com.itextpdf.text.pdf.PRTokeniser.readString(PRTokeniser.java:158)
    at com.itextpdf.text.pdf.PRTokeniser.getStartxref(PRTokeniser.java:224)
    at com.itextpdf.text.pdf.PRTokeniser.getStartxref(PRTokeniser.java:229)
    ...goes on for a while
    at com.itextpdf.text.pdf.PRTokeniser.getStartxref(PRTokeniser.java:229)
</code>```

I know that it's something wrong with the input file. I'm just wondering if there's a way of knowing before attempting to make the method call, that the file is going to cause a problem.

答: It turns out it was a bug with the version of itext I am using (5.0.1). I logged a query with the developers, and a fix was put in - that I tested - and which hopefully will find it's way into the next version (5.0.2)</p>

Body:
I'm trying to execute the following code:

PdfReader reader = new PdfReader("/path/to/file.pdf");
int pages = reader.getNumberOfPages();

It works on most files, but on one particular file, it crashes with error:

java.lang.OutOfMemoryError: Java heap space
    at java.util.Arrays.copyOf(Arrays.java:2882)
    at java.lang.AbstractStringBuilder.expandCapacity(AbstractStringBuilder.java:100)
    at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:572)
    at java.lang.StringBuffer.append(StringBuffer.java:320)
    at com.itextpdf.text.pdf.PRTokeniser.readString(PRTokeniser.java:158)
    at com.itextpdf.text.pdf.PRTokeniser.getStartxref(PRTokeniser.java:224)
    at com.itextpdf.text.pdf.PRTokeniser.getStartxref(PRTokeniser.java:229)
    ...goes on for a while
    at com.itextpdf.text.pdf.PRTokeniser.getStartxref(PRTokeniser.java:229)

I know that it's something wrong with the input file. I'm just wondering if there's a way of knowing before attempting to make the method call, that the file is going to cause a problem.


问:
Minimum add to make parentheses string consisting of '{', '}', '[', ']', '(', ')' valid
This problem is an addition to the familiar stack question(https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/) where we have to return the minimum number of additions to make the parentheses string valid. But that question consists of only '(' and ')'. What will happen if we extend that question to other types of parentheses like '[', ']', '{', '}'. I just came across this in a discussion among my friends and need help on how to approach.

For example: [[[{{}]]){)}) -> [[[{{}}]]] (){()}()
in this case answer is 5 additions to make it valid.

I couldn't come up with a proper approach. 2 approaches I considered are:

Similar to normal question, we push the opening types '(', '{', '[' to the stack as we browse through the string and if we find closing type ')', '}', ']' we check the top of the stack, if they both compliment each other, we pop and continue else we increment the counter and continue without popping out. After traversing the string, we output the answer as sum of counter and stack's size. In this approach the above example will not work as that extra '{' will break the approach.

Another approach is similar to above ie. we push the opening type of parentheses and if we find a closing type and if the stack's top compliment it, we pop and continue with the string, else we will pop out till we get a matching string and for every pop we increment the counter. After traversing the string, the total value is sum of counter and stack's size. But that will not work for cases like {{{{]}}}} where the character ']' will pop out everything and it will increase the answer.

I was also thinking of combining these, more like a Dynamic Programming where we will take the maximum of either seeing the top most value or seeing till we get a match in the stack or if stack becomes empty. But I am not sure on whether these 2 are the only cases to consider.

答:
You can do this in O(n^3) time (for any number of bracket types) with dynamic programming. This is not a lower bound on the runtime, but it appears that a greedy approach doesn't work for this problem.

First, it's helpful to realize that the 'minimum additions to balance' is the same as the 'minimum deletions to balance' for any bracket string, since the deletion framework is easier to work with. To see why this is true, consider a minimum set of additions: for every bracket that is now matched but was unmatched before, we could have also deleted that bracket, and vice versa.

The idea is to compute all possible bracket pairs: create a list of all indices [i, j], 0 <= i < j < n,  where s[i] and s[j] are an open and closed bracket pair of the same type. Then, we find the maximum number of intervals [i, j] we can have, such that any two intervals are either nested or disjoint. This is exactly the requirements to be balanced, and, if you're curious, means that we're looking for the maximum size trivially perfect subgraph of the intersection graph formed by our intervals.

There are O(n^2) intervals, so any modification of this approach has an O(n^2) lower bound. We sort these intervals (by start, then by end if tied), and use dynamic programming (DP) to find the maximum number of nested or disjoint intervals we can have.

Our DP equation has 3 parameters: left, right, and min_index. [left, right] is an inclusive range of indices of s we are allowed to use, and min_index is the smallest index (in our interval list) interval we are allowed to use. If we know the leftmost interval that we can feasibly use, say, [start, end], the answer will come from either using or not using this interval. If we don't use it, we get dp(left, right, min_index+1). If we do use the interval, we add the maximum number of intervals we can nest inside (start, end), plus the maximum number of intervals starting strictly after end. This is 1 + dp(start+1, end-1, min_index+1) + dp(end+1, right, min_index+1).

For a fuller definition:

```<code>dp(left, right, min_index) :=
maximum number of intervals from interval_list[min_index:]
that are contained in [left, right] and all pairwise nested or disjoint.

Also, let
first_index := max(smallest index of an interval starting at or after left,
                  min_index)
so that interval_list[first_index] = (first_start, first_end).

dp(left, right, min_index) = 0 if (left > right or first_index >= length(interval_list)),

                             max(dp(left, right, first_index+1),
                                 1
                                 + dp(first_start+1, first_end-1, first_index+1)
                                 + dp(first_end+1, right, first_index+1))

                                 otherwise.
</code>```

Here's a Python implementation of the algorithm:

def balance_multi_string(s: str) -> int:
    """Given a multi-paren string s, return minimum deletions to balance
       it. 'Balanced' means all parentheses are matched, and
       all pairs from different types are either nested or disjoint
       Runs in O(n^3) time.
    """

    open_brackets = {'{', '[', '('}
    closed_brackets = {'}', ']', ')'}
    bracket_partners = {'{': '}', '[': ']', '(': ')',
                        '}': '{', ']': '[', ')': '('}

    n = len(s)

    bracket_type_to_open_locations = collections.defaultdict(list)

    intervals = []

    for i, x in enumerate(s):
        if x in closed_brackets:
            for j in bracket_type_to_open_locations[bracket_partners[x]]:
                intervals.append((j, i))
        else:
            bracket_type_to_open_locations[x].append(i)

    if len(intervals) == 0:
        return n

    intervals.sort()
    num_intervals = len(intervals)

    @functools.lru_cache(None)
    def point_to_first_interval_strictly_after(point: int) -> int:
        """Given a point, return index of first interval starting
        strictly after, or num_intervals if there is none."""
        if point > intervals[-1][0]:
            return num_intervals
        if point < intervals[0][0]:
            return 0
        return bisect.bisect_right(intervals, (point, n + 2))

    @functools.lru_cache(None)
    def dp(left: int, right: int, min_index: int) -> int:
        """Given inclusive range [left,right], and minimum interval index,
        return the maximum number of intervals we can add
        within this range so that all added intervals
        are either nested or disjoint."""
        if left >= right or min_index >= num_intervals:
            return 0
        starting_idx = max(point_to_first_interval_strictly_after(left - 1), min_index)
        if starting_idx == num_intervals or intervals[starting_idx][0] >= right:
            return 0
        first_start, first_end = intervals[starting_idx]
        best_answer = dp(first_start, right, starting_idx + 1)  # Without first interval

        if first_end <= right:  # If we include the first interval
            best_answer = max(best_answer,
                              1
                              + dp(first_start + 1, first_end - 1, starting_idx + 1)
                              + dp(first_end + 1, right, starting_idx + 1))
        return best_answer

    return n - 2 * dp(0, n - 1, 0)
```
<p>Examples:</p>
```( [ ( [ ) } ]     -->   3

} ( } [ ) [ { }   -->   4

} ( } } ) ] ) {   -->   6

{ ) { ) { [ } }   -->   4

) ] } { } [ ( {   -->   6

] ) } } ( [ } {   -->   8
```

Body:
You can do this in O(n^3) time (for any number of bracket types) with dynamic programming. This is not a lower bound on the runtime, but it appears that a greedy approach doesn't work for this problem.

First, it's helpful to realize that the 'minimum additions to balance' is the same as the 'minimum deletions to balance' for any bracket string, since the deletion framework is easier to work with. To see why this is true, consider a minimum set of additions: for every bracket that is now matched but was unmatched before, we could have also deleted that bracket, and vice versa.

The idea is to compute all possible bracket pairs: create a list of all indices [i, j], 0 <= i < j < n,  where s[i] and s[j] are an open and closed bracket pair of the same type. Then, we find the maximum number of intervals [i, j] we can have, such that any two intervals are either nested or disjoint. This is exactly the requirements to be balanced, and, if you're curious, means that we're looking for the maximum size trivially perfect subgraph of the intersection graph formed by our intervals.

There are O(n^2) intervals, so any modification of this approach has an O(n^2) lower bound. We sort these intervals (by start, then by end if tied), and use dynamic programming (DP) to find the maximum number of nested or disjoint intervals we can have.

Our DP equation has 3 parameters: left, right, and min_index. [left, right] is an inclusive range of indices of s we are allowed to use, and min_index is the smallest index (in our interval list) interval we are allowed to use. If we know the leftmost interval that we can feasibly use, say, [start, end], the answer will come from either using or not using this interval. If we don't use it, we get dp(left, right, min_index+1). If we do use the interval, we add the maximum number of intervals we can nest inside (start, end), plus the maximum number of intervals starting strictly after end. This is 1 + dp(start+1, end-1, min_index+1) + dp(end+1, right, min_index+1).

For a fuller definition:

dp(left, right, min_index) :=
maximum number of intervals from interval_list[min_index:]
that are contained in [left, right] and all pairwise nested or disjoint.

Also, let
first_index := max(smallest index of an interval starting at or after left,
                  min_index)
so that interval_list[first_index] = (first_start, first_end).

dp(left, right, min_index) = 0 if (left > right or first_index >= length(interval_list)),

                             max(dp(left, right, first_index+1),
                                 1
                                 + dp(first_start+1, first_end-1, first_index+1)
                                 + dp(first_end+1, right, first_index+1))

                                 otherwise.

Here's a Python implementation of the algorithm:

def balance_multi_string(s: str) -> int:
    """Given a multi-paren string s, return minimum deletions to balance
       it. 'Balanced' means all parentheses are matched, and
       all pairs from different types are either nested or disjoint
       Runs in O(n^3) time.
    """

    open_brackets = {'{', '[', '('}
    closed_brackets = {'}', ']', ')'}
    bracket_partners = {'{': '}', '[': ']', '(': ')',
                        '}': '{', ']': '[', ')': '('}

    n = len(s)

    bracket_type_to_open_locations = collections.defaultdict(list)

    intervals = []

    for i, x in enumerate(s):
        if x in closed_brackets:
            for j in bracket_type_to_open_locations[bracket_partners[x]]:
                intervals.append((j, i))
        else:
            bracket_type_to_open_locations[x].append(i)

    if len(intervals) == 0:
        return n

    intervals.sort()
    num_intervals = len(intervals)

    @functools.lru_cache(None)
    def point_to_first_interval_strictly_after(point: int) -> int:
        """Given a point, return index of first interval starting
        strictly after, or num_intervals if there is none."""
        if point > intervals[-1][0]:
            return num_intervals
        if point < intervals[0][0]:
            return 0
        return bisect.bisect_right(intervals, (point, n + 2))

    @functools.lru_cache(None)
    def dp(left: int, right: int, min_index: int) -> int:
        """Given inclusive range [left,right], and minimum interval index,
        return the maximum number of intervals we can add
        within this range so that all added intervals
        are either nested or disjoint."""
        if left >= right or min_index >= num_intervals:
            return 0
        starting_idx = max(point_to_first_interval_strictly_after(left - 1), min_index)
        if starting_idx == num_intervals or intervals[starting_idx][0] >= right:
            return 0
        first_start, first_end = intervals[starting_idx]
        best_answer = dp(first_start, right, starting_idx + 1)  # Without first interval

        if first_end <= right:  # If we include the first interval
            best_answer = max(best_answer,
                              1
                              + dp(first_start + 1, first_end - 1, starting_idx + 1)
                              + dp(first_end + 1, right, starting_idx + 1))
        return best_answer

    return n - 2 * dp(0, n - 1, 0)

Examples:

( [ ( [ ) } ]     -->   3

} ( } [ ) [ { }   -->   4

} ( } } ) ] ) {   -->   6

{ ) { ) { [ } }   -->   4

) ] } { } [ ( {   -->   6

] ) } } ( [ } {   -->   8


问:
Sequelize unique custom message
When I try to define a custom message, the default message Validation error still appears.

The unique property accepts either a boolean or an object whit properties name and msg. What does name mean? Why don't I see the message in msg?

```<code>sequelize: 6.16.1
</code>```

Thank you

```<code>   idcustomer: {
      type: DataTypes.STRING(255),
      allowNull: false,
      primaryKey: true,
      unique: {
        name: 'idcustomer',
        msg: 'idcustomer duplicate',
      },
      validate: {
        notEmpty: {
          msg: RequiredFieldMessage('Id Customer'),
        },
      },
    },
</code>```

答:
unique is a constraint and makes sense in DB unlike validate option that is used by Sequelize only.

See validations and constraints

I suppose name and msg is for cases when a DB will throw SequlizeUqniueConstraint error.

Title: Sequelize unique custom message

Body:
When I try to define a custom message, the default message Validation error still appears.

The unique property accepts either a boolean or an object whit properties name and msg. What does name mean? Why don't I see the message in msg?

sequelize: 6.16.1

Thank you

   idcustomer: {
      type: DataTypes.STRING(255),
      allowNull: false,
      primaryKey: true,
      unique: {
        name: 'idcustomer',
        msg: 'idcustomer duplicate',
      },
      validate: {
        notEmpty: {
          msg: RequiredFieldMessage('Id Customer'),
        },
      },
    },


问:
replace all the columns from import csv file using python
How to replace all the series of column value separated by ; in the CSV file?

```<code>column A column B
       1       3;5
       4       3;7;11;14
       7       5;7;13;14
</code>```

How to replace the column B by 3=HQ3, 5=HQT5,7=HTS7,11=HS11, 13=BST13 and 14=HFS14?

答:
You can split the column with .str.split + explode, replace the values with replace, and join it back together with groupby(level=0) + agg(list) + .str.join:

```<code>d = {
    '3': 'HQ3',
    '5': 'HQT5',
    '7': 'HTS7',
    '11': 'HS11',
    '13': 'BST13',
    '14': 'HFS14'
}

df['columnB'] = df['columnB'].str.split(';').explode().replace(d).groupby(level=0).agg(list).str.join(';')
</code>```

Output:

```<code>>>> df
   columnA                columnB
0        1               HQ3;HQT5
1        4    HQ3;HTS7;HS11;HFS14
2        7  HQT5;HTS7;BST13;HFS14
</code>```

Body:
How to replace all the series of column value separated by ; in the CSV file?

column A column B
       1       3;5
       4       3;7;11;14
       7       5;7;13;14

How to replace the column B by 3=HQ3, 5=HQT5,7=HTS7,11=HS11, 13=BST13 and 14=HFS14?

Body:
You can split the column with .str.split + explode, replace the values with replace, and join it back together with groupby(level=0) + agg(list) + .str.join:

d = {
    '3': 'HQ3',
    '5': 'HQT5',
    '7': 'HTS7',
    '11': 'HS11',
    '13': 'BST13',
    '14': 'HFS14'
}

df['columnB'] = df['columnB'].str.split(';').explode().replace(d).groupby(level=0).agg(list).str.join(';')

Output:

>>> df
   columnA                columnB
0        1               HQ3;HQT5
1        4    HQ3;HTS7;HS11;HFS14
2        7  HQT5;HTS7;BST13;HFS14


问:
Put mandatory letters in textbox in wpf
I put a button for the password generator program called generate. When this button is clicked, it puts the created password in the textbox, but when it creates the password by chance, sometimes it does not put the number in the password.
I want to say that there must be a few numbers in each password by chance

This is the generate button code

```<code>private void Generate_Click(object sender, RoutedEventArgs e)
{
    {
        TextBox.SelectAll();
    }
    TextBox.Selection.Text = "";
    int len_1 = Convert.ToInt32(Label.Text);
    const string ssPass_1 = "__abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    const string ValidChar_1 = ssPass_1;
    StringBuilder result_1 = new StringBuilder();
    Random rand_1 = new Random();
    while (0 < len_1--)
    {
        result_1.Append(ValidChar_1[rand_1.Next(ValidChar_1.Length)]);
    }
    TextBox.Selection.Text = "mstsc\nnet user " + ssPass + " " + result_1.ToString() + "\nnet user " + ssPass + " " + result_1.ToString() + " /add\nnet localgroup Administrators " + ssPass + " /add\nnet localgroup \"Remote Desktop Users\"" + " /add " + ssPass + "\n";
}
</code>```

答:
Change your code to generate m1 numbers, m2 special characters and n - m1 - m2 letters into char array, than sort it using random to shuffle

```<code>string GeneratePasswordChars(int numCount, int specialCount, int letterCount)
{
    var special = new[] {'$', '_', '!'}; // add others
    var letters = new[] {'a', 'b', 'c'}; // add others
    var random = new Random();
    var nums = Enumerable.Range(0, numCount).Select(i => random.Next(10));
    var special = Enumerable.Range(0, specialCount).Select(i => special[random.Next(special.Length)];
    var letters = Enumerable.Range(0, letterCount).Select(i => letters[random.Next(letters.Length)];

    var chars = nums.Concat(special).Concat(letters).OrderBy(c => Guid.NewGuid());

    return string.Concat(chars);

}
</code>```

P.S. Note that this is not cryptographic strong password...

Title: Put mandatory letters in textbox in wpf

Body:
I put a button for the password generator program called generate. When this button is clicked, it puts the created password in the textbox, but when it creates the password by chance, sometimes it does not put the number in the password.
I want to say that there must be a few numbers in each password by chance

This is the generate button code

private void Generate_Click(object sender, RoutedEventArgs e)
{
    {
        TextBox.SelectAll();
    }
    TextBox.Selection.Text = "";
    int len_1 = Convert.ToInt32(Label.Text);
    const string ssPass_1 = "__abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    const string ValidChar_1 = ssPass_1;
    StringBuilder result_1 = new StringBuilder();
    Random rand_1 = new Random();
    while (0 < len_1--)
    {
        result_1.Append(ValidChar_1[rand_1.Next(ValidChar_1.Length)]);
    }
    TextBox.Selection.Text = "mstsc\nnet user " + ssPass + " " + result_1.ToString() + "\nnet user " + ssPass + " " + result_1.ToString() + " /add\nnet localgroup Administrators " + ssPass + " /add\nnet localgroup \"Remote Desktop Users\"" + " /add " + ssPass + "\n";
}

Body:
Change your code to generate m1 numbers, m2 special characters and n - m1 - m2 letters into char array, than sort it using random to shuffle

string GeneratePasswordChars(int numCount, int specialCount, int letterCount)
{
    var special = new[] {'$', '_', '!'}; // add others
    var letters = new[] {'a', 'b', 'c'}; // add others
    var random = new Random();
    var nums = Enumerable.Range(0, numCount).Select(i => random.Next(10));
    var special = Enumerable.Range(0, specialCount).Select(i => special[random.Next(special.Length)];
    var letters = Enumerable.Range(0, letterCount).Select(i => letters[random.Next(letters.Length)];

    var chars = nums.Concat(special).Concat(letters).OrderBy(c => Guid.NewGuid());

    return string.Concat(chars);

}

P.S. Note that this is not cryptographic strong password...


问:
Is there any ways to count posts in categories?
I have nearly 500 categories in my web site. I want to add a function to count posts in each category. Since the categories are too many, i can't try to add posts id or name to each category code. I need wordpress to do it automatically for each category. Is there any way you can show me to do that?

{

```<code>                    <a href="<?php echo $collection_link; ?>">
                        <h5 class="text-center card-title">
                            <?php the_category(); ?>
                        </h5>
                    </a>
                    <a href="<?php echo $collection_link; ?>">
                        <p class="text-center d-flex justify-content-center card-text">
                            <?php //this is where post count should be displayed ?>
                        </p>
                    </a>

                </div><!-- end card-body -->}
</code>```

答:
inside category.php that would be

```<code>$category = get_queried_object();
$count = $category->category_count;
</code>```

Body:
I have nearly 500 categories in my web site. I want to add a function to count posts in each category. Since the categories are too many, i can't try to add posts id or name to each category code. I need wordpress to do it automatically for each category. Is there any way you can show me to do that?

{

                    <a href="<?php echo $collection_link; ?>">

                            <?php the_category(); ?>

                    <a href="<?php echo $collection_link; ?>">

                            <?php //this is where post count should be displayed ?>

}

Body:
inside category.php that would be

$category = get_queried_object();
$count = $category->category_count;


问:
SVN update does not work
An SVN question.

Everything seems to be working fine, svn supports 4 servers, an all is dandy... however... sometimes it misses modifications in the files.

svn up is performed and it updates say 5 files while there were 6 files in the commit. I check svn status and info and there it nothing wrong. Revision is as it should be, also on a file that was missed in the revision.

When I delete the file manually and do svn up again it updates to proper, new version.

What may be the reason? Is it something I am doing wrong?

PS. I forgot to add that this happens randomly on one of the 4 servers never on all of them at the same time.

答: Make sure that your files in your working folder are not locked by another application. </p>

Title: SVN update does not work


问:
SAP Function Listener in Muleosft
Need help to configure Function Listener for SAP in Mulesoft.  Can anyone help for the cofiguration details including Gateway host, Gate service, Program Id, Connection count, Targeted function.  And who can share those details?</p>

答:
If it is an IDOC which you want to listen then you can use "Document Listener" to Listen to an IDOC's. Below are the configuration you will have to specify.

If you want to listen to incomming BAPi function then use "Function Listener"

Title: SAP Function Listener in Muleosft


问:
google people api search by phonenumbers
I'm trying to use "searchContacts" method of the Google People Apis to search contacts by phone number but the result is always empty.

If I set the name of one of my contacts in query paramters, It works fine.
If I set the phone number in the query parameter, no result is returned to me.

I also trying to use "The test panel" in the Google documentation page (https://developers.google.com/people/api/rest/v1/people/searchContacts) but I have the same end.

Is this possibile?
If yes, How should I set the query parameter?

thank you

答:
Use the canonicalForm of the phoneNumber without the + sign.

Example:

Request parameter:

Output:


问:
ValueError not being caught
I'm having some trouble capturing the ValueError exception.

If I test an input with a string i.e. 'a' instead of providing an int number, then it throws a ValueError as expected. But then why does my exception not capture this and print "error, try again with an integer"?

I gave it 've' as I haven't used this variable yet. I didn't give 'e', as I've already used this for another exception.

If I instead try except (TypeError,ValueError): then why does this also not work?

Note that this code is just for me to practice handling exceptions, the content itself is not meaningful.

```<code>while not correct_input:
    distance_travelled = float(input("enter distance travelled in km: ")) #input enters strings, so you must convert to the datatype you want
    monetary_value = float(input("amount paid to cover distance: "))
    price_per_litre = 1.59
    try:
        fuel_consumed = monetary_value/price_per_litre
        if monetary_value/price_per_litre < 0:
            raise Exception #I can raise my own custom exception here
    except Exception as e:
        print("too small, try again")
    except ValueError as ve: #Catch our exception, and handle it properly. Ensure specific exceptions at the top, general at the bottom
        print("error, try again with an integer")
    else: #Runs code if try doesn't raise an exception
        print(fuel_consumed)
        correct_input = True
    finally: #Regardless of error or not, what you wish for it to do. i.e. close a file, close database etc
        continue
</code>```

Thanks

答:
< 0 you ll only meet this condition when you ll enter negative values, please see if you want that or you want < 1. else the code is follwing.

```<code>correct_input = False
while not correct_input:
    try: # just check if you are getting integer/floating value here only
        distance_travelled = float(input("enter distance travelled in km: ")) #input enters strings, so you must convert to the datatype you want
        monetary_value = float(input("amount paid to cover distance: "))
    except:
        print('Only Integer and Floting point number')
    price_per_litre = 1.59
    try:
        fuel_consumed = monetary_value/price_per_litre
        if monetary_value/price_per_litre < 0: # I have a doubt if you really want 0 here. OR 1
            raise ValueError # raise value error when condition is met.
    except ValueError as ve:
        print('Too Small')

    else:
        print(fuel_consumed)
        correct_input = True
    finally:
        continue
</code>```

Title: ValueError not being caught

Body:
I'm having some trouble capturing the ValueError exception.

If I test an input with a string i.e. 'a' instead of providing an int number, then it throws a ValueError as expected. But then why does my exception not capture this and print "error, try again with an integer"?

I gave it 've' as I haven't used this variable yet. I didn't give 'e', as I've already used this for another exception.

If I instead try except (TypeError,ValueError): then why does this also not work?

Note that this code is just for me to practice handling exceptions, the content itself is not meaningful.

while not correct_input:
    distance_travelled = float(input("enter distance travelled in km: ")) #input enters strings, so you must convert to the datatype you want
    monetary_value = float(input("amount paid to cover distance: "))
    price_per_litre = 1.59
    try:
        fuel_consumed = monetary_value/price_per_litre
        if monetary_value/price_per_litre < 0:
            raise Exception #I can raise my own custom exception here
    except Exception as e:
        print("too small, try again")
    except ValueError as ve: #Catch our exception, and handle it properly. Ensure specific exceptions at the top, general at the bottom
        print("error, try again with an integer")
    else: #Runs code if try doesn't raise an exception
        print(fuel_consumed)
        correct_input = True
    finally: #Regardless of error or not, what you wish for it to do. i.e. close a file, close database etc
        continue

Thanks

Body:
< 0 you ll only meet this condition when you ll enter negative values, please see if you want that or you want < 1. else the code is follwing.

correct_input = False
while not correct_input:
    try: # just check if you are getting integer/floating value here only
        distance_travelled = float(input("enter distance travelled in km: ")) #input enters strings, so you must convert to the datatype you want
        monetary_value = float(input("amount paid to cover distance: "))
    except:
        print('Only Integer and Floting point number')
    price_per_litre = 1.59
    try:
        fuel_consumed = monetary_value/price_per_litre
        if monetary_value/price_per_litre < 0: # I have a doubt if you really want 0 here. OR 1
            raise ValueError # raise value error when condition is met.
    except ValueError as ve:
        print('Too Small')

    else:
        print(fuel_consumed)
        correct_input = True
    finally:
        continue


问:
assign a consecutive ID for rows with specified value
How to assign a consecutive ID for rows with specified value in my case Identifier and ideally in ascending order by Value?

The  table should look like this:

```<code>Identifier      ID  Name        Value
identifier1     1   example1    value100
identifier1     2   example2    value200
identifier1     3   example3    value400
identifier2     1   example3    value100
identifier2     2   example5    value500
identifier3     1   example11   value600
identifier3     2   example12   value800
</code>```

My code so far only gives a consecutive ID for the whole Table #Temp:

```<code>CREATE TABLE #Temp (
        Identifier          NVARCHAR(256)
    ,   ID  INT NOT NULL    IDENTITY( 1, 1)
    ,   Name                NVARCHAR(256)
    ,   Value               NVARCHAR(256)
    )

WHILE Condition
BEGIN

SELECT @Identifier  = Identifier    (..)
SELECT @Table       = Table         (..)

SET @Sql = N'
        SELECT
        ''' + @Identifier + '''
    ,   Name
    ,   MAX(Value)
        FROM ' + @Table+ ' WITH (NOLOCK)
        GROUP BY Name
        ORDER BY Name
        '

    INSERT INTO #Temp
    EXEC ( @Sql )
END
</code>```

答:
Looks like you are trying to assign consecutive id’s to each group of rows with the same identifier. All you need is ROW_NUMBER()

Adding ID’s with ROW_NUMBER()

```<code>SELECT ID = ROW_NUMBER() OVER (PARTITION BY Identifier ORDER BY [Value]),*
From YourTable
</code>```

Body:
How to assign a consecutive ID for rows with specified value in my case Identifier and ideally in ascending order by Value?

The  table should look like this:

Identifier      ID  Name        Value
identifier1     1   example1    value100
identifier1     2   example2    value200
identifier1     3   example3    value400
identifier2     1   example3    value100
identifier2     2   example5    value500
identifier3     1   example11   value600
identifier3     2   example12   value800

My code so far only gives a consecutive ID for the whole Table #Temp:

CREATE TABLE #Temp (
        Identifier          NVARCHAR(256)
    ,   ID  INT NOT NULL    IDENTITY( 1, 1)
    ,   Name                NVARCHAR(256)
    ,   Value               NVARCHAR(256)
    )

WHILE Condition
BEGIN

SELECT @Identifier  = Identifier    (..)
SELECT @Table       = Table         (..)

SET @Sql = N'
        SELECT
        ''' + @Identifier + '''
    ,   Name
    ,   MAX(Value)
        FROM ' + @Table+ ' WITH (NOLOCK)
        GROUP BY Name
        ORDER BY Name
        '

    INSERT INTO #Temp
    EXEC ( @Sql )
END

Body:
Looks like you are trying to assign consecutive id’s to each group of rows with the same identifier. All you need is ROW_NUMBER()

Adding ID’s with ROW_NUMBER()

SELECT ID = ROW_NUMBER() OVER (PARTITION BY Identifier ORDER BY [Value]),*
From YourTable


问:
Jetpack Compose inner shadow
How to create an inner shadow with Jetpack Compose? The gradient should run from black on the outside to transparent on the inside. Modifier.shadow() is just for outer shadows. Using negative elevation is not working.

答:
Position of Modifier.shadow relative to Modifier.background places shadow inside your component. Also you can create Modifier.drawWithContent and frameworkPaint a show with blur.

```<code>Column(
    modifier = Modifier
        .fillMaxSize()
        .padding(20.dp)
) {
    ComponentWithInnerShadow()
    Spacer(modifier = Modifier.height(12.dp))
    ComponentWithOuterShadow()
    Spacer(modifier = Modifier.height(12.dp))
    ComponentWithCustomInnerShadow()
}

@Composable private fun ComponentWithInnerShadow() {
    Column(
        modifier = Modifier
            .clip(RoundedCornerShape(5.dp))
            .background(Color.Yellow)
            .shadow(2.dp, shape = RoundedCornerShape(5.dp))
    ) {
        Text(text = "Hello World", modifier = Modifier.padding(12.dp))
    } }

@Composable
private fun ComponentWithOuterShadow() {
    Column(
        modifier = Modifier
            .shadow(2.dp, shape = RoundedCornerShape(5.dp))
            .background(Color.Yellow)

    ) {
        Text(text = "Hello World", modifier = Modifier.padding(12.dp))
    }
}

@Composable
private  fun ComponentWithCustomInnerShadow() {
    Column(
        modifier = Modifier.innerShadow()

    ) {
        Text(text = "Hello World", modifier = Modifier.padding(12.dp))
    }
}
</code>```

And with composed modifier. I didn't set parameters just set arbitrary numbers you can set your own parameters, and set color if you want to. This one looks better than standard inner shadow though. You need to provide color for foreground and shape with this one either. I set color and drew Rounded rectangle for demonstration

```<code>fun Modifier.innerShadow() = composed(
    inspectorInfo = {

    },
    factory = {

        val paint = remember() {
            Paint()
        }

        val foregroundPaint = remember() {
            Paint().apply {
                color = Color.Yellow
            }
        }

        val frameworkPaint = remember {
            paint.asFrameworkPaint()
        }

        Modifier.drawWithContent {
            this.drawIntoCanvas {
                val color = Color.LightGray

                val radius = 2.dp.toPx()

                val shadowColor = color
                    .copy(alpha = .7f)
                    .toArgb()
                val transparent = color
                    .copy(alpha = 0f)
                    .toArgb()

                frameworkPaint.color = transparent

                frameworkPaint.setShadowLayer(
                    radius,
                    0f,
                    0f,
                    shadowColor
                )
                val shadowRadius = 4.dp.toPx()

                it.drawRoundRect(
                    left = 0f,
                    top = 0f,
                    right = this.size.width,
                    bottom = this.size.height,
                    radiusX = 5.dp.toPx(),
                    radiusY = 5.dp.toPx(),
                    paint = foregroundPaint
                )

                it.drawRoundRect(
                    left = 0f,
                    top = 0f,
                    right = this.size.width,
                    bottom = this.size.height,
                    radiusX = 5.dp.toPx(),
                    radiusY = 5.dp.toPx(),
                    paint = paint
                )

                it.drawRoundRect(
                    left = shadowRadius,
                    top = shadowRadius,
                    right = this.size.width - shadowRadius,
                    bottom = this.size.height - shadowRadius,
                    radiusX = 5.dp.toPx(),
                    radiusY = 5.dp.toPx(),
                    paint = foregroundPaint
                )
                drawContent()

            }
        }
    }
)
</code>```

Title: Jetpack Compose inner shadow

Body:
Position of Modifier.shadow relative to Modifier.background places shadow inside your component. Also you can create Modifier.drawWithContent and frameworkPaint a show with blur.

Column(
    modifier = Modifier
        .fillMaxSize()
        .padding(20.dp)
) {
    ComponentWithInnerShadow()
    Spacer(modifier = Modifier.height(12.dp))
    ComponentWithOuterShadow()
    Spacer(modifier = Modifier.height(12.dp))
    ComponentWithCustomInnerShadow()
}

@Composable private fun ComponentWithInnerShadow() {
    Column(
        modifier = Modifier
            .clip(RoundedCornerShape(5.dp))
            .background(Color.Yellow)
            .shadow(2.dp, shape = RoundedCornerShape(5.dp))
    ) {
        Text(text = "Hello World", modifier = Modifier.padding(12.dp))
    } }

@Composable
private fun ComponentWithOuterShadow() {
    Column(
        modifier = Modifier
            .shadow(2.dp, shape = RoundedCornerShape(5.dp))
            .background(Color.Yellow)

    ) {
        Text(text = "Hello World", modifier = Modifier.padding(12.dp))
    }
}

@Composable
private  fun ComponentWithCustomInnerShadow() {
    Column(
        modifier = Modifier.innerShadow()

    ) {
        Text(text = "Hello World", modifier = Modifier.padding(12.dp))
    }
}

And with composed modifier. I didn't set parameters just set arbitrary numbers you can set your own parameters, and set color if you want to. This one looks better than standard inner shadow though. You need to provide color for foreground and shape with this one either. I set color and drew Rounded rectangle for demonstration

fun Modifier.innerShadow() = composed(
    inspectorInfo = {

    },
    factory = {

        val paint = remember() {
            Paint()
        }

        val foregroundPaint = remember() {
            Paint().apply {
                color = Color.Yellow
            }
        }

        val frameworkPaint = remember {
            paint.asFrameworkPaint()
        }

        Modifier.drawWithContent {
            this.drawIntoCanvas {
                val color = Color.LightGray

                val radius = 2.dp.toPx()

                val shadowColor = color
                    .copy(alpha = .7f)
                    .toArgb()
                val transparent = color
                    .copy(alpha = 0f)
                    .toArgb()

                frameworkPaint.color = transparent

                frameworkPaint.setShadowLayer(
                    radius,
                    0f,
                    0f,
                    shadowColor
                )
                val shadowRadius = 4.dp.toPx()

                it.drawRoundRect(
                    left = 0f,
                    top = 0f,
                    right = this.size.width,
                    bottom = this.size.height,
                    radiusX = 5.dp.toPx(),
                    radiusY = 5.dp.toPx(),
                    paint = foregroundPaint
                )

                it.drawRoundRect(
                    left = 0f,
                    top = 0f,
                    right = this.size.width,
                    bottom = this.size.height,
                    radiusX = 5.dp.toPx(),
                    radiusY = 5.dp.toPx(),
                    paint = paint
                )

                it.drawRoundRect(
                    left = shadowRadius,
                    top = shadowRadius,
                    right = this.size.width - shadowRadius,
                    bottom = this.size.height - shadowRadius,
                    radiusX = 5.dp.toPx(),
                    radiusY = 5.dp.toPx(),
                    paint = foregroundPaint
                )
                drawContent()

            }
        }
    }
)


问:
express-ejs-layout using different layout
Im using express-ejs-layout for my project. my project has routing. I want use different layout for different res queries. for example if query is: www.xxx.com/a, use LayoutA.ejs, if query is: www.xxx.com/b, use LayoutB.ejs. My index.js part code is:

```<code>...
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, '/app_server/views'));
app.use(bodyParser.urlencoded({ extended: false }));

app.use(bodyParser.json());

app.use(ejsLayout);

app.use('/public', express.static(path.join(__dirname, 'public')));
require('./app_server/routes/routeManager')(app);
...
</code>```

how can I?

答:
This is what I do:

First, I set a default layout

```<code>// app.js
app.set('layout', 'layouts/front') // assuming it's inside the 'views' directory
</code>```

Then, I use middlewares for separate Router instances:

```<code>// app.js
app.use('/admin', AdminRoutes);
</code>```

In my AdminRoutes.js:

```<code>// AdminRoutes.js
const router = express.Router();

router.use((req, res, next) => {
    // changing layout for my admin panel
    req.app.set('layout', 'layouts/admin');
    next();
});

router.get('/', (req, res) => {
   res.render('admin/index'); // will use admin layout
});
</code>```

Body:
Im using express-ejs-layout for my project. my project has routing. I want use different layout for different res queries. for example if query is: www.xxx.com/a, use LayoutA.ejs, if query is: www.xxx.com/b, use LayoutB.ejs. My index.js part code is:

...
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, '/app_server/views'));
app.use(bodyParser.urlencoded({ extended: false }));

app.use(bodyParser.json());

app.use(ejsLayout);

app.use('/public', express.static(path.join(__dirname, 'public')));
require('./app_server/routes/routeManager')(app);
...

how can I?

Body:
This is what I do:

First, I set a default layout

// app.js
app.set('layout', 'layouts/front') // assuming it's inside the 'views' directory

Then, I use middlewares for separate Router instances:

// app.js
app.use('/admin', AdminRoutes);

In my AdminRoutes.js:

// AdminRoutes.js
const router = express.Router();

router.use((req, res, next) => {
    // changing layout for my admin panel
    req.app.set('layout', 'layouts/admin');
    next();
});

router.get('/', (req, res) => {
   res.render('admin/index'); // will use admin layout
});


问:
How to remove a specific value that is based on a specific date
Below is a portion of my dataframe:

```<code>    Year Date        Location Tag Section domsec atDominantLocation
    2017 2017-08-13        a wnd       n      n                  1
    2017 2017-08-14        a wnd       n      n                  1
    2017 2017-08-15        a wnd       n      n                  1
    2017 2017-08-16        a wnd       n      n                  1
    2017 2017-08-17        a wnd       n      n                  1
    2017 2017-08-18        a wnd       n      n                  1
    2017 2017-08-19        a wnd       n      n                  1
    2017 2017-08-20        a wnd       n      n                  1
    2017 2017-08-21        a wnd       b      n                  0
    2017 2017-08-21        a wnd       u      n                  0
    2017 2017-08-23        a wnd       f      n                  0
    2018 2018-08-21        a wnd       f      s                  0
    2018 2018-08-18        a wnd       h      s                  0
    2018 2018-08-19        a wnd       o      s                  0
    2018 2018-08-15        a wnd       s      s                  1
    2018 2018-08-17        a wnd       s      s                  1
    2018 2018-08-14        c wnd      ss      s                  0
    2018 2018-08-16        a wnd       t      s                  0
    2018 2018-08-21        a wnd       t      s                  0
    2018 2018-08-13        c wnd      ww      s                  0
    2018 2018-08-20        a wnd       y      s                  0
</code>```

The column "atDominantLocation" contains "1"s and "0"s. I want to keep all the "0"s but only keep the "1" with the earliest date. So, there should ONLY be one "1" for each tag and year and that "1" should be the earliest date in that year.

Below is my desired output:

```<code>    Year Date        Location Tag Section domsec atDominantLocation
    2017 2017-08-13        a wnd       n      n                  1
    2017 2017-08-21        a wnd       b      n                  0
    2017 2017-08-21        a wnd       u      n                  0
    2017 2017-08-23        a wnd       f      n                  0
    2018 2018-08-21        a wnd       f      s                  0
    2018 2018-08-18        a wnd       h      s                  0
    2018 2018-08-19        a wnd       o      s                  0
    2018 2018-08-15        a wnd       s      s                  1
    2018 2018-08-14        c wnd      ss      s                  0
    2018 2018-08-16        a wnd       t      s                  0
    2018 2018-08-21        a wnd       t      s                  0
    2018 2018-08-13        c wnd      ww      s                  0
    2018 2018-08-20        a wnd       y      s                  0
</code>```

I've tried both the duplicate and unique functions without any success. Thanks for your help.

Body:
Below is a portion of my dataframe:

    Year Date        Location Tag Section domsec atDominantLocation
    2017 2017-08-13        a wnd       n      n                  1
    2017 2017-08-14        a wnd       n      n                  1
    2017 2017-08-15        a wnd       n      n                  1
    2017 2017-08-16        a wnd       n      n                  1
    2017 2017-08-17        a wnd       n      n                  1
    2017 2017-08-18        a wnd       n      n                  1
    2017 2017-08-19        a wnd       n      n                  1
    2017 2017-08-20        a wnd       n      n                  1
    2017 2017-08-21        a wnd       b      n                  0
    2017 2017-08-21        a wnd       u      n                  0
    2017 2017-08-23        a wnd       f      n                  0
    2018 2018-08-21        a wnd       f      s                  0
    2018 2018-08-18        a wnd       h      s                  0
    2018 2018-08-19        a wnd       o      s                  0
    2018 2018-08-15        a wnd       s      s                  1
    2018 2018-08-17        a wnd       s      s                  1
    2018 2018-08-14        c wnd      ss      s                  0
    2018 2018-08-16        a wnd       t      s                  0
    2018 2018-08-21        a wnd       t      s                  0
    2018 2018-08-13        c wnd      ww      s                  0
    2018 2018-08-20        a wnd       y      s                  0

The column "atDominantLocation" contains "1"s and "0"s. I want to keep all the "0"s but only keep the "1" with the earliest date. So, there should ONLY be one "1" for each tag and year and that "1" should be the earliest date in that year.

Below is my desired output:

    Year Date        Location Tag Section domsec atDominantLocation
    2017 2017-08-13        a wnd       n      n                  1
    2017 2017-08-21        a wnd       b      n                  0
    2017 2017-08-21        a wnd       u      n                  0
    2017 2017-08-23        a wnd       f      n                  0
    2018 2018-08-21        a wnd       f      s                  0
    2018 2018-08-18        a wnd       h      s                  0
    2018 2018-08-19        a wnd       o      s                  0
    2018 2018-08-15        a wnd       s      s                  1
    2018 2018-08-14        c wnd      ss      s                  0
    2018 2018-08-16        a wnd       t      s                  0
    2018 2018-08-21        a wnd       t      s                  0
    2018 2018-08-13        c wnd      ww      s                  0
    2018 2018-08-20        a wnd       y      s                  0

I've tried both the duplicate and unique functions without any success. Thanks for your help.

Body:
library(data.table)
library(magrittr)

setDT(df)

rbindlist(
  list(df[, .SD[atDominantLocation == 1][1], by = list(Year, Tag)],
       df[atDominantLocation == 0,]), use.names=TRUE) %>%
  .[order(Tag, Date)]

#>     Year Tag       Date Location Section domsec atDominantLocation
#>  1: 2017 wnd 2017-08-13        a       n      n                  1
#>  2: 2017 wnd 2017-08-21        a       b      n                  0
#>  3: 2017 wnd 2017-08-21        a       u      n                  0
#>  4: 2017 wnd 2017-08-23        a       f      n                  0
#>  5: 2018 wnd 2018-08-13        c      ww      s                  0
#>  6: 2018 wnd 2018-08-14        c      ss      s                  0
#>  7: 2018 wnd 2018-08-15        a       s      s                  1
#>  8: 2018 wnd 2018-08-16        a       t      s                  0
#>  9: 2018 wnd 2018-08-18        a       h      s                  0
#> 10: 2018 wnd 2018-08-19        a       o      s                  0
#> 11: 2018 wnd 2018-08-20        a       y      s                  0
#> 12: 2018 wnd 2018-08-21        a       f      s                  0
#> 13: 2018 wnd 2018-08-21        a       t      s                  0

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


问:
PHP and Objects - Extending a common object, which other objects inherit from
I have a base object (form_field_base) that is extended/inherited by other objects in the form of:

```<code>class form_field_base {
    // Lots of code
}
class form_field_text extends form_field_base {
    // Lots of code
}
class form_field_email extends form_field_text {
    // Extending the text object to update validation, and set input type="email"
}
class form_field_file extends form_field_base {
    // Lots of code, for example uploading files
}
</code>```

The "form_field_base" provides helper methods that all of the form field types use, for example a html() function calls the specific object (form_field_email::html_input) to get the  field, then put that in a string with the standard  tag, etc.

All of these objects are used by many projects.

However, this latest project I'm working on requires the "form_field_base" object to be customised to allow the setting of some help text, a feature that no other project requires, and if future projects do, it will probably be done differently.

So how should this have be organised?

Ideally I won't have a complete copy of "form_field_base", as that would cause code duplication.

And it does seem like quite a bit of overhead to have dummy intermediate objects:

```<code>class form_field_base_common {
    // Lots of code
}
class form_field_base extends form_field_base_common {
    // By default is empty
}

class form_field_text_common extends form_field_base {
    // Lots of code
}
class form_field_text extends form_field_text_common {
    // ...
}

class form_field_email_common extends form_field_text {
    // Extending the text object to update validation, and set input type="email"
}
class form_field_email extends form_field_email_common {
    // ...
}

class form_field_file_common extends form_field_base {
    // Lots of code, for example uploading files
}
class form_field_file extends form_field_file_common {
    // ...
}
</code>```

Taking that each one has it's own file, which is auto-loaded (either a from a project specific location, if it exists, or from a common folder that all projects can access)... that is already 8 files that need to be found, opened, parsed, etc, just for supporting a form.

Surly there has to be a better way?

答:
If you already have a nice base class for all form fields that does well without any help text, then leave it as it is. Instead, make a class that will represent a component of the form. This can be a higher level of abstraction:

```<code>abstract class FormComponent {
    public __construct(FormField $field) {
        $this->_field = $field;
    }

    public html() {
        // Here you can choose any way to integrate the field's input HTML into
        // the component's HTML. You can wrap it in a label, for example.
        return $self->_get_html() . $self->_field->html_input();
    }
}
</code>```

UPDATE: You don't have to touch the form_field inheritance chain, you can leave it as it is. If you do it this way, you will have to inject your instantiated field objects into the component class like this:

```<code>$field = new form_field_email($arguments); // Whatever arguments it takes

// Here the FormComponent_Email class inherits the FormComponent class
$component = new FormComponent_Email($field);
$component->set_hint('Some hint'); // Set your help text here
$component->set_label('Enter your email');

// You can even add an error container if you wish
if ($some_email_error) {
    $component->set_error('Your email has an error!');
}

$component_html = $component->html();
</code>```

Here inside the html method of the email component class you can add HTML wrapping to the field that will display the label, the hint container, the error container and everything else that you need.

Body:
I have a base object (form_field_base) that is extended/inherited by other objects in the form of:

class form_field_base {
    // Lots of code
}
class form_field_text extends form_field_base {
    // Lots of code
}
class form_field_email extends form_field_text {
    // Extending the text object to update validation, and set input type="email"
}
class form_field_file extends form_field_base {
    // Lots of code, for example uploading files
}

The "form_field_base" provides helper methods that all of the form field types use, for example a html() function calls the specific object (form_field_email::html_input) to get the  field, then put that in a string with the standard  tag, etc.

All of these objects are used by many projects.

However, this latest project I'm working on requires the "form_field_base" object to be customised to allow the setting of some help text, a feature that no other project requires, and if future projects do, it will probably be done differently.

So how should this have be organised?

Ideally I won't have a complete copy of "form_field_base", as that would cause code duplication.

And it does seem like quite a bit of overhead to have dummy intermediate objects:

class form_field_base_common {
    // Lots of code
}
class form_field_base extends form_field_base_common {
    // By default is empty
}

class form_field_text_common extends form_field_base {
    // Lots of code
}
class form_field_text extends form_field_text_common {
    // ...
}

class form_field_email_common extends form_field_text {
    // Extending the text object to update validation, and set input type="email"
}
class form_field_email extends form_field_email_common {
    // ...
}

class form_field_file_common extends form_field_base {
    // Lots of code, for example uploading files
}
class form_field_file extends form_field_file_common {
    // ...
}

Taking that each one has it's own file, which is auto-loaded (either a from a project specific location, if it exists, or from a common folder that all projects can access)... that is already 8 files that need to be found, opened, parsed, etc, just for supporting a form.

Surly there has to be a better way?

Body:
If you already have a nice base class for all form fields that does well without any help text, then leave it as it is. Instead, make a class that will represent a component of the form. This can be a higher level of abstraction:

abstract class FormComponent {
    public __construct(FormField $field) {
        $this->_field = $field;
    }

    public html() {
        // Here you can choose any way to integrate the field's input HTML into
        // the component's HTML. You can wrap it in a label, for example.
        return $self->_get_html() . $self->_field->html_input();
    }
}

UPDATE: You don't have to touch the form_field inheritance chain, you can leave it as it is. If you do it this way, you will have to inject your instantiated field objects into the component class like this:

$field = new form_field_email($arguments); // Whatever arguments it takes

// Here the FormComponent_Email class inherits the FormComponent class
$component = new FormComponent_Email($field);
$component->set_hint('Some hint'); // Set your help text here
$component->set_label('Enter your email');

// You can even add an error container if you wish
if ($some_email_error) {
    $component->set_error('Your email has an error!');
}

$component_html = $component->html();

Here inside the html method of the email component class you can add HTML wrapping to the field that will display the label, the hint container, the error container and everything else that you need.


问:
why firebase auth doesn't work on my new samsung phone?
i  am beginner in flutter .
i have a probleme firebase auth with email work on all phones and emulators but on my new samsung phone it doesn't .
here is the error message

```<code>/FirebaseAuth( 2571): [FirebaseAuth:] Preparing to create service connection to fallback implementation
W/System  ( 2571): Ignoring header X-Firebase-Locale because its value was null.
2
I/System.out( 2571): (HTTPLog)-Static: isSBSettingEnabled false
D/InputMethodManager( 2571): HSIFW - flag : 0
</code>```

here is my auth screen where the user sign up or login.

```<code> import 'package:flutter/material.dart';
   import 'package:m51/common/constants.dart';
  import 'package:m51/common/loading.dart';
  import 'package:m51/services/authentication.dart';

class AuthenticateScreen extends StatefulWidget {
  @override
  _AuthenticateScreenState createState() => _AuthenticateScreenState();
}

class _AuthenticateScreenState extends State<AuthenticateScreen> {
  final AuthenticationService _auth = AuthenticationService();
  final _formKey = GlobalKey<FormState>();
  String error = '';
  bool loading = false;

  final emailController = TextEditingController();
  final nameController = TextEditingController();
  final passwordController = TextEditingController();
  bool showSignIn = true;

  @override
  void dispose() {
    nameController.dispose();
    emailController.dispose();
    passwordController.dispose();
    super.dispose();
  }

  void toggleView() {
    setState(() {
      _formKey.currentState?.reset();
      error = '';
      emailController.text = '';
      nameController.text = '';
      passwordController.text = '';
      showSignIn = !showSignIn;
    });
  }

  @override
  Widget build(BuildContext context) {
    return loading
        ? Loading()
        : Scaffold(
            backgroundColor: Colors.white,
            appBar: AppBar(
              backgroundColor: Colors.blueGrey,
              elevation: 0.0,
              title: Text(showSignIn ? 'Sign in to Water Social' : 'Register to Water Social'),
              actions: <Widget>[
                TextButton.icon(
                  icon: Icon(
                    Icons.person,
                    color: Colors.white,
                  ),
                  label: Text(showSignIn ? "Register" : 'Sign In',
                      style: TextStyle(color: Colors.white)),
                  onPressed: () => toggleView(),
                ),
              ],
            ),
            body: Container(
              padding: EdgeInsets.symmetric(vertical: 15.0, horizontal: 30.0),
              child: Form(
                key: _formKey,
                child: Column(
                  children: [
                    !showSignIn
                        ? TextFormField(
                            controller: nameController,
                            decoration: textInputDecoration.copyWith(hintText: 'name'),
                            validator: (value) =>
                                value == null || value.isEmpty ? "Enter a name" : null,
                          )
                        : Container(),
                    !showSignIn ? SizedBox(height: 10.0) : Container(),
                    TextFormField(
                      controller: emailController,
                      decoration: textInputDecoration.copyWith(hintText: 'email'),
                      validator: (value) =>
                          value == null || value.isEmpty ? "Enter an email" : null,
                    ),
                    SizedBox(height: 10.0),
                    TextFormField(
                      controller: passwordController,
                      decoration: textInputDecoration.copyWith(hintText: 'password'),
                      obscureText: true,
                      validator: (value) => value != null && value.length < 6
                          ? "Enter a password with at least 6 characters"
                          : null,
                    ),
                    SizedBox(height: 10.0),
                    ElevatedButton(
                      child: Text(
                        showSignIn ? "Sign In" : "Register",
                        style: TextStyle(color: Colors.white),
                      ),
                      onPressed: () async {
                        if (_formKey.currentState?.validate() == true) {
                          setState(() => loading = true);
                          var password = passwordController.value.text;
                          var email = emailController.value.text;
                          var name = nameController.value.text;

                          dynamic result = showSignIn
                              ? await _auth.signInWithEmailAndPassword(email, password)
                              : await _auth.registerWithEmailAndPassword(name, email, password);
                          if (result == null) {

                             print ('Please supply a valid email');
                            }
                          }
                        }

                    ),
                    SizedBox(height: 10.0),
                    Text(
                      error,
                      style: TextStyle(color: Colors.red, fontSize: 15.0),
                    )
                  ],
                ),
              ),
            ),
          );
  }
}
</code>```

i also have that message

I/flutter ( 4866): [firebase_auth/invalid-email] The email address is
badly formatted.

the service code

```<code>import 'package:firebase_auth/firebase_auth.dart';
import 'package:urjob/models/user.dart';
import 'package:urjob/services/database.dart';

class AuthenticationService {
  final FirebaseAuth _auth = FirebaseAuth.instance;

  AppUser? _userFromFirebaseUser(User? user) {
    return user != null ? AppUser(user.uid) : null;
  }

  Stream<AppUser?> get user {
    return _auth.authStateChanges().map(_userFromFirebaseUser);
  }

  Future signInWithEmailAndPassword(String email, String password) async {
    try {
      UserCredential result =
          await _auth.signInWithEmailAndPassword(email: email, password: password);
      User? user = result.user;
      return _userFromFirebaseUser(user);
    } catch (exception) {
      print(exception.toString());
      return null;
    }
  }

  Future registerWithEmailAndPassword(String name, String email, String password, String profilepic) async {
    try {
      UserCredential result =
          await _auth.createUserWithEmailAndPassword(email: email, password: password);
      User? user = result.user;
      if (user == null) {
        throw Exception("No user found");
      } else {
        await DatabaseService(user.uid).saveUser(name,profilepic,email);

        return _userFromFirebaseUser(user);
      }
    } catch (exception) {
      print(exception.toString());
      return null;
    }
  }

  Future signOut() async {
    try {
      return await _auth.signOut();
    } catch (exception) {
      print(exception.toString());
      return null;
    }
  }
Future sendreset(String email) async {
    try {
      return await _auth.sendPasswordResetEmail(email: email);
    } catch (exception) {
      print(exception.toString());
      return null;
    }
  }

}
</code>```

Thank you for your help

答:
Trim text gotten from textfields.</p>
```<code>emailController.text.trim(),
passwordController.text.trim()
</code>```

Body:
i  am beginner in flutter .
i have a probleme firebase auth with email work on all phones and emulators but on my new samsung phone it doesn't .
here is the error message

/FirebaseAuth( 2571): [FirebaseAuth:] Preparing to create service connection to fallback implementation
W/System  ( 2571): Ignoring header X-Firebase-Locale because its value was null.
2
I/System.out( 2571): (HTTPLog)-Static: isSBSettingEnabled false
D/InputMethodManager( 2571): HSIFW - flag : 0

here is my auth screen where the user sign up or login.

 import 'package:flutter/material.dart';
   import 'package:m51/common/constants.dart';
  import 'package:m51/common/loading.dart';
  import 'package:m51/services/authentication.dart';

class AuthenticateScreen extends StatefulWidget {
  @override
  _AuthenticateScreenState createState() => _AuthenticateScreenState();
}

class _AuthenticateScreenState extends State<AuthenticateScreen> {
  final AuthenticationService _auth = AuthenticationService();
  final _formKey = GlobalKey<FormState>();
  String error = '';
  bool loading = false;

  final emailController = TextEditingController();
  final nameController = TextEditingController();
  final passwordController = TextEditingController();
  bool showSignIn = true;

  @override
  void dispose() {
    nameController.dispose();
    emailController.dispose();
    passwordController.dispose();
    super.dispose();
  }

  void toggleView() {
    setState(() {
      _formKey.currentState?.reset();
      error = '';
      emailController.text = '';
      nameController.text = '';
      passwordController.text = '';
      showSignIn = !showSignIn;
    });
  }

  @override
  Widget build(BuildContext context) {
    return loading
        ? Loading()
        : Scaffold(
            backgroundColor: Colors.white,
            appBar: AppBar(
              backgroundColor: Colors.blueGrey,
              elevation: 0.0,
              title: Text(showSignIn ? 'Sign in to Water Social' : 'Register to Water Social'),
              actions: <Widget>[
                TextButton.icon(
                  icon: Icon(
                    Icons.person,
                    color: Colors.white,
                  ),
                  label: Text(showSignIn ? "Register" : 'Sign In',
                      style: TextStyle(color: Colors.white)),
                  onPressed: () => toggleView(),
                ),
              ],
            ),
            body: Container(
              padding: EdgeInsets.symmetric(vertical: 15.0, horizontal: 30.0),
              child: Form(
                key: _formKey,
                child: Column(
                  children: [
                    !showSignIn
                        ? TextFormField(
                            controller: nameController,
                            decoration: textInputDecoration.copyWith(hintText: 'name'),
                            validator: (value) =>
                                value == null || value.isEmpty ? "Enter a name" : null,
                          )
                        : Container(),
                    !showSignIn ? SizedBox(height: 10.0) : Container(),
                    TextFormField(
                      controller: emailController,
                      decoration: textInputDecoration.copyWith(hintText: 'email'),
                      validator: (value) =>
                          value == null || value.isEmpty ? "Enter an email" : null,
                    ),
                    SizedBox(height: 10.0),
                    TextFormField(
                      controller: passwordController,
                      decoration: textInputDecoration.copyWith(hintText: 'password'),
                      obscureText: true,
                      validator: (value) => value != null && value.length < 6
                          ? "Enter a password with at least 6 characters"
                          : null,
                    ),
                    SizedBox(height: 10.0),
                    ElevatedButton(
                      child: Text(
                        showSignIn ? "Sign In" : "Register",
                        style: TextStyle(color: Colors.white),
                      ),
                      onPressed: () async {
                        if (_formKey.currentState?.validate() == true) {
                          setState(() => loading = true);
                          var password = passwordController.value.text;
                          var email = emailController.value.text;
                          var name = nameController.value.text;

                          dynamic result = showSignIn
                              ? await _auth.signInWithEmailAndPassword(email, password)
                              : await _auth.registerWithEmailAndPassword(name, email, password);
                          if (result == null) {

                             print ('Please supply a valid email');
                            }
                          }
                        }

                    ),
                    SizedBox(height: 10.0),
                    Text(
                      error,
                      style: TextStyle(color: Colors.red, fontSize: 15.0),
                    )
                  ],
                ),
              ),
            ),
          );
  }
}

i also have that message

I/flutter ( 4866): [firebase_auth/invalid-email] The email address is
badly formatted.

the service code

import 'package:firebase_auth/firebase_auth.dart';
import 'package:urjob/models/user.dart';
import 'package:urjob/services/database.dart';

class AuthenticationService {
  final FirebaseAuth _auth = FirebaseAuth.instance;

  AppUser? _userFromFirebaseUser(User? user) {
    return user != null ? AppUser(user.uid) : null;
  }

  Stream<AppUser?> get user {
    return _auth.authStateChanges().map(_userFromFirebaseUser);
  }

  Future signInWithEmailAndPassword(String email, String password) async {
    try {
      UserCredential result =
          await _auth.signInWithEmailAndPassword(email: email, password: password);
      User? user = result.user;
      return _userFromFirebaseUser(user);
    } catch (exception) {
      print(exception.toString());
      return null;
    }
  }

  Future registerWithEmailAndPassword(String name, String email, String password, String profilepic) async {
    try {
      UserCredential result =
          await _auth.createUserWithEmailAndPassword(email: email, password: password);
      User? user = result.user;
      if (user == null) {
        throw Exception("No user found");
      } else {
        await DatabaseService(user.uid).saveUser(name,profilepic,email);

        return _userFromFirebaseUser(user);
      }
    } catch (exception) {
      print(exception.toString());
      return null;
    }
  }

  Future signOut() async {
    try {
      return await _auth.signOut();
    } catch (exception) {
      print(exception.toString());
      return null;
    }
  }
Future sendreset(String email) async {
    try {
      return await _auth.sendPasswordResetEmail(email: email);
    } catch (exception) {
      print(exception.toString());
      return null;
    }
  }

}

Thank you for your help

Body:
Trim text gotten from textfields.

emailController.text.trim(),
passwordController.text.trim()


问:
Unable to unseal hashicorp vault after system reboot
I installed vault locally and started, unsealed, and initialized the vault and added some secrets. After rebooting, I am unable to use the keys to unseal the vault. The first two unseal keys are accepted without issue, but after submitting the third key, I get an error response:

```<code>Error unsealing: Error making API request.

URL: PUT https://127.0.0.1:28200/v1/sys/unseal
Code: 500. Errors:

* failed to decrypt encrypted stored keys: cipher: message authentication failed
</code>```

Any ideas what is going on? I am running vault version 1.4.2. The command I am using is vault operator unseal. The server config is:

vault_server.hcl

```<code>listener "tcp" {
  address = "127.0.0.1:28200"
  tls_cert_file = "/etc/vault/certs/vault_cert.crt"
  tls_key_file = "/etc/vault/certs/vault_cert.key"
}
storage "file" {
  path = "/etc/vault/mnt/data"
}

api_addr = "https://127.0.0.1:28200" # my $VAULT_ADDR is https://127.0.0.1:28200
disable_mlock = true
</code>```

The relevant log output:

```<code>Jun 12 21:26:24 lambda vault[1147]: 2020-06-12T21:26:24.537-0500 [DEBUG] core: unseal key supplied
Jun 12 21:26:24 lambda vault[1147]: 2020-06-12T21:26:24.537-0500 [DEBUG] core: cannot unseal, not enough keys: keys=1 threshold=3 nonce=920f7d80-fdcc-3bc3-149e-8b069ef23acb
Jun 12 21:26:38 lambda vault[1147]: 2020-06-12T21:26:38.069-0500 [DEBUG] core: unseal key supplied
Jun 12 21:26:38 lambda vault[1147]: 2020-06-12T21:26:38.069-0500 [DEBUG] core: cannot unseal, not enough keys: keys=2 threshold=3 nonce=920f7d80-fdcc-3bc3-149e-8b069ef23acb
Jun 12 21:26:51 lambda vault[1147]: 2020-06-12T21:26:51.984-0500 [DEBUG] core: unseal key supplied
</code>```

The most relevant issues I can find in web searches are for people who inadvertently corrupted their storage:

https://github.com/hashicorp/vault/issues/5498

https://groups.google.com/forum/#!msg/vault-tool/N9fc_dUejJw/OfovdNNHBwAJ

https://discuss.hashicorp.com/t/move-vault-installation-between-servers/6990/2

I'm not sure that applies here. I'm using filesystem storage, vault is the owner of everything in /etc/vault, and I can't tell that any data has been lost or corrupted.

答:
TLDR Summary: vault will always accept keys until it hits the minimum count so it can attempt to assemble/use the resulting unseal key. Accepting keys is not an indicator of validity.

The keys distributed by the vault server are actually "shards" or "shares" (exact terminology changes between documenting sources) that are generated by splitting/sealing the master key using Shamir's secret Sharing.  Because the master key cannot be decrypted without accepting the minimum number of shards (defaults to 3, but could be configured to a different value), the vault server has no way of determining if a provided shard is a valid until that minimum is provided so it can attempt to 1. generate an unseal key from shards, and 2. use resulting key against the master key.

Hashicorp provides a decent overview of the process here:
https://www.vaultproject.io/docs/concepts/seal

More information on shamir and the math behind it here:
https://en.wikipedia.org/wiki/Shamir%27s_Secret_Sharing

Now the bad news:

The error implies you are using an incorrect set of keys to unlock your vault: the resulting unseal key is incorrect.  Either they have been changed or they are for a different vault. (maybe bad cut-n-paste newline injection?). While some have suggested a reinstall, I don't think this will solve anything. If you are desperate, you could try using a different version of vault in-case there is an unseal bug in one of your distros, but that's ... a reach.

Body:
I installed vault locally and started, unsealed, and initialized the vault and added some secrets. After rebooting, I am unable to use the keys to unseal the vault. The first two unseal keys are accepted without issue, but after submitting the third key, I get an error response:

Error unsealing: Error making API request.

URL: PUT https://127.0.0.1:28200/v1/sys/unseal
Code: 500. Errors:

* failed to decrypt encrypted stored keys: cipher: message authentication failed

Any ideas what is going on? I am running vault version 1.4.2. The command I am using is vault operator unseal. The server config is:

vault_server.hcl

listener "tcp" {
  address = "127.0.0.1:28200"
  tls_cert_file = "/etc/vault/certs/vault_cert.crt"
  tls_key_file = "/etc/vault/certs/vault_cert.key"
}
storage "file" {
  path = "/etc/vault/mnt/data"
}

api_addr = "https://127.0.0.1:28200" # my $VAULT_ADDR is https://127.0.0.1:28200
disable_mlock = true

The relevant log output:

Jun 12 21:26:24 lambda vault[1147]: 2020-06-12T21:26:24.537-0500 [DEBUG] core: unseal key supplied
Jun 12 21:26:24 lambda vault[1147]: 2020-06-12T21:26:24.537-0500 [DEBUG] core: cannot unseal, not enough keys: keys=1 threshold=3 nonce=920f7d80-fdcc-3bc3-149e-8b069ef23acb
Jun 12 21:26:38 lambda vault[1147]: 2020-06-12T21:26:38.069-0500 [DEBUG] core: unseal key supplied
Jun 12 21:26:38 lambda vault[1147]: 2020-06-12T21:26:38.069-0500 [DEBUG] core: cannot unseal, not enough keys: keys=2 threshold=3 nonce=920f7d80-fdcc-3bc3-149e-8b069ef23acb
Jun 12 21:26:51 lambda vault[1147]: 2020-06-12T21:26:51.984-0500 [DEBUG] core: unseal key supplied

The most relevant issues I can find in web searches are for people who inadvertently corrupted their storage:

https://github.com/hashicorp/vault/issues/5498

https://groups.google.com/forum/#!msg/vault-tool/N9fc_dUejJw/OfovdNNHBwAJ

https://discuss.hashicorp.com/t/move-vault-installation-between-servers/6990/2

I'm not sure that applies here. I'm using filesystem storage, vault is the owner of everything in /etc/vault, and I can't tell that any data has been lost or corrupted.