问:
How to know which character at what location the mouse hovers on in a DIV
As we know, we can use mouse envent to get target and then get the target's position in web page.

But how to know what character my mouse hovers on?

for example, in a div there is some text "Test" and my mouse is hovering on character 's'; how can I get the target is 's' and it's position like offsetTop and offsetLeft?

there are 2 solutions NOT satisfied:

split text into character and every character in a standalone span. it will create huge number of spans and may cause page die (correct me if i am wrong, how to avoid page die?) ...

use canvas and set font as div has; use measure text to get text width; this method can roughly location where we are but it is not stable; for example, we do not know how browser wrap wrods and break them into a new line...

答:
Would this be good for you?

$cont = $('p');
parts = $.map($cont.text().split(''), function(v){
    return $('', {text:v});
});
$cont.empty().append(parts);

$(document).ready(function() {
 $('span').on('mouseover', function() {
   console.log($(this).text() + ': ' + JSON.stringify($(this).offset()))
  })
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>p span:hover{background:#F00}</code>```

Lorem ipsum dolor sit amet, consetetur sadipscing elitr,
sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat,
sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.
Stet clita kasd gubergren, no sea takimata sanctus e Lorem ipsum dolor sit amet.
```

Body:
Would this be good for you?

$cont = $('p');
parts = $.map($cont.text().split(''), function(v){
    return $('<span/>', {text:v});
});
$cont.empty().append(parts);

$(document).ready(function() {
 $('span').on('mouseover', function() {
   console.log($(this).text() + ': ' + JSON.stringify($(this).offset()))
  })
})

p span:hover{background:#F00}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr,
sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat,
sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.
Stet clita kasd gubergren, no sea takimata sanctus e Lorem ipsum dolor sit amet.</p>


来源: stackexchange

问:
TagManager in Android : Failed to load the container. NO default container resource found with resource ID -1
I followed every step right in setting up tag manager + firebase:

FirebaseB, GA and Tag Manager properly set up
Install necessary nugets as stated above.
Put the JSON of the tag manager container inside assets/containers
When I tested in iOS, it went smoothly, however in Android, I kept getting this error:

Invalid macro: _gtm.loadEventEnabled

I also encounter this in the device log afterwards:

Failed to load the container. NO default container resource found with resource ID -1

refresh test, containerHolder: com.google.android.gms.tagmanager.dc@XXXXXXX

Steps to Reproduce:

1) Create a Xamarin Forms app.
2) In the Android project, install the necessary nuget packages.
3) Enable firebase and call _firebaseAnalytics.SetAnalyticsCollectionEnabled(true);.
4) Log some events
5) Create a GA and google tag manager account. Create a container (Android), then download the JSON file. Put the JSON file inside Assets/containers folder.
6) Run the application while Device logcat is running (you can check error here)

These are the packages that I used:

PackageReference Include="Xamarin.GooglePlayServices.Analytics" Version="71.1608.1"
    PackageReference Include="Xamarin.GooglePlayServices.Base" Version="71.1610.1
 PackageReference Include="Xamarin.GooglePlayServices.TagManager" Version="71.1604.1
 PackageReference Include="Xamarin.Firebase.Analytics" Version="71.1630.1
 PackageReference Include="Xamarin.Firebase.Messaging" Version="71.1740.1

Has anyone encountered this and knows how to fix this?

答:
Welcome to SO !

Using Tag Manager in Xamarin Android , after installing Nuget Package for solution . There are follow steps for reference :

1, Create a Google Analytics account, please make sure you select a mobile account (Under New Property - you'll have to select mobile/Web).

2,Create a Google Tag Manager account - create a container, then create a tag of type Google Analytics - universal analytics. a) Put your analytics account id in the Tracking ID (should be in the form "UA-XXXXXX-X"). b) Create a macro for screen name (you can view in the screenshots 'TagManagerMacro.jpeg') c) The Rule Track Type should be App View. d) In the more settings --> basic configuration --> screen name - add the macro we defined in step b. e) In Firing rules - make sure your rule is set for always.

In your Activity, call to

```<code>var tagmanager = TagManagerClass.GetInstance(this);

 var pendingResult = _tagmanager.LoadContainerPreferNonDefault("GTM-XXXXXX",
            Resource.Raw.gtm_analytics);

pendingResult.SetResultCallback(new TagMnagerResultCallback(), 2, TimeUnit.Seconds);
</code>```

After the callback as returned, you can fire events like this:

```<code>_tagmanager.DataLayer.PushEvent("openScreen", DataLayer.MapOf("screenName", "testScreen"));
</code>```

This guide was followed by the guidelines instructed here.

ContentLicense: CC BY-SA 4.0

Body:
Welcome to SO !

Using Tag Manager in Xamarin Android , after installing Nuget Package for solution . There are follow steps for reference :

1, Create a Google Analytics account, please make sure you select a mobile account (Under New Property - you'll have to select mobile/Web).

2,Create a Google Tag Manager account - create a container, then create a tag of type Google Analytics - universal analytics. a) Put your analytics account id in the Tracking ID (should be in the form "UA-XXXXXX-X"). b) Create a macro for screen name (you can view in the screenshots 'TagManagerMacro.jpeg') c) The Rule Track Type should be App View. d) In the more settings --> basic configuration --> screen name - add the macro we defined in step b. e) In Firing rules - make sure your rule is set for always.

In your Activity, call to

var tagmanager = TagManagerClass.GetInstance(this);

 var pendingResult = _tagmanager.LoadContainerPreferNonDefault("GTM-XXXXXX",
            Resource.Raw.gtm_analytics);

pendingResult.SetResultCallback(new TagMnagerResultCallback(), 2, TimeUnit.Seconds);

After the callback as returned, you can fire events like this:

_tagmanager.DataLayer.PushEvent("openScreen", DataLayer.MapOf("screenName", "testScreen"));

This guide was followed by the guidelines instructed here.


问:
How to check if a string is a valid Json Schema?
If I have a string = "{}", which is not a valid Json Schema, how do I check it using jackson whether it is a valid Json Schema or not?</p>

答:
Because a JSON schema is itself a JSON document, you can validate it using a... JSON schema.

There are JSON meta-schemas available that can be used to validate your schema against on the JSON Schema website , so to check whether your schema is valid, it's sufficient to validate it against the correct meta-schema.

Meta-schemas can be found here, and a list of libraries to perform the actual validation can be found here.


问:
__dopostback not working as expected
Scenario 1 (That Works)
This is a POC i created.
I have a script manager, a html textbox, an ASP.NET button, an updatepanel with async trigger set for Click event of above mentioned button. For html textbox i have, onkeyup='__doPostBack('<%=ASPBUTTON.ClientID%>',''). AND IT WORKS, the Click event of button is hit, and updatepanel is updated asynchronously.

Scenario 2 (It's not working)
The only difference with my actual codebase is that i have a JQUERY FILAMENTGROUP datetimepicker whose onchange event is being used instead of html textbox's onchange. Further, here my page uses a master page. Now, my problem is that when onchange event for datetimepicker fires, the request goes server side, but BUTTON click event is not getting fired.

Some more details,
I want to update the updatepanel automatically on datetimepicker selection. So, the button would be actually hidden through css (display:none).

Button id - btnDateRangeCallback

Datetimepicker Textbox (non ASP control) - dateRange

```<code>        onChange: function() {__doPostBack('<%=btnDateRangeCallback.ClientID%>',   $('#dateRange').val());}
</code>```

[Please remember i said it works in case of my simplistic POC, while in my actual codebase i am using a masterpage to inherit from, and so all these controls are placed in a contentplaceholder. Furthermore, postback is happening, and i can see _EVENTTARGET and _EVENTARGUMENT being sent correctly if i break at Page_Load]

Please help.

To put it more simply,
After postback, when i break at Page_Load, i see the Request.Form contents as,
ctl00%24ContentPlaceHolder1%24SMgr1=ctl00%24ContentPlaceHolder1%24SMgr1%7cctl00_ContentPlaceHolder1_btnDateRangeCallback
&__EVENTTARGET=ctl00_ContentPlaceHolder1_btnDateRangeCallback
&_EVENTARGUMENT=5%2f3%2f2011+-+6%2f2%2f2011
&_VIEWSTATE=%2fwEPDwULLTE3NDY5NDIwMDRkZIuTqMNNsFHlRYhjpKaUCaCXj42h
&_EVENTVALIDATION=%2fwEWAgLBx52kBALP6Ln6DdkkwE%2frVIKQzKE1L0k4QhIc768w
&_ASYNCPOST=true&

Why is not Click event for btnDateRangeCallback hitting???

答: Use the UniqueID instead: __doPostBack('<%=btnDateRangeCallback.UniqueID %>', ...

ContentLicense: CC BY-SA 3.0

Title: __dopostback not working as expected

Body:
Scenario 1 (That Works)
This is a POC i created.
I have a script manager, a html textbox, an ASP.NET button, an updatepanel with async trigger set for Click event of above mentioned button. For html textbox i have, onkeyup='__doPostBack('<%=ASPBUTTON.ClientID%>',''). AND IT WORKS, the Click event of button is hit, and updatepanel is updated asynchronously.

Scenario 2 (It's not working)
The only difference with my actual codebase is that i have a JQUERY FILAMENTGROUP datetimepicker whose onchange event is being used instead of html textbox's onchange. Further, here my page uses a master page. Now, my problem is that when onchange event for datetimepicker fires, the request goes server side, but BUTTON click event is not getting fired.

Some more details,
I want to update the updatepanel automatically on datetimepicker selection. So, the button would be actually hidden through css (display:none).

Button id - btnDateRangeCallback

Datetimepicker Textbox (non ASP control) - dateRange

        onChange: function() {__doPostBack('<%=btnDateRangeCallback.ClientID%>',   $('#dateRange').val());}

[Please remember i said it works in case of my simplistic POC, while in my actual codebase i am using a masterpage to inherit from, and so all these controls are placed in a contentplaceholder. Furthermore, postback is happening, and i can see _EVENTTARGET and _EVENTARGUMENT being sent correctly if i break at Page_Load]

Please help.

To put it more simply,
After postback, when i break at Page_Load, i see the Request.Form contents as,
ctl00%24ContentPlaceHolder1%24SMgr1=ctl00%24ContentPlaceHolder1%24SMgr1%7cctl00_ContentPlaceHolder1_btnDateRangeCallback
&__EVENTTARGET=ctl00_ContentPlaceHolder1_btnDateRangeCallback
&_EVENTARGUMENT=5%2f3%2f2011+-+6%2f2%2f2011
&_VIEWSTATE=%2fwEPDwULLTE3NDY5NDIwMDRkZIuTqMNNsFHlRYhjpKaUCaCXj42h
&_EVENTVALIDATION=%2fwEWAgLBx52kBALP6Ln6DdkkwE%2frVIKQzKE1L0k4QhIc768w
&_ASYNCPOST=true&

Why is not Click event for btnDateRangeCallback hitting???


问:
How to check if a named table exists or not in ETS Erlang/Elixir
I want to create a table in ets if it does not exists . How can I check if this named exists or not ?</p>

答:
This should do the trick: </p>

<blockquote>
```<code>def create_table? do
  if Enum.member?(:ets.all(), :my_table) == false do
      :ets.new(:my_table, [:public, :named_table])
  end
end
</code>```
</blockquote>

Body:
This should do the trick:

def create_table? do
  if Enum.member?(:ets.all(), :my_table) == false do
      :ets.new(:my_table, [:public, :named_table])
  end
end


问:
Modify strings within a vector? (Without using loops)
I'm trying to take a vector of strings and remove every character that's not a letter (number, symbols, etc.) I'm also not trying to use loops.

So here's an example of a vector:

```<code>std::vector<std::string> a = {"he2llo*", "3worl$d"};
</code>```

And I want the string returned to look like this:

```<code>std::vector<std::string> a = {"hello", "world"};
</code>```

Right now I'm trying to use the transfrom and erase algorithms, but I can't get the syntax right.

This is obviously incomplete, but it's the basic setup of what I have so far:

```<code>int trim(std::vector<std::string> a){
    std::transform(a.begin(), a.end(), a.erase())
</code>```

答:
You can try it in different ways with STL <algorithm>s, i implemented a functor to process each word :

```<code>#include <iostream>
#include <vector>
#include <cctype>
#include <algorithm>

class Processing{

public:

    std::string operator()(std::string& value){

        for_each(value.begin(), value.end(), [&](char v) mutable throw() ->
                 void {
                    auto fetch = std::find_if( value.begin(), value.end(), [&](char v)mutable throw()->
                                              bool{
                                                  return(!isalpha(v));
                                                  });
                    if(*fetch){
                        value.erase( fetch );
                    }
                 });
        return value;
    }

};

int main()
{

  std::vector<std::string> values = {"44h%ello333","%w%or333ld21"};

  std::for_each(values.begin(),values.end(), Processing());

  std::for_each(values.begin(),values.end(), [](std::string& value)->
                void {
                    std::cout<<value<<" ";
                    });

    return 0;
}
</code>```

Body:
I'm trying to take a vector of strings and remove every character that's not a letter (number, symbols, etc.) I'm also not trying to use loops.

So here's an example of a vector:

std::vector<std::string> a = {"he2llo*", "3worl$d"};

And I want the string returned to look like this:

std::vector<std::string> a = {"hello", "world"};

Right now I'm trying to use the transfrom and erase algorithms, but I can't get the syntax right.

This is obviously incomplete, but it's the basic setup of what I have so far:

int trim(std::vector<std::string> a){
    std::transform(a.begin(), a.end(), a.erase())

Body:
You can try it in different ways with STL <algorithm>s, i implemented a functor to process each word :

#include <iostream>
#include <vector>
#include <cctype>
#include <algorithm>

class Processing{

public:

    std::string operator()(std::string& value){

        for_each(value.begin(), value.end(), [&](char v) mutable throw() ->
                 void {
                    auto fetch = std::find_if( value.begin(), value.end(), [&](char v)mutable throw()->
                                              bool{
                                                  return(!isalpha(v));
                                                  });
                    if(*fetch){
                        value.erase( fetch );
                    }
                 });
        return value;
    }

};

int main()
{

  std::vector<std::string> values = {"44h%ello333","%w%or333ld21"};

  std::for_each(values.begin(),values.end(), Processing());

  std::for_each(values.begin(),values.end(), [](std::string& value)->
                void {
                    std::cout<<value<<" ";
                    });

    return 0;
}


问:
Manage SQL session state using Azure AD
We have an old .net web form application using SQL session management and membership module.
As per new directive we have to implement Azure AD for authentication. It's all done and completed.
Now the issue here is how to manage session state.
I know we can configure in Azure directly:Manage session in Azure

But security team will not allow it and told us we need to use sql server(On-PREM, our sql server is not hosted in Azure) session management only.
I am able to get session entries in [ASPStateTempSessions].
But not able to achieve session timeout. I have set it for 20 mins but session never gets expired.

Thanks in advance for the help. :)

答:
Actually, Azure AD doesn't support on-premise SQL Server.

You can not using Azure AD to manage the session state.

Hope this helps.

Title: Manage SQL session state using Azure AD


问:
How to jump to an IP address when connected to a remote server on VS Code?
I've never connected to a remote server before. I want to connect to my company's remote server then jump to another IP address.

I followed VS Code Guide here and connected to the server, but I'm not sure how to jump to the IP address.

Could anyone help me? Thanks a lot!

答:
I figured it out.

I wanted to connect to my company's private server. In order to do that, I must connect to my company's host server. When I'm in the host server, I have to connect to a private server (sorry for not phrasing my question in a clearer sense).

I'm leaving my solution here for future reference.
In VS Code, do F1 (fn+F1 on Mac) -> Remote-SSH: Connect to Host -> Configure SSH Host -> /Users//.ssh/config.

From there, edit the config file as follows:

```<code>Host <host-name>
  HostName <IP-address>
  Port <specify-port-number-here>
  User <user-name>

### The Remote Host
Host <private-server-name>
  HostName <IP-address>
  Port <specify-port-number-here>
  User <user-name>
  ProxyJump <host-name>

</code>```

Save the config file and connect to the private server by F1 -> Remote-SSH: Connect to Host -> private-server-name

Body:
I figured it out.

I wanted to connect to my company's private server. In order to do that, I must connect to my company's host server. When I'm in the host server, I have to connect to a private server (sorry for not phrasing my question in a clearer sense).

I'm leaving my solution here for future reference.
In VS Code, do F1 (fn+F1 on Mac) -> Remote-SSH: Connect to Host -> Configure SSH Host -> /Users//.ssh/config.

From there, edit the config file as follows:

Host <host-name>
  HostName <IP-address>
  Port <specify-port-number-here>
  User <user-name>

### The Remote Host
Host <private-server-name>
  HostName <IP-address>
  Port <specify-port-number-here>
  User <user-name>
  ProxyJump <host-name>

Save the config file and connect to the private server by F1 -> Remote-SSH: Connect to Host -> private-server-name


问:
FFMPEG HLS multiple Tracks not in sync
This script works but the video doesnt sync with the sub or audio tracks.   Could someone help fix this or Help me with a NEW script.  I have been trying to figure this out with 0 luck and have had friends look at it.  I even went to FFMPEG discord and FB  asking for help from others who have posted scripts in the past.   Seems no one has a interest in this.   Please  will someone help me.

All I am trying to do is BULK encode  MKVs to HLS  with multiple resoutions  in 10 sec segments  and include all the Audio and SUb tracks that were originally in the MKV

```<code>$files = Get-ChildItem ${Get-Location}
$loco = Get-Location
$p1 = Join-Path -Path $loco -ChildPath "/out"
New-Item -ItemType Directory -Force -Path $p1

function lnCodeTransform {
    param( $String )
    echo $String
    switch ($String)
    {
        "jpn" {"jp"}
        "eng" {"en"}
        "esp" {"es"}
        "fra" {"fr"}
        "deu" {"de"}
        default {$String}
    }
}

function lnNameTransform {
    param( $String )
    switch ($String)
    {
        "jpn" {"Japanese"}
        "eng" {"English"}
        "esp" {"Spanish"}
        "fra" {"French"}
        "deu" {"German"}
        default {$String}
    }
}

foreach ($f in $files){
    if ($f.Name -eq "out"){
        continue;
    }
    $p2 = Join-Path -Path $loco -ChildPath "/out/" | Join-Path -ChildPath $f
    New-Item -ItemType Directory -Force -Path $p2/audio
    New-Item -ItemType Directory -Force -Path $p2/video
    New-Item -ItemType Directory -Force -Path $p2/subtitle
    $sb = [System.Text.StringBuilder]::new();
    [void]$sb.AppendLine( '#EXTM3U' )
    [void]$sb.AppendLine( '#EXT-X-VERSION:3' )
    #[void]$sb.AppendLine( '#EXT-X-STREAM-INF:BANDWIDTH=800000,RESOLUTION=640x360' )
    #[void]$sb.AppendLine( '360p.m3u8' )

    New-Item -ItemType Directory -Force -Path $p2
    $resStr = ffprobe -v error -select_streams v:0 -show_entries stream=height -of csv=s=x:p=0 $f.FullName;
    $res = [convert]::ToInt32($resStr)
    $audioTracks = ffprobe $f.FullName -show_entries stream=index:stream_tags=language -select_streams a -of compact=p=0:nk=1
    $audioTracks = $audioTracks.split("\n")
    foreach($audio in $audioTracks) {
        $ID = $audio.split("|")[0];
        $audioName = $audio.split("|")[1];
        ffmpeg -i $f.FullName -threads 0 -muxdelay 0 -y -map 0:$ID -async 1 -codec aac -f segment -segment_time 10 -segment_list_size 0 -segment_list out/$f/audio/audio_"$ID.m3u8" -segment_format mpegts out/$f/audio/"audio_$ID""_%d.ts"
        $name = lnNameTransform($audioName)
        $code = lnCodeTransform($audioName)
        [void]$sb.AppendLine( "#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID=`"aac`",LANGUAGE=`"$code`",NAME=`"$name`",DEFAULT=NO,AUTOSELECT=NO,URI=`"audio/audio_$ID.m3u8`"" )
    }
    $subTracks = ffprobe $f.FullName -show_entries stream=index:stream_tags=language -select_streams s -of compact=p=0:nk=1
    $subTracks = $subTracks.split("")
    foreach($subtitle in $subTracks) {
        $ID = $subtitle.split("|")[0];
        $subName = $subtitle.split("|")[1];
        ffmpeg -i $f.FullName -map 0:$ID -f segment -segment_time 10 -segment_list_size 0 -segment_list out/$f/subtitle/sub_"$subName.m3u8" -segment_format webvtt -scodec webvtt out/$f/subtitle/"sub_$subName%d.vtt"
        $name = lnNameTransform($subName)
        $code = lnCodeTransform($subName)
        [void]$sb.AppendLine( "#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID=`"subs`",LANGUAGE=`"$code`",NAME=`"$name`",FORCED=NO,AUTOSELECT=NO,URI=`"subtitle/sub_$subName.m3u8`"" )
    }

    [void]$sb.AppendLine( '#EXT-X-STREAM-INF:BANDWIDTH=1400000,CODECS="avc1.4d4015,mp4a.40.2",RESOLUTION=842x480,AUDIO="aac",SUBTITLES="subs"' )
    [void]$sb.AppendLine( 'video/480p.m3u8' )
    #ffmpeg -i $f.FullName -c:a copy -vf scale=w=640:h=360:force_original_aspect_ratio=decrease -c:a aac -ar 48000  -rc cqp -qp_p 0 -qp_i 1 -profile:v main -crf 20 -sc_threshold 0 -g 48 -keyint_min 48 -hls_time 4 -hls_playlist_type vod  -b:v 800k -maxrate 856k -bufsize 1200k -b:a 96k -hls_segment_filename out/$f/360p_%03d.ts out/$f/360p.m3u8 -vf scale=w=842:h=480:force_original_aspect_ratio=decrease -c:a aac -ar 48000 -gpu 1 -c:v h264_amf -rc cqp -qp_p 0 -qp_i 1 -profile:v main -crf 20 -sc_threshold 0 -g 48 -keyint_min 48 -hls_time 4 -hls_playlist_type vod -b:v 1400k -maxrate 1498k -bufsize 2100k -b:a 128k -hls_segment_filename out/$f/480p_%03d.ts out/$f/480p.m3u8 -vf  scale=w=1280:h=720:force_original_aspect_ratio=decrease -c:a aac -ar 48000 -gpu 1 -c:v h264_amf -rc cqp -qp_p 0 -qp_i 1 -profile:v main -crf 20 -sc_threshold 0 -g 48 -keyint_min 48 -hls_time 4 -hls_playlist_type vod -b:v 2800k -maxrate 2996k -bufsize 4200k -b:a 128k -hls_segment_filename out/$f/720p_%03d.ts out/$f/720p.m3u8 -vf  scale=w=1920:h=1080:force_original_aspect_ratio=decrease -c:a aac -ar 48000 -gpu 1 -c:v h264_amf -rc cqp -qp_p 0 -qp_i 1 -profile:v main -crf 20 -sc_threshold 0 -g 48 -keyint_min 48 -hls_time 4 -hls_playlist_type vod -b:v 5000k -maxrate 5350k -bufsize 7500k -b:a 192k -hls_segment_filename out/$f/1080p_%03d.ts out/$f/1080p.m3u8
    #ffmpeg -hwaccel auto -hwaccel_device 0 -i $f.FullName -c:v h264 -profile:v main -c:a aac -filter:v scale=360:640 -ar 48000  -rc cqp -qp_p 0 -qp_i 1 -profile:v main -crf 23 -sc_threshold 0 -g 48 -b:v 800k -maxrate 856k -bufsize 1200k -b:a 96k  -keyint_min 4 -start_number 0 -hls_time 10 -hls_playlist_type vod  -hls_list_size 0 -f hls -hls_segment_filename out/$f/360p_%03d.ts out/$f/360p.m3u8
    #ffmpeg -hwaccel auto -hwaccel_device 0 -i $f.FullName -c:v h264 -profile:v main -c:a aac -filter:v scale=360:640 -start_number 0 -hls_time 10 -hls_list_size 0 -f hls -hls_segment_filename out/$f/360p_%03d.ts out/$f/360p.m3u8
    ffmpeg -i $f.FullName -c:v h264 -async 1 -profile:v main -y -filter:v scale="trunc(oh*a/2)*2:480" -map 0:v -start_number 0 -hls_time 10 -hls_list_size 0 -f hls -hls_segment_filename out/$f/video/480p_%03d.ts out/$f/video/480p.m3u8
    If($res -ge 720) {
        ffmpeg -i $f.FullName -c:v h264 -profile:v main -filter:v scale="trunc(oh*a/2)*2:720" -map 0:v -start_number 0 -hls_time 10 -hls_list_size 0 -f hls -hls_segment_filename out/$f/video/720p_%03d.ts out/$f/video/720p.m3u8
        [void]$sb.AppendLine( '#EXT-X-STREAM-INF:BANDWIDTH=2800000,CODECS="avc1.4d4015,mp4a.40.2",RESOLUTION=1280x720,AUDIO="aac",SUBTITLES="subs"' )
        [void]$sb.AppendLine( 'video/720p.m3u8' )
    }
    If($res -ge 1080) {
        ffmpeg -i $f.FullName -c:v h264 -profile:v main -filter:v scale="trunc(oh*a/2)*2:1080" -map 0:v -start_number 0 -hls_time 10 -hls_list_size 0 -f hls -hls_segment_filename out/$f/video/1080p_%03d.ts out/$f/video/1080p.m3u8
        [void]$sb.AppendLine( '#EXT-X-STREAM-INF:BANDWIDTH=5000000,CODECS="avc1.4d4015,mp4a.40.2",RESOLUTION=1920x1080,AUDIO="aac",SUBTITLES="subs"' )
        [void]$sb.AppendLine( 'video/1080p.m3u8' )
    }

    $p3 = Join-Path -Path $p2 -ChildPath "/index.m3u8"
    #echo $index | Out-File -Encoding UTF8 -LiteralPath $p3
    echo $sb.ToString()
    [System.IO.File]::WriteAllLines($p3, $sb.ToString().Trim().replace("`r`n", "`n"))
}
$sw.Stop()
echo $sw.Elapsed ```
```

答:
```<code>$files = Get-ChildItem ${Get-Location}
$loco = Get-Location
$p1 = Join-Path -Path $loco -ChildPath "/out"
New-Item -ItemType Directory -Force -Path $p1

function lnCodeTransform {
    param( $String )
    switch ($String)
    {
        "jpn" {"jp"}
        "eng" {"en"}
        "esp" {"es"}
        "fra" {"fr"}
        "deu" {"de"}
        default {$String}
    }
}

function lnNameTransform {
    param( $String )
    switch ($String)
    {
        "jpn" {"Japanese"}
        "eng" {"English"}
        "esp" {"Spanish"}
        "fra" {"French"}
        "deu" {"German"}
        default {$String}
    }
}

foreach ($f in $files){
    if ($f.Name -eq "out"){
        continue;
    }
    $p2 = Join-Path -Path $loco -ChildPath "/out/" | Join-Path -ChildPath $f
    New-Item -ItemType Directory -Force -Path $p2/audio
    New-Item -ItemType Directory -Force -Path $p2/video
    New-Item -ItemType Directory -Force -Path $p2/subtitle
    $sb = [System.Text.StringBuilder]::new();
    [void]$sb.AppendLine( '#EXTM3U' )
    [void]$sb.AppendLine( '#EXT-X-VERSION:3' )
    #[void]$sb.AppendLine( '#EXT-X-STREAM-INF:BANDWIDTH=800000,RESOLUTION=640x360' )
    #[void]$sb.AppendLine( '360p.m3u8' )

    New-Item -ItemType Directory -Force -Path $p2
    $resStr = ffprobe -v error -select_streams v:0 -show_entries stream=height -of csv=s=x:p=0 $f.FullName;
    $res = [convert]::ToInt32($resStr)
    $audioTracks = ffprobe $f.FullName -show_entries stream=index:stream_tags=language -select_streams a -of compact=p=0:nk=1
    $audioTracks = $audioTracks.split("\n")
    foreach($audio in $audioTracks) {
        $ID = $audio.split("|")[0];
        $audioName = $audio.split("|")[1];
        ffmpeg -i $f.FullName -ss 0 -y -map 0:$ID -start_number 0 -codec aac -f segment -segment_time 10 -segment_list_size 0 -segment_list out/$f/audio/audio_"$ID.m3u8" -segment_format mpegts out/$f/audio/"audio_$ID""_%d.ts"
        $name = lnNameTransform($audioName)
        $code = lnCodeTransform($audioName)
        [void]$sb.AppendLine( "#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID=`"aac`",LANGUAGE=`"$code`",NAME=`"$name`",DEFAULT=NO,AUTOSELECT=NO,URI=`"audio/audio_$ID.m3u8`"" )
    }
    $subTracks = ffprobe $f.FullName -show_entries stream=index:stream_tags=language -select_streams s -of compact=p=0:nk=1
    $subTracks = $subTracks.split("")
    foreach($subtitle in $subTracks) {
        $ID = $subtitle.split("|")[0];
        $subName = $subtitle.split("|")[1];
        ffmpeg -i $f.FullName -map 0:$ID -f segment -segment_time 10 -segment_list_size 0 -segment_list out/$f/subtitle/sub_"$subName.m3u8" -segment_format webvtt -scodec webvtt out/$f/subtitle/"sub_$subName%d.vtt"
        $name = lnNameTransform($subName)
        $code = lnCodeTransform($subName)
        [void]$sb.AppendLine( "#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID=`"subs`",LANGUAGE=`"$code`",NAME=`"$name`",FORCED=NO,AUTOSELECT=NO,URI=`"subtitle/sub_$subName.m3u8`"" )
    }

    [void]$sb.AppendLine( '#EXT-X-STREAM-INF:BANDWIDTH=1400000,CODECS="avc1.4d4015,mp4a.40.2",RESOLUTION=842x480,AUDIO="aac",SUBTITLES="subs"' )
    [void]$sb.AppendLine( 'video/480p.m3u8' )
    #ffmpeg -i $f.FullName -c:a copy -vf scale=w=640:h=360:force_original_aspect_ratio=decrease -c:a aac -ar 48000  -rc cqp -qp_p 0 -qp_i 1 -profile:v main -crf 20 -sc_threshold 0 -g 48 -keyint_min 48 -hls_time 4 -hls_playlist_type vod  -b:v 800k -maxrate 856k -bufsize 1200k -b:a 96k -hls_segment_filename out/$f/360p_%03d.ts out/$f/360p.m3u8 -vf scale=w=842:h=480:force_original_aspect_ratio=decrease -c:a aac -ar 48000 -gpu 1 -c:v h264_amf -rc cqp -qp_p 0 -qp_i 1 -profile:v main -crf 20 -sc_threshold 0 -g 48 -keyint_min 48 -hls_time 4 -hls_playlist_type vod -b:v 1400k -maxrate 1498k -bufsize 2100k -b:a 128k -hls_segment_filename out/$f/480p_%03d.ts out/$f/480p.m3u8 -vf  scale=w=1280:h=720:force_original_aspect_ratio=decrease -c:a aac -ar 48000 -gpu 1 -c:v h264_amf -rc cqp -qp_p 0 -qp_i 1 -profile:v main -crf 20 -sc_threshold 0 -g 48 -keyint_min 48 -hls_time 4 -hls_playlist_type vod -b:v 2800k -maxrate 2996k -bufsize 4200k -b:a 128k -hls_segment_filename out/$f/720p_%03d.ts out/$f/720p.m3u8 -vf  scale=w=1920:h=1080:force_original_aspect_ratio=decrease -c:a aac -ar 48000 -gpu 1 -c:v h264_amf -rc cqp -qp_p 0 -qp_i 1 -profile:v main -crf 20 -sc_threshold 0 -g 48 -keyint_min 48 -hls_time 4 -hls_playlist_type vod -b:v 5000k -maxrate 5350k -bufsize 7500k -b:a 192k -hls_segment_filename out/$f/1080p_%03d.ts out/$f/1080p.m3u8
    #ffmpeg -hwaccel auto -hwaccel_device 0 -i $f.FullName -c:v h264 -profile:v main -c:a aac -filter:v scale=360:640 -ar 48000  -rc cqp -qp_p 0 -qp_i 1 -profile:v main -crf 23 -sc_threshold 0 -g 48 -b:v 800k -maxrate 856k -bufsize 1200k -b:a 96k  -keyint_min 4 -start_number 0 -hls_time 10 -hls_playlist_type vod  -hls_list_size 0 -f hls -hls_segment_filename out/$f/360p_%03d.ts out/$f/360p.m3u8
    #ffmpeg -hwaccel auto -hwaccel_device 0 -i $f.FullName -c:v h264 -profile:v main -c:a aac -filter:v scale=360:640 -start_number 0 -hls_time 10 -hls_list_size 0 -f hls -hls_segment_filename out/$f/360p_%03d.ts out/$f/360p.m3u8
    ffmpeg -i $f.FullName -c:v h264_nvenc -b:v 1200k -minrate 750k -maxrate 2100k -profile:v main -y -async 1 -force_key_frames:v "expr:gte(t,n_forced*2.000)" -filter:v scale=-2:480 -map 0:v -start_number 0 -hls_time 10 -hls_list_size 0 -f hls -hls_segment_filename out/$f/video/480p_%03d.ts out/$f/video/480p.m3u8
    If($res -ge 720) {
        ffmpeg -i $f.FullName -c:v h264_nvenc -b:v 2400k -minrate 1500k -maxrate 4200k -profile:v main -force_key_frames:v "expr:gte(t,n_forced*2.000)" -filter:v scale=-2:720 -map 0:v -start_number 0 -hls_time 10 -hls_list_size 0 -f hls -hls_segment_filename out/$f/video/720p_%03d.ts out/$f/video/720p.m3u8
        [void]$sb.AppendLine( '#EXT-X-STREAM-INF:BANDWIDTH=2800000,CODECS="avc1.4d4015,mp4a.40.2",RESOLUTION=1280x720,AUDIO="aac",SUBTITLES="subs"' )
        [void]$sb.AppendLine( 'video/720p.m3u8' )
    }
    If($res -ge 900) {
        ffmpeg -i $f.FullName -c:v h264_nvenc -b:v 4800k -minrate 3000k -maxrate 8400k -profile:v main -force_key_frames:v "expr:gte(t,n_forced*2.000)" -filter:v scale=-2:1080 -map 0:v -start_number 0 -hls_time 10 -hls_list_size 0 -f hls -hls_segment_filename out/$f/video/1080p_%03d.ts out/$f/video/1080p.m3u8
        [void]$sb.AppendLine( '#EXT-X-STREAM-INF:BANDWIDTH=5000000,CODECS="avc1.4d4015,mp4a.40.2",RESOLUTION=1920x1080,AUDIO="aac",SUBTITLES="subs"' )
        [void]$sb.AppendLine( 'video/1080p.m3u8' )
    }

    $p3 = Join-Path -Path $p2 -ChildPath "/index.m3u8"
    #echo $index | Out-File -Encoding UTF8 -LiteralPath $p3
    echo $sb.ToString()
    [System.IO.File]::WriteAllLines($p3, $sb.ToString().Trim().replace("`r`n", "`n"))
}
$sw.Stop()
echo $sw.Elapsed ```
</code>```

Title: FFMPEG HLS multiple Tracks not in sync

Body:
This script works but the video doesnt sync with the sub or audio tracks.   Could someone help fix this or Help me with a NEW script.  I have been trying to figure this out with 0 luck and have had friends look at it.  I even went to FFMPEG discord and FB  asking for help from others who have posted scripts in the past.   Seems no one has a interest in this.   Please  will someone help me.

All I am trying to do is BULK encode  MKVs to HLS  with multiple resoutions  in 10 sec segments  and include all the Audio and SUb tracks that were originally in the MKV

$files = Get-ChildItem ${Get-Location}
$loco = Get-Location
$p1 = Join-Path -Path $loco -ChildPath "/out"
New-Item -ItemType Directory -Force -Path $p1

function lnCodeTransform {
    param( $String )
    echo $String
    switch ($String)
    {
        "jpn" {"jp"}
        "eng" {"en"}
        "esp" {"es"}
        "fra" {"fr"}
        "deu" {"de"}
        default {$String}
    }
}

function lnNameTransform {
    param( $String )
    switch ($String)
    {
        "jpn" {"Japanese"}
        "eng" {"English"}
        "esp" {"Spanish"}
        "fra" {"French"}
        "deu" {"German"}
        default {$String}
    }
}

foreach ($f in $files){
    if ($f.Name -eq "out"){
        continue;
    }
    $p2 = Join-Path -Path $loco -ChildPath "/out/" | Join-Path -ChildPath $f
    New-Item -ItemType Directory -Force -Path $p2/audio
    New-Item -ItemType Directory -Force -Path $p2/video
    New-Item -ItemType Directory -Force -Path $p2/subtitle
    $sb = [System.Text.StringBuilder]::new();
    [void]$sb.AppendLine( '#EXTM3U' )
    [void]$sb.AppendLine( '#EXT-X-VERSION:3' )
    #[void]$sb.AppendLine( '#EXT-X-STREAM-INF:BANDWIDTH=800000,RESOLUTION=640x360' )
    #[void]$sb.AppendLine( '360p.m3u8' )

    New-Item -ItemType Directory -Force -Path $p2
    $resStr = ffprobe -v error -select_streams v:0 -show_entries stream=height -of csv=s=x:p=0 $f.FullName;
    $res = [convert]::ToInt32($resStr)
    $audioTracks = ffprobe $f.FullName -show_entries stream=index:stream_tags=language -select_streams a -of compact=p=0:nk=1
    $audioTracks = $audioTracks.split("\n")
    foreach($audio in $audioTracks) {
        $ID = $audio.split("|")[0];
        $audioName = $audio.split("|")[1];
        ffmpeg -i $f.FullName -threads 0 -muxdelay 0 -y -map 0:$ID -async 1 -codec aac -f segment -segment_time 10 -segment_list_size 0 -segment_list out/$f/audio/audio_"$ID.m3u8" -segment_format mpegts out/$f/audio/"audio_$ID""_%d.ts"
        $name = lnNameTransform($audioName)
        $code = lnCodeTransform($audioName)
        [void]$sb.AppendLine( "#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID=`"aac`",LANGUAGE=`"$code`",NAME=`"$name`",DEFAULT=NO,AUTOSELECT=NO,URI=`"audio/audio_$ID.m3u8`"" )
    }
    $subTracks = ffprobe $f.FullName -show_entries stream=index:stream_tags=language -select_streams s -of compact=p=0:nk=1
    $subTracks = $subTracks.split("")
    foreach($subtitle in $subTracks) {
        $ID = $subtitle.split("|")[0];
        $subName = $subtitle.split("|")[1];
        ffmpeg -i $f.FullName -map 0:$ID -f segment -segment_time 10 -segment_list_size 0 -segment_list out/$f/subtitle/sub_"$subName.m3u8" -segment_format webvtt -scodec webvtt out/$f/subtitle/"sub_$subName%d.vtt"
        $name = lnNameTransform($subName)
        $code = lnCodeTransform($subName)
        [void]$sb.AppendLine( "#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID=`"subs`",LANGUAGE=`"$code`",NAME=`"$name`",FORCED=NO,AUTOSELECT=NO,URI=`"subtitle/sub_$subName.m3u8`"" )
    }

    [void]$sb.AppendLine( '#EXT-X-STREAM-INF:BANDWIDTH=1400000,CODECS="avc1.4d4015,mp4a.40.2",RESOLUTION=842x480,AUDIO="aac",SUBTITLES="subs"' )
    [void]$sb.AppendLine( 'video/480p.m3u8' )
    #ffmpeg -i $f.FullName -c:a copy -vf scale=w=640:h=360:force_original_aspect_ratio=decrease -c:a aac -ar 48000  -rc cqp -qp_p 0 -qp_i 1 -profile:v main -crf 20 -sc_threshold 0 -g 48 -keyint_min 48 -hls_time 4 -hls_playlist_type vod  -b:v 800k -maxrate 856k -bufsize 1200k -b:a 96k -hls_segment_filename out/$f/360p_%03d.ts out/$f/360p.m3u8 -vf scale=w=842:h=480:force_original_aspect_ratio=decrease -c:a aac -ar 48000 -gpu 1 -c:v h264_amf -rc cqp -qp_p 0 -qp_i 1 -profile:v main -crf 20 -sc_threshold 0 -g 48 -keyint_min 48 -hls_time 4 -hls_playlist_type vod -b:v 1400k -maxrate 1498k -bufsize 2100k -b:a 128k -hls_segment_filename out/$f/480p_%03d.ts out/$f/480p.m3u8 -vf  scale=w=1280:h=720:force_original_aspect_ratio=decrease -c:a aac -ar 48000 -gpu 1 -c:v h264_amf -rc cqp -qp_p 0 -qp_i 1 -profile:v main -crf 20 -sc_threshold 0 -g 48 -keyint_min 48 -hls_time 4 -hls_playlist_type vod -b:v 2800k -maxrate 2996k -bufsize 4200k -b:a 128k -hls_segment_filename out/$f/720p_%03d.ts out/$f/720p.m3u8 -vf  scale=w=1920:h=1080:force_original_aspect_ratio=decrease -c:a aac -ar 48000 -gpu 1 -c:v h264_amf -rc cqp -qp_p 0 -qp_i 1 -profile:v main -crf 20 -sc_threshold 0 -g 48 -keyint_min 48 -hls_time 4 -hls_playlist_type vod -b:v 5000k -maxrate 5350k -bufsize 7500k -b:a 192k -hls_segment_filename out/$f/1080p_%03d.ts out/$f/1080p.m3u8
    #ffmpeg -hwaccel auto -hwaccel_device 0 -i $f.FullName -c:v h264 -profile:v main -c:a aac -filter:v scale=360:640 -ar 48000  -rc cqp -qp_p 0 -qp_i 1 -profile:v main -crf 23 -sc_threshold 0 -g 48 -b:v 800k -maxrate 856k -bufsize 1200k -b:a 96k  -keyint_min 4 -start_number 0 -hls_time 10 -hls_playlist_type vod  -hls_list_size 0 -f hls -hls_segment_filename out/$f/360p_%03d.ts out/$f/360p.m3u8
    #ffmpeg -hwaccel auto -hwaccel_device 0 -i $f.FullName -c:v h264 -profile:v main -c:a aac -filter:v scale=360:640 -start_number 0 -hls_time 10 -hls_list_size 0 -f hls -hls_segment_filename out/$f/360p_%03d.ts out/$f/360p.m3u8
    ffmpeg -i $f.FullName -c:v h264 -async 1 -profile:v main -y -filter:v scale="trunc(oh*a/2)*2:480" -map 0:v -start_number 0 -hls_time 10 -hls_list_size 0 -f hls -hls_segment_filename out/$f/video/480p_%03d.ts out/$f/video/480p.m3u8
    If($res -ge 720) {
        ffmpeg -i $f.FullName -c:v h264 -profile:v main -filter:v scale="trunc(oh*a/2)*2:720" -map 0:v -start_number 0 -hls_time 10 -hls_list_size 0 -f hls -hls_segment_filename out/$f/video/720p_%03d.ts out/$f/video/720p.m3u8
        [void]$sb.AppendLine( '#EXT-X-STREAM-INF:BANDWIDTH=2800000,CODECS="avc1.4d4015,mp4a.40.2",RESOLUTION=1280x720,AUDIO="aac",SUBTITLES="subs"' )
        [void]$sb.AppendLine( 'video/720p.m3u8' )
    }
    If($res -ge 1080) {
        ffmpeg -i $f.FullName -c:v h264 -profile:v main -filter:v scale="trunc(oh*a/2)*2:1080" -map 0:v -start_number 0 -hls_time 10 -hls_list_size 0 -f hls -hls_segment_filename out/$f/video/1080p_%03d.ts out/$f/video/1080p.m3u8
        [void]$sb.AppendLine( '#EXT-X-STREAM-INF:BANDWIDTH=5000000,CODECS="avc1.4d4015,mp4a.40.2",RESOLUTION=1920x1080,AUDIO="aac",SUBTITLES="subs"' )
        [void]$sb.AppendLine( 'video/1080p.m3u8' )
    }

    $p3 = Join-Path -Path $p2 -ChildPath "/index.m3u8"
    #echo $index | Out-File -Encoding UTF8 -LiteralPath $p3
    echo $sb.ToString()
    [System.IO.File]::WriteAllLines($p3, $sb.ToString().Trim().replace("`r`n", "`n"))
}
$sw.Stop()
echo $sw.Elapsed ```


问:
Group items inside of another group
I want to group the following collection by category and sum its total value, then create a subcategory attribute, on same structure, summing subcategories if more than one equal.

```<code>[
  {
    "_id": 1,
    "date": ISODate("2019-10-10T00:00:00.000Z"),
    "description": "INTERNET BILL",
    "credit": "",
    "debit": "-100.00",
    "category": "home",
    "subcategory": "internet",
    "__v": 0
  },
  {
    "_id": 2,
    "date": ISODate("2019-10-10T00:00:00.000Z"),
    "description": "WATER BILL",
    "credit": "",
    "debit": "-150.00",
    "category": "home",
    "subcategory": "water",
    "__v": 0
  },
  {
    "_id": 3,
    "date": ISODate("2019-10-10T00:00:00.000Z"),
    "description": "MC DONALDS",
    "credit": "",
    "debit": "-30.00",
    "category": "food",
    "subcategory": "restaurants",
    "__v": 0
  },
{
    "_id": 4,
    "date": ISODate("2019-10-10T00:00:00.000Z"),
    "description": "BURGER KING",
    "credit": "",
    "debit": "-50.00",
    "category": "food",
    "subcategory": "restaurants",
    "__v": 0
  },
  {
    "_id": 5,
    "date": ISODate("2019-10-10T00:00:00.000Z"),
    "description": "WALMART",
    "credit": "",
    "debit": "-20.00",
    "category": "food",
    "subcategory": "groceries",
    "__v": 0
  },
]
</code>```

Desireble output:

```<code>[
  {
    "_id": "home",
    "total": "-250.00",
    "subcategory" : [
     {"id": "internet", "total": "-100"},
     {"id": "water", "total": "-150"}
    ]
  },
  {
    "_id": "food",
    "total": "-100.00",
    "subcategory" : [
      {"id": "restaurants", "total": "-80"},
      {"id": "groceries", "total": "-20"}
    ]
  }
]

</code>```

With the following query, I've almost achieved it, but I haven't find a way to sum values on subcategories.

```<code>db.getCollection('expenses').aggregate([
    {$match:
        {"date" : { "$gte" : new Date("11-10-2019"), "$lte": new Date("2019-10-11") }}
    },
    {$group: {
        _id: "$category",
        total: { $sum: { $toDouble: { $cond: { if: { $ne: [ "$debit", ""] }, then: "$debit", else: "$credit" } } } },
        subcategories: { $addToSet: {id: "$subcategory" }},

   }}
])

</code>```

答:
You can to $group twice (by subcategory first):

```<code>db.collection.aggregate([
    {
        $group: {
            _id: { category: "$category", subcategory: "$subcategory" },
            total: { $sum: { $toDouble: "$debit" } }
        }
    },
    {
        $group: {
            _id: "$_id.category",
            total: { $sum: "$total" },
            subcategories: { $push: { id: "$_id.subcategory", total: "$total" } }
        }
    }
])
</code>```

Mongo Playground

Title: Group items inside of another group

Body:
I want to group the following collection by category and sum its total value, then create a subcategory attribute, on same structure, summing subcategories if more than one equal.

[
  {
    "_id": 1,
    "date": ISODate("2019-10-10T00:00:00.000Z"),
    "description": "INTERNET BILL",
    "credit": "",
    "debit": "-100.00",
    "category": "home",
    "subcategory": "internet",
    "__v": 0
  },
  {
    "_id": 2,
    "date": ISODate("2019-10-10T00:00:00.000Z"),
    "description": "WATER BILL",
    "credit": "",
    "debit": "-150.00",
    "category": "home",
    "subcategory": "water",
    "__v": 0
  },
  {
    "_id": 3,
    "date": ISODate("2019-10-10T00:00:00.000Z"),
    "description": "MC DONALDS",
    "credit": "",
    "debit": "-30.00",
    "category": "food",
    "subcategory": "restaurants",
    "__v": 0
  },
{
    "_id": 4,
    "date": ISODate("2019-10-10T00:00:00.000Z"),
    "description": "BURGER KING",
    "credit": "",
    "debit": "-50.00",
    "category": "food",
    "subcategory": "restaurants",
    "__v": 0
  },
  {
    "_id": 5,
    "date": ISODate("2019-10-10T00:00:00.000Z"),
    "description": "WALMART",
    "credit": "",
    "debit": "-20.00",
    "category": "food",
    "subcategory": "groceries",
    "__v": 0
  },
]

Desireble output:

[
  {
    "_id": "home",
    "total": "-250.00",
    "subcategory" : [
     {"id": "internet", "total": "-100"},
     {"id": "water", "total": "-150"}
    ]
  },
  {
    "_id": "food",
    "total": "-100.00",
    "subcategory" : [
      {"id": "restaurants", "total": "-80"},
      {"id": "groceries", "total": "-20"}
    ]
  }
]

With the following query, I've almost achieved it, but I haven't find a way to sum values on subcategories.

db.getCollection('expenses').aggregate([
    {$match:
        {"date" : { "$gte" : new Date("11-10-2019"), "$lte": new Date("2019-10-11") }}
    },
    {$group: {
        _id: "$category",
        total: { $sum: { $toDouble: { $cond: { if: { $ne: [ "$debit", ""] }, then: "$debit", else: "$credit" } } } },
        subcategories: { $addToSet: {id: "$subcategory" }},

   }}
])

Body:
You can to $group twice (by subcategory first):

db.collection.aggregate([
    {
        $group: {
            _id: { category: "$category", subcategory: "$subcategory" },
            total: { $sum: { $toDouble: "$debit" } }
        }
    },
    {
        $group: {
            _id: "$_id.category",
            total: { $sum: "$total" },
            subcategories: { $push: { id: "$_id.subcategory", total: "$total" } }
        }
    }
])

Mongo Playground


问:
Need Help: AttributeError: "SQLAlchemy" object has no attribute 'Models'
AttributeError: sqlalchemy object has no attribute "Models" error is occurring. I already installed all requirements like pip install sqlalchemy, flask-sqlalchemy, psycopy2-binary. this file name is create.py

```<code>import os

from flask import Flask, render_template, request
from models import *

app = Flask(__name__)

app.config["SQLALchemy_DATABASE_URI"] = os.getenv("DATABASE_URL")
app.config["SQLALchemy_TRACK_MODIFICATIONS"] = False
db.init_app(app)

def main():
   db.create_all()
if __name__ == "__main__":
    with app.app_context():
        main()
</code>```

this file is models.py

```<code> from flask_sqlalchemy import SQLAlchemy

db=SQLAlchemy()

class Flight(db.Models):
    __tablename__ = "flights"
    id = db.Column(db.Integer, primary_key=True)
    origin = db.Column(db.String, nullable=False)
    destination = db.Column(db.String, nullable=False)
    duration = db.Column(db.Integer, nullable=False)

class Passenger(db.Models):
    __tablename__ = "passengers"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, nullable=False)
    flight_id = db.Column(db.Integer, db.ForeignKey("flights.id",
nullable=False))
</code>```

output is:

Traceback (most recent call last):
  File "create.py", line 4, in
    from models import *
  File "D:\web\flaskrun\models.py", line 5, in
    class Flight(db.Models):
AttributeError: 'SQLAlchemy' object has no attribute 'Models'

答: It should be db.Model instead of db.Models.

Body:
AttributeError: sqlalchemy object has no attribute "Models" error is occurring. I already installed all requirements like pip install sqlalchemy, flask-sqlalchemy, psycopy2-binary. this file name is create.py

import os

from flask import Flask, render_template, request
from models import *

app = Flask(__name__)

app.config["SQLALchemy_DATABASE_URI"] = os.getenv("DATABASE_URL")
app.config["SQLALchemy_TRACK_MODIFICATIONS"] = False
db.init_app(app)

def main():
   db.create_all()
if __name__ == "__main__":
    with app.app_context():
        main()

this file is models.py

 from flask_sqlalchemy import SQLAlchemy

db=SQLAlchemy()

class Flight(db.Models):
    __tablename__ = "flights"
    id = db.Column(db.Integer, primary_key=True)
    origin = db.Column(db.String, nullable=False)
    destination = db.Column(db.String, nullable=False)
    duration = db.Column(db.Integer, nullable=False)

class Passenger(db.Models):
    __tablename__ = "passengers"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, nullable=False)
    flight_id = db.Column(db.Integer, db.ForeignKey("flights.id",
nullable=False))

output is:

Traceback (most recent call last):
  File "create.py", line 4, in
    from models import *
  File "D:\web\flaskrun\models.py", line 5, in
    class Flight(db.Models):
AttributeError: 'SQLAlchemy' object has no attribute 'Models'


问:
React Js map function gives an "not a function" error
I'm trying to map through objects to display their values in my React JS project. It looks like I can't access values of the objects within objects using the map function, values simply are not displayed, or if I try to use (.split("/p")) it gives me an error saying "split is not a function".

Link to codesandbox

this is my code:

```<code>import React from "react";
import { studies } from "./studies";

import "./styles.css";

const Data = ({ title, text, number, numberdesc }) => {
  return (
    <>
      <div style={{ margin: "1rem" }}>{title}</div>
      <div style={{ margin: "1rem" }}>{text}</div>
      <div>{number}</div>
      <div>{numberdesc}</div>
    </>
  );
};

function App() {
  const appComponent = studies.map((post, i) => {
    console.log(studies);
    return (
      <Data
        key={i}
        number={studies[i].post.number}
        title={studies[i].post.title}
        text={studies[i].post.text
          .split("/p")
          .reduce((total, line) => [total, <br />, <br />, line])}
      />
    );
  });
  return <>{appComponent}</>;
}

export default App;
</code>```

and {studies} file:

```<code>export const studies = [
  {
    id: "first",
    text: "1st Post",
    post: {
      data: [
        { number: "100", numberdesc: "description1" },
        { number: "200", numberdesc: "description2" },
        { number: "300", numberdesc: "description3" }
      ],

      text: [
        {
          title: "Title1 from the 1st post",
          text: "Text1 from the 1st post."
        },
        {
          title: "Title2 from the 1st post",
          text: "Text2 from the 1st post."
        },
        {
          title: "Title3 from the 1st post",
          text: "Text3 from the 1st post"
        }
      ]
    }
  },
  {
    id: "second",
    text: "2nd Post",
    post: {
      data: [
        { number: "100", numberdesc: "description1" },
        { number: "200", numberdesc: "description2" },
        { number: "300", numberdesc: "description3" }
      ],

      text: [
        {
          title: "Title1 from the 2nd post",
          text: "Text1 from the 2nd post "
        },
        {
          title: "Title2 from the 2nd post",
          text: "Text2 /p from the 2nd post"
        },
        {
          title: "Title3 from the 2nd post",
          text: "Text3 from the 2nd post"
        }
      ]
    }
  }
];

</code>```

What I want to do is to access data and text values for each post, and display them in my Project. Any help and suggestion is greatly appreciated,

Thank you.

答:
Is this what you're looking for?

function App() {
  const appComponent = studies.map(study =>
    study.post.data.map((data, k) => (
      <Data
        key={k}
        number={data.number}
        numberdesc={data.numberdesc}
        title={study.post.text[k].title}
        text={study.post.text[k].text}
      />
    ))
  );
  return <>{appComponent}</>;
}
```

Note I arbitrarily zipped data[k]'s number and numberdesc with text[k]'s title and text, but that might not necessarily be what you intend to display.

The above will likely break in case your data and text arrays do not have the same length in any given study.

See it here.

Body:
I'm trying to map through objects to display their values in my React JS project. It looks like I can't access values of the objects within objects using the map function, values simply are not displayed, or if I try to use (.split("/p")) it gives me an error saying "split is not a function".

Link to codesandbox

this is my code:

import React from "react";
import { studies } from "./studies";

import "./styles.css";

const Data = ({ title, text, number, numberdesc }) => {
  return (
    <>

{title}

{text}

{number}

{numberdesc}

    </>
  );
};

function App() {
  const appComponent = studies.map((post, i) => {
    console.log(studies);
    return (
      <Data
        key={i}
        number={studies[i].post.number}
        title={studies[i].post.title}
        text={studies[i].post.text
          .split("/p")
          .reduce((total, line) => [total,
,
, line])}
      />
    );
  });
  return <>{appComponent}</>;
}

export default App;

and {studies} file:

export const studies = [
  {
    id: "first",
    text: "1st Post",
    post: {
      data: [
        { number: "100", numberdesc: "description1" },
        { number: "200", numberdesc: "description2" },
        { number: "300", numberdesc: "description3" }
      ],

      text: [
        {
          title: "Title1 from the 1st post",
          text: "Text1 from the 1st post."
        },
        {
          title: "Title2 from the 1st post",
          text: "Text2 from the 1st post."
        },
        {
          title: "Title3 from the 1st post",
          text: "Text3 from the 1st post"
        }
      ]
    }
  },
  {
    id: "second",
    text: "2nd Post",
    post: {
      data: [
        { number: "100", numberdesc: "description1" },
        { number: "200", numberdesc: "description2" },
        { number: "300", numberdesc: "description3" }
      ],

      text: [
        {
          title: "Title1 from the 2nd post",
          text: "Text1 from the 2nd post "
        },
        {
          title: "Title2 from the 2nd post",
          text: "Text2 /p from the 2nd post"
        },
        {
          title: "Title3 from the 2nd post",
          text: "Text3 from the 2nd post"
        }
      ]
    }
  }
];

What I want to do is to access data and text values for each post, and display them in my Project. Any help and suggestion is greatly appreciated,

Thank you.

Body:
Is this what you're looking for?

function App() {
  const appComponent = studies.map(study =>
    study.post.data.map((data, k) => (
      <Data
        key={k}
        number={data.number}
        numberdesc={data.numberdesc}
        title={study.post.text[k].title}
        text={study.post.text[k].text}
      />
    ))
  );
  return <>{appComponent}</>;
}

Note I arbitrarily zipped data[k]'s number and numberdesc with text[k]'s title and text, but that might not necessarily be what you intend to display.

The above will likely break in case your data and text arrays do not have the same length in any given study.

See it here.


问:
Soft delete in laravel and model binding
I have applied a soft delete as mentioned in the documentation for Laravel 5.2. I have one [get] route and another [delete] route:

```<code>Route::get('profile/{id}/delete', 'uses' => 'ProfileController@delete');
Route::delete('profile/{id}', 'uses' => 'ProfileController@destroy');
</code>```

The controller methods as following:

```<code>public function delete($id)
{
    $profile = Profile::with('contract.division')->withTrashed()->where('id', $id)->first();

    return view('pages.profiles.delete', compact('profile'));
}

public function destroy($id)
{
    $profile = Profile::withTrashed()->find($id);

    $profile->delete();

    return redirect('employees/list');
}
</code>```

With this code when I try with non-trashed id I got the content. If I tried with trashed ID I got the following error:

No query results for model [App\Profile]. (View: \xyz\xyz\xyz\resources\views\pages\profiles\delete.blade.php)

Despite the error means that there is no query results when I dd($profile) in the delete method I got the full model with relations. So what is going wrong?!

When type hinted the profile function delete(Profile $id) I got 404 for trashed model, how exactly I should fix the routes to have the profile ready withTrashed() ?

答:
The best way that I found is use suffix or prefix on bind name.

Example:

$controllerPath = 'UsersController';
$routeName = 'users';
$routeBindNameTrashed = "user_trashed";
Route::bind($routeBindNameTrashed, function($userId) use () {
  return App\User::onlyTrashed()->findOrFail($userId);
});

Route::put("$routeName/{{$routeBindNameTrashed}}/restore", "{$controllerPath}@restore")->name("{$routeName}.restore");
Route::delete("$routeName/{{$routeBindNameTrashed}}/force", "{$controllerPath}@forceDelete")->name("{$routeName}.force-delete");

```

My real example

Complete example: https://stackoverflow.com/a/62143846/9813428

Body:
I have applied a soft delete as mentioned in the documentation for Laravel 5.2. I have one [get] route and another [delete] route:

Route::get('profile/{id}/delete', 'uses' => 'ProfileController@delete');
Route::delete('profile/{id}', 'uses' => 'ProfileController@destroy');

The controller methods as following:

public function delete($id)
{
    $profile = Profile::with('contract.division')->withTrashed()->where('id', $id)->first();

    return view('pages.profiles.delete', compact('profile'));
}

public function destroy($id)
{
    $profile = Profile::withTrashed()->find($id);

    $profile->delete();

    return redirect('employees/list');
}

With this code when I try with non-trashed id I got the content. If I tried with trashed ID I got the following error:

No query results for model [App\Profile]. (View: \xyz\xyz\xyz\resources\views\pages\profiles\delete.blade.php)

Despite the error means that there is no query results when I dd($profile) in the delete method I got the full model with relations. So what is going wrong?!

When type hinted the profile function delete(Profile $id) I got 404 for trashed model, how exactly I should fix the routes to have the profile ready withTrashed() ?

Body:
The best way that I found is use suffix or prefix on bind name.

Example:

$controllerPath = 'UsersController';
$routeName = 'users';
$routeBindNameTrashed = "user_trashed";
Route::bind($routeBindNameTrashed, function($userId) use () {
  return App\User::onlyTrashed()->findOrFail($userId);
});

Route::put("$routeName/{{$routeBindNameTrashed}}/restore", "{$controllerPath}@restore")->name("{$routeName}.restore");
Route::delete("$routeName/{{$routeBindNameTrashed}}/force", "{$controllerPath}@forceDelete")->name("{$routeName}.force-delete");

My real example

Complete example: https://stackoverflow.com/a/62143846/9813428


问:
Dash Data Table Horizontal Scroll Bar Default to Right
I have a Data Table in Dash (python) that works very well.  I would like the scroll bar to default to the right - that is, to show the most right information in the data table.  The current default is the scroll bar is set to the left.  I am using time series data for a finance table, so I want to show the most current year, which is all the way to the right (don't want to make it left) and have the scroll bar set so that its show the right and then you would need to scroll to the left to see the left.

Here is what I have and it works fine except for the issue above:

```<code>app = dash.Dash(__name__)

app.layout = dash_table.DataTable(
    id='table',
    columns=[{"name": i, "id": i} for i in df.columns],
    data=df.to_dict('records'),
    fixed_columns={'headers': True, 'data': 1},
    fixed_rows={'headers': True, 'data': 1},
    # style_cell={'textAlign': 'left'},
    style_cell={'fontFamily': 'sans-serif', 'fontSize': '12px', 'border': '0px'}, #, 'boxShadow': '10 0'},
    style_table={'minWidth': '60%'},
    style_cell_conditional=[
        {
            'if': {'column_id': i},
            'textAlign': 'left',
            'fontWeight': 'bold'
        } for i in ['$ in millions']#, 'C']

    ],
    style_header={
        'backgroundColor': 'white',
        'fontWeight': 'bold',
        'borderBottom': '1px solid black'
    },
    # style_as_list_view=True,
)
# $ in millions
if __name__ == '__main__':
    app.run_server()
</code>```

答: If you were making your Dash application using JavaScript, the solution would have been pretty straight forward, unfortunately there is no straight forward answer other than creating 'assets' folder and creating a HTML file with a function to scroll right. The easiest way to tackle this, in my opinion, is to just re-arranging the columns backward by doing df = df.columns[::-1] or by slicing and rearranging the df.

Body:
I have a Data Table in Dash (python) that works very well.  I would like the scroll bar to default to the right - that is, to show the most right information in the data table.  The current default is the scroll bar is set to the left.  I am using time series data for a finance table, so I want to show the most current year, which is all the way to the right (don't want to make it left) and have the scroll bar set so that its show the right and then you would need to scroll to the left to see the left.

Here is what I have and it works fine except for the issue above:

app = dash.Dash(__name__)

app.layout = dash_table.DataTable(
    id='table',
    columns=[{"name": i, "id": i} for i in df.columns],
    data=df.to_dict('records'),
    fixed_columns={'headers': True, 'data': 1},
    fixed_rows={'headers': True, 'data': 1},
    # style_cell={'textAlign': 'left'},
    style_cell={'fontFamily': 'sans-serif', 'fontSize': '12px', 'border': '0px'}, #, 'boxShadow': '10 0'},
    style_table={'minWidth': '60%'},
    style_cell_conditional=[
        {
            'if': {'column_id': i},
            'textAlign': 'left',
            'fontWeight': 'bold'
        } for i in ['$ in millions']#, 'C']

    ],
    style_header={
        'backgroundColor': 'white',
        'fontWeight': 'bold',
        'borderBottom': '1px solid black'
    },
    # style_as_list_view=True,
)
# $ in millions
if __name__ == '__main__':
    app.run_server()


问:
What's the difference between non-unique key lookup and index range scan?
I don't know what's the difference between non-unique key lookup and index range scan because I think both of them return rows which follow a condition like the operator "=" o "<".</p>

答:
```<code>WHERE x = 123   -- with INDEX(x)
</code>```

will scan all the row or rows with x=123.  It performs identically to

```<code>WHERE y BETWEEN 22 and 33   -- with any kind of index on y
</code>```

Both will drill down the BTree of the index to find the first match.  Then it will scan forward until the value no longer matches.

However, these work differently:

```<code>WHERE x = 123              AND b >= 88
WHERE y BETWEEN 22 and 33  AND b >= 88
</code>```

The first can take advantage of INDEX(x,b).  It locates the first x=123 and b=88, then scans until x > 123.

The second cannot do anything like that.  No composite index will really handle both y and b.

"Index range scan" and "table range scan" are similar, but applied to different BTrees.  The "table" is contained in a BTree that is ordered by the PRIMARY KEY so, arguably, a "table range scan" is an "index range scan"

A "unique key lookup" and a "non-unique key lookup" differ in that the unique one can stop after finding 1 row (or no rows), where as the non-unique one must keep going until a non-matching value is encountered (or LIMIT is reached).

Body:
WHERE x = 123   -- with INDEX(x)

will scan all the row or rows with x=123.  It performs identically to

WHERE y BETWEEN 22 and 33   -- with any kind of index on y

Both will drill down the BTree of the index to find the first match.  Then it will scan forward until the value no longer matches.

However, these work differently:

WHERE x = 123              AND b >= 88
WHERE y BETWEEN 22 and 33  AND b >= 88

The first can take advantage of INDEX(x,b).  It locates the first x=123 and b=88, then scans until x > 123.

The second cannot do anything like that.  No composite index will really handle both y and b.

"Index range scan" and "table range scan" are similar, but applied to different BTrees.  The "table" is contained in a BTree that is ordered by the PRIMARY KEY so, arguably, a "table range scan" is an "index range scan"

A "unique key lookup" and a "non-unique key lookup" differ in that the unique one can stop after finding 1 row (or no rows), where as the non-unique one must keep going until a non-matching value is encountered (or LIMIT is reached).


问:
Create a parent activity instead of continuing when a child activity is finished
Is that possible that a parent activity is recreated instead of continuation when its child activity is finished (it was destroyed by "back" key)..

A problem is the following:
I use CameraX in activity A (parent) and B (child).
When I return from the activity B into A I try bind CameraX but it happens before B is totally destroyed and camera doesn't launch.
I tried to find out the moment when B is destroyed is A but didn't find anything for that.

答:
You can do that by clearing the back stack at both activities by attaching FLAG_ACTIVITY_NEW_TASK and FLAG_ACTIVITY_CLEAR_TOP flags to the intent.

Assuming that the original activity is Activity1, and the second activity is Activit2.

Then the code at Activity1 whenever you want to start Activity2 will be:

```<code>Intent intent = new Intent(Activity1.this, Activity2.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
</code>```

And when you press the back button at Activity2, start over Activity1 by overriding onBackPrssed()

```<code>@Override
public void onBackPressed() {
    Intent intent = new Intent(Activity2.this, Activity1.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
    finish();
}
</code>```

Body:
You can do that by clearing the back stack at both activities by attaching FLAG_ACTIVITY_NEW_TASK and FLAG_ACTIVITY_CLEAR_TOP flags to the intent.

Assuming that the original activity is Activity1, and the second activity is Activit2.

Then the code at Activity1 whenever you want to start Activity2 will be:

Intent intent = new Intent(Activity1.this, Activity2.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();

And when you press the back button at Activity2, start over Activity1 by overriding onBackPrssed()

@Override
public void onBackPressed() {
    Intent intent = new Intent(Activity2.this, Activity1.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
    finish();
}


问:
How to calculate the number of matching positions among two strings?
I have two vectors with characters in each cell.

```<code>Ex:       Vet 1.     Vet 2.

Row 1.    AAABBC     BCABDE

Row 2.    EDAACD     ADBBEE

...         ...        ...

Row n.    CCCDAC     EECEAC
</code>```

Comparing the characters in same row, e.g., AAABBC and BCABDE, we have two matches in the same position (A - 3rd position - and B - 4th position).
I want to create a third vector (Vet 3) containing the number of matches between Vet 1 and Vet 2 for characters in the same row.

Output

```<code>         Vet. 3

Row 1.     2

Row 2.     1

...      ...

Row n.     3
</code>```

I don't know how to do it. Can someone help me?

答:
We can split every character in both the columns and count how many of them match. In case, number of characters are not the same in both the columns we can use the one only minimum number of characters to compare.

Assuming df is your dataframe name and col1, col2 are column names.

```<code>mapply(function(x, y) {
   len <- min(length(x), length(y))
   sum(x[1:len] == y[1:len])
}, strsplit(df$col1, ''), strsplit(df$col2, ''))

#[1] 2 1 3
</code>```

If we are guaranteed to have same number of characters in both the columns we can simplify this :

```<code>mapply(function(x, y) sum(x == y), strsplit(df$col1, ''), strsplit(df$col2, ''))
</code>```

data

```<code>df <- structure(list(col1 = c("AAABBC", "EDAACD", "CCCDAC"), col2 = c("BCABDE",
"ADBBEE", "EECEAC")), class = "data.frame", row.names = c(NA, -3L))
</code>```

Body:
I have two vectors with characters in each cell.

Ex:       Vet 1.     Vet 2.

Row 1.    AAABBC     BCABDE

Row 2.    EDAACD     ADBBEE

...         ...        ...

Row n.    CCCDAC     EECEAC

Comparing the characters in same row, e.g., AAABBC and BCABDE, we have two matches in the same position (A - 3rd position - and B - 4th position).
I want to create a third vector (Vet 3) containing the number of matches between Vet 1 and Vet 2 for characters in the same row.

Output

         Vet. 3

Row 1.     2

Row 2.     1

...      ...

Row n.     3

I don't know how to do it. Can someone help me?

Body:
We can split every character in both the columns and count how many of them match. In case, number of characters are not the same in both the columns we can use the one only minimum number of characters to compare.

Assuming df is your dataframe name and col1, col2 are column names.

mapply(function(x, y) {
   len <- min(length(x), length(y))
   sum(x[1:len] == y[1:len])
}, strsplit(df$col1, ''), strsplit(df$col2, ''))

#[1] 2 1 3

If we are guaranteed to have same number of characters in both the columns we can simplify this :

mapply(function(x, y) sum(x == y), strsplit(df$col1, ''), strsplit(df$col2, ''))

data

df <- structure(list(col1 = c("AAABBC", "EDAACD", "CCCDAC"), col2 = c("BCABDE",
"ADBBEE", "EECEAC")), class = "data.frame", row.names = c(NA, -3L))


问:
Not obtaining the correct output for the following code
I'm curious as to why the output for the following code is 14 1. When I go through the code myself, I'm ending up with counter being equal to 2, and count being equal to 4. I want to make sure that we are only printing the second index, so we only go through the loop two times, right?

```<code> package mix4;

public class Mix4 {

    int counter = 0;

    public static void main(String[] args) {
        int count = 0;
        Mix4[] m4a = new Mix4[20];
        int x = 0;
        while(x < 9) {
            m4a[x] = new Mix4();
            m4a[x].counter = m4a[x].counter + 1;
            count = count + 1;
            count = count + m4a[x].maybeNew(x);
            x = x + 1;
        }
        System.out.println(count + " " + m4a[1].counter);
    }

        public static int maybeNew(int index) {
            if (index < 5) {
                Mix4 m4 = new Mix4();
                m4.counter = m4.counter + 1;
                return 1;
            }

            return 0;

        }

    }
</code>```

答:
This code in your if statement does nothing

```<code>Mix4 m4 = new Mix4();
m4.counter = m4.counter + 1;
</code>```

m4 immediately goes out of scope and is not used.

Your code could be changed to

```<code>count = count + maybeNew(x);  // static method
</code>```

and maybeNew is the same as

```<code>if (index < 5) {
        return 1;
    }

return 0;
</code>```

not sure what logic you are wanting, but this is the logic you have wrote

Body:
I'm curious as to why the output for the following code is 14 1. When I go through the code myself, I'm ending up with counter being equal to 2, and count being equal to 4. I want to make sure that we are only printing the second index, so we only go through the loop two times, right?

 package mix4;

public class Mix4 {

    int counter = 0;

    public static void main(String[] args) {
        int count = 0;
        Mix4[] m4a = new Mix4[20];
        int x = 0;
        while(x < 9) {
            m4a[x] = new Mix4();
            m4a[x].counter = m4a[x].counter + 1;
            count = count + 1;
            count = count + m4a[x].maybeNew(x);
            x = x + 1;
        }
        System.out.println(count + " " + m4a[1].counter);
    }

        public static int maybeNew(int index) {
            if (index < 5) {
                Mix4 m4 = new Mix4();
                m4.counter = m4.counter + 1;
                return 1;
            }

            return 0;

        }

    }

Body:
This code in your if statement does nothing

Mix4 m4 = new Mix4();
m4.counter = m4.counter + 1;

m4 immediately goes out of scope and is not used.

Your code could be changed to

count = count + maybeNew(x);  // static method

and maybeNew is the same as

if (index < 5) {
        return 1;
    }

return 0;

not sure what logic you are wanting, but this is the logic you have wrote


问:
Nodejs Not able to create directory
I want to post an image to server.But before that I want to make sure that directory is create, before placing an image to a correct folder.The folder that I want to create is year/month/day/[image]. I am able to generate the folder  on my local PC, but when I want to apply on the server, an error message is displayed and the folder is not created.I don't know what mistake that I have made, I hope someone can help me solve this problem.
Thank you in advance.

PWD

ERROR

return binding.mkdir(pathModule._makeLong(path),  Error: ENOENT: no
  such file or directory, mkdir
  '/home/eis/development/eis-api-dev/picture/2020/06/01/'

CODE

```<code>var storage = multer.diskStorage({
     destination: function (req, file, cb) {
         ///output: home/eis/development/eis-api-dev/picture/2020/06/01/
          const dir = path.join(__dirname,_const.IMAGE_FILE_PATH+_const.generateImagePath(null,null,null));
          console.log("path:"+dir);
          fs.exists(dir,exists =>{
               if(!exists){
                    //mkdirp.sync(dir);
                    return fs.mkdirSync(dir,{recursive: true},error => cb(error,dir));

               }
               return cb(null,dir)
          });

     },
     filename: function (req, file, cb) {
       cb(null, file.originalname)
     }
   })
</code>```

答:
try to create using mkdirp </p>

```<code> if (!fs.existsSync(directoryPath)){
            mkdirp(directoryPath, function (err) {
              if (err) {
                console.log("Error Creating Directory "+directoryPath);
              }
              else {
                    console.log("Creating Directory "+directoryPath);
              }
   }
</code>```

Title: Nodejs Not able to create directory

Body:
I want to post an image to server.But before that I want to make sure that directory is create, before placing an image to a correct folder.The folder that I want to create is year/month/day/[image]. I am able to generate the folder  on my local PC, but when I want to apply on the server, an error message is displayed and the folder is not created.I don't know what mistake that I have made, I hope someone can help me solve this problem.
Thank you in advance.

PWD

ERROR

return binding.mkdir(pathModule._makeLong(path),  Error: ENOENT: no
  such file or directory, mkdir
  '/home/eis/development/eis-api-dev/picture/2020/06/01/'

CODE

var storage = multer.diskStorage({
     destination: function (req, file, cb) {
         ///output: home/eis/development/eis-api-dev/picture/2020/06/01/
          const dir = path.join(__dirname,_const.IMAGE_FILE_PATH+_const.generateImagePath(null,null,null));
          console.log("path:"+dir);
          fs.exists(dir,exists =>{
               if(!exists){
                    //mkdirp.sync(dir);
                    return fs.mkdirSync(dir,{recursive: true},error => cb(error,dir));

               }
               return cb(null,dir)
          });

     },
     filename: function (req, file, cb) {
       cb(null, file.originalname)
     }
   })

Body:
try to create using mkdirp

 if (!fs.existsSync(directoryPath)){
            mkdirp(directoryPath, function (err) {
              if (err) {
                console.log("Error Creating Directory "+directoryPath);
              }
              else {
                    console.log("Creating Directory "+directoryPath);
              }
   }


问:
Using jQuery to post back to a controller
I'm using jQuery to post back to my controller, but i'm wondering how you pass values as parameters in the ActionResult.  For example:

I have a jQuery post:

```<code>$.post("Home\PostExample")
</code>```

but i would like to include a value from a dropdown menu:

```<code>@Html.DropDownListFor(m => m.Example, Model.Example, new { @id = "exampleCssId" })
</code>```

into an Actionresult:

```<code>[HttpPost]
public ActionResult PostExample(string myString)
{
    //TODO: Write contents of ActionResult
}
</code>```

Any help would be appreciated.

Thanks.

答:
I think this should work:</p>

```<code>$.post("Home/PostExample", { myString: $("#exampleCssId").val() } );
</code>```

Body:
I'm using jQuery to post back to my controller, but i'm wondering how you pass values as parameters in the ActionResult.  For example:

I have a jQuery post:

$.post("Home\PostExample")

but i would like to include a value from a dropdown menu:

@Html.DropDownListFor(m => m.Example, Model.Example, new { @id = "exampleCssId" })

into an Actionresult:

[HttpPost]
public ActionResult PostExample(string myString)
{
    //TODO: Write contents of ActionResult
}

Any help would be appreciated.

Thanks.

Body:
I think this should work:

$.post("Home/PostExample", { myString: $("#exampleCssId").val() } );


问:
CSS Transition When Moved
When the first element gets deleted, I want to make the other elements to slide into their new places instead of going instantly there. Using the code below, all of the other boxes move instantly to their new positions when you delete the first one. Eventually, there will be many rows of boxes.

var pile = document.getElementById("pile");
function removeFirst(){
  pile.removeChild(event.target);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box{
  border: 1px solid black;
  padding: 20px;
}
#pile{
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}</code>```

I'm the first box

I'm the second box

I'm the third box

I'm the fourth box

```

答:
You can do this using CSS.

Try this one

```<code>#pile{
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    margin-left: 144px;
    transition: padding-left 1s;
}
.box{
    border: 1px solid black;
    padding: 20px;
    transition: margin-left 1s;
}
.box:first-child{
    margin-left: -144px;
}
</code>```

You can change margin according to your requirements.

Title: CSS Transition When Moved

Body:
When the first element gets deleted, I want to make the other elements to slide into their new places instead of going instantly there. Using the code below, all of the other boxes move instantly to their new positions when you delete the first one. Eventually, there will be many rows of boxes.

var pile = document.getElementById("pile");
function removeFirst(){
  pile.removeChild(event.target);
}

.box{
  border: 1px solid black;
  padding: 20px;
}
#pile{
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

I'm the first box

I'm the second box

I'm the third box

I'm the fourth box

Body:
You can do this using CSS.

Try this one

#pile{
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    margin-left: 144px;
    transition: padding-left 1s;
}
.box{
    border: 1px solid black;
    padding: 20px;
    transition: margin-left 1s;
}
.box:first-child{
    margin-left: -144px;
}

You can change margin according to your requirements.


问:
How to execute gcloud command in bash script from crontab -e
I am trying execute some gcloud commands in bash script from crontab. The script execute sucessfully from command shell but not from the cron job.

I have tried with:

Settng the full path to gcloud like:

```<code> /etc/bash_completion.d/gcloud
 /home/Arturo/.config/gcloud
 /usr/bin/gcloud
 /usr/lib/google-cloud-sdk/bin/gcloud
</code>```

Setting in the begin the script:

```<code>  /bin/bash -l
</code>```

Setting in the crontab:

```<code>51 21 30 5 6 CLOUDSDK_PYTHON=/usr/bin/python2.7;
/home/myuser/folder1/myscript.sh param1 param2 param3 -f >>
/home/myuser/folder1/mylog.txt`
</code>```

Setting inside the script:

export CLOUDSDK_PYTHON=/usr/bin/python2.7

Setting inside the script:

sudo ln -s /home/myuser/google-cloud-sdk/bin/gcloud /usr/bin/gcloud

Version Ubuntu 18.04.3 LTS
command to execute: gcloud config set project myproject

but nothing is working, maybe I am doing something wrongly. I hope you can help me.

答: I found my error, the problem here was only in the command: "gcloud dns record-sets transaction start", the others command was executing sucesfully but only no logging nothing, by that I though that was not executng the other commands. This Command create a temp file ex. transaction.yaml and that file could not be created in the default path for gcloud(snap/bin), but the log simply dont write any thing!. I had to specify the path and name for that file with the flag --transaction-file=mytransaction.yaml. Thanks for your supprot and ideas</p>

Body:
I am trying execute some gcloud commands in bash script from crontab. The script execute sucessfully from command shell but not from the cron job.

I have tried with:

Settng the full path to gcloud like:

 /etc/bash_completion.d/gcloud
 /home/Arturo/.config/gcloud
 /usr/bin/gcloud
 /usr/lib/google-cloud-sdk/bin/gcloud

Setting in the begin the script:

  /bin/bash -l

Setting in the crontab:

51 21 30 5 6 CLOUDSDK_PYTHON=/usr/bin/python2.7;
/home/myuser/folder1/myscript.sh param1 param2 param3 -f >>
/home/myuser/folder1/mylog.txt`

Setting inside the script:

export CLOUDSDK_PYTHON=/usr/bin/python2.7

Setting inside the script:

sudo ln -s /home/myuser/google-cloud-sdk/bin/gcloud /usr/bin/gcloud

Version Ubuntu 18.04.3 LTS
command to execute: gcloud config set project myproject

but nothing is working, maybe I am doing something wrongly. I hope you can help me.


问:
Is it possible to create an animated gif from a youtube or vimeo location using php?
Just a thought on whether this would be possible really, I thought it would be really cool if I could create animated gifs for embedded videos on the fly. Has anyone seen this done before?</p>

答:
first you'd need to get the video file.  After that you'd have to run it through ffmpeg to create stills from selected frames.

Plenty of guides out there just google away. I refer to this page every now and then; there is a command to convert the entire video into an animated gif on there.


问:
How do I continue looping, even through an error? Python
I have two conditions in my story using the question that I made to ask the users.

The first condition is true and second condition is false. In the first condition, if it's true, I want the program to finish. In the second condition, if it's false, I want to loop back to the question that I asked.

I have the following code, but so far it will loop back if the first is true and the second is false.

Any ideas?

invalid = ValueError

def age():
  user_input = input("Enter your Age")
  try:
    val = int(user_input)
    print("Input is an integer number. Number = ", val)
  except ValueError:
    print("No.. input is not a number. It's a string")

while invalid:
  age()
```

答:
The simplest way to execute a while loop is to just use while True and then break from the loop once the condition is satisfied

def age():
  while True:
    try:
      val = int(input("Enter your Age"))
      print("Input is an integer number. Number = ", val)
      break
    except ValueError:
      print("No.. input is not a number. It's a string")

age()
```


问:
How can I use a variable from a received messaged in a javascript function?
This is one of my very first HTML webpages projects. Long story short, I have an iframe inside the webpage which i need a button to download an svg created by the user in the webpage. I already have the download part figured out, my problem is in receiving the message and passing it to the download function. I already changed the download function to a print to see if the iframe is receiving the correct message, and it is. However, when i use the download function, it says that received data is not defined. Any help is greatly appreci

window.onmessage = (event) => {
  if (event.data) {
    let receivedData = event.data;
  }
};

function downloadSVG() {
  let svgData = receivedData;

  /// Create a fake  element
  let fakeLink = document.createElement("a");
  /// Add image data as href
  fakeLink.setAttribute('href', 'data:image/svg+xml;base64,' + window.btoa(svgData));
  /// Add download attribute
  fakeLink.setAttribute('download', 'imageName.svg');
  /// Simulate click
  fakeLink.click();

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>download SVG</code>```

答:
I believe you have an issue with scoping, you need to declare 'receivedData' outside of 'window.onmessage' handler. Just declare it right before 'window.onmessage' like this

```<code>let receivedData = null;
window.onmessage = (event) => {
    if (event.data) {
        receivedData = event.data;
    }
};
</code>```

Update #0

Here is the replacement for your 'a'-tag, to make it a button

<button id='downloadSVG' type="button" onclick="downloadSVG()" disabled>download SVG</button>

```<code>let receivedData = null;
window.onmessage = (event) => {
  if (event.data) {
    // once the data is received - get the button by ID
    const button = document.querySelector('#downloadSVG')
    // activate the button
    button.disabled = false
    receivedData = event.data;
  }
};

function downloadSVG() {
  let svgData = receivedData;
  /// Create a fake <a> element
  let fakeLink = document.createElement("a");
  /// Add image data as href
  fakeLink.setAttribute('href', 'data:image/svg+xml;base64,' + window.btoa(svgData));
  /// Add download attribute
  fakeLink.setAttribute('download', 'imageName.svg');
  /// Simulate click
  fakeLink.click();

}
</code>```

Body:
This is one of my very first HTML webpages projects. Long story short, I have an iframe inside the webpage which i need a button to download an svg created by the user in the webpage. I already have the download part figured out, my problem is in receiving the message and passing it to the download function. I already changed the download function to a print to see if the iframe is receiving the correct message, and it is. However, when i use the download function, it says that received data is not defined. Any help is greatly appreci

window.onmessage = (event) => {
  if (event.data) {
    let receivedData = event.data;
  }
};

function downloadSVG() {
  let svgData = receivedData;

  /// Create a fake  element
  let fakeLink = document.createElement("a");
  /// Add image data as href
  fakeLink.setAttribute('href', 'data:image/svg+xml;base64,' + window.btoa(svgData));
  /// Add download attribute
  fakeLink.setAttribute('download', 'imageName.svg');
  /// Simulate click
  fakeLink.click();

}

download SVG

Body:
I believe you have an issue with scoping, you need to declare 'receivedData' outside of 'window.onmessage' handler. Just declare it right before 'window.onmessage' like this

let receivedData = null;
window.onmessage = (event) => {
    if (event.data) {
        receivedData = event.data;
    }
};

Update #0

Here is the replacement for your 'a'-tag, to make it a button

<button id='downloadSVG' type="button" onclick="downloadSVG()" disabled>download SVG</button>

let receivedData = null;
window.onmessage = (event) => {
  if (event.data) {
    // once the data is received - get the button by ID
    const button = document.querySelector('#downloadSVG')
    // activate the button
    button.disabled = false
    receivedData = event.data;
  }
};

function downloadSVG() {
  let svgData = receivedData;
  /// Create a fake <a> element
  let fakeLink = document.createElement("a");
  /// Add image data as href
  fakeLink.setAttribute('href', 'data:image/svg+xml;base64,' + window.btoa(svgData));
  /// Add download attribute
  fakeLink.setAttribute('download', 'imageName.svg');
  /// Simulate click
  fakeLink.click();

}


问:
AWS: Delete Permanently S3 objects less than 30 days using 'Lifecycle Rule'
Is there a way to configure on S3 Lifecycle to delete object less than 30 days (say I want to delete in 5 days Permanently  without moving to any other Storage class like glacier?
Or should I go by other alternative like Lambda ?

I believe, S3 'Lifecycle Rule' allows storage class only more than 30 days.

答:
You can use expiration action:

Define when objects expire. Amazon S3 deletes expired objects on your behalf.

You can set expiration time to 5 days or 1 day, or what suits you.  For example, for a version bucket you can delete both current and previous versions after 5 days as shown on the screenshot:

Regarding the storage classes. You can still delete the objects, but you will be charged for 30, 90 or 180 days, depending on the storage class, if not deleting from the Standard class:

If you create an S3 Lifecycle expiration rule that causes objects that have been in S3 Intelligent-Tiering, S3 Standard-IA, or S3 One Zone-IA storage for less than 30 days to expire, you are charged for 30 days. If you create a Lifecycle expiration rule that causes objects that have been in S3 Glacier storage for less than 90 days to expire, you are charged for 90 days. If you create a Lifecycle expiration rule that causes objects that have been in S3 Glacier Deep Archive storage for less than 180 days to expire, you are charged for 180 days.


问:
Maven docker cache dependencies
I'm trying to use docker to automate maven builds. The project I want to build takes nearly 20 minutes to download all the dependencies, so I tried to build a docker image that would cache these dependencies, but it doesn't seem to save it. My Dockerfile is

```<code>FROM maven:alpine
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
ADD pom.xml /usr/src/app
RUN mvn dependency:go-offline
</code>```

The image builds, and it does download everything. However, the resulting image is the same size as the base maven:alpine image, so it doesn't seem to have cached the dependencies in the image. When I try to use the image to mvn compile it goes through the full 20 minutes of redownloading everything.

Is it possible to build a maven image that caches my dependencies so they don't have to download everytime I use the image to perform a build?

I'm running the following commands:

```<code>docker build -t my-maven .

docker run -it --rm --name my-maven-project -v "$PWD":/usr/src/mymaven -w /usr/src/mymaven my-maven mvn compile
</code>```

My understanding is that whatever RUN does during the docker build process becomes part of the resulting image.

答:
A local Nexus 3 Image running in Docker and acting as a local Proxy is an acceptable solution:

The idea is similar to Dockerize an apt-cacher-ng service apt-cacher-ng

here you can find a comprehensive step by step. github repo

Its really fast.

Title: Maven docker cache dependencies

Body:
I'm trying to use docker to automate maven builds. The project I want to build takes nearly 20 minutes to download all the dependencies, so I tried to build a docker image that would cache these dependencies, but it doesn't seem to save it. My Dockerfile is

FROM maven:alpine
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
ADD pom.xml /usr/src/app
RUN mvn dependency:go-offline

The image builds, and it does download everything. However, the resulting image is the same size as the base maven:alpine image, so it doesn't seem to have cached the dependencies in the image. When I try to use the image to mvn compile it goes through the full 20 minutes of redownloading everything.

Is it possible to build a maven image that caches my dependencies so they don't have to download everytime I use the image to perform a build?

I'm running the following commands:

docker build -t my-maven .

docker run -it --rm --name my-maven-project -v "$PWD":/usr/src/mymaven -w /usr/src/mymaven my-maven mvn compile

My understanding is that whatever RUN does during the docker build process becomes part of the resulting image.


问:
How can we get a result from the following tables for a some key values , when the values can change based on user's upload
P1 (Master table) Cols:Teamname TeamID

```<code>              Data: ABC      1
                    DEF      2
</code>```

P2 (Fieldmapping) Cols:FieldDesc Fieldname TeamID:

```<code>              Data:Goals     Text1     1,
                   Player    Text2     1,
                   Shots     Text1     2,
                   Batsman   Text2     2,
                   Runs      Text3     2,
</code>```

P3 (Values)        Cols:TeamID  text1  text2  text3 text4 text5 text6 text7 text8 text9 text10

```<code>              Data:  1      3   John
                     1      2   Mark
                     1      1   Stu
                     2      10  Bart   14
                     2      3   Mary   6
                     2      50  Ba     100
</code>```

Expected Output: If the user selects the ABC then the output should be

O/p: Col: Team Goal Player

```<code> Data: ABC  3   John
       ABC  2   Mark
       ABC  1   Stu
</code>```

Expected Output: If the user selects the DEF then the output should be

```<code> O/p: Col: Team Shots Batsman Runs

 Data: DEF  10   Bart    14
       DEF  3    Mary    6
       DEF  50   Ba     100
</code>```

How can i write this in SQL ?

答:
You need to learn how to use join in sql queries. Here you can join table p1 and  table p3 on teamId to get the desired results.

```<code>select
  teamname,
  shots,
  batsman,
  coalesce(runs, 0) as runs
from p1
join p3
on p1.teamId = p3.teamId
where teamname = 'DEF'
order by
  teamname
</code>```

Output:

```<code>| teamname | shots | batsman | runs |
| -------- | ----- | ------- | ---- |
| DEF      | 10    | Bart    | 14   |
| DEF      | 3     | Mary    | 6    |
| DEF      | 50    | Ba      | 100  |
</code>```

Body:
P1 (Master table) Cols:Teamname TeamID

              Data: ABC      1
                    DEF      2

P2 (Fieldmapping) Cols:FieldDesc Fieldname TeamID:

              Data:Goals     Text1     1,
                   Player    Text2     1,
                   Shots     Text1     2,
                   Batsman   Text2     2,
                   Runs      Text3     2,

P3 (Values)        Cols:TeamID  text1  text2  text3 text4 text5 text6 text7 text8 text9 text10

              Data:  1      3   John
                     1      2   Mark
                     1      1   Stu
                     2      10  Bart   14
                     2      3   Mary   6
                     2      50  Ba     100

Expected Output: If the user selects the ABC then the output should be

O/p: Col: Team Goal Player

 Data: ABC  3   John
       ABC  2   Mark
       ABC  1   Stu

Expected Output: If the user selects the DEF then the output should be

 O/p: Col: Team Shots Batsman Runs

 Data: DEF  10   Bart    14
       DEF  3    Mary    6
       DEF  50   Ba     100

How can i write this in SQL ?

Body:
You need to learn how to use join in sql queries. Here you can join table p1 and  table p3 on teamId to get the desired results.

select
  teamname,
  shots,
  batsman,
  coalesce(runs, 0) as runs
from p1
join p3
on p1.teamId = p3.teamId
where teamname = 'DEF'
order by
  teamname

Output:

| teamname | shots | batsman | runs |
| -------- | ----- | ------- | ---- |
| DEF      | 10    | Bart    | 14   |
| DEF      | 3     | Mary    | 6    |
| DEF      | 50    | Ba      | 100  |


答:
The variable receiveData is declared with let keyword, it will local scope. If you required is another method then use declared it outside the method.</p>

```<code>let receivedData;
window.onmessage = (event) => {
        if (event.data) {
            receivedData = event.data;
        }
    };

function downloadSVG() {
    let svgData = receivedData;

    /// Create a fake <a> element
    let fakeLink = document.createElement("a");
    /// Add image data as href
    fakeLink.setAttribute('href', 'data:image/svg+xml;base64,' + window.btoa(svgData));
    /// Add download attribute
    fakeLink.setAttribute('download', 'imageName.svg');
    /// Simulate click
    fakeLink.click();
}
</code>```

Title: How can I use a variable from a received messaged in a javascript function?

Body:
The variable receiveData is declared with let keyword, it will local scope. If you required is another method then use declared it outside the method.

let receivedData;
window.onmessage = (event) => {
        if (event.data) {
            receivedData = event.data;
        }
    };

function downloadSVG() {
    let svgData = receivedData;

    /// Create a fake <a> element
    let fakeLink = document.createElement("a");
    /// Add image data as href
    fakeLink.setAttribute('href', 'data:image/svg+xml;base64,' + window.btoa(svgData));
    /// Add download attribute
    fakeLink.setAttribute('download', 'imageName.svg');
    /// Simulate click
    fakeLink.click();
}