问:
Paginate one page with different tabs Laravel
I want to paginate in a blade file different tabs , each tabs show different collections of object but each time i go to next page in one page it redirects to the first tab and also paginate each tab not just the one i wanted to paginate.

Blade Part Where i have tabs

```<code>    <div class="container">
        <div class="section-bg-color">
            <div class="row">
                <div class="col-lg-12">
                    <!-- My Account Page Start -->
                    <div class="myaccount-page-wrapper">
                        <!-- My Account Tab Menu Start -->
                        <div class="row">
                            <div class="col-lg-3 col-md-4">
                                <div class="myaccount-tab-menu nav" role="tablist" id="myTab">
                                    <a href="#dashboad" class="active" data-toggle="tab"><i class="fa fa-dashboard"></i>Dashboard</a>
                                    <a href="#users" data-toggle="tab"><i class="fa fa-user"></i>Gestione Utenti</a>
                                    <a href="#comics" data-toggle="tab"><i class="fa fa-book"></i>Gestione Fumetti</a>
                                    <a href="#reviews" data-toggle="tab"><i class="fa fa-map-marker"></i>Gestione Recensione</a>
                                </div>
                            </div>

                            <!-- My Account Tab Menu End -->
                            <!-- My Account Tab Content Start -->
                            <div class="col-lg-9 col-md-8">
                                <div class="tab-content" id="myaccountContent">
                                    <!-- Single Tab Content Start -->
                                    <div class="tab-pane fade show active" id="dashboad" role="tabpanel">
                                        <div class="myaccount-content">
                                            <h5>Dashboard</h5>
                                            <div class="welcome">
                                                <p>Ciao, <strong>{{ $user->username }}</strong>! (Non sei <strong>{{ $user->username }}</strong>?<a href="{{ url('/logout') }}" class="logout"> Logout</a>)</p>
                                            </div>
                                            <p class="mb-0">I tuoi dati:</p>
                                            <p class="mb-0">E-mail:   <strong>{{ $user->email }} </strong></p>
                                        </div>
                                        <div class="myaccount-content">
                                            @php
                                                $notifications = \App\Http\Controllers\NotificationController::getNotification($user->id);
                                            @endphp
                                            <h5>Notifiche</h5>
                                            @if($notifications->count() < 1)
                                                <div class="myaccount-content">
                                                    <h5>Non ci sono ancora notifiche</h5>
                                                </div>
                                            @else
                                                <div class="myaccount-table table-responsive text-center">
                                                    <table class="table table-bordered">
                                                        <thead class="thead-light">
                                                        <tr>
                                                            <th>Data</th>
                                                            <th>testo</th>
                                                            <th>stato</th>
                                                            <th>Action</th>
                                                        </tr>
                                                        </thead>
                                                        <tbody>
                                                        @foreach($notifications as $notification)
                                                            <tr>
                                                                <td>{{ $notification->date }}</td>
                                                                <td>
                                                                    @if(strlen($notification->notification_text) > 50 )
                                                                        @php
                                                                            $subnotification = substr($notification->notification_text, 0, 50)
                                                                        @endphp
                                                                        {{ $subnotification }}...
                                                                    @else
                                                                        {{ $notification->notification_text }}
                                                                    @endif
                                                                </td>
                                                                @if($notification->state == 1)
                                                                    <td>
                                                                        Letto
                                                                    </td>
                                                                    <td>
                                                                        <a href="{{ url('/accountArea') }}" class="btn btn-sqr">View</a>
                                                                    </td>
                                                                @else
                                                                    <td>
                                                                        Non letto
                                                                    </td>
                                                                    <td>
                                                                        <a href="{{ route('notificaLetta', ['id' => $notification->id]) }}" class="btn btn-sqr">View</a>
                                                                    </td>
                                                                @endif
                                                            </tr>
                                                        @endforeach
                                                        </tbody>
                                                    </table>
                                                </div>
                                            @endif
                                        </div>
                                    </div>
                                    <!-- Single Tab Content End -->
                                @if(session('message'))
                                    {{session('message')}}
                                @endif
                                    <!-- Single Tab Content Start -->
                                    <div class="tab-pane fade" id="users" role="tabpanel">
                                        <div class="myaccount-content">
                                            <h5>Utenti</h5>
                                            <div class="myaccount-table table-responsive text-center">
                                                <table class="table table-bordered">
                                                    <thead class="thead-light">
                                                    <tr>
                                                        <th>Nickname</th>
                                                        <th>Phone</th>
                                                        <th>Email</th>
                                                        <th>Tipologia</th>
                                                        <th>Elimina</th>
                                                    </tr>
                                                    </thead>
                                                    <tbody>
                                                    @foreach($users as $user)
                                                    <tr>
                                                        <td>{{$user->username}}</td>
                                                        <td>{{$user->phone_number}}</td>
                                                        <td>{{$user->email}}</td>
                                                        @if($user->hasGroup('il gruppo degli utenti'))
                                                        <td>Utente</td>
                                                        @else
                                                            <td>Venditore</td>
                                                        @endif
                                                        <td><a class="btn btn-danger" onclick="return myFunction();"  href="{{route('user-delete', $user->id)}}"><i class="fa fa-trash"></i></a></td>
                                                        <script>
                                                            function myFunction() {
                                                                if(!confirm("Sei sicuro di voler eliminare questo utente"))
                                                                    event.preventDefault();
                                                            }
                                                        </script>
                                                    </tr>
                                                    @endforeach
                                                    {{ $users->links() }}
                                                    </tbody>

                                                </table>
                                            </div>
                                        </div>
                                    </div>
                                    <!-- Single Tab Content End -->

                                    <!-- Single Tab Content Start -->
                                    <div class="tab-pane fade" id="comics" role="tabpanel">
                                        <div class="myaccount-content">
                                            <h5>Fumetti</h5>
                                            <div class="myaccount-table table-responsive text-center">
                                                <table class="table table-bordered">
                                                    <thead class="thead-dark">
                                                    <tr>
                                                        <th>Titolo</th>
                                                        <th>ISBN</th>
                                                        <th>Quantità</th>
                                                        <th>Utente</th>
                                                        <th>Elimina</th>
                                                    </tr>
                                                    </thead>
                                                    <tbody>
                                                    @foreach($comics as $comic)
                                                        @php
                                                            $userNeed = App\User::where('id','=',$comic->user_id)->first();
                                                        @endphp
                                                        <tr>
                                                            <td>{{$comic->comic_name}}</td>
                                                            <td>{{$comic->ISBN}}</td>
                                                            <td>{{$comic->quantity}}</td>
                                                            <td>{{$userNeed->username}}</td>
                                                            <td><a class="btn btn-danger" onclick="return myFunction();"  href="{{route('comic-delete', $comic->id)}}"><i class="fa fa-trash"></i></a></td>
                                                            <script>
                                                                function myFunction() {
                                                                    if(!confirm("Sei sicuro di voler eliminare questo fumetto"))
                                                                        event.preventDefault();
                                                                }
                                                            </script>
                                                        </tr>
                                                    @endforeach
                                                    {{ $comics->links() }}
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </div>
                                    <!-- Single Tab Content End -->

                                    <!-- Single Tab Content Start -->
                                    <div class="tab-pane fade" id="reviews" role="tabpanel">
                                        <div class="myaccount-content">
                                            <h5>Recensione</h5>
                                            <div class="myaccount-table table-responsive text-center">
                                                <table class="table table-bordered">
                                                    <thead class="thead-dark">
                                                    <tr>
                                                        <th>Titolo</th>
                                                        <th>Fumetto</th>
                                                        <th>Recensore</th>
                                                        <th>Elimina</th>
                                                    </tr>
                                                    </thead>
                                                    <tbody>
                                                    @foreach($reviews as $review)
                                                        @php
                                                            $userReview = App\User::where('id','=',$review->user_id)->first();
                                                            $comicReview = App\Comic::where('id','=',$review->comic_id)->first();
                                                        @endphp
                                                        <tr>
                                                            <td>{{$review->review_title}}</td>
                                                            <td>{{$comicReview->comic_name}}</td>
                                                            <td>{{$userReview->username}}</td>
                                                            <td><a class="btn btn-danger" onclick="return myFunction();"  href="{{route('review-delete-local', $review->id)}}"><i class="fa fa-trash"></i></a></td>
                                                            <script>
                                                                function myFunction() {
                                                                    if(!confirm("Sei sicuro di voler eliminare questa recensione"))
                                                                        event.preventDefault();
                                                                }
                                                            </script>
                                                        </tr>
                                                    @endforeach
                                                    {{ $reviews->links() }}
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div> <!-- My Account Tab Content End -->
                        </div>
                    </div> <!-- My Account Page End -->
                </div>
            </div>
        </div>
    </div>
</div>

</code>```

And this is my route
Route

```<code>Route::get('/adminArea', function () {
    $user = \Illuminate\Support\Facades\Auth::user();
    $users = \App\User::where('username','!=','admin')->orderBy('username', 'asc')->paginate(12);
    $comics =Comic::orderBy('comic_name', 'asc')->paginate(12);
    $reviews = \App\Review::orderBy('review_title', 'asc')->paginate(12);
    return view('adminPanel')
        ->with(compact('user'))
        ->with(compact('users'))
        ->with(compact('comics'))
        ->with(compact('reviews'));
})->name('AdminAccount');
</code>```

In the end what i want to do is to paginate each tab differently meaning if a put the next on the comics i don't want to show also in the user tab the second page of user. The problem is that it use the same pagination url for each tabs so i was wondering if the solution is to give each tab an indipendent url

答:
Solution look like this.

Navigation code:

```<code><div class="myaccount-tab-menu nav" role="tablist" id="myTab">
  <a href="#dashboad" class="{{ (Route::currentRouteName() == 'dashboard') ? 'active' : '' }}" data-toggle="tab"><i class="fa fa-dashboard"></i>Dashboard</a>
  <a href="#users" class="{{ (Route::currentRouteName() == 'users') ? 'active' : '' }}" data-toggle="tab"><i class="fa fa-user"></i>Gestione Utenti</a>
  <a href="#comics" class="{{ (Route::currentRouteName() == 'comics') ? 'active' : '' }}" data-toggle="tab"><i class="fa fa-book"></i>Gestione Fumetti</a>
  <a href="#reviews" class="{{ (Route::currentRouteName() == 'reviews') ? 'active' : '' }}" data-toggle="tab"><i class="fa fa-map-marker"></i>Gestione Recensione</a>
</div>
</code>```

Also for each tab add, don't forget to change route name for each:

```<code><!-- Single Tab Content Start -->
<div class="tab-pane fade show {{ (Route::currentRouteName() == 'dashboard') ? 'active' : '' }}" id="dashboad" role="tabpanel">
</code>```

Route code:

```<code>Route::get('/dashboard', function () {
    $user = \Illuminate\Support\Facades\Auth::user();
    return view('adminPanel')->with(compact('user'));
})->name('dashboard');

Route::get('/users', function () {
    $users = \App\User::where('username','!=','admin')->orderBy('username', 'asc')->paginate(12);
    return view('adminPanel')->with(compact('users'));
})->name('users');

Route::get('/comics', function () {
    $comics =Comic::orderBy('comic_name', 'asc')->paginate(12);
    return view('adminPanel')->with(compact('comics'));
})->name('comics');

Route::get('/reviews', function () {
    $reviews = \App\Review::orderBy('review_title', 'asc')->paginate(12);
    return view('adminPanel')->with(compact('reviews'));
})->name('reviews');
</code>```

Body:
I want to paginate in a blade file different tabs , each tabs show different collections of object but each time i go to next page in one page it redirects to the first tab and also paginate each tab not just the one i wanted to paginate.

Blade Part Where i have tabs

                                    Dashboard
                                    Gestione Utenti
                                    Gestione Fumetti
                                    Gestione Recensione

Dashboard

Ciao, {{ $user->username }}! (Non sei {{ $user->username }}? Logout)

I tuoi dati:

E-mail:   {{ $user->email }}

                                            @php
                                                $notifications = \App\Http\Controllers\NotificationController::getNotification($user->id);
                                            @endphp

Notifiche

                                            @if($notifications->count() < 1)

Non ci sono ancora notifiche

                                            @else

                                                            Data
                                                            testo
                                                            stato
                                                            Action

                                                        @foreach($notifications as $notification)

                                                                {{ $notification->date }}

                                                                    @if(strlen($notification->notification_text) > 50 )
                                                                        @php
                                                                            $subnotification = substr($notification->notification_text, 0, 50)
                                                                        @endphp
                                                                        {{ $subnotification }}...
                                                                    @else
                                                                        {{ $notification->notification_text }}
                                                                    @endif

                                                                @if($notification->state == 1)

                                                                        Letto

                                                                        View

                                                                @else

                                                                        Non letto

                                                                         $notification->id]) }}" class="btn btn-sqr">View

                                                                @endif

                                                        @endforeach

                                            @endif

                                @if(session('message'))
                                    {{session('message')}}
                                @endif

Utenti

                                                        Nickname
                                                        Phone
                                                        Email
                                                        Tipologia
                                                        Elimina

                                                    @foreach($users as $user)

                                                        {{$user->username}}
                                                        {{$user->phone_number}}
                                                        {{$user->email}}
                                                        @if($user->hasGroup('il gruppo degli utenti'))
                                                        Utente
                                                        @else
                                                            Venditore
                                                        @endif
                                                        id)}}">

                                                    @endforeach
                                                    {{ $users->links() }}

Fumetti

                                                        Titolo
                                                        ISBN
                                                        Quantità
                                                        Utente
                                                        Elimina

                                                    @foreach($comics as $comic)
                                                        @php
                                                            $userNeed = App\User::where('id','=',$comic->user_id)->first();
                                                        @endphp

                                                            {{$comic->comic_name}}
                                                            {{$comic->ISBN}}
                                                            {{$comic->quantity}}
                                                            {{$userNeed->username}}
                                                            id)}}">

                                                    @endforeach
                                                    {{ $comics->links() }}

Recensione

                                                        Titolo
                                                        Fumetto
                                                        Recensore
                                                        Elimina

                                                    @foreach($reviews as $review)
                                                        @php
                                                            $userReview = App\User::where('id','=',$review->user_id)->first();
                                                            $comicReview = App\Comic::where('id','=',$review->comic_id)->first();
                                                        @endphp

                                                            {{$review->review_title}}
                                                            {{$comicReview->comic_name}}
                                                            {{$userReview->username}}
                                                            id)}}">

                                                    @endforeach
                                                    {{ $reviews->links() }}

And this is my route
Route

Route::get('/adminArea', function () {
    $user = \Illuminate\Support\Facades\Auth::user();
    $users = \App\User::where('username','!=','admin')->orderBy('username', 'asc')->paginate(12);
    $comics =Comic::orderBy('comic_name', 'asc')->paginate(12);
    $reviews = \App\Review::orderBy('review_title', 'asc')->paginate(12);
    return view('adminPanel')
        ->with(compact('user'))
        ->with(compact('users'))
        ->with(compact('comics'))
        ->with(compact('reviews'));
})->name('AdminAccount');

In the end what i want to do is to paginate each tab differently meaning if a put the next on the comics i don't want to show also in the user tab the second page of user. The problem is that it use the same pagination url for each tabs so i was wondering if the solution is to give each tab an indipendent url

Body:
Solution look like this.

Navigation code:

<div class="myaccount-tab-menu nav" role="tablist" id="myTab">
  <a href="#dashboad" class="{{ (Route::currentRouteName() == 'dashboard') ? 'active' : '' }}" data-toggle="tab"><i class="fa fa-dashboard"></i>Dashboard</a>
  <a href="#users" class="{{ (Route::currentRouteName() == 'users') ? 'active' : '' }}" data-toggle="tab"><i class="fa fa-user"></i>Gestione Utenti</a>
  <a href="#comics" class="{{ (Route::currentRouteName() == 'comics') ? 'active' : '' }}" data-toggle="tab"><i class="fa fa-book"></i>Gestione Fumetti</a>
  <a href="#reviews" class="{{ (Route::currentRouteName() == 'reviews') ? 'active' : '' }}" data-toggle="tab"><i class="fa fa-map-marker"></i>Gestione Recensione</a>
</div>

Also for each tab add, don't forget to change route name for each:

<!-- Single Tab Content Start -->
<div class="tab-pane fade show {{ (Route::currentRouteName() == 'dashboard') ? 'active' : '' }}" id="dashboad" role="tabpanel">

Route code:

Route::get('/dashboard', function () {
    $user = \Illuminate\Support\Facades\Auth::user();
    return view('adminPanel')->with(compact('user'));
})->name('dashboard');

Route::get('/users', function () {
    $users = \App\User::where('username','!=','admin')->orderBy('username', 'asc')->paginate(12);
    return view('adminPanel')->with(compact('users'));
})->name('users');

Route::get('/comics', function () {
    $comics =Comic::orderBy('comic_name', 'asc')->paginate(12);
    return view('adminPanel')->with(compact('comics'));
})->name('comics');

Route::get('/reviews', function () {
    $reviews = \App\Review::orderBy('review_title', 'asc')->paginate(12);
    return view('adminPanel')->with(compact('reviews'));
})->name('reviews');


来源: stackexchange

问:
Is there _JAVA_OPTIONS on Mac?
I was wondering if there was _JAVA_OPTIONS on macOS. If yes, how can I get to it like on Windows (windows key and pause/break)?</p>

答: _JAVA_OPTIONS, is an environment variable, theres is no screen on mac for setting it like on windows, you have to define it on your terminal (for that session) or in a file (for all future sessions) if you choose to set it on a file, that could be .bash_profile o .zshrc depending on which terminal you use, take a look at thisfor an example </p>

ContentLicense: CC BY-SA 4.0

Title: Is there _JAVA_OPTIONS on Mac?


问:
Add a blog to an existing webpage
How can I insert a blog (not created yet) into an already existing 'static' webpage? The webpage is written mostly in PHP. I'm considering using something like WordPress.org (host install version) and using it to update the website's news page.

From what I've read, its sounds like I would need to do a lot of theme tweaking to get WordPress to display correctly with our website's template. This sounds a bit daunting to me.

答:
A simple solution is to simply add an iframe and place the blog site in it. It takes almost no code and the blog entries will show up.

As for a code option, I would look at an RSS Reader, like this one:
http://www.scriptol.com/rss/rss-reader.php

A bit of code, but you read the blog entries via RSS and display what you desire.

OwnerDisplayName: djbender

Title: Add a blog to an existing webpage

LastEditorDisplayName: tinkertim

OwnerDisplayName: Gregory A Beamer

ContentLicense: CC BY-SA 2.5


问:
Can I generate .MD files from XML Documentation?
I have used Sandcastle to document my class libraries recently.  However, I have recently discovered that Sandcastle is no longer developed by Microsoft: https://archive.codeplex.com/?p=sandcastle.

I have had a look online on GitHub and I see that lots of open source projects use .MD (MarkDown) files these days.  I see that .MD files are supported by GitHub and TFS.  How can I generate .MD files from XML Documentation files?

I have spent the last few hours Googling this.  For example, I have found this with only a few hundred downloads: https://github.com/lijunle/Vsxmd/tree/master/Vsxmd  I am not asking for tool recommendations.  I am asking if it is possible to convert .XML Documentation to .MD files.

答:
In my scenario, I wanted code documentation for my project in the GitHub Wiki, and it takes markdown files not html.

Visual Studio (Mac, in my case) has a project options > build > compiler checkbox to generate the xml documentation file for the project.  Vsxmd generates one md file from this one xml file.  It is very well and extensively laid out when looking at it in most markdown previewers, but GitHub seems to have low timeouts and cannot render a large markdown page.

It is not laid out as well, but something I found that GitHub can render is the single md file generated by the web tool, vsdoc-2-md.

What I ended up using for my project is Default Documentation.  It is a nuget that runs during buildtime just like Vsxmd, but generates multiple md files that are small enough for GitHub to not complain.

Just note that GitHub Wiki renames files in its urls so that all .md extensions get stripped.  I had to do a search/replace to strip .md from all the links in order to get clicking around documentation from the GitHub Wiki to work.

ContentLicense: CC BY-SA 3.0


问:
Adding context sensitive help to my Excel workbook
I have developed a fairly complex Excel workbook.  Now I want to document it.  I discovered MS compiled HTML file.  So I wrote a document in Word that contains detailed information about each sheet in my workbook.  I saved it and use the MS HTML Help Workshop and the chmProcessor that I downloaded from the web.  Eventually I got it to work and created the .CHM file.  In my workbook I wrote a sub that looks like this:

```<code>Sub getHelp()
    Dim currentPath As String
    currentPath = ActiveWorkbook.Path
    Application.Help (currentPath & "\LogicAndAccuracyTesting.chm")
End Sub
</code>```

It all works.  From my workbook, I set {f1} to call getHelp and it does display my documentation.

Help also support the HelpContextID property.  I want to use it to display the exact topic that the user has asked for help.

How do I get the HelpContextID from my Word document?  If I save the .docx file as a .htm file, how can I get the HelpContextID?  How do I use 2 components of office (Word and Excel) to create a tightly integrated help system?  I'm not a professional developer at this point so I don't want to spend a lot of money on a professional help authoring system.

Thank you for your help.

答:
HelpContextID has a learn curve when using CHM files. ChmProcessor makes it a bit difficult too. ChmProcessor is not well suited for using contextID's. But give it a try (the man's way).

First use the Generate help project option

Copy the file names generated into the foobar.hhp file (open by e.g Notepad++) to a file named alias.h

Edit the lines into the format described at: ALIAS and MAP files

Create a map.h file as described (see link above).

Save the file as alias.h and map.h in same folder as your help project file *.hhp

Add following section to your e.g foobar.hhp file:

```<code>[ALIAS]
#include alias.h

[MAP]
#include map.h
</code>```

Save the files you created in another place too!

Compile your help project by using HTMLHelp Workshop or other freeware tools like FAR HTML.

As for test case only I add a CHM help file call below. Please note, you'll get one help viewer window showing the default topic by this code (edit the code for your needs). After a click to the help button (in German "Hilfe") the topic related to HelpContextID:=20010 is shown in another window.

```<code>Function TestMacro()
'----------------------------------------------------------------
' Display a message box with a help button linked to a help topic
'----------------------------------------------------------------
    Dim currentPath As String
    currentPath = ActiveWorkbook.Path
    Application.Help HelpFile:=currentPath & "\CHM-example.chm", HelpContextID:=0

    '--- MsgBox sample code -------------------------------------
    MsgBox "The 'Hello World' message for testing this function!.", _
    Buttons:=vbOKOnly + vbMsgBoxHelpButton, _
    HelpFile:=ActiveWorkbook.Path & "\CHM-example.chm", _
    Context:=20010
End Function
</code>```

Body:
I have developed a fairly complex Excel workbook.  Now I want to document it.  I discovered MS compiled HTML file.  So I wrote a document in Word that contains detailed information about each sheet in my workbook.  I saved it and use the MS HTML Help Workshop and the chmProcessor that I downloaded from the web.  Eventually I got it to work and created the .CHM file.  In my workbook I wrote a sub that looks like this:

Sub getHelp()
    Dim currentPath As String
    currentPath = ActiveWorkbook.Path
    Application.Help (currentPath & "\LogicAndAccuracyTesting.chm")
End Sub

It all works.  From my workbook, I set {f1} to call getHelp and it does display my documentation.

Help also support the HelpContextID property.  I want to use it to display the exact topic that the user has asked for help.

How do I get the HelpContextID from my Word document?  If I save the .docx file as a .htm file, how can I get the HelpContextID?  How do I use 2 components of office (Word and Excel) to create a tightly integrated help system?  I'm not a professional developer at this point so I don't want to spend a lot of money on a professional help authoring system.

Thank you for your help.

Body:
HelpContextID has a learn curve when using CHM files. ChmProcessor makes it a bit difficult too. ChmProcessor is not well suited for using contextID's. But give it a try (the man's way).

First use the Generate help project option

Copy the file names generated into the foobar.hhp file (open by e.g Notepad++) to a file named alias.h

Edit the lines into the format described at: ALIAS and MAP files

Create a map.h file as described (see link above).

Save the file as alias.h and map.h in same folder as your help project file *.hhp

Add following section to your e.g foobar.hhp file:

[ALIAS]
#include alias.h

[MAP]
#include map.h

Save the files you created in another place too!

Compile your help project by using HTMLHelp Workshop or other freeware tools like FAR HTML.

As for test case only I add a CHM help file call below. Please note, you'll get one help viewer window showing the default topic by this code (edit the code for your needs). After a click to the help button (in German "Hilfe") the topic related to HelpContextID:=20010 is shown in another window.

Function TestMacro()
'----------------------------------------------------------------
' Display a message box with a help button linked to a help topic
'----------------------------------------------------------------
    Dim currentPath As String
    currentPath = ActiveWorkbook.Path
    Application.Help HelpFile:=currentPath & "\CHM-example.chm", HelpContextID:=0

    '--- MsgBox sample code -------------------------------------
    MsgBox "The 'Hello World' message for testing this function!.", _
    Buttons:=vbOKOnly + vbMsgBoxHelpButton, _
    HelpFile:=ActiveWorkbook.Path & "\CHM-example.chm", _
    Context:=20010
End Function


问:
RabbitMQ conf file location
Where do I put my rabbitmq.conf file and how do I make it known to the rabbitmq-server?

All documentation and what I can find only clarifies that this file is not there initially, and the example config file is referenced. Official doc says that I can override the RABBITMQ_CONFIG_FILE env variable. It is unset on my system, but how would I set it so that it is known to rabbitmq-server?

答:
By default, the location is at /etc/rabbitmq, according to https://medium.com/@lukaszlenart/how-to-configure-rabbitmq-properly-fa39b2d4cda2.

How to properly set the env variable depends on your operating system, but you could just do it in a startup shell script.

Title: RabbitMQ conf file location


问:
My Script that sorts Videos by their tags isn't functioning at all
I have a script that basically says when you type a valid video tag it prints out "Found Tag" to the console. This is useful for organization / sorting purposes. The bad thing is, the code dosen't work. How come, and what can I do to improve the script?

window.onload = () => {
  const vids = [
    {
      tags : ['technology','programming','life','2020'],
      url : "videos/tech.mp4",
      name : "7 Amazing Technology",
    }
  ]
  const search = document.getElementById("Search")
  const btnSearch = document.getElementById("btnSearch")

  btnSearch.addEventListener('click', () => {
    let videoTag = search.value;
    for (let x = 0; x < vids.length; x++)
    {
      for (let y of vids.tags)
      {
        if (vids[x].tags == videoTag)
        {
          console.log("Found Tag!")
        }
      }
    }
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <script src="script.js"></script>
    <input id = "Search" type = "text" placeholder = "Search videos">
    <input id = "btnSearch" type = 'button' value = "Search">
    <script src = "script.js"></script>
  </body>
</html></code>```

TL;DR: For now I only have one added video, but in the future I plan on adding more, so please have a solution that would loop through all elements of the objects, and find the video tags'

Thanks!

答:
It looks like your indexing is slightly off in your nested looping:

  btnSearch.addEventListener('click', () => {
    let videoTag = search.value;
    for (let x = 0; x < vids.length; x++)
    {
      for (let y = 0; y < vids[x].tags.length; y++)
      {
        if (vids[x].tags[y] == videoTag)
        {
          console.log("Found Tag!")
        }
      }
    }
  });
```

Body:
I have a script that basically says when you type a valid video tag it prints out "Found Tag" to the console. This is useful for organization / sorting purposes. The bad thing is, the code dosen't work. How come, and what can I do to improve the script?

window.onload = () => {
  const vids = [
    {
      tags : ['technology','programming','life','2020'],
      url : "videos/tech.mp4",
      name : "7 Amazing Technology",
    }
  ]
  const search = document.getElementById("Search")
  const btnSearch = document.getElementById("btnSearch")

  btnSearch.addEventListener('click', () => {
    let videoTag = search.value;
    for (let x = 0; x < vids.length; x++)
    {
      for (let y of vids.tags)
      {
        if (vids[x].tags == videoTag)
        {
          console.log("Found Tag!")
        }
      }
    }
  });
}

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="style.css" rel="stylesheet" type="text/css" />

    <input id = "Search" type = "text" placeholder = "Search videos">
    <input id = "btnSearch" type = 'button' value = "Search">

TL;DR: For now I only have one added video, but in the future I plan on adding more, so please have a solution that would loop through all elements of the objects, and find the video tags'

Thanks!


问:
Cypress Sum of two array

hi all, i want to sum of two columns values in a cypress .

i declared  two array variable : quantity and price , and push all columns elements as well.
 if i log the quantity cy.log(quantity) it shows all values in array. but cy.log(quantity[1]) is not working. same in price array.

i don't know why it's not behave like a array.

if i declare , a=[1,2,3,4,5,6] and then cy.log(a[1]) , it's working

i have to sum both of the arrays. tried many approaches.

```<code>var quantity =[]
var price =[]

cy.get('td:nth-child(10) > div > span:visible').each(($el, index, $list) =>
        {
            quantity.push(Number($el.text())).toFixed(4)

        })

        cy.get('td:nth-child(14) > div > span:visible').each(($el, index, $list) =>
        {
            price.push(Number($el.text())).toFixed(4)
        })

     cy.log(quantity) // working
     cy.log(price) // working

     cy.log(quantity[1]) //not working
     cy.log(price[3])  //not working

     // this part is working:
        var a=[1,2,3,4,5,6]
        cy.log(a[3])
</code>```

Title: Cypress Sum of two array

Body:
hi all, i want to sum of two columns values in a cypress .

i declared  two array variable : quantity and price , and push all columns elements as well.
 if i log the quantity cy.log(quantity) it shows all values in array. but cy.log(quantity[1]) is not working. same in price array.

i don't know why it's not behave like a array.

if i declare , a=[1,2,3,4,5,6] and then cy.log(a[1]) , it's working

i have to sum both of the arrays. tried many approaches.

var quantity =[]
var price =[]

cy.get('td:nth-child(10) > div > span:visible').each(($el, index, $list) =>
        {
            quantity.push(Number($el.text())).toFixed(4)

        })

        cy.get('td:nth-child(14) > div > span:visible').each(($el, index, $list) =>
        {
            price.push(Number($el.text())).toFixed(4)
        })

     cy.log(quantity) // working
     cy.log(price) // working

     cy.log(quantity[1]) //not working
     cy.log(price[3])  //not working

     // this part is working:
        var a=[1,2,3,4,5,6]
        cy.log(a[3])

Body:
Thank you so much. i used to sum of two arrays using below. its working.

model=[]
  lower=[]
    var squares = model.map((a, i) => a.toFixed(4) - lower[i].toFixed(4));

but my result is like:

[0.01, 0.019999999999999997, 0.060000000000000005, 0.04, 0.09000000000000001, 0.019999999999999997, 0.08, 0.35, 0.12000000000000001, 0.07, 0.03].

how to fixed with two decimal points


问:
C# Datacontext in class library
I thought it would be nice to move my database classes out of a NET.Core project into a class library.

I had a class called ApiRegistrationDataContext, inheriting from DbContext and a class ApiRegistrationSqliteDataContext, inheriting from ApiRegistrationDataContext.

In the ASP.Core-project I had some lines regarding the database classes in file Startup.cs and in a service. I would create a migration via Add-Migration SomeName -Context ApiRegistrationSqliteDataContext -OutputDir Migrations\ApiRegistrationSqliteMigrations.

Now I moved those classes into a class library and removed all connections from the ASP.Core project. However now I cannot create a new Migration (I was able to move the old migration from the ASP.Core project to the class library).

The error message reads

```<code>Unable to create an object of type 'ContactDataContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
</code>```

which is honestly no help at all.
Why did it work in the ASP.Core project but not in my class library anymore?

答:
As docs state:

Some of the EF Core Tools commands (for example, the Migrations commands) require a derived DbContext instance to be created at design time in order to gather details about the application's entity types and how they map to a database schema.

So after your changes EF can't do it. One of the options would be to create IDesignTimeDbContextFactory inside of the corresponding project:

```<code>public class ApiRegistrationSqliteDataContextContextFactory : IDesignTimeDbContextFactory<ApiRegistrationSqliteDataContext>
{
    public ApiRegistrationSqliteDataContext CreateDbContext(string[] args)
    {
       var optionsBuilder = new DbContextOptionsBuilder<ApiRegistrationSqliteDataContext>();
            optionsBuilder.UseSqlite("Data Source=blog.db");

       return new ApiRegistrationSqliteDataContext(optionsBuilder.Options);
    }
}
</code>```

Also if you are using VS package manager console to work with migrations make sure that you have set correct startup project (in solution explorer) and default project (in package manager console).

Also try to run Add-Migration specifying Verbose flag:

```<code>Add-Migration SomeName -Context ApiRegistrationSqliteDataContext -OutputDir Migrations\ApiRegistrationSqliteMigrations -Verbose
</code>```

Title: C# Datacontext in class library

Body:
I thought it would be nice to move my database classes out of a NET.Core project into a class library.

I had a class called ApiRegistrationDataContext, inheriting from DbContext and a class ApiRegistrationSqliteDataContext, inheriting from ApiRegistrationDataContext.

In the ASP.Core-project I had some lines regarding the database classes in file Startup.cs and in a service. I would create a migration via Add-Migration SomeName -Context ApiRegistrationSqliteDataContext -OutputDir Migrations\ApiRegistrationSqliteMigrations.

Now I moved those classes into a class library and removed all connections from the ASP.Core project. However now I cannot create a new Migration (I was able to move the old migration from the ASP.Core project to the class library).

The error message reads

Unable to create an object of type 'ContactDataContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

which is honestly no help at all.
Why did it work in the ASP.Core project but not in my class library anymore?

Body:
As docs state:

Some of the EF Core Tools commands (for example, the Migrations commands) require a derived DbContext instance to be created at design time in order to gather details about the application's entity types and how they map to a database schema.

So after your changes EF can't do it. One of the options would be to create IDesignTimeDbContextFactory inside of the corresponding project:

public class ApiRegistrationSqliteDataContextContextFactory : IDesignTimeDbContextFactory<ApiRegistrationSqliteDataContext>
{
    public ApiRegistrationSqliteDataContext CreateDbContext(string[] args)
    {
       var optionsBuilder = new DbContextOptionsBuilder<ApiRegistrationSqliteDataContext>();
            optionsBuilder.UseSqlite("Data Source=blog.db");

       return new ApiRegistrationSqliteDataContext(optionsBuilder.Options);
    }
}

Also if you are using VS package manager console to work with migrations make sure that you have set correct startup project (in solution explorer) and default project (in package manager console).

Also try to run Add-Migration specifying Verbose flag:

Add-Migration SomeName -Context ApiRegistrationSqliteDataContext -OutputDir Migrations\ApiRegistrationSqliteMigrations -Verbose


问:
flask wtforms triggering a python function with post
I don't want to use javascript as its probably just a one-off usecase. Here's my code and the problem statement follows.

```<code># Form class
class ManageContainers(FlaskForm):
    stop_container = SubmitField('stop')

# HTML Render
{% for i in containers %}
        <tbody>
            <tr>
                <th scope="row">{{ i.short_id }}</th>
                <td>{{ i.name }}</td>
                <td>{{ i.image.tags }}</td>
                <td>{{ i.ports }}</td>
                <td>
                    <form action="#" method="post">
                    {{ form.stop_container() }}
                    </form>
                </td>
            </tr>
        </tbody>
{% endfor %}

# Actual app route
@app.route('/list-containers', methods=['POST','GET'])
def index():
    containers_list = client.containers.list(all=False)
    form = ManageContainers()
    if form.is_submitted():
        print("stop the container")
        delete_container(HOW_TO_GET_THIS?)
        return redirect(url_for('index'))
    return render_template('index.html', containers=containers_list, form=form)

def delete_container(container_id):
    container = client.containers.get(container_id)
    container.stop()
    container.remove()
</code>```

I am using docker sdk for python and basically trying to stop / start containers. I am stuck where I want to use that button that says "stop" which will delete the container.

Important - It is actually calling a function like this because I can see "stop the container" in my console. But I don't know how to pass the ID (i.id) of the container while the function is getting called.

Here's a screenshot of what the page actually looks like to save you sometime.
SCREENSHOT

答:
Since you are not taking any user input for any fields, I don't think, it's related to WTForms.

You can try the below steps:

Create a route for stopping the container:

@app.route('/stop-container/<id>', methods=['POST'])
def stop_container(id):
    delete_container(id)
    return redirect(url_for('index'))
```

<ol start="2">
<li>Change your form to:</li>
</ol>

<pre class="lang-html prettyprint-override"><code><form action={{ url_for('stop_container', id=i.short_id) }} method='post'>
    {{ form.stop_container() }}
</form>
</code>```

Body:
I don't want to use javascript as its probably just a one-off usecase. Here's my code and the problem statement follows.

# Form class
class ManageContainers(FlaskForm):
    stop_container = SubmitField('stop')

# HTML Render
{% for i in containers %}

                {{ i.short_id }}
                {{ i.name }}
                {{ i.image.tags }}
                {{ i.ports }}

                    <form action="#" method="post">
                    {{ form.stop_container() }}
                    </form>

{% endfor %}

# Actual app route
@app.route('/list-containers', methods=['POST','GET'])
def index():
    containers_list = client.containers.list(all=False)
    form = ManageContainers()
    if form.is_submitted():
        print("stop the container")
        delete_container(HOW_TO_GET_THIS?)
        return redirect(url_for('index'))
    return render_template('index.html', containers=containers_list, form=form)

def delete_container(container_id):
    container = client.containers.get(container_id)
    container.stop()
    container.remove()

I am using docker sdk for python and basically trying to stop / start containers. I am stuck where I want to use that button that says "stop" which will delete the container.

Important - It is actually calling a function like this because I can see "stop the container" in my console. But I don't know how to pass the ID (i.id) of the container while the function is getting called.

Here's a screenshot of what the page actually looks like to save you sometime.
SCREENSHOT

Body:
Since you are not taking any user input for any fields, I don't think, it's related to WTForms.

You can try the below steps:

Create a route for stopping the container:

@app.route('/stop-container/<id>', methods=['POST'])
def stop_container(id):
    delete_container(id)
    return redirect(url_for('index'))

Change your form to:

<form action={{ url_for('stop_container', id=i.short_id) }} method='post'>
    {{ form.stop_container() }}
</form>


问:
SQLite & INNER JOIN Query
Hi everyone I have this query where there are 3 tables in join. In Access it works, but in SQLite it gives me an error, how can I "adapt" the SQL command? thanks</p>

```<code>UPDATE (
    CategoriaTB
    INNER JOIN MagazzinoTB ON CategoriaTB.IDCategoria =
MagazzinoTB.IDCategoria
) INNER JOIN PersoneTB ON MagazzinoTB.IDPersone =
PersoneTB.IDPersone
SET MagazzinoTB.DataReso = "aaa"
WHERE ((
    (PersoneTB.CodicePer)="F")
    AND ((MagazzinoTB.Stato)=0)
    AND ((MagazzinoTB.DataVendita) Is Null)
)
</code>```

答:
SQLite does not support joins in the UPDATE statement, but you can do it with EXISTS:

```<code>UPDATE MagazzinoTB
SET DataReso = 'aaa'
WHERE Stato = 0 AND DataVendita IS NULL
  AND EXISTS (SELECT 1 FROM CategoriaTB c WHERE c.IDCategoria = MagazzinoTB.IDCategoria)
  AND EXISTS (SELECT 1 FROM PersoneTB p WHERE p.IDPersone = MagazzinoTB.IDPersone AND p.CodicePer = 'F')
</code>```

Title: SQLite & INNER JOIN Query

Body:
Hi everyone I have this query where there are 3 tables in join. In Access it works, but in SQLite it gives me an error, how can I "adapt" the SQL command? thanks

UPDATE (
    CategoriaTB
    INNER JOIN MagazzinoTB ON CategoriaTB.IDCategoria =
MagazzinoTB.IDCategoria
) INNER JOIN PersoneTB ON MagazzinoTB.IDPersone =
PersoneTB.IDPersone
SET MagazzinoTB.DataReso = "aaa"
WHERE ((
    (PersoneTB.CodicePer)="F")
    AND ((MagazzinoTB.Stato)=0)
    AND ((MagazzinoTB.DataVendita) Is Null)
)

Body:
SQLite does not support joins in the UPDATE statement, but you can do it with EXISTS:

UPDATE MagazzinoTB
SET DataReso = 'aaa'
WHERE Stato = 0 AND DataVendita IS NULL
  AND EXISTS (SELECT 1 FROM CategoriaTB c WHERE c.IDCategoria = MagazzinoTB.IDCategoria)
  AND EXISTS (SELECT 1 FROM PersoneTB p WHERE p.IDPersone = MagazzinoTB.IDPersone AND p.CodicePer = 'F')


问:
Removing non Printable values aftert Encoding.ASCII.GetString()
Suppose I have a Byte array and I use Encoding.ASCII.GetString() to convert the bytes into a string. Now the first few bytes will contain actual values, but the remaining ones will all have value of 0. After obtaining the string, when I show it on a WPF Form, there are some non printable characters. How can I remove these non printable characters. One way would be to loop through the array and only consider up to an index not containing 0, but I may also Encode using Unicode, that is Encoding.Unicode.GetString().

What would be the most generic way to solve the problem.

答:
```<code>var buffer = new byte[] { 65, 66, 67, 68, 0, 0, 0, 0, 0 };
var length = buffer.TakeWhile(b => b != 0).Count();
var text = Encoding.UTF8.GetString(buffer, 0, length);
</code>```


问:
How to write a function with a for loop to check tic tac toe wins
I want to write a function with a for loop that checks for wining combination for a tic tac toe game based on a given list (board) and a marker ('X','O').

I was able to achieve this for the row wins with this for loop statement

```<code>def win_check(board, mark):
    # Win tic tac toe?

    board = board[1:]

    # ALL ROWS, and check to see if they all share the same marker?
    # i used `for loop` to achieve the row wins check.
    # But if there is another way to achieve it with this `r_win = [[9,8,7],[6,5,4],[3,2,1]]`

    # This works fine for the row checks
    for i in reversed(range(3)):
        if board[i*3] in mark and board[i*3+1] in mark and board[i*3+2] in mark:
            return True
    else:
        return False

    # ALL COLUMNS, check to see if marker matches

    c_win = [[7,4,1],[8,5,2],[9,6,3]] # i created this list if it can be used to make check for column wins.

    for i in c_win:
        # if statement goes here to check columns wins
            return True # and return true if there is a match
    else:
        return False

    # 2 diagonals, check to see match
    d_win = [[9,5,1],[7,5,3]] # i created this list if it can be used to make check for diagonal wins.

    for i in d_win:
        # if statement goes here to check diagonal wins
            return True # and return true if there is a match
    else:
        return False

</code>```

example function call

test_board = ['#','X','O','X','X','X','X','O','X','X']

win_check(test_board,'X')

答:
To make it more pythonish:

def win_check(board, mark):
    board_=[el==mark for el in board]
    if(any([
        all(board_[1:4]),
        all(board_[4:7]),
        all(board_[7:10]),
        all(board_[slice(1,8,3)]),
        all(board_[slice(2,9,3)]),
        all(board_[slice(3,10,3)]),
        all(board_[slice(1,10,4)]),
        all(board_[slice(3,8,2)])
    ])):
        return True
    return False
```

<p>Outputs:</p>

<pre class="lang-py prettyprint-override"><code>>>> test_board = ['#','X','O','X','X','X','X','O','X','X']
>>> print(win_check(test_board,'X'))

True
</code>```

Body:
I want to write a function with a for loop that checks for wining combination for a tic tac toe game based on a given list (board) and a marker ('X','O').

I was able to achieve this for the row wins with this for loop statement

def win_check(board, mark):
    # Win tic tac toe?

    board = board[1:]

    # ALL ROWS, and check to see if they all share the same marker?
    # i used `for loop` to achieve the row wins check.
    # But if there is another way to achieve it with this `r_win = [[9,8,7],[6,5,4],[3,2,1]]`

    # This works fine for the row checks
    for i in reversed(range(3)):
        if board[i*3] in mark and board[i*3+1] in mark and board[i*3+2] in mark:
            return True
    else:
        return False

    # ALL COLUMNS, check to see if marker matches

    c_win = [[7,4,1],[8,5,2],[9,6,3]] # i created this list if it can be used to make check for column wins.

    for i in c_win:
        # if statement goes here to check columns wins
            return True # and return true if there is a match
    else:
        return False

    # 2 diagonals, check to see match
    d_win = [[9,5,1],[7,5,3]] # i created this list if it can be used to make check for diagonal wins.

    for i in d_win:
        # if statement goes here to check diagonal wins
            return True # and return true if there is a match
    else:
        return False

example function call

test_board = ['#','X','O','X','X','X','X','O','X','X']

win_check(test_board,'X')

Body:
To make it more pythonish:

def win_check(board, mark):
    board_=[el==mark for el in board]
    if(any([
        all(board_[1:4]),
        all(board_[4:7]),
        all(board_[7:10]),
        all(board_[slice(1,8,3)]),
        all(board_[slice(2,9,3)]),
        all(board_[slice(3,10,3)]),
        all(board_[slice(1,10,4)]),
        all(board_[slice(3,8,2)])
    ])):
        return True
    return False

Outputs:

>>> test_board = ['#','X','O','X','X','X','X','O','X','X']
>>> print(win_check(test_board,'X'))

True


问:
What's time complexity of this algorithm for finding all Path Sum?

Path Sum
 Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

  For example: sum = 11.

```<code>    5
   / \
  4   8
 /   / \
2  -2   1
</code>```

The answer is :

```<code>[
  [5, 4, 2],
  [5, 8, -2]
]
</code>```

Personally I think, the time complexity = O(2^n), n is the number of
  nodes of the given binary tree.

  Thank you Vikram Bhat and David Grayson, the tight time
  complexity = O(nlogn), n is the number of nodes in the given binary
  tree.

Algorithm checks each node once, which causes O(n)

"vector one_result(subList);" will copy entire path from subList to one_result, each time, which causes O(logn), because the
  height is O(logn).

So finally, the time complexity = O(n * logn) =O(nlogn).

  The idea of this solution is DFS[C++].

```<code>/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
#include <vector>
using namespace std;

class Solution {
public:
    vector<vector<int> > pathSum(TreeNode *root, int sum) {
        vector<vector<int>> list;

        // Input validation.
        if (root == NULL) return list;

        vector<int> subList;
        int tmp_sum = 0;

        helper(root, sum, tmp_sum, list, subList);

        return list;
    }

    void helper(TreeNode *root, int sum, int tmp_sum,
                vector<vector<int>> &list, vector<int> &subList) {

        // Base case.
        if (root == NULL) return;
        if (root->left == NULL && root->right == NULL) {
            // Have a try.
            tmp_sum += root->val;
            subList.push_back(root->val);

            if (tmp_sum == sum) {
                vector<int> one_result(subList);
                list.push_back(one_result);
            }

            // Roll back.
            tmp_sum -= root->val;
            subList.pop_back();

            return;
        }

        // Have a try.
        tmp_sum += root->val;
        subList.push_back(root->val);

        // Do recursion.
        helper(root->left, sum, tmp_sum, list, subList);
        helper(root->right, sum, tmp_sum, list, subList);

        // Roll back.
        tmp_sum -= root->val;
        subList.pop_back();
    }
};
</code>```

答:
```<code>TIME COMPLEXITY
</code>```

The time complexity of the algorithm is O(N^2), where ‘N’ is the total number of nodes in the tree. This is due to the fact that we traverse each node once (which will take O(N)), and for every leaf node we might have to store its path which will take O(N).

We can calculate a tighter time complexity of O(NlogN) from the space complexity discussion below.

```<code>SPACE COMPLEXITY
</code>```

If we ignore the space required for all paths list, the space complexity of the above algorithm will be O(N) in the worst case. This space will be used to store the recursion stack. The worst-case will happen when the given tree is a linked list (i.e., every node has only one child).

How can we estimate the space used for the all paths list? Take the example of the following balanced tree:

```<code>          1
      /      \
     2        3
   /   \    /   \
  4     5  6     7
</code>```

Here we have seven nodes (i.e., N = 7). Since, for binary trees, there exists only one path to reach any leaf node, we can easily say that total root-to-leaf paths in a binary tree can’t be more than the number of leaves. As we know that there can’t be more than N/2 leaves in a binary tree, therefore the maximum number of elements in all paths list will be O(N/2) = O(N). Now, each of these paths can have many nodes in them. For a balanced binary tree (like above), each leaf node will be at maximum depth. As we know that the depth (or height) of a balanced binary tree is O(logN) we can say that, at the most, each path can have logN nodes in it. This means that the total size of the all paths list will be O(N*logN). If the tree is not balanced, we will still have the same worst-case space complexity.

From the above discussion, we can conclude that the overall space complexity of our algorithm is O(N*logN).

Also from the above discussion, since for each leaf node, in the worst case, we have to copy log(N) nodes to store its path, therefore the time complexity of our algorithm will also be O(N*logN).

Body:
Path Sum
 Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

  For example: sum = 11.

    5
   / \
  4   8
 /   / \
2  -2   1

The answer is :

[
  [5, 4, 2],
  [5, 8, -2]
]

Personally I think, the time complexity = O(2^n), n is the number of
  nodes of the given binary tree.

  Thank you Vikram Bhat and David Grayson, the tight time
  complexity = O(nlogn), n is the number of nodes in the given binary
  tree.

Algorithm checks each node once, which causes O(n)

"vector one_result(subList);" will copy entire path from subList to one_result, each time, which causes O(logn), because the
  height is O(logn).

So finally, the time complexity = O(n * logn) =O(nlogn).

  The idea of this solution is DFS[C++].

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
#include <vector>
using namespace std;

class Solution {
public:
    vector<vector<int> > pathSum(TreeNode *root, int sum) {
        vector<vector<int>> list;

        // Input validation.
        if (root == NULL) return list;

        vector<int> subList;
        int tmp_sum = 0;

        helper(root, sum, tmp_sum, list, subList);

        return list;
    }

    void helper(TreeNode *root, int sum, int tmp_sum,
                vector<vector<int>> &list, vector<int> &subList) {

        // Base case.
        if (root == NULL) return;
        if (root->left == NULL && root->right == NULL) {
            // Have a try.
            tmp_sum += root->val;
            subList.push_back(root->val);

            if (tmp_sum == sum) {
                vector<int> one_result(subList);
                list.push_back(one_result);
            }

            // Roll back.
            tmp_sum -= root->val;
            subList.pop_back();

            return;
        }

        // Have a try.
        tmp_sum += root->val;
        subList.push_back(root->val);

        // Do recursion.
        helper(root->left, sum, tmp_sum, list, subList);
        helper(root->right, sum, tmp_sum, list, subList);

        // Roll back.
        tmp_sum -= root->val;
        subList.pop_back();
    }
};

Body:
TIME COMPLEXITY

The time complexity of the algorithm is O(N^2), where ‘N’ is the total number of nodes in the tree. This is due to the fact that we traverse each node once (which will take O(N)), and for every leaf node we might have to store its path which will take O(N).

We can calculate a tighter time complexity of O(NlogN) from the space complexity discussion below.

SPACE COMPLEXITY

If we ignore the space required for all paths list, the space complexity of the above algorithm will be O(N) in the worst case. This space will be used to store the recursion stack. The worst-case will happen when the given tree is a linked list (i.e., every node has only one child).

How can we estimate the space used for the all paths list? Take the example of the following balanced tree:

          1
      /      \
     2        3
   /   \    /   \
  4     5  6     7

Here we have seven nodes (i.e., N = 7). Since, for binary trees, there exists only one path to reach any leaf node, we can easily say that total root-to-leaf paths in a binary tree can’t be more than the number of leaves. As we know that there can’t be more than N/2 leaves in a binary tree, therefore the maximum number of elements in all paths list will be O(N/2) = O(N). Now, each of these paths can have many nodes in them. For a balanced binary tree (like above), each leaf node will be at maximum depth. As we know that the depth (or height) of a balanced binary tree is O(logN) we can say that, at the most, each path can have logN nodes in it. This means that the total size of the all paths list will be O(N*logN). If the tree is not balanced, we will still have the same worst-case space complexity.

From the above discussion, we can conclude that the overall space complexity of our algorithm is O(N*logN).

Also from the above discussion, since for each leaf node, in the worst case, we have to copy log(N) nodes to store its path, therefore the time complexity of our algorithm will also be O(N*logN).


问:
How to get data from firebase query based on value from another firebase query in FutureBuilder in Flutter?
I am new to flutter and I am sure there is a simple way of doing this. Let me first give you a background. I have 2 tables(collections). The first one store a mapping. Therefore it returns a key based on an id which will be used to query the second table and retrieve the data from firebase.

I have written 2 data models and 2 functions which return Future<> data. They are as follows-

```<code>Future<SpecificDevice> getSpecificDevice(String deviceId) {
    Future<SpecificDevice> obj =_database.reference().child("deviceMapping").orderByChild("deviceId").equalTo(deviceId).once().then((snapshot) {
      SpecificDevice specificDevice = new SpecificDevice(deviceId, "XXXX", new List<String> ());
      if(snapshot.value.isNotEmpty){
        print(snapshot.value);
        snapshot.value.forEach((key,values) {
          if(values["deviceId"] == deviceId) {
            specificDevice.deviceKey = values["deviceDesc"];
            specificDevice.vendorList = List.from(values["vendorList"]);
          }
        });
      }
      return specificDevice;
    });
    return obj;
  }
</code>```

This function gets the mapping deviceId -> deviceKey.
This is the key of record stored in another table. Following is the function for it.

```<code>Future<Device> getDeviceDescription(String deviceKey) {
    Future<Device> device = _database.reference().child("deviceDescription").once().then((snapshot) {
      Device deviceObj = new Device("YYYY", "YYYY", "YYY", "YYYY", "YYYY");
      if(snapshot.value.isNotEmpty){
        print(snapshot.value);
        //Future<SpecificDevice> obj = getSpecificDevice(deviceId);
        //obj.then((value) {
          snapshot.value.forEach((key,values) {
            if(key == deviceKey) { // compare with value.deviceKey instead
              print(values["deviceDescription"]); // I get the correct data here.
              deviceObj.manual = values["deviceManual"];
              deviceObj.deviceType = values["deviceType"];
              deviceObj.description = values["deviceDescription"];
              deviceObj.brand = values["deviceBrand"];
              deviceObj.picture = values["devicePicture"];
            }
         // });
        });
      }
      return deviceObj;
    });
    return device;
  }
</code>```

Now both of these functions work. I want to make it work one after the other. In the above function, if I  uncomment the lines of code, the data is retrieved properly in the inner function but it returns initial default values set because the values get returned before setting the obj of SpecificDevice.

Here is where I am getting the error. I am calling the second function in FutureBuilder<> code with the above lines uncommented and taking input param as deviceId.

```<code>return FutureBuilder<Device>(
              future: getDeviceDescription(deviceId),
              builder:(BuildContext context,AsyncSnapshot snapshot){... // using snapshot.data in its child.
</code>```

Here in snapshot.data. would give me YYYY. But it should get me the value from the database.
I am stuck with this for a while. Any help in fixing this? or if what I am trying to do is clear then please suggest me a better way to approach this. Thanks in advance!

答:
The answer is rather simple:

first and foremost - you forgot to use async / await keywords, which will guarantee synchronous data retrieval from the database. Always use them, if you are connecting to any network service

to make one command work after another - use .then((value) {}). It will get data from the first function (which you pass using return) and use it in the second function.

Body:
I am new to flutter and I am sure there is a simple way of doing this. Let me first give you a background. I have 2 tables(collections). The first one store a mapping. Therefore it returns a key based on an id which will be used to query the second table and retrieve the data from firebase.

I have written 2 data models and 2 functions which return Future<> data. They are as follows-

Future<SpecificDevice> getSpecificDevice(String deviceId) {
    Future<SpecificDevice> obj =_database.reference().child("deviceMapping").orderByChild("deviceId").equalTo(deviceId).once().then((snapshot) {
      SpecificDevice specificDevice = new SpecificDevice(deviceId, "XXXX", new List<String> ());
      if(snapshot.value.isNotEmpty){
        print(snapshot.value);
        snapshot.value.forEach((key,values) {
          if(values["deviceId"] == deviceId) {
            specificDevice.deviceKey = values["deviceDesc"];
            specificDevice.vendorList = List.from(values["vendorList"]);
          }
        });
      }
      return specificDevice;
    });
    return obj;
  }

This function gets the mapping deviceId -> deviceKey.
This is the key of record stored in another table. Following is the function for it.

Future<Device> getDeviceDescription(String deviceKey) {
    Future<Device> device = _database.reference().child("deviceDescription").once().then((snapshot) {
      Device deviceObj = new Device("YYYY", "YYYY", "YYY", "YYYY", "YYYY");
      if(snapshot.value.isNotEmpty){
        print(snapshot.value);
        //Future<SpecificDevice> obj = getSpecificDevice(deviceId);
        //obj.then((value) {
          snapshot.value.forEach((key,values) {
            if(key == deviceKey) { // compare with value.deviceKey instead
              print(values["deviceDescription"]); // I get the correct data here.
              deviceObj.manual = values["deviceManual"];
              deviceObj.deviceType = values["deviceType"];
              deviceObj.description = values["deviceDescription"];
              deviceObj.brand = values["deviceBrand"];
              deviceObj.picture = values["devicePicture"];
            }
         // });
        });
      }
      return deviceObj;
    });
    return device;
  }

Now both of these functions work. I want to make it work one after the other. In the above function, if I  uncomment the lines of code, the data is retrieved properly in the inner function but it returns initial default values set because the values get returned before setting the obj of SpecificDevice.

Here is where I am getting the error. I am calling the second function in FutureBuilder<> code with the above lines uncommented and taking input param as deviceId.

return FutureBuilder<Device>(
              future: getDeviceDescription(deviceId),
              builder:(BuildContext context,AsyncSnapshot snapshot){... // using snapshot.data in its child.

Here in snapshot.data. would give me YYYY. But it should get me the value from the database.
I am stuck with this for a while. Any help in fixing this? or if what I am trying to do is clear then please suggest me a better way to approach this. Thanks in advance!


问:
Storing an HTML node as key in an *object*
Similar to this SO question, I would like to use HTML nodes as keys in an object (not an array).

Example:

```<code>var _hotspots = {
                 [object HTMLDivElement] : { someProps:[1,2,3] },
                 [object HTMLDivElement] : { someProps:[1,2,3] }
                }
</code>```

and so I might achieve things like this:

```<code>for( var a in _hotspots ){
    if(YAHOO.lang.hasOwnProperty(_hotspots, a)){
    alert('key nodeName: '+a.nodeName);
    }
}
</code>```

So far, when I alert out 'a' above, it alerts out that it is in fact a [object HTMLDivElement], so it all seemed fine - but I can't access properties on 'a', like nodeName.

Is what I am doing possible? Is it wrong? If I should be able to access properties on the object's key reference then please let me know and I'll write up a sample page.

cheers.

答: You could use my own jshashtable, which accepts any object as key, but if it's not a problem for you to give all your elements an id then I'd recommend using an object with element IDs as keys, since that will be the simplest and most performant solution.

Body:
Similar to this SO question, I would like to use HTML nodes as keys in an object (not an array).

Example:

var _hotspots = {
                 [object HTMLDivElement] : { someProps:[1,2,3] },
                 [object HTMLDivElement] : { someProps:[1,2,3] }
                }

and so I might achieve things like this:

for( var a in _hotspots ){
    if(YAHOO.lang.hasOwnProperty(_hotspots, a)){
    alert('key nodeName: '+a.nodeName);
    }
}

So far, when I alert out 'a' above, it alerts out that it is in fact a [object HTMLDivElement], so it all seemed fine - but I can't access properties on 'a', like nodeName.

Is what I am doing possible? Is it wrong? If I should be able to access properties on the object's key reference then please let me know and I'll write up a sample page.

cheers.


问:
How to append to a list from a csv reading a column with operators appearing in line ; getting "invalid literal for float()" error
I am appending to a list from a csv which looks like this

SampleA,Type,3.782*0.0627

then vals = line.split(',')

So, I ve tried something like
value = float(str(vals[2]))
or
value = float(vals[2])

but I get errors like ValueError: invalid literal for float(): 3.782*0.0627

So what I want, is to basically store to value = 0.237 ie the result of the mutlipication

TIA

答:
The accepted answer doesn't handle the case that there is only one value, for that I would suggest (Python 3.8 or later)

```<code>from math import prod

value = prod(map(float, vals[2].split("*")))
</code>```

Or similarly

```<code>from math import prod

value = prod(float(x) for x in vals[2].split("*"))
</code>```

Body:
The accepted answer doesn't handle the case that there is only one value, for that I would suggest (Python 3.8 or later)

from math import prod

value = prod(map(float, vals[2].split("*")))

Or similarly

from math import prod

value = prod(float(x) for x in vals[2].split("*"))


问:
Extracting certain elements from array of each row for a specific column
I'm trying to extract values from array rows of a specific column with specified indices.

A dummy example, if I have a column called 'arr' in my dataframe where each array below is a row-

```<code>[1, 2, 3, 4, 5]

[6, 7, 8, 9, 10]

[11, 12, 13, 14, 15]

[16, 17, 18, 19, 20]
</code>```

I've tried:

```<code>for row in df.itertuples():
    i1 = [0,1,2]
    r1 = np.array(df.arr)[i1]

    i2 = [2,3]
    r2 = np.array(df.arr)[i2]
</code>```

which gives the rows 0, 1 and 2 from the dataframe.

And I've tried:

```<code>for row in df.itertuples():
    i1 = [0,1,2]
    r1 = np.array(row.arr)[i1]

    i2 = [2,3]
    r2 = np.array(row.arr)[i2]
</code>```

which gives the values from only the last row. I don't understand why.

What I want to get are the indices specified in i1 and i2 as two different variables (r1 and r2) for each row. So-

r1 should give-

```<code>[1, 2, 3]

[6, 7, 8]

[11, 12, 13]

[16, 17, 18]
</code>```

And r2 should give-

```<code>[3, 4]

[8, 9]

[13, 14]

[18, 19]
</code>```

I've also used iterrows() with no luck.

答:
if you want columns r1 and r2 in same dataframe , you can use:

```<code>df = pd.DataFrame(np.random.randn(10, 5), columns=['a', 'b', 'c', 'd', 'e'])
df['arr'] = df[['b', 'c', 'd', 'e']].values.tolist()
df['r1']=df['arr']
df['r1']=df['r1'].apply(lambda x:x[0:3])
df['r2']=df['arr']
df['r2']=df['r2'].apply(lambda x:x[2:4])
</code>```

I have applied lambda that does the work, is this what you want?

If you want a new dataframe with rows r1 and r2 , you can use

```<code>from operator import itemgetter
a=[0,1,2]
b=[2,3]
df = pd.DataFrame(np.random.randn(10, 5), columns=['a', 'b', 'c', 'd', 'e'])
df['arr'] = df[['b', 'c', 'd', 'e']].values.tolist()
data=pd.DataFrame()
data['r1']=df['arr']
data['r2']=df['arr']
data['r1']=data['r1'].apply(lambda x:itemgetter(*a)(x))
data['r2']=data['r2'].apply(lambda x:itemgetter(*b)(x))
data
</code>```

does this edit help you!

Body:
I'm trying to extract values from array rows of a specific column with specified indices.

A dummy example, if I have a column called 'arr' in my dataframe where each array below is a row-

[1, 2, 3, 4, 5]

[6, 7, 8, 9, 10]

[11, 12, 13, 14, 15]

[16, 17, 18, 19, 20]

I've tried:

for row in df.itertuples():
    i1 = [0,1,2]
    r1 = np.array(df.arr)[i1]

    i2 = [2,3]
    r2 = np.array(df.arr)[i2]

which gives the rows 0, 1 and 2 from the dataframe.

And I've tried:

for row in df.itertuples():
    i1 = [0,1,2]
    r1 = np.array(row.arr)[i1]

    i2 = [2,3]
    r2 = np.array(row.arr)[i2]

which gives the values from only the last row. I don't understand why.

What I want to get are the indices specified in i1 and i2 as two different variables (r1 and r2) for each row. So-

r1 should give-

[1, 2, 3]

[6, 7, 8]

[11, 12, 13]

[16, 17, 18]

And r2 should give-

[3, 4]

[8, 9]

[13, 14]

[18, 19]

I've also used iterrows() with no luck.

Body:
if you want columns r1 and r2 in same dataframe , you can use:

df = pd.DataFrame(np.random.randn(10, 5), columns=['a', 'b', 'c', 'd', 'e'])
df['arr'] = df[['b', 'c', 'd', 'e']].values.tolist()
df['r1']=df['arr']
df['r1']=df['r1'].apply(lambda x:x[0:3])
df['r2']=df['arr']
df['r2']=df['r2'].apply(lambda x:x[2:4])

I have applied lambda that does the work, is this what you want?

If you want a new dataframe with rows r1 and r2 , you can use

from operator import itemgetter
a=[0,1,2]
b=[2,3]
df = pd.DataFrame(np.random.randn(10, 5), columns=['a', 'b', 'c', 'd', 'e'])
df['arr'] = df[['b', 'c', 'd', 'e']].values.tolist()
data=pd.DataFrame()
data['r1']=df['arr']
data['r2']=df['arr']
data['r1']=data['r1'].apply(lambda x:itemgetter(*a)(x))
data['r2']=data['r2'].apply(lambda x:itemgetter(*b)(x))
data

does this edit help you!