问:
How to hold plot figures in Python
I have this code, where c_X,c_Y,c_Z,X,Y,Z X_2,Y_2,Z_2,X_4,Y_4,Z_4, are lists of points (my data).

```<code>import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

for i in range (2):

    fig = plt.figure(i)
    ax = fig.add_subplot(111, projection='3d')

    ax.scatter(c_X,c_Y,c_Z, color = 'midnightblue')
    ax.scatter(X, Y, Z, color = 'mediumaquamarine')
    ax.scatter(X_2,Y_2,Z_2, color = 'cadetblue')
    ax.scatter(X_4,Y_4,Z_4, color = 'cadetblue')
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('z')
    plt.draw()
</code>```

How can i hold or get the 3 plots, in 3 different figures, in the end ?

答:
If you have only 4 figures you can just use:

```<code>fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(c_X,c_Y,c_Z, color = 'midnightblue')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.show()

fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(X, Y, Z, color = 'mediumaquamarine')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.show()

fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(X_2,Y_2,Z_2, color = 'cadetblue')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.show()

fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(X_4,Y_4,Z_4, color = 'cadetblue')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.show()
</code>```

Is that working?

Or you can merge your arrays into one for X, one for Y and one for Z. Create a list for the color and use a loop:

```<code>c = ['color1', 'color2', etc]

for i in range(k):
    plt.figure()
    ax = Axes3D(fig)
    ax.scatter(X[i], Y[i], Z[i], color=c[i])
    plt.show()
</code>```

Title: How to hold plot figures in Python

Body:
I have this code, where c_X,c_Y,c_Z,X,Y,Z X_2,Y_2,Z_2,X_4,Y_4,Z_4, are lists of points (my data).

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

for i in range (2):

    fig = plt.figure(i)
    ax = fig.add_subplot(111, projection='3d')

    ax.scatter(c_X,c_Y,c_Z, color = 'midnightblue')
    ax.scatter(X, Y, Z, color = 'mediumaquamarine')
    ax.scatter(X_2,Y_2,Z_2, color = 'cadetblue')
    ax.scatter(X_4,Y_4,Z_4, color = 'cadetblue')
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('z')
    plt.draw()

How can i hold or get the 3 plots, in 3 different figures, in the end ?

Body:
If you have only 4 figures you can just use:

fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(c_X,c_Y,c_Z, color = 'midnightblue')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.show()

fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(X, Y, Z, color = 'mediumaquamarine')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.show()

fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(X_2,Y_2,Z_2, color = 'cadetblue')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.show()

fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(X_4,Y_4,Z_4, color = 'cadetblue')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.show()

Is that working?

Or you can merge your arrays into one for X, one for Y and one for Z. Create a list for the color and use a loop:

c = ['color1', 'color2', etc]

for i in range(k):
    plt.figure()
    ax = Axes3D(fig)
    ax.scatter(X[i], Y[i], Z[i], color=c[i])
    plt.show()


来源: stackexchange

问:
SQL Server - How to record which entries are duplicates?
I am working on a project in SQL Server to create an audit database from 3 different criteria. The 3 separate queries each work exactly how I want them to and are used to populate respective temp tables. From that I used a union to bring those 3 into one final aggregated temp table. The problem I am having is that some of my entries meet the criteria of more than one of my initial queries, creating duplicates. I want to remove these duplicates, but also be able to record that the entries came up on multiple bases.

```<code>SELECT * INTO #all_audits FROM
(SELECT * FROM #audita
UNION ALL
SELECT * FROM #auditb
UNION ALL
SELECT * FROM #auditc) as tmp
</code>```

I started by adding a column in each initial temp table with the name of the audit. This worked without a hitch to be able to tell on the union. Now I was thinking that I should add another column for audit type 2, to record the second audit that an entry was flagged on, but I'm not quite sure how to go about it. I know an update set sequence would probably work for my current format that I was thinking of.

```<code>ALTER TABLE #all_audits  ADD AuditType2 varchar(255)
</code>```

Each of these tables above shares the same primary key. Tables also each have a column "AuditType" that labels which audit they are from.

Now this is probably simple, but the code to actually perform that match and still remove duplicates is where I am stuck. Something like this?

```<code>UPDATE #all_audits
SET AuditType2 = AuditType
FROM #all_audits
WHERE Primary_Key IN
        (SELECT Primary_Key
        FROM #all_audits
        GROUP BY Primary Key HAVING COUNT(*)>1)
</code>```

答:
If I am correctly understanding your requirement, you want set new column auditType2 on rows whose primary_key is not unique.

If so, you could use window functions and an updateable cte:

```<code>with cte as (
    select auditType, auditType2, count(*) over(partition by primary_key) cnt
    from  #all_audit
)
update cte set auditType2 = auditType where cnt > 1
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am working on a project in SQL Server to create an audit database from 3 different criteria. The 3 separate queries each work exactly how I want them to and are used to populate respective temp tables. From that I used a union to bring those 3 into one final aggregated temp table. The problem I am having is that some of my entries meet the criteria of more than one of my initial queries, creating duplicates. I want to remove these duplicates, but also be able to record that the entries came up on multiple bases.

SELECT * INTO #all_audits FROM
(SELECT * FROM #audita
UNION ALL
SELECT * FROM #auditb
UNION ALL
SELECT * FROM #auditc) as tmp

I started by adding a column in each initial temp table with the name of the audit. This worked without a hitch to be able to tell on the union. Now I was thinking that I should add another column for audit type 2, to record the second audit that an entry was flagged on, but I'm not quite sure how to go about it. I know an update set sequence would probably work for my current format that I was thinking of.

ALTER TABLE #all_audits  ADD AuditType2 varchar(255)

Each of these tables above shares the same primary key. Tables also each have a column "AuditType" that labels which audit they are from.

Now this is probably simple, but the code to actually perform that match and still remove duplicates is where I am stuck. Something like this?

UPDATE #all_audits
SET AuditType2 = AuditType
FROM #all_audits
WHERE Primary_Key IN
        (SELECT Primary_Key
        FROM #all_audits
        GROUP BY Primary Key HAVING COUNT(*)>1)

Body:
If I am correctly understanding your requirement, you want set new column auditType2 on rows whose primary_key is not unique.

If so, you could use window functions and an updateable cte:

with cte as (
    select auditType, auditType2, count(*) over(partition by primary_key) cnt
    from  #all_audit
)
update cte set auditType2 = auditType where cnt > 1


问:
Calling Vuex mutator within Axios interceptor
I would like to trigger a mutation from within an interceptor. In this case, trigger the logout mutation whenever Axios encounters an http 403.

I imported Vuex mutations and mapped as I've done elsewhere but I have not been able to access it within the Axios interceptor error function. I've added my interceptor config in App.vue's created() method.

I've tried the syntax from these 2 questions without success, most likely due to my project using modules, and the Axios config being located in a created() method.

https://www.reddit.com/r/vuejs/comments/eq5eej/question_how_to_access_vuex_store_modules_mode_in/ <- Axios config in a seperate file, is this the best practice?

Can't access Vuex storage mutation inside Axios interceptor <- Not using modules

App.vue

```<code><script>
import { mapMutations } from "vuex";
import axios from 'axios';
export default {
  methods: {
    ...mapMutations(["logout"])
  },
  created(){
    axios.interceptors.response.use(
      function (response) {
        return response;
      },
      function (error) {
        if (error.response.status === 403) {
          this.logout()
            .then(() => {
              this.$router.push("/");
            })
        }
    });
  }
}
</script>
</code>```

EDIT
Adding screenshot of results from the below answers

答:
You will either need to use an arrow function or bind the this context to your function in order to access this correctly

```<code><script>
import { mapMutations } from "vuex";
import axios from 'axios';
export default {
  methods: {
    ...mapMutations(["logout"])
  },
  created(){
    axios.interceptors.response.use(
      function (response) {
        return response;
      },
      (error) => {
        if (error.response.status === 403) {
          this.logout()
            .then(() => {
              this.$router.push("/");
            })
        }
      }
    );
  }
}
</script>
</code>```

or

```<code><script>
import { mapMutations } from "vuex";
import axios from 'axios';
export default {
  methods: {
    ...mapMutations(["logout"])
  },
  created(){
    axios.interceptors.response.use(
      function (response) {
        return response;
      },
      function (error) {
        if (error.response.status === 403) {
          this.logout()
            .then(() => {
              this.$router.push("/");
            })
        }
      }.bind(this)
    );
  }
}
</script>
</code>```

Body:
I would like to trigger a mutation from within an interceptor. In this case, trigger the logout mutation whenever Axios encounters an http 403.

I imported Vuex mutations and mapped as I've done elsewhere but I have not been able to access it within the Axios interceptor error function. I've added my interceptor config in App.vue's created() method.

I've tried the syntax from these 2 questions without success, most likely due to my project using modules, and the Axios config being located in a created() method.

https://www.reddit.com/r/vuejs/comments/eq5eej/question_how_to_access_vuex_store_modules_mode_in/ <- Axios config in a seperate file, is this the best practice?

Can't access Vuex storage mutation inside Axios interceptor <- Not using modules

App.vue

EDIT
Adding screenshot of results from the below answers

Body:
You will either need to use an arrow function or bind the this context to your function in order to access this correctly

<script>
import { mapMutations } from "vuex";
import axios from 'axios';
export default {
  methods: {
    ...mapMutations(["logout"])
  },
  created(){
    axios.interceptors.response.use(
      function (response) {
        return response;
      },
      (error) => {
        if (error.response.status === 403) {
          this.logout()
            .then(() => {
              this.$router.push("/");
            })
        }
      }
    );
  }
}
</script>

or

<script>
import { mapMutations } from "vuex";
import axios from 'axios';
export default {
  methods: {
    ...mapMutations(["logout"])
  },
  created(){
    axios.interceptors.response.use(
      function (response) {
        return response;
      },
      function (error) {
        if (error.response.status === 403) {
          this.logout()
            .then(() => {
              this.$router.push("/");
            })
        }
      }.bind(this)
    );
  }
}
</script>


答:
You are close. The only thing that is stopping you is that you were declaring functions using the function() {} declaration, rather than the "fat-arrow" function declaration, which was creating a new scope (this was different). You should see the differences between the two changes below.

// Your current script.
import { mapMutations } from "vuex";
import axios from 'axios';
export default {
  methods: {
    ...mapMutations(["logout"])
  },
  created(){
    axios.interceptors.response.use(
      function (response) {
        return response;
      },
      function (error) {
        if (error.response.status === 403) {
          this.logout()
            .then(() => {
              this.$router.push("/");
            })
        }
    });
  }
}

// Updated
import { mapMutations } from "vuex";
import axios from 'axios';
export default {
  methods: {
    ...mapMutations(["logout"])
  },
  mounted() {
    axios.interceptors.response.use(
      (response) => response,
      (error) => {
        if (error.response.status === 403) {
          return this.logout()
            .then(() => this.$router.push("/"));
        }
        else {
          return Promise.reject(err);
        }
    });
  }
}
</script>```

Title: Calling Vuex mutator within Axios interceptor


问:
namespace altering the function definition
I have a small snipped of code, which just produces a function to get the current directory for either Windows or Linux platform:

```<code>#include <stdio.h>  /* defines FILENAME_MAX */
#include <string>
#ifdef WINDOWS
    #include <direct.h>
    #define GetCurrentDir _getcwd
#else
    #include <unistd.h>
    #define GetCurrentDir getcwd
 #endif

    std::string getcwd(){
    char mCurrentPath[FILENAME_MAX];
    GetCurrentDir(mCurrentPath, sizeof(mCurrentPath));
    return *(new std::string (mCurrentPath));

    }
</code>```

This is all great and working; however, I'd like to make the getcwd() function inside the namespace, fUtils, hence I did this:

```<code>#include <stdio.h>  /* defines FILENAME_MAX */
#include <string>
#ifdef WINDOWS
    #include <direct.h>
    #define GetCurrentDir _getcwd
#else
    #include <unistd.h>
    #define GetCurrentDir getcwd
 #endif

namespace fUtils{
    std::string getcwd(){
    char mCurrentPath[FILENAME_MAX];
    GetCurrentDir(mCurrentPath, sizeof(mCurrentPath));
    return *(new std::string (mCurrentPath));

    }
}
</code>```

But this gives an error in VSCode which says:

no matching function for call to 'getcwd'

What mistake am I making in this? If this isn't how I put the function to the namespace fUtils, then how should I put it into the namespace?

答:
Your fUtils::getcwd() function is attempting to call itself when the GetCurrentDir macro is evaluated (to getcwd), and this results in a function that expects no argument but is being given two arguments.

To resolve this, add the global namespace operator (::) in the definitions for GetCurrentDir, as follows:

#ifdef WINDOWS
    #include <direct.h>
    #define GetCurrentDir ::_getcwd
#else
    #include <unistd.h>
    #define GetCurrentDir ::getcwd
#endif
```

Then, in your function body, it is clear to the compiler that your aren't looking for a 'recursive' (and invalid) call.

Body:
I have a small snipped of code, which just produces a function to get the current directory for either Windows or Linux platform:

#include <stdio.h>  /* defines FILENAME_MAX */
#include <string>
#ifdef WINDOWS
    #include <direct.h>
    #define GetCurrentDir _getcwd
#else
    #include <unistd.h>
    #define GetCurrentDir getcwd
 #endif

    std::string getcwd(){
    char mCurrentPath[FILENAME_MAX];
    GetCurrentDir(mCurrentPath, sizeof(mCurrentPath));
    return *(new std::string (mCurrentPath));

    }

This is all great and working; however, I'd like to make the getcwd() function inside the namespace, fUtils, hence I did this:

#include <stdio.h>  /* defines FILENAME_MAX */
#include <string>
#ifdef WINDOWS
    #include <direct.h>
    #define GetCurrentDir _getcwd
#else
    #include <unistd.h>
    #define GetCurrentDir getcwd
 #endif

namespace fUtils{
    std::string getcwd(){
    char mCurrentPath[FILENAME_MAX];
    GetCurrentDir(mCurrentPath, sizeof(mCurrentPath));
    return *(new std::string (mCurrentPath));

    }
}

But this gives an error in VSCode which says:

no matching function for call to 'getcwd'

What mistake am I making in this? If this isn't how I put the function to the namespace fUtils, then how should I put it into the namespace?

Body:
Your fUtils::getcwd() function is attempting to call itself when the GetCurrentDir macro is evaluated (to getcwd), and this results in a function that expects no argument but is being given two arguments.

To resolve this, add the global namespace operator (::) in the definitions for GetCurrentDir, as follows:

#ifdef WINDOWS
    #include <direct.h>
    #define GetCurrentDir ::_getcwd
#else
    #include <unistd.h>
    #define GetCurrentDir ::getcwd
#endif

Then, in your function body, it is clear to the compiler that your aren't looking for a 'recursive' (and invalid) call.


问:
How can I open a text file with my executable?
I want to right-click on a text file and "Open With..." it with my own program, but I can't find any information on how to do that. I want to make my program in C++ or with WinForms (C#).
I want to open that file and to use my program as an interpreter on a small "homemade programming language", so I want to pass the data from the file directly to my program.
Can anyone help me?
*hope I'm clear enough on what I'm trying to do.</p>

答:
I'm just gonna to answer your Question for C#. If you still need C++ support you can tell me.

Option 1 - Drop down:

So if you for example create a Console-Application in C# (Visual Studio), it will look like this:

As you can see in the Picture: the Program accepts Arguments (args String Array)
If you drag & drop your file on your .exe, the filepath of the file you dropped will be saved in the args String Array. Now you can read the file (for example with the File-Class).

Option 2 - Right Click -> Open with my Program:

For that, you can simply add a new entry in HKEY_CLASSES_ROOT\Directory\Background\shell (Windows Registry) to register you Program as a "Right Click Menu Program".
Here is a detailed How-To:

https://www.howtogeek.com/howto/windows-vista/add-any-application-to-the-desktop-right-click-menu-in-vista/

After you added your Program to the Windows Registry you can proceed as shown in Option 1 (args).

Any more questions? Let me know.

Greets
Bennet

EDIT:
Sorry, didnt really read the comments :D but i guess your Question is answered. I will let this stay here for future readers which dont read the comments either ;)


问:
How okay is it to call vuex actions asynchronously from router.js?
I have already achieved this. But is there any drawback of doing this?</p>

答:
It depends on the case I believe, but most likely if you are doing it, there is a good chance it is spaghetti code.

The drawback is, most likely your structure is not solid


问:
Issues with creating an animation using matplotlib for normal, gaussian, exponential and gamma distributions
I have the following code below to create an animation for a Gaussian, Normal, Exponential and Gamma distribution:

```<code>import matplotlib.animation as animation
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()

def update(curr):
        if curr == n:
            a.event_source.stop()
        plt.cla()
        plt.axis([-7,21,0,0.6])
        bins = np.arange(-7,21,1)
        plt.hist(x[:curr], bins=bins)
        plt.gca().set_title('Sampling the' + " "+distribution+" " + 'Distribution')
        plt.gca().set_ylabel('Frequency')
        plt.gca().set_xlabel('Value')
        plt.annotate('n = {}'.format(curr), [3,27])

n = 10000
x = np.random.normal(-2.5, 1, 10000)
distribution = 'normal'
a1 = animation.FuncAnimation(fig, update, interval=100)
x = np.random.gamma(2, 1.5, 10000)
distribution = 'gamma'
a2 = animation.FuncAnimation(fig, update, interval=100)
x = np.random.exponential(2, 10000)+7
distribution = 'exponential'
a3 = animation.FuncAnimation(fig, update, interval=100)
x = np.random.uniform(14,20, 10000)
distribution = 'uniform'
a4 = animation.FuncAnimation(fig, update, interval=100)
</code>```

I want to create 4 animations, one of a normal distribution, one of a Gaussian distribution, one of an exponential distribution and one of a gamma distribution.

However, when I run this code I get a blank graph (with only the y-axis and x-axis).

Could anyone tell me where I am going wrong?

答:
I rearranged your code a little bit to make the animation work properly.

The animation is updated in the animate() function, instead I use the plot_histogram() function to avoid repetitions.

The parameter that is updated frame by frame is i, which in this case is used to increase the number of samples from which the np.random._ functions draw.

```<code>import matplotlib.animation as animation
import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots(2, 2, figsize = (8, 8))
bins = np.arange(-7,21,1)

def animate(i):
        normal_data = np.random.normal(-2.5, 1, 100*i)
        plot_histogram(ax[0, 0], normal_data, 'Sampling the Normal Distribution', 'n = {}'.format(100*i))

        gamma_data = np.random.gamma(2, 1.5, 100*i)
        plot_histogram(ax[0, 1], gamma_data, 'Sampling the Gamma Distribution', 'n = {}'.format(100*i))

        exponential_data = np.random.exponential(2, 100*i)+7
        plot_histogram(ax[1, 0], exponential_data, 'Sampling the Exponential Distribution', 'n = {}'.format(100*i))

        uniform_data = np.random.uniform(14,20, 100*i)
        plot_histogram(ax[1, 1], uniform_data, 'Sampling the Uniform Distribution', 'n = {}'.format(100*i))

def plot_histogram(ax, data, title, annotation):
    ax.cla()
    ax.hist(data, bins = bins)
    ax.set_title(title)
    ax.set_ylabel('Frequency')
    ax.set_xlabel('Value')
    ax.annotate(annotation, [3, 27])

ani = animation.FuncAnimation(fig, animate, frames = 11, interval = 200)

plt.show()
</code>```

With this code I get this animation:

Body:
I have the following code below to create an animation for a Gaussian, Normal, Exponential and Gamma distribution:

import matplotlib.animation as animation
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()

def update(curr):
        if curr == n:
            a.event_source.stop()
        plt.cla()
        plt.axis([-7,21,0,0.6])
        bins = np.arange(-7,21,1)
        plt.hist(x[:curr], bins=bins)
        plt.gca().set_title('Sampling the' + " "+distribution+" " + 'Distribution')
        plt.gca().set_ylabel('Frequency')
        plt.gca().set_xlabel('Value')
        plt.annotate('n = {}'.format(curr), [3,27])

n = 10000
x = np.random.normal(-2.5, 1, 10000)
distribution = 'normal'
a1 = animation.FuncAnimation(fig, update, interval=100)
x = np.random.gamma(2, 1.5, 10000)
distribution = 'gamma'
a2 = animation.FuncAnimation(fig, update, interval=100)
x = np.random.exponential(2, 10000)+7
distribution = 'exponential'
a3 = animation.FuncAnimation(fig, update, interval=100)
x = np.random.uniform(14,20, 10000)
distribution = 'uniform'
a4 = animation.FuncAnimation(fig, update, interval=100)

I want to create 4 animations, one of a normal distribution, one of a Gaussian distribution, one of an exponential distribution and one of a gamma distribution.

However, when I run this code I get a blank graph (with only the y-axis and x-axis).

Could anyone tell me where I am going wrong?

Body:
I rearranged your code a little bit to make the animation work properly.

The animation is updated in the animate() function, instead I use the plot_histogram() function to avoid repetitions.

The parameter that is updated frame by frame is i, which in this case is used to increase the number of samples from which the np.random._ functions draw.

import matplotlib.animation as animation
import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots(2, 2, figsize = (8, 8))
bins = np.arange(-7,21,1)

def animate(i):
        normal_data = np.random.normal(-2.5, 1, 100*i)
        plot_histogram(ax[0, 0], normal_data, 'Sampling the Normal Distribution', 'n = {}'.format(100*i))

        gamma_data = np.random.gamma(2, 1.5, 100*i)
        plot_histogram(ax[0, 1], gamma_data, 'Sampling the Gamma Distribution', 'n = {}'.format(100*i))

        exponential_data = np.random.exponential(2, 100*i)+7
        plot_histogram(ax[1, 0], exponential_data, 'Sampling the Exponential Distribution', 'n = {}'.format(100*i))

        uniform_data = np.random.uniform(14,20, 100*i)
        plot_histogram(ax[1, 1], uniform_data, 'Sampling the Uniform Distribution', 'n = {}'.format(100*i))

def plot_histogram(ax, data, title, annotation):
    ax.cla()
    ax.hist(data, bins = bins)
    ax.set_title(title)
    ax.set_ylabel('Frequency')
    ax.set_xlabel('Value')
    ax.annotate(annotation, [3, 27])

ani = animation.FuncAnimation(fig, animate, frames = 11, interval = 200)

plt.show()

With this code I get this animation:


问:
How do I run a Docker pre-entrypoint command without knowing the original entrypoint?
I can not find a clear answer to this particular use case!

I have an arbitrary docker image, let's say postgres:latest, this has a 'baked in' entrypoint of some complex command that fires up the postgres server.

What I want to do is run a command, say apt install ca-certificates && wget 'MyTimestampedCAConfig' as an example, and then call the original (unknown) entrypoint to start the database.

The context I am doing this in is in Kubernetes by supplying a custom command: in the yml. docker run --entrypoint is more or less equivalent.

I can find the original command for the postgres:latest container manually in this specific case via docker history, and hard code it into the kube-yml. But this doesn't work in an environment with hundreds of custom containers and the endpoints periodically and quite randomly change...

How do I dynamically call the original entrypoint after my own command?

答:
How do I dynamically call the original entrypoint after my own command?

You can't. There is no way to say "call the entrypoint script of the base image after the entrypoint script in my custom image". The only solution is to determine the original entrypoint using e.g. docker inspect and then call that explicitly from your own entrypoint script.

Do you really need to override the entrypoint script for your use case? The example you've given (installing a new package) seems it would best be solved by creating a new image based on the postgres image and then adding the necessary RUN apt install ... command to the Dockerfile.


问:
Android WebView Responsive Youtube not playing
I have a very basic WebActivity that serves up a page that has the styling of

```<code>CSS

.video-container {
position: relative;
padding-bottom: 56.25%;
padding-top: 30px; height: 0; overflow: hidden;
}

.video-container iframe,
.video-container object,
.video-container embed {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}

Next, edit add some HTML around your embed code.
HTML

<div class="video-container"><iframe width="853" height="480" src="https://www.youtube.com/embed/xxxxxx" frameborder="0" allowfullscreen</iframe</div>
</code>```

If I view this page with the browser on the device, the page loads and the video plays just fine.

However if I use a webview programmed into my app, and load the page,clicking on the like, I get a message on the youtube video window (after the loading spinner) of "An error occurred.  Please try again later (Playback ID: xxxxxx) Learn More"

of which learn more does not display anything useful.  Idea's on how to go about seeing what is going on?  The Android Studio logcat is not displaying any issues?

答: I have create a demo for it. You may visit my github link</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a very basic WebActivity that serves up a page that has the styling of

CSS

.video-container {
position: relative;
padding-bottom: 56.25%;
padding-top: 30px; height: 0; overflow: hidden;
}

.video-container iframe,
.video-container object,
.video-container embed {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}

Next, edit add some HTML around your embed code.
HTML

<iframe width="853" height="480" src="https://www.youtube.com/embed/xxxxxx" frameborder="0" allowfullscreen</iframe

If I view this page with the browser on the device, the page loads and the video plays just fine.

However if I use a webview programmed into my app, and load the page,clicking on the like, I get a message on the youtube video window (after the loading spinner) of "An error occurred.  Please try again later (Playback ID: xxxxxx) Learn More"

of which learn more does not display anything useful.  Idea's on how to go about seeing what is going on?  The Android Studio logcat is not displaying any issues?


问:
Where should I implement my check for collision method?
I am making a pokemon ripoff in pygame, and I have made a method to test whether the player is in the tall grass. However, I do not know where I should call the method. I have tried in the player move method, in the game loop method, and the update method. When I do it like this, it checks after you have moved out of the grass, which means the first time you move into grass it won't work, and when you first move out of grass it works (when it shouldn't).

in_grass(self) method:

```<code>def in_grass(self):
        for g in self.game.grass:
            if pygame.sprite.collide_rect(self, g):
                print(random.randint(1, 10000))
                if random.randint(1, 180) <= 25:
                    self.battle()
</code>```

player move(self) method:

```<code>def move(self, x_change, y_change):
        if x_change > 0:
            self.dir = 'RIGHT'
        if x_change < 0:
            self.dir = 'LEFT'
        if y_change > 0:
            self.dir = 'DOWN'
        if y_change < 0:
            self.dir = 'UP'

        if not self.collide(x_change, y_change):
            self.x += x_change
            self.y += y_change

            image_list = None
            if self.dir == 'UP':
                image_list = self.image_up
            elif self.dir == 'LEFT':
                image_list = self.image_left
            elif self.dir == 'RIGHT':
                image_list = self.image_right
            elif self.dir == 'DOWN':
                image_list = self.image_down

            if image_list:
                if self.walkcount >= len(image_list):
                    self.walkcount = 0
                self.image = image_list[self.walkcount]
                self.walkcount += 1
                self.image.set_colorkey(BLACK)
</code>```

Main loop:

```<code> def events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_w:
                    self.player.move(0, -1)
                if event.key == pygame.K_a:
                    self.player.move(-1, 0)
                if event.key == pygame.K_s:
                    self.player.move(0, 1)
                if event.key == pygame.K_d:
                    self.player.move(1, 0)

            if event.type == pygame.KEYUP:
                self.player.image = self.player.default_images[self.player.dir]
                self.player.image.set_colorkey(BLACK)
</code>```

EDIT: I finally got it working! I can't give myself the bounty, so I guess it will just sit there.

答:
Create a boolean in the player's __init__ method callled self.checked = False. Then, in the in_grass method, at the end, set self.checked = True. In the update method, if not self.checked: self.in_grass. Finally in the move method, at the very start, set self.checked = False
I finally got it working, yay!

Body:
I am making a pokemon ripoff in pygame, and I have made a method to test whether the player is in the tall grass. However, I do not know where I should call the method. I have tried in the player move method, in the game loop method, and the update method. When I do it like this, it checks after you have moved out of the grass, which means the first time you move into grass it won't work, and when you first move out of grass it works (when it shouldn't).

in_grass(self) method:

def in_grass(self):
        for g in self.game.grass:
            if pygame.sprite.collide_rect(self, g):
                print(random.randint(1, 10000))
                if random.randint(1, 180) <= 25:
                    self.battle()

player move(self) method:

def move(self, x_change, y_change):
        if x_change > 0:
            self.dir = 'RIGHT'
        if x_change < 0:
            self.dir = 'LEFT'
        if y_change > 0:
            self.dir = 'DOWN'
        if y_change < 0:
            self.dir = 'UP'

        if not self.collide(x_change, y_change):
            self.x += x_change
            self.y += y_change

            image_list = None
            if self.dir == 'UP':
                image_list = self.image_up
            elif self.dir == 'LEFT':
                image_list = self.image_left
            elif self.dir == 'RIGHT':
                image_list = self.image_right
            elif self.dir == 'DOWN':
                image_list = self.image_down

            if image_list:
                if self.walkcount >= len(image_list):
                    self.walkcount = 0
                self.image = image_list[self.walkcount]
                self.walkcount += 1
                self.image.set_colorkey(BLACK)

Main loop:

 def events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_w:
                    self.player.move(0, -1)
                if event.key == pygame.K_a:
                    self.player.move(-1, 0)
                if event.key == pygame.K_s:
                    self.player.move(0, 1)
                if event.key == pygame.K_d:
                    self.player.move(1, 0)

            if event.type == pygame.KEYUP:
                self.player.image = self.player.default_images[self.player.dir]
                self.player.image.set_colorkey(BLACK)

EDIT: I finally got it working! I can't give myself the bounty, so I guess it will just sit there.


问:
How to Desrialize JSON using C#
I am currently using Json.Net to deserialize my JSON. I now have the following situation:

I am getting the following JSON response:

```<code>{"Success":false,"Errors":{"UserName":"User Name already registered","EmailAddress":"Email Address already registered"}}
</code>```

I want to parse it into this type:

```<code>public class CustomJsonResult
{
    public bool Success { get; set; }
    public string[] Errors { get; set; }
}
</code>```

Using Json.net, I tried doing this:

```<code>CustomJsonResult regResult = JsonConvert.DeserializeObject<CustomJsonResult>(json);
</code>```

But this is not working, I get the error Cannot deserialize JSON object into type 'System.String[]'.

How can I fix this? (using Json.Net or any other library)

答:
That's because your "Errors" in your JSON doesn't match what it's trying to deserialize to. It should be something like this:

```<code>public class CustomJsonResult
{
    public bool Success { get; set; }
    public ErrorType[] Errors { get; set; }
}

public class ErrorType
{
     public string UserName {get;set;}
     public string EmailAddress {get;set;}
}
</code>```

If you want to change the JSON to match, it should look something like this:

```<code>{"Success":false, "Errors": ["User Name already registered", "Email Address already registered"]}
</code>```

Otherwise you may need some intermediate mapping.

Title: How to Desrialize JSON using C#

Body:
I am currently using Json.Net to deserialize my JSON. I now have the following situation:

I am getting the following JSON response:

{"Success":false,"Errors":{"UserName":"User Name already registered","EmailAddress":"Email Address already registered"}}

I want to parse it into this type:

public class CustomJsonResult
{
    public bool Success { get; set; }
    public string[] Errors { get; set; }
}

Using Json.net, I tried doing this:

CustomJsonResult regResult = JsonConvert.DeserializeObject<CustomJsonResult>(json);

But this is not working, I get the error Cannot deserialize JSON object into type 'System.String[]'.

How can I fix this? (using Json.Net or any other library)

Body:
That's because your "Errors" in your JSON doesn't match what it's trying to deserialize to. It should be something like this:

public class CustomJsonResult
{
    public bool Success { get; set; }
    public ErrorType[] Errors { get; set; }
}

public class ErrorType
{
     public string UserName {get;set;}
     public string EmailAddress {get;set;}
}

If you want to change the JSON to match, it should look something like this:

{"Success":false, "Errors": ["User Name already registered", "Email Address already registered"]}

Otherwise you may need some intermediate mapping.


问:
How do I double space a tkinter text widget without using extra newline characters?
I have a tkinter Text widget in which I want to display the contents of a dict as a reference. I have no trouble configuring the style of each item, but I'm not pleased with the display because the lines are too close together for me to read comfortably. I want to "double space" the list, but I don't want to add extra newline characters, as this would get confusing and could potentially screw up how tagged areas are displayed. Specifically, I want to space the lines out so that the following criteria are met:

no vertical space above the first line of the listing

no vertical space below the last line of the listing

a consistent vertical spacing I specify between the lines of the listing

the text widget is wide enough to contain all the text without wrapping

each line of the listing is separated from the next by exactly one newline character

each key and each value is separately tagged and configurable

Here's my current code:

```<code>import tkinter

dictionary = {
  "test": "blue",
  "test2": "red",
  "test3": "green"
}
spacing = 30

root = tkinter.Tk()
text_widget = tkinter.Text(root)
text_widget.pack()
# "works" with this line, but don't want the side effect:
# text_widget.configure(width=5)

for index, (key, value) in enumerate(dictionary.items()):
  text_widget.mark_set("begin", "insert")
  text_widget.insert("insert", key+": ", (key,))
  text_widget.insert("insert", value+"\n", (value,))
  text_widget.tag_configure(key, font="courier 12 normal")
  text_widget.tag_configure(value, foreground=value)

#corrected the starting index as per the comments
text_widget.tag_add("whole", "1.0", "end")
text_widget.tag_configure("whole", spacing2=spacing)

root.mainloop()
</code>```

Though there are three spacing tag attributes that look like one of them should work for my case, none of them do. The spacing2 attribute comes frustratingly close, but according to https://www.tutorialspoint.com/python/tk_text.htm,

spacing2

This option specifies how much extra vertical space to add between displayed lines of text when a logical line wraps. Default is 0.

and this functionality doesn't seem particularly useful either, in my opinion.

Since I want to space all the text in the widget, it doesn't matter whether the solution is implemented at the tag level or widget-wide.

How can I put space between the lines of my listing according to the criteria given?

My expected output looks like this:

Python 3.8.2 Tkinter 8.6

答:
Yyou need to use either spacing1 on all but the first line, or spacing3 on all but the last line. spacing1 defines how much space to add above each line, and spacing3 defines how much space to add below each line.

For example, this uses spacing1 on all but the first line:

```<code>text_widget.tag_add("whole", "2.0", "end-1c")
text_widget.tag_configure("whole", spacing1=spacing)
</code>```

Body:
I have a tkinter Text widget in which I want to display the contents of a dict as a reference. I have no trouble configuring the style of each item, but I'm not pleased with the display because the lines are too close together for me to read comfortably. I want to "double space" the list, but I don't want to add extra newline characters, as this would get confusing and could potentially screw up how tagged areas are displayed. Specifically, I want to space the lines out so that the following criteria are met:

no vertical space above the first line of the listing

no vertical space below the last line of the listing

a consistent vertical spacing I specify between the lines of the listing

the text widget is wide enough to contain all the text without wrapping

each line of the listing is separated from the next by exactly one newline character

each key and each value is separately tagged and configurable

Here's my current code:

import tkinter

dictionary = {
  "test": "blue",
  "test2": "red",
  "test3": "green"
}
spacing = 30

root = tkinter.Tk()
text_widget = tkinter.Text(root)
text_widget.pack()
# "works" with this line, but don't want the side effect:
# text_widget.configure(width=5)

for index, (key, value) in enumerate(dictionary.items()):
  text_widget.mark_set("begin", "insert")
  text_widget.insert("insert", key+": ", (key,))
  text_widget.insert("insert", value+"\n", (value,))
  text_widget.tag_configure(key, font="courier 12 normal")
  text_widget.tag_configure(value, foreground=value)

#corrected the starting index as per the comments
text_widget.tag_add("whole", "1.0", "end")
text_widget.tag_configure("whole", spacing2=spacing)

root.mainloop()

Though there are three spacing tag attributes that look like one of them should work for my case, none of them do. The spacing2 attribute comes frustratingly close, but according to https://www.tutorialspoint.com/python/tk_text.htm,

spacing2

This option specifies how much extra vertical space to add between displayed lines of text when a logical line wraps. Default is 0.

and this functionality doesn't seem particularly useful either, in my opinion.

Since I want to space all the text in the widget, it doesn't matter whether the solution is implemented at the tag level or widget-wide.

How can I put space between the lines of my listing according to the criteria given?

My expected output looks like this:

Python 3.8.2 Tkinter 8.6

Body:
Yyou need to use either spacing1 on all but the first line, or spacing3 on all but the last line. spacing1 defines how much space to add above each line, and spacing3 defines how much space to add below each line.

For example, this uses spacing1 on all but the first line:

text_widget.tag_add("whole", "2.0", "end-1c")
text_widget.tag_configure("whole", spacing1=spacing)


问:
How to convert String to LocalDate without using DateTimeFormatter
i have a date in String "2020-06-02"

now i have to convert it in LocalDate but without using DateTimeFormatter.

is it possible.

```<code>    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    LocalDate inputAdDate = LocalDate.parse(adDate, formatter);
</code>```

as of now my code looks like this. but i dont want to use DateTimeFormatter as it is not supported in API level below 26.

答:
Also, you can try the java.text.SimpleDateFormat

```<code>String strDate = "20-03-2019";
SimpleDateFormat sdfDateDMY = new SimpleDateFormat("dd-MM-yyyy");
sdfDateDMY.parse(strDate);

</code>```

Body:
i have a date in String "2020-06-02"

now i have to convert it in LocalDate but without using DateTimeFormatter.

is it possible.

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    LocalDate inputAdDate = LocalDate.parse(adDate, formatter);

as of now my code looks like this. but i dont want to use DateTimeFormatter as it is not supported in API level below 26.

Body:
Also, you can try the java.text.SimpleDateFormat

String strDate = "20-03-2019";
SimpleDateFormat sdfDateDMY = new SimpleDateFormat("dd-MM-yyyy");
sdfDateDMY.parse(strDate);


问:
LINQ - Will FirstOrDefault() always return the same record?
if I have the following 'User' table

```<code>UserName UserID
-------- ------
abc      1
xyz      2
pqr      2

</code>```

and the following linq query:

```<code>_context.User.OrderByDescending(x => x.UserID).FirstOrDefault();
</code>```

will the result always be consistent?

as in will I always get either user with UserName 'xyz' or user with UserName 'pqr' or will it be random?

答: To be a bit snarky, yes, FirstOrDefault will always return the "first" item in the sequence (or a default value if there are no items). What could change is what is presented by OrderByDescending. You have two items with the same UserId value, so when you ask for items ordered by that value, SQL makes no guarantee that the order of the items with the same ID will be the same every time.

Body:
if I have the following 'User' table

UserName UserID
-------- ------
abc      1
xyz      2
pqr      2

and the following linq query:

_context.User.OrderByDescending(x => x.UserID).FirstOrDefault();

will the result always be consistent?

as in will I always get either user with UserName 'xyz' or user with UserName 'pqr' or will it be random?


问:
How do you make websites with Java?
This might be a really trivial question, but I've been writing Java programs at my school and I just found out that I can create websites with Java as well.

How can I do that? Any good books/tutorials for that?

Which is better for Web development, Java or PHP?

Also, when using PHP, MySQL comes into picture and while writing Java programs for desktop, we just use File I/O, so what is better for web dev, File I/O or MySQL?

答:
Also be advised, that while Java is in general very beginner friendly, getting into JavaEE, Servlets, Facelets, Eclipse integration, JSP and getting everything in Tomcat up and running is not. Certainly not the easiest way to build a website and probably way overkill for most things.

On top of that you may need to host your website yourself, because most webspace providers don't provide Servlet Containers. If you just want to check it out for fun, I would try Ruby or Python, which are much more cooler things to fiddle around with. But anyway, to provide at least something relevant to the question, here's a nice Servlet tutorial: link

OwnerDisplayName: GVRV

Title: How do you make websites with Java?

OwnerDisplayName: Jan Gressmann

ContentLicense: CC BY-SA 2.5


问:
User to start Passenger (with Nginx)
I have Nginx with Passenger.  In nginx.conf I have line:

```<code>user pass users;
</code>```

and Nginx process works on 'pass' user, but Passenger* processes work on 'nobody' user.

I can run Passenger standalone:

```<code>sudo passanger start -e production -p 80 --user=pass
</code>```

How can I run Passenger with Nginx with my custom user?

答:
You can pass a user line into your nginx conf.
http://wiki.nginx.org/CoreModule#user

I suggest that in the future you ask server questions on ServerFault, they usually know a lot more about nginx and passenger.

Title: User to start Passenger (with Nginx)

Body:
I have Nginx with Passenger.  In nginx.conf I have line:

user pass users;

and Nginx process works on 'pass' user, but Passenger* processes work on 'nobody' user.

I can run Passenger standalone:

sudo passanger start -e production -p 80 --user=pass

How can I run Passenger with Nginx with my custom user?


问:
Constraint layout has space bottom and top
I'm building an app using Constraint layout, but it has extra space bottom and top. I can't find where they come from. I checked maybe ten times from top to bottom all code but there is no margin or padding or anything else for it.

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/black"
    android:paddingLeft="0dp"
    android:paddingTop="0dp"
    android:paddingRight="0dp"
    android:paddingBottom="0dp">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/Brand"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toTopOf="@id/guideline"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:orientation="horizontal"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">

            <TextView
                android:id="@+id/brandname"
                style="@style/viewParent.headerText"
                android:text="Did"
                android:textColor="@color/white" />

            <TextView
                android:id="@+id/brandname2"
                style="@style/viewParent.headerText2"
                android:layout_toRightOf="@id/brandname"
                android:text="You"
                android:textColor="@color/yellow" />

            <TextView
                style="@style/viewParent.headerText2"
                android:layout_toRightOf="@id/brandname2"
                android:text="Know!"
                android:textColor="@color/red"
                android:textStyle="bold|italic" />
        </RelativeLayout>
    </androidx.constraintlayout.widget.ConstraintLayout>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/container_main"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_margin="4dp"
        android:background="@drawable/card_bg"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"
        app:layout_constraintBottom_toTopOf="@id/guideline2"
        app:layout_constraintEnd_toEndOf="@id/guidelineyazisag"
        app:layout_constraintStart_toStartOf="@id/guidelineyazisol"
        app:layout_constraintTop_toBottomOf="@id/guideline">

        <TextView
            android:id="@+id/activity_main_text_view_id"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:text="simple Title Text"
            android:textColor="#5E4C4C"
            android:textStyle="bold"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/activity_main_did_u_know"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:text="Category"
            android:textColor="#5E4C4C"
            android:textStyle="bold"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <androidx.core.widget.NestedScrollView
            android:id="@+id/scrollview"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:fillViewport="true"
            app:layout_constraintBottom_toTopOf="@id/activity_main_image_view"
            app:layout_constraintTop_toBottomOf="@id/activity_main_did_u_know">

            <androidx.constraintlayout.widget.ConstraintLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                app:layout_constraintBottom_toTopOf="@id/activity_main_image_view"
                app:layout_constraintTop_toBottomOf="@id/activity_main_did_u_know">

                <TextView
                    android:id="@+id/factTextView"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_marginTop="8dp"
                    android:gravity="center_vertical|center_horizontal"
                    android:lineSpacingExtra="8dp"
                    android:padding="10dp"
                    android:text="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged."
                    android:textColor="#000000"
                    android:textSize="16dp"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintHorizontal_bias="1.0"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toTopOf="parent"
                    app:layout_constraintVertical_bias="0.0" />

            </androidx.constraintlayout.widget.ConstraintLayout>

        </androidx.core.widget.NestedScrollView>

        <ImageView
            android:id="@+id/activity_main_image_view"
            android:layout_width="30dp"
            android:layout_height="40dp"
            android:layout_marginStart="16dp"
            android:layout_marginLeft="16dp"
            android:clickable="true"
            android:src="@drawable/ic_share_black_24dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/scrollview" />

        <ImageView
            android:id="@+id/activity_main_fav_button"
            android:layout_width="30dp"
            android:layout_height="40dp"
            android:layout_margin="16dp"
            android:clickable="true"
            android:src="@drawable/ic_favorite_border_black_24dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toBottomOf="@id/scrollview" />

    </androidx.constraintlayout.widget.ConstraintLayout>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/LeftRight"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toTopOf="@id/adView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/guideline2">

        <ImageView
            android:id="@+id/activity_main_left_button"
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:clickable="true"
            android:src="@drawable/ic_previous"
            android:elevation="3dp"
            android:background="@drawable/okarka"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toStartOf="@id/guideline3"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <ImageView
            android:id="@+id/activity_main_right_button"
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:clickable="true"
            android:src="@drawable/ic_next"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.5"
            android:background="@drawable/okarka"
            app:layout_constraintStart_toEndOf="@+id/guideline3"
            app:layout_constraintTop_toTopOf="parent" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/guideline3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintGuide_percent="0.5" />
    </androidx.constraintlayout.widget.ConstraintLayout>

    <com.google.android.gms.ads.AdView xmlns:ads="http://schemas.android.com/apk/res-auto"
        android:id="@+id/adView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        ads:adSize="SMART_BANNER"
        ads:adUnitId="ca-app-pub-3940256099942544/6300978111"
        ads:layout_constraintBottom_toBottomOf="parent"
        ads:layout_constraintLeft_toLeftOf="parent"
        ads:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/LeftRight" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.076" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.7" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guidelineyazisol"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.07" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guidelineyazisag"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.93" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

I tried adding guidelines to 0 points in the bottom but it also starts in that space. I gave -(minus) values to margin and padding but doesn't work. I don't know what else to do. You can see from screenshots how it looks.

```<code>public class MainActivity extends AppCompatActivity {

    private ColorWheel colorWheel = new ColorWheel();
    private TextView factTextView;
    private TextView textViewId;
    private TextView textViewTableName;
    ImageView tableImageView;
    AdView adView;
    ImageView shareImageView;
    ImageView favImageView;
    float x1,x2,y1,y2;
    int i = 1;
    int adCounter = 0;
    private ConstraintLayout constraintLayout;
    String fact;
    ArrayList<Fact> favList = new ArrayList<>();
    private InterstitialAd mInterstitial;
    AdRequest interAdRequest;
    int favId;
    String favTable;
    Typeface typeface;
    List<Fact> mData;
    private DatabaseFacts db;
    GradientDrawable shape;

    @SuppressLint({"ClickableViewAccessibility", "SetTextI18n"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        db = new DatabaseFacts(this);
        db.copyDbIfNotExists();
        shape =  new GradientDrawable();
        shape.setCornerRadius(40);
        mData = new ArrayList<>();
        MobileAds.initialize(this, "ca-app-pub-2469721886989416~7390658870");
        adView = findViewById(R.id.adView);
        AdRequest bannerAdRequest = new AdRequest.Builder().build();
        adView.loadAd(bannerAdRequest);

        interAdRequest = new AdRequest.Builder().build();
        mInterstitial = new InterstitialAd(this);
        mInterstitial.setAdUnitId("ca-app-pub-2469721886989416/9441000894");
        mInterstitial.loadAd(interAdRequest);

        factTextView = findViewById(R.id.factTextView);
        constraintLayout = (ConstraintLayout) findViewById(R.id.container_main);
        textViewId = findViewById(R.id.activity_main_text_view_id);
        favImageView = findViewById(R.id.activity_main_fav_button);
        shareImageView = findViewById(R.id.activity_main_image_view);
        textViewTableName = findViewById(R.id.activity_main_did_u_know);
//        tableImageView = findViewById(R.id.img_user);
//        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
//            typeface = getResources().getFont(R.font.sourceserifproregular);
//        }
        factTextView.setTypeface(typeface);
        Intent intent  = getIntent();
        final int choice = intent.getIntExtra("choice",0);

        switch (choice) {
            case 1:

                textViewTableName.setText("General Facts");
                factTextView.setText(db.getFact((readFromShared("defaultKey") - 1), DatabaseFacts.TABLE_GENERAL_NAME).getFact());
                textViewId.setText("Fact " + (readFromShared("defaultKey") - 1) + " of " + db.getFactsCount(DatabaseFacts.TABLE_GENERAL_NAME));

                if (db.getFact((readFromShared("defaultKey") - 1), DatabaseFacts.TABLE_GENERAL_NAME).isFavorite() == 0) {
                    favImageView.setImageResource(R.drawable.ic_favorite_border_black_24dp);
                } else {
                    favImageView.setImageResource(R.drawable.ic_favorite_black_24dp);
                }

                ImageView leftClick = (ImageView) findViewById(R.id.activity_main_left_button);
                leftClick.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        leftClickMethod("defaultKey", DatabaseFacts.TABLE_GENERAL_NAME);

                    }
                });

                ImageView rightClick = (ImageView) findViewById(R.id.activity_main_right_button);
                rightClick.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        rightClickMethod("defaultKey",DatabaseFacts.TABLE_GENERAL_NAME);
                        return;
                    }
                });

                favImageView.setOnClickListener(v -> handleFavorites("defaultKey", DatabaseFacts.TABLE_GENERAL_NAME));
                break;
</code>```

答:
Remove app:layout_constraintBottom_toTopOf="@id/guideline" from Brand and app:layout_constraintTop_toBottomOf="@id/LeftRight" from adView.
You can't put constraints for Top and Bottom because it will center your View between those two constraints. Same about left and right (start, end), but you have match_parent here, so this problem doesn't occur (visualy - if you set wrap_content, view will go to the center too).

Body:
I'm building an app using Constraint layout, but it has extra space bottom and top. I can't find where they come from. I checked maybe ten times from top to bottom all code but there is no margin or padding or anything else for it.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/black"
    android:paddingLeft="0dp"
    android:paddingTop="0dp"
    android:paddingRight="0dp"
    android:paddingBottom="0dp">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/Brand"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toTopOf="@id/guideline"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:orientation="horizontal"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">

            <TextView
                android:id="@+id/brandname"
                style="@style/viewParent.headerText"
                android:text="Did"
                android:textColor="@color/white" />

            <TextView
                android:id="@+id/brandname2"
                style="@style/viewParent.headerText2"
                android:layout_toRightOf="@id/brandname"
                android:text="You"
                android:textColor="@color/yellow" />

            <TextView
                style="@style/viewParent.headerText2"
                android:layout_toRightOf="@id/brandname2"
                android:text="Know!"
                android:textColor="@color/red"
                android:textStyle="bold|italic" />
        </RelativeLayout>
    </androidx.constraintlayout.widget.ConstraintLayout>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/container_main"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_margin="4dp"
        android:background="@drawable/card_bg"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"
        app:layout_constraintBottom_toTopOf="@id/guideline2"
        app:layout_constraintEnd_toEndOf="@id/guidelineyazisag"
        app:layout_constraintStart_toStartOf="@id/guidelineyazisol"
        app:layout_constraintTop_toBottomOf="@id/guideline">

        <TextView
            android:id="@+id/activity_main_text_view_id"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:text="simple Title Text"
            android:textColor="#5E4C4C"
            android:textStyle="bold"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/activity_main_did_u_know"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:text="Category"
            android:textColor="#5E4C4C"
            android:textStyle="bold"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <androidx.core.widget.NestedScrollView
            android:id="@+id/scrollview"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:fillViewport="true"
            app:layout_constraintBottom_toTopOf="@id/activity_main_image_view"
            app:layout_constraintTop_toBottomOf="@id/activity_main_did_u_know">

            <androidx.constraintlayout.widget.ConstraintLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                app:layout_constraintBottom_toTopOf="@id/activity_main_image_view"
                app:layout_constraintTop_toBottomOf="@id/activity_main_did_u_know">

                <TextView
                    android:id="@+id/factTextView"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_marginTop="8dp"
                    android:gravity="center_vertical|center_horizontal"
                    android:lineSpacingExtra="8dp"
                    android:padding="10dp"
                    android:text="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged."
                    android:textColor="#000000"
                    android:textSize="16dp"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintHorizontal_bias="1.0"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toTopOf="parent"
                    app:layout_constraintVertical_bias="0.0" />

            </androidx.constraintlayout.widget.ConstraintLayout>

        </androidx.core.widget.NestedScrollView>

        <ImageView
            android:id="@+id/activity_main_image_view"
            android:layout_width="30dp"
            android:layout_height="40dp"
            android:layout_marginStart="16dp"
            android:layout_marginLeft="16dp"
            android:clickable="true"
            android:src="@drawable/ic_share_black_24dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/scrollview" />

        <ImageView
            android:id="@+id/activity_main_fav_button"
            android:layout_width="30dp"
            android:layout_height="40dp"
            android:layout_margin="16dp"
            android:clickable="true"
            android:src="@drawable/ic_favorite_border_black_24dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toBottomOf="@id/scrollview" />

    </androidx.constraintlayout.widget.ConstraintLayout>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/LeftRight"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toTopOf="@id/adView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/guideline2">

        <ImageView
            android:id="@+id/activity_main_left_button"
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:clickable="true"
            android:src="@drawable/ic_previous"
            android:elevation="3dp"
            android:background="@drawable/okarka"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toStartOf="@id/guideline3"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <ImageView
            android:id="@+id/activity_main_right_button"
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:clickable="true"
            android:src="@drawable/ic_next"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.5"
            android:background="@drawable/okarka"
            app:layout_constraintStart_toEndOf="@+id/guideline3"
            app:layout_constraintTop_toTopOf="parent" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/guideline3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintGuide_percent="0.5" />
    </androidx.constraintlayout.widget.ConstraintLayout>

    <com.google.android.gms.ads.AdView xmlns:ads="http://schemas.android.com/apk/res-auto"
        android:id="@+id/adView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        ads:adSize="SMART_BANNER"
        ads:adUnitId="ca-app-pub-3940256099942544/6300978111"
        ads:layout_constraintBottom_toBottomOf="parent"
        ads:layout_constraintLeft_toLeftOf="parent"
        ads:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/LeftRight" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.076" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.7" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guidelineyazisol"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.07" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guidelineyazisag"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.93" />
</androidx.constraintlayout.widget.ConstraintLayout>

I tried adding guidelines to 0 points in the bottom but it also starts in that space. I gave -(minus) values to margin and padding but doesn't work. I don't know what else to do. You can see from screenshots how it looks.

public class MainActivity extends AppCompatActivity {

    private ColorWheel colorWheel = new ColorWheel();
    private TextView factTextView;
    private TextView textViewId;
    private TextView textViewTableName;
    ImageView tableImageView;
    AdView adView;
    ImageView shareImageView;
    ImageView favImageView;
    float x1,x2,y1,y2;
    int i = 1;
    int adCounter = 0;
    private ConstraintLayout constraintLayout;
    String fact;
    ArrayList<Fact> favList = new ArrayList<>();
    private InterstitialAd mInterstitial;
    AdRequest interAdRequest;
    int favId;
    String favTable;
    Typeface typeface;
    List<Fact> mData;
    private DatabaseFacts db;
    GradientDrawable shape;

    @SuppressLint({"ClickableViewAccessibility", "SetTextI18n"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        db = new DatabaseFacts(this);
        db.copyDbIfNotExists();
        shape =  new GradientDrawable();
        shape.setCornerRadius(40);
        mData = new ArrayList<>();
        MobileAds.initialize(this, "ca-app-pub-2469721886989416~7390658870");
        adView = findViewById(R.id.adView);
        AdRequest bannerAdRequest = new AdRequest.Builder().build();
        adView.loadAd(bannerAdRequest);

        interAdRequest = new AdRequest.Builder().build();
        mInterstitial = new InterstitialAd(this);
        mInterstitial.setAdUnitId("ca-app-pub-2469721886989416/9441000894");
        mInterstitial.loadAd(interAdRequest);

        factTextView = findViewById(R.id.factTextView);
        constraintLayout = (ConstraintLayout) findViewById(R.id.container_main);
        textViewId = findViewById(R.id.activity_main_text_view_id);
        favImageView = findViewById(R.id.activity_main_fav_button);
        shareImageView = findViewById(R.id.activity_main_image_view);
        textViewTableName = findViewById(R.id.activity_main_did_u_know);
//        tableImageView = findViewById(R.id.img_user);
//        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
//            typeface = getResources().getFont(R.font.sourceserifproregular);
//        }
        factTextView.setTypeface(typeface);
        Intent intent  = getIntent();
        final int choice = intent.getIntExtra("choice",0);

        switch (choice) {
            case 1:

                textViewTableName.setText("General Facts");
                factTextView.setText(db.getFact((readFromShared("defaultKey") - 1), DatabaseFacts.TABLE_GENERAL_NAME).getFact());
                textViewId.setText("Fact " + (readFromShared("defaultKey") - 1) + " of " + db.getFactsCount(DatabaseFacts.TABLE_GENERAL_NAME));

                if (db.getFact((readFromShared("defaultKey") - 1), DatabaseFacts.TABLE_GENERAL_NAME).isFavorite() == 0) {
                    favImageView.setImageResource(R.drawable.ic_favorite_border_black_24dp);
                } else {
                    favImageView.setImageResource(R.drawable.ic_favorite_black_24dp);
                }

                ImageView leftClick = (ImageView) findViewById(R.id.activity_main_left_button);
                leftClick.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        leftClickMethod("defaultKey", DatabaseFacts.TABLE_GENERAL_NAME);

                    }
                });

                ImageView rightClick = (ImageView) findViewById(R.id.activity_main_right_button);
                rightClick.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        rightClickMethod("defaultKey",DatabaseFacts.TABLE_GENERAL_NAME);
                        return;
                    }
                });

                favImageView.setOnClickListener(v -> handleFavorites("defaultKey", DatabaseFacts.TABLE_GENERAL_NAME));
                break;


问:
Hide shiny box content and keep only the header of the box shown
I am asking if is it possible to hide/show box content while the header of the box is always displayed.

Example:
box(id = "myBox",width = 10, height = '500px', solidHeader = TRUE, status="primary",title ="Barplot",collapsible=TRUE,"Do you want to make a bar plot")

Collapse hide the content, but i am looking to hide whole box except the header.

Thank you

答:
What you are asking for is the default behaviour when height = NULL.
The height of the box is then controlled by it's content (you could e.g. set a height of 500px for your plot).

Please see the following:

```<code>library(shiny)
library(shinydashboard)

ui <- dashboardPage(dashboardHeader(),
                    dashboardSidebar(),
                    dashboardBody(
                      box(
                        id = "myBox",
                        width = 10,
                        solidHeader = TRUE,
                        status = "primary",
                        title = "Barplot",
                        collapsible = TRUE,
                        "Do you want to make a bar plot"
                      )
                    ))

server <- function(input, output, session) {

}

shinyApp(ui, server)
</code>```

Body:
What you are asking for is the default behaviour when height = NULL.
The height of the box is then controlled by it's content (you could e.g. set a height of 500px for your plot).

Please see the following:

library(shiny)
library(shinydashboard)

ui <- dashboardPage(dashboardHeader(),
                    dashboardSidebar(),
                    dashboardBody(
                      box(
                        id = "myBox",
                        width = 10,
                        solidHeader = TRUE,
                        status = "primary",
                        title = "Barplot",
                        collapsible = TRUE,
                        "Do you want to make a bar plot"
                      )
                    ))

server <- function(input, output, session) {

}

shinyApp(ui, server)


问:
How to plot multiple ROC curves in one plot with legend and AUC scores in python?
I am building 2 models.

Model 1

```<code>modelgb = GradientBoostingClassifier()
modelgb.fit(x_train,y_train)
predsgb = modelgb.predict_proba(x_test)[:,1]
metrics.roc_auc_score(y_test,predsgb, average='macro', sample_weight=None)
</code>```

Model 2

```<code>model = LogisticRegression()
model = model.fit(x_train,y_train)
predslog = model.predict_proba(x_test)[:,1]
metrics.roc_auc_score(y_test,predslog, average='macro', sample_weight=None)
</code>```

How do i plot both the ROC curves in one plot , with a legend & text of AUC scores for each model ?

答:
Something like this ...</p>

```<code>#ROC Curve
from sklearn.metrics import roc_curve
y_pred_prob1 = classifier1.predict_proba(X_test)[:,1]
fpr1 , tpr1, thresholds1 = roc_curve(Y_test, y_pred_prob1)

y_pred_prob2 = classifier2.predict_proba(X_test)[:,1]
fpr2 , tpr2, thresholds2 = roc_curve(Y_test, y_pred_prob2)

y_pred_prob3 = classifier3.predict_proba(X_test)[:,1]
fpr3 , tpr3, thresholds3 = roc_curve(Y_test, y_pred_prob3)

y_pred_prob4 = classifier4.predict_proba(X_test)[:,1]
fpr4 , tpr4, thresholds4 = roc_curve(Y_test, y_pred_prob4)

plt.plot([0,1],[0,1], 'k--')
plt.plot(fpr1, tpr1, label= "Linear")
plt.plot(fpr2, tpr2, label= "Poly")
plt.plot(fpr3, tpr3, label= "RBF")
plt.plot(fpr4, tpr4, label= "Sigmoid")
plt.legend()
plt.xlabel("FPR")
plt.ylabel("TPR")
plt.title('Receiver Operating Characteristic')
plt.show()
</code>```

Body:
I am building 2 models.

Model 1

modelgb = GradientBoostingClassifier()
modelgb.fit(x_train,y_train)
predsgb = modelgb.predict_proba(x_test)[:,1]
metrics.roc_auc_score(y_test,predsgb, average='macro', sample_weight=None)

Model 2

model = LogisticRegression()
model = model.fit(x_train,y_train)
predslog = model.predict_proba(x_test)[:,1]
metrics.roc_auc_score(y_test,predslog, average='macro', sample_weight=None)

How do i plot both the ROC curves in one plot , with a legend & text of AUC scores for each model ?

Body:
Something like this ...

#ROC Curve
from sklearn.metrics import roc_curve
y_pred_prob1 = classifier1.predict_proba(X_test)[:,1]
fpr1 , tpr1, thresholds1 = roc_curve(Y_test, y_pred_prob1)

y_pred_prob2 = classifier2.predict_proba(X_test)[:,1]
fpr2 , tpr2, thresholds2 = roc_curve(Y_test, y_pred_prob2)

y_pred_prob3 = classifier3.predict_proba(X_test)[:,1]
fpr3 , tpr3, thresholds3 = roc_curve(Y_test, y_pred_prob3)

y_pred_prob4 = classifier4.predict_proba(X_test)[:,1]
fpr4 , tpr4, thresholds4 = roc_curve(Y_test, y_pred_prob4)

plt.plot([0,1],[0,1], 'k--')
plt.plot(fpr1, tpr1, label= "Linear")
plt.plot(fpr2, tpr2, label= "Poly")
plt.plot(fpr3, tpr3, label= "RBF")
plt.plot(fpr4, tpr4, label= "Sigmoid")
plt.legend()
plt.xlabel("FPR")
plt.ylabel("TPR")
plt.title('Receiver Operating Characteristic')
plt.show()


问:
Does Android save and restore instance state of some field automatically?
I have a RecyclerView with MyItem as holding the data for each rows in the RecyclerView, and everything is properly implemented and working fine.

```<code>public class MyAdapter extends RecyclerView.Adapter<MyViewHolder>{
    protected final List<MyItem> items= new ArrayList<>();
    public MyAdapter (List<RVItem> list) {
        if (list != null) {
            items.addAll(list);
        }
    }
}
</code>```

And the List items is passed from another object.

```<code>public class MyObject{
    private String otherThing;
    private List<MyItem> items;
    public someMethodToInitItems() {
        items = new ArrayList<>();
        items.add(...);
        items.add(...);
    }
    public createFragment() {
        Fragment f = new MyCustomFragment();
        f.setAdapter(new MyAdapter(items));
        // replace commit fragment...
    }
}
</code>```

The problem here is when my Activity is restored, the field private List<MyItem> items in MyObject somehow magically get restored too, but field like otherThing is still null and not getting restored.
FYI, I did not explicitly save and restore items in any way. Also, onSaveInstanceState in MyCustomFragment is left untouched and not overridden from super.

Below is how I'm trying to save and restore the Fragment state from the Activity. That's it.

```<code>public class MyActivity{
    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        getSupportFragmentManager().putFragment(outState, tag, getLastFragment());
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(savedInstanceState != null) {
            Fragment fg = getSupportFragmentManager().getFragment(savedInstanceState, tag);
        }
    }
}
</code>```

So, I don't get it. Is Android system did this job? Save and restore the field items in MyObject automatically? Or there must be something else causing this behavior.

答:
You need to override onRetainNonConfigurationInstance method. This method could helps you to store your data

More details here

Body:
I have a RecyclerView with MyItem as holding the data for each rows in the RecyclerView, and everything is properly implemented and working fine.

public class MyAdapter extends RecyclerView.Adapter<MyViewHolder>{
    protected final List<MyItem> items= new ArrayList<>();
    public MyAdapter (List<RVItem> list) {
        if (list != null) {
            items.addAll(list);
        }
    }
}

And the List items is passed from another object.

public class MyObject{
    private String otherThing;
    private List<MyItem> items;
    public someMethodToInitItems() {
        items = new ArrayList<>();
        items.add(...);
        items.add(...);
    }
    public createFragment() {
        Fragment f = new MyCustomFragment();
        f.setAdapter(new MyAdapter(items));
        // replace commit fragment...
    }
}

The problem here is when my Activity is restored, the field private List<MyItem> items in MyObject somehow magically get restored too, but field like otherThing is still null and not getting restored.
FYI, I did not explicitly save and restore items in any way. Also, onSaveInstanceState in MyCustomFragment is left untouched and not overridden from super.

Below is how I'm trying to save and restore the Fragment state from the Activity. That's it.

public class MyActivity{
    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        getSupportFragmentManager().putFragment(outState, tag, getLastFragment());
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(savedInstanceState != null) {
            Fragment fg = getSupportFragmentManager().getFragment(savedInstanceState, tag);
        }
    }
}

So, I don't get it. Is Android system did this job? Save and restore the field items in MyObject automatically? Or there must be something else causing this behavior.


问:
How to change the index of a vector element?
In JavaScript I would do this:

function move(arr, old_index, new_index) {
  while (old_index < 0) {
    old_index += arr.length;
  }
  while (new_index < 0) {
    new_index += arr.length;
  }
  if (new_index >= arr.length) {
    var k = new_index - arr.length;
    while ((k--) + 1) {
      arr.push(undefined);
    }
  }
  arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);
  return arr;
}
```

How can I accomplish the same thing in Rust?

I don't want to use insert and remove because my vector is a std::vec::Vec<std::string::String> and I want to literally move them to a different location in the vector, not remove them and then insert a copy.

I don't want to swap 2 elements.  I want to change the index of an element to an arbitrary other index, like a person cutting to some arbitrary other position in a queue.

答:
When you do insert + remove (or the double splice in JavaScript) you move all of the items between the larger of the two indices and the end of the array twice: first you move them back one slot for the remove, and then you move them forward one slot for the insert. But this is unnecessary. Instead you can simply take a slice of the Vec and rotate it:

```<code>fn move_me(arr: &mut [String], old_index: usize, new_index: usize) {
    if old_index < new_index {
        arr[old_index..=new_index].rotate_left(1);
    } else {
        arr[new_index..=old_index].rotate_right(1);
    }
}
</code>```

Note that this change allows move_me to take &mut [String] instead of &mut Vec<String>, which makes this code more general as well as more efficient. It is better to accept &[T] instead of &Vec<T>, and in this case the same logic applies to &mut Vec<T> because move_me does not need to grow or shrink the vector.

Also, as in the other answer, I have left out the part that makes negative indices count from the back of the slice, and the part that grows the vector when the index is too large, because neither of those conventions is common in idiomatic Rust.

Body:
In JavaScript I would do this:

function move(arr, old_index, new_index) {
  while (old_index < 0) {
    old_index += arr.length;
  }
  while (new_index < 0) {
    new_index += arr.length;
  }
  if (new_index >= arr.length) {
    var k = new_index - arr.length;
    while ((k--) + 1) {
      arr.push(undefined);
    }
  }
  arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);
  return arr;
}

How can I accomplish the same thing in Rust?

I don't want to use insert and remove because my vector is a std::vec::Vec<std::string::String> and I want to literally move them to a different location in the vector, not remove them and then insert a copy.

I don't want to swap 2 elements.  I want to change the index of an element to an arbitrary other index, like a person cutting to some arbitrary other position in a queue.

Body:
When you do insert + remove (or the double splice in JavaScript) you move all of the items between the larger of the two indices and the end of the array twice: first you move them back one slot for the remove, and then you move them forward one slot for the insert. But this is unnecessary. Instead you can simply take a slice of the Vec and rotate it:

fn move_me(arr: &mut [String], old_index: usize, new_index: usize) {
    if old_index < new_index {
        arr[old_index..=new_index].rotate_left(1);
    } else {
        arr[new_index..=old_index].rotate_right(1);
    }
}

Note that this change allows move_me to take &mut [String] instead of &mut Vec<String>, which makes this code more general as well as more efficient. It is better to accept &[T] instead of &Vec<T>, and in this case the same logic applies to &mut Vec<T> because move_me does not need to grow or shrink the vector.

Also, as in the other answer, I have left out the part that makes negative indices count from the back of the slice, and the part that grows the vector when the index is too large, because neither of those conventions is common in idiomatic Rust.


问:
Flutter onClosing callback for showModalBottomSheet
I have a showModalBottomSheet like the below, which I understand to inherit from BottomSheet (right?)

```<code>      showModalBottomSheet<void>(
        context: context,
        builder: (BuildContext context) {
          return Container(
            height: 260.0,
            child: Text('I am text')
          );
        },
      );
</code>```

What I want to do:

I want to know (listen) when the modal is being closed, and act on it.

I've seen this onClosing callback:
https://docs.flutter.io/flutter/material/BottomSheet/onClosing.html

How can I have a listener attached to the showModalBottomSheet, and then act accordingly when it fires?

答:
showBottomSheet does not return a future, now it returns a PersistentBottomSheetController</p>

```<code>  var _scaffoldKey = GlobalKey<ScaffoldState>();
  PersistentBottomSheetController persistentBottomSheetController;
</code>```

```<code> persistentBottomSheetController = _scaffoldKey.currentState.showBottomSheet<void>(
    (context)=>Container(

    )
 );
</code>```

```<code> persistentBottomSheetController.closed.then(_closeModal);
</code>```

```<code>  void _closeModal(void value) {
    print('modal closed');
  }
</code>```

Body:
I have a showModalBottomSheet like the below, which I understand to inherit from BottomSheet (right?)

      showModalBottomSheet<void>(
        context: context,
        builder: (BuildContext context) {
          return Container(
            height: 260.0,
            child: Text('I am text')
          );
        },
      );

What I want to do:

I want to know (listen) when the modal is being closed, and act on it.

I've seen this onClosing callback:
https://docs.flutter.io/flutter/material/BottomSheet/onClosing.html

How can I have a listener attached to the showModalBottomSheet, and then act accordingly when it fires?

Body:
showBottomSheet does not return a future, now it returns a PersistentBottomSheetController

  var _scaffoldKey = GlobalKey<ScaffoldState>();
  PersistentBottomSheetController persistentBottomSheetController;

 persistentBottomSheetController = _scaffoldKey.currentState.showBottomSheet<void>(
    (context)=>Container(

    )
 );

 persistentBottomSheetController.closed.then(_closeModal);

  void _closeModal(void value) {
    print('modal closed');
  }


问:
How to write the application insights telemetry data into local database
I want to write the application insights telemetry data into local database/file using Application insights SDK in UWP application. Once written into the local file/database then i have to read the data to AZURE for some reason.

Is it possible to do that ?

Thanks
Sekar

答:
You can use the Continuous Export feature of Application Insights.
It exports everything continuously to a Blob Storage and from there you can do your post processing either in Azure or downloading it to some local storage.

If you need to save it locally before sending it to Azure you could implement your logic in a Custom Telemetry Processor.

Hope that helps,
Andreas


问:
Silverstripe - Blog module blog entry via front end but image upload/insert button missing from tinymce
We allow users to create blog entries via front end. but for some reason the tinymce editor doesn't have image upload button. Authors have to drag the image from their desktop to tinymce to insert an image.

is there a way to add image button allowing authors to upload images and using them in their blog?

Also just realised, there is no "Link" button either

答:
You can enable the default TinyMCE image and link insertion buttons using the code below. However, this won't contain the SilverStripe specific functionality such as choosing a page to link to or uploading images - you have to manually enter link and image URLs.

```<code>HtmlEditorConfig::get()->addButtonsToLine(1, 'link', 'unlink', 'image');
</code>```

The image and link insertion functionality is quite heavily tied to the CMS in version 2.4, but is being rewritten as part of 3.0 and will work in the front end.

See the HtmlEditorConfig API documentation for more details on customising the functionality available in the WYSIWYG editor.

Body:
You can enable the default TinyMCE image and link insertion buttons using the code below. However, this won't contain the SilverStripe specific functionality such as choosing a page to link to or uploading images - you have to manually enter link and image URLs.

HtmlEditorConfig::get()->addButtonsToLine(1, 'link', 'unlink', 'image');

The image and link insertion functionality is quite heavily tied to the CMS in version 2.4, but is being rewritten as part of 3.0 and will work in the front end.

See the HtmlEditorConfig API documentation for more details on customising the functionality available in the WYSIWYG editor.


问:
Mocking method with callback param
I am trying to mock this method:

```<code>$transformer = $this->transformerFactory->createProductTransformer($product, function (ProductInterface $product) use ($discount) {
    $product->setDiscount($discount);
});
</code>```

It accepts callback parameter as a second argument and I don't know how to mock it.

I am using Mockery so that would look like that:

```<code>$this->transformerFactoryMock
    ->shouldReceive('createProductTransformer')
    ->with(???) // here!
</code>```

If I pass the same callback to the with() method, the instances does not match.
I don't mind using PHPUnit mocking if Mockery doesn't support that.

答:
If you need check exactly that callback is called then it is not possible as each \Closure instance is unique and inside your tested method you created new one.

But you can do next:

1) validate dynamic args for type

```<code>// Assume in test case you have these mock/stub
$discount;
$product;

$transformerFactoryMock = \Mockery::mock('TransformerFactory')
    ->shouldReceive('createProductTransformer')
    ->with($product, \Mockery::type(\Closure::class))
</code>```

2) check any hidden args (created before call mocked method inside your testing method)

```<code>$transformerFactoryMock = \Mockery::mock('TransformerFactory')
    ->shouldReceive('createProductTransformer')
    ->with(function(...$args) use ($product) {
        // check any args
    })
</code>```

3) finally, fake result using passed callback to mocked method

```<code>// then mock will be
$transformerFactoryMock = \Mockery::mock('TransformerFactory')
    ->shouldReceive('createProductTransformer')
    ->andReturnUsing(function($closure) {
        // execute closure
        $closure();

        // any logic to fake return
        return;
    })
</code>```

Check doc of mockery complex argument matching and declaring return value

Title: Mocking method with callback param

Body:
I am trying to mock this method:

$transformer = $this->transformerFactory->createProductTransformer($product, function (ProductInterface $product) use ($discount) {
    $product->setDiscount($discount);
});

It accepts callback parameter as a second argument and I don't know how to mock it.

I am using Mockery so that would look like that:

$this->transformerFactoryMock
    ->shouldReceive('createProductTransformer')
    ->with(???) // here!

If I pass the same callback to the with() method, the instances does not match.
I don't mind using PHPUnit mocking if Mockery doesn't support that.

Body:
If you need check exactly that callback is called then it is not possible as each \Closure instance is unique and inside your tested method you created new one.

But you can do next:

1) validate dynamic args for type

// Assume in test case you have these mock/stub
$discount;
$product;

$transformerFactoryMock = \Mockery::mock('TransformerFactory')
    ->shouldReceive('createProductTransformer')
    ->with($product, \Mockery::type(\Closure::class))

2) check any hidden args (created before call mocked method inside your testing method)

$transformerFactoryMock = \Mockery::mock('TransformerFactory')
    ->shouldReceive('createProductTransformer')
    ->with(function(...$args) use ($product) {
        // check any args
    })

3) finally, fake result using passed callback to mocked method

// then mock will be
$transformerFactoryMock = \Mockery::mock('TransformerFactory')
    ->shouldReceive('createProductTransformer')
    ->andReturnUsing(function($closure) {
        // execute closure
        $closure();

        // any logic to fake return
        return;
    })

Check doc of mockery complex argument matching and declaring return value