问:
Changing the date format to yyyy-mm-dd
I've got a date column that contains dates in mixed format. For example:

A

21.03.1990

03/21/1990

So, basically there are two different formats in one column: dd.mm.yyyy and mm/dd/yyyy. I'm trying to write a VBA script to change format of all dates in the column to be yyyy-mm-dd. That's what I've got so far:

```<code>Sub changeFormat()

Dim rLastCell As Range
Dim cell As Range, i As Long
Dim LValue As String

i = 1

With ActiveWorkbook.Worksheets("Sheet1")
    Set rLastCell = .Range("A65536").End(xlUp)
    On Error Resume Next
    For Each cell In .Range("A1:A" & rLastCell.Row)
        LValue = Format(cell.Value, "yyyy-mm-dd")
        .Range("B" & i).Value = LValue
        i = i + 1
    Next cell
    On Error GoTo 0
End With

End Sub
</code>```

I know that it's not elegant piece of code, but I'm beginner with VBA so please forgive me.
The problem with that code is that it just rewrite unchanged A column into column B, when I change argument in Format function from yyyy-mm-dd to dd/mm/yyyy it works, but only for dates in format mm/dd/yyyy, and leaves dd.mm.yyyy untouched. I would appreciate any advice.

答:
UPDATED: NEW ANSWER

Here is a solution that will do the job! The sub routine includes a function that does the replacement (the function itself is really useful!). Run the sub and all occurances in column A will be fixed.

```<code>Sub FixDates()

Dim cell As range
Dim lastRow As Long

lastRow = range("A" & Rows.count).End(xlUp).Row

For Each cell In range("A1:A" & lastRow)
    If InStr(cell.Value, ".") <> 0 Then
        cell.Value = RegexReplace(cell.Value, _
        "(\d{2})\.(\d{2})\.(\d{4})", "$3-$2-$1")
    End If
    If InStr(cell.Value, "/") <> 0 Then
        cell.Value = RegexReplace(cell.Value, _
        "(\d{2})/(\d{2})/(\d{4})", "$3-$1-$2")
    End If
    cell.NumberFormat = "yyyy-mm-d;@"
Next

End Sub
</code>```

Place this function in the same module:

```<code>Function RegexReplace(ByVal text As String, _
                      ByVal replace_what As String, _
                      ByVal replace_with As String) As String

Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.pattern = replace_what
RE.Global = True
RegexReplace = RE.Replace(text, replace_with)

End Function
</code>```

How it works: I have a nifty RegexReplace function that allows you to do replace using regular expressions. The sub mearly loops through your A column and does a regex replace for those 2 cases you mentioned. The reason I use an Instr() first is to determain if it needs the replacement, and which kind. You could technically skip this but doing replace on cells that don't need it is really costly. At the end I format the cell to your custom date format regardless of what's inside for safe measure.

In case you aren't familiar with Regex (for ref: http://www.regular-expressions.info/), the expression I am using is:

Each item in () are capture groups - aka, the stuff you want to mess with

\d stands for a number [0-9].

{2} means 2 of, and {4} mean 4 of. I have been explicit here for safety.

The \ before the . in the first replace is needed since "." has special meaning.

In VBA regex, you refer to capture groups by using $ + no. of group. This is how I flip the order of the 3 items.

Title: Changing the date format to yyyy-mm-dd

Body:
I've got a date column that contains dates in mixed format. For example:

A

21.03.1990

03/21/1990

So, basically there are two different formats in one column: dd.mm.yyyy and mm/dd/yyyy. I'm trying to write a VBA script to change format of all dates in the column to be yyyy-mm-dd. That's what I've got so far:

Sub changeFormat()

Dim rLastCell As Range
Dim cell As Range, i As Long
Dim LValue As String

i = 1

With ActiveWorkbook.Worksheets("Sheet1")
    Set rLastCell = .Range("A65536").End(xlUp)
    On Error Resume Next
    For Each cell In .Range("A1:A" & rLastCell.Row)
        LValue = Format(cell.Value, "yyyy-mm-dd")
        .Range("B" & i).Value = LValue
        i = i + 1
    Next cell
    On Error GoTo 0
End With

End Sub

I know that it's not elegant piece of code, but I'm beginner with VBA so please forgive me.
The problem with that code is that it just rewrite unchanged A column into column B, when I change argument in Format function from yyyy-mm-dd to dd/mm/yyyy it works, but only for dates in format mm/dd/yyyy, and leaves dd.mm.yyyy untouched. I would appreciate any advice.

Body:
UPDATED: NEW ANSWER

Here is a solution that will do the job! The sub routine includes a function that does the replacement (the function itself is really useful!). Run the sub and all occurances in column A will be fixed.

Sub FixDates()

Dim cell As range
Dim lastRow As Long

lastRow = range("A" & Rows.count).End(xlUp).Row

For Each cell In range("A1:A" & lastRow)
    If InStr(cell.Value, ".") <> 0 Then
        cell.Value = RegexReplace(cell.Value, _
        "(\d{2})\.(\d{2})\.(\d{4})", "$3-$2-$1")
    End If
    If InStr(cell.Value, "/") <> 0 Then
        cell.Value = RegexReplace(cell.Value, _
        "(\d{2})/(\d{2})/(\d{4})", "$3-$1-$2")
    End If
    cell.NumberFormat = "yyyy-mm-d;@"
Next

End Sub

Place this function in the same module:

Function RegexReplace(ByVal text As String, _
                      ByVal replace_what As String, _
                      ByVal replace_with As String) As String

Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.pattern = replace_what
RE.Global = True
RegexReplace = RE.Replace(text, replace_with)

End Function

How it works: I have a nifty RegexReplace function that allows you to do replace using regular expressions. The sub mearly loops through your A column and does a regex replace for those 2 cases you mentioned. The reason I use an Instr() first is to determain if it needs the replacement, and which kind. You could technically skip this but doing replace on cells that don't need it is really costly. At the end I format the cell to your custom date format regardless of what's inside for safe measure.

In case you aren't familiar with Regex (for ref: http://www.regular-expressions.info/), the expression I am using is:

Each item in () are capture groups - aka, the stuff you want to mess with

\d stands for a number [0-9].

{2} means 2 of, and {4} mean 4 of. I have been explicit here for safety.

The \ before the . in the first replace is needed since "." has special meaning.

In VBA regex, you refer to capture groups by using $ + no. of group. This is how I flip the order of the 3 items.


来源: stackexchange

问:
Prevent Apexcharts from scrolling to top of page on load
I have an ApexChart dynamically load when a user presses a link. Once the link is pressed, there's a backend process to load the data into the chart. However once that happens the page automatically scrolls to the top for some reason. There seems to be a related bug that was closed not long ago but I'm not sure how related it is.

How do I prevent the scroll to top on load?

Here is my chart config:

```<code>export class UserChart extends React.Component {

  state = {
    series: this.props.data,
    options: {
      chart: {
        height: 350,
        type: "bar",
        background: '#FFF',
        zoom: {
          enabled: false
        },
        toolbar: {
          show: false,
        },
      },
      noData: {
        text: "Unavailable"
      },
      dataLabels: {
        enabled: false
      },
      stroke: {
        width: [1, 1, 4]
      },
      title: {
        text: this.props.title,
        align: 'center',

      },
      xaxis: {
        categories: this.props.xaxis,
        tooltip: {
          enabled: false
        }
      },

      yaxis: [
        {
          axisTicks: {
            show: true,
          },
          axisBorder: {
            show: false,
            color: '#000'
          },
          labels: {
            formatter: v => valueFormat(v),
            style: {
              colors: '#007871',
            }
          },

          tooltip: {
            enabled: false
          }
        },

      ],
      tooltip: {
        fixed: {
          enabled: false,
          position: 'topLeft',
          offsetY: 30,
          offsetX: 60
        },
      },
      legend: {
        horizontalAlign: 'left',
        offsetX: 40
      }
    },

  };

  render() {
    return <Chart options={this.state.options} series={this.state.series} type={this.props.type} height={350}/>
  }
}
</code>```

答:
I had the exact same issue.

I obviously do not know your App's exact layout. But most probably as you render the chart, for a brief moment, you may be rendering another component (In my case it was a loader as I waited for the calls to resolve).

If there isn't enough scroll left on the page, things will jump around. I fixed it by fixing the height of the parent container of the chart and the loader.

Try wrapping your chart in a
 that has a fixed height (350px in your case).

ContentLicense: CC BY-SA 4.0

Body:
I have an ApexChart dynamically load when a user presses a link. Once the link is pressed, there's a backend process to load the data into the chart. However once that happens the page automatically scrolls to the top for some reason. There seems to be a related bug that was closed not long ago but I'm not sure how related it is.

How do I prevent the scroll to top on load?

Here is my chart config:

export class UserChart extends React.Component {

  state = {
    series: this.props.data,
    options: {
      chart: {
        height: 350,
        type: "bar",
        background: '#FFF',
        zoom: {
          enabled: false
        },
        toolbar: {
          show: false,
        },
      },
      noData: {
        text: "Unavailable"
      },
      dataLabels: {
        enabled: false
      },
      stroke: {
        width: [1, 1, 4]
      },
      title: {
        text: this.props.title,
        align: 'center',

      },
      xaxis: {
        categories: this.props.xaxis,
        tooltip: {
          enabled: false
        }
      },

      yaxis: [
        {
          axisTicks: {
            show: true,
          },
          axisBorder: {
            show: false,
            color: '#000'
          },
          labels: {
            formatter: v => valueFormat(v),
            style: {
              colors: '#007871',
            }
          },

          tooltip: {
            enabled: false
          }
        },

      ],
      tooltip: {
        fixed: {
          enabled: false,
          position: 'topLeft',
          offsetY: 30,
          offsetX: 60
        },
      },
      legend: {
        horizontalAlign: 'left',
        offsetX: 40
      }
    },

  };

  render() {
    return <Chart options={this.state.options} series={this.state.series} type={this.props.type} height={350}/>
  }
}

Body:
I had the exact same issue.

I obviously do not know your App's exact layout. But most probably as you render the chart, for a brief moment, you may be rendering another component (In my case it was a loader as I waited for the calls to resolve).

If there isn't enough scroll left on the page, things will jump around. I fixed it by fixing the height of the parent container of the chart and the loader.

Try wrapping your chart in a <div> that has a fixed height (350px in your case).


问:
why marginTop not working in using nth-of-type?
i have added margin top using nth-of-type why it is not applied ?but it working find when I am passing value 3 why ?

```<code><html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    .rc105 .rc105-subheader:nth-of-type(2) {
      margin-top: 32px;
    }

  </style>
</head>
<body>
<section class="rc105 rc105v0" >
  <div class="cwidth">
    <div class="rc105-subheader">
      <div class="rc105-ttl">
         Applications
      </div>
      <p class="desc"> together.
        <a href="#" class="link">Learn more </a></p>
    </div>

    <div class="rc105w1 rw-scrim-neutral-40bg">
    </div>

    <div class="rc105-subheader">
      <div class="rc105-ttl">
        Test
      </div>
      <p class="desc"> platform.
        <a href="#" class="link">Learn</a></p>
    </div>

    <div class="rc105w1 rw-scrim-neutral-40bg">
    </div>

  </div>
</section>
</body>
</html>
</code>```

答:
The nth-of-type is referring to the element type, in this case a div.

It is not referring to the nth instance of that class in the selector.

The 3 works because the class you are targeting is the 3rd div in that node. The 2 doesn't work because the second div does not have that class, it has some rw-scrim-neutral-40bg class.

It is typically more common to see nth-of-type used with the element in the selector, e.g. div:nth-of-type(#) or p.something:nth-of-type(#)

Body:
i have added margin top using nth-of-type why it is not applied ?but it working find when I am passing value 3 why ?

  <meta charset="UTF-8">
  <title>Title</title>

         Applications

 together.
        Learn more

        Test

 platform.
        Learn


问:
I want to make a loop of this code so that if the ord(message) entered is more than 124 it comes back to 0 and if the ord(message)
```<code>message = input("Enter a message: ")
list1 = []
for i in range(len(message)):
if ord(message[i])>124 then +3-127
list1.append(chr(ord(message[i])+3))
print("".join(list1))
</code>```

I want to make a loop of this code so that if the ord(message) entered is more than 124 it comes back to 0 and if the ord(message) is less than 124 then the loop will break. How can I make this loop?

答:
What you asked for :

message = "example : ~"
#                    ^ 126
result = "".join(
    chr(0) if ord_c > 124 else chr(ord_c + 3)
    for ord_c in map(ord, message)
)
print(message)
print(result)
```
```example : ~
h{dpsoh#=#�
```

In the ASCII table, h is 3 after e, { is 3 after x, ...

And 0 is not a printable character, so you get tofu : �

Body:
message = input("Enter a message: ")
list1 = []
for i in range(len(message)):
if ord(message[i])>124 then +3-127
list1.append(chr(ord(message[i])+3))
print("".join(list1))

I want to make a loop of this code so that if the ord(message) entered is more than 124 it comes back to 0 and if the ord(message) is less than 124 then the loop will break. How can I make this loop?

Body:
What you asked for :

message = "example : ~"
#                    ^ 126
result = "".join(
    chr(0) if ord_c > 124 else chr(ord_c + 3)
    for ord_c in map(ord, message)
)
print(message)
print(result)

example : ~
h{dpsoh#=#�

In the ASCII table, h is 3 after e, { is 3 after x, ...

And 0 is not a printable character, so you get tofu : �


问:
SQL Dynamic Exchange Rate
I'm trying to create a stored procedure that provided the exchange rate based on the users selection.

When I simply type this query, it works fine:

```<code>SELECT RATE

FROM USERCONFIG.dbo.curr

WHERE CODE = 'GBP'
</code>```

However when I try to transfer this into a stored procedure:

```<code>ALTER PROCEDURE [dbo].[TEST] (@CCY char(3))

AS
BEGIN

    SET NOCOUNT ON;

EXEC('

SELECT RATE

FROM USERCONFIG.dbo.curr

WHERE CODE = ' + @CCY + '

    ')

END
</code>```

I get the following error message and I can't work out why.

答:
Aside from the design questions (see comments) your dynamic code tries to execute the following query:

```<code>SELECT RATE
FROM USERCONFIG.dbo.curr
WHERE CODE = GBP
</code>```

So it tries to match column CODE to column GBP.
Hence the error.

The way to build dynamic SQL with string conversions is to use single quotes twice around the string like:

```<code>'SELECT RATE
 FROM USERCONFIG.dbo.curr
 WHERE CODE = ''' + @CCY + '''
'
</code>```

The repeated single quotes are turned into a single quote on execution.

Title: SQL Dynamic Exchange Rate

Body:
I'm trying to create a stored procedure that provided the exchange rate based on the users selection.

When I simply type this query, it works fine:

SELECT RATE

FROM USERCONFIG.dbo.curr

WHERE CODE = 'GBP'

However when I try to transfer this into a stored procedure:

ALTER PROCEDURE [dbo].[TEST] (@CCY char(3))

AS
BEGIN

    SET NOCOUNT ON;

EXEC('

SELECT RATE

FROM USERCONFIG.dbo.curr

WHERE CODE = ' + @CCY + '

    ')

END

I get the following error message and I can't work out why.

Body:
Aside from the design questions (see comments) your dynamic code tries to execute the following query:

SELECT RATE
FROM USERCONFIG.dbo.curr
WHERE CODE = GBP

So it tries to match column CODE to column GBP.
Hence the error.

The way to build dynamic SQL with string conversions is to use single quotes twice around the string like:

'SELECT RATE
 FROM USERCONFIG.dbo.curr
 WHERE CODE = ''' + @CCY + '''
'

The repeated single quotes are turned into a single quote on execution.


问:
onBackPressed location update android
i have a problem. I have 2 MapActivitys. In first i display some places on the map and have i listView with that places. When i click on listView it opens second Map and display one place on map and under some info about that place. Update location is good, but when i press Back button it displays first activity with a location not updated. My question is how to update location in first activity when pressed back button in second??? This is what i have done:

```<code>@Override
public void onBackPressed() {
    Intent data = new Intent();
    data.putExtra("Latitude", location.getLatitude() );
    data.putExtra("Longitude", location.getLongitude());
    setResult(RESULT_OK,data);
    super.onBackPressed();

}
 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode == request_Code){
        if(resultCode == RESULT_OK){
                            Location location = new Location(provider);
            location.setLatitude(data.getDoubleExtra("Latitude", 0));
            location.setLongitude(data.getDoubleExtra("Longitude", 0));
            listener.onLocationChanged(location);
        }
    }
    super.onActivityResult(requestCode, resultCode, data);
}
</code>```

This is solution for my problem

答: In first activity,start second activity by startActivityForResult().Then implement onActivityResult() where update your location.

ContentLicense: CC BY-SA 3.0

Title: onBackPressed location update android

Body:
i have a problem. I have 2 MapActivitys. In first i display some places on the map and have i listView with that places. When i click on listView it opens second Map and display one place on map and under some info about that place. Update location is good, but when i press Back button it displays first activity with a location not updated. My question is how to update location in first activity when pressed back button in second??? This is what i have done:

@Override
public void onBackPressed() {
    Intent data = new Intent();
    data.putExtra("Latitude", location.getLatitude() );
    data.putExtra("Longitude", location.getLongitude());
    setResult(RESULT_OK,data);
    super.onBackPressed();

}
 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode == request_Code){
        if(resultCode == RESULT_OK){
                            Location location = new Location(provider);
            location.setLatitude(data.getDoubleExtra("Latitude", 0));
            location.setLongitude(data.getDoubleExtra("Longitude", 0));
            listener.onLocationChanged(location);
        }
    }
    super.onActivityResult(requestCode, resultCode, data);
}

This is solution for my problem


问:
Custom class range based for-loop over a 2D map
I have the following class MyClass that contains a 2D map (std::map<std::string, std::map<std::string,double>>).

I would like to know if it is possible to implement the MyClass::begin() MyClass::end() functions for MyClass in order to have a range-based for loop (as in the code below) that would allow me to print all doubles contained in that 2D map.

To be clear I do not want to introduce double for loops,
I would like a single for() loop

(The aim after is putting the map map as a private member of MyClass and only allow to loop over the class through that range-based for loop)

Many thanks in advance!

```<code>
class MyClass {
public:
    MyClass(){};
    ~MyClass(){};
    std::map<std::string, std::map<std::string,double>> map = {};
};

int main()
{
    MyClass myClass;
    myClass.map["a"]["a"] = 1;
    // ...
    myClass.map["e"]["c"] = 12;

    for (std::pair<const std::string, double> &obj : mycls){
        std::cout << "obj.second = " << obj.second << std::endl;
  }
  return 0;
}
</code>```

答:
Yes, It can be done. You must introduce iterator functionality.

If you look in the CPP reference here, then you can see the requirements for the range based for loop in the explanation. Only 5 functions are needed.

Your class must have a begin() function that returns a custom iterator

Your class must have a end() function that returns a custom iterator

Your class must have a custom iterator and a function for dereferencing it

Your class must have a custom iterator and a function for incrementing it

Your class must have a custom iterator and a function for comparison

The implementation of a custom iterator is very simple.

You write 5 using statements to fulfill formal requirements. Then, you need to define the internal representation of your iterator, for example a pointer or a other iterator.

In the example below, we reuse the 2 iterators from the nested maps. An iterator to the outer map and an interator for the inner map. For easier implementation of functionality, we will also store a pointer to the surrounding custom class.

The increment (and decrement operation) causes a little bit more effort, because we need to handle the wrap around of the inner map iterator.

Example: If the inner iterator reaches the end, we must increment the outer iterator and then reset the inner iterator to the begin position.

I adedd also a decrement function which faces similar challenges.

By adding a difference function, I make the whole thing even sortable, by destroying the relation of the strings to the double. So, do not do that.

But with that function, we can easily implement space ship like comparision of iterators.

Please see one of many potential solutions below. I added some more functions for your convenience.

```<code>#include<string>
#include<map>
#include<iostream>
#include <iterator>
#include <algorithm>
#include <numeric>

using Map = std::map<std::string, double>;
using MapMap = std::map<std::string, Map>;

struct MyClass {
    struct iterator; // Forward declaration

    MapMap mp{};

    bool empty() { return mp.empty(); }
    size_t size() { return std::accumulate(mp.begin(), mp.end(), 0u, [](const size_t& sum, const auto& m) { return sum + m.second.size(); }); }

    iterator begin() { return iterator(&mp, mp.begin()->second.begin(), mp.begin()); }
    iterator end() { return iterator(&mp, ((--mp.end())->second).end(), mp.end()); }

    // iterator stuff ---------------------------------------------------------------------------
    struct iterator {
        // Definitions ----------------
        using iterator_category = std::bidirectional_iterator_tag;
        using difference_type = std::ptrdiff_t;
        using value_type = double;
        using pointer = double*;
        using reference = double&;

        // Data
        MapMap* outerMapPtr{};               // Reference to surrounding nested map
        MapMap::iterator outerMapIterator{}; // Iterator to the outer part of the nesed map
        Map::iterator innerMapIterator{};    // Iterator to the outer part of the nesed map

        // Constructor for iterator. Take a pointer to the surrounding nested map and both iterators
        iterator(MapMap* const mmSD, const Map::iterator& msdIter, const MapMap::iterator& mmsdIter) :
            outerMapPtr(mmSD), innerMapIterator(msdIter), outerMapIterator(mmsdIter) {}

        // Dereferencing
        reference operator *() const { return innerMapIterator->second; }
        reference operator->() const { return **this; }

        // Comparison. Must be template, because the other iterator may be of different type
        template <typename Iter>
        bool operator != (const Iter& other) const { return(outerMapIterator != other.outerMapIterator) or (innerMapIterator != other.innerMapIterator); }
        template <typename Iter>
        bool operator == (const Iter& other) const { return(outerMapIterator == other.outerMapIterator) and (innerMapIterator == other.innerMapIterator); }

        bool operator < (const iterator& other) const { return other - *this < 0; };
        bool operator <= (const iterator& other) const { return other - *this <= 0; };
        bool operator > (const iterator& other) const { return other - *this > 0; };
        bool operator >= (const iterator& other) const { return other - *this >= 0; };

        // Arithmetic operations
        // A little bit complex
        iterator operator ++() {
            // If we are at the end with the outer iterator, we do nothing
            if (outerMapPtr->empty() or (outerMapIterator != outerMapPtr->end())) {

                // We want to increment the inner iterator. Before we do that, we check, if this is already at the end
                if (innerMapIterator != outerMapIterator->second.end())
                    ++innerMapIterator;

                // So, now the innerMapIterator can be at the end, either from the beginning or after incrementing it
                if (innerMapIterator == outerMapIterator->second.end()) {

                    // Increment outer iterator
                    ++outerMapIterator;

                    // And reset the inner interator back to begin, but only if the outer iterator is not at the end now
                    if (outerMapIterator != outerMapPtr->end())
                        innerMapIterator = outerMapIterator->second.begin();
                }
            }
            return *this;
        }
        iterator operator --() {
            // No decrementation on empty container
            if (not outerMapPtr->empty()) {

                // If we are at the end of the outer iterator then decrement it
                if (outerMapIterator == outerMapPtr->end())
                    --outerMapIterator;

                // If we are not at the begin the inner iterator
                if (innerMapIterator != outerMapIterator->second.begin())
                    --innerMapIterator;
                else {
                    // Inner iterator was at begin, therefore also decrement outer one
                    if (outerMapIterator != outerMapPtr->begin()) {
                        --outerMapIterator;
                        innerMapIterator = outerMapIterator->second.end();
                        if (innerMapIterator != outerMapIterator->second.begin())
                            --innerMapIterator;
                    }
                }
            }
            return *this;
        }

        // Derived functions
        iterator operator++(int) { iterator tmp = *this; ++* this; return tmp; }
        iterator operator--(int) { iterator tmp = *this; --* this; return tmp; }
        iterator operator +(const difference_type& n) const {
            iterator temp{ *this };  difference_type k{ n }; if (k > 0) while (k--)++temp; else while (k++)--temp; return temp;
        }
        iterator operator +=(const difference_type& n) {
            difference_type k{ n }; if (k > 0) while (k--)++* this; else while (k++)--* this; return *this;
        };
        iterator operator -(const difference_type& n) const {
            iterator temp{ *this };  difference_type k{ n }; if (k > 0) while (k--)--temp; else while (k++)++temp; return temp;
        }
        iterator operator -=(const difference_type& n) {
            difference_type k{ n }; if (k > 0) while (k--)--* this; else while (k++)++* this; return *this;
        };

        // Difference. Very inefficient
        difference_type operator-(const iterator& other) const {

            difference_type result{};
            // No subtraction on empty container
            if (not outerMapPtr->empty()) {

                int indexThis{ }, indexOther{ }, index{};

                iterator current(outerMapPtr, outerMapPtr->begin()->second.begin(), outerMapPtr->begin());
                iterator last(outerMapPtr, ((--outerMapPtr->end())->second).end(), outerMapPtr->end());

                for (; current != last; ++current, ++index) {
                    if (current  == *this)
                        indexThis = index;
                    if (current == other)
                        indexOther = index;
                }
                if (current == *this)
                    indexThis = index;
                if (current == other)
                    indexOther = index;

                if (indexThis >= 0 and indexOther >= 0)
                    result = indexThis - indexOther;
            }
            return result;
        }
    };
};

int main()
{
    MyClass mycls;
    mycls.mp["a"]["a"] = 1;
    mycls.mp["a"]["b"] = 2;
    mycls.mp["a"]["c"] = 3;
    mycls.mp["b"]["a"] = 4;
    mycls.mp["b"]["b"] = 5;
    mycls.mp["b"]["c"] = 6;
    mycls.mp["d"]["a"] = 7;
    mycls.mp["d"]["b"] = 8;
    mycls.mp["d"]["c"] = 9;
    mycls.mp["e"]["a"] = 10;
    mycls.mp["e"]["b"] = 11;
    mycls.mp["e"]["c"] = 12;

    std::cout << "\nSize: " << mycls.size() << "\n\n";

    for (double d : mycls)
        std::cout << d << ' ';

    return 0;
}

</code>```

Body:
I have the following class MyClass that contains a 2D map (std::map<std::string, std::map<std::string,double>>).

I would like to know if it is possible to implement the MyClass::begin() MyClass::end() functions for MyClass in order to have a range-based for loop (as in the code below) that would allow me to print all doubles contained in that 2D map.

To be clear I do not want to introduce double for loops,
I would like a single for() loop

(The aim after is putting the map map as a private member of MyClass and only allow to loop over the class through that range-based for loop)

Many thanks in advance!

class MyClass {
public:
    MyClass(){};
    ~MyClass(){};
    std::map<std::string, std::map<std::string,double>> map = {};
};

int main()
{
    MyClass myClass;
    myClass.map["a"]["a"] = 1;
    // ...
    myClass.map["e"]["c"] = 12;

    for (std::pair<const std::string, double> &obj : mycls){
        std::cout << "obj.second = " << obj.second << std::endl;
  }
  return 0;
}

Body:
Yes, It can be done. You must introduce iterator functionality.

If you look in the CPP reference here, then you can see the requirements for the range based for loop in the explanation. Only 5 functions are needed.

Your class must have a begin() function that returns a custom iterator

Your class must have a end() function that returns a custom iterator

Your class must have a custom iterator and a function for dereferencing it

Your class must have a custom iterator and a function for incrementing it

Your class must have a custom iterator and a function for comparison

The implementation of a custom iterator is very simple.

You write 5 using statements to fulfill formal requirements. Then, you need to define the internal representation of your iterator, for example a pointer or a other iterator.

In the example below, we reuse the 2 iterators from the nested maps. An iterator to the outer map and an interator for the inner map. For easier implementation of functionality, we will also store a pointer to the surrounding custom class.

The increment (and decrement operation) causes a little bit more effort, because we need to handle the wrap around of the inner map iterator.

Example: If the inner iterator reaches the end, we must increment the outer iterator and then reset the inner iterator to the begin position.

I adedd also a decrement function which faces similar challenges.

By adding a difference function, I make the whole thing even sortable, by destroying the relation of the strings to the double. So, do not do that.

But with that function, we can easily implement space ship like comparision of iterators.

Please see one of many potential solutions below. I added some more functions for your convenience.

#include<string>
#include<map>
#include<iostream>
#include <iterator>
#include <algorithm>
#include <numeric>

using Map = std::map<std::string, double>;
using MapMap = std::map<std::string, Map>;

struct MyClass {
    struct iterator; // Forward declaration

    MapMap mp{};

    bool empty() { return mp.empty(); }
    size_t size() { return std::accumulate(mp.begin(), mp.end(), 0u, [](const size_t& sum, const auto& m) { return sum + m.second.size(); }); }

    iterator begin() { return iterator(&mp, mp.begin()->second.begin(), mp.begin()); }
    iterator end() { return iterator(&mp, ((--mp.end())->second).end(), mp.end()); }

    // iterator stuff ---------------------------------------------------------------------------
    struct iterator {
        // Definitions ----------------
        using iterator_category = std::bidirectional_iterator_tag;
        using difference_type = std::ptrdiff_t;
        using value_type = double;
        using pointer = double*;
        using reference = double&;

        // Data
        MapMap* outerMapPtr{};               // Reference to surrounding nested map
        MapMap::iterator outerMapIterator{}; // Iterator to the outer part of the nesed map
        Map::iterator innerMapIterator{};    // Iterator to the outer part of the nesed map

        // Constructor for iterator. Take a pointer to the surrounding nested map and both iterators
        iterator(MapMap* const mmSD, const Map::iterator& msdIter, const MapMap::iterator& mmsdIter) :
            outerMapPtr(mmSD), innerMapIterator(msdIter), outerMapIterator(mmsdIter) {}

        // Dereferencing
        reference operator *() const { return innerMapIterator->second; }
        reference operator->() const { return **this; }

        // Comparison. Must be template, because the other iterator may be of different type
        template <typename Iter>
        bool operator != (const Iter& other) const { return(outerMapIterator != other.outerMapIterator) or (innerMapIterator != other.innerMapIterator); }
        template <typename Iter>
        bool operator == (const Iter& other) const { return(outerMapIterator == other.outerMapIterator) and (innerMapIterator == other.innerMapIterator); }

        bool operator < (const iterator& other) const { return other - *this < 0; };
        bool operator <= (const iterator& other) const { return other - *this <= 0; };
        bool operator > (const iterator& other) const { return other - *this > 0; };
        bool operator >= (const iterator& other) const { return other - *this >= 0; };

        // Arithmetic operations
        // A little bit complex
        iterator operator ++() {
            // If we are at the end with the outer iterator, we do nothing
            if (outerMapPtr->empty() or (outerMapIterator != outerMapPtr->end())) {

                // We want to increment the inner iterator. Before we do that, we check, if this is already at the end
                if (innerMapIterator != outerMapIterator->second.end())
                    ++innerMapIterator;

                // So, now the innerMapIterator can be at the end, either from the beginning or after incrementing it
                if (innerMapIterator == outerMapIterator->second.end()) {

                    // Increment outer iterator
                    ++outerMapIterator;

                    // And reset the inner interator back to begin, but only if the outer iterator is not at the end now
                    if (outerMapIterator != outerMapPtr->end())
                        innerMapIterator = outerMapIterator->second.begin();
                }
            }
            return *this;
        }
        iterator operator --() {
            // No decrementation on empty container
            if (not outerMapPtr->empty()) {

                // If we are at the end of the outer iterator then decrement it
                if (outerMapIterator == outerMapPtr->end())
                    --outerMapIterator;

                // If we are not at the begin the inner iterator
                if (innerMapIterator != outerMapIterator->second.begin())
                    --innerMapIterator;
                else {
                    // Inner iterator was at begin, therefore also decrement outer one
                    if (outerMapIterator != outerMapPtr->begin()) {
                        --outerMapIterator;
                        innerMapIterator = outerMapIterator->second.end();
                        if (innerMapIterator != outerMapIterator->second.begin())
                            --innerMapIterator;
                    }
                }
            }
            return *this;
        }

        // Derived functions
        iterator operator++(int) { iterator tmp = *this; ++* this; return tmp; }
        iterator operator--(int) { iterator tmp = *this; --* this; return tmp; }
        iterator operator +(const difference_type& n) const {
            iterator temp{ *this };  difference_type k{ n }; if (k > 0) while (k--)++temp; else while (k++)--temp; return temp;
        }
        iterator operator +=(const difference_type& n) {
            difference_type k{ n }; if (k > 0) while (k--)++* this; else while (k++)--* this; return *this;
        };
        iterator operator -(const difference_type& n) const {
            iterator temp{ *this };  difference_type k{ n }; if (k > 0) while (k--)--temp; else while (k++)++temp; return temp;
        }
        iterator operator -=(const difference_type& n) {
            difference_type k{ n }; if (k > 0) while (k--)--* this; else while (k++)++* this; return *this;
        };

        // Difference. Very inefficient
        difference_type operator-(const iterator& other) const {

            difference_type result{};
            // No subtraction on empty container
            if (not outerMapPtr->empty()) {

                int indexThis{ }, indexOther{ }, index{};

                iterator current(outerMapPtr, outerMapPtr->begin()->second.begin(), outerMapPtr->begin());
                iterator last(outerMapPtr, ((--outerMapPtr->end())->second).end(), outerMapPtr->end());

                for (; current != last; ++current, ++index) {
                    if (current  == *this)
                        indexThis = index;
                    if (current == other)
                        indexOther = index;
                }
                if (current == *this)
                    indexThis = index;
                if (current == other)
                    indexOther = index;

                if (indexThis >= 0 and indexOther >= 0)
                    result = indexThis - indexOther;
            }
            return result;
        }
    };
};

int main()
{
    MyClass mycls;
    mycls.mp["a"]["a"] = 1;
    mycls.mp["a"]["b"] = 2;
    mycls.mp["a"]["c"] = 3;
    mycls.mp["b"]["a"] = 4;
    mycls.mp["b"]["b"] = 5;
    mycls.mp["b"]["c"] = 6;
    mycls.mp["d"]["a"] = 7;
    mycls.mp["d"]["b"] = 8;
    mycls.mp["d"]["c"] = 9;
    mycls.mp["e"]["a"] = 10;
    mycls.mp["e"]["b"] = 11;
    mycls.mp["e"]["c"] = 12;

    std::cout << "\nSize: " << mycls.size() << "\n\n";

    for (double d : mycls)
        std::cout << d << ' ';

    return 0;
}


问:
how can i redirect my error message from console to file in Python
I need to redirect my error message from the console to a file. For this example, I need to insert the error message into a file:

```<code>Traceback (most recent call last):
  File "C:/Users/", line 5, in <module>
    1/0
ZeroDivisionError: division by zero"
</code>```

I have already tried to do something like this:

```<code>from contextlib import redirect_stdout

with open('error.txt', 'w') as f:
    with redirect_stdout(f):
        1/0
        print('here is my error')
</code>```

答:
If you plan to run your script in console itself, you can just use the bash's ">" operator to send the input of your command (in this situation : your script) in a file just like this :

```<code>python ./yourScript > ./outputFile
</code>```

Everything that your script will print will go in the specified file.

Body:
I need to redirect my error message from the console to a file. For this example, I need to insert the error message into a file:

Traceback (most recent call last):
  File "C:/Users/", line 5, in <module>
    1/0
ZeroDivisionError: division by zero"

I have already tried to do something like this:

from contextlib import redirect_stdout

with open('error.txt', 'w') as f:
    with redirect_stdout(f):
        1/0
        print('here is my error')

Body:
If you plan to run your script in console itself, you can just use the bash's ">" operator to send the input of your command (in this situation : your script) in a file just like this :

python ./yourScript > ./outputFile

Everything that your script will print will go in the specified file.


问:
golang: Insert to a sorted slice
What's the most efficient way of inserting an element to a sorted slice?

I tried a couple of things but all ended up using at least 2 appends which as I understand makes a new copy of the slice

答:
There are two approaches mentioned here to insert into the slice when the position i is known:

data = append(data, "")
copy(data[i+1:], data[i:])
data[i] = s
```
<p>and</p>
<pre class="lang-golang prettyprint-override"><code>data = append(data[:i+1], data[i:]...)
data[i] = s
</code>```

I just benchmarked both with go1.18beta2, and the first solution is approximately 10% faster.

Title: golang: Insert to a sorted slice

Body:
There are two approaches mentioned here to insert into the slice when the position i is known:

data = append(data, "")
copy(data[i+1:], data[i:])
data[i] = s

and

data = append(data[:i+1], data[i:]...)
data[i] = s

I just benchmarked both with go1.18beta2, and the first solution is approximately 10% faster.


问:
Refit Python Statsmodel ARIMA model parameters to new data and predict
I've stored the coefficients of intercept, AR, MA off ARIMA model of statsmodel package

```<code>x = df_sku
x_train = x['Weekly_Volume_Sales']

x_train_log = np.log(x_train)
x_train_log[x_train_log == -np.inf] = 0
x_train_mat = x_train_log.as_matrix()

model = ARIMA(x_train_mat, order=(1,1,1))
model_fit = model.fit(disp=0)
res = model_fit.predict(start=1, end=137, exog=None, dynamic=False)
print(res)
params = model_fit.params
</code>```

But I'm unable to find any documentation on statsmodel that lets me refit the model parameters onto a set of new data and predict N steps.

Has anyone been able to accomplishing refitting the model and predicting out of time samples ?

I'm trying to accomplish something similar to R:

```<code># Refit the old model with testData
new_model <- Arima(as.ts(testData.zoo), model = old_model)
</code>```

答:
Great question. I have found such example: https://alkaline-ml.com/pmdarima/develop/auto_examples/arima/example_add_new_samples.html

briefly:

```<code>import pmdarima as pmd

...

### split data as train/test:
train, test = ...

### fit initial model on `train` data:
arima = pmd.auto_arima(train)

...

### update initial fit with `test` data:
arima.update(test)

...

### create forecast using updated fit for N steps:
new_preds = arima.predict(n_periods=10)
</code>```

Body:
I've stored the coefficients of intercept, AR, MA off ARIMA model of statsmodel package

x = df_sku
x_train = x['Weekly_Volume_Sales']

x_train_log = np.log(x_train)
x_train_log[x_train_log == -np.inf] = 0
x_train_mat = x_train_log.as_matrix()

model = ARIMA(x_train_mat, order=(1,1,1))
model_fit = model.fit(disp=0)
res = model_fit.predict(start=1, end=137, exog=None, dynamic=False)
print(res)
params = model_fit.params

But I'm unable to find any documentation on statsmodel that lets me refit the model parameters onto a set of new data and predict N steps.

Has anyone been able to accomplishing refitting the model and predicting out of time samples ?

I'm trying to accomplish something similar to R:

# Refit the old model with testData
new_model <- Arima(as.ts(testData.zoo), model = old_model)

Body:
Great question. I have found such example: https://alkaline-ml.com/pmdarima/develop/auto_examples/arima/example_add_new_samples.html

briefly:

import pmdarima as pmd

...

### split data as train/test:
train, test = ...

### fit initial model on `train` data:
arima = pmd.auto_arima(train)

...

### update initial fit with `test` data:
arima.update(test)

...

### create forecast using updated fit for N steps:
new_preds = arima.predict(n_periods=10)


问:
Get a portion of numbers from a pandas column with dtype int
How do I get the first 8 digits from a column with 15 digits?

```<code>data = [['tom', 355552107972100], ['nick', 356557107972103], ['juli', 455552107972100]]

df = pd.DataFrame(data, columns = ['Name', 'Code'])
</code>```
```<code>    Name    Code
0   tom     355552107972100
1   nick    356557107972103
2   juli    455552107972100
</code>```

I want to create a new column with the first 8 digits from the code column

答:
@jezrael comment is correct, but you can also divide each number by 10000000, and convert to int:

```<code>df['Code'] = (df['Code']/10000000).astype('int')
</code>```

This will result in trimming the 7 right digits.

Body:
How do I get the first 8 digits from a column with 15 digits?

data = [['tom', 355552107972100], ['nick', 356557107972103], ['juli', 455552107972100]]

df = pd.DataFrame(data, columns = ['Name', 'Code'])

    Name    Code
0   tom     355552107972100
1   nick    356557107972103
2   juli    455552107972100

I want to create a new column with the first 8 digits from the code column

Body:
@jezrael comment is correct, but you can also divide each number by 10000000, and convert to int:

df['Code'] = (df['Code']/10000000).astype('int')

This will result in trimming the 7 right digits.


问:
Multiple GLSurfaceView moving at the same time
I am facing an strange issue not sure why this is happening.

I have a Java based Activity which has a LinearLayout. This LinearLayout consists of two GLSurfaceView. All the associated methods of GLSurfaceView like OnDraw, SurfaceChanged etc are moving call down to JNI layer. Inside the JNI layer I am drawing a cube using OpenGLES. I have also created a touch listener and have associated it with first GLSurfaceView. Once I get a touch event I move the call to JNI layer and randomly rotate the first cube.

Problem is when I rotate my first cube both the cubes rotates at exactly same angle. I have debugged this issue for last four hours and I am pretty sure there is nothing wrong in my logic. But for some unknown reason when I make change in one GLSurfaceView other cube changes automatically.

Any ideas? Similar issues? Guess?

Update

I am using same context i.e. my activity for both GLSurfaceView. Basically I have a class inside C++ which draws cube through opengles. Now I am successfully creating two cubes and displaying them simultaneously. Both cubes have different texture on them which I am passing via Java layer. My c++ class has a method which randomly rotates the cube. Problem is if I call method of one cube to rotate it other automatically rotates at same angle no make what I do.

答: Without your code, I'd guess you are initializing your GLSurfaceView's using the same context. When sharing a context changing one will change the other because they will share the same GL10 instance in the Renderer. I don't program in android, but in general you'd use multiple "viewports" to display different things.</p>


问:
Reorder vector in R according to index vector
I have a vector of elements that I want to bring in a new order. The order is defined in an index vector:

```<code>vector <- c("l","e","s","k","c","w","a","o","f","t","o","r","v")
index <- c(11,8,1,5,4,13,3,6,10,2,12,9,7)
</code>```

I want to reorder the vector according to the index such that the first element goes to position 11, the second one position 8, the third to 1 etc.

I am sure that there is a very simple one-liner for this but I haven't found a solution yet despite playing around with sort() and order() for some time.

答:
Answer goes to akrun.

You can use a subsetting mechanism, which allows to manipulate indices inside of square brackets. order function returns the positions in the sorted vector. Then you use the output of order function to reorder a character string.

```<code>vector <- c("l", "e", "s", "k", "c", "w", "a", "o", "f", "t", "o", "r", "v")
index <- c(11, 8, 1, 5, 4, 13, 3, 6, 10, 2, 12, 9, 7)

vector[order(index)]
# [1] "s" "t" "a" "c" "k" "o" "v" "e" "r" "f" "l" "o" "w"
</code>```

Body:
I have a vector of elements that I want to bring in a new order. The order is defined in an index vector:

vector <- c("l","e","s","k","c","w","a","o","f","t","o","r","v")
index <- c(11,8,1,5,4,13,3,6,10,2,12,9,7)

I want to reorder the vector according to the index such that the first element goes to position 11, the second one position 8, the third to 1 etc.

I am sure that there is a very simple one-liner for this but I haven't found a solution yet despite playing around with sort() and order() for some time.

Body:
Answer goes to akrun.

You can use a subsetting mechanism, which allows to manipulate indices inside of square brackets. order function returns the positions in the sorted vector. Then you use the output of order function to reorder a character string.

vector <- c("l", "e", "s", "k", "c", "w", "a", "o", "f", "t", "o", "r", "v")
index <- c(11, 8, 1, 5, 4, 13, 3, 6, 10, 2, 12, 9, 7)

vector[order(index)]
# [1] "s" "t" "a" "c" "k" "o" "v" "e" "r" "f" "l" "o" "w"


问:
Get the user's email address from Azure AD via OpenID Connect
I'm trying to authenticate users to my site with their Office 365 accounts, so I have been following the guidance on using the OWIN OpenID Connect middleware to add authentication and successfully managed to authenticate and retrieve their profile.

I am now trying to get the email address of the user (so I can populate their system account with their contact details), but I can't seem to get an email claim back. I have tried making a request using the scope openid profile email, but the claim-set does not contain any mail information.

Is there a way to get the email of a user from Azure AD via the OpenID Connect endpoint?

答:
Get the upn value from the user's claims:

```<code>var userClaims = User.Identity as System.Security.Claims.ClaimsIdentity;
string email = userClaims?.FindFirst(System.Security.Claims.ClaimTypes.Upn)?.Value;
</code>```

Body:
Get the upn value from the user's claims:

var userClaims = User.Identity as System.Security.Claims.ClaimsIdentity;
string email = userClaims?.FindFirst(System.Security.Claims.ClaimTypes.Upn)?.Value;


问:
Drop redundant rows for group in pandas
I have the following DataFrame:

```<code>import pandas as pd

data = {'id':  ['A','A','A','A','A','A',
                'A','A','A','A','A','A',
                'B','B','B','B','B','B',
               'C', 'C', 'C', 'C', 'C', 'C',
               'D', 'D', 'D', 'D', 'D', 'D'],
        'city':['London', 'London','London', 'London', 'London', 'London',
                'New York', 'New York', 'New York', 'New York', 'New York', 'New York',
                'Milan', 'Milan','Milan', 'Milan','Milan', 'Milan',
               'Paris', 'Paris', 'Paris', 'Paris', 'Paris', 'Paris',
               'Berlin', 'Berlin','Berlin', 'Berlin','Berlin', 'Berlin'],
        'year': [2000,2001, 2002, 2003, 2004, 2005,
                2000,2001, 2002, 2003, 2004, 2005,
                 2000,2001, 2002, 2003, 2004, 2005,
                2000,2001, 2002, 2003, 2004, 2005,
                2000,2001, 2002, 2003, 2004, 2005],
        't': [0,0,0,0,1,0,
              0,0,0,0,0,1,
              0,0,0,0,0,0,
              0,0,1,0,0,0,
             0,0,0,0,1,0]}

df = pd.DataFrame(data)
</code>```

For each group id - city, I need to drop the rows for those higher years after t=1. For instance, id = A is in London in year=2004 (t=1). I want to drop the rows for the group A - London when year=2005. Please note that if an id is never in a city over 2000-2005, I want to keep all the rows (see, for instance, id = B in Milan).

The desired output:

```<code>import pandas as pd

data = {'id':  ['A','A','A','A','A',
                'A','A','A','A','A','A',
                'B','B','B','B','B','B',
               'C', 'C', 'C',
               'D', 'D', 'D', 'D', 'D'],
        'city':['London', 'London','London', 'London', 'London',
                'New York', 'New York', 'New York', 'New York', 'New York', 'New York',
                'Milan', 'Milan','Milan', 'Milan','Milan', 'Milan',
               'Paris', 'Paris', 'Paris',
               'Berlin', 'Berlin','Berlin', 'Berlin','Berlin'],
        'year': [2000,2001, 2002, 2003, 2004,
                2000,2001, 2002, 2003, 2004, 2005,
                 2000,2001, 2002, 2003, 2004, 2005,
                2000,2001, 2002,
                2000,2001, 2002, 2003, 2004],
        't': [0,0,0,0,1,
              0,0,0,0,0,1,
              0,0,0,0,0,0,
              0,0,1,
             0,0,0,0,1]}

df = pd.DataFrame(data)
</code>```

答:
Idea is use cumualtive sum per groups, but need shift values and then remove all rows after first 1 in boolean indexing:

```<code>#if not sorted years per groups
#df = df.sort_values(['id','city','year'])

df = df[~df.groupby(['id', 'city'])['t'].transform(lambda x: x.shift().cumsum()).gt(0)]

print (df)
   id      city  year  t
0   A    London  2000  0
1   A    London  2001  0
2   A    London  2002  0
3   A    London  2003  0
4   A    London  2004  1
6   A  New York  2000  0
7   A  New York  2001  0
8   A  New York  2002  0
9   A  New York  2003  0
10  A  New York  2004  0
11  A  New York  2005  1
12  B     Milan  2000  0
13  B     Milan  2001  0
14  B     Milan  2002  0
15  B     Milan  2003  0
16  B     Milan  2004  0
17  B     Milan  2005  0
18  C     Paris  2000  0
19  C     Paris  2001  0
20  C     Paris  2002  1
24  D    Berlin  2000  0
25  D    Berlin  2001  0
26  D    Berlin  2002  0
27  D    Berlin  2003  0
28  D    Berlin  2004  1
</code>```

Title: Drop redundant rows for group in pandas

Body:
I have the following DataFrame:

import pandas as pd

data = {'id':  ['A','A','A','A','A','A',
                'A','A','A','A','A','A',
                'B','B','B','B','B','B',
               'C', 'C', 'C', 'C', 'C', 'C',
               'D', 'D', 'D', 'D', 'D', 'D'],
        'city':['London', 'London','London', 'London', 'London', 'London',
                'New York', 'New York', 'New York', 'New York', 'New York', 'New York',
                'Milan', 'Milan','Milan', 'Milan','Milan', 'Milan',
               'Paris', 'Paris', 'Paris', 'Paris', 'Paris', 'Paris',
               'Berlin', 'Berlin','Berlin', 'Berlin','Berlin', 'Berlin'],
        'year': [2000,2001, 2002, 2003, 2004, 2005,
                2000,2001, 2002, 2003, 2004, 2005,
                 2000,2001, 2002, 2003, 2004, 2005,
                2000,2001, 2002, 2003, 2004, 2005,
                2000,2001, 2002, 2003, 2004, 2005],
        't': [0,0,0,0,1,0,
              0,0,0,0,0,1,
              0,0,0,0,0,0,
              0,0,1,0,0,0,
             0,0,0,0,1,0]}

df = pd.DataFrame(data)

For each group id - city, I need to drop the rows for those higher years after t=1. For instance, id = A is in London in year=2004 (t=1). I want to drop the rows for the group A - London when year=2005. Please note that if an id is never in a city over 2000-2005, I want to keep all the rows (see, for instance, id = B in Milan).

The desired output:

import pandas as pd

data = {'id':  ['A','A','A','A','A',
                'A','A','A','A','A','A',
                'B','B','B','B','B','B',
               'C', 'C', 'C',
               'D', 'D', 'D', 'D', 'D'],
        'city':['London', 'London','London', 'London', 'London',
                'New York', 'New York', 'New York', 'New York', 'New York', 'New York',
                'Milan', 'Milan','Milan', 'Milan','Milan', 'Milan',
               'Paris', 'Paris', 'Paris',
               'Berlin', 'Berlin','Berlin', 'Berlin','Berlin'],
        'year': [2000,2001, 2002, 2003, 2004,
                2000,2001, 2002, 2003, 2004, 2005,
                 2000,2001, 2002, 2003, 2004, 2005,
                2000,2001, 2002,
                2000,2001, 2002, 2003, 2004],
        't': [0,0,0,0,1,
              0,0,0,0,0,1,
              0,0,0,0,0,0,
              0,0,1,
             0,0,0,0,1]}

df = pd.DataFrame(data)

Body:
Idea is use cumualtive sum per groups, but need shift values and then remove all rows after first 1 in boolean indexing:

#if not sorted years per groups
#df = df.sort_values(['id','city','year'])

df = df[~df.groupby(['id', 'city'])['t'].transform(lambda x: x.shift().cumsum()).gt(0)]

print (df)
   id      city  year  t
0   A    London  2000  0
1   A    London  2001  0
2   A    London  2002  0
3   A    London  2003  0
4   A    London  2004  1
6   A  New York  2000  0
7   A  New York  2001  0
8   A  New York  2002  0
9   A  New York  2003  0
10  A  New York  2004  0
11  A  New York  2005  1
12  B     Milan  2000  0
13  B     Milan  2001  0
14  B     Milan  2002  0
15  B     Milan  2003  0
16  B     Milan  2004  0
17  B     Milan  2005  0
18  C     Paris  2000  0
19  C     Paris  2001  0
20  C     Paris  2002  1
24  D    Berlin  2000  0
25  D    Berlin  2001  0
26  D    Berlin  2002  0
27  D    Berlin  2003  0
28  D    Berlin  2004  1


问:
How to generate HS256 secret key in Python & Flask-JWT-Extended?
I am creating a login system and using Flask-JWT-Extended in my project. However, when I wanted to create a HS256 secret key to encode my JWT, I couldn't find any proper way to do this. Is there any suitable way to do this in Python, Flask? Thanks in advance.</p>

答:
When you set the configuration options in the flask app

# Example from flask-jwt-extended docs
app = Flask(__name__)

# Setup the Flask-JWT-Extended extension
app.config["JWT_SECRET_KEY"] = "super-secret"  # Change this!
jwt = JWTManager(app)
```
<p>you can also add the config option <code>JWT_ALGORITHM</code> e.g.</p>
<pre class="lang-py prettyprint-override"><code>app.config["JWT_ALGORITHM"] = "HS256"
</code>```

The rest of the basic usage tutorial will show you how to actually create the token.

See docs for this config option and others here

Body:
When you set the configuration options in the flask app

# Example from flask-jwt-extended docs
app = Flask(__name__)

# Setup the Flask-JWT-Extended extension
app.config["JWT_SECRET_KEY"] = "super-secret"  # Change this!
jwt = JWTManager(app)

you can also add the config option JWT_ALGORITHM e.g.

app.config["JWT_ALGORITHM"] = "HS256"

The rest of the basic usage tutorial will show you how to actually create the token.

See docs for this config option and others here


问:
In Gatsby.js, use an image as li bullet
I am trying to use an image as an "li" bullet point. What I am trying tis to import the image as a "StaticImage" to use it in Styled Components, like this:

```<code>import { StaticImage } from "gatsby-plugin-image";

export function Bullet() {
    return <StaticImage src="../images/bullet.png" alt="li bullet" />;
}
</code>```

Then I'm trying several different solutions to add it as a bullepoint, for example, as a pseudo element:

```<code>
li {
    &:before {
        content: ${Bullet}
    }

}
</code>```

But I always get [Object object]. Is there any way of doing this?

答:
Why you don't use directly:

```<code>li {
    &:before {
        content: '../images/bullet.png'
    }

}
</code>```

Or even:

```<code>import bullet from '../images/bullet.png'
li {
    &:before {
        content: ${bullet}
    }

}
</code>```

You may need to do: content: ${props => props.bullet} depending on your implementation

If you want to use your own component you can try using the props, following the last approach as:

```<code>li {
     &:before {
        content: ${props => props.Bullet}
     }
}
</code>```

Title: In Gatsby.js, use an image as li bullet

Body:
I am trying to use an image as an "li" bullet point. What I am trying tis to import the image as a "StaticImage" to use it in Styled Components, like this:

import { StaticImage } from "gatsby-plugin-image";

export function Bullet() {
    return <StaticImage src="../images/bullet.png" alt="li bullet" />;
}

Then I'm trying several different solutions to add it as a bullepoint, for example, as a pseudo element:

li {
    &:before {
        content: ${Bullet}
    }

}

But I always get [Object object]. Is there any way of doing this?

Body:
Why you don't use directly:

li {
    &:before {
        content: '../images/bullet.png'
    }

}

Or even:

import bullet from '../images/bullet.png'
li {
    &:before {
        content: ${bullet}
    }

}

You may need to do: content: ${props => props.bullet} depending on your implementation

If you want to use your own component you can try using the props, following the last approach as:

li {
     &:before {
        content: ${props => props.Bullet}
     }
}


问:
Notify icon does not show in tray C# winforms
why does my notification icon does not show in system tray when i launch my windows form?

Here is what i am doing.

I have a windows service which launches my tray application which is a windows form application (I am using impersonation to launch that application in current user's context).
In tray application i am launching a form which contains notify icon.

The problem here is that the notify icon some times does not appear in system tray and i am unable to find out why.

In the OnLoad method of the form i am setting form's visible property to false.
Also i am doing some remoting service calls (like ipc). Is that a problem?

How do i make my notify icon to appear always in system tray?

EDIT: Here is the code for OnLoad function

```<code>protected override void OnLoad(System.EventArgs e)
{
    this.Visible = false;
    //Get some value from registry
    CheckForStealthMode();
    GetLoginType();
    bool GetProbeStatus = false;
    ServiceActivityInterface remoteMethods = null;
    do
    {
        try
        {
            remoteMethods = (ServiceActivityInterface)Activator.GetObject(typeof(ServiceActivityInterface), "tcp://localhost:18800/ServiceRemoting);
            ProbeStatus = remoteMethods.GetProbeStatus();
            GetProbeStatus = true;
        }
        catch (Exception exception)
        {
            GetProbeStatus = false;
            log.Error("Exception while getting the status of Probe:" + exception.Message);
        }
        finally
        {
            remoteMethods = null;
            if (!GetProbeStatus)
            {
                Thread.Sleep(5000);
                log.Debug("Retrying to get the probe status.");
            }
        }
    } while (!GetProbeStatus);
}
</code>```

答:
For now I would suggest a few breakpoints around the Notify icon code or other conditional statements to find if something isn't being called. Try and find a consistent reproduction in order to help you diagnose what is going on. I have had strange goings on in past of which the most confusin was one linked to a timed event

I would also suggest (and this may solve your problem if it does relate the Thread.Sleep method that this is not ideal. The user just gets a frozen UI. Use one of the timer classes and pick up the tick or elapsed event so the user can carry on but you still get the delay your after.

Body:
why does my notification icon does not show in system tray when i launch my windows form?

Here is what i am doing.

I have a windows service which launches my tray application which is a windows form application (I am using impersonation to launch that application in current user's context).
In tray application i am launching a form which contains notify icon.

The problem here is that the notify icon some times does not appear in system tray and i am unable to find out why.

In the OnLoad method of the form i am setting form's visible property to false.
Also i am doing some remoting service calls (like ipc). Is that a problem?

How do i make my notify icon to appear always in system tray?

EDIT: Here is the code for OnLoad function

protected override void OnLoad(System.EventArgs e)
{
    this.Visible = false;
    //Get some value from registry
    CheckForStealthMode();
    GetLoginType();
    bool GetProbeStatus = false;
    ServiceActivityInterface remoteMethods = null;
    do
    {
        try
        {
            remoteMethods = (ServiceActivityInterface)Activator.GetObject(typeof(ServiceActivityInterface), "tcp://localhost:18800/ServiceRemoting);
            ProbeStatus = remoteMethods.GetProbeStatus();
            GetProbeStatus = true;
        }
        catch (Exception exception)
        {
            GetProbeStatus = false;
            log.Error("Exception while getting the status of Probe:" + exception.Message);
        }
        finally
        {
            remoteMethods = null;
            if (!GetProbeStatus)
            {
                Thread.Sleep(5000);
                log.Debug("Retrying to get the probe status.");
            }
        }
    } while (!GetProbeStatus);
}


问:
Is there a way to transform a nominal DataFrame into a Bubble Plot in Altair?
I have the following code:

```<code>test_dict = {'A': ['a', 'b', 'c'], 'B': ['d', 'e', 'f'], 'C': ['g', 'h', 'i'],
            'D': ['j', 'k', 'l'], 'E': ['m', 'n', 'o'], 'F': ['p', 'q', 'r'],
            'G': ['s', 't', 'u'], 'H': ['v', 'w', 'x']}

test_df = pd.DataFrame(test_dict)
</code>```

which produces the following DataFrame:

Is there a way to transform this into a BubblePlot in Altair? I want the columns (A - H) to make up the y-axis, and I want there to be a bubble for each entry in the column (so in this case, three entries per column). Can this be done?

答:
You have wide-form data that you need to transform to long-form data (See See Wide-form vs. Long-form data in Altair's docs). You can generally address this with the Fold Transform:

import pandas as pd
import altair as alt

test_dict = {'A': ['a', 'b', 'c'], 'B': ['d', 'e', 'f'], 'C': ['g', 'h', 'i'],
             'D': ['j', 'k', 'l'], 'E': ['m', 'n', 'o'], 'F': ['p', 'q', 'r'],
             'G': ['s', 't', 'u'], 'H': ['v', 'w', 'x']}

test_df = pd.DataFrame(test_dict)

alt.Chart(test_df).transform_fold(
    list(test_df.columns), as_=['key', 'value']
).mark_point().encode(
    x='value:N',
    y='key:N',
)
```

Body:
I have the following code:

test_dict = {'A': ['a', 'b', 'c'], 'B': ['d', 'e', 'f'], 'C': ['g', 'h', 'i'],
            'D': ['j', 'k', 'l'], 'E': ['m', 'n', 'o'], 'F': ['p', 'q', 'r'],
            'G': ['s', 't', 'u'], 'H': ['v', 'w', 'x']}

test_df = pd.DataFrame(test_dict)

which produces the following DataFrame:

Is there a way to transform this into a BubblePlot in Altair? I want the columns (A - H) to make up the y-axis, and I want there to be a bubble for each entry in the column (so in this case, three entries per column). Can this be done?


问:
HardFault with STM32 caused through GSL
I successfully cross-compiled the GNU Scientific Library for my STM32F303 with an Arm Cortex M4, as I've described here:

How to crosscompile GSL for Arm Cortex M4?

However, this works fine, but now I got for every memory allocation from the GSL an HardFault. For example, this line:

```<code>gsl_vector_float *x = gsl_vector_float_alloc(2);
</code>```

or this

```<code>T = gsl_multimin_fdfminimizer_conjugate_fr;
</code>```

causes directly an HardFault. Has anyone an idea what the reason could be? I am pretty sure to have enough RAM (the IDE shows 59 kB free RAM at beginning). The problem holds only for GSL allocations, malloc stand-alone works perfectly.

Furthermore, I found on the internet some post that described thread-safety in the sense of using locks for malloc as a possible issue. Since the GSL is Thread-Safe, could this be the reason? Although I did not find any clue for using locks in the source code.

答: As in the comments described, I've used indeed the wrong linker script during cross-compiling (the default linker script). It worked after specifying the linker-script (I had to use the linker-script for the specific MCU).</p>

Title: HardFault with STM32 caused through GSL

Body:
I successfully cross-compiled the GNU Scientific Library for my STM32F303 with an Arm Cortex M4, as I've described here:

How to crosscompile GSL for Arm Cortex M4?

However, this works fine, but now I got for every memory allocation from the GSL an HardFault. For example, this line:

gsl_vector_float *x = gsl_vector_float_alloc(2);

or this

T = gsl_multimin_fdfminimizer_conjugate_fr;

causes directly an HardFault. Has anyone an idea what the reason could be? I am pretty sure to have enough RAM (the IDE shows 59 kB free RAM at beginning). The problem holds only for GSL allocations, malloc stand-alone works perfectly.

Furthermore, I found on the internet some post that described thread-safety in the sense of using locks for malloc as a possible issue. Since the GSL is Thread-Safe, could this be the reason? Although I did not find any clue for using locks in the source code.


问:
Combine multple aggregation queries into a single query
How can I combine these four queries into a single query?

select count(ornon_id) as DEC_AUTH_Y from tbbu_policies where DECL_AUTH_REQ_FLAG = 'Y' and status_code = 'ACTI';

select count(ornon_id) as DEC_AUTH_N from tbbu_policies where DECL_AUTH_REQ_FLAG = 'N'and  status_code = 'ACTI';

select count(ornon_id) as INV_AUTH_Y from tbbu_policies where INV_AUTH_REQ_FLAG = 'Y' and status_code = 'ACTI';

select count(ornon_id) as INV_AUTH_N from tbbu_policies where INV_AUTH_REQ_FLAG = 'N'  and status_code = 'ACTI';
```

答:
Use conditional aggregation:

SELECT COUNT(CASE WHEN DECL_AUTH_REQ_FLAG = 'Y' THEN ornon_id END) as DEC_AUTH_Y,
       COUNT(CASE WHEN DECL_AUTH_REQ_FLAG = 'N' THEN ornon_id END) as DEC_AUTH_N,
       COUNT(CASE WHEN INV_AUTH_REQ_FLAG  = 'Y' THEN ornon_id END) as INV_AUTH_Y,
       COUNT(CASE WHEN INV_AUTH_REQ_FLAG  = 'N' THEN ornon_id END) as INV_AUTH_N
FROM   tbbu_policies
WHERE  status_code = 'ACTI';
```


问:
Cypress sees undefined when reffering to an aliased text value
My test results in adding a row to the table. In afterEach hook I wanted to add a method to delete the newest row after the test ran so I wrote this piece of code:

```<code>deleteTheNewestRequest() {
    cy.get('table#return-request-list').find('tr').eq(1).then( firstRow => {
        cy.wrap(firstRow).find('td').eq(0).invoke('text').as('rowId')
        cy.wrap(firstRow).find('a[title="Delete"]').click()
        cy.get('button.btn-delete-return-request').click()
        cy.wrap(firstRow).find('td').first().should('not.have.text', this.rowId)
    })
}
</code>```

With 'then' I'm saving a table element to later use to find and operate on the elements inside it. I wanted to first save the value of the newest row in the table that was added after the test ran successfully, then delete and as the last step make sure that the row with the ID that was deleted is actually gone from the table. The problem is that cypress test runner assertions marks it green because it sees that value of  is not equal to 'undefined' and not, let's say 3794.

答:
You can do something like this:

deleteTheNewestRequest() {
    cy.get('table#return-request-list').find('tr').eq(1).then(firstRow => {
        cy.wrap(firstRow).find('td').eq(0).invoke('text').as('rowId')
        cy.wrap(firstRow).find('a[title="Delete"]').click()
        cy.get('button.btn-delete-return-request').click()
        cy.get('@rowId').then((rowId) => {
            cy.wrap(firstRow).find('td').first().should('not.have.text', rowId)
        })
    })
}
```

Body:
My test results in adding a row to the table. In afterEach hook I wanted to add a method to delete the newest row after the test ran so I wrote this piece of code:

deleteTheNewestRequest() {
    cy.get('table#return-request-list').find('tr').eq(1).then( firstRow => {
        cy.wrap(firstRow).find('td').eq(0).invoke('text').as('rowId')
        cy.wrap(firstRow).find('a[title="Delete"]').click()
        cy.get('button.btn-delete-return-request').click()
        cy.wrap(firstRow).find('td').first().should('not.have.text', this.rowId)
    })
}

With 'then' I'm saving a table element to later use to find and operate on the elements inside it. I wanted to first save the value of the newest row in the table that was added after the test ran successfully, then delete and as the last step make sure that the row with the ID that was deleted is actually gone from the table. The problem is that cypress test runner assertions marks it green because it sees that value of  is not equal to 'undefined' and not, let's say 3794.


问:
How to add background color for all the text come inside curly brackets in reactjs
I am using sunEditor-react to get HTML files into a text editor. I got the HTML value and displayed inside the editor successfully.

The purpose of this to edit the HTML file in the frontend.
But when I am getting the HTML template, there are some places I need to highlight and show.

I need to highlight the text inside curly brackets {}.
Can any explain me how can I do this using CSS or a function to highlight the values inside {}.

This is my current class.

```<code>import { useState } from 'react';
import SunEditor from 'suneditor-react';

import { useLocale } from 'hooks/useLocale/useLocale';
import { Button, Heading, Loader, Typography } from 'ui/atoms';

import 'suneditor/dist/css/suneditor.min.css';

import { useStyles } from './Edit.styles';
import { EditProps } from './Edit.types';
import { EditWarning } from './editWarning/EditWarning';

export const EMAIL_EDIT_WARNING_COOKIE_KEY = 'emailEditWarning';

export const Edit = ({ title, defaultTemplate }: EditProps) => {
 const classes = useStyles();
 const { formatMessage } = useLocale();
 const [htmlData, setHtmlData] = useState(defaultTemplate?.html);

 if (!defaultTemplate) {
   return <Loader className={classes.loader} />;
 }

 function reset() {
   setHtmlData(defaultTemplate?.html);
 }

 return (
   <>
     <div className={classes.button}>
       <Button type="button" onClick={reset}>
         {formatMessage({ id: 'event.emails.edit.reset' })}
       </Button>
     </div>

     <div className={classes.container}>
       <Heading variant="h4" bold className={classes.title}>
         {formatMessage({ id: 'event.emails.edit.title' })}
       </Heading>
       <Typography variant="h5" className={classes.subtitle}>
         {title}
       </Typography>

       <EditWarning name={EMAIL_EDIT_WARNING_COOKIE_KEY}>
         <div>{formatMessage({ id: 'event.emails.edit.warning_message' })}</div>
         <div>{formatMessage({ id: 'event.emails.edit.warning_note' })}</div>
       </EditWarning>
     </div>
     <SunEditor
       width="100%"
       height="100%"
       autoFocus={true}
       setContents={htmlData}

     />
   </>
 ); };
</code>```

I need to add css to  to highlight all the values inside curly brackets {}.

This is the current UI.

Here I need to highlight {{FULL_NAME}} and {{{event_name}}}.
How can I do this using CSS or any function in react?

Can any one please give a solution for this? I am trying this more than a week to get a solution?

答:
If you are receiving the HTML data as a string, you could use the string method replaceAll to replace the curly braces with span elements, and then parse the string to DOM. You could then add styling to span elements in your stylesheet as you wish.

```<code>const [htmlData, setHtmlData] = useState(defaultTemplate?.html);

const htmlWithTags = htmlData.replaceAll('{{','<span>').replaceAll('}}','</span>') //Replace curly braces with HTML elements.

const domHTML = new DOMParser().parseFromString(htmlWithTags, "text/xml"); //Parse string to actual DOM.
</code>```

You can then use the domHTML variable data to render your HTML content.

In your stylesheet:

```<code>span{
 color:red;      //Change the color and weight accordingly, or add more customisations as required.
 font-weight:bold;
}
</code>```

Body:
I am using sunEditor-react to get HTML files into a text editor. I got the HTML value and displayed inside the editor successfully.

The purpose of this to edit the HTML file in the frontend.
But when I am getting the HTML template, there are some places I need to highlight and show.

I need to highlight the text inside curly brackets {}.
Can any explain me how can I do this using CSS or a function to highlight the values inside {}.

This is my current class.

import { useState } from 'react';
import SunEditor from 'suneditor-react';

import { useLocale } from 'hooks/useLocale/useLocale';
import { Button, Heading, Loader, Typography } from 'ui/atoms';

import 'suneditor/dist/css/suneditor.min.css';

import { useStyles } from './Edit.styles';
import { EditProps } from './Edit.types';
import { EditWarning } from './editWarning/EditWarning';

export const EMAIL_EDIT_WARNING_COOKIE_KEY = 'emailEditWarning';

export const Edit = ({ title, defaultTemplate }: EditProps) => {
 const classes = useStyles();
 const { formatMessage } = useLocale();
 const [htmlData, setHtmlData] = useState(defaultTemplate?.html);

 if (!defaultTemplate) {
   return <Loader className={classes.loader} />;
 }

 function reset() {
   setHtmlData(defaultTemplate?.html);
 }

 return (
   <>

       <Button type="button" onClick={reset}>
         {formatMessage({ id: 'event.emails.edit.reset' })}
       </Button>

       <Heading variant="h4" bold className={classes.title}>
         {formatMessage({ id: 'event.emails.edit.title' })}
       </Heading>
       <Typography variant="h5" className={classes.subtitle}>
         {title}
       </Typography>

       <EditWarning name={EMAIL_EDIT_WARNING_COOKIE_KEY}>

{formatMessage({ id: 'event.emails.edit.warning_message' })}

{formatMessage({ id: 'event.emails.edit.warning_note' })}

       </EditWarning>

     <SunEditor
       width="100%"
       height="100%"
       autoFocus={true}
       setContents={htmlData}

     />
   </>
 ); };

I need to add css to  to highlight all the values inside curly brackets {}.

This is the current UI.

Here I need to highlight {{FULL_NAME}} and {{{event_name}}}.
How can I do this using CSS or any function in react?

Can any one please give a solution for this? I am trying this more than a week to get a solution?

Body:
If you are receiving the HTML data as a string, you could use the string method replaceAll to replace the curly braces with span elements, and then parse the string to DOM. You could then add styling to span elements in your stylesheet as you wish.

const [htmlData, setHtmlData] = useState(defaultTemplate?.html);

const htmlWithTags = htmlData.replaceAll('{{','<span>').replaceAll('}}','</span>') //Replace curly braces with HTML elements.

const domHTML = new DOMParser().parseFromString(htmlWithTags, "text/xml"); //Parse string to actual DOM.

You can then use the domHTML variable data to render your HTML content.

In your stylesheet:

span{
 color:red;      //Change the color and weight accordingly, or add more customisations as required.
 font-weight:bold;
}


问:
flutter image picker not working and crashing app without error on debug
I'm currently using these versions:
flutter : 2.16.0
image_picker : ^0.8.4+7

The image picker is not working. After running the app, when I click on the button to activate the pickImage function, running suddenly stops and the app crashes and stops. On debug, the only message I get is:

Lost connection to device.

Here's the code:

```<code>import 'dart:io';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:hipocampus_editors/widgets/textformfield_widget.dart';
import 'package:image_picker/image_picker.dart';

class AddSystemPage extends StatefulWidget {
  const AddSystemPage({Key? key}) : super(key: key);

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

class _AddSystemPageState extends State<AddSystemPage> {
  final _formKey = GlobalKey<FormState>();
File? image1;

  Future pickImage() async{

final image = await ImagePicker().pickImage(source: ImageSource.gallery);
if (image == null)  return;
final imageTemporary = File(image.path);
setState(() {
  image1 = imageTemporary;
});

    }
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
      child: Scaffold(
        appBar: AppBar(title: const Text('System',),),

        body: SafeArea(
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 5),
            child: Form(
              key: _formKey,
              child: Container(
                width: MediaQuery.of(context).size.width,
                padding: const EdgeInsets.symmetric(horizontal: 10),
                child: SingleChildScrollView(
                    child: Column(
                  children: [

                    ElevatedButton(onPressed: (){
                      pickImage();
                                          }, child: Text('Select image'))

                  ],
                )),
              ),
            ),
          ),
        ),
      ),
    );
    }
    }
</code>```

答:
Please check if you have registered the ImagePicker Correctly.

and if you have registered ImagePicker correctly then put a try and catch blog in the pick Image Function to get more debug information:

```<code>Future pickImage() async{

  try{
    final image = await ImagePicker().pickImage(source: ImageSource.gallery);
    if (image == null)  return;
    final imageTemporary = File(image.path);
    setState(() {
      image1 = imageTemporary;
    });
  } catch(error) {
    print("error: $error");
  }

}
</code>```

Body:
I'm currently using these versions:
flutter : 2.16.0
image_picker : ^0.8.4+7

The image picker is not working. After running the app, when I click on the button to activate the pickImage function, running suddenly stops and the app crashes and stops. On debug, the only message I get is:

Lost connection to device.

Here's the code:

import 'dart:io';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:hipocampus_editors/widgets/textformfield_widget.dart';
import 'package:image_picker/image_picker.dart';

class AddSystemPage extends StatefulWidget {
  const AddSystemPage({Key? key}) : super(key: key);

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

class _AddSystemPageState extends State<AddSystemPage> {
  final _formKey = GlobalKey<FormState>();
File? image1;

  Future pickImage() async{

final image = await ImagePicker().pickImage(source: ImageSource.gallery);
if (image == null)  return;
final imageTemporary = File(image.path);
setState(() {
  image1 = imageTemporary;
});

    }
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
      child: Scaffold(
        appBar: AppBar(title: const Text('System',),),

        body: SafeArea(
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 5),
            child: Form(
              key: _formKey,
              child: Container(
                width: MediaQuery.of(context).size.width,
                padding: const EdgeInsets.symmetric(horizontal: 10),
                child: SingleChildScrollView(
                    child: Column(
                  children: [

                    ElevatedButton(onPressed: (){
                      pickImage();
                                          }, child: Text('Select image'))

                  ],
                )),
              ),
            ),
          ),
        ),
      ),
    );
    }
    }

Body:
Please check if you have registered the ImagePicker Correctly.

and if you have registered ImagePicker correctly then put a try and catch blog in the pick Image Function to get more debug information:

Future pickImage() async{

  try{
    final image = await ImagePicker().pickImage(source: ImageSource.gallery);
    if (image == null)  return;
    final imageTemporary = File(image.path);
    setState(() {
      image1 = imageTemporary;
    });
  } catch(error) {
    print("error: $error");
  }

}


问:
XSLT : Remove XML one node based on element value & remove an element in another node
I'm facing the following problem :

The XML input is :

```<code><root>
    <ITEM_DATA>
        <DOC_NUMBER>0021182064</DOC_NUMBER>
        <ITM_NUMBER>000010</ITM_NUMBER>
        <ITEM_CATEG>ZBOM</ITEM_CATEG>
        <HG_LV_ITEM>000000</HG_LV_ITEM>
    </ITEM_DATA>

    <ITEM_DATA>
        <DOC_NUMBER>0021182064</DOC_NUMBER>
        <ITM_NUMBER>000020</ITM_NUMBER>
        <ITEM_CATEG>ZAN</ITEM_CATEG>
        <REL_FOR_BI>A</REL_FOR_BI>
        <HG_LV_ITEM>000010</HG_LV_ITEM>
        <ALTERN_ITM>000000</ALTERN_ITM>
    </ITEM_DATA>

    <ITEM_DATA>
        <DOC_NUMBER>0021182064</DOC_NUMBER>
        <ITM_NUMBER>000030</ITM_NUMBER>
        <ITEM_CATEG>ZAN</ITEM_CATEG>
        <REL_FOR_BI>A</REL_FOR_BI>
        <HG_LV_ITEM>000010</HG_LV_ITEM>
        <ALTERN_ITM>000000</ALTERN_ITM>
    </ITEM_DATA>

    <ITEM_DATA>
        <DOC_NUMBER>0021182064</DOC_NUMBER>
        <ITM_NUMBER>000040</ITM_NUMBER>
        <ITEM_CATEG>ZTAT</ITEM_CATEG>
        <REL_FOR_BI>A</REL_FOR_BI>
        <ALTERN_ITM>000000</ALTERN_ITM>
    </ITEM_DATA>
</root>
</code>```

I want to remove the XML node "ITEM_DATA" having the element "ITEM_CATEG" with value ZBOM. So to do that I apply this XSLT code :

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>
<xsl:template match="ITEM_DATA[ITEM_CATEG = 'ZBOM']"/>
  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>
</code>```

That's works fine. But I also want to remove the element "HG_LV_ITEM" in the other nodes where their value equal to "ITM_NUMBER" value and "ITEM_CATEG" = ZBOM.

The expected output result is :

```<code><root>
    <ITEM_DATA>
        <DOC_NUMBER>0021182064</DOC_NUMBER>
        <ITM_NUMBER>000020</ITM_NUMBER>
        <ITEM_CATEG>ZAN</ITEM_CATEG>
        <REL_FOR_BI>A</REL_FOR_BI>
        <ALTERN_ITM>000000</ALTERN_ITM>
    </ITEM_DATA>

    <ITEM_DATA>
        <DOC_NUMBER>0021182064</DOC_NUMBER>
        <ITM_NUMBER>000030</ITM_NUMBER>
        <ITEM_CATEG>ZAN</ITEM_CATEG>
        <REL_FOR_BI>A</REL_FOR_BI>
        <ALTERN_ITM>000000</ALTERN_ITM>
    </ITEM_DATA>

    <ITEM_DATA>
        <DOC_NUMBER>0021182064</DOC_NUMBER>
        <ITM_NUMBER>000040</ITM_NUMBER>
        <ITEM_CATEG>ZTAT</ITEM_CATEG>
        <REL_FOR_BI>A</REL_FOR_BI>
        <ALTERN_ITM>000000</ALTERN_ITM>
    </ITEM_DATA>
</root>
</code>```

Can you please share your advices ?

Thanks in advance.

答:
Please try the following XSLT.

XSLT

```<code><?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="ITEM_DATA[ITEM_CATEG = 'ZBOM']"/>

    <xsl:template match="HG_LV_ITEM[. = ../ITM_NUMBER][../ITEM_CATEG = 'ZBOM']"/>
</xsl:stylesheet>
</code>```

Body:
I'm facing the following problem :

The XML input is :

<root>
    <ITEM_DATA>
        <DOC_NUMBER>0021182064</DOC_NUMBER>
        <ITM_NUMBER>000010</ITM_NUMBER>
        <ITEM_CATEG>ZBOM</ITEM_CATEG>
        <HG_LV_ITEM>000000</HG_LV_ITEM>
    </ITEM_DATA>

    <ITEM_DATA>
        <DOC_NUMBER>0021182064</DOC_NUMBER>
        <ITM_NUMBER>000020</ITM_NUMBER>
        <ITEM_CATEG>ZAN</ITEM_CATEG>
        <REL_FOR_BI>A</REL_FOR_BI>
        <HG_LV_ITEM>000010</HG_LV_ITEM>
        <ALTERN_ITM>000000</ALTERN_ITM>
    </ITEM_DATA>

    <ITEM_DATA>
        <DOC_NUMBER>0021182064</DOC_NUMBER>
        <ITM_NUMBER>000030</ITM_NUMBER>
        <ITEM_CATEG>ZAN</ITEM_CATEG>
        <REL_FOR_BI>A</REL_FOR_BI>
        <HG_LV_ITEM>000010</HG_LV_ITEM>
        <ALTERN_ITM>000000</ALTERN_ITM>
    </ITEM_DATA>

    <ITEM_DATA>
        <DOC_NUMBER>0021182064</DOC_NUMBER>
        <ITM_NUMBER>000040</ITM_NUMBER>
        <ITEM_CATEG>ZTAT</ITEM_CATEG>
        <REL_FOR_BI>A</REL_FOR_BI>
        <ALTERN_ITM>000000</ALTERN_ITM>
    </ITEM_DATA>
</root>

I want to remove the XML node "ITEM_DATA" having the element "ITEM_CATEG" with value ZBOM. So to do that I apply this XSLT code :

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>
<xsl:template match="ITEM_DATA[ITEM_CATEG = 'ZBOM']"/>
  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

That's works fine. But I also want to remove the element "HG_LV_ITEM" in the other nodes where their value equal to "ITM_NUMBER" value and "ITEM_CATEG" = ZBOM.

The expected output result is :

<root>
    <ITEM_DATA>
        <DOC_NUMBER>0021182064</DOC_NUMBER>
        <ITM_NUMBER>000020</ITM_NUMBER>
        <ITEM_CATEG>ZAN</ITEM_CATEG>
        <REL_FOR_BI>A</REL_FOR_BI>
        <ALTERN_ITM>000000</ALTERN_ITM>
    </ITEM_DATA>

    <ITEM_DATA>
        <DOC_NUMBER>0021182064</DOC_NUMBER>
        <ITM_NUMBER>000030</ITM_NUMBER>
        <ITEM_CATEG>ZAN</ITEM_CATEG>
        <REL_FOR_BI>A</REL_FOR_BI>
        <ALTERN_ITM>000000</ALTERN_ITM>
    </ITEM_DATA>

    <ITEM_DATA>
        <DOC_NUMBER>0021182064</DOC_NUMBER>
        <ITM_NUMBER>000040</ITM_NUMBER>
        <ITEM_CATEG>ZTAT</ITEM_CATEG>
        <REL_FOR_BI>A</REL_FOR_BI>
        <ALTERN_ITM>000000</ALTERN_ITM>
    </ITEM_DATA>
</root>

Can you please share your advices ?

Thanks in advance.

Body:
Please try the following XSLT.

XSLT

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="ITEM_DATA[ITEM_CATEG = 'ZBOM']"/>

    <xsl:template match="HG_LV_ITEM[. = ../ITM_NUMBER][../ITEM_CATEG = 'ZBOM']"/>
</xsl:stylesheet>


问:
How to make route work? Laravel Sluggable (Cviebrock) with category id
I'm new to Laravel, could you push me into the right direction?

I need to render blog post on url like this site.com/posts/1/slugged-url-of-the-post/, where 1 is the category_id.

I have no problem with site.com/posts/slugged-url-of-the-post/, but absolutely stuck with adding one more parameter to the route and making it work. The database is okay, and I have no problems with displaying the post category_id as a text value, for example, in the posts.show blade file.

Please, help?

routes/web.php

Route::get('/posts/{post}', function( App\Models\Post $post) {

// need to make this work:
// Route::get('/posts/{category_id}/{post}' ...

  return view('posts.show')->with('post', $post);
});
```
<h4>app/Models/Post.php</h4>
<pre class="lang-php prettyprint-override"><code>namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Cviebrock\EloquentSluggable\Sluggable;
use Cviebrock\EloquentSluggable\SluggableScopeHelpers;

class Post extends Model
{
    use HasFactory, Sluggable, SluggableScopeHelpers;

    public function sluggable(): array
    {
        return [
            'slug' => [
                'source' => 'title',
            ],

        ];
    }

    public function getRouteKeyName(): string
    {
        return 'slug';
    }

}
</code>```

答:
I don't know if this decision is good or not, but I came up with the following:

routes/web.php

Route::get('/posts/{category}/{slug}', [PostController::class, 'getSingle']);
```
<p><strong>app/Http/Controllers/PostController.php</strong></p>
<pre class="lang-php prettyprint-override"><code>public function getSingle($category, $slug)
{

    $post = Post::where('category_id','=',$category)->where('slug','=',$slug)->first();

    return view('posts.single')->with('post', $post);
}
</code>```

Body:
I'm new to Laravel, could you push me into the right direction?

I need to render blog post on url like this site.com/posts/1/slugged-url-of-the-post/, where 1 is the category_id.

I have no problem with site.com/posts/slugged-url-of-the-post/, but absolutely stuck with adding one more parameter to the route and making it work. The database is okay, and I have no problems with displaying the post category_id as a text value, for example, in the posts.show blade file.

Please, help?

routes/web.php

Route::get('/posts/{post}', function( App\Models\Post $post) {

// need to make this work:
// Route::get('/posts/{category_id}/{post}' ...

  return view('posts.show')->with('post', $post);
});

app/Models/Post.php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Cviebrock\EloquentSluggable\Sluggable;
use Cviebrock\EloquentSluggable\SluggableScopeHelpers;

class Post extends Model
{
    use HasFactory, Sluggable, SluggableScopeHelpers;

    public function sluggable(): array
    {
        return [
            'slug' => [
                'source' => 'title',
            ],

        ];
    }

    public function getRouteKeyName(): string
    {
        return 'slug';
    }

}

Body:
I don't know if this decision is good or not, but I came up with the following:

routes/web.php

Route::get('/posts/{category}/{slug}', [PostController::class, 'getSingle']);

app/Http/Controllers/PostController.php

public function getSingle($category, $slug)
{

    $post = Post::where('category_id','=',$category)->where('slug','=',$slug)->first();

    return view('posts.single')->with('post', $post);
}


问:
Using ctrl+arrow to jump between punctuation in VSCode?
VSCode has a handy keybinding to jump by identifier using ctrl+arrow. However, I would like to change the behaviour of this slightly.

For example, my code looks like this: (| stands for the cursor)

```<code>|bar(foo.baz)
</code>```

ctrl+right:

```<code>bar(|foo.baz)
</code>```

I would like VSCode to treat the parentheses and other punctuation such as . as identifiers when I press ctrl+arrow so that each one has its own "stop". In my previous example I would like this to happen after repeated ctrl+right presses:

```<code>|bar(foo.baz)
bar|(foo.baz)
bar(|foo.baz)
bar(foo|.baz)
bar(foo.|baz)
bar(foo.baz|)
bar(foo.baz)|
</code>```

This is what actually happens:

```<code>|bar(foo.baz)
bar(|foo.baz)
bar(foo.|baz)
bar(foo.baz)|
</code>```

I've discovered that the Stack Exchange text editor has the behaviour I want, so you can try navigating some code in the Answer box using ctrl+arrow yourself to see what I mean.

Is there a setting or even extension that does this? I've tried googling but this problem is quite hard to describe in a short query.

答:
I found a solution:

Binding to cursorWordPartLeft and cursorWordPartRight in keybindings.

Body:
VSCode has a handy keybinding to jump by identifier using ctrl+arrow. However, I would like to change the behaviour of this slightly.

For example, my code looks like this: (| stands for the cursor)

|bar(foo.baz)

ctrl+right:

bar(|foo.baz)

I would like VSCode to treat the parentheses and other punctuation such as . as identifiers when I press ctrl+arrow so that each one has its own "stop". In my previous example I would like this to happen after repeated ctrl+right presses:

|bar(foo.baz)
bar|(foo.baz)
bar(|foo.baz)
bar(foo|.baz)
bar(foo.|baz)
bar(foo.baz|)
bar(foo.baz)|

This is what actually happens:

|bar(foo.baz)
bar(|foo.baz)
bar(foo.|baz)
bar(foo.baz)|

I've discovered that the Stack Exchange text editor has the behaviour I want, so you can try navigating some code in the Answer box using ctrl+arrow yourself to see what I mean.

Is there a setting or even extension that does this? I've tried googling but this problem is quite hard to describe in a short query.


问:
View height is not coming right when open dev tools in browser
The background height is coming right but when we open the console the background shifts upwards leaving white space. I have tried both height: 100% AND height:100vh. Still it's not fixed

enter image description here

.main {
  width: 100%;
  height: 100vh;
  float: left;
  background: rgb(63, 63, 63);
  background: radial-gradient(circle, rgba(63, 63, 63, 1) 0%, rgba(0, 0, 0, 1) 97%);
  padding: 100px 0px 100px 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><template>

      <section class="main">
        <div class="container">
          <div class="row">
            <div class="col-md-4"></div>
            <div class="col-md-4"><img :src="logo" width="100%"><br><br></div>
            <div class="col-md-4"></div>
          </div>

          <div class="disclaimer font-weight-light animated-text">
              <vue-typed-js
                class="d-block"
                :loop="true"
                :strings="disclaimer"
              >
                <span class="typing"></span>
              </vue-typed-js>
            </div>

          <div class="row mt-4 pt-4">
            <div class="col-md-4"></div>
            <div class="col-md-4">
              <form autocomplete="off" @submit.prevent="submitNewsletter">
                <input type="email" name="email" id="email" v-model='enteredEmail' ref='enteredEmail' placeholder="Enter Your Email" class="sub-feild">
                <center>
                    <div class="mt-2">
                        <p class="error-message">{{errorMessage}}</p>
                    </div>
                </center>
                <center><button type="submit" class="cross_line">Subscribe</button></center>
              </form>
            </div>
            <div class="col-md-4"></div>
          </div>
        </div>
      </section>

    </template></code>```

答: Apply height 100% on parent of main div like body,html etc.</p>

Body:
The background height is coming right but when we open the console the background shifts upwards leaving white space. I have tried both height: 100% AND height:100vh. Still it's not fixed

enter image description here

.main {
  width: 100%;
  height: 100vh;
  float: left;
  background: rgb(63, 63, 63);
  background: radial-gradient(circle, rgba(63, 63, 63, 1) 0%, rgba(0, 0, 0, 1) 97%);
  padding: 100px 0px 100px 0px;
}

<template>

              <vue-typed-js
                class="d-block"
                :loop="true"
                :strings="disclaimer"
              >

              </vue-typed-js>

              <form autocomplete="off" @submit.prevent="submitNewsletter">
                <input type="email" name="email" id="email" v-model='enteredEmail' ref='enteredEmail' placeholder="Enter Your Email" class="sub-feild">

{{errorMessage}}

                <button type="submit" class="cross_line">Subscribe</button>
              </form>

    </template>