问:
Saving Animated Matplotlib Chart to GIF
I have an animated matplotlib chart that I'm trying to save to a .gif file, but I can't get my image writer to work.

I've installed imagemagick and verified that it works on my computer via the instructions given on its installation page, but when I do this:

```<code>anim.save('gd.gif', writer='imagemagick')
</code>```

I get the following error message:

```<code>MovieWriter imagemagick unavailable. Trying to use pillow instead.
</code>```

However, doing anim.save('gd.gif', writer='pillow') gives the following error message:

```<code>ValueError: not enough image data
</code>```

I tried installing ffmpeg with the command conda install -c conda-forge ffmpeg. It looked like it installed correctly, but I don't know how to bind it to matplotlib apparently.

Specifying the writer as ffmpeg gives the same error message that I encountered with imagemagick.

I also tried adding imagemagick's path to matplotlib's config file path with the following line:

```<code>animation.convert_path: 'C:\Program Files\ImageMagick-7.0.8-Q16\magick.exe'
</code>```

That was suggested in this question.

None of these seemed to have worked though.

I'm on Windows 10, and am using Python 3.7

答: A quick solve is to simply add plt.show() before running anim.save('gd.gif', writer='imagemagick'). When you close the plot it will save the animation correctly.

Title: Saving Animated Matplotlib Chart to GIF

Body:
I have an animated matplotlib chart that I'm trying to save to a .gif file, but I can't get my image writer to work.

I've installed imagemagick and verified that it works on my computer via the instructions given on its installation page, but when I do this:

anim.save('gd.gif', writer='imagemagick')

I get the following error message:

MovieWriter imagemagick unavailable. Trying to use pillow instead.

However, doing anim.save('gd.gif', writer='pillow') gives the following error message:

ValueError: not enough image data

I tried installing ffmpeg with the command conda install -c conda-forge ffmpeg. It looked like it installed correctly, but I don't know how to bind it to matplotlib apparently.

Specifying the writer as ffmpeg gives the same error message that I encountered with imagemagick.

I also tried adding imagemagick's path to matplotlib's config file path with the following line:

animation.convert_path: 'C:\Program Files\ImageMagick-7.0.8-Q16\magick.exe'

That was suggested in this question.

None of these seemed to have worked though.

I'm on Windows 10, and am using Python 3.7


来源: stackexchange

问:
Show function name in status line
I edit a large C, C++, or Java file, say, about 15000 lines, with pretty long function definitions, say, about 400 lines. When the cursor is in middle of a function definition, it would be cool to see the function name in Vim status line.

When we set :set ls=2 in Vim, we can get the file path (relative to the current directory), line number, etc. It would be really cool if we could see the function name too. Any ideas how to get it?

Currently I use [[ to go to start of the function and Ctrl-O to get back to the line I'm editing.

答:
Based on @solidak solution (which was already based on another one :)

I wanted to always show the function name in the bottom of the terminal.
But I had some problems with very large function which I solved that way:

```<code>fun! ShowFuncName()
  echohl ModeMsg
  echo getline(search("^[^ \t#/]\\{2}.*[^:]\s*$", 'bWn'))[:winwidth('%')-3]
  echohl None
endfun

augroup show_funcname
  autocmd CursorMoved * :call ShowFuncName()
augroup end
</code>```

ContentLicense: CC BY-SA 3.0

Title: Show function name in status line

Body:
Based on @solidak solution (which was already based on another one :)

I wanted to always show the function name in the bottom of the terminal.
But I had some problems with very large function which I solved that way:

fun! ShowFuncName()
  echohl ModeMsg
  echo getline(search("^[^ \t#/]\\{2}.*[^:]\s*$", 'bWn'))[:winwidth('%')-3]
  echohl None
endfun

augroup show_funcname
  autocmd CursorMoved * :call ShowFuncName()
augroup end

ContentLicense: CC BY-SA 4.0


问:
How do I rerun a static integer array?
here's the array I want to rerun:

```<code>public static int[] rollDice(int dice[]) {
    // generate 5 random numbers / update dice array
    for (int i = 0; i < dice.length; i++) {
        dice[i] = (int)(Math.random() * 6 + 1);
    }

    return dice;
}
</code>```

If I want to reset this array and find new random numbers how would I do that? I tried rollDice() only to get an error.

答:
```<code>You can get every time a new dynamic length array with random numbers, and you can access by call rollDice(integer value).

public static int[] rollDice(int length) {
         final int dice[] = new int [length];
        // generate array with random values
        for (int i = 0; i < length; i++) {
            dice[i] = (int)(Math.random() * length + 1);
        }

        return dice;
    }
</code>```

Title: How do I rerun a static integer array?

Body:
here's the array I want to rerun:

public static int[] rollDice(int dice[]) {
    // generate 5 random numbers / update dice array
    for (int i = 0; i < dice.length; i++) {
        dice[i] = (int)(Math.random() * 6 + 1);
    }

    return dice;
}

If I want to reset this array and find new random numbers how would I do that? I tried rollDice() only to get an error.


问:
How to base CSS on parallel DOM elements?
I have a procedurally generated visualisation that switches between mine and my friends visualizations, removing them from the DOM in the process and reintroducing them when need be (This needs to be the case).

On the footer, there is a bit of text that is only relevant to one view.

```<code><div class='container'>
    <div id='myvis'>The Vis</div>
</div>
<footer><p>Hi Mom</p></footer>
</code>```

But then #myvis will be removed from the DOM and replaced with this:

```<code><div class='container'>
    <div id='myfriendsvis'>The Vis</div>
</div>
<footer><p>Hi Mom</p></footer>
</code>```

But I obviously don't want to say Hi mom here, because why would my mom be viewing my friends vis?

Since they are parallel, I can't necessary say

```<code>#myfriendsvis p {
display: none;
}
</code>```

I also tried

```<code>#myfriendsvis ~ p {
display: none;
}
</code>```

I also wrote this:

```<code>    function myFunction(x) {
    if (slides) {
        HiMom.style.display = "none";
    } else {
        HiMom.style.display = "block";
    }
};

const slides = document.getElementById('myfriendsvis').style.width == 1024; // basically saying if this item exists in the dom, it'll exist with this style, so if its there do this
const HiMom = document.getElementsByClassName('footer p'); // IK its not a class but you get it
myFunction(slides) // Call listener function at run time
slides.addListener(myFunction) // Attach listener function on state changes
</code>```

But because myfriendsvis comes 2nd, it doesn't exist in the DOM.

Is there a way I can css the p based on another element above despite the fact it's nested?

Accepting JS, CSS, and HTML advice. Might be tricky to implement but I'll solve it.

答:
Unfortunately, a pure css solution is not possible, because you would have to get the parent of #myfriendsvis and that is currently not possible.

In order to get it to work, I updated your Javascript:

```<code>    function myFunction(x) {

    if (slides) {
        HiMom.style.display = "none"
    } else {
        HiMom.style.display = "block";
    }
};

const slides = document.getElementById('myfriendsvis')
slides.style.width == 1024; // basically saying if this item exists in the dom, it'll exist with this style, so if its there do this
const HiMom = document.querySelector('footer p'); // IK its not a class but you get it

myFunction(slides) // Call listener function at run time
slides.addEventListener("onload",myFunction) // Attach listener function on state changes
</code>```

Doing the slides style update in one go, caused it's value to become false instead of a node. So I made it a two step process. I also use a querySelector, as it will only return one node instead of a collection and I used an onload event listener. Depending on your use case, you may have to update it with an update event listener.

Here is a codepen for you to play around with.

Body:
I have a procedurally generated visualisation that switches between mine and my friends visualizations, removing them from the DOM in the process and reintroducing them when need be (This needs to be the case).

On the footer, there is a bit of text that is only relevant to one view.

The Vis

Hi Mom

But then #myvis will be removed from the DOM and replaced with this:

The Vis

Hi Mom

But I obviously don't want to say Hi mom here, because why would my mom be viewing my friends vis?

Since they are parallel, I can't necessary say

#myfriendsvis p {
display: none;
}

I also tried

#myfriendsvis ~ p {
display: none;
}

I also wrote this:

    function myFunction(x) {
    if (slides) {
        HiMom.style.display = "none";
    } else {
        HiMom.style.display = "block";
    }
};

const slides = document.getElementById('myfriendsvis').style.width == 1024; // basically saying if this item exists in the dom, it'll exist with this style, so if its there do this
const HiMom = document.getElementsByClassName('footer p'); // IK its not a class but you get it
myFunction(slides) // Call listener function at run time
slides.addListener(myFunction) // Attach listener function on state changes

But because myfriendsvis comes 2nd, it doesn't exist in the DOM.

Is there a way I can css the p based on another element above despite the fact it's nested?

Accepting JS, CSS, and HTML advice. Might be tricky to implement but I'll solve it.

Body:
Unfortunately, a pure css solution is not possible, because you would have to get the parent of #myfriendsvis and that is currently not possible.

In order to get it to work, I updated your Javascript:

    function myFunction(x) {

    if (slides) {
        HiMom.style.display = "none"
    } else {
        HiMom.style.display = "block";
    }
};

const slides = document.getElementById('myfriendsvis')
slides.style.width == 1024; // basically saying if this item exists in the dom, it'll exist with this style, so if its there do this
const HiMom = document.querySelector('footer p'); // IK its not a class but you get it

myFunction(slides) // Call listener function at run time
slides.addEventListener("onload",myFunction) // Attach listener function on state changes

Doing the slides style update in one go, caused it's value to become false instead of a node. So I made it a two step process. I also use a querySelector, as it will only return one node instead of a collection and I used an onload event listener. Depending on your use case, you may have to update it with an update event listener.

Here is a codepen for you to play around with.


问:
How can I add unsubscribe links to my emails when sending via sendgrid/mail
I'm sending emails using: https://github.com/sendgrid/sendgrid-nodejs/tree/master/packages/mail

I have not been able to find out HOW I can add the Unsubscribe equivalent. This is documented in here: https://sendgrid.com/docs/Classroom/Basics/Marketing_Campaigns/unsubscribe_groups.html#-Using-a-Custom-Unsubscribe-Link

On the website, you just use a shortcode [Unsubscribe], this does not work when sending emails via the sendgrid/mail package.

答:
One tip that would have saved me an hour or two is that:

It's possible to send the following in the api json along with other stuff:

```<code>  "asm":{
    "group_id":123,
    "groups_to_display": [123],
    }
</code>```

then the following variables become available to use within the template:

```<code><%asm_group_unsubscribe_raw_url%>
<%asm_preferences_raw_url%>
</code>```

If you want to keep things simple don't include the following variable as it fiddles with too many things (this wasn't obvious from the documentation so obviously I did so and wasted time :( ):

```<code>  "tracking_settings": {
    "subscription_tracking": {
      "enable": true,
      "substitution_tag": "[unsubscribe_url]"
    }
  }
</code>```

Just use them in their raw format and you shall be fine.

Body:
One tip that would have saved me an hour or two is that:

It's possible to send the following in the api json along with other stuff:

  "asm":{
    "group_id":123,
    "groups_to_display": [123],
    }

then the following variables become available to use within the template:

<%asm_group_unsubscribe_raw_url%>
<%asm_preferences_raw_url%>

If you want to keep things simple don't include the following variable as it fiddles with too many things (this wasn't obvious from the documentation so obviously I did so and wasted time :( ):

  "tracking_settings": {
    "subscription_tracking": {
      "enable": true,
      "substitution_tag": "[unsubscribe_url]"
    }
  }

Just use them in their raw format and you shall be fine.


问:
how to insert video path, video name in mysql database in php.?
I want to store video path and name in MySQL database but actually only stored the some fields information which i used in the form. and video stored the test upload folder

I have tried but video path(location) and name not store in database.

Here my code,

```<code><form id="upload_form" enctype="multipart/form-data" method="post">
<input type="file" name="file1" id="file1"><br><br>
<input type="button" value="Upload File" onclick="uploadFile()">
</form>
</code>```

Controller:

public function Insert_vedio()
{

```<code>$vedio_data=array(
 'title'=>$this->input->post('Title'),
 'v_name'=>$this->input->post('fileName'),
 );
$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
if (!$fileTmpLoc) { // if file not chosen
    exit();
}
if(move_uploaded_file($fileTmpLoc, "test_uploads/$fileName")){
    echo "$fileName upload is complete";
} else {
    echo "move_uploaded_file function failed";
}
</code>```

}

答:
Here my Javascript</p>

```<code><script>
function _(el)
{
    return document.getElementById(el);
}
function uploadFile(){
    var file = _("file1").files[0];

    if(typeof file === "undefined") {

        _("status").innerHTML = "ERROR: Please browse for a file before clicking the upload button";
        _("progressBar").value = 0;
        return;
    }

    $.get('Upload_vedio/Insert_vedio?getsize', function(sizelimit) {
        if(file.type !== "video/mp4") {
            var typewarn = "ERROR: You have to select a MP4-File";
            _("status").innerHTML = typewarn;
            _("progressBar").value = 0;
            return;
        }
        if(sizelimit < file.size) {
            var sizewarn = "ERROR: The File is too big! The maximum file size is ";
            sizewarn += sizelimit/(1024*1024);
            sizewarn += "MB";
            _("status").innerHTML = sizewarn;
            _("progressBar").value = 0;
            return;
        }
        var formdata = new FormData();
            formdata.append("file1", file);
            formdata.append("size", file.size);
            var ajax = new XMLHttpRequest();
            ajax.upload.addEventListener("progress", progressHandler, false);
            ajax.addEventListener("load", completeHandler, false);
            ajax.addEventListener("error", errorHandler, false);
            ajax.addEventListener("abort", abortHandler, false);
            ajax.open("POST", "Upload_vedio/Insert_vedio");
            ajax.send(formdata);
    });
}
function progressHandler(event){
    _("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
    var percent = (event.loaded / event.total) * 100;
    _("progressBar").value = Math.round(percent);
    _("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
}
function completeHandler(event){
    _("status").innerHTML = event.target.responseText;
    _("progressBar").value = 0;
}
function errorHandler(event){
    _("status").innerHTML = "Upload Failed";
}
function abortHandler(event){
    _("status").innerHTML = "Upload Aborted";
}
</script>
</code>```

Body:
I want to store video path and name in MySQL database but actually only stored the some fields information which i used in the form. and video stored the test upload folder

I have tried but video path(location) and name not store in database.

Here my code,

<form id="upload_form" enctype="multipart/form-data" method="post">
<input type="file" name="file1" id="file1">

<input type="button" value="Upload File" onclick="uploadFile()">
</form>

Controller:

public function Insert_vedio()
{

$vedio_data=array(
 'title'=>$this->input->post('Title'),
 'v_name'=>$this->input->post('fileName'),
 );
$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
if (!$fileTmpLoc) { // if file not chosen
    exit();
}
if(move_uploaded_file($fileTmpLoc, "test_uploads/$fileName")){
    echo "$fileName upload is complete";
} else {
    echo "move_uploaded_file function failed";
}

}

Body:
Here my Javascript

<script>
function _(el)
{
    return document.getElementById(el);
}
function uploadFile(){
    var file = _("file1").files[0];

    if(typeof file === "undefined") {

        _("status").innerHTML = "ERROR: Please browse for a file before clicking the upload button";
        _("progressBar").value = 0;
        return;
    }

    $.get('Upload_vedio/Insert_vedio?getsize', function(sizelimit) {
        if(file.type !== "video/mp4") {
            var typewarn = "ERROR: You have to select a MP4-File";
            _("status").innerHTML = typewarn;
            _("progressBar").value = 0;
            return;
        }
        if(sizelimit < file.size) {
            var sizewarn = "ERROR: The File is too big! The maximum file size is ";
            sizewarn += sizelimit/(1024*1024);
            sizewarn += "MB";
            _("status").innerHTML = sizewarn;
            _("progressBar").value = 0;
            return;
        }
        var formdata = new FormData();
            formdata.append("file1", file);
            formdata.append("size", file.size);
            var ajax = new XMLHttpRequest();
            ajax.upload.addEventListener("progress", progressHandler, false);
            ajax.addEventListener("load", completeHandler, false);
            ajax.addEventListener("error", errorHandler, false);
            ajax.addEventListener("abort", abortHandler, false);
            ajax.open("POST", "Upload_vedio/Insert_vedio");
            ajax.send(formdata);
    });
}
function progressHandler(event){
    _("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
    var percent = (event.loaded / event.total) * 100;
    _("progressBar").value = Math.round(percent);
    _("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
}
function completeHandler(event){
    _("status").innerHTML = event.target.responseText;
    _("progressBar").value = 0;
}
function errorHandler(event){
    _("status").innerHTML = "Upload Failed";
}
function abortHandler(event){
    _("status").innerHTML = "Upload Aborted";
}
</script>


问:
How to transfer files from Azure Data Lake to Network File Folder(Remote server folder) using Azure Data Factory
Is it possible to transfer files from Azure Data Lake to remote file server using Azure Data Factory. I don't have any problem with source but i am not sure how i can achieve for destination.

Am I able to transfer files from ADL to local file folder but I am unsure about how we can do this with remote server.

Help me if you have any idea on these.

答:
Per my knowledge, all the transmissions in ADF are hosted on the Integration Runtime. So i suppose that there are 2 conditions in this scenario:

1.Your remote server is hosted in the public network, Default IR should be used. You could consider to expose REST API of your remote file server and try to configure it as sink dataset in the copy activity.

2.Your remote server is hosted in private network, then Self-Hosted IR should be used and you have to install Self-Hosted IR. However, currently, MS only supports running the self-hosted IR on a Windows operating system according to the official statement.


问:
Intellij Idea does not find my android device
Hi I want to do some test app that uses sound recording, but it doesn't work in the emulator. I need to test it on my phone but every time I change the option to use USB, it never detects my Wildfire S ... which is connected and in USB debugging mode.

It says "No USB Device Found".

Using 11.1.2

Any ideas?

答:
It could be the configuration of your phone. Open the developer settings and make sure that the option of USB Configuration is in:

MIDI


问:
Duplicate class in modules dagger-1.2.2.jar and dagger-2.22.jar
After upgrading all libraries to androidx and to the latest versions of Firebase libraries

I got error with 2 different versions of dagger java files, link in the error message doesn't work. Problem occurs at step :app:checkDebugDuplicateClasses.

I do not use dagger directly in my code, using

```<code>./gradlew app:dependencies
</code>```

I found what com.google.android.gms:play-services-cast-framework:17.1.0 uses com.google.dagger:dagger:2.22, but no info about 1.2.2.

```<code>Cause 1: java.util.concurrent.ExecutionException: java.lang.RuntimeException: java.lang.RuntimeException: Duplicate class dagger.Lazy found in modules dagger-1.2.2.jar (dagger-1.2.2.jar) and dagger-2.22.jar (com.google.dagger:dagger:2.22)
Duplicate class dagger.MembersInjector found in modules dagger-1.2.2.jar (dagger-1.2.2.jar) and dagger-2.22.jar (com.google.dagger:dagger:2.22)
Duplicate class dagger.Module found in modules dagger-1.2.2.jar (dagger-1.2.2.jar) and dagger-2.22.jar (com.google.dagger:dagger:2.22)
Duplicate class dagger.Provides found in modules dagger-1.2.2.jar (dagger-1.2.2.jar) and dagger-2.22.jar (com.google.dagger:dagger:2.22)
Duplicate class javax.inject.Inject found in modules javax.inject-1.jar (javax.inject-1.jar) and javax.inject-1.jar (javax.inject:javax.inject:1)
Duplicate class javax.inject.Named found in modules javax.inject-1.jar (javax.inject-1.jar) and javax.inject-1.jar (javax.inject:javax.inject:1)
Duplicate class javax.inject.Provider found in modules javax.inject-1.jar (javax.inject-1.jar) and javax.inject-1.jar (javax.inject:javax.inject:1)
Duplicate class javax.inject.Qualifier found in modules javax.inject-1.jar (javax.inject-1.jar) and javax.inject-1.jar (javax.inject:javax.inject:1)
Duplicate class javax.inject.Scope found in modules javax.inject-1.jar (javax.inject-1.jar) and javax.inject-1.jar (javax.inject:javax.inject:1)
Duplicate class javax.inject.Singleton found in modules javax.inject-1.jar (javax.inject-1.jar) and javax.inject-1.jar (javax.inject:javax.inject:1)

Go to the documentation to learn how to Fix dependency resolution errors.
</code>```

答:
The easiest way is to analyze dependencies.

SOLUTION #1 (console only)

Run in console:

```<code>./gradlew -q dependencies app:dependencies
</code>```

After receiving list of dependencies in the console, go to Analyze part (below Solution #2).

SOLUTION #2 (generate html)

1) Add plugin to generate report

In to app/build.gradle (this with compileSdkVersion, targetSdkVersion or buildTypes), at the top add:

```<code>apply plugin: 'project-report'
</code>```

near one of them:

```<code>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
</code>```

which are on top.

2) Generate report

Just from the console run:

```<code> ./gradlew htmlDependencyReport
</code>```

or from Android Studio

```<code>Tasks > other > htmlDependencyReport
</code>```

3) Open report

In console you will find URL:

```<code>./gradlew htmlDependencyReport

> Task :app:htmlDependencyReport
See the report at: file:///Users/user_name/your_path/project_name/app/build/reports/project/dependencies/index.html
</code>```

And go to the project ':app'

4) Analyze report

After clicking each of the position there are dependencies:

To expand all of them, you can in develper console such code:

```<code>$('#dependencies').html(function(index, html) {
    return html.split('style="display: none;"')
               .join('style="display: block;"')
               .split('<h3 class="closed">')
               .join('<h3>')
});
</code>```

ANALYZE

1) Find old dependencies

In your case you are searching phrase dagger:1

Or in the console:

2) Exlude dependencies

Find in the report library name, and just exclude group from this import.

In your build.gradle (where you have all of dependencies) modify "problematic" library excluding dagger v1.

For example:

```<code>implementation("some.old.library.using.dagger1:1.0.0") {
    exclude group: 'com.squareup.dagger', module: 'dagger'
}
</code>```

Body:
After upgrading all libraries to androidx and to the latest versions of Firebase libraries

I got error with 2 different versions of dagger java files, link in the error message doesn't work. Problem occurs at step :app:checkDebugDuplicateClasses.

I do not use dagger directly in my code, using

./gradlew app:dependencies

I found what com.google.android.gms:play-services-cast-framework:17.1.0 uses com.google.dagger:dagger:2.22, but no info about 1.2.2.

Cause 1: java.util.concurrent.ExecutionException: java.lang.RuntimeException: java.lang.RuntimeException: Duplicate class dagger.Lazy found in modules dagger-1.2.2.jar (dagger-1.2.2.jar) and dagger-2.22.jar (com.google.dagger:dagger:2.22)
Duplicate class dagger.MembersInjector found in modules dagger-1.2.2.jar (dagger-1.2.2.jar) and dagger-2.22.jar (com.google.dagger:dagger:2.22)
Duplicate class dagger.Module found in modules dagger-1.2.2.jar (dagger-1.2.2.jar) and dagger-2.22.jar (com.google.dagger:dagger:2.22)
Duplicate class dagger.Provides found in modules dagger-1.2.2.jar (dagger-1.2.2.jar) and dagger-2.22.jar (com.google.dagger:dagger:2.22)
Duplicate class javax.inject.Inject found in modules javax.inject-1.jar (javax.inject-1.jar) and javax.inject-1.jar (javax.inject:javax.inject:1)
Duplicate class javax.inject.Named found in modules javax.inject-1.jar (javax.inject-1.jar) and javax.inject-1.jar (javax.inject:javax.inject:1)
Duplicate class javax.inject.Provider found in modules javax.inject-1.jar (javax.inject-1.jar) and javax.inject-1.jar (javax.inject:javax.inject:1)
Duplicate class javax.inject.Qualifier found in modules javax.inject-1.jar (javax.inject-1.jar) and javax.inject-1.jar (javax.inject:javax.inject:1)
Duplicate class javax.inject.Scope found in modules javax.inject-1.jar (javax.inject-1.jar) and javax.inject-1.jar (javax.inject:javax.inject:1)
Duplicate class javax.inject.Singleton found in modules javax.inject-1.jar (javax.inject-1.jar) and javax.inject-1.jar (javax.inject:javax.inject:1)

Go to the documentation to learn how to Fix dependency resolution errors.

Body:
The easiest way is to analyze dependencies.

SOLUTION #1 (console only)

Run in console:

./gradlew -q dependencies app:dependencies

After receiving list of dependencies in the console, go to Analyze part (below Solution #2).

SOLUTION #2 (generate html)

1) Add plugin to generate report

In to app/build.gradle (this with compileSdkVersion, targetSdkVersion or buildTypes), at the top add:

apply plugin: 'project-report'

near one of them:

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

which are on top.

2) Generate report

Just from the console run:

 ./gradlew htmlDependencyReport

or from Android Studio

Tasks > other > htmlDependencyReport

3) Open report

In console you will find URL:

./gradlew htmlDependencyReport

> Task :app:htmlDependencyReport
See the report at: file:///Users/user_name/your_path/project_name/app/build/reports/project/dependencies/index.html

And go to the project ':app'

4) Analyze report

After clicking each of the position there are dependencies:

To expand all of them, you can in develper console such code:

$('#dependencies').html(function(index, html) {
    return html.split('style="display: none;"')
               .join('style="display: block;"')
               .split('<h3 class="closed">')
               .join('<h3>')
});

ANALYZE

1) Find old dependencies

In your case you are searching phrase dagger:1

Or in the console:

2) Exlude dependencies

Find in the report library name, and just exclude group from this import.

In your build.gradle (where you have all of dependencies) modify "problematic" library excluding dagger v1.

For example:

implementation("some.old.library.using.dagger1:1.0.0") {
    exclude group: 'com.squareup.dagger', module: 'dagger'
}


问:
Laravel how can using the require file
Laravel how can I use the require file when using @section('content') method, how can I require the file into the this?

I want to using the menu bar, but I don't know how to separate it.

I have this code

```<code><div class="links">
            <a href="http://127.0.0.1:8000/aboutme">About Me</a>
            <a href="http://127.0.0.1:8000/employmenthistory">Employment History</a>
            <a href="https://laravel-news.com">News</a>
            <a href="https://blog.laravel.com">Blog</a>
            <a href="https://nova.laravel.com">Nova</a>
            <a href="https://forge.laravel.com">Forge</a>
            <a href="https://vapor.laravel.com">Vapor</a>
            <a href="https://github.com/laravel/laravel">GitHub</a>
        </div>
</code>```

can independent to menu.php

答: In Laravel blade you can use @include('file path')

Title: Laravel how can using the require file

Body:
Laravel how can I use the require file when using @section('content') method, how can I require the file into the this?

I want to using the menu bar, but I don't know how to separate it.

I have this code

            About Me
            Employment History
            News
            Blog
            Nova
            Forge
            Vapor
            GitHub

can independent to menu.php


问:
Overload of a nested template function
I was thinking a lot what title to put on my question and failed anyway, so if you find a good one, please edit it.

I am trying to write a print function for a vector or other container<T> and have another print function for container<container<T>>, so here what I came up with:

```<code>template<typename T>
void print(T const& cont){
    for (const auto& i : cont) {
        cout << i << " ";
    }
    cout << endl;
}

template<typename T, template<typename> typename Cont>
void print(Cont<T> const& cont) {
    for (const auto& i : cont) {
        print(i);
    }
}
</code>```

and I have my 2 target containers here:

```<code>vector<vector<int>> subsets;
vector<int> subset;
</code>```

When I invoke print(subset); the program works as expected,  but when i invoke print(subsets), compiler starts complaining:

```<code>error C2679: binary '<<': no operator found which takes a right-hand operand of type 'const std::vector<int,std::allocator<int>>' (or there is no acceptable conversion)
</code>```

My conclusion is that its still trying to call the non-nested template print function and failing on cout as I am trying to cout a vector.

Can anyone explain why the overload resolution is not working as I expect and what I did wrong here? Even when I rename the nested-template function to printn, its started to complain for a different reason:

```<code>error C2784: 'void prints(const Cont<T> &)': could not deduce template argument for 'const Cont<T> &' from 'std::vector<std::vector<int,std::allocator<int>>,std::allocator<std::vector<int,std::allocator<int>>>>'
</code>```

答:
You can also use SFINAE (or C++ Concepts, if you live in the future) to get the result you want without having to know how many template params your incoming container has. Here's an example using trailing return types to do SFINAE:

#include <iostream>
#include <vector>

template<typename T>
auto print( const T& cont ) -> decltype(std::cout << *begin(cont), void())
{
    for( auto&& i : cont )
        std::cout << i << ' ';
    std::cout << '\n';
}

template<typename T>
auto print( const T& cont ) -> decltype(begin(*begin(cont)), void())
{
    for( auto&& i : cont )
        print(i);
}

int main()
{
    const auto subset1  = std::vector<int>{ 1, 2, 3, 4 };
    const auto subset2 = std::vector<std::vector<int>>{ {5,6,7}, {8,9} };
    const auto subset3 = std::vector<std::vector<std::vector<int>>>{
        { {10,20,30}, {40,50} },
        { {60}, {70,80,90}, {100,110,120} },
        { {200,400,600} }
    };

    print( subset1 );
    print( subset2 );
    print( subset3 );
}
```

<p>See it live on <kbd>Coliru</kbd> where it outputs:</p>

```1 2 3 4
5 6 7
8 9
10 20 30
40 50
60
70 80 90
100 110 120
200 400 600
```

Note how the first function expresses that it requires the ability to write a single element via the begin() function (implicitly used by range-for loops) and the second requires at least doubly nested sequences accessible via begin().

I'd probably lean toward a variadic template myself unless you need to handle containers separately from containers of containers (of containers (of containers...)).

Title: Overload of a nested template function

Body:
I was thinking a lot what title to put on my question and failed anyway, so if you find a good one, please edit it.

I am trying to write a print function for a vector or other container<T> and have another print function for container<container<T>>, so here what I came up with:

template<typename T>
void print(T const& cont){
    for (const auto& i : cont) {
        cout << i << " ";
    }
    cout << endl;
}

template<typename T, template<typename> typename Cont>
void print(Cont<T> const& cont) {
    for (const auto& i : cont) {
        print(i);
    }
}

and I have my 2 target containers here:

vector<vector<int>> subsets;
vector<int> subset;

When I invoke print(subset); the program works as expected,  but when i invoke print(subsets), compiler starts complaining:

error C2679: binary '<<': no operator found which takes a right-hand operand of type 'const std::vector<int,std::allocator<int>>' (or there is no acceptable conversion)

My conclusion is that its still trying to call the non-nested template print function and failing on cout as I am trying to cout a vector.

Can anyone explain why the overload resolution is not working as I expect and what I did wrong here? Even when I rename the nested-template function to printn, its started to complain for a different reason:

error C2784: 'void prints(const Cont<T> &)': could not deduce template argument for 'const Cont<T> &' from 'std::vector<std::vector<int,std::allocator<int>>,std::allocator<std::vector<int,std::allocator<int>>>>'

Body:
You can also use SFINAE (or C++ Concepts, if you live in the future) to get the result you want without having to know how many template params your incoming container has. Here's an example using trailing return types to do SFINAE:

#include <iostream>
#include <vector>

template<typename T>
auto print( const T& cont ) -> decltype(std::cout << *begin(cont), void())
{
    for( auto&& i : cont )
        std::cout << i << ' ';
    std::cout << '\n';
}

template<typename T>
auto print( const T& cont ) -> decltype(begin(*begin(cont)), void())
{
    for( auto&& i : cont )
        print(i);
}

int main()
{
    const auto subset1  = std::vector<int>{ 1, 2, 3, 4 };
    const auto subset2 = std::vector<std::vector<int>>{ {5,6,7}, {8,9} };
    const auto subset3 = std::vector<std::vector<std::vector<int>>>{
        { {10,20,30}, {40,50} },
        { {60}, {70,80,90}, {100,110,120} },
        { {200,400,600} }
    };

    print( subset1 );
    print( subset2 );
    print( subset3 );
}

See it live on Coliru where it outputs:

1 2 3 4
5 6 7
8 9
10 20 30
40 50
60
70 80 90
100 110 120
200 400 600

Note how the first function expresses that it requires the ability to write a single element via the begin() function (implicitly used by range-for loops) and the second requires at least doubly nested sequences accessible via begin().

I'd probably lean toward a variadic template myself unless you need to handle containers separately from containers of containers (of containers (of containers...)).


问:
Is it possible to create multi page apps in angular?
I am thinking of creating a clone of Food ordering applications like Zomato, and I found out that it uses Angular like routing on certain pages that are at the time of Ordering after selecting a Restaurant.
i.e. the page is not refreshed can be seen from the Reload button on the browser and it seems that the request doesn't go to the server.

While on other sections such as selecting a restaurant the request does seem to get routed by the server.

So my question is that Is it feasible to make a multi-page application in angular?

and if yes then how please provide some links of a demo or something on the Internet, and if no then what should be the architecture of such a Food ordering app?

The architecture I am thinking:

But I am stuck at the problem that how will the server be able to render or request angular to get the data, I know the way angular can request the server to fetch the data using Restful Services but I don't know how the server will be able to pass control to the angular app when user requests for a particular URL that is designed for the angular app such as the URL at the time of ordering.

答:
Looks to me - and especially looking through the comments, with various people giving appropriate responses - that you're not exactly aware what SPA (Single Page Application) are. What you're attempting doesn't make a whole lot of sense. While I've seen some hackish solutions that are coming close to what you want, it's an awful mess that is highly unmaintainable.

If it's SSR (Server-Side-Rendering) what you want (Pages are being served from the backend) , the official Documentation of Angular Universal is something you should look into, but that would require you to serve your Application with Node.js. If you want to keep your Java Spring backend, you will have to consider a Server to Server Communication


问:
Python on Server: What does the following error message mean?
I have a python that works perfectly fine when I let it run via a
local python server on my machine. So, I uploaded it on a server,
set the correct permission octals and then tried to access the
.cgi file via the browser.It doesn't run, but I get the following message:

```<code>The following python binaries are available:

python3: Python 3.7.7

Please use the binary for the version of Python you want.
</code>```

As I am new to Python, I don't know how to interprete this.

Thank you.

答:
Your cgi file probably has a line at the top that looks something like this:

```<code>#! /usr/bin/python
</code>```

Change python to python3.

Body:
I have a python that works perfectly fine when I let it run via a
local python server on my machine. So, I uploaded it on a server,
set the correct permission octals and then tried to access the
.cgi file via the browser.It doesn't run, but I get the following message:

The following python binaries are available:

python3: Python 3.7.7

Please use the binary for the version of Python you want.

As I am new to Python, I don't know how to interprete this.

Thank you.

Body:
Your cgi file probably has a line at the top that looks something like this:

#! /usr/bin/python

Change python to python3.


答:
Your issue here is that std::vector has more than one template type.  Because of this, the T overload is use instead.  The reason this happens is from an ambiguity in the language on how default template parameters should be considered in template template parameter.  This led to the defect report DR150 which was adopted in C++17 and will allow your code to work in a compliant compiler1.  To work around this you can use a variadic template template parameter and adjust the base case to just print the element like

```<code>template<typename T>
void print(T const& elem){
    cout << elem << " ";
}

template<template<typename...> typename Cont, typename... Params>
void print(Cont<Params...> const& cont) {
    for (const auto& i : cont) {
        print(i);
    }
    cout << endl;
}

int main()
{
    vector<vector<int>> subsets{{1,2},{3,4}};
    print(subsets);
}
</code>```

outputs

```<code>1 2
3 4
</code>```

1: I had to adjust the base case like in my example because now the template temaplte version will call the nested vector

Title: Overload of a nested template function

Body:
Your issue here is that std::vector has more than one template type.  Because of this, the T overload is use instead.  The reason this happens is from an ambiguity in the language on how default template parameters should be considered in template template parameter.  This led to the defect report DR150 which was adopted in C++17 and will allow your code to work in a compliant compiler1.  To work around this you can use a variadic template template parameter and adjust the base case to just print the element like

template<typename T>
void print(T const& elem){
    cout << elem << " ";
}

template<template<typename...> typename Cont, typename... Params>
void print(Cont<Params...> const& cont) {
    for (const auto& i : cont) {
        print(i);
    }
    cout << endl;
}

int main()
{
    vector<vector<int>> subsets{{1,2},{3,4}};
    print(subsets);
}

outputs

1 2
3 4

1: I had to adjust the base case like in my example because now the template temaplte version will call the nested vector


问:
Google Cloud SQL Failover, how to setup?
I am trying to set up a new failover to my SQL instance.

This is my second instance. I made the first one a year ago, so I don't exactly remember the procedure to create a Failover instance.

When I am creating the main instance, under

"Backups, recovery, and high availability"  > "Availability"

I select:

• High availability (regional)
Automatic failover to another zone within your selected region. Recommended for production instances. Increases cost.

Is this enough to ensure I have a failover?

I am asking because after I created the instance I see there is no failover.

While under my first instance - the old one I created a year ago - I see a MySQL failover. Like this:

```<code>Instance ID                       Type
- sql-old-instance                MySQL 5.6
  - sql-old-instance-failover     MySQL Failover
- sql-new-instance                MySQL 5.7
</code>```

Why there is no Failover under the new one? Is there a different way of creating it?

Thank you

答:
Failover replicas are now called standby replicas and are not available until a failover event occurs.

The new failover strategy works like the old strategy, but now the data is written synchronously to the master instance disk and the standby instance disk, thus reducing the downtime in a failover event.

If you marked the option High availability (regional) the standby replica will be created for your Cloud SQL instance.

You can test the high availability by performing a manual failover event this will be started the standby instance in another zone and it will atttend all queries.

To return the traffic to the master you need to perform a second manual failover event called failback.

Body:
I am trying to set up a new failover to my SQL instance.

This is my second instance. I made the first one a year ago, so I don't exactly remember the procedure to create a Failover instance.

When I am creating the main instance, under

"Backups, recovery, and high availability"  > "Availability"

I select:

• High availability (regional)
Automatic failover to another zone within your selected region. Recommended for production instances. Increases cost.

Is this enough to ensure I have a failover?

I am asking because after I created the instance I see there is no failover.

While under my first instance - the old one I created a year ago - I see a MySQL failover. Like this:

Instance ID                       Type
- sql-old-instance                MySQL 5.6
  - sql-old-instance-failover     MySQL Failover
- sql-new-instance                MySQL 5.7

Why there is no Failover under the new one? Is there a different way of creating it?

Thank you


问:
getting issue while fetching multiple column using PostgreSQL select into
getting error while compiling below sp

```<code>CREATE OR REPLACE FUNCTION get_name ( IN E_ID NUMERIC, OUT N varchar(30), OUT S NUMERIC)
LANGUAGE plpgsql
AS $P1$
DECLARE CURSOR1 CURSOR FOR
SELECT NAME, SALARY INTO N,S
FROM PUBLIC.EMPLOYEE
WHERE(EMP_ID=E_ID);
BEGIN
-- CURSOR LEFT OPEN FOR CLIENT APPLICATION
OPEN CURSOR1;
END $P1$
</code>```

ERROR:  syntax error at or near ","

LINE 6: SELECT NAME, SALARY INTO N,S

whats wrong in this line

select col1, col2 into v1,v2 from table1  Is this correct in PostgreSQL?

答:
Remove 'INTO N,S' in your cursor declaration: this is not the right way to use cursor in PL/PGSQL.

After the cursor is opened,  you use FETCH INTO: this is where you are using table column from cursor result set.

See https://www.postgresql.org/docs/current/plpgsql-cursors.html

Body:
getting error while compiling below sp

CREATE OR REPLACE FUNCTION get_name ( IN E_ID NUMERIC, OUT N varchar(30), OUT S NUMERIC)
LANGUAGE plpgsql
AS $P1$
DECLARE CURSOR1 CURSOR FOR
SELECT NAME, SALARY INTO N,S
FROM PUBLIC.EMPLOYEE
WHERE(EMP_ID=E_ID);
BEGIN
-- CURSOR LEFT OPEN FOR CLIENT APPLICATION
OPEN CURSOR1;
END $P1$

ERROR:  syntax error at or near ","

LINE 6: SELECT NAME, SALARY INTO N,S

whats wrong in this line

select col1, col2 into v1,v2 from table1  Is this correct in PostgreSQL?


问:
How do I troubleshoot "simplexml_load_file() parser error: Entity 'nbsp' not defined"?
I use PHP to generate XML files. I have use some code below to avoid error.

```<code>$str = str_ireplace(array('<','>','&','\'','"'),array('<','>','&',''','"'),$str);
</code>```

but still cause fault.

```<code>simplexml_load_file() [function.simplexml-load-file] *[file name]* parser error : Entity 'nbsp' not defined in *[file name] [line]*
</code>```

The error text here:

```<code>Dallas  Dallas () is the third-largest city in Texas and the ninth-largest in the United States.
</code>```

In IE8, it seems to fault in (). So how many symbols should I notice?

答:
HTML specific entities - in this case   - are not valid xml entities, and that is what simplexml complains about; it reads the file as xml (not html) and finds entities which are not valid. You need to convert HTML entities back to their character representation first (you can use html_entity_decode() to do that)

```<code>$str = "some string containing html";
// this line will convert back html entities to regular characters
$str = html_entity_decode($str, ...);
// now convert special character to their xml entities
$str = str_ireplace(array('<','>','&','\'','"'),array('<','>','&',''','"'),$str);

save_to_xml($str);
</code>```

Note that if you use htmlentities() on your string before saving it in the xml, then that is the source of your problem (as you are converting html character to their respective html entities, which are not recognized by simplexml as xml entities).

```<code>// this won't work, the html entities it will uses are not valid xml entities
$str = htmlentities($str, ...)

save_to_xml($str);
</code>```

If you have troubles understanding it, think of it as two different languages, like spanish (html) and english (xml), a valid word in spanish ( ) doesn't mean it is also valid in english, no matter the similarities between the two languages.

Body:
I use PHP to generate XML files. I have use some code below to avoid error.

$str = str_ireplace(array('<','>','&','\'','"'),array('<','>','&',''','"'),$str);

but still cause fault.

simplexml_load_file() [function.simplexml-load-file] *[file name]* parser error : Entity 'nbsp' not defined in *[file name] [line]*

The error text here:

Dallas  Dallas () is the third-largest city in Texas and the ninth-largest in the United States.

In IE8, it seems to fault in (). So how many symbols should I notice?

Body:
HTML specific entities - in this case &nbsp; - are not valid xml entities, and that is what simplexml complains about; it reads the file as xml (not html) and finds entities which are not valid. You need to convert HTML entities back to their character representation first (you can use html_entity_decode() to do that)

$str = "some string containing html";
// this line will convert back html entities to regular characters
$str = html_entity_decode($str, ...);
// now convert special character to their xml entities
$str = str_ireplace(array('<','>','&','\'','"'),array('&lt;','&gt;','&amp;','&apos;','&quot;'),$str);

save_to_xml($str);

Note that if you use htmlentities() on your string before saving it in the xml, then that is the source of your problem (as you are converting html character to their respective html entities, which are not recognized by simplexml as xml entities).

// this won't work, the html entities it will uses are not valid xml entities
$str = htmlentities($str, ...)

save_to_xml($str);

If you have troubles understanding it, think of it as two different languages, like spanish (html) and english (xml), a valid word in spanish ( ) doesn't mean it is also valid in english, no matter the similarities between the two languages.


问:
How to scrape data from Google sheets to present it on webpage by using Gscript?
I was trying to use Dynamic HTML table in Googleapps script to fetch data from Google sheets. But not able to implement it successfully.</p>

答:
Have you tried using Apps Script?

You can use the Spreadsheet Service to interact with the spreadsheet.

Further reading:

Extending Google Sheets


问:
How to resolve https://kubernetes-charts.storage.googleapis.com" is not a valid chart repository
I am working on helm 2 and trying to deploy Tiller as pod.

```<code>>helm init --service-account tiller
</code>```

But i am getting below Error:
Error: error initializing: Looks like "https://kubernetes-charts.storage.googleapis.com" is not a valid chart repository or cannot be reached: Get https://kubernetes-charts.storage.googleapis.com/index.yaml: dial tcp 172.217.2.240:443: connect: connection timed out

Has anyone faced this error and if yes , what is the recommended way to overcome this for helm2?

答:
Just for history and maybe anyone else will face also. Community answer.

Errors like "Error: error initializing: Looks like "https://kubernetes-charts.storage.googleapis.com" is not a valid chart repository or cannot be reached: Get https://kubernetes-charts.storage.googleapis.com/index.yaml: dial tcp 172.217.2.240:443: connect: connection timed out" are typically due to problems with Proxy and non-direct connection.

This was discussed in related github issue Cannot perform helm init behind proxy, lots have same problems. As per topic - users can have such problems with some of helm versions. Its recommended to use it  starting from v2.11.0

Body:
I am working on helm 2 and trying to deploy Tiller as pod.

>helm init --service-account tiller

But i am getting below Error:
Error: error initializing: Looks like "https://kubernetes-charts.storage.googleapis.com" is not a valid chart repository or cannot be reached: Get https://kubernetes-charts.storage.googleapis.com/index.yaml: dial tcp 172.217.2.240:443: connect: connection timed out

Has anyone faced this error and if yes , what is the recommended way to overcome this for helm2?


问:
Java, moving from desktop app to web app
I'm going to write my first Java based web app, and I'm sort of lost how to begin.

Firstly, I would like a web app and a desktop app that do pretty much the same thing, without the hackish idea of embedding a web browser into the desktop app because that doesn't allow to easily make changes to the desktop without affecting the web app and vice versa.

Now, here my questions.

Right now, I have a bunch of POJOs and they communicate with a single class that, right now, uses a flat file as a "database", of course, in production, I would use a legitimate database and just change that single class. Is this a good idea? Will I be able to go from POJOs to a web app?

Should I use a framework? I would like to have this app written pretty soon, seeing that all the buisness logic is there, I just need to wrap it so its usable, so, I don't want to spend an extreme amount of time learning, say, Spring (which AFAIK is huge), but, I don't want to keep reinventing the wheel throughout my app either. I can always just use JSP and scriptlets...

If you said yes to the above, what framework(s) do you suggest? Please note that I would like a framework that I can start using in maybe 3-4 weeks of learning.

Will I have to start from scratch with the POJOs that I have written? They're well over 30k LOC, so, if it is like that, I'll be hesitant.

答:
You should definitely use a framework as otherwise sooner or later you'll end up writing your own.

If you use maven then simply typing mvn archetype:generate will give you a huge list of frameworks to choose from and it'll set up all of the scaffolding for you so you can just play with a few frameworks until you find the one that works for you.

Spring has good documentation and is surprisingly easy to get started with.  Don't be put off by the pages of documentation!  You could use JPA to store stuff in the database.  You should (in theory) just be able to annotate your existing POJO's to denote primary keys and so on and it should just work.  You can also use JSP's within Spring if that makes life easier.


问:
Testing two JSON objects for equality ignoring child order in Java
I'm looking for a JSON parsing library that supports comparing two JSON objects ignoring child order, specifically for unit testing JSON returning from a web service.

Do any of the major JSON libraries support this? The org.json library simply does a reference comparison.

答: Looking at the answers, I tried JSONAssert but it failed. So I used Jackson with zjsonpatch. I posted details in the SO answer here.</p>


问:
SQL query to find duplicate records and discount from COUNT
I am using below SQL query to count the records.
I would like to discount the duplicate testID after I got the count.

example:

```<code>select COUNT(*)  from PRODUCT where CLASS_TYPE = 'test'
</code>```

above query give 5 records

```<code>testID
1234-00-01
1234-00-01
1234-00-02
1234-00-02
1111222233
</code>```

I want to get the count = 5 - duplicate 2 = 3

Is there SQL query I can use to find out the duplicate records, then calculate the final count?

Body:
I am using below SQL query to count the records.
I would like to discount the duplicate testID after I got the count.

example:

select COUNT(*)  from PRODUCT where CLASS_TYPE = 'test'

above query give 5 records

testID
1234-00-01
1234-00-01
1234-00-02
1234-00-02
1111222233

I want to get the count = 5 - duplicate 2 = 3

Is there SQL query I can use to find out the duplicate records, then calculate the final count?

Body:
CREATE TABLE #Test
(
testID VARCHAR(100)
)

INSERT INTO #Test
(testID)
VALUES
('1234-00-01'),
('1234-00-01'),
('1234-00-02'),
('1234-00-02'),
('1111222233')

select COUNT(distinct testID) from #Test


问:
Dynamic component loader - Cannot read property 'viewContainerRef' of undefined
im following all steps of the ad-banner tutorial on Angular.io. But at the end  after all setup, i get an error comming from this component and function:

Ad-banner.component TS

```<code>loadComponent() {
    this.currentAdIndex = (this.currentAdIndex + 1) % this.ads.length;
    const adItem = this.ads[this.currentAdIndex];

    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(adItem.component);

    const viewContainerRef = this.adHost.viewContainerRef; ---->ERROR comes from this Line
    viewContainerRef.clear();

    const componentRef = viewContainerRef.createComponent(componentFactory);
    (<AdComponent>componentRef.instance).data = adItem.data;
  }
</code>```

I get the log correctly, the hero data comes to the home component where I'll display the ads, but not with the error, so can anyone sort me out?

EDIT
The Main Directive

```<code>import { Directive, ViewContainerRef } from '@angular/core';

@Directive({
  selector: '[ad-host]'
})
export class AdDirective {

  constructor(public viewContainerRef: ViewContainerRef) { }

}
</code>```

答:
Your component HTML should be :-

```<code><div class="ad-banner-example">
              <h3>Advertisements</h3>
              <ng-template ad-host></ng-template>
            </div>
</code>```

You component Ts  should have :-

```<code>@ViewChild(AdDirective, {static: true}) adHost: AdDirective;
</code>```

You AdhostDirective should be in declarations of your module.

and you should be calling this.loadComponent(); in ngoninit.

Body:
im following all steps of the ad-banner tutorial on Angular.io. But at the end  after all setup, i get an error comming from this component and function:

Ad-banner.component TS

loadComponent() {
    this.currentAdIndex = (this.currentAdIndex + 1) % this.ads.length;
    const adItem = this.ads[this.currentAdIndex];

    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(adItem.component);

    const viewContainerRef = this.adHost.viewContainerRef; ---->ERROR comes from this Line
    viewContainerRef.clear();

    const componentRef = viewContainerRef.createComponent(componentFactory);
    (<AdComponent>componentRef.instance).data = adItem.data;
  }

I get the log correctly, the hero data comes to the home component where I'll display the ads, but not with the error, so can anyone sort me out?

EDIT
The Main Directive

import { Directive, ViewContainerRef } from '@angular/core';

@Directive({
  selector: '[ad-host]'
})
export class AdDirective {

  constructor(public viewContainerRef: ViewContainerRef) { }

}

Body:
Your component HTML should be :-

<div class="ad-banner-example">
              <h3>Advertisements</h3>
              <ng-template ad-host></ng-template>
            </div>

You component Ts  should have :-

@ViewChild(AdDirective, {static: true}) adHost: AdDirective;

You AdhostDirective should be in declarations of your module.

and you should be calling this.loadComponent(); in ngoninit.


问:
Jmeter - Using varible: from JDBC request into JSR223 PostProcessor
Based on this thread: Jmeter - Using varible: from JDBC request into another JDBC query under loop

I tried to get variable from DB query and use it.

If i use into parameter value like: ${__V(id_${__intSum(${__jm__Loop Controller__idx},1,)},)} inside loop controller works perfectly fine.

But, if i want to use in JSR223 PostProcessor like:

```<code>def dbID = '${__V(id_${__intSum(${__jm__Loop Controller__idx},1,)},)}'
log.warn(dbID);
</code>```

or

```<code>def dbID = prop.getObject("id").get(i).get("id")
log.warn(dbID);
</code>```

My script fails.

What is the equivalent usage of ${__V(id_${__intSum(${__jm__Loop Controller__idx},1,)},)} into JSR223 PostProcessor?

My script:

答:
Use vars:

```<code> int id = Integer.parseInt(vars.get("__jm__Loop Controller__idx"))+1;
 vars.get("id_"+ id);
</code>```

Body:
Based on this thread: Jmeter - Using varible: from JDBC request into another JDBC query under loop

I tried to get variable from DB query and use it.

If i use into parameter value like: ${__V(id_${__intSum(${__jm__Loop Controller__idx},1,)},)} inside loop controller works perfectly fine.

But, if i want to use in JSR223 PostProcessor like:

def dbID = '${__V(id_${__intSum(${__jm__Loop Controller__idx},1,)},)}'
log.warn(dbID);

or

def dbID = prop.getObject("id").get(i).get("id")
log.warn(dbID);

My script fails.

What is the equivalent usage of ${__V(id_${__intSum(${__jm__Loop Controller__idx},1,)},)} into JSR223 PostProcessor?

My script:

Body:
Use vars:

 int id = Integer.parseInt(vars.get("__jm__Loop Controller__idx"))+1;
 vars.get("id_"+ id);


问:
Copying Specific Outgoing Links
There are 46 links on the site: http://www.math.hmc.edu/~ajb/PCMI/problem_solve.html. I want links from 7th link to 33th link. I need them separated to a file. Can I copy the outgoing links?

答: It is rather easy to parse the html and extract the < a > tags. And then find the href attributes. If you have those you can select which to keep and which to drop.</p>

OwnerDisplayName: UnixBasics

ContentLicense: CC BY-SA 2.5

Title: Copying Specific Outgoing Links

OwnerDisplayName: Gamecat


问:
Xamarin (Visual Studio 2019) Xaml Previewer Not working on Windows or Mac
I have created my first Xamarin Project, simply using the template created by Visual Studio 2019 Community Edition. When I try to open the previewer for the XAML for the IOS I get this error:

Image - https://i.stack.imgur.com/cPOVH.png
The error code:
    System.AggregateException: One or more errors occurred...
    https://pastebin.com/4kwiGW2U

This also occurs on my Macbook with the same setup.

Image - https://i.stack.imgur.com/ExzXa.png
The error code:
    System.AggregateException: One or more errors occurred...
    https://pastebin.com/RvdPdKUw

I am using visual studio version 16.6.0

This is my first Stack overflow post so I may not be providing all the necessary info, so please just comment and ask if you need any more info to properly answer the question :)

Thanks everyone!

P.S I am on Windows 10 with an AMD Ryzen 7 1700 and the Macbook is a Macbook Pro (2016), dual-core intel core i7

答:
Answer for anyone wondering:

Don't use the previewer, it is redundant since the implementation of Hot Reload. :)
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/xaml/hot-reload

Thanks, @Lex Li for the help!

Edit:

I've actually found a fix for this entirely. You can revert the version of the Xamarin.Forms NuGet Package to version 4.5.0.356. :)

Goodluck everyone!


问:
imageLoad glsl always return 0 in compute shader OpenGL 4.3
I know that there is another question with exactly the same title here however the solution provided over there does not work for my case.

I am trying to access pixel value from my compute shader. But the imageLoad function always returns 0.

Here is how I load the image:

void setTexture(GLuint texture_input, const char *fname)
{
    // set texture related

    int width, height, nbChannels;
    unsigned char *data = stbi_load(fname, &width, &height, &nbChannels, 0);
    if (data)
    {
        GLenum format;
        if (nbChannels == 1)
        {
            format = GL_RED;
        }
        else if (nbChannels == 3)
        {
            format = GL_RGB;
        }
        else if (nbChannels == 4)
        {
            format = GL_RGBA;
        }
        glActiveTexture(GL_TEXTURE0 + 1);
        gerr();
        glBindTexture(GL_TEXTURE_2D, texture_input);
        gerr();
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        gerr();
        glTexImage2D(GL_TEXTURE_2D, // target
                     0,             // level, 0 means base level
                     format,        // internal format of image specifies color  components
                     width, height, // what it says
                     0,             // border, should be 0 at all times
                     format, GL_UNSIGNED_BYTE, // data type of pixel data
                     data);
        gerr();
        glBindImageTexture(1,             // unit
                           texture_input, // texture id
                           0,             // level
                           GL_FALSE,      // is layered
                           0,             // layer no
                           GL_READ_ONLY,  // access type
                           GL_RGBA32F);

        // end texture handling
        gerr();
        glBindTexture(GL_TEXTURE_2D, 0); // unbind
    }
    else
    {
        std::cout << "Failed to load texture" << std::endl;
    }
    stbi_image_free(data);
}
```

<p>And here is the relevant declaration and calling code in the shader:</p>

<pre class="lang-c prettyprint-override"><code>
layout(rgba32f, location = 1, binding = 1) readonly uniform image2D in_image;

struct ImageTexture
{
    int width;
    int height;
};

vec3 imageValue(ImageTexture im, float u, float v, in vec3 p)
{
    u = clamp(u, 0.0, 1.0);
    v = 1 - clamp(v, 0.0, 1.0);
    int i = int(u * im.width);
    int j = int(v * im.height);

    if (i >= im.width)
        i = im.width - 1;

    if (j >= im.height)
        j = im.height - 1;

    vec3 color = imageLoad(in_image, ivec2(i, j)).xyz;

    if (color == vec3(0))
        color = vec3(0, u, v); // debug

    return color;
}
</code>```

I am seeing a green gradient instead of the contents of the image, which means my debugging code is in effect.

答:
Either the internal format of the texture does not match the format which is specified at glBindImageTexture or the format argument is not a valid enumerator constant, when the two-dimensional texture image is specified, because format is used twice, for the internal format and the format (see glTexImage2D):

glTexImage2D(GL_TEXTURE_2D, // target
                0,             // level, 0 means base level
                format,        // internal format of image specifies color
                // components
                width, height, // what it says
                0,             // border, should be 0 at all times
                format, GL_UNSIGNED_BYTE, // data type of pixel data
                data);
```
</blockquote>

<p>The <em>format</em> argument to <code>glBindImageTexture</code> is <code>GL_RGBA32F</code>:</p>

<blockquote>
  <pre class="lang-cpp prettyprint-override"><code>glBindImageTexture(1,             // unit
                    texture_input, // texture id
                    0,             // level
                    GL_FALSE,      // is layered
                    0,             // layer no
                    GL_READ_ONLY,  // access type
                    GL_RGBA32F);
</code>```

Hence, internal format has to be GL_RGBA32F. A possible fomrat is GL_RGBA:

glTexImage2D(GL_TEXTURE_2D, // target
                0,             // level, 0 means base level
                GL_RGBA32F,        // internal format of image specifies color
                // components
                width, height, // what it says
                0,             // border, should be 0 at all times
                GL_RGBA, GL_UNSIGNED_BYTE, // data type of pixel data
                data);
```

Body:
I know that there is another question with exactly the same title here however the solution provided over there does not work for my case.

I am trying to access pixel value from my compute shader. But the imageLoad function always returns 0.

Here is how I load the image:

void setTexture(GLuint texture_input, const char *fname)
{
    // set texture related

    int width, height, nbChannels;
    unsigned char *data = stbi_load(fname, &width, &height, &nbChannels, 0);
    if (data)
    {
        GLenum format;
        if (nbChannels == 1)
        {
            format = GL_RED;
        }
        else if (nbChannels == 3)
        {
            format = GL_RGB;
        }
        else if (nbChannels == 4)
        {
            format = GL_RGBA;
        }
        glActiveTexture(GL_TEXTURE0 + 1);
        gerr();
        glBindTexture(GL_TEXTURE_2D, texture_input);
        gerr();
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        gerr();
        glTexImage2D(GL_TEXTURE_2D, // target
                     0,             // level, 0 means base level
                     format,        // internal format of image specifies color  components
                     width, height, // what it says
                     0,             // border, should be 0 at all times
                     format, GL_UNSIGNED_BYTE, // data type of pixel data
                     data);
        gerr();
        glBindImageTexture(1,             // unit
                           texture_input, // texture id
                           0,             // level
                           GL_FALSE,      // is layered
                           0,             // layer no
                           GL_READ_ONLY,  // access type
                           GL_RGBA32F);

        // end texture handling
        gerr();
        glBindTexture(GL_TEXTURE_2D, 0); // unbind
    }
    else
    {
        std::cout << "Failed to load texture" << std::endl;
    }
    stbi_image_free(data);
}

And here is the relevant declaration and calling code in the shader:

layout(rgba32f, location = 1, binding = 1) readonly uniform image2D in_image;

struct ImageTexture
{
    int width;
    int height;
};

vec3 imageValue(ImageTexture im, float u, float v, in vec3 p)
{
    u = clamp(u, 0.0, 1.0);
    v = 1 - clamp(v, 0.0, 1.0);
    int i = int(u * im.width);
    int j = int(v * im.height);

    if (i >= im.width)
        i = im.width - 1;

    if (j >= im.height)
        j = im.height - 1;

    vec3 color = imageLoad(in_image, ivec2(i, j)).xyz;

    if (color == vec3(0))
        color = vec3(0, u, v); // debug

    return color;
}

I am seeing a green gradient instead of the contents of the image, which means my debugging code is in effect.

Body:
Either the internal format of the texture does not match the format which is specified at glBindImageTexture or the format argument is not a valid enumerator constant, when the two-dimensional texture image is specified, because format is used twice, for the internal format and the format (see glTexImage2D):

glTexImage2D(GL_TEXTURE_2D, // target
                0,             // level, 0 means base level
                format,        // internal format of image specifies color
                // components
                width, height, // what it says
                0,             // border, should be 0 at all times
                format, GL_UNSIGNED_BYTE, // data type of pixel data
                data);

The format argument to glBindImageTexture is GL_RGBA32F:

glBindImageTexture(1,             // unit
                    texture_input, // texture id
                    0,             // level
                    GL_FALSE,      // is layered
                    0,             // layer no
                    GL_READ_ONLY,  // access type
                    GL_RGBA32F);

Hence, internal format has to be GL_RGBA32F. A possible fomrat is GL_RGBA:

glTexImage2D(GL_TEXTURE_2D, // target
                0,             // level, 0 means base level
                GL_RGBA32F,        // internal format of image specifies color
                // components
                width, height, // what it says
                0,             // border, should be 0 at all times
                GL_RGBA, GL_UNSIGNED_BYTE, // data type of pixel data
                data);


问:
EF Core set XACT_ABORT for all database connections
I am using EF Core 3.1 to connect to SQL Server. I would like to SET XACT_ABORT ON for SQL Server on for all the connections I make in my application.

Is there a hook on start up or context creation that I can run this? Because I am working with AWS RDS, I do not have the ability to turn it on server wide.

Any help would be appreciated.

答:
Open the SqlConnection and set XACT_ABORT ON before passing the open SqlConnection to your DbContext constructor.  The pattern for BYO-connection in EF core is

```<code>SqlConnection con;
public Db(SqlConnection con)
{
    this.con = con;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.UseLoggerFactory(loggerFactory)
                  .UseSqlServer(con, o => o.UseRelationalNulls());

    base.OnConfiguring(optionsBuilder);
}
public override void Dispose()
{
    con.Close();
    base.Dispose();
}
</code>```

or if you're using DI, introduce a IDbConnectionFactory or somesuch and write

```<code>public Db(IDbConnectionfactory cf)
{
    this.con = cf.GetConnection();
}
</code>```

Passing an open connection to the DbContext constructor will prevent the DbContext from opening and closing the connection for each command.  This might slightly increase the size of your connection pool, but it shouldn't be a big deal.

Body:
Open the SqlConnection and set XACT_ABORT ON before passing the open SqlConnection to your DbContext constructor.  The pattern for BYO-connection in EF core is

SqlConnection con;
public Db(SqlConnection con)
{
    this.con = con;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.UseLoggerFactory(loggerFactory)
                  .UseSqlServer(con, o => o.UseRelationalNulls());

    base.OnConfiguring(optionsBuilder);
}
public override void Dispose()
{
    con.Close();
    base.Dispose();
}

or if you're using DI, introduce a IDbConnectionFactory or somesuch and write

public Db(IDbConnectionfactory cf)
{
    this.con = cf.GetConnection();
}

Passing an open connection to the DbContext constructor will prevent the DbContext from opening and closing the connection for each command.  This might slightly increase the size of your connection pool, but it shouldn't be a big deal.


问:
Lazarus DBGrid totally blank after record commit
I have been using Lazarus 2.x (free pascal) with firebird 3 (via flamerobin) and i try to commit records via TSQLConnection, TSQLQuery, TDBConnection in data module (appeals) etc.

I run the following code snippet and the records are successfully commited to firebird, but unfortunately DB connection afterwards is lost and thus there is not any record to be seen via DBGrid (not even column headers - totally blank). I have to terminate the application and reopen it to gain visual insight of my firebird via DBGrid.

Button click event

```<code>  appeals.SQLTransaction1.Active:=false;

  appeals.SQLQuery1.SQL.Text:='UPDATE appeals set name=:name,date_entry=:entry,date_suspended=:suspended,'+
  'date_court=:court,date_judgement=:judgement where id='+IntToStr(row_num);

  appeals.SQLQuery1.Params.ParamByName('name').AsString:=Trim(Edit1.Text);
  appeals.SQLQuery1.Params.ParamByName('entry').AsDate:=DateTimePicker1.Date;
  appeals.SQLQuery1.Params.ParamByName('suspended').AsDate:=IncDay(DateTimePicker1.Date,10);
  appeals.SQLQuery1.Params.ParamByName('court').AsDate:=DateTimePicker2.Date;
  appeals.SQLQuery1.Params.ParamByName('judgement').AsDate:=IncDay(DateTimePicker2.Date,20);

  appeals.SQLTransaction1.StartTransaction;
  appeals.SQLQuery1.ExecSQL;
  appeals.SQLTransaction1.Commit;
</code>```

I have also used .CommitRetaining as exactly mentioned in lazarus forum without success. Any idea what could i do in order to see my records live in DBGrid after commit.

Regards

答:
The reason the DBgrid shows nothing is that SqlQuery1.ExecSQL does not return a result set, so SqlQuery1 cannot supply any records for the DBGrid to display. So call SqlQuery1.Open after your Commit.

However, before you can call SqlQuery1.Open, you need to give it a SELECT statement to Execute, because a SQL UPDATE statement does not return a result set, as you have already found.  So, do something like:

```<code>  [...]
  appeals.SQLTransaction1.StartTransaction;
  appeals.SQLQuery1.ExecSQL;
  appeals.SQLTransaction1.Commit;

  appeals.SQLQuery1.Sql.Text := 'Select * from appeals where ...';
  appeals.SQLQuery1.Open;
</code>```

obviously replacing '...' in the 'where' clause by something appropriate.  Normally. a SELECT query should be parameterised to limit the number of rows returned and the amount of time the table is locked on the server.

Body:
I have been using Lazarus 2.x (free pascal) with firebird 3 (via flamerobin) and i try to commit records via TSQLConnection, TSQLQuery, TDBConnection in data module (appeals) etc.

I run the following code snippet and the records are successfully commited to firebird, but unfortunately DB connection afterwards is lost and thus there is not any record to be seen via DBGrid (not even column headers - totally blank). I have to terminate the application and reopen it to gain visual insight of my firebird via DBGrid.

Button click event

  appeals.SQLTransaction1.Active:=false;

  appeals.SQLQuery1.SQL.Text:='UPDATE appeals set name=:name,date_entry=:entry,date_suspended=:suspended,'+
  'date_court=:court,date_judgement=:judgement where id='+IntToStr(row_num);

  appeals.SQLQuery1.Params.ParamByName('name').AsString:=Trim(Edit1.Text);
  appeals.SQLQuery1.Params.ParamByName('entry').AsDate:=DateTimePicker1.Date;
  appeals.SQLQuery1.Params.ParamByName('suspended').AsDate:=IncDay(DateTimePicker1.Date,10);
  appeals.SQLQuery1.Params.ParamByName('court').AsDate:=DateTimePicker2.Date;
  appeals.SQLQuery1.Params.ParamByName('judgement').AsDate:=IncDay(DateTimePicker2.Date,20);

  appeals.SQLTransaction1.StartTransaction;
  appeals.SQLQuery1.ExecSQL;
  appeals.SQLTransaction1.Commit;

I have also used .CommitRetaining as exactly mentioned in lazarus forum without success. Any idea what could i do in order to see my records live in DBGrid after commit.

Regards

Body:
The reason the DBgrid shows nothing is that SqlQuery1.ExecSQL does not return a result set, so SqlQuery1 cannot supply any records for the DBGrid to display. So call SqlQuery1.Open after your Commit.

However, before you can call SqlQuery1.Open, you need to give it a SELECT statement to Execute, because a SQL UPDATE statement does not return a result set, as you have already found.  So, do something like:

  [...]
  appeals.SQLTransaction1.StartTransaction;
  appeals.SQLQuery1.ExecSQL;
  appeals.SQLTransaction1.Commit;

  appeals.SQLQuery1.Sql.Text := 'Select * from appeals where ...';
  appeals.SQLQuery1.Open;

obviously replacing '...' in the 'where' clause by something appropriate.  Normally. a SELECT query should be parameterised to limit the number of rows returned and the amount of time the table is locked on the server.


问:
ERROR 1049 (42000): Unknown database 'mydatabasename'
I am trying to restore database from .sql file , i have created the database in phpmyadmin and also using the create if not exist command in the .sql file which i am restoring to the database and both names of database are same in phpmyadmin and .sql file which is"mydatabase".

Here is the command which i am using to restore database.

```<code>mysql -uroot -pmypassword mydatabase<mydatabase.sql;
</code>```

When i execute the above command i am getting the following error, i have also given all the permission to the user upon this database.

```<code>ERROR 1049 (42000): Unknown database 'mydatabasename'
</code>```

答:
```<code>mysql -uroot -psecret mysql < mydatabase.sql
</code>```

Body:
I am trying to restore database from .sql file , i have created the database in phpmyadmin and also using the create if not exist command in the .sql file which i am restoring to the database and both names of database are same in phpmyadmin and .sql file which is"mydatabase".

Here is the command which i am using to restore database.

mysql -uroot -pmypassword mydatabase<mydatabase.sql;

When i execute the above command i am getting the following error, i have also given all the permission to the user upon this database.

ERROR 1049 (42000): Unknown database 'mydatabasename'


问:
Lua alternative to optim()
I'm currently looking for a lua alternative to the R programming languages; optim() function, if anyone knows how to deal with this?</p>

答:
http://numlua.luaforge.net/ looks interesting but doesn't seem to have minimization. The most promising lead seems to be a Lua wrapper for GSL, which has a variety of  multidimensional minimization algorithms included.

With derivatives
 - BFGS (method="BFGS" in optim) and two conjugate gradient methods (Fletcher-Reeves and Polak-Ribiere) which are two of the three options available for method="CG" in optim.
 Without derivatives
 - the Nelder-Mead simplex (method="Nelder-Mead", the default in optim).

More specifically, see here for the Lua shell documentation covering minimization.

I agree with @Zack that you should try to use existing implementations if at all possible, and that you might need a little bit more background knowledge to know which algorithms will be useful for your particular problems ...

Title: Lua alternative to optim()


问:
Using self.pack and self.grid works without classes, but fails with them
So I tried to use Tkinter Button Alignment in Grid to make a toolbar, but the difference is im using classes. So while they use frame.pack and button.grid, i get the error of using both pack and grid. Here is my code:

class Application(Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.master.title('Hi!')
        self.master.configure(bg='dark grey')
        self.pack(fill=X, side=TOP)
        self.create_toolbar()

    def create_toolbar(self):
        Home = Button(text='Home', bd=1)
        About = Button(text='About', bd=1)

        self.columnconfigure(0, weight=1)
        self.columnconfigure(1, weight=1)

        Home.grid(row=0, column=0, sticky=W+E)
        About.grid(row=0, column=1, sticky=W+E)
```

答:
It seems to me that the issue here is that the Widgets don't have master set, so they are defaulting to the class' master, where you have already used pack for geometry management.

The solution here is to set master=self when you are declaring your widgets, then when you go to place the widgets in the tk.Frame object you can use grid.


问:
Perforce: how to apply a later commit to a workspace synced to an earlier version?
I have a workspace synced to a changelist A.

I need to test version A with a changelist D, that was committed a few commits after A to the same branch. Cherry-pick it, so to speak.

How can I do it, other than p4 diff -du and applying a patch?

答:
If you're content with just getting the files in D (at their @D revision) while leaving everything else synced to A, this is simply:

```<code>p4 sync @D,@D
</code>```

But if some of the files in D were also affected by changes B and C, this might not be acceptable, since the D revisions will also contain those changes.  For a true cherry-pick, you have to open the files so you can do a set of resolves that ignore B and C before cherry-picking D.  My approach to this would be:

```<code>p4 -F "%depotFile%" files @D,@D | p4 -x - edit
p4 -F "%depotFile%@<D" files @D,@D | p4 -x - sync
p4 resolve -ay
p4 sync @D,@D
p4 resolve -am
</code>```

If there are merge conflicts you'll need to follow this up with an interactive p4 resolve.

Note that if you actually submit these files, you'll be rolling back B and C (at least within those specific files).

If B and C didn't affect the files in D (i.e. the files returned by p4 files @D,@D), then steps 2 and 3 will be no-ops -- the sync to @<D will just leave the files at their currently synced revisions (@A), and there will be nothing to resolve/ignore.  The resolve at step 5 will then do an automatic "accept theirs" (i.e. "copy from" D) since there's no "ignored" base revision in between A and D.

Another possible option would be to do this in a new branch (which you don't necessarily need to submit at any point):

```<code>p4 integ original_branch/...@A cherry_pick/...
p4 integ original_branch/...@D,@D cherry_pick/...
p4 resolve -am
</code>```

The main downside of this is that it'll entail syncing new copies of all the files when you open them for branch, but if the files aren't large/numerous enough for that to be a concern, the ergonomics of p4 integ lend themselves a bit better to this sort of thing, and it can be convenient to do things like this in a separate branch within your workspace so you can mess around freely without interfering with any other work in progress, and then discard the whole thing with a revert when you're done.

Body:
If you're content with just getting the files in D (at their @D revision) while leaving everything else synced to A, this is simply:

p4 sync @D,@D

But if some of the files in D were also affected by changes B and C, this might not be acceptable, since the D revisions will also contain those changes.  For a true cherry-pick, you have to open the files so you can do a set of resolves that ignore B and C before cherry-picking D.  My approach to this would be:

p4 -F "%depotFile%" files @D,@D | p4 -x - edit
p4 -F "%depotFile%@<D" files @D,@D | p4 -x - sync
p4 resolve -ay
p4 sync @D,@D
p4 resolve -am

If there are merge conflicts you'll need to follow this up with an interactive p4 resolve.

Note that if you actually submit these files, you'll be rolling back B and C (at least within those specific files).

If B and C didn't affect the files in D (i.e. the files returned by p4 files @D,@D), then steps 2 and 3 will be no-ops -- the sync to @<D will just leave the files at their currently synced revisions (@A), and there will be nothing to resolve/ignore.  The resolve at step 5 will then do an automatic "accept theirs" (i.e. "copy from" D) since there's no "ignored" base revision in between A and D.

Another possible option would be to do this in a new branch (which you don't necessarily need to submit at any point):

p4 integ original_branch/...@A cherry_pick/...
p4 integ original_branch/...@D,@D cherry_pick/...
p4 resolve -am

The main downside of this is that it'll entail syncing new copies of all the files when you open them for branch, but if the files aren't large/numerous enough for that to be a concern, the ergonomics of p4 integ lend themselves a bit better to this sort of thing, and it can be convenient to do things like this in a separate branch within your workspace so you can mess around freely without interfering with any other work in progress, and then discard the whole thing with a revert when you're done.


答:
If you want to get the total count and duplicate, you can try this SQL:

```<code>SELECT count(DISTINCT testID) as distinct_elements, count(*) as total_elements,
      (count(*) - count(DISTINCT testID)) as duplicate_elements
FROM PRODUCT
WHERE CLASS_TYPE = 'test';
</code>```

Title: SQL query to find duplicate records and discount from COUNT

Body:
If you want to get the total count and duplicate, you can try this SQL:

SELECT count(DISTINCT testID) as distinct_elements, count(*) as total_elements,
      (count(*) - count(DISTINCT testID)) as duplicate_elements
FROM PRODUCT
WHERE CLASS_TYPE = 'test';


问:
How can I check if an array contains a value of another array?
I would like to check to see if an array contains a value from another array. For example, I would like to check if the array A contains a value from an array B.

I'm looking for any value not one specific value.

答:
Return true if any value matches

```<code>  private fun ArrayList<Int>.isAnyValueMatched(list2:ArrayList<Int> ):Boolean{
        this.forEach { value1->
            list2.forEach {
                value2->
                if (value1==value2) return true
            }
        }
        return false
    }
</code>```

Or use intersect(
Returns a set containing all elements that are contained by both this array and the specified collection)

```<code>private fun ArrayList<Int>.isAnyValueMatched(list2:ArrayList<Int> ):Boolean{
        return (this intersect list2).isNotEmpty()
 }
</code>```

Body:
Return true if any value matches

  private fun ArrayList<Int>.isAnyValueMatched(list2:ArrayList<Int> ):Boolean{
        this.forEach { value1->
            list2.forEach {
                value2->
                if (value1==value2) return true
            }
        }
        return false
    }

Or use intersect(
Returns a set containing all elements that are contained by both this array and the specified collection)

private fun ArrayList<Int>.isAnyValueMatched(list2:ArrayList<Int> ):Boolean{
        return (this intersect list2).isNotEmpty()
 }


问:
spacial character replacement using sed or awk
I have a string in a dat file

```<code>Times-New   $\Gamma$
</code>```

and I want to replace it using sed or awk (I would prefer to use awk) utility  with

```<code>/Symbol G
</code>```

I could replace only one $ sign but failed for the remaining text.

So what I want is

```<code>sed   's/Times-New   $\Gamma$/Symbol G/g'  case.dat
</code>```

Could you please help me?

答:
Could you please try following, written and tested with shown samples. We need  to escape \ and $ to make awk treat them as a literal character in program.

```<code>awk '{gsub(/Times-New   \$\\Gamma\$/,"/Symbol G")} 1' Input_file
</code>```

OR as per OP's comment try(Thanks to anubhava sir for adding solution):

```<code>awk '{gsub(/Times-New[ \t]+(G|\$\\Gamma\$)/, "/Symbol G")} 1' Input_file
</code>```

With GNU sed try:

```<code>sed -E 's/Times-New   \$\\Gamma\$/Symbol G/g' Input_file
</code>```

Body:
I have a string in a dat file

Times-New   $\Gamma$

and I want to replace it using sed or awk (I would prefer to use awk) utility  with

/Symbol G

I could replace only one $ sign but failed for the remaining text.

So what I want is

sed   's/Times-New   $\Gamma$/Symbol G/g'  case.dat

Could you please help me?

Body:
Could you please try following, written and tested with shown samples. We need  to escape \ and $ to make awk treat them as a literal character in program.

awk '{gsub(/Times-New   \$\\Gamma\$/,"/Symbol G")} 1' Input_file

OR as per OP's comment try(Thanks to anubhava sir for adding solution):

awk '{gsub(/Times-New[ \t]+(G|\$\\Gamma\$)/, "/Symbol G")} 1' Input_file

With GNU sed try:

sed -E 's/Times-New   \$\\Gamma\$/Symbol G/g' Input_file


问:
Android emulator no sound in ubuntu
I am running android emulator in ubuntu-19.10 and I have attempted following solutions with no results,

Link-1

Link-2

Link-3

Error,

```<code>1:10 PM Emulator: pulseaudio: pa_context_connect() failed
1:10 PM Emulator: pulseaudio: Reason: Connection refused
1:10 PM Emulator: pulseaudio: Failed to initialize PA contextaudio: Could not init `pa' audio driver
</code>```

Some notes on solution I tried,

When trying Link-1 i don't see "Qemu-system" in settings. Also created many different versions of AVDs but does seem to work.

After trying Link-2 pulseaudio -D command errors out.

I have also tried Link-3 which looks like widely suggested solution in multiple blog posts. But still I find the same error on emulator startup. I would like to note that I am not smart enough understand this solution.

Thanks in advance for helping out.

答:
I got crazy while trying to solve this issue but finally, it was solved. I figured out that we have to enable multiple simultaneous audio outputs in order to hear both sounds the emulator and the OS.

The solution is by installing paprefs small app as the following.

1- Install it:

```<code>$ sudo apt install paprefs
</code>```

2- Open it:

```<code>$ paprefs
</code>```

3- Go to the last tab Simultaneous Output and click on the only option there in order to enable the Simultaneous Output.

4- Restart it:

```<code>$ pulseaudio -k
</code>```

5- If it fails then you have to restart the daemon

```<code>$ pulseaudio -D
</code>```

6- Almost finished, go to the system settings and navigate to Sounds options and change the output sounds to the newly added one as below.

Title: Android emulator no sound in ubuntu

Body:
I am running android emulator in ubuntu-19.10 and I have attempted following solutions with no results,

Link-1

Link-2

Link-3

Error,

1:10 PM Emulator: pulseaudio: pa_context_connect() failed
1:10 PM Emulator: pulseaudio: Reason: Connection refused
1:10 PM Emulator: pulseaudio: Failed to initialize PA contextaudio: Could not init `pa' audio driver

Some notes on solution I tried,

When trying Link-1 i don't see "Qemu-system" in settings. Also created many different versions of AVDs but does seem to work.

After trying Link-2 pulseaudio -D command errors out.

I have also tried Link-3 which looks like widely suggested solution in multiple blog posts. But still I find the same error on emulator startup. I would like to note that I am not smart enough understand this solution.

Thanks in advance for helping out.

Body:
I got crazy while trying to solve this issue but finally, it was solved. I figured out that we have to enable multiple simultaneous audio outputs in order to hear both sounds the emulator and the OS.

The solution is by installing paprefs small app as the following.

1- Install it:

$ sudo apt install paprefs

2- Open it:

$ paprefs

3- Go to the last tab Simultaneous Output and click on the only option there in order to enable the Simultaneous Output.

4- Restart it:

$ pulseaudio -k

5- If it fails then you have to restart the daemon

$ pulseaudio -D

6- Almost finished, go to the system settings and navigate to Sounds options and change the output sounds to the newly added one as below.


问:
Refresh multiple div-[unique_ID]'s with jQuery and .load()?
I am working on modifying a plugin to allow users to vote on posts. My page looks something like this (though this is simplified of course):

```<code><div class="vote vote1">
//voting buttons
</div>

<div class="vote vote2">
//voting buttons
</div>

<div class="vote vote3">
//voting buttons
</div>

<div class="vote vote4">
//voting buttons
</div>
</code>```

As you can see, each voting div has a unique class associated with it, vote[id]. My trouble is that after submitting the vote to my vote.php file I need to refresh this unique voting div with the new data. I have been able to do this without trouble when I hardcode a particular voting div's unique id into .load(), but I cannot seem to get this to work dynamically for all voting divs using a single script. Would somebody be able to help me out in refreshing the unique voting div that has been clicked?

```<code><script type="text/javascript">
jQuery(document).ready(function(){
$(".vote a.can-vote").click(
    function() {
        var some = jQuery(this).parent();
        var thepost = jQuery(this).attr("post");
        var theuser = jQuery(this).attr("user");
        var updown = jQuery(this).attr("up-down");
        var is_update = jQuery(this).attr("update");
        var votebox = ".vote"+thepost+" span";

        jQuery.ajax({
            type: "POST",
            url: "<?php bloginfo('template_url'); ?>/vote.php",
            data: {user: theuser, post: thepost, up_down: updown, update: is_update},
            cache: false,
            success: function( data ){
                jQuery(some).load('http://mydomain.com div.vote[ID]');
            }
        });
        return false;
    });
});
</script>
</code>```

I'm sorry if this is a simple question but I've been trying my best to figure it out for two days with no luck; thank you in advance for any help.

答:
My guess is that you're using the "jQuery()"-selector instead of the $()-selector in order to avoid conflicts with other Javascript libraries on the page. Yet you are using the $-selector before ('.vote a.can-vote') and not the jQuery()-alternative. This might be the cause of your script not executing well.

You are able to use the regular $-selector by using the noConflict() function. (http://api.jquery.com/jQuery.noConflict/)

Body:
I am working on modifying a plugin to allow users to vote on posts. My page looks something like this (though this is simplified of course):

//voting buttons

//voting buttons

//voting buttons

//voting buttons

As you can see, each voting div has a unique class associated with it, vote[id]. My trouble is that after submitting the vote to my vote.php file I need to refresh this unique voting div with the new data. I have been able to do this without trouble when I hardcode a particular voting div's unique id into .load(), but I cannot seem to get this to work dynamically for all voting divs using a single script. Would somebody be able to help me out in refreshing the unique voting div that has been clicked?

I'm sorry if this is a simple question but I've been trying my best to figure it out for two days with no luck; thank you in advance for any help.