问:
Concrete JavaScript regular expression for accented characters (diacritics)
I've looked on Stack Overflow (replacing characters.. eh, how JavaScript doesn't follow the Unicode standard concerning RegExp, etc.) and haven't really found a concrete answer to the question "How can JavaScript match accented characters (those with diacritical marks)?"

I'm forcing a field in a UI to match the format: last_name, first_name (last [comma space] first), and I want to provide support for diacritics, but evidently in JavaScript it's a bit more difficult than other languages/platforms.

This was my original version, until I wanted to add diacritic support:

/^[a-zA-Z]+,\s[a-zA-Z]+$/

Currently I'm debating one of three methods to add support, all of which I have tested and work (at least to some extent, I don't really know what the "extent" is of the second approach). Here they are:

Explicitly listing all accented characters that I would want to accept as valid (lame and overly-complicated):

```<code>var accentedCharacters = "àèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇßØøÅåÆæœ";
// Build the full regex
var regex = "^[a-zA-Z" + accentedCharacters + "]+,\\s[a-zA-Z" + accentedCharacters + "]+$";
// Create a RegExp from the string version
regexCompiled = new RegExp(regex);
// regexCompiled = /^[a-zA-ZàèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇßØøÅåÆæœ]+,\s[a-zA-ZàèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇßØøÅåÆæœ]+$/
</code>```

This correctly matches a last/first name with any of the supported accented characters in accentedCharacters.

My other approach was to use the . character class, to have a simpler expression:

```<code>var regex = /^.+,\s.+$/;
</code>```

This would match for just about anything, at least in the form of: something, something. That's alright I suppose...

The last approach, which I just found might be simpler...

```<code>/^[a-zA-Z\u00C0-\u017F]+,\s[a-zA-Z\u00C0-\u017F]+$/
</code>```

It matches a range of Unicode characters - tested and working, though I didn't try anything crazy, just the normal stuff I see in our language department for faculty member names.

Here are my concerns:

The first solution is far too limiting, and sloppy and convoluted at that. It would need to be changed if I forgot a character or two, and that's just not very practical.

The second solution is better, concise, but it probably matches far more than it actually should. I couldn't find any real documentation on exactly what . matches, just the generalization of "any character except the newline character" (from a table on the MDN).

The third solution seems the be the most precise, but are there any gotchas? I'm not very familiar with Unicode, at least in practice, but looking at a code table/continuation of that table, \u00C0-\u017F seems to be pretty solid, at least for my expected input.

Faculty won't be submitting forms with their names in their native language (e.g., Arabic, Chinese, Japanese, etc.), so I don't have to worry about out-of-Latin-character-set characters

Which of these three approaches is most suited for the task? Or are there better solutions?

答:
<pre class="lang-none prettyprint-override"><code>/^[\pL\pM\p{Zs}.-]+$/u
</code>```
<p>Explanation:</p>
<ul>
<li><code>\pL</code> - matches any kind of letter from any language</li>
<li><code>\pM</code> - matches a character intended to be combined with another character (e.g. accents, umlauts, enclosing boxes, etc.)</li>
<li><code>\p{Zs}</code> - matches a whitespace character that is invisible, but does take up space</li>
<li><code>u</code> - Pattern and subject strings are treated as UTF-8</li>
</ul>
<p>Unlike other proposed regex (such as <code>[A-Za-zÀ-ÖØ-öø-ÿ]</code>), this will work with all language specific characters, e.g. <code>Šš</code> is matched by this rule, but not matched by others on this page.</p>
<p>Unfortunately, natively JavaScript does not support these classes. However, you can use <code>xregexp</code>, e.g.</p>
<pre class="lang-js prettyprint-override"><code>const XRegExp = require('xregexp');

const isInputRealHumanName = (input: string): boolean => {
  return XRegExp('^[\\pL\\pM-]+ [\\pL\\pM-]+$', 'u').test(input);
};

</code>```

Body:
I've looked on Stack Overflow (replacing characters.. eh, how JavaScript doesn't follow the Unicode standard concerning RegExp, etc.) and haven't really found a concrete answer to the question "How can JavaScript match accented characters (those with diacritical marks)?"

I'm forcing a field in a UI to match the format: last_name, first_name (last [comma space] first), and I want to provide support for diacritics, but evidently in JavaScript it's a bit more difficult than other languages/platforms.

This was my original version, until I wanted to add diacritic support:

/^[a-zA-Z]+,\s[a-zA-Z]+$/

Currently I'm debating one of three methods to add support, all of which I have tested and work (at least to some extent, I don't really know what the "extent" is of the second approach). Here they are:

Explicitly listing all accented characters that I would want to accept as valid (lame and overly-complicated):

var accentedCharacters = "àèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇßØøÅåÆæœ";
// Build the full regex
var regex = "^[a-zA-Z" + accentedCharacters + "]+,\\s[a-zA-Z" + accentedCharacters + "]+$";
// Create a RegExp from the string version
regexCompiled = new RegExp(regex);
// regexCompiled = /^[a-zA-ZàèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇßØøÅåÆæœ]+,\s[a-zA-ZàèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇßØøÅåÆæœ]+$/

This correctly matches a last/first name with any of the supported accented characters in accentedCharacters.

My other approach was to use the . character class, to have a simpler expression:

var regex = /^.+,\s.+$/;

This would match for just about anything, at least in the form of: something, something. That's alright I suppose...

The last approach, which I just found might be simpler...

/^[a-zA-Z\u00C0-\u017F]+,\s[a-zA-Z\u00C0-\u017F]+$/

It matches a range of Unicode characters - tested and working, though I didn't try anything crazy, just the normal stuff I see in our language department for faculty member names.

Here are my concerns:

The first solution is far too limiting, and sloppy and convoluted at that. It would need to be changed if I forgot a character or two, and that's just not very practical.

The second solution is better, concise, but it probably matches far more than it actually should. I couldn't find any real documentation on exactly what . matches, just the generalization of "any character except the newline character" (from a table on the MDN).

The third solution seems the be the most precise, but are there any gotchas? I'm not very familiar with Unicode, at least in practice, but looking at a code table/continuation of that table, \u00C0-\u017F seems to be pretty solid, at least for my expected input.

Faculty won't be submitting forms with their names in their native language (e.g., Arabic, Chinese, Japanese, etc.), so I don't have to worry about out-of-Latin-character-set characters

Which of these three approaches is most suited for the task? Or are there better solutions?

Body:
/^[\pL\pM\p{Zs}.-]+$/u

Explanation:

\pL - matches any kind of letter from any language

\pM - matches a character intended to be combined with another character (e.g. accents, umlauts, enclosing boxes, etc.)

\p{Zs} - matches a whitespace character that is invisible, but does take up space

u - Pattern and subject strings are treated as UTF-8

Unlike other proposed regex (such as [A-Za-zÀ-ÖØ-öø-ÿ]), this will work with all language specific characters, e.g. Šš is matched by this rule, but not matched by others on this page.

Unfortunately, natively JavaScript does not support these classes. However, you can use xregexp, e.g.

const XRegExp = require('xregexp');

const isInputRealHumanName = (input: string): boolean => {
  return XRegExp('^[\\pL\\pM-]+ [\\pL\\pM-]+$', 'u').test(input);
};


来源: stackexchange

问:
I cannot pass data to view it show http error 500 in laravel
Hi guyz i am kind of new to laravel and im trying to show the reviews posted by users . Now i checked with dd() and indeed i am able to get that data however when i send it to the view laravel responds with Http error 500. Previously i was only sending the doctors data which was working fine but when i tried to pass the reviews this happened.
This is my show Profile function

```<code>     public function profile($id)
    {
    $doctor=Doctor::find($id);
    $reviews=Review::where('doctor_id',$doctor->account_id)->get();

   // dd($doctor,$reviews);
    //  foreach($reviews as $review)
    //  {
    //      dd($doctor,$review);
    //  }
   // dd($reviews);
   // dd(DB::select("select * from reviews where doctor_id='D-1'"));
    //dd(Review::all()->where('doctor_id',$doctor->account_id));
   // $reviews=;
  // $array=['reviews'=>$reviews];
    return View('pages.doctorProfile',['reviews'=>$reviews])->with('doctor',$doctor);
}
</code>```

and this is the section of the view where i was trying to show the review

```<code>@foreach($reviews as $review)
    <!-- Comment List -->
    <li>
    <div class="comment">
        <img class="avatar avatar-sm rounded-circle" alt="User Image" src="/storage/images/patients/{{$review->patient->image}}">
        <div class="comment-body">
            <div class="meta-data">
                <span class="comment-author">{{$review->patient->first_name}} {{$review->patient->last_name}}</span>
                <span class="comment-date">{{$review->created_at}}</span>

            </div>
            <div  class="review-count rating">
                <?php $rating=explode('-',$review->rating)  ?>
                @for($i=1;$i<=5;$i++)
                    @for($i=1;$i<=$rating[1];$i++)
                        <i class="fas fa-star filled"></i>
                    @endfor
                    <i class="fas fa-star"></i>
                @endfor
                {{-- <i class="fas fa-star filled"></i>
                <i class="fas fa-star filled"></i>
                <i class="fas fa-star filled"></i>
                <i class="fas fa-star filled"></i>
                <i class="fas fa-star"></i> --}}
            </div>
            <p class="comment-content">
               {{$review->content}}
            </p>
            <div class="comment-reply">
                <a class="comment-btn" href="#">
                    <i class="fas fa-reply"></i> Reply
                </a>

            </div>
        </div>
    </div>
    </li>
    <!-- /Comment List -->
@endforeach
</code>```

Need this solved quick. Please help

答:
If you need to pass both $reviews and $doctor into view, you can do it like this :</p>

```<code>public function profile($id){
    $data = ['reviews'=>null,'doctor'=>null];
    $doctor = Doctor::find($id);
    $reviews = Review::where('doctor_id',$doctor->account_id)->get();
    $data = ['reviews'=>$reviews,'doctor'=>$doctor];
    return view('pages.doctorProfile',$data);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Hi guyz i am kind of new to laravel and im trying to show the reviews posted by users . Now i checked with dd() and indeed i am able to get that data however when i send it to the view laravel responds with Http error 500. Previously i was only sending the doctors data which was working fine but when i tried to pass the reviews this happened.
This is my show Profile function

     public function profile($id)
    {
    $doctor=Doctor::find($id);
    $reviews=Review::where('doctor_id',$doctor->account_id)->get();

   // dd($doctor,$reviews);
    //  foreach($reviews as $review)
    //  {
    //      dd($doctor,$review);
    //  }
   // dd($reviews);
   // dd(DB::select("select * from reviews where doctor_id='D-1'"));
    //dd(Review::all()->where('doctor_id',$doctor->account_id));
   // $reviews=;
  // $array=['reviews'=>$reviews];
    return View('pages.doctorProfile',['reviews'=>$reviews])->with('doctor',$doctor);
}

and this is the section of the view where i was trying to show the review

@foreach($reviews as $review)

        patient->image}}">

                {{$review->patient->first_name}} {{$review->patient->last_name}}
                {{$review->created_at}}

                <?php $rating=explode('-',$review->rating)  ?>
                @for($i=1;$i<=5;$i++)
                    @for($i=1;$i<=$rating[1];$i++)

                    @endfor

                @endfor
                {{--

                 --}}

               {{$review->content}}

                     Reply

@endforeach

Need this solved quick. Please help

Body:
If you need to pass both $reviews and $doctor into view, you can do it like this :

public function profile($id){
    $data = ['reviews'=>null,'doctor'=>null];
    $doctor = Doctor::find($id);
    $reviews = Review::where('doctor_id',$doctor->account_id)->get();
    $data = ['reviews'=>$reviews,'doctor'=>$doctor];
    return view('pages.doctorProfile',$data);
}


问:
Array loop always returning last value
I have the following loop:

```<code>var array = ["Value 1", "Value 2", "Value 3"];
var textArray = ["Text 1", "Text 2", "Text 3"];

var html = "";

for (let i = 0; i < array.length; i++) {
  var html = "<div class='group' data-department='"+array[i]+"'>";
  html += "<div class='title'>" + textArray[i] + "</div>";
  html += "</div>";
}
</code>```

The output of this JS is:

```<code><div class="group" data-department="Value 3">
   <div class="title">Text 3</div>
</div>

<div class="group" data-department="Value 3">
   <div class="title">Text 3</div>
</div>

<div class="group" data-department="Value 3">
   <div class="title">Text 3</div>
</div>
</code>```

What I'm after is:

```<code><div class="group" data-department="Value 1">
   <div class="title">Text 1</div>
</div>

<div class="group" data-department="Value 2">
   <div class="title">Text 2</div>
</div>

<div class="group" data-department="Value 3">
   <div class="title">Text 3</div>
</div>
</code>```

A console.log("Value: " + array[i]); returns:

```<code>Value: Value 1
Value: Value 2
Value: Value 3
</code>```

And a console.log("Text: " + textArray[i]); returns:

```<code>Text: Text 1
Text: Text 2
Text: Text 3
</code>```

So unsure why my markup is being rendered based on the last item in the array?

Following the removal of var from with the loop, I'm getting the following results (container divs get nested within each other):

var html = "";

for (let i = 0; i < array.length; i++) {
  html += "
";
  html += "
" + textArray[i] + "
";
  html += "
";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="group" data-department="Value 1">
  <div class="title">Text 1</div>
  <div class="group" data-department="Value 2">
    <div class="title">Text 2</div>
    <div class="group" data-department="Value 3">
      <div class="title">Text 3</div>
    </div>
  </div>
</div></code>```

答:
var array = ["Value 1", "Value 2", "Value 3"];
var textArray = ["Text 1", "Text 2", "Text 3"];

var html = "";

for (let i = 0; i < array.length; i++) {
  html += "
";
  html += "
" + textArray[i] + "
";
  html += "
";
}

console.log(html)```

Title: Array loop always returning last value

Body:
I have the following loop:

var array = ["Value 1", "Value 2", "Value 3"];
var textArray = ["Text 1", "Text 2", "Text 3"];

var html = "";

for (let i = 0; i < array.length; i++) {
  var html = "
";
  html += "
" + textArray[i] + "
";
  html += "
";
}

The output of this JS is:

Text 3

Text 3

Text 3

What I'm after is:

Text 1

Text 2

Text 3

A console.log("Value: " + array[i]); returns:

Value: Value 1
Value: Value 2
Value: Value 3

And a console.log("Text: " + textArray[i]); returns:

Text: Text 1
Text: Text 2
Text: Text 3

So unsure why my markup is being rendered based on the last item in the array?

Following the removal of var from with the loop, I'm getting the following results (container divs get nested within each other):

var html = "";

for (let i = 0; i < array.length; i++) {
  html += "
";
  html += "
" + textArray[i] + "
";
  html += "
";
}

Text 1

Text 2

Text 3

Body:
var array = ["Value 1", "Value 2", "Value 3"];
var textArray = ["Text 1", "Text 2", "Text 3"];

var html = "";

for (let i = 0; i < array.length; i++) {
  html += "<div class='group' data-department='"+array[i]+"'>";
  html += "<div class='title'>" + textArray[i] + "</div>";
  html += "</div>";
}

console.log(html)


问:
How to focus bootstrap select picker
I've use data-live-search for searchable option. When I click on focus button it should focus again select. I've use following code

$("#focus").click(function() {
  $(".selectpicker").focus();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.1/css/bootstrap-select.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.1/js/bootstrap-select.js"></script>

<select data-live-search="true" data-live-search-style="startsWith" class="selectpicker">
  <option value="4444">4444</option>
  <option value="Fedex">Fedex</option>
  <option value="Elite">Elite</option>
  <option value="Interp">Interp</option>
  <option value="Test">Test</option>
</select>
<button id="focus">focus</button></code>```

Whenever I press enter t is focus to select box but search option is not shown. I've attach screenshot
Please give me suggestion for display proper option with search option when I enter it

答:
focus() not working because it turned to customized select not native select option, by the way there is a native way to do this in selectpicker plugin, an event called toggle

$("#focus").click(function() {
  // toggle
  $('.selectpicker').selectpicker('toggle');

  // select by value
  $('.selectpicker').selectpicker('val', 'Test');
  $('.remove-example').selectpicker('refresh');

  // change highlight
  $('.dropdown-menu li').removeClass('active')
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.1/css/bootstrap-select.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.1/js/bootstrap-select.js"></script>

<select data-live-search="true" data-live-search-style="startsWith" class="selectpicker">
  <option value="4444">4444</option>
  <option value="Fedex">Fedex</option>
  <option value="Elite">Elite</option>
  <option value="Interp">Interp</option>
  <option value="Test">Test</option>
</select>
<button id="focus">focus</button></code>```

Title: How to focus bootstrap select picker

Body:
I've use data-live-search for searchable option. When I click on focus button it should focus again select. I've use following code

$("#focus").click(function() {
  $(".selectpicker").focus();
});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.1/css/bootstrap-select.css" />

<select data-live-search="true" data-live-search-style="startsWith" class="selectpicker">
  <option value="4444">4444</option>
  <option value="Fedex">Fedex</option>
  <option value="Elite">Elite</option>
  <option value="Interp">Interp</option>
  <option value="Test">Test</option>
</select>
<button id="focus">focus</button>

Whenever I press enter t is focus to select box but search option is not shown. I've attach screenshot
Please give me suggestion for display proper option with search option when I enter it

Body:
focus() not working because it turned to customized select not native select option, by the way there is a native way to do this in selectpicker plugin, an event called toggle

$("#focus").click(function() {
  // toggle
  $('.selectpicker').selectpicker('toggle');

  // select by value
  $('.selectpicker').selectpicker('val', 'Test');
  $('.remove-example').selectpicker('refresh');

  // change highlight
  $('.dropdown-menu li').removeClass('active')
});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.1/css/bootstrap-select.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.1/js/bootstrap-select.js"></script>

<select data-live-search="true" data-live-search-style="startsWith" class="selectpicker">
  <option value="4444">4444</option>
  <option value="Fedex">Fedex</option>
  <option value="Elite">Elite</option>
  <option value="Interp">Interp</option>
  <option value="Test">Test</option>
</select>
<button id="focus">focus</button>


问:
vba count visible rows after filter
I keep having issues with visible rows after filtering.
I have a table that looks like this:

The name of the table is tstTBL.
I am applying 2 filters: filtering for case ID 3 and Filed = Yes, which gives no results. However, when I count the visible rows, it counts 1, although I use only the databodyrange of the table. I am expecting numRows = 0. How should I change the code?

```<code>Sub tstFilter()
    Dim filterredRange As Range
    Dim tbl As ListObject
    Dim caseCol As Integer
    Dim trCol As Integer
    Dim numRows As Integer

    Set tbl = Sheet1.ListObjects("tstTbl")
    caseCol = Sheet1.Rows("1:1").Find(What:="Case ID", LookAt:=xlWhole).Column
    tbl.Range.AutoFilter Field:=caseCol, Criteria1:=3

    'check first filter
    On Error Resume Next
        Set filterredRange = tbl.ListColumns("Case ID").DataBodyRange.SpecialCells(xlVisible)
    On Error GoTo 0
    If filterredRange Is Nothing Then
        Debug.Print "no such case"
    End If

    trCol = ActiveSheet.Rows("1:1").Find(What:="Filed", LookAt:=xlWhole).Column
    tbl.Range.AutoFilter Field:=trCol, Criteria1:="Yes"

    'check second filter
    On Error Resume Next
            Set filterredRange = tbl.ListColumns("Filed").DataBodyRange.SpecialCells(xlVisible)
    On Error GoTo 0
    If filterredRange Is Nothing Then
        numRows = 0
    Else
        numRows = filterredRange.Rows.Count
    End If

    Debug.Print numRows

End Sub
</code>```

答:
The issue is if the first filter set's a range correctly Set filterredRange then the variable contains a range.

If you now re-use the same variable for your second filter

```<code>'check second filter
On Error Resume Next
    Set filterredRange = tbl.ListColumns("Filed").DataBodyRange.SpecialCells(xlVisible)
On Error GoTo 0
</code>```

and there are no visible cells, your code errors (but doesn't show a message because you suppressed it with On Error Resume Next) and your filterredRange is not re-set (this line errored and therefore filterredRange still has its original value). If a line errors this line does nothing at all (just as it was never executed).

To prevent this you must re-initialize your variable with Set filterredRange = Nothing before using it for the second filter.

Title: vba count visible rows after filter

Body:
I keep having issues with visible rows after filtering.
I have a table that looks like this:

The name of the table is tstTBL.
I am applying 2 filters: filtering for case ID 3 and Filed = Yes, which gives no results. However, when I count the visible rows, it counts 1, although I use only the databodyrange of the table. I am expecting numRows = 0. How should I change the code?

Sub tstFilter()
    Dim filterredRange As Range
    Dim tbl As ListObject
    Dim caseCol As Integer
    Dim trCol As Integer
    Dim numRows As Integer

    Set tbl = Sheet1.ListObjects("tstTbl")
    caseCol = Sheet1.Rows("1:1").Find(What:="Case ID", LookAt:=xlWhole).Column
    tbl.Range.AutoFilter Field:=caseCol, Criteria1:=3

    'check first filter
    On Error Resume Next
        Set filterredRange = tbl.ListColumns("Case ID").DataBodyRange.SpecialCells(xlVisible)
    On Error GoTo 0
    If filterredRange Is Nothing Then
        Debug.Print "no such case"
    End If

    trCol = ActiveSheet.Rows("1:1").Find(What:="Filed", LookAt:=xlWhole).Column
    tbl.Range.AutoFilter Field:=trCol, Criteria1:="Yes"

    'check second filter
    On Error Resume Next
            Set filterredRange = tbl.ListColumns("Filed").DataBodyRange.SpecialCells(xlVisible)
    On Error GoTo 0
    If filterredRange Is Nothing Then
        numRows = 0
    Else
        numRows = filterredRange.Rows.Count
    End If

    Debug.Print numRows

End Sub

Body:
The issue is if the first filter set's a range correctly Set filterredRange then the variable contains a range.

If you now re-use the same variable for your second filter

'check second filter
On Error Resume Next
    Set filterredRange = tbl.ListColumns("Filed").DataBodyRange.SpecialCells(xlVisible)
On Error GoTo 0

and there are no visible cells, your code errors (but doesn't show a message because you suppressed it with On Error Resume Next) and your filterredRange is not re-set (this line errored and therefore filterredRange still has its original value). If a line errors this line does nothing at all (just as it was never executed).

To prevent this you must re-initialize your variable with Set filterredRange = Nothing before using it for the second filter.


问:
Which win32 API can be used to listen on a port in windows?
I'm reverse engineering a software,and I set a bp on listen,doesn't work.

What other win32 APi are there to listen on a specific port?

And I know the port it's listenning on is 8888.

UPDATE
What I'm doing is for this task:

How can I implement a http proxy server myself? Do I need to need to bother with TCP/IP protocols?

答:
I think that what you are asking is, how to implement a transparent proxy. In which case you can do it on one of two levels:

You can implement a local PC only transparent proxy, by injecting a hook dll into all processes, that hooks winsock calls, and intercepts traffic by directly monitoring connect, send, recv requests (and re-writing as necessary).

To implement a transparent proxy on a network, you a. need to have access to the gateway that the other PCs are routing their internet traffic through. b. You need to get a special library that works with raw sockets to intercept the traffic that should be routing through the gateway, and rerouting it to your local proxy server.

Typically this is done on Linux, rather than Windows, as Linux has a simple tool iptables, that can be used to "transparently" redirect traffic that was passing through a gateway, to a specific proxy server.

ContentLicense: CC BY-SA 3.0


问:
PHPMailer Error: Fatal error: Uncaught Error: Call to undefined method PHPMailer\PHPMailer\PHPMailer::isSTMP()
I am trying to send Mails using PHPMailer But its Showing me Error. This is test code. and When it's done I am thinking to add it to my main code. but  I don't know What's Wrong with this code. its just giving me this Error.

This is the Error:

Fatal error: Uncaught Error: Call to undefined method
PHPMailer\PHPMailer\PHPMailer::isSTMP() in

And Here is my Code:

```<code><!DOCTYPE html>
 <html>
<head>
 <title></title>
</head>
<body>
<?php

require "vendor/autoload.php";

 use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

 $developmentMode = true;
 $mailer = new PHPMailer($developmentMode);

  try {
     $mailer->SMTPDebug = 2;
    $mailer->isSMTP();            //edited here

 if ($developmentMode) {

   $mailer->SMTPOptions = [
    'ssl'=> [
         'verify_peer' => false,
        'verify_peer_name' => false,
        'allow_self_signed' => true
      ]
   ];

 }

 $mailer->Host = 'smtp.gmail.com';
$mailer->SMTPAuth = true;
 $mailer->Username = "mygmail@gmail.com";
 $mailer->Password = "password";
 $mailer->SMTPSecure = 'tls';
$mailer->Port = 587;

$mailer-> setFrom("mygmail@gmail.com", "Izaya");
$mailer->addAddress("anothergmail@gmail.com","orihara");

  $mailer->isHTML(true);
   $mailer->Subject = "Hey There";
  $mailer->Body = "NICE TO MEET YOU IZAYA ";

   $mailer->send();
$mailer->ClearAllRecipients();
  echo "Mail has been Sent";

   }catch (Exception $e) {
echo "Email Error.INFO:" . $mailer->ErrorInfo;

  }

  ?>
 </body>
 </html>
</code>```

答:
Use this code below with version more than v6.0

```<code>// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// Load Composer's autoloader
require 'vendor/autoload.php';

// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);

try {
    //Server settings
    $mail->SMTPDebug = SMTP::DEBUG_SERVER;                      // Enable verbose debug output
    $mail->isSMTP();                                            // Send using SMTP
    $mail->Host       = 'smtp1.example.com';                    // Set the SMTP server to send through
    $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
    $mail->Username   = 'user@example.com';                     // SMTP username
    $mail->Password   = 'secret';                               // SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;         // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted
    $mail->Port       = 587;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('from@example.com', 'Mailer');
    $mail->addAddress('joe@example.net', 'Joe User');     // Add a recipient
    $mail->addAddress('ellen@example.com');               // Name is optional
    $mail->addReplyTo('info@example.com', 'Information');
    $mail->addCC('cc@example.com');
    $mail->addBCC('bcc@example.com');

    // Attachments
    $mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
    $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

    // Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
</code>```

Body:
I am trying to send Mails using PHPMailer But its Showing me Error. This is test code. and When it's done I am thinking to add it to my main code. but  I don't know What's Wrong with this code. its just giving me this Error.

This is the Error:

Fatal error: Uncaught Error: Call to undefined method
PHPMailer\PHPMailer\PHPMailer::isSTMP() in

And Here is my Code:

<!DOCTYPE html>

 <title></title>

<?php

require "vendor/autoload.php";

 use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

 $developmentMode = true;
 $mailer = new PHPMailer($developmentMode);

  try {
     $mailer->SMTPDebug = 2;
    $mailer->isSMTP();            //edited here

 if ($developmentMode) {

   $mailer->SMTPOptions = [
    'ssl'=> [
         'verify_peer' => false,
        'verify_peer_name' => false,
        'allow_self_signed' => true
      ]
   ];

 }

 $mailer->Host = 'smtp.gmail.com';
$mailer->SMTPAuth = true;
 $mailer->Username = "mygmail@gmail.com";
 $mailer->Password = "password";
 $mailer->SMTPSecure = 'tls';
$mailer->Port = 587;

$mailer-> setFrom("mygmail@gmail.com", "Izaya");
$mailer->addAddress("anothergmail@gmail.com","orihara");

  $mailer->isHTML(true);
   $mailer->Subject = "Hey There";
  $mailer->Body = "NICE TO MEET YOU IZAYA ";

   $mailer->send();
$mailer->ClearAllRecipients();
  echo "Mail has been Sent";

   }catch (Exception $e) {
echo "Email Error.INFO:" . $mailer->ErrorInfo;

  }

  ?>

Body:
Use this code below with version more than v6.0

// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// Load Composer's autoloader
require 'vendor/autoload.php';

// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);

try {
    //Server settings
    $mail->SMTPDebug = SMTP::DEBUG_SERVER;                      // Enable verbose debug output
    $mail->isSMTP();                                            // Send using SMTP
    $mail->Host       = 'smtp1.example.com';                    // Set the SMTP server to send through
    $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
    $mail->Username   = 'user@example.com';                     // SMTP username
    $mail->Password   = 'secret';                               // SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;         // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted
    $mail->Port       = 587;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('from@example.com', 'Mailer');
    $mail->addAddress('joe@example.net', 'Joe User');     // Add a recipient
    $mail->addAddress('ellen@example.com');               // Name is optional
    $mail->addReplyTo('info@example.com', 'Information');
    $mail->addCC('cc@example.com');
    $mail->addBCC('bcc@example.com');

    // Attachments
    $mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
    $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

    // Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}


问:
Using an hybrid solution with both Azure IoT Hub and Event Hub
We are building an IoT solution where we need bi-directional communication between Device and Cloud.

Azure IoT Hub seems to be a perfect fit.

However, the pricing is steep for a reasonable amount of outgoing messages/day  for our needs (when compared to Event Hub).

So I was thinking of an hybrid solution where Azure IoT Hub would be used only for Cloud-to-Device messages, and Event Hub would be used  for Device-To-Cloud messages.

Would this be a viable solution ?

答:
Well, it seems like the question was asked long ago, but I hope that this will be of some help to someone in the future.

I believe that choosing Event Hub for Device messages will result in losing the following capabilities that IoT Hub present:

Per-device Identity: Every IoT hub has an identity registry that stores information about the devices and modules permitted to connect to the IoT hub. Before a device or module can connect to an IoT hub, there must be an entry for that device or module in the IoT hub's identity registry. A device or module must also authenticate with the IoT hub based on credentials stored in the identity registry.

Device Provisioning Service: The device data that a given IoT solution stores depends on the specific requirements of that solution. But, as a minimum, a solution must store device identities and authentication keys. Azure IoT Hub includes an identity registry that can store values for each device such as IDs, authentication keys, and status codes. A solution can use other Azure services such as table storage, blob storage, or Cosmos DB to store any additional device data. Device provisioning is the process of adding the initial device data to the stores in your solution. To enable a new device to connect to your hub, you must add a device ID and keys to the IoT Hub identity registry. As part of the provisioning process, you might need to initialize device-specific data in other solution stores. You can also use the Azure IoT Hub Device Provisioning Service to enable zero-touch, just-in-time provisioning to one or more IoT hubs without requiring human intervention. To learn more, see the provisioning service documentation.

Device Twin and Device Management: Device twins are JSON documents that store device state information including metadata, configurations, and conditions. Azure IoT Hub maintains a device twin for each device that you connect to IoT Hub.

IoT Edge: Azure IoT Edge moves cloud analytics and custom business logic to devices so that your organization can focus on business insights instead of data management. Scale out your IoT solution by packaging your business logic into standard containers, then you can deploy those containers to any of your devices and monitor it all from the cloud.

Device heartbeat : The IoT Hub identity registry contains a field called connectionState. Only use the connectionState field during development and debugging. IoT solutions should not query the field at run time. For example, do not query the connectionState field to check if a device is connected before you send a cloud-to-device message or an SMS. We recommend subscribing to the device disconnected event on Event Grid to get alerts and monitor the device connection state. Use this tutorial to learn how to integrate Device Connected and Device Disconnected events from IoT Hub in your IoT solution.

In order to have a low-cost solution, I think that you should consider send a batch of telemetry data (which means sending less device to cloud messages) if that something that can still answer to your technical/functional requirements.


问:
convert month-day-year into day-month-year using javascript
I'm trying to convert a MM/DD/YYYY date to a long date. So for example, 02/16/2020 would convert to something like 16/02/2020.

Is there a way to make this date conversion accurately?

答:
You need to specify the original format of the time, and then convert it to a new format.

const date = "02/16/2020";
alert(moment(date, "MM/DD/YYYY").format('DD/MM/YYYY'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script></code>```

Body:
You need to specify the original format of the time, and then convert it to a new format.

const date = "02/16/2020";
alert(moment(date, "MM/DD/YYYY").format('DD/MM/YYYY'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>


问:
Can't resize UIView in IB
Probably something simple, but I can't figure why I cannot resize a UIView in a xib in Interface Builder.

I created a new view XIB in xcode and in the size inspector, the width and height are disabled and grayed out to 320 by 460. This is strange since I can change the size for the other two views (associated with the other two tab bar items).

I am not sure if this has anything to do with but I recently updated the sdk to 3.

Thanks!

答: In storyboard select the UIVIew and go to the attributes inspector change the UIVIew size to "FreeForm" instead of "Inferred"

OwnerDisplayName: Ayrad

ContentLicense: CC BY-SA 2.5

Title: Can't resize UIView in IB


问:
Next.js returns 500: internal server error in Production
Created a next.js full stack application. After production build when I run next start it returns 500 : internal server. I'm using environment varibles for hitting api.

```<code>env.development file

BASE_URL=http://localhost:3000
</code>```

It was working fine in development
service.ts

```<code>import axios from 'axios';
const axiosDefaultConfig = {
  baseURL: process.env.BASE_URL, // is this line reason for error?
  headers: {
    'Access-Control-Allow-Origin': '*'
  }
};
const axio = axios.create(axiosDefaultConfig);

export class Steam {
  static getGames = async () => {
    return await axio.get('/api/getAppList');
  };
}
</code>```

答:
Do you have a next.config.js file?

To add runtime configuration to your app open next.config.js and add the publicRuntimeConfig and serverRuntimeConfig configs:

```<code>module.exports = {
  serverRuntimeConfig: {
    // Will only be available on the server side
    mySecret: 'secret',
    secondSecret: process.env.SECOND_SECRET, // Pass through env variables
  },
  publicRuntimeConfig: {
    // Will be available on both server and client
    staticFolder: '/static',
  },
}
</code>```

To get access to the runtime configs in your app use next/config, like so:

```<code>import getConfig from 'next/config'

// Only holds serverRuntimeConfig and publicRuntimeConfig
const { serverRuntimeConfig, publicRuntimeConfig } = getConfig()
// Will only be available on the server-side
console.log(serverRuntimeConfig.mySecret)
// Will be available on both server-side and client-side
console.log(publicRuntimeConfig.staticFolder)

function MyImage() {
  return (
    <div>
      <img src={`${publicRuntimeConfig.staticFolder}/logo.png`} alt="logo" />
    </div>
  )
}

export default MyImage
</code>```

I hope this helps.

Body:
Created a next.js full stack application. After production build when I run next start it returns 500 : internal server. I'm using environment varibles for hitting api.

env.development file

BASE_URL=http://localhost:3000

It was working fine in development
service.ts

import axios from 'axios';
const axiosDefaultConfig = {
  baseURL: process.env.BASE_URL, // is this line reason for error?
  headers: {
    'Access-Control-Allow-Origin': '*'
  }
};
const axio = axios.create(axiosDefaultConfig);

export class Steam {
  static getGames = async () => {
    return await axio.get('/api/getAppList');
  };
}

Body:
Do you have a next.config.js file?

To add runtime configuration to your app open next.config.js and add the publicRuntimeConfig and serverRuntimeConfig configs:

module.exports = {
  serverRuntimeConfig: {
    // Will only be available on the server side
    mySecret: 'secret',
    secondSecret: process.env.SECOND_SECRET, // Pass through env variables
  },
  publicRuntimeConfig: {
    // Will be available on both server and client
    staticFolder: '/static',
  },
}

To get access to the runtime configs in your app use next/config, like so:

import getConfig from 'next/config'

// Only holds serverRuntimeConfig and publicRuntimeConfig
const { serverRuntimeConfig, publicRuntimeConfig } = getConfig()
// Will only be available on the server-side
console.log(serverRuntimeConfig.mySecret)
// Will be available on both server-side and client-side
console.log(publicRuntimeConfig.staticFolder)

function MyImage() {
  return (
    <div>
      <img src={`${publicRuntimeConfig.staticFolder}/logo.png`} alt="logo" />
    </div>
  )
}

export default MyImage

I hope this helps.


问:
When should I use Microsoft.Owin implementation and when should I use AspNetCore?
I read many articles and posts on the internet about the differences between Microsoft.Owin and AspNetCore for REST Services. Most sources state that AspNetCore is a higher level alternative for Microsoft.Owin and a lot of sources suggest using AspNetCore instead of Microsoft.Owin. I managed to build a good working REST API with AspNetCore only. Now I'd like to use SignalR in addition to my REST Interface and found out that SignalR only works with Microsoft.Owin and not AspNetCore only.

So when should I use Microsoft.Owin and when should I use AspNetCore? Obviously I need Microsoft.Owin if I need SignalR. But even if I don't need SignalR why should I go with AspNetCore and not always use Microsoft.Owin?

My questions refers to self hosted REST Services

答:
ASP.NET Core is the newer framework, I'd recommend using that instead of Owin.

You can use SignalR Core on ASP.NET Core.


问:
I have a method withdraw(); that doesnt work, any idea why?
My withdraw method doesnt work, maybe someone see things I dont see?

This is part of my abstract class Account and abstract method withdraw

```<code>import java.util.ArrayList;

public abstract class Account {
private String accountType;
private static double balance = 0;
protected int accountId;
private static int accountNumberCounter = 1000;
private ArrayList<Account> accounts;

public Account(String acType, int acNumber){
    accountType = acType;
    accountNumberCounter ++;
    accountId = accountNumberCounter;
}

public Account() {
    accountNumberCounter++;
    accountId = accountNumberCounter;
}

public abstract boolean withdraw(double value);
</code>```

This is SavingsAccount class and its method withdraw()

```<code>public class SavingsAccount extends Account {
private static double balance = 0;
private static final double RATE = 1.0;
private static  String accountType = "Savings Account";
private int accountId;

public SavingsAccount(){
    super();
}

public double getBalance(){
    return balance;
}

public void deposit(double amount){
    balance = balance + amount;
}

public boolean withdraw(double amount){
    if (balance<= amount){
        System.out.println("You have only" + amount + "left on your account.");
    return false;
    }
    else{
        balance -= amount;
        System.out.println("You took:" + amount);
        return true;
    }
}
</code>```

Method from BankLogic as well, I think this part should be correct:

```<code>  public boolean withdraw(String pNo, int accountId, double amount){
    for(Customer pers: customerList) {
        if (pers.getPersonalNumber().equals(pNo)) {
            for (Account account : pers.getAllAccounts()) {
                if (account.getAccountNumber() == accountId) {
                    account.withdraw(amount);
                }
            }
        }
    }
    return false;
}
</code>```

答:
Well, I am not sure what you mean by it's not working, but I see two problems.

Balance shouldn't be static. It should be a class variable that has its own value for each object created.

In your withdraw-method you are saying "You have only" + amount + "left on your account.", while it should be balance instead of amount.

Hope I could help.

Body:
My withdraw method doesnt work, maybe someone see things I dont see?

This is part of my abstract class Account and abstract method withdraw

import java.util.ArrayList;

public abstract class Account {
private String accountType;
private static double balance = 0;
protected int accountId;
private static int accountNumberCounter = 1000;
private ArrayList<Account> accounts;

public Account(String acType, int acNumber){
    accountType = acType;
    accountNumberCounter ++;
    accountId = accountNumberCounter;
}

public Account() {
    accountNumberCounter++;
    accountId = accountNumberCounter;
}

public abstract boolean withdraw(double value);

This is SavingsAccount class and its method withdraw()

public class SavingsAccount extends Account {
private static double balance = 0;
private static final double RATE = 1.0;
private static  String accountType = "Savings Account";
private int accountId;

public SavingsAccount(){
    super();
}

public double getBalance(){
    return balance;
}

public void deposit(double amount){
    balance = balance + amount;
}

public boolean withdraw(double amount){
    if (balance<= amount){
        System.out.println("You have only" + amount + "left on your account.");
    return false;
    }
    else{
        balance -= amount;
        System.out.println("You took:" + amount);
        return true;
    }
}

Method from BankLogic as well, I think this part should be correct:

  public boolean withdraw(String pNo, int accountId, double amount){
    for(Customer pers: customerList) {
        if (pers.getPersonalNumber().equals(pNo)) {
            for (Account account : pers.getAllAccounts()) {
                if (account.getAccountNumber() == accountId) {
                    account.withdraw(amount);
                }
            }
        }
    }
    return false;
}


问:
How to bind item selected data to a button command in xamarin forms
I have a command button inside a syncfusion list view , I fired the command on the view model , but I dont know how to pass the data of the item selected . This is what I have

```<code> <syncfusion:SfListView x:Name="listView"
                   SelectionBackgroundColor="Transparent"
                     ItemsSource="{Binding AvailableData}"  ItemSpacing="10" >
                     <syncfusion:SfListView.ItemTemplate>
                       <DataTemplate>
                           <Label text="{Binding id requests}"/>
                           <Button Text="Cancel" Command="{Binding Source={x:Reference RequestsPage}, Path=BindingContext.CancelCommand}" ></Button>
                       </DataTemplate>
                       </syncfusion:SfListView.ItemTemplate>
  </syncfusion:SfListView>
</code>```

View Model

```<code>         public ICommand CancelCommand
         {
           get;
           set;
         }
         CancelCommand = new Command(CancelBooking);

         void CancelBooking()
         {
          I need to capture the item source this button is inside each item that is
          displayed in the list , I need to capture the data from this selection
         }
</code>```

答:
Please refer below links,

binding-command-of-button-inside-the-itemtemplate-of-xamarinforms-listview-to-viewmodel-command

how-to-delete-an-item-when-tapping-delete-button-in-listview-itemtemplate-in-mvvm

Body:
I have a command button inside a syncfusion list view , I fired the command on the view model , but I dont know how to pass the data of the item selected . This is what I have

 <syncfusion:SfListView x:Name="listView"
                   SelectionBackgroundColor="Transparent"
                     ItemsSource="{Binding AvailableData}"  ItemSpacing="10" >
                     <syncfusion:SfListView.ItemTemplate>
                       <DataTemplate>

                           <Button Text="Cancel" Command="{Binding Source={x:Reference RequestsPage}, Path=BindingContext.CancelCommand}" ></Button>
                       </DataTemplate>
                       </syncfusion:SfListView.ItemTemplate>
  </syncfusion:SfListView>

View Model

         public ICommand CancelCommand
         {
           get;
           set;
         }
         CancelCommand = new Command(CancelBooking);

         void CancelBooking()
         {
          I need to capture the item source this button is inside each item that is
          displayed in the list , I need to capture the data from this selection
         }


问:
How to implement a vertical carousel in android
I am trying to figure out how to implement a vertical carousel in android  like a dialer look and feel in single view when user scroll up it will feel like a dialer view like the below image

http://2.bp.blogspot.com/-UTkFCT2A2BY/UUapxk1EvmI/AAAAAAAAX-Q/wHdlVYALMWw/s1600/2013-03-18+13.26.23.png

答:
I would start with Recycler (with custom adapter if you need to generate items as user scrolls or with set of items if you know upfront)

All additional UI elements on "picker" can be done with RecyclerView.ItemDecoration

And to do vertical scroll just use LinearLayoutManager(context, RecyclerView.VERTICAL, false)


答: Just for completeness and info, the classInt package (on CRAN) is another handy way to classify numbers into classes.</p>

Title: coding variable values into classes using R

Body:
I have a set of data in which I need to code values of certain variables (numeric) into 3 classes.

My data set is similar to this but has 60 more variables:

anim <- c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)
wt <- c(181,179,180.5,201,201.5,245,246.4,189.3,301,354,369,205,199,394,231.3)
data <- data.frame(anim,wt)

> data
   anim    wt
1     1 181.0
2     2 179.0
3     3 180.5
4     4 201.0
5     5 201.5
6     6 245.0
7     7 246.4
8     8 189.3
9     9 301.0
10   10 354.0
11   11 369.0
12   12 205.0
13   13 199.0
14   14 394.0
15   15 231.3

I need to code values of the variable "wt" up into 3 classes: (wt >= 179 & wt < 200) = 1; (wt >= 200 & wt < 300) = 2; (wt > 300) = 3

which should give me this

> data2
   anim    wt SWT
1     1 181.0   1
2     2 179.0   1
3     3 180.5   1
4     4 201.0   2
5     5 201.5   2
6     6 245.0   2
7     7 246.4   2
8     8 189.3   1
9     9 301.0   3
10   10 354.0   3
11   11 369.0   3
12   12 205.0   2
13   13 199.0   1
14   14 394.0   3
15   15 231.3   2


问:
Aggregating two rows based on condition of different ID in R
I am dealing with a dataset of players statistics for a sport. There is an error in the data where one week a player who doesn't exist, has been attributed the data that belongs to a real player. I need to aggregate the two players data and delete the instance of the false players' row.

I need to adjust my preprocessing code to accommodate this so when I scrape future weeks data then I don't need to make manual adjustments.

```<code>df <- data.frame(Name = c("Bob","Ben","Bill"),
                 Team = c("Dogs","Cats","Birds"),
                 Runs = c(6, 4, 2)
</code>```

I'd like to do something along the lines of aggregating the two rows based on their df$Name e.g. when df$Name == "Bob" & df$Name == "Bill" aggregate columns [3:40] -- these are my columns with numeric statistics, [1:2] have df$Name and df$Team.

答:
It would depend on the type of aggregation you are trying to do. This looks like a perfect use of the group_by from the dplyr package. Consider the CO2 data set.

```<code>library(dplyr)

CO2 %>%
 group_by(Plant) %>%
 summarise(
     n = n(), #Calculate number of rows in each group
     meanUptake = mean(uptake) # Aggregate data and take mean for each group
  ) %>%
  ungroup()
</code>```

Here we take each group, in your case above it would be name. In the summarise, if you wish to include extra information (like team) include it within the summarise.

Body:
I am dealing with a dataset of players statistics for a sport. There is an error in the data where one week a player who doesn't exist, has been attributed the data that belongs to a real player. I need to aggregate the two players data and delete the instance of the false players' row.

I need to adjust my preprocessing code to accommodate this so when I scrape future weeks data then I don't need to make manual adjustments.

df <- data.frame(Name = c("Bob","Ben","Bill"),
                 Team = c("Dogs","Cats","Birds"),
                 Runs = c(6, 4, 2)

I'd like to do something along the lines of aggregating the two rows based on their df$Name e.g. when df$Name == "Bob" & df$Name == "Bill" aggregate columns [3:40] -- these are my columns with numeric statistics, [1:2] have df$Name and df$Team.

Body:
It would depend on the type of aggregation you are trying to do. This looks like a perfect use of the group_by from the dplyr package. Consider the CO2 data set.

library(dplyr)

CO2 %>%
 group_by(Plant) %>%
 summarise(
     n = n(), #Calculate number of rows in each group
     meanUptake = mean(uptake) # Aggregate data and take mean for each group
  ) %>%
  ungroup()

Here we take each group, in your case above it would be name. In the summarise, if you wish to include extra information (like team) include it within the summarise.


问:
Control formatting of the argparse help argument list?
```<code>import argparse
parser = argparse.ArgumentParser(prog='tool')
args = [('-u', '--upf', 'ref. upf', dict(required='True')),
        ('-s', '--skew', 'ref. skew', {}),
        ('-m', '--model', 'ref. model', {})]
for args1, args2, desc, options in args:
     parser.add_argument(args1, args2, help=desc, **options)

parser.print_help()
</code>```

Output:

```<code>usage: capcheck [-h] -u UPF [-s SKEW] [-m MODEL]

optional arguments:
  -h, --help            show this help message and exit
  -u UPF, --upf UPF     ref. upf
  -s SKEW, --skew SKEW  ref. skew
  -m MODEL, --model MODEL
                        ref. model
</code>```

How do I print ref. model in the same line as -m MODEL, --model MODEL instead of that appearing on a separate line when I run the script with -h option?

答:
Another approach: hijack sys.argv, check it for --help and -h, if found extract help text using argparse.format_help, massage it, print it, and exit.

```<code>import  sys, re, argparse

RGX_MID_WS = re.compile(r'(\S)\s{2,}')

def main(argv):

#   note add_help = False
    parser = argparse.ArgumentParser(description = '%(prog)s: testing help mods', formatter_class= argparse.RawTextHelpFormatter, add_help = False)

    parser.add_argument('bar', nargs='+', help='two bars that need to be frobbled')
    parser.add_argument('--foo', action='store_true', help='foo the bars before frobbling\nfoo the bars before frobbling')
    parser.add_argument('--xxxxx', nargs=2, help='many xes')
    parser.add_argument('--bacon', help ='a striped food')
    parser.add_argument('--badger', help='in a striped pyjamas')
    parser.add_argument('--animal', dest='animal', choices=('zabra', 'donkey', 'bat') ,help ='could be one of these')

#   may exit
    lArgs = help_manage(parser)
    args = parser.parse_args() # args = lArgs

    print('bars are: ', args.bar)

def help_manage(parser):
    """
    check for -h, --help, -h in a single-letter cluster;
    if none found, return, otherwise clean up help text and exit
    """

    lArgs = sys.argv[1:]
    lArgsNoHelp = [sOpt for sOpt in lArgs if (not sOpt in ('--help', '-h')) and not (sOpt[0] == '-' and sOpt[1] != '-' and 'h' in sOpt)]

#   no change?  then no --help params
    if len(lArgsNoHelp) == len(lArgs): return

    sHelp = parser.format_help()

#   to see help as formated by argparse, uncomment:
#   print(sHelp)
#   exit()

    for sLine in sHelp.split('\n'): print(clean_line(sLine))

    exit()

def clean_line(sLine):
    """
    this is just an example, and goes nowhere near covering all possible
    argument properties
    """
#   avoid messing with usage: lines
    if 'usage' in sLine: return sLine
    if sLine.startswith('  ') and '[' in sLine: return sLine

    if sLine.endswith(' arguments:'): return sLine + '\n'

    sLine = sLine.lstrip()

    sLine = RGX_MID_WS.sub(r'\1\n', sLine)
    if sLine.startswith('-'): sLine = '\n' + sLine
    return sLine.replace('{', '\n(can be: ').replace('}', ')').replace('\n\n', '\n')

if __name__ == '__main__':

    bRes =  main(sys.argv[1:])
    sys.exit(bRes)
</code>```

Help without formatting:

```<code>usage: argparse_fix_min2.py [--foo] [--xxxxx XXXXX XXXXX] [--bacon BACON]
                                [--badger BADGER] [--animal {zabra,donkey,bat}]
                                bar [bar ...]

    argparse_fix_min2.py: testing help mods

    positional arguments:
      bar                   two bars that need to be frobbled

    optional arguments:
      --foo                 foo the bars before frobbling
                            foo the bars before frobbling
      --xxxxx XXXXX XXXXX   many xes
      --bacon BACON         a striped food
      --badger BADGER       in a striped pyjamas
      --animal {zabra,donkey,bat}
                            could be one of these

</code>```

with formatting:

```<code>usage: argparse_fix_min2.py [--foo] [--xxxxx XXXXX XXXXX] [--bacon BACON]
                                [--badger BADGER] [--animal {zabra,donkey,bat}]
                                bar [bar ...]

    argparse_fix_min2.py: testing help mods

    positional arguments:

    bar
    two bars that need to be frobbled

    optional arguments:

    --foo
    foo the bars before frobbling
    foo the bars before frobbling

    --xxxxx XXXXX XXXXX
    many xes

    --bacon BACON
    a striped food

    --badger BADGER
    in a striped pyjamas

    --animal
    (can be: zabra,donkey,bat)
    could be one of these

    """

</code>```

Body:
import argparse
parser = argparse.ArgumentParser(prog='tool')
args = [('-u', '--upf', 'ref. upf', dict(required='True')),
        ('-s', '--skew', 'ref. skew', {}),
        ('-m', '--model', 'ref. model', {})]
for args1, args2, desc, options in args:
     parser.add_argument(args1, args2, help=desc, **options)

parser.print_help()

Output:

usage: capcheck [-h] -u UPF [-s SKEW] [-m MODEL]

optional arguments:
  -h, --help            show this help message and exit
  -u UPF, --upf UPF     ref. upf
  -s SKEW, --skew SKEW  ref. skew
  -m MODEL, --model MODEL
                        ref. model

How do I print ref. model in the same line as -m MODEL, --model MODEL instead of that appearing on a separate line when I run the script with -h option?

Body:
Another approach: hijack sys.argv, check it for --help and -h, if found extract help text using argparse.format_help, massage it, print it, and exit.

import  sys, re, argparse

RGX_MID_WS = re.compile(r'(\S)\s{2,}')

def main(argv):

#   note add_help = False
    parser = argparse.ArgumentParser(description = '%(prog)s: testing help mods', formatter_class= argparse.RawTextHelpFormatter, add_help = False)

    parser.add_argument('bar', nargs='+', help='two bars that need to be frobbled')
    parser.add_argument('--foo', action='store_true', help='foo the bars before frobbling\nfoo the bars before frobbling')
    parser.add_argument('--xxxxx', nargs=2, help='many xes')
    parser.add_argument('--bacon', help ='a striped food')
    parser.add_argument('--badger', help='in a striped pyjamas')
    parser.add_argument('--animal', dest='animal', choices=('zabra', 'donkey', 'bat') ,help ='could be one of these')

#   may exit
    lArgs = help_manage(parser)
    args = parser.parse_args() # args = lArgs

    print('bars are: ', args.bar)

def help_manage(parser):
    """
    check for -h, --help, -h in a single-letter cluster;
    if none found, return, otherwise clean up help text and exit
    """

    lArgs = sys.argv[1:]
    lArgsNoHelp = [sOpt for sOpt in lArgs if (not sOpt in ('--help', '-h')) and not (sOpt[0] == '-' and sOpt[1] != '-' and 'h' in sOpt)]

#   no change?  then no --help params
    if len(lArgsNoHelp) == len(lArgs): return

    sHelp = parser.format_help()

#   to see help as formated by argparse, uncomment:
#   print(sHelp)
#   exit()

    for sLine in sHelp.split('\n'): print(clean_line(sLine))

    exit()

def clean_line(sLine):
    """
    this is just an example, and goes nowhere near covering all possible
    argument properties
    """
#   avoid messing with usage: lines
    if 'usage' in sLine: return sLine
    if sLine.startswith('  ') and '[' in sLine: return sLine

    if sLine.endswith(' arguments:'): return sLine + '\n'

    sLine = sLine.lstrip()

    sLine = RGX_MID_WS.sub(r'\1\n', sLine)
    if sLine.startswith('-'): sLine = '\n' + sLine
    return sLine.replace('{', '\n(can be: ').replace('}', ')').replace('\n\n', '\n')

if __name__ == '__main__':

    bRes =  main(sys.argv[1:])
    sys.exit(bRes)

Help without formatting:

usage: argparse_fix_min2.py [--foo] [--xxxxx XXXXX XXXXX] [--bacon BACON]
                                [--badger BADGER] [--animal {zabra,donkey,bat}]
                                bar [bar ...]

    argparse_fix_min2.py: testing help mods

    positional arguments:
      bar                   two bars that need to be frobbled

    optional arguments:
      --foo                 foo the bars before frobbling
                            foo the bars before frobbling
      --xxxxx XXXXX XXXXX   many xes
      --bacon BACON         a striped food
      --badger BADGER       in a striped pyjamas
      --animal {zabra,donkey,bat}
                            could be one of these

with formatting:

usage: argparse_fix_min2.py [--foo] [--xxxxx XXXXX XXXXX] [--bacon BACON]
                                [--badger BADGER] [--animal {zabra,donkey,bat}]
                                bar [bar ...]

    argparse_fix_min2.py: testing help mods

    positional arguments:

    bar
    two bars that need to be frobbled

    optional arguments:

    --foo
    foo the bars before frobbling
    foo the bars before frobbling

    --xxxxx XXXXX XXXXX
    many xes

    --bacon BACON
    a striped food

    --badger BADGER
    in a striped pyjamas

    --animal
    (can be: zabra,donkey,bat)
    could be one of these

    """


问:
Android: onDestroy not executed after calling stopSelf
I have a QtAndroid application with a service implemented using QtService. If I want to quit the service, I do it like this:

In C++:

```<code>QtAndroid::androidService().callMethod<void>("quit");
</code>```

In Java service:

```<code>public void quit() {
    stopSelf();
}
</code>```

Then there is an onDestroy function:

```<code>@Override
public void onDestroy() {
    Log.d("MyService", "Called onDestroy");
    super.onDestroy();
}
</code>```

The log message is never shown and I suppose the onDestroy function gets not called. In my application the service is not even stopped. I tried a minimal example based on this guide. With this minimal implementation the service is stopped but the onDestroy function is not called neither.

To demonstrate the problem I took the example source code and modified it like this:

server.cpp

```<code>#include <QAndroidService>
#include <QtAndroid>
#include "rep_pingpong_source.h"

class PingPong : public PingPongSource {
public slots:
    // PingPongSource interface
    void ping(const QString &msg) override {
        qDebug() << "KDAB: Message "+msg;
        emit pong(msg + " from server");
        if (msg == "Quit") {
            qDebug() << "MyService: C++ quit";
            QtAndroid::androidService().callMethod<void>("quit");
        }
    }
};

int main(int argc, char *argv[])
{
    QAndroidService app(argc, argv);

    QRemoteObjectHost srcNode(QUrl(QStringLiteral("local:replica")));
    PingPong pingPongServer;
    srcNode.enableRemoting(&pingPongServer);

    return app.exec();
}
</code>```

MyService.java

```<code>// java file android/src/com/kdab/training/MyService.java
package com.kdab.training;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import org.qtproject.qt5.android.bindings.QtService;

public class MyService extends QtService
{
    public static void startMyService(Context ctx) {
        ctx.startService(new Intent(ctx, MyService.class));
    }

    @Override
    public void onDestroy() {
        Log.d("MyService", "Called onDestroy");
        super.onDestroy();
    }

    public void quit() {
        Log.d("MyService", "Called quit");
        stopSelf();
    }
}
</code>```

If I check the log, the Called quit message appears but the Called onDestroy never. Do you have any idea why this happens and how can I debug the behavior? Also what could be the reason that my service won't stop? How can I find out what is preventing it from quitting?

Thank you!

答:
in every service in android can run as a foreground or background. if you want to quit service. you just need to call  stopSelf();
the method in onDestroy but you need to make sure that there is no callback happening before calling stopSelf();

Body:
I have a QtAndroid application with a service implemented using QtService. If I want to quit the service, I do it like this:

In C++:

QtAndroid::androidService().callMethod<void>("quit");

In Java service:

public void quit() {
    stopSelf();
}

Then there is an onDestroy function:

@Override
public void onDestroy() {
    Log.d("MyService", "Called onDestroy");
    super.onDestroy();
}

The log message is never shown and I suppose the onDestroy function gets not called. In my application the service is not even stopped. I tried a minimal example based on this guide. With this minimal implementation the service is stopped but the onDestroy function is not called neither.

To demonstrate the problem I took the example source code and modified it like this:

server.cpp

#include <QAndroidService>
#include <QtAndroid>
#include "rep_pingpong_source.h"

class PingPong : public PingPongSource {
public slots:
    // PingPongSource interface
    void ping(const QString &msg) override {
        qDebug() << "KDAB: Message "+msg;
        emit pong(msg + " from server");
        if (msg == "Quit") {
            qDebug() << "MyService: C++ quit";
            QtAndroid::androidService().callMethod<void>("quit");
        }
    }
};

int main(int argc, char *argv[])
{
    QAndroidService app(argc, argv);

    QRemoteObjectHost srcNode(QUrl(QStringLiteral("local:replica")));
    PingPong pingPongServer;
    srcNode.enableRemoting(&pingPongServer);

    return app.exec();
}

MyService.java

// java file android/src/com/kdab/training/MyService.java
package com.kdab.training;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import org.qtproject.qt5.android.bindings.QtService;

public class MyService extends QtService
{
    public static void startMyService(Context ctx) {
        ctx.startService(new Intent(ctx, MyService.class));
    }

    @Override
    public void onDestroy() {
        Log.d("MyService", "Called onDestroy");
        super.onDestroy();
    }

    public void quit() {
        Log.d("MyService", "Called quit");
        stopSelf();
    }
}

If I check the log, the Called quit message appears but the Called onDestroy never. Do you have any idea why this happens and how can I debug the behavior? Also what could be the reason that my service won't stop? How can I find out what is preventing it from quitting?

Thank you!


问:
Voice call recording Application in android
I like to make an application for recording voice call.Is it possible? I expecting some proper guiding from well experienced people in android.

i have seen android.media.MediaRecorder class in android. Is that class i need to use for this?

Thanks and Regards

Parvathi Kamalone.

答: Developers do not have access to the in-call audio stream, sorry. The only way this sort of works is if the device is in speakerphone mode.</p>


问:
Dialogflow Webhooks: What is a webhookStatus code 14 mean?
My Dialogflow project is not making proper webhook calls. I ran the curl command, given to you while testing, in command prompt.

```<code>curl -H "Content-Type: application/json; charset=utf-8"  -H "Authorization: Bearer ya29.c.Ko8BvQcQFJJgEzKprtZn9kWStTWE5trMyYN8_oilT_4LInyASeCGiBcrrSepTvrjomVCZKSaFF_RaCYoC_yBU0LWM8ODzRlliAHQv1C97veQuxNjq_aeWLEN361drz6Rk_WEn7hl52DRN32ee4xmV97rW8nqBVFsbPykXdkjj83iKWjwKv9FKVhNJNOfMaejMH4"  -d "{\"queryInput\":{\"text\":{\"text\":\"run\",\"languageCode\":\"en\"}},\"queryParams\":{\"timeZone\":\"America/New_York\"}}" "https://dialogflow.googleapis.com/v2/projects/weathersample-ifjqjr/agent/sessions/ed2ec645-d8da-55b7-f71e-d0ee8d7ff2bb:detectIntent"
</code>```

The response I got back was:

```<code>    {
  "responseId": "5eea8256-8771-4db1-8b51-2c82e31c7bf4-2e39b744",
  "queryResult": {
    "queryText": "run",
    "parameters": {},
    "allRequiredParamsPresent": true,
    "fulfillmentText": "Error: Speed test has not been called properly",
    "fulfillmentMessages": [
      {
        "text": {
          "text": [
            "Error: Speed test has not been called properly"
          ]
        }
      }
    ],
    "outputContexts": [
      {
        "name": "projects/weathersample-ifjqjr/agent/sessions/ed2ec645-d8da-55b7-f71e-d0ee8d7ff2bb/contexts/location",
        "lifespanCount": 5
      },
      {
        "name": "projects/weathersample-ifjqjr/agent/sessions/ed2ec645-d8da-55b7-f71e-d0ee8d7ff2bb/contexts/weathercontext-followup",
        "lifespanCount": 2
      }
    ],
    "intent": {
      "name": "projects/weathersample-ifjqjr/agent/intents/98199125-8fc6-466f-98b6-7648e14b06e7",
      "displayName": "runSpeedTest"
    },
    "intentDetectionConfidence": 1,
    "diagnosticInfo": {
      "webhook_latency_ms": 2439
    },
    "languageCode": "en"
  },
  "webhookStatus": {
    "code": 14,
    "message": "Webhook call failed. Error: UNAVAILABLE."
  }
</code>```

At the bottom of this response there is a "webhookStatus" object with an unavailable error and code of 14. Does anyone know what that code means?

答: Webhook is basically HTTP callback which will be triggered when the web-hook enabled intents are matched. Code:14 UNAVAILABLE means that it is looking for a handling function mapped to "runSpeedTest" intent which is not present in the web-hook provided. You can test it in Fulfilment->Inline Editor before deploying it externally.</p>

Body:
My Dialogflow project is not making proper webhook calls. I ran the curl command, given to you while testing, in command prompt.

curl -H "Content-Type: application/json; charset=utf-8"  -H "Authorization: Bearer ya29.c.Ko8BvQcQFJJgEzKprtZn9kWStTWE5trMyYN8_oilT_4LInyASeCGiBcrrSepTvrjomVCZKSaFF_RaCYoC_yBU0LWM8ODzRlliAHQv1C97veQuxNjq_aeWLEN361drz6Rk_WEn7hl52DRN32ee4xmV97rW8nqBVFsbPykXdkjj83iKWjwKv9FKVhNJNOfMaejMH4"  -d "{\"queryInput\":{\"text\":{\"text\":\"run\",\"languageCode\":\"en\"}},\"queryParams\":{\"timeZone\":\"America/New_York\"}}" "https://dialogflow.googleapis.com/v2/projects/weathersample-ifjqjr/agent/sessions/ed2ec645-d8da-55b7-f71e-d0ee8d7ff2bb:detectIntent"

The response I got back was:

    {
  "responseId": "5eea8256-8771-4db1-8b51-2c82e31c7bf4-2e39b744",
  "queryResult": {
    "queryText": "run",
    "parameters": {},
    "allRequiredParamsPresent": true,
    "fulfillmentText": "Error: Speed test has not been called properly",
    "fulfillmentMessages": [
      {
        "text": {
          "text": [
            "Error: Speed test has not been called properly"
          ]
        }
      }
    ],
    "outputContexts": [
      {
        "name": "projects/weathersample-ifjqjr/agent/sessions/ed2ec645-d8da-55b7-f71e-d0ee8d7ff2bb/contexts/location",
        "lifespanCount": 5
      },
      {
        "name": "projects/weathersample-ifjqjr/agent/sessions/ed2ec645-d8da-55b7-f71e-d0ee8d7ff2bb/contexts/weathercontext-followup",
        "lifespanCount": 2
      }
    ],
    "intent": {
      "name": "projects/weathersample-ifjqjr/agent/intents/98199125-8fc6-466f-98b6-7648e14b06e7",
      "displayName": "runSpeedTest"
    },
    "intentDetectionConfidence": 1,
    "diagnosticInfo": {
      "webhook_latency_ms": 2439
    },
    "languageCode": "en"
  },
  "webhookStatus": {
    "code": 14,
    "message": "Webhook call failed. Error: UNAVAILABLE."
  }

At the bottom of this response there is a "webhookStatus" object with an unavailable error and code of 14. Does anyone know what that code means?


问:
Get paginated result in Mongodb aggregation
I am playing with some large amount of data and to query that data I am using mongodb aggregation framework. Here is a sample data:

```<code>{
   "id": "1"
   "name":"abc"
},
{
   "id": "2"
   "name":"abc"
},
{
   "id": "3"
   "name":"abc"
},
...,
{
   "id": "100"
   "name":"abc"
}
</code>```

So what I am doing is 10 results at a time so for that I set the $limit to 10. But what if I want 10 result after id:10 i.e. 10 results after the object with id 10. So it should return

```<code>{
   "id": "11"
   "name":"abc"
},
{
   "id": "12"
   "name":"abc"
},
{
   "id": "13"
   "name":"abc"
},
...(And So on till id:20)
</code>```

Is there any way to do this kind of aggregation query? Any help or suggestion would be appreciated. Thank you in advance.

答:
While requesting for results, pass pageSize and pageNumber in your request.

```<code>db.your_collection.aggregate([
    {
        "$match": {
            // your query
        }
    },
    {
        "$skip": (pageNumber - 1) * pageSize
    },
    {
        "$limit": pageSize
    }
])
</code>```

Or you can use:

```<code>db.your_collection.find({/*your query*/}).skip((pageNumber - 1) * pageSize).limit(pageSize)
</code>```

Body:
I am playing with some large amount of data and to query that data I am using mongodb aggregation framework. Here is a sample data:

{
   "id": "1"
   "name":"abc"
},
{
   "id": "2"
   "name":"abc"
},
{
   "id": "3"
   "name":"abc"
},
...,
{
   "id": "100"
   "name":"abc"
}

So what I am doing is 10 results at a time so for that I set the $limit to 10. But what if I want 10 result after id:10 i.e. 10 results after the object with id 10. So it should return

{
   "id": "11"
   "name":"abc"
},
{
   "id": "12"
   "name":"abc"
},
{
   "id": "13"
   "name":"abc"
},
...(And So on till id:20)

Is there any way to do this kind of aggregation query? Any help or suggestion would be appreciated. Thank you in advance.

Body:
While requesting for results, pass pageSize and pageNumber in your request.

db.your_collection.aggregate([
    {
        "$match": {
            // your query
        }
    },
    {
        "$skip": (pageNumber - 1) * pageSize
    },
    {
        "$limit": pageSize
    }
])

Or you can use:

db.your_collection.find({/*your query*/}).skip((pageNumber - 1) * pageSize).limit(pageSize)


问:
KDevelop automatically inserts a space after # in #include <file.h>
I simply want to include a C++ header file in KDevelop by writing

```<code>#include <file.h>
</code>```

However, KDevelop automatically corrects the above statement to

```<code># include <file.h>
</code>```

I have not been able to figure out where I can change this. I want the first version, such that my files are similar to the other files in the project I am working on.

The file is type set correctly as a C++ file. I think the reason for the extra space is that KDevelop wants to indent the line because it is inside a conditional, i.e. a include guard as given below:

```<code>#ifndef THIS_FILE_H
#define THIS_FILE_H

// THIS_FILE_H
#endif
</code>```

KDevelop also wants to indent the #define THIS_FILE_H line.

I have tried created my own indentation style by going to the Settings -> Customize KDevelop menu item, and then clicking on Source Formatter on the left. When defining the formatting style, I have disabled the indentation of preprocessor directives, nevertheless, it has no effect on the indentation of the #include and #define inside the include guard.

答:
The automatic spaces appear to be caused by the indentation mode, which (in KDevelop 4.7.1) you can switch for the current file via Editor -> Tools -> Indentation. If indentation is set to C++/boost Style, you'll get those weird automatic spaces while typing; while in mode Normal you only get the usual indentation at beginning of line.

The default indentation mode can be set in Settings -> Configure Editor -> Open/Save -> Modes & Filetypes. For each Filetype (eg. Sources/C, Sources/C++, Sources/C++11, Sources/C++11/Qt4) the Indentation Mode can be set independently.

KDevelop appears to remember the setting for files you have opened once; so for these files the new configuration settings have no effect. I don't know how to make KDevelop forget these per-file settings.

Body:
I simply want to include a C++ header file in KDevelop by writing

#include <file.h>

However, KDevelop automatically corrects the above statement to

# include <file.h>

I have not been able to figure out where I can change this. I want the first version, such that my files are similar to the other files in the project I am working on.

The file is type set correctly as a C++ file. I think the reason for the extra space is that KDevelop wants to indent the line because it is inside a conditional, i.e. a include guard as given below:

#ifndef THIS_FILE_H
#define THIS_FILE_H

// THIS_FILE_H
#endif

KDevelop also wants to indent the #define THIS_FILE_H line.

I have tried created my own indentation style by going to the Settings -> Customize KDevelop menu item, and then clicking on Source Formatter on the left. When defining the formatting style, I have disabled the indentation of preprocessor directives, nevertheless, it has no effect on the indentation of the #include and #define inside the include guard.


问:
Firebase create Dynamic Link not working in react native iOS. However it seems to work fine in android
I have created a dynamic link using :

```<code>var link = new firebase.links.DynamicLink(
      "https://freshc.in",
      "frendy.page.link",
    ).android
      .setPackageName("in.frendy.app")
      .ios.setBundleId("in.freshchat.app");
    console.log('link', link); //This is giving the console in both android and ios

    firebase
      .links()
      .createDynamicLink(link)
      .then(url => {
        console.log('Dynamic Link', url); //This is not working in iOS.
        link = "http://" + decodeURIComponent(url);
      });
</code>```

The above code is working fine in android but when we move on to iOS it throws an error that :

Possible Unhandled Promise Rejection (id: 0):
  Error: Failed to create Dynamic Link
  Error: Failed to create Dynamic Link
      at createErrorFromErrorData (blob:http://localhost:8081/e76b670d-7fe9-40cb-b837-aa0d40d85769:2122:17)
      at blob:http://localhost:8081/e76b670d-7fe9-40cb-b837-aa0d40d85769:2074:27
      at MessageQueue.__invokeCallback (blob:http://localhost:8081/e76b670d-7fe9-40cb-b837-aa0d40d85769:2645:18)
      at blob:http://localhost:8081/e76b670d-7fe9-40cb-b837-aa0d40d85769:2376:18
      at MessageQueue.__guard (blob:http://localhost:8081/e76b670d-7fe9-40cb-b837-aa0d40d85769:2549:13)
      at MessageQueue.invokeCallbackAndReturnFlushedQueue (blob:http://localhost:8081/e76b670d-7fe9-40cb-b837-aa0d40d85769:2375:14)
      at http://localhost:8081/debugger-ui/debuggerWorker.js:80:58

Also note that I can open the application when I search from google with the app prefix name like in.freshachat.app://
But I don't get the link

What might be causing this issue?

答:
Well well well,
if someone gets this problem remember to add 'HTTPS' in the domain name :

var link = new firebase.links.DynamicLink(
      "https://freshc.in",
      "https://frendy.page.link",
 )

Body:
I have created a dynamic link using :

var link = new firebase.links.DynamicLink(
      "https://freshc.in",
      "frendy.page.link",
    ).android
      .setPackageName("in.frendy.app")
      .ios.setBundleId("in.freshchat.app");
    console.log('link', link); //This is giving the console in both android and ios

    firebase
      .links()
      .createDynamicLink(link)
      .then(url => {
        console.log('Dynamic Link', url); //This is not working in iOS.
        link = "http://" + decodeURIComponent(url);
      });

The above code is working fine in android but when we move on to iOS it throws an error that :

Possible Unhandled Promise Rejection (id: 0):
  Error: Failed to create Dynamic Link
  Error: Failed to create Dynamic Link
      at createErrorFromErrorData (blob:http://localhost:8081/e76b670d-7fe9-40cb-b837-aa0d40d85769:2122:17)
      at blob:http://localhost:8081/e76b670d-7fe9-40cb-b837-aa0d40d85769:2074:27
      at MessageQueue.__invokeCallback (blob:http://localhost:8081/e76b670d-7fe9-40cb-b837-aa0d40d85769:2645:18)
      at blob:http://localhost:8081/e76b670d-7fe9-40cb-b837-aa0d40d85769:2376:18
      at MessageQueue.__guard (blob:http://localhost:8081/e76b670d-7fe9-40cb-b837-aa0d40d85769:2549:13)
      at MessageQueue.invokeCallbackAndReturnFlushedQueue (blob:http://localhost:8081/e76b670d-7fe9-40cb-b837-aa0d40d85769:2375:14)
      at http://localhost:8081/debugger-ui/debuggerWorker.js:80:58

Also note that I can open the application when I search from google with the app prefix name like in.freshachat.app://
But I don't get the link

What might be causing this issue?


问:
How to calculate the time spent when using got?
Example code:

```<code>const got = require('got');
async function timeSpent (){
   const time = new Date().getTime()
   await got('***')
   return new Date().getTime() - time
}
</code>```

I wonder if there is a better way?

答:
performance - is a native way to measure things like this.

```<code>const got = require('got');
async function timeSpent (){
  var t0 = performance.now();
  await got('***')
  var t1 = performance.now();
  console.log("Call to do something took " + (t1 - t0) + " milliseconds.");
  return t1 - t0;
}
</code>```

Check browser support https://caniuse.com/#search=performance

Body:
Example code:

const got = require('got');
async function timeSpent (){
   const time = new Date().getTime()
   await got('***')
   return new Date().getTime() - time
}

I wonder if there is a better way?

Body:
performance - is a native way to measure things like this.

const got = require('got');
async function timeSpent (){
  var t0 = performance.now();
  await got('***')
  var t1 = performance.now();
  console.log("Call to do something took " + (t1 - t0) + " milliseconds.");
  return t1 - t0;
}

Check browser support https://caniuse.com/#search=performance


问:
Get column sum and use it for distribute a value
I have 2 tables, sales_order and sales_order_line.

sales_order table contains a detail of a transaction in transaction level and sales_order_line table contains a detail in SKU (item) level. I joined those 2 tables and realized that discount value is on transaction level. When customer bought more than 1 item, I need to distribute the value of discount based on item price and when customer bought just 1 item, discount value just applied as it is. The tables look like this.

sales_order

```<code>ID   | PLATFORM_ORDER_CODE | OMS_ORDER_CODE | DISCOUNT_TOTAL
0001          19000001         nebula0001         300000
0002          19000001         nebula0002         300000
0003          19000001         nebula0003         300000
0004          19000002         nebula0004         100000
0005          19000002         nebula0005         100000
0006          19000003         nebula0006          50000
</code>```

sales_order_line

```<code>SALES_ORDER_ID | PLATFORM_ORDER_CODE | SKU_CODE | UNIT_PRICE
0001                   19000001        SKUA0001     200000
0002                   19000001        SKUA0002     100000
0003                   19000001        SKUA0003     300000
0004                   19000002        SKUA0001     200000
0005                   19000002        SKUA0002     100000
0006                   19000003        SKUA0001     200000
</code>```

This is my attempt on DB Fiddle and I need the result to be like this

```<code>PLATFORM_ORDER_CODE | OMS_ORDER_CODE | SKU_CODE | UNIT_PRICE | DISCOUNT
19000001                 nebula0001    SKUA0001     200000      100000
19000001                 nebula0002    SKUA0002     100000      50000
19000001                 nebula0003    SKUA0003     300000      150000
19000002                 nebula0004    SKUA0001     200000      66666.6666
19000002                 nebula0005    SKUA0002     100000      33333.3333
19000003                 nebula0006    SKUA0001     200000      50000
</code>```

答:
If you are running MySQL 8.0, you can use window functions for this:

```<code>select
    o.platform_order_code,
    o.oms_order_code,
    l.sku_code,
    l.unit_price,
    o.discount_total
        * l.unit_price
        / sum(l.unit_price) over(partition by o.platform_order_code) discount
from sales_order o
inner join sales_order_line l on l.sales_order_id  = o.id
</code>```

The logic to compute the order line discount is to compute the ratio of the current order line unit_price against the total price for the current platform_order_code, and then appply it to the order discount.

Body:
I have 2 tables, sales_order and sales_order_line.

sales_order table contains a detail of a transaction in transaction level and sales_order_line table contains a detail in SKU (item) level. I joined those 2 tables and realized that discount value is on transaction level. When customer bought more than 1 item, I need to distribute the value of discount based on item price and when customer bought just 1 item, discount value just applied as it is. The tables look like this.

sales_order

ID   | PLATFORM_ORDER_CODE | OMS_ORDER_CODE | DISCOUNT_TOTAL
0001          19000001         nebula0001         300000
0002          19000001         nebula0002         300000
0003          19000001         nebula0003         300000
0004          19000002         nebula0004         100000
0005          19000002         nebula0005         100000
0006          19000003         nebula0006          50000

sales_order_line

SALES_ORDER_ID | PLATFORM_ORDER_CODE | SKU_CODE | UNIT_PRICE
0001                   19000001        SKUA0001     200000
0002                   19000001        SKUA0002     100000
0003                   19000001        SKUA0003     300000
0004                   19000002        SKUA0001     200000
0005                   19000002        SKUA0002     100000
0006                   19000003        SKUA0001     200000

This is my attempt on DB Fiddle and I need the result to be like this

PLATFORM_ORDER_CODE | OMS_ORDER_CODE | SKU_CODE | UNIT_PRICE | DISCOUNT
19000001                 nebula0001    SKUA0001     200000      100000
19000001                 nebula0002    SKUA0002     100000      50000
19000001                 nebula0003    SKUA0003     300000      150000
19000002                 nebula0004    SKUA0001     200000      66666.6666
19000002                 nebula0005    SKUA0002     100000      33333.3333
19000003                 nebula0006    SKUA0001     200000      50000

Body:
If you are running MySQL 8.0, you can use window functions for this:

select
    o.platform_order_code,
    o.oms_order_code,
    l.sku_code,
    l.unit_price,
    o.discount_total
        * l.unit_price
        / sum(l.unit_price) over(partition by o.platform_order_code) discount
from sales_order o
inner join sales_order_line l on l.sales_order_id  = o.id

The logic to compute the order line discount is to compute the ratio of the current order line unit_price against the total price for the current platform_order_code, and then appply it to the order discount.


问:
How to reset the base route in my Flutter App - that is pop any routes and replace it with a new one using Navigator
New to Flutter to please forgive me if this is obvious, but I have read the documentation and tried a bunch of the Navigator options but none of them work as I would like.  The problem set:  We have a complex (well, semi-complex) series of screens, etc. that handle the login / authorization / registration process.  This can get down to 3 or 4 levels on the Route stack.  This is all fine -- no worries.

The problem comes when we get a successful login event (from a few different paths) and want to go to the "home" page.  Once we are on the home page that should be the new "root" of the Route tree (I am sure this isn't the correct terminology -- but I think the idea is solid).

So, given we could be 1/2/3 or even 4 levels down and want to "pop" and replace the whole stack (with any transition events, please) to a new top level root -- what magical Navigator set or methods will do this cleanly?

My current (horrid) approach is to hand "pop()" the levels and do a Navigator.pushReplacementNamed() call (they are all named routes here) but that isn't a generic solution (have to know exactly how many levels) and worse, it causes a "animation" transition to "pop" on the screen for a split second for each pop() which looks .. not very good.

TIA!

答:
The good news is now we can use pushReplacementNamed

```<code>Navigator.pushReplacementNamed(context, '/');
</code>```

(Channel master, v1.15.4-pre.97, I'm not sure the previous version can do that)

Body:
The good news is now we can use pushReplacementNamed

Navigator.pushReplacementNamed(context, '/');

(Channel master, v1.15.4-pre.97, I'm not sure the previous version can do that)


问:
Breakpoint not hitting
I ported an application from VC6 to VS 2008. I rebuilt the application in release build.  The Pdb file is available in the folder where exe is located.  But when I loaded the application and put break point I am getting the following message

"The breakpoint will not currently be hit.No symbols have been loaded for this document"

What would be the cause of the issue?

答:
The PDB file you mention is probably not related to the release build,

Debug information is normally absent in the release build (though you can enable it if you have to but should anticipate surprising effects due to compiler optimizations).

Therefore, you can only set breakpoints on known DLL entry points (possible via the Module List view - it has been a while since I used Visual Studio intensively) or directly on assembly instructions.

Note that you could perhaps compile part of your application with debug symbols.

Title: Breakpoint not hitting