问:
Plotting a section of defined length of a data stream
I want to plot a continuous stream of data. Here's a simplified version of what I'm doing.

```<code>x_values = []
y_values = []

index = count()

def animate(i):
    x_values.append(next(index))
    y_values.append(random.randint(0, 5))
    plt.cla()
    plt.plot(x_values, y_values)

ani = FuncAnimation(plt.gcf(), animate, 1000)

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

The code works as expected and the whole existing data is plotted while at the end of each iteration a new datapoint is added. The result is a growing plot. But I want to implement that only a certain section of the plot is shown which moves along with the generated data. E.g., in the first iteration the figure should show the section of the x-axis from 0-10, in the second iteration it should show the section of the x-axis from 1-11, and so on.

答:
Not sure why you thought that the linked example was not relevant. If matplotlib doesn't auto-update the x-axis, then we have to ask it politely. A simple implementation could look like this:</p>
```<code>import matplotlib.pyplot as plt
import matplotlib.animation as anim
import numpy as np
rng = np.random.default_rng()

fig, ax = plt.subplots()

#intialize x and y arrays with number of display points
points = 100
x = np.linspace(0, 1, points)
x_offset = x[1]
y = np.zeros(points)

l, = ax.plot(x, y)
ax.set_ylim(-2, 2)

def update(i):
    #set random new y-value within display range
    while True:
        y_new = y[-1] + 0.2 * rng.random() - 0.1
        if -2 < y_new < 2:
            y[:] = np.roll(y, -1)
            y[-1] = y_new
            break
    #shift x-values
    x_new = x[-1] + x_offset
    x[:] = np.roll(x, -1)
    x[-1] = x_new
    #update line with new values
    l.set_ydata(y)
    l.set_xdata(x)
    #and update x axis
    ax.set_xlim(x[0], x[-1])
    return l,

ani = anim.FuncAnimation(fig, update, frames=100 , interval=50, repeat=True)
plt.show()
</code>```

Body:
I want to plot a continuous stream of data. Here's a simplified version of what I'm doing.

x_values = []
y_values = []

index = count()

def animate(i):
    x_values.append(next(index))
    y_values.append(random.randint(0, 5))
    plt.cla()
    plt.plot(x_values, y_values)

ani = FuncAnimation(plt.gcf(), animate, 1000)

plt.tight_layout()
plt.show()

The code works as expected and the whole existing data is plotted while at the end of each iteration a new datapoint is added. The result is a growing plot. But I want to implement that only a certain section of the plot is shown which moves along with the generated data. E.g., in the first iteration the figure should show the section of the x-axis from 0-10, in the second iteration it should show the section of the x-axis from 1-11, and so on.

Body:
Not sure why you thought that the linked example was not relevant. If matplotlib doesn't auto-update the x-axis, then we have to ask it politely. A simple implementation could look like this:

import matplotlib.pyplot as plt
import matplotlib.animation as anim
import numpy as np
rng = np.random.default_rng()

fig, ax = plt.subplots()

#intialize x and y arrays with number of display points
points = 100
x = np.linspace(0, 1, points)
x_offset = x[1]
y = np.zeros(points)

l, = ax.plot(x, y)
ax.set_ylim(-2, 2)

def update(i):
    #set random new y-value within display range
    while True:
        y_new = y[-1] + 0.2 * rng.random() - 0.1
        if -2 < y_new < 2:
            y[:] = np.roll(y, -1)
            y[-1] = y_new
            break
    #shift x-values
    x_new = x[-1] + x_offset
    x[:] = np.roll(x, -1)
    x[-1] = x_new
    #update line with new values
    l.set_ydata(y)
    l.set_xdata(x)
    #and update x axis
    ax.set_xlim(x[0], x[-1])
    return l,

ani = anim.FuncAnimation(fig, update, frames=100 , interval=50, repeat=True)
plt.show()


来源: stackexchange

问:
How do I create a tf.Tensor from a pandas DataFrame containing arrays?
I have a pandas DataFrame like below.

```<code>import pandas as pd
import numpy as np
import tensorflow as tf  # Version 2.8.0
df = pd.DataFrame({"id":
                   ["i123", "i456"],
                   "col": [np.array(["igh", "ghdd", "yu"]),
                           np.array(["uh", "lkk", "nj"])]})
print(df)
</code>```

Output:

```<code>    id      col
0   i123    [igh, ghdd, yu]
1   i456    [uh, lkk, nj]
</code>```

I would to create a Tensor from the values of the col column, in order to use them in a specific use case. I have tried converting the values like

```<code>values = df["col"].to_numpy()
values
</code>```

Which looks like:

```<code>array([array(['igh', 'ghdd', 'yu'], dtype='<U4'),
       array(['uh', 'lkk', 'nj'], dtype='<U3')], dtype=object)
</code>```

When I try to convert this to a Tensor, by

```<code>tf.constant(values)
</code>```

I get an exception:

```<code>ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray).
</code>```

I can see from the documentation that the tf.constant method should work on a very similar array

The values variable I create have .shape like (2,) while the image below have (2, 3), which might be the problem.
I can't seem to get the dtype and/or shape to match exactly, and I'm unsure how to get it to work. Any ideas?

答:
Try:

import pandas as pd
import numpy as np
import tensorflow as tf  # Version 2.8.0
df = pd.DataFrame({"id":
                   ["i123", "i456"],
                   "col": [np.array(["igh", "ghdd", "yu"]),
                           np.array(["uh", "lkk", "nj"])]})

values = df["col"].to_list()
print(tf.constant(values))
```
```tf.Tensor(
[[b'igh' b'ghdd' b'yu']
 [b'uh' b'lkk' b'nj']], shape=(2, 3), dtype=string)
```
<p>Or</p>
```values = np.stack(df["col"].to_numpy())
print(tf.constant(values))
```

ContentLicense: CC BY-SA 4.0

Body:
I have a pandas DataFrame like below.

import pandas as pd
import numpy as np
import tensorflow as tf  # Version 2.8.0
df = pd.DataFrame({"id":
                   ["i123", "i456"],
                   "col": [np.array(["igh", "ghdd", "yu"]),
                           np.array(["uh", "lkk", "nj"])]})
print(df)

Output:

    id      col
0   i123    [igh, ghdd, yu]
1   i456    [uh, lkk, nj]

I would to create a Tensor from the values of the col column, in order to use them in a specific use case. I have tried converting the values like

values = df["col"].to_numpy()
values

Which looks like:

array([array(['igh', 'ghdd', 'yu'], dtype='<U4'),
       array(['uh', 'lkk', 'nj'], dtype='<U3')], dtype=object)

When I try to convert this to a Tensor, by

tf.constant(values)

I get an exception:

ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray).

I can see from the documentation that the tf.constant method should work on a very similar array

The values variable I create have .shape like (2,) while the image below have (2, 3), which might be the problem.
I can't seem to get the dtype and/or shape to match exactly, and I'm unsure how to get it to work. Any ideas?

Body:
Try:

import pandas as pd
import numpy as np
import tensorflow as tf  # Version 2.8.0
df = pd.DataFrame({"id":
                   ["i123", "i456"],
                   "col": [np.array(["igh", "ghdd", "yu"]),
                           np.array(["uh", "lkk", "nj"])]})

values = df["col"].to_list()
print(tf.constant(values))

tf.Tensor(
[[b'igh' b'ghdd' b'yu']
 [b'uh' b'lkk' b'nj']], shape=(2, 3), dtype=string)

Or

values = np.stack(df["col"].to_numpy())
print(tf.constant(values))


问:
Nodpi images vs. Android 1.5
I have an image in my app that I don't want to scale on loading. At the same time, I want to retain compatibility with Android 1.5.

So here's the deal. If I place the image under drawable, Android 1.6+ thinks it's MDPI, and scales accordingly. If I place the image under drawable-nodpi, Android 1.6+ does not scale it, but Android 1.5 cannot find it.

If I place a copy in both folders, Android 1.6 prefers the one in drawable, and scales it as if MDPI. And I don't want to ship two copies of the same file, so this was a last resort measure anyway.

Can you think of any way out? Preferably a way that does not involve two copies of the file.

答:
You could probarly do it though code.
Put myimage.png in the drawable folder, and create a file called myimage_nodpi.xml in the drawable-nodpi folder.

In this xml file you put:

```<code><?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android" android:src="@drawable/myimage" />
</code>```

This way, you won't have to copy the file.

In code, you can check if the API level is 4, and only load the nodpi version if that is the case:

```<code>int version = Integer.parseInt(android.os.Build.VERSION.SDK);
if(version >= 4) {
  drawable = res.getDrawable(R.drawable.myimage_nodpi);
} else {
  drawable = res.getDrawable(R.drawable.myimage);
}
</code>```

Disclaimer: Not tested!

ContentLicense: CC BY-SA 3.0

Title: Nodpi images vs. Android 1.5

Body:
You could probarly do it though code.
Put myimage.png in the drawable folder, and create a file called myimage_nodpi.xml in the drawable-nodpi folder.

In this xml file you put:

<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android" android:src="@drawable/myimage" />

This way, you won't have to copy the file.

In code, you can check if the API level is 4, and only load the nodpi version if that is the case:

int version = Integer.parseInt(android.os.Build.VERSION.SDK);
if(version >= 4) {
  drawable = res.getDrawable(R.drawable.myimage_nodpi);
} else {
  drawable = res.getDrawable(R.drawable.myimage);
}

Disclaimer: Not tested!


问:
How to scale a SwiftUI Image including its overlay?
Given this view with an image that has an overlay:

struct TestView: View {
    var body: some View {
        Image("image")
            .overlay {
                Image("logo")
                    .position(x: 20, y: 130) // I want to freely position the overlay image
            }
    }
}
```
<p>The size of the images shouldn’t matter. I my example they are 150×150 pixels (“image”) and 20×20 pixels (logo).</p>
<img src="https://i.stack.imgur.com/a6jeu.png" width="200" />
<p>How can I scale this up to its bounds (like superviews frame), <strong>including</strong> the overlay?</p>
<h2>Some must-have conditions:</h2>
<ul>
<li><p>I need to <strong>freely position</strong> the overlay image, so I can not use the <code>alignment</code> parameter of <code>overlay</code> in conjunction with a padding on the logo.</p>
</li>
<li><p>I also need to <strong>position</strong> the overlay image <strong>absolutely</strong>, not relatively. So I can’t use a <code>GeometryReader</code> (or <code>alignment</code>).</p>
</li>
<li><p>I need the view to be <strong>reusable</strong> in different scenarios (different devices, different view hierarchies). That means I <strong>don’t know the scale factor</strong>, so I can’t use <code>scaleEffect</code>.</p>
</li>
</ul>
<h2>I tried:</h2>
<h3>A) <code>.aspectRatio(contentMode: .fit)</code></h3>
<pre class="lang-swift prettyprint-override"><code>struct TestView: View {
    var body: some View {
        Image("image")
            .resizable()
            .overlay {
                Image("logo")
                    .position(x: 20, y: 130)
            }
            .aspectRatio(contentMode: .fit)
    }
}
</code>```

B) .scaledToFit()

struct TestView: View {
    var body: some View {
        Image("image")
            .resizable()
            .overlay {
                Image("logo")
                    .position(x: 20, y: 130)
            }
            .scaledToFit()
    }
}
```
<h3>C) Making logo resizable</h3>
<pre class="lang-swift prettyprint-override"><code>struct TestView: View {
    var body: some View {
        Image("image")
            .resizable()
            .overlay {
                Image("logo")
                    .resizable()
                    .position(x: 20, y: 130)
            }
            .scaledToFit() // or .aspectRatio(contentMode: .fit)
        }
}
</code>```

A and B looking like this:

C looking like this:

Both of which gave me a relative position of the logo that was different from the original (see linked screenshot). The relative size differs as well (it is now too small).

Wrapping in a stack and scale this stack instead also didn’t help.

[UPDATE] Accepted answer

Apparently not having a real view hierarchy in SwiftUI vs UIKit comes at a price. Scaling a hierarchy shouldn’t be that complicated imho. Instead I still would expect .scaledToFit (if added at the end) to scale everything before it (see A), B), and C)).

Adapted accepted answer (minus contentSize and alignment: .topLeading):

struct ContentView: View {
    var body: some View {
        Image("image")
            .resizable()
            .scaledToFit()
            .overlay {
                GeometryReader { geometry in
                    let imageSize = CGSize(width: 150, height: 150)
                    let logoSize = CGSize(width: 20, height: 20)
                    let logoPosition = CGPoint(x: 20, y: 130)
                    Image("logo")
                        .resizable()
                        .position(
                            x: logoPosition.x / imageSize.width * geometry.size.width,
                            y: logoPosition.y / imageSize.height * geometry.size.height
                        )
                        .frame(
                            width: logoSize.width / imageSize.width * geometry.size.width,
                            height: logoSize.height / imageSize.height * geometry.size.height
                        )
                }
            }
    }
}
```

答:
The problem is the absolute positioning of the logo. I see two ways:

scale the whole resulting image with .scaleEffect.

Be aware this is a render scaling of the underlying image, it will not be redrawn in the new size, so can become blurry.

```<code> Image("dog")
     .overlay {
         Image(systemName: "circle.hexagongrid.circle.fill")
             .foregroundColor(.pink)
             .position(x: 20, y: 130)
     }
     .scaleEffect(2.0)
</code>```

or – and my preference

2. Position the Logo relative to the lower left corner

```<code>    ZStack(alignment: .bottomLeading) {
        Image("dog")
            .resizable()
            .scaledToFit()
        Image(systemName: "circle.hexagongrid.circle.fill")
            .resizable()
            .foregroundColor(.pink)
            .frame(width: 70, height: 70)
            .padding()
    }
</code>```

Body:
Given this view with an image that has an overlay:

struct TestView: View {
    var body: some View {
        Image("image")
            .overlay {
                Image("logo")
                    .position(x: 20, y: 130) // I want to freely position the overlay image
            }
    }
}

The size of the images shouldn’t matter. I my example they are 150×150 pixels (“image”) and 20×20 pixels (logo).

How can I scale this up to its bounds (like superviews frame), including the overlay?

Some must-have conditions:

I need to freely position the overlay image, so I can not use the alignment parameter of overlay in conjunction with a padding on the logo.

I also need to position the overlay image absolutely, not relatively. So I can’t use a GeometryReader (or alignment).

I need the view to be reusable in different scenarios (different devices, different view hierarchies). That means I don’t know the scale factor, so I can’t use scaleEffect.

I tried:

A) .aspectRatio(contentMode: .fit)

struct TestView: View {
    var body: some View {
        Image("image")
            .resizable()
            .overlay {
                Image("logo")
                    .position(x: 20, y: 130)
            }
            .aspectRatio(contentMode: .fit)
    }
}

B) .scaledToFit()

struct TestView: View {
    var body: some View {
        Image("image")
            .resizable()
            .overlay {
                Image("logo")
                    .position(x: 20, y: 130)
            }
            .scaledToFit()
    }
}

C) Making logo resizable

struct TestView: View {
    var body: some View {
        Image("image")
            .resizable()
            .overlay {
                Image("logo")
                    .resizable()
                    .position(x: 20, y: 130)
            }
            .scaledToFit() // or .aspectRatio(contentMode: .fit)
        }
}

A and B looking like this:

C looking like this:

Both of which gave me a relative position of the logo that was different from the original (see linked screenshot). The relative size differs as well (it is now too small).

Wrapping in a stack and scale this stack instead also didn’t help.

[UPDATE] Accepted answer

Apparently not having a real view hierarchy in SwiftUI vs UIKit comes at a price. Scaling a hierarchy shouldn’t be that complicated imho. Instead I still would expect .scaledToFit (if added at the end) to scale everything before it (see A), B), and C)).

Adapted accepted answer (minus contentSize and alignment: .topLeading):

struct ContentView: View {
    var body: some View {
        Image("image")
            .resizable()
            .scaledToFit()
            .overlay {
                GeometryReader { geometry in
                    let imageSize = CGSize(width: 150, height: 150)
                    let logoSize = CGSize(width: 20, height: 20)
                    let logoPosition = CGPoint(x: 20, y: 130)
                    Image("logo")
                        .resizable()
                        .position(
                            x: logoPosition.x / imageSize.width * geometry.size.width,
                            y: logoPosition.y / imageSize.height * geometry.size.height
                        )
                        .frame(
                            width: logoSize.width / imageSize.width * geometry.size.width,
                            height: logoSize.height / imageSize.height * geometry.size.height
                        )
                }
            }
    }
}

Body:
The problem is the absolute positioning of the logo. I see two ways:

scale the whole resulting image with .scaleEffect.

Be aware this is a render scaling of the underlying image, it will not be redrawn in the new size, so can become blurry.

 Image("dog")
     .overlay {
         Image(systemName: "circle.hexagongrid.circle.fill")
             .foregroundColor(.pink)
             .position(x: 20, y: 130)
     }
     .scaleEffect(2.0)

or – and my preference

2. Position the Logo relative to the lower left corner

    ZStack(alignment: .bottomLeading) {
        Image("dog")
            .resizable()
            .scaledToFit()
        Image(systemName: "circle.hexagongrid.circle.fill")
            .resizable()
            .foregroundColor(.pink)
            .frame(width: 70, height: 70)
            .padding()
    }


问:
How to use `strsplit` before every capital letter of a camel case?
I want to use strsplit at a pattern before every capital letter and use a positive lookahead. However it also splits after every, and I'm confused about that. Is this regex incompatible with strsplit? Why is that so and what is to change?

```<code>strsplit('AaaBbbCcc', '(?=\\p{Lu})', perl=TRUE)[[1]]
strsplit('AaaBbbCcc', '(?=[A-Z])', perl=TRUE)[[1]]
strsplit('AaaBbbCcc', '(?=[ABC])', perl=TRUE)[[1]]
# [1] "A"  "aa" "B"  "bb" "C"  "cc"
</code>```

Expected result:

```<code># [1] "Aaa" "Bbb" "Ccc"
</code>```

In the Demo  it actually looks fine.

Ideally it should split before every camel case, e.g. Aa and not AA; there's \\p{Lt} but this doesn't seem to work at all.

```<code>strsplit('AaaABbbBCcc', '(?=\\p{Lt})', perl=TRUE)[[1]]
# [1] "AaaABbbBCcc"
</code>```

Expected result:

```<code># [1] "AaaA" "BbbB" "Ccc"
</code>```

答:
It seems that by adding (?!^) you can obtained the desired result.

```<code>strsplit('AaaBbbCcc', "(?!^)(?=[A-Z])", perl=TRUE)
</code>```

For the camel case we may do

```<code>strsplit('AaaABbbBCcc', '(?!^)(?=\\p{Lu}\\p{Ll})', perl=TRUE)[[1]]
strsplit('AaaABbbBCcc', '(?!^)(?=[A-Z][a-z])', perl=TRUE)[[1]]  ## or
# [1] "AaaA" "BbbB" "Ccc"
</code>```

Body:
I want to use strsplit at a pattern before every capital letter and use a positive lookahead. However it also splits after every, and I'm confused about that. Is this regex incompatible with strsplit? Why is that so and what is to change?

strsplit('AaaBbbCcc', '(?=\\p{Lu})', perl=TRUE)[[1]]
strsplit('AaaBbbCcc', '(?=[A-Z])', perl=TRUE)[[1]]
strsplit('AaaBbbCcc', '(?=[ABC])', perl=TRUE)[[1]]
# [1] "A"  "aa" "B"  "bb" "C"  "cc"

Expected result:

# [1] "Aaa" "Bbb" "Ccc"

In the Demo  it actually looks fine.

Ideally it should split before every camel case, e.g. Aa and not AA; there's \\p{Lt} but this doesn't seem to work at all.

strsplit('AaaABbbBCcc', '(?=\\p{Lt})', perl=TRUE)[[1]]
# [1] "AaaABbbBCcc"

Expected result:

# [1] "AaaA" "BbbB" "Ccc"

Body:
It seems that by adding (?!^) you can obtained the desired result.

strsplit('AaaBbbCcc', "(?!^)(?=[A-Z])", perl=TRUE)

For the camel case we may do

strsplit('AaaABbbBCcc', '(?!^)(?=\\p{Lu}\\p{Ll})', perl=TRUE)[[1]]
strsplit('AaaABbbBCcc', '(?!^)(?=[A-Z][a-z])', perl=TRUE)[[1]]  ## or
# [1] "AaaA" "BbbB" "Ccc"


问:
Problems with props passed to child component
I am having trouble passing props to a child component in my app.

When I navigate to any subject link that which has <PageTemplate />, I get blank page with an error in the console that says: subjects is not iterable.
subjects is an array of strings imported from another file as your can see from the code below: -

Here is the code:

Root component

```<code>import React from "react";

import Signup from './theQuestionsSteps/signup';
import Home from './home';
import ErrorPage from './pageNotFound';
import {
    Mathematics,
    English,
    Physics,
} from './subjects/subjects';

const RouterComponent = () => {

    return (
         <HashRouter>
             <Switch>
                <Route exact path="/" component={Home} />
                <Route path="/signup" component={Signup} />
                <Route path="/maths" component={Mathematics}></Route>
                <Route path="/english" component={English}></Route>
                <Route path="/physics" component={Physics}></Route>
             </switch>
         </HashRouter>
)

export default RouterComponent;
</code>```

This is the page header component where I navigate to subject components. Navigating to components that doesn't have the <PageTemplate /> render fine. But the mathematics throws the error I mentioned above.

```<code>import {NavLink} from 'react-router-dom';

const HeaderOfCategory = ({subjects}) => {

    const [s1, s2, s3, s4] = subjects;
    const routesVariabele = subjects.map((item) => {

        return "/" + item.replace(/\s/, '');
    });

    const [r1, r2, r3, r4] = routesVariabele;
    const styles = {
        backgroundColor: "green",
        color: "white"
    }

    return (
       <div className="flex flex-row gap-3 w-3/4 mx-auto justify-center">
            <NavLink to={{pathname: r1, subjects}} activeStyle={styles} className="p-3 rounded-lg hover:text-white bg-blue-100 mt-10 hover:bg-green-500 capitalize">{s1}</NavLink>
            <NavLink to={r2} activeStyle={styles} className="p-3 rounded-lg hover:text-white bg-blue-100 mt-10 hover:bg-green-500 capitalize">{s2}</NavLink>
            <NavLink to={r3} activeStyle={styles} className="p-3 rounded-lg hover:text-white bg-blue-100 mt-10 hover:bg-green-500 capitalize">{s3}</NavLink>
            <NavLink to={r4} activeStyle={styles} className="p-3 rounded-lg hover:text-white bg-blue-100 mt-10 hover:bg-green-500 capitalize">{s4}</NavLink>
 </div>
</code>```

The template component

```<code>import HeaderOfCategory from './headerOfCategory';

const PageTemplate = ({children, subjects}) =>
<div>
    <HeaderOfCategory subjects={subjects} />
    {children}
</div>

export default PageTemplate;
</code>```

The Subjects component

```<code>import PageTemplate from '../pageTemplate';

export const Mathematics = ({subjects}) => {

     return (
         <PageTemplate subjects={subjects}><div>I am maths</div></PageTemplate>
     )
}

export const English = () => {

     return (
         <div>I am english</div>
     )
}

export const Physics = () => {

     return (
         <div>I am physics</div>
     )
}
</code>```

Home page where the user selects subjects of his/her choice. This renders fine.

```<code>import React, {useState} from 'react';
import {NavLink} from 'react-router-dom';
import {subjects} from './subjectsList';

const Home = () => {

    const [countSelection, setCountSelection] = useState({four : 0, count : ''});
    const [theInput, setTheInput] = useState([]);

    const handleClick = (e) => {
            setCountSelection({...countSelection, four : countSelection.four + 1});
            if(countSelection.four >= 3){
                setCountSelection({...countSelection, count: 'disabled'});
            }
    }

    const handleChange = (e) => {

        setTheInput([...theInput, e.target.value]);

    }

    return (
        <div className="p-10 w-3/4 mx-auto">
            <div className="p-3 mx-auto">
                <h1 className="text-xl text-gray-500 mx-auto text-center">Select your combination of subjects to begin your exercise</h1>
            </div>

    <div  className="flex flex-col w-3/4 mt-8 p-10 mx-auto justify-center shadow-sm shadow-gray-600">
            <p className="mb-5">Note: You can only select Four (4) subjects of your choice</p>
            {subjects.map((item, index) => (
                <div key={index}>
                    <input
                    type="checkbox"
                    id={`subject${index}`} value={item}
                    onChange={handleChange}
                    onClick={handleClick}
                    disabled={countSelection.count}
                    />
                    <label htmlFor="" className="m-5 text-gray-600 capitalize">{item}</label>

                </div>

                ))
            }

            {countSelection.count === "disabled" ?<NavLink to={{pathname : "/startPage", theInput}} className="mt-10 w-2/4 p-3 bg-green-500 rounded-lg text-white hover:bg-blue-500 cursor-pointer">Submit</NavLink> : ''}
        </div>

        </div>
    )
}

export default Home;
</code>```

答:
Ok, I think I see now. You are trying to pass subjects to the Mathematics component via the NavLink, i.e. as route state.

```<code><NavLink
  to={{
    pathname: r1,
    subjects, // <-- not a valid to object property
  }}
  activeStyle={styles}
  className="...."
>
  {s1}
</NavLink>
</code>```

to: object

An object that can have any of the following properties:

pathname: A string representing the path to link to.

search: A string representation of query parameters.

hash: A hash to put in the URL, e.g. #a-hash.

state: State to persist to the location.

```<code><Link
  to={{
    pathname: "/courses",
    search: "?sort=name",
    hash: "#the-hash",
    state: { fromDashboard: true }
  }}
/>
</code>```

The issue here is that the link doesn't care about any subjects property. It should be passed on the state property.

```<code><NavLink
  to={{
    pathname: r1,
    state: { subjects }, // <-- pass in state
  }}
  activeStyle={styles}
  className="...."
>
  {s1}
</NavLink>
</code>```

Since Mathematics is rendered directly by a Route on the component prop it is passed route props, i.e. history, location, and match. It is in the location object that Mathematics can access the passed route state.

```<code><Route path="/maths" component={Mathematics} />
</code>```

...

```<code>export const Mathematics = ({ location }) => {
  const { state } = location;
  const { subjects } = state || {}; // provide fallback object to destructure from!

  return (
    <PageTemplate subjects={subjects}>
      <div>I am maths</div>
    </PageTemplate>
  )
}
</code>```

You may want to also provide a default subjects prop value in PageTemplate so if the prop isn't passed or it's undefined that subjects is at least an empty, iterable array.

```<code>const PageTemplate = ({ children, subjects = [] }) => (
  <div>
    <HeaderOfCategory subjects={subjects} />
    {children}
  </div>
);
</code>```

Body:
I am having trouble passing props to a child component in my app.

When I navigate to any subject link that which has <PageTemplate />, I get blank page with an error in the console that says: subjects is not iterable.
subjects is an array of strings imported from another file as your can see from the code below: -

Here is the code:

Root component

import React from "react";

import Signup from './theQuestionsSteps/signup';
import Home from './home';
import ErrorPage from './pageNotFound';
import {
    Mathematics,
    English,
    Physics,
} from './subjects/subjects';

const RouterComponent = () => {

    return (
         <HashRouter>
             <Switch>
                <Route exact path="/" component={Home} />
                <Route path="/signup" component={Signup} />
                <Route path="/maths" component={Mathematics}></Route>
                <Route path="/english" component={English}></Route>
                <Route path="/physics" component={Physics}></Route>
             </switch>
         </HashRouter>
)

export default RouterComponent;

This is the page header component where I navigate to subject components. Navigating to components that doesn't have the <PageTemplate /> render fine. But the mathematics throws the error I mentioned above.

import {NavLink} from 'react-router-dom';

const HeaderOfCategory = ({subjects}) => {

    const [s1, s2, s3, s4] = subjects;
    const routesVariabele = subjects.map((item) => {

        return "/" + item.replace(/\s/, '');
    });

    const [r1, r2, r3, r4] = routesVariabele;
    const styles = {
        backgroundColor: "green",
        color: "white"
    }

    return (

            <NavLink to={{pathname: r1, subjects}} activeStyle={styles} className="p-3 rounded-lg hover:text-white bg-blue-100 mt-10 hover:bg-green-500 capitalize">{s1}</NavLink>
            <NavLink to={r2} activeStyle={styles} className="p-3 rounded-lg hover:text-white bg-blue-100 mt-10 hover:bg-green-500 capitalize">{s2}</NavLink>
            <NavLink to={r3} activeStyle={styles} className="p-3 rounded-lg hover:text-white bg-blue-100 mt-10 hover:bg-green-500 capitalize">{s3}</NavLink>
            <NavLink to={r4} activeStyle={styles} className="p-3 rounded-lg hover:text-white bg-blue-100 mt-10 hover:bg-green-500 capitalize">{s4}</NavLink>

The template component

import HeaderOfCategory from './headerOfCategory';

const PageTemplate = ({children, subjects}) =>

    <HeaderOfCategory subjects={subjects} />
    {children}

export default PageTemplate;

The Subjects component

import PageTemplate from '../pageTemplate';

export const Mathematics = ({subjects}) => {

     return (
         <PageTemplate subjects={subjects}>
I am maths
</PageTemplate>
     )
}

export const English = () => {

     return (

I am english

     )
}

export const Physics = () => {

     return (

I am physics

     )
}

Home page where the user selects subjects of his/her choice. This renders fine.

import React, {useState} from 'react';
import {NavLink} from 'react-router-dom';
import {subjects} from './subjectsList';

const Home = () => {

    const [countSelection, setCountSelection] = useState({four : 0, count : ''});
    const [theInput, setTheInput] = useState([]);

    const handleClick = (e) => {
            setCountSelection({...countSelection, four : countSelection.four + 1});
            if(countSelection.four >= 3){
                setCountSelection({...countSelection, count: 'disabled'});
            }
    }

    const handleChange = (e) => {

        setTheInput([...theInput, e.target.value]);

    }

    return (

Select your combination of subjects to begin your exercise

Note: You can only select Four (4) subjects of your choice

            {subjects.map((item, index) => (

                    <input
                    type="checkbox"
                    id={`subject${index}`} value={item}
                    onChange={handleChange}
                    onClick={handleClick}
                    disabled={countSelection.count}
                    />
                    {item}

                ))
            }

            {countSelection.count === "disabled" ?<NavLink to={{pathname : "/startPage", theInput}} className="mt-10 w-2/4 p-3 bg-green-500 rounded-lg text-white hover:bg-blue-500 cursor-pointer">Submit</NavLink> : ''}

    )
}

export default Home;

Body:
Ok, I think I see now. You are trying to pass subjects to the Mathematics component via the NavLink, i.e. as route state.

<NavLink
  to={{
    pathname: r1,
    subjects, // <-- not a valid to object property
  }}
  activeStyle={styles}
  className="...."
>
  {s1}
</NavLink>

to: object

An object that can have any of the following properties:

pathname: A string representing the path to link to.

search: A string representation of query parameters.

hash: A hash to put in the URL, e.g. #a-hash.

state: State to persist to the location.

<Link
  to={{
    pathname: "/courses",
    search: "?sort=name",
    hash: "#the-hash",
    state: { fromDashboard: true }
  }}
/>

The issue here is that the link doesn't care about any subjects property. It should be passed on the state property.

<NavLink
  to={{
    pathname: r1,
    state: { subjects }, // <-- pass in state
  }}
  activeStyle={styles}
  className="...."
>
  {s1}
</NavLink>

Since Mathematics is rendered directly by a Route on the component prop it is passed route props, i.e. history, location, and match. It is in the location object that Mathematics can access the passed route state.

<Route path="/maths" component={Mathematics} />

...

export const Mathematics = ({ location }) => {
  const { state } = location;
  const { subjects } = state || {}; // provide fallback object to destructure from!

  return (
    <PageTemplate subjects={subjects}>
      <div>I am maths</div>
    </PageTemplate>
  )
}

You may want to also provide a default subjects prop value in PageTemplate so if the prop isn't passed or it's undefined that subjects is at least an empty, iterable array.

const PageTemplate = ({ children, subjects = [] }) => (
  <div>
    <HeaderOfCategory subjects={subjects} />
    {children}
  </div>
);


问:
how to fix this in bootstrap 5 nav bar dropdown stays open with click and mouse over
I am using Bootstrap 5 and enabled dropdown on click and hover.

.dropdown:hover .dropdown-menu{
        display: block;
        border-style:none;
        }```
</div>
</div>
</p>
<p>The problem is after I click on the top level dropdown item (that displays the dropdown items) and when I mouse over to next item the previous dropdown window stays open. How can I avoid this?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav class="navbar navbar-expand-sm bg-dark navbar-dark">
  <div class="container-fluid">
    Logo
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#collapsibleNavbar">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="collapsibleNavbar">
      <ul class="navbar-nav">
        <li class="nav-item">
          Home
        </li>

        <li class="nav-item dropdown">
          Dropdown
          <ul class="dropdown-menu">
            <li>Link</li>
            <li>Another link</li>
            <li>A third link</li>
          </ul>
        </li>

        <li class="nav-item dropdown">
          Dropdown1
          <ul class="dropdown-menu">
            <li>Link</li>
            <li>Another link</li>
            <li>A third link</li>
          </ul>
        </li>
      </ul>
    </div>
  </div>
</nav></code>```

how can I fix this issue?

答: Since it opens on mouse over, you don't need it on click. Remove data-bs-toggle="dropdown" from the dropdown and it should work fine.

Body:
I am using Bootstrap 5 and enabled dropdown on click and hover.

.dropdown:hover .dropdown-menu{
        display: block;
        border-style:none;
        }

The problem is after I click on the top level dropdown item (that displays the dropdown items) and when I mouse over to next item the previous dropdown window stays open. How can I avoid this?

    Logo
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#collapsibleNavbar">

    </button>

          Home

          Dropdown

Link

Another link

A third link

          Dropdown1

Link

Another link

A third link

how can I fix this issue?


问:
Generate values in separate dataframe
I trying to generate random data with Pandas.

Data is need to be stored in two columns. The first column needs to contain categorical variables (from Stratum_1 until Stratum_19) each of these stratums can contain a random number of values.

Second column needs to have data in the range between 1 to 180000000 with a standard deviation of 453210, a mean of 170000, and a number of rows 100000.

I try to

```<code>   categorical = {'name': ['Stratum_1','Stratum_2','Stratum_3','Stratum_4','Stratum_5','Stratum_6','Stratum_7','Stratum_8','Stratum_9',
    'Stratum_10','Stratum_11','Stratum_12','Stratum_13','Stratum_14','Stratum_15','Stratum_16','Stratum_17','Stratum_18','Stratum_19']}

desired_mean = 170000
desired_std_dev = 453210

df = pd.DataFrame(np.random.randint(0,180000000,size=(100000, 1)),columns=list('1'))
</code>```

I tried with this code above but don't know how to implement categorical and numerical values together with desired mean and standard deviation. So can anybody help how to solve this problem and generate?

答:
Try:

```<code>import numpy as np
categorical = {'name': ['Stratum_1','Stratum_2','Stratum_3','Stratum_4','Stratum_5','Stratum_6','Stratum_7','Stratum_8','Stratum_9',
    'Stratum_10','Stratum_11','Stratum_12','Stratum_13','Stratum_14','Stratum_15','Stratum_16','Stratum_17','Stratum_18','Stratum_19']}

desired_mean = 170000
desired_std_dev = 453210

df = pd.DataFrame({'num':np.random.normal(170000, 453210,size=(300000, 1)).reshape(-1), 'cat':np.random.choice(categorical['name'], 300000)})
df[(0<df['num'])&(df['num']<180000000)].sample(100000)
</code>```

result:

Title: Generate values in separate dataframe

Body:
I trying to generate random data with Pandas.

Data is need to be stored in two columns. The first column needs to contain categorical variables (from Stratum_1 until Stratum_19) each of these stratums can contain a random number of values.

Second column needs to have data in the range between 1 to 180000000 with a standard deviation of 453210, a mean of 170000, and a number of rows 100000.

I try to

   categorical = {'name': ['Stratum_1','Stratum_2','Stratum_3','Stratum_4','Stratum_5','Stratum_6','Stratum_7','Stratum_8','Stratum_9',
    'Stratum_10','Stratum_11','Stratum_12','Stratum_13','Stratum_14','Stratum_15','Stratum_16','Stratum_17','Stratum_18','Stratum_19']}

desired_mean = 170000
desired_std_dev = 453210

df = pd.DataFrame(np.random.randint(0,180000000,size=(100000, 1)),columns=list('1'))

I tried with this code above but don't know how to implement categorical and numerical values together with desired mean and standard deviation. So can anybody help how to solve this problem and generate?

Body:
Try:

import numpy as np
categorical = {'name': ['Stratum_1','Stratum_2','Stratum_3','Stratum_4','Stratum_5','Stratum_6','Stratum_7','Stratum_8','Stratum_9',
    'Stratum_10','Stratum_11','Stratum_12','Stratum_13','Stratum_14','Stratum_15','Stratum_16','Stratum_17','Stratum_18','Stratum_19']}

desired_mean = 170000
desired_std_dev = 453210

df = pd.DataFrame({'num':np.random.normal(170000, 453210,size=(300000, 1)).reshape(-1), 'cat':np.random.choice(categorical['name'], 300000)})
df[(0<df['num'])&(df['num']<180000000)].sample(100000)

result:


问:
Button hover does not work after I change button color using JS
I have a button that has a color change when hovering. And in Script the button color changes when a click event occurs.  However, Hover works when the page is loaded but after the color changes, it doesn't work. The code is below:

var count = 1;

function setColor(btn, color) {
  var property = document.getElementById(btn);
  if (count == 0) {
    property.style.backgroundColor = "white";
    count = 1;
  } else {
    property.style.backgroundColor = color;
    count = 0;
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.button {
  background-color: #4caf50;
  /* Green */
  border: none;
  color: white;
  padding: 16px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  transition-duration: 0.4s;
  cursor: pointer;
}

.button1 {
  background-color: white;
  color: black;
  border: 2px solid #4caf50;
}

.button1:hover {
  background-color: red;
  color: black;
  border: 2px solid #4caf50;
}</code>```

 Hoverable Buttons

<button id="buttonGreen" class="button button1" onclick="setColor('buttonGreen', '#122256')">
Green</button>```

After I click the button event occurs and the color changes to dark blue and the hover do not work.

答:
You should probably avoid inline JS. Here's an example that uses a closure to prevent globals variables, and some modified CSS so you don't have to add styles directly on to the element. Think more of the button, and how it changes. You basically adding and removing colours, so make them the new CSS classes.

// Cache the button
const button = document.querySelector('button');

// Add an event handler to it. The handler is a function
// that returns another function which acts as the listener
// This way you don't need to create global variables.
// A function that's returned from another function, and carries
// with it the variables from its local lexical environment
// is called a closure.
button.addEventListener('click', setColor(), false);

function setColor(color) {

  // Initialise count
  let count = true;

  // Return the function to be used as the button
  // handler. Instead of updating the style directly
  // just simply add/remove classes to the element
  return function () {
    this.classList.remove('green');
    if (count) {
      this.classList.remove('blue');
      this.classList.add('white');
      this.textContent = 'White';
    } else {
      this.classList.add('blue');
      this.classList.remove('white');
      this.textContent = 'Blue';
    }

    // Change count to true if it's false, or
    // false if it's true
    count = !count;
  }

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.button {
  border: 2px solid #4caf50;
  padding: 16px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  transition-duration: 0.4s;
  cursor: pointer;
}

.button:hover {
  background-color: red;
}

.white { background-color: white; }
.green { background-color: #4caf50; }
.blue { background-color: #122256; color: white; }</code>```

Hoverable Buttons

<button class="button green">Green</button>```

Body:
I have a button that has a color change when hovering. And in Script the button color changes when a click event occurs.  However, Hover works when the page is loaded but after the color changes, it doesn't work. The code is below:

var count = 1;

function setColor(btn, color) {
  var property = document.getElementById(btn);
  if (count == 0) {
    property.style.backgroundColor = "white";
    count = 1;
  } else {
    property.style.backgroundColor = color;
    count = 0;
  }
}

.button {
  background-color: #4caf50;
  /* Green */
  border: none;
  color: white;
  padding: 16px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  transition-duration: 0.4s;
  cursor: pointer;
}

.button1 {
  background-color: white;
  color: black;
  border: 2px solid #4caf50;
}

.button1:hover {
  background-color: red;
  color: black;
  border: 2px solid #4caf50;
}

 Hoverable Buttons

<button id="buttonGreen" class="button button1" onclick="setColor('buttonGreen', '#122256')">
Green</button>

After I click the button event occurs and the color changes to dark blue and the hover do not work.

Body:
You should probably avoid inline JS. Here's an example that uses a closure to prevent globals variables, and some modified CSS so you don't have to add styles directly on to the element. Think more of the button, and how it changes. You basically adding and removing colours, so make them the new CSS classes.

// Cache the button
const button = document.querySelector('button');

// Add an event handler to it. The handler is a function
// that returns another function which acts as the listener
// This way you don't need to create global variables.
// A function that's returned from another function, and carries
// with it the variables from its local lexical environment
// is called a closure.
button.addEventListener('click', setColor(), false);

function setColor(color) {

  // Initialise count
  let count = true;

  // Return the function to be used as the button
  // handler. Instead of updating the style directly
  // just simply add/remove classes to the element
  return function () {
    this.classList.remove('green');
    if (count) {
      this.classList.remove('blue');
      this.classList.add('white');
      this.textContent = 'White';
    } else {
      this.classList.add('blue');
      this.classList.remove('white');
      this.textContent = 'Blue';
    }

    // Change count to true if it's false, or
    // false if it's true
    count = !count;
  }

}

.button {
  border: 2px solid #4caf50;
  padding: 16px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  transition-duration: 0.4s;
  cursor: pointer;
}

.button:hover {
  background-color: red;
}

.white { background-color: white; }
.green { background-color: #4caf50; }
.blue { background-color: #122256; color: white; }

<h2>Hoverable Buttons</h2>
<button class="button green">Green</button>


问:
Force Postgres to install with UTF8 encoding, not LATIN1?
I'm trying to set up CartoDB on a Vagrant box, following the instructions here. However, it keeps failing because it complains that Postgres has been installed with Latin-1 encoding.

I can't work out why Postgres is doing this, because I'm explicitly forcing all the local settings to UTF8. Here's what I've been doing:

```<code>export LANGUAGE="en_US.UTF-8"
export LANG="en_US.UTF-8"
export LC_ALL="en_US.UTF-8"
locale
sudo apt-get update
sudo apt-get install -y python-software-properties
sudo add-apt-repository -y ppa:cartodb/gis
sudo add-apt-repository -y ppa:mapnik/v2.1.0
sudo add-apt-repository -y ppa:cartodb/nodejs
sudo add-apt-repository -y ppa:cartodb/redis
sudo add-apt-repository -y ppa:cartodb/postgresql
sudo add-apt-repository -y ppa:ubuntugis/ubuntugis-unstable
sudo apt-get update
sudo apt-get install -y make unp zip libgeos-c1 libgeos-dev gdal-bin libgdal1-dev libjson0
sudo apt-get install python-simplejson libjson0-dev proj-bin proj-data libproj-dev postgresql-9.1
</code>```

Here is the output of the early locale, showing that UTF8 has been set successfully:

```<code>LANG=en_US.UTF-8
LANGUAGE=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=en_US.UTF-8
</code>```

After running all the above commands, when I check the status of Postgres, it seems Postgres nonetheless installed itself with Latin-1 encoding:

```<code>sudo -u postgres psql -l

                         List of databases
   Name    |  Owner   | Encoding | Collate | Ctype |   Access privileges
-----------+----------+----------+---------+-------+-----------------------
 postgres  | postgres | LATIN1   | en_US   | en_US |
 template0 | postgres | LATIN1   | en_US   | en_US | =c/postgres          +
           |          |          |         |       | postgres=CTc/postgres
 template1 | postgres | LATIN1   | en_US   | en_US | =c/postgres          +
           |          |          |         |       | postgres=CTc/postgres
</code>```

Why is this happening? How can I force Postgres to install itself with UTF8 encoding?

答:
I just had the same problem in an ubuntu machine.

A freshly installed postgresql created the template databases with encoding=SQL_ASCII and collate/ctype=C

One of the answers here led me to the solution:

removed/purged the postgresql just installed

dpkg-reconfigure locales

installed locale for en_US.UTF-8

logout

login

checked the environment variable was automatically set LANG=en_US.UTF-8

reinstall postgresql

And ready, my databases are now with encoding=UTF8 and collate/ctype=en_US.UTF-8

Body:
I'm trying to set up CartoDB on a Vagrant box, following the instructions here. However, it keeps failing because it complains that Postgres has been installed with Latin-1 encoding.

I can't work out why Postgres is doing this, because I'm explicitly forcing all the local settings to UTF8. Here's what I've been doing:

export LANGUAGE="en_US.UTF-8"
export LANG="en_US.UTF-8"
export LC_ALL="en_US.UTF-8"
locale
sudo apt-get update
sudo apt-get install -y python-software-properties
sudo add-apt-repository -y ppa:cartodb/gis
sudo add-apt-repository -y ppa:mapnik/v2.1.0
sudo add-apt-repository -y ppa:cartodb/nodejs
sudo add-apt-repository -y ppa:cartodb/redis
sudo add-apt-repository -y ppa:cartodb/postgresql
sudo add-apt-repository -y ppa:ubuntugis/ubuntugis-unstable
sudo apt-get update
sudo apt-get install -y make unp zip libgeos-c1 libgeos-dev gdal-bin libgdal1-dev libjson0
sudo apt-get install python-simplejson libjson0-dev proj-bin proj-data libproj-dev postgresql-9.1

Here is the output of the early locale, showing that UTF8 has been set successfully:

LANG=en_US.UTF-8
LANGUAGE=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=en_US.UTF-8

After running all the above commands, when I check the status of Postgres, it seems Postgres nonetheless installed itself with Latin-1 encoding:

sudo -u postgres psql -l

                         List of databases
   Name    |  Owner   | Encoding | Collate | Ctype |   Access privileges
-----------+----------+----------+---------+-------+-----------------------
 postgres  | postgres | LATIN1   | en_US   | en_US |
 template0 | postgres | LATIN1   | en_US   | en_US | =c/postgres          +
           |          |          |         |       | postgres=CTc/postgres
 template1 | postgres | LATIN1   | en_US   | en_US | =c/postgres          +
           |          |          |         |       | postgres=CTc/postgres

Why is this happening? How can I force Postgres to install itself with UTF8 encoding?


问:
My directory in PhpStorm have yellow background
My directory in PhpStorm have this yellow contrast. What can I do to remove this?

答:
Welcome to StackOverflow, Matheus!

Your .idea directory which contain PHPStorm project settings seem to be corrupted. This dark-yellowish background marks files that do not belong to your project.

Try deleting .idea from outside your IDE using rm -rf .idea and reopen your project with File > Open..

Another way PHPStorm provides to solve issues like this could be using File > Repair IDE..

As this question seems to be a duplicate, I also found this useful stackoverflow answer.


问:
I cannot run npm install
I've dual Boot(ubuntu/Windows 10) on my laptop.
I am getting this error and I can't run npm install on Ubuntu. I checked with node -v and it shows v17.4.0
:

```<code>npm does not support Node.js v13.14.0

npm ERR! Invalid or unexpected token

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/diana/.npm/_logs/2022-02-12T09_42_18_704Z-debug-0.log
</code>```

Update: I had to uninstall and remove all the folders related to node and npm. I've also installed the latest version of nvm 0.39 and only then I managed to actually upgrade the node to the right version. Everything is working now.

How can I completely uninstall nodejs, npm and node in Ubuntu

答:
Have you tried updating your npm?

If no, run this:

```<code>sudo apt-get install -y npm
</code>```

or check this:

https://stackoverflow.com/questions/23393707/how-to-update-npm#:~:text=sudo%20add%2Dapt%2Drepository%20ppa%3Achris%2Dlea/node.js%0Asudo%20apt%2Dget%20update%0Asudo%20apt%2Dget%20install%20nodejs%20npm

Title: I cannot run npm install

Body:
I've dual Boot(ubuntu/Windows 10) on my laptop.
I am getting this error and I can't run npm install on Ubuntu. I checked with node -v and it shows v17.4.0
:

npm does not support Node.js v13.14.0

npm ERR! Invalid or unexpected token

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/diana/.npm/_logs/2022-02-12T09_42_18_704Z-debug-0.log

Update: I had to uninstall and remove all the folders related to node and npm. I've also installed the latest version of nvm 0.39 and only then I managed to actually upgrade the node to the right version. Everything is working now.

How can I completely uninstall nodejs, npm and node in Ubuntu

Body:
Have you tried updating your npm?

If no, run this:

sudo apt-get install -y npm

or check this:

https://stackoverflow.com/questions/23393707/how-to-update-npm#:~:text=sudo%20add%2Dapt%2Drepository%20ppa%3Achris%2Dlea/node.js%0Asudo%20apt%2Dget%20update%0Asudo%20apt%2Dget%20install%20nodejs%20npm


问:
Change font size if the text exceeds the boundary of Textblock
I have a textblock with a dimension of Width=511, Height=159. FontSize=28. I want to change the font size if the text exceeds the dimension of the textblock so that all the text will be displayed. Is there a way of doing this? A formula maybe?</p>

答:
Here's what I came up with.  Be sure you handle the -1.0 font size case.</p>

```<code>      private static double GetFontSize(TextBox textBox)
      {
         double fontSize = textBox.FontSize;
         FormattedText ft = new FormattedText(textBox.Text, CultureInfo.CurrentCulture, System.Windows.FlowDirection.LeftToRight,
                                          new Typeface(textBox.FontFamily, textBox.FontStyle, textBox.FontWeight, textBox.FontStretch),
                                          fontSize, textBox.Foreground);
         while (textBox.Width < ft.Width)
         {
            fontSize -= 1;
            if (fontSize < 0) return -1.0;
            ft = new FormattedText(textBox.Text, CultureInfo.CurrentCulture, System.Windows.FlowDirection.LeftToRight,
                                                      new Typeface(textBox.FontFamily, textBox.FontStyle, textBox.FontWeight, textBox.FontStretch),
                                                      fontSize, textBox.Foreground);
         }

         return fontSize;
      }
</code>```

Body:
Here's what I came up with.  Be sure you handle the -1.0 font size case.

      private static double GetFontSize(TextBox textBox)
      {
         double fontSize = textBox.FontSize;
         FormattedText ft = new FormattedText(textBox.Text, CultureInfo.CurrentCulture, System.Windows.FlowDirection.LeftToRight,
                                          new Typeface(textBox.FontFamily, textBox.FontStyle, textBox.FontWeight, textBox.FontStretch),
                                          fontSize, textBox.Foreground);
         while (textBox.Width < ft.Width)
         {
            fontSize -= 1;
            if (fontSize < 0) return -1.0;
            ft = new FormattedText(textBox.Text, CultureInfo.CurrentCulture, System.Windows.FlowDirection.LeftToRight,
                                                      new Typeface(textBox.FontFamily, textBox.FontStyle, textBox.FontWeight, textBox.FontStretch),
                                                      fontSize, textBox.Foreground);
         }

         return fontSize;
      }


问:
How to free data malloc()'d inside a loop?
```<code>#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
    int data;
    struct Node *next;
} Node;

void reverse_print_list(Node *head)
{
    if(head == NULL)
        return;

    print_list(head->next);
    printf("%d ", head->data);
}

int main()
{
    Node *head = malloc(sizeof(Node));
    head->data = rand() % 100;
    head->next = NULL;

    Node *temp = head;
    for (int i = 0; i < 9; i++) {
        Node* new_node = malloc(sizeof(Node));
        new_node->data = rand() % 100;
        new_node->next = NULL;

        temp->next = new_node;
        temp = temp->next;
    }

    temp = head;
    printf("Original list : \n");
    while (temp != NULL) {
        printf("%d ", temp->data);
        temp = temp->next;
    }
    printf("\n---------------------------\n");

    reverse_print_list(head);

    free(head);
    free(temp);

    return 0;
}
</code>```

In the above code, inside the for loop in main(), I am dynamically allocating memory for new nodes of a linked-list and attaching every newly created node to the last node in the list. But this seems like it would result in a memory leak since I am not freeing those nodes at the end of the loop as I need those nodes to exist outside of the loop. How can I free the nodes I have created inside the for loop? Running another loop starting from head to save all the nodes' addresses and then running another loop to manually free() all of those addresses seems tedious. Is there any other way? Thanks.

答:
Just delete the head node and replace head with its successor. Repeat until head becomes empty. Please note, you must backup the next pointer before calling free().

```<code>int main()
{
    Node *head = malloc(sizeof(Node));
    head->data = rand() % 100;
    head->next = NULL;

    ... build and print your list ...

    while (head)
    {
       Node * remainingChain = head->next;
       free(head);
       head = remainingChain;
    }
    return 0;
}
</code>```

Body:
#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
    int data;
    struct Node *next;
} Node;

void reverse_print_list(Node *head)
{
    if(head == NULL)
        return;

    print_list(head->next);
    printf("%d ", head->data);
}

int main()
{
    Node *head = malloc(sizeof(Node));
    head->data = rand() % 100;
    head->next = NULL;

    Node *temp = head;
    for (int i = 0; i < 9; i++) {
        Node* new_node = malloc(sizeof(Node));
        new_node->data = rand() % 100;
        new_node->next = NULL;

        temp->next = new_node;
        temp = temp->next;
    }

    temp = head;
    printf("Original list : \n");
    while (temp != NULL) {
        printf("%d ", temp->data);
        temp = temp->next;
    }
    printf("\n---------------------------\n");

    reverse_print_list(head);

    free(head);
    free(temp);

    return 0;
}

In the above code, inside the for loop in main(), I am dynamically allocating memory for new nodes of a linked-list and attaching every newly created node to the last node in the list. But this seems like it would result in a memory leak since I am not freeing those nodes at the end of the loop as I need those nodes to exist outside of the loop. How can I free the nodes I have created inside the for loop? Running another loop starting from head to save all the nodes' addresses and then running another loop to manually free() all of those addresses seems tedious. Is there any other way? Thanks.

Body:
Just delete the head node and replace head with its successor. Repeat until head becomes empty. Please note, you must backup the next pointer before calling free().

int main()
{
    Node *head = malloc(sizeof(Node));
    head->data = rand() % 100;
    head->next = NULL;

    ... build and print your list ...

    while (head)
    {
       Node * remainingChain = head->next;
       free(head);
       head = remainingChain;
    }
    return 0;
}


问:
How to set a composite to the right side of the screen
I have created 2 labels and I wish to move these labels to the right most side of the screen. I have created a new composite for the 2 labels and set the labels with the label composite. But now the label is somewhere towards the center. I have 7 other widgets already in the screen.

Following is the code I used:

```<code>Composite blockControls = this.formToolkit.createComposite(this.mainComposite, SWT.NONE);
blockControls.setLayout(GridLayoutFactory.fillDefaults().numColumns(8).create());
blockControls.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false));

Composite labelComposite = new Composite(blockControls, SWT.NONE);
GridLayout layout = new GridLayout();
labelComposite.setLayout(layout);
GridData layoutData = new GridData(SWT.END, SWT.END, true, true);
labelComposite.setLayoutData(layoutData);
labelComposite.setBackground(GUIHelper.COLOR_WHITE);

Label mappedEleLabel = new Label(labelComposite, SWT.LEAD);
mappedEleLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
mappedEleLabel.setText("hello");
mappedEleLabel.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_YELLOW));
mappedEleLabel.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK));

Label unmappedEleLabel = new Label(labelComposite, SWT.LEAD);
unmappedEleLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
unmappedEleLabel.setText("world");
unmappedEleLabel.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_GREEN));
unmappedEleLabel.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK));
</code>```

答:
You can use FormData but there are many ways.
FormData objects specify how each widget in a FormLayout will be laid out.

But the solution depends on the arrangement of the other 7 widgets.

I recommend this article: Layouts in SWT

Though the article may seem deprecated , Layouts in SWT haven't changed.

Body:
I have created 2 labels and I wish to move these labels to the right most side of the screen. I have created a new composite for the 2 labels and set the labels with the label composite. But now the label is somewhere towards the center. I have 7 other widgets already in the screen.

Following is the code I used:

Composite blockControls = this.formToolkit.createComposite(this.mainComposite, SWT.NONE);
blockControls.setLayout(GridLayoutFactory.fillDefaults().numColumns(8).create());
blockControls.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false));

Composite labelComposite = new Composite(blockControls, SWT.NONE);
GridLayout layout = new GridLayout();
labelComposite.setLayout(layout);
GridData layoutData = new GridData(SWT.END, SWT.END, true, true);
labelComposite.setLayoutData(layoutData);
labelComposite.setBackground(GUIHelper.COLOR_WHITE);

Label mappedEleLabel = new Label(labelComposite, SWT.LEAD);
mappedEleLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
mappedEleLabel.setText("hello");
mappedEleLabel.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_YELLOW));
mappedEleLabel.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK));

Label unmappedEleLabel = new Label(labelComposite, SWT.LEAD);
unmappedEleLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
unmappedEleLabel.setText("world");
unmappedEleLabel.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_GREEN));
unmappedEleLabel.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK));


问:
Decimal to Hexadecimal conversion of a number with fractional part, in python?
I want to change decimal with fraction to hexadecimal in python, I tried hex() function but works just for integer number</p>

答:
Python uses the float class to represent the real numbers.

CPython implements float using C double type. The C double type
usually implements IEEE 754 double-precision binary float, which is
also called binary64.

Python float uses 8 bytes (or 64 bits) to represent real numbers.
Unlike the integer type, the float type uses a fixed number of bytes.

Technically, Python uses 64 bits as follows:

1 bit for sign (positive or negative) 11 bits for exponent 1.5e-5 1.5
x 10-5 (exponent is -5) the range is [-1022, 1023]. 52 bits for
significant digits

quotes from this site

```<code>Take integer part convert it to hexa decimal
</code>```

And for fractional part use below algorithm:

Take a fractional part of the number

Multiply by 16

Convert integer part of the number to hexadecimal and remove it

Go to step 1

Finally join the integer and floating part together

please visit this link of stackoverflow for more details.

```<code>"""
Converts from float to hexadecimal
"""
def toHex(value:float):
    result = ""
    l = list()
    #converting to positive number and storing the - sign to the list
    if value < 0:
        value = -value;
        l.append('-')

    ivalue = int(value)#represent the integer part
    fvalue = value - ivalue#represent the floating part

    l.append(hex(ivalue))#storing the hexadecimal representation of integer part
    l.append('.')

    #float is 8 bytes and so has at most 16 hexadecimal values
    for i in range(16):
        fvalue = fvalue * 16
        digit = int(fvalue)
        l.append(format(digit,'X'))
        fvalue -= digit#removing the integer part
        if fvalue == 0:
          break
    #converting the result to a string
    for v in l:
        result += str(v)

    return result;

print(toHex(3.141592653))
</code>```

Output:

```<code>$ python3 hexa.py
0x3.243F6A85FD27
</code>```

Body:
Python uses the float class to represent the real numbers.

CPython implements float using C double type. The C double type
usually implements IEEE 754 double-precision binary float, which is
also called binary64.

Python float uses 8 bytes (or 64 bits) to represent real numbers.
Unlike the integer type, the float type uses a fixed number of bytes.

Technically, Python uses 64 bits as follows:

1 bit for sign (positive or negative) 11 bits for exponent 1.5e-5 1.5
x 10-5 (exponent is -5) the range is [-1022, 1023]. 52 bits for
significant digits

quotes from this site

Take integer part convert it to hexa decimal

And for fractional part use below algorithm:

Take a fractional part of the number

Multiply by 16

Convert integer part of the number to hexadecimal and remove it

Go to step 1

Finally join the integer and floating part together

please visit this link of stackoverflow for more details.

"""
Converts from float to hexadecimal
"""
def toHex(value:float):
    result = ""
    l = list()
    #converting to positive number and storing the - sign to the list
    if value < 0:
        value = -value;
        l.append('-')

    ivalue = int(value)#represent the integer part
    fvalue = value - ivalue#represent the floating part

    l.append(hex(ivalue))#storing the hexadecimal representation of integer part
    l.append('.')

    #float is 8 bytes and so has at most 16 hexadecimal values
    for i in range(16):
        fvalue = fvalue * 16
        digit = int(fvalue)
        l.append(format(digit,'X'))
        fvalue -= digit#removing the integer part
        if fvalue == 0:
          break
    #converting the result to a string
    for v in l:
        result += str(v)

    return result;

print(toHex(3.141592653))

Output:

$ python3 hexa.py
0x3.243F6A85FD27


问:
How to make a specific rectangle flutter
I want to make shape like the one below and write on it in my flutter app

How can I make it?

答:
You should make a CustomPainter like this:

```<code>class MyCustomRectangle extends CustomPainter {
  final Color color;

  const MyCustomRectangle({
    this.color = Colors.red,
  });

  @override
  void paint(Canvas canvas, Size size) {
    var paint = Paint();
    paint.color = color;
    paint.style = PaintingStyle.fill;

    var path = Path();

    path.lineTo(size.width, 0);
    path.lineTo(size.width - (size.height / 2), size.height / 2);
    path.lineTo(size.width, size.height);
    path.lineTo(0, size.height);

    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => oldDelegate != this;
}
</code>```

then use it like this:

```<code>CustomPaint(
          painter: MyCustomRectangle(),
          child: Padding(
            padding: EdgeInsets.symmetric(
              horizontal: 36.0,
              vertical: 8.0,
            ),
            child: Text(
              "Free Home Delivery 30 min",
              style: TextStyle(
                color: Colors.white,
                fontSize: 23.0,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        )
</code>```

the output:

Body:
You should make a CustomPainter like this:

class MyCustomRectangle extends CustomPainter {
  final Color color;

  const MyCustomRectangle({
    this.color = Colors.red,
  });

  @override
  void paint(Canvas canvas, Size size) {
    var paint = Paint();
    paint.color = color;
    paint.style = PaintingStyle.fill;

    var path = Path();

    path.lineTo(size.width, 0);
    path.lineTo(size.width - (size.height / 2), size.height / 2);
    path.lineTo(size.width, size.height);
    path.lineTo(0, size.height);

    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => oldDelegate != this;
}

then use it like this:

CustomPaint(
          painter: MyCustomRectangle(),
          child: Padding(
            padding: EdgeInsets.symmetric(
              horizontal: 36.0,
              vertical: 8.0,
            ),
            child: Text(
              "Free Home Delivery 30 min",
              style: TextStyle(
                color: Colors.white,
                fontSize: 23.0,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        )

the output:


问:
Is there any feasible solution to read WOT battle results .dat files?
I am new here to try to solve one of my interesting questions in World of Tanks. I heard that every battle data is reserved in the client's disk in the Wargaming.net folder because I want to make a batch of data analysis for our clan's battle performances.
 image

It is said that these .dat files are a kind of json files, so I tried to use a couple of lines of Python code to read but failed.

```<code>import json
f = open('ex.dat', 'r', encoding='unicode_escape')
content = f.read()
a = json.loads(content)
print(type(a))
print(a)
f.close()
</code>```

The code is very simple and obviously fails to make it. Well, could anyone tell me the truth about that?

Added on Feb. 9th, 2022
After I tried another set of codes via Jupyter Notebook, it seems like something can be shown from the .dat files

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

with open('C:/Users/xukun/Desktop/br/ex.dat', 'rb') as f:
    fbuff = io.BufferedReader(f)
    N = len(fbuff.read())
    print('byte length: ', N)

    with open('C:/Users/xukun/Desktop/br/ex.dat', 'rb') as f:
        data =struct.unpack('b'*N, f.read(1*N))
</code>```

The result is a set of tuple but I have no idea how to deal with it now.

答:
Here's how you can parse some parts of it.

```<code>import pickle
import zlib

file = '4402905758116487.dat'
cache_file = open(file, 'rb') # This can be improved to not keep the file opened.

# Converting pickle items from python2 to python3 you need to use the "bytes" encoding or "latin1".
legacyBattleResultVersion, brAllDataRaw = pickle.load(cache_file, encoding='bytes', errors='ignore')

arenaUniqueID, brAccount, brVehicleRaw, brOtherDataRaw = brAllDataRaw

# The data stored inside the pickled file will be a compressed pickle again.
vehicle_data = pickle.loads(zlib.decompress(brVehicleRaw), encoding='latin1')
account_data = pickle.loads(zlib.decompress(brAccount), encoding='latin1')
brCommon, brPlayersInfo, brPlayersVehicle, brPlayersResult = pickle.loads(zlib.decompress(brOtherDataRaw), encoding='latin1')

# Lastly you can print all of these and see a lot of data inside.
</code>```

The response contains a mixture of more binary files as well as some data captured from the replays.
This is not a complete solution but it's a decent start to parsing these files.

Body:
I am new here to try to solve one of my interesting questions in World of Tanks. I heard that every battle data is reserved in the client's disk in the Wargaming.net folder because I want to make a batch of data analysis for our clan's battle performances.
 image

It is said that these .dat files are a kind of json files, so I tried to use a couple of lines of Python code to read but failed.

import json
f = open('ex.dat', 'r', encoding='unicode_escape')
content = f.read()
a = json.loads(content)
print(type(a))
print(a)
f.close()

The code is very simple and obviously fails to make it. Well, could anyone tell me the truth about that?

Added on Feb. 9th, 2022
After I tried another set of codes via Jupyter Notebook, it seems like something can be shown from the .dat files

import struct
import numpy as np
import matplotlib.pyplot as plt
import io

with open('C:/Users/xukun/Desktop/br/ex.dat', 'rb') as f:
    fbuff = io.BufferedReader(f)
    N = len(fbuff.read())
    print('byte length: ', N)

    with open('C:/Users/xukun/Desktop/br/ex.dat', 'rb') as f:
        data =struct.unpack('b'*N, f.read(1*N))

The result is a set of tuple but I have no idea how to deal with it now.

Body:
Here's how you can parse some parts of it.

import pickle
import zlib

file = '4402905758116487.dat'
cache_file = open(file, 'rb') # This can be improved to not keep the file opened.

# Converting pickle items from python2 to python3 you need to use the "bytes" encoding or "latin1".
legacyBattleResultVersion, brAllDataRaw = pickle.load(cache_file, encoding='bytes', errors='ignore')

arenaUniqueID, brAccount, brVehicleRaw, brOtherDataRaw = brAllDataRaw

# The data stored inside the pickled file will be a compressed pickle again.
vehicle_data = pickle.loads(zlib.decompress(brVehicleRaw), encoding='latin1')
account_data = pickle.loads(zlib.decompress(brAccount), encoding='latin1')
brCommon, brPlayersInfo, brPlayersVehicle, brPlayersResult = pickle.loads(zlib.decompress(brOtherDataRaw), encoding='latin1')

# Lastly you can print all of these and see a lot of data inside.

The response contains a mixture of more binary files as well as some data captured from the replays.
This is not a complete solution but it's a decent start to parsing these files.


问:
mysql tables: Join to two tables in a request
Newbie here.. Here's what I'm trying to do.

I have a Posts table with the following columns

id, userid, bodyText, date
```

and I have another table for users users.

When users submit a post, the user-id saves into the "posts" table under "userid". Well, I want to display that users information, such as name and picture, on the posts using the "userid" to get each users information so that their name and picture shows along with the post they submitted.

Sorry if I'm not being clear, english is not my first language and like I said, I'm new at this and still trying to learn.
I had it where when they submit the post, their name and picture also saves into the "posts" table but I want to change it because if the user updates their name or picture, it will still show the name and picture they had when they submitted the post. I want their name and picture to update on the posts if they update their information on the users table.

答:
What you are asking about is a JOIN. In general the Join will look like

SELECT p.id. p.bodyText, p.date, u.name, u.picture FROM posts as p INNER JOIN users as u ON p.user_id = u.id where p.id = 123;
```
<p>This will select the post with the ID <code>123</code> from the posts table and joins the users information from the users table based on the user_id columns value from the posts table.</p>
<p>In Syntax this could be something like</p>
<pre class="lang-php prettyprint-override"><code>$sth = $dbh->prepare("SELECT p.id. p.bodyText, p.date, u.name, u.picture FROM posts as p INNER JOIN users as u ON p.user_id = u.id where p.id = ?");

$sth->execute(array(123));
$red = $sth->fetchAll();

</code>```

Body:
Newbie here.. Here's what I'm trying to do.

I have a Posts table with the following columns

id, userid, bodyText, date

and I have another table for users users.

When users submit a post, the user-id saves into the "posts" table under "userid". Well, I want to display that users information, such as name and picture, on the posts using the "userid" to get each users information so that their name and picture shows along with the post they submitted.

Sorry if I'm not being clear, english is not my first language and like I said, I'm new at this and still trying to learn.
I had it where when they submit the post, their name and picture also saves into the "posts" table but I want to change it because if the user updates their name or picture, it will still show the name and picture they had when they submitted the post. I want their name and picture to update on the posts if they update their information on the users table.

Body:
What you are asking about is a JOIN. In general the Join will look like

SELECT p.id. p.bodyText, p.date, u.name, u.picture FROM posts as p INNER JOIN users as u ON p.user_id = u.id where p.id = 123;

This will select the post with the ID 123 from the posts table and joins the users information from the users table based on the user_id columns value from the posts table.

In Syntax this could be something like

$sth = $dbh->prepare("SELECT p.id. p.bodyText, p.date, u.name, u.picture FROM posts as p INNER JOIN users as u ON p.user_id = u.id where p.id = ?");

$sth->execute(array(123));
$red = $sth->fetchAll();


问:
Overlay boxplot obtained grouping continuous variable with scatterplot of the original variables
I have a two continuous variables, one of which I have categorized in two groups. I want a scatterplot of the original variables over a boxplot of the categorized variable:

library(ggplot2)
data(cancer, package="survival")
lung$age2 <- lung$age >= 75

## Boxplot
ggplot(lung, aes(x=age2, y=wt.loss)) +
  geom_boxplot()
#> Warning: Removed 14 rows containing non-finite values (stat_boxplot).
```
<p><img src="https://i.imgur.com/zI8Jzgo.png" alt="" /></p>
<pre class="lang-r prettyprint-override"><code>## Scatterplot
ggplot(lung, aes(x=age, y=wt.loss)) +
  geom_point()
#> Warning: Removed 14 rows containing missing values (geom_point).
</code>```

Created on 2022-02-11 by the reprex package (v2.0.1)

I want the two graphs together, with the boxplot drawn at 50 and 70. Is that possible? ggplot2 preferred.

答:
I found this post that shows how to create a boxplot with a numeric x-axis. That is an acceptable solution to my problem, although not perfect:

library(ggplot2)
data(cancer, package="survival")
lung$age2 <- ifelse(lung$age < 75, 50, 70)
ggplot(lung) +
  geom_boxplot(aes(x=age, y=wt.loss, group=age2)) +
  geom_point(aes(x=age, y=wt.loss))
#> Warning: Removed 14 rows containing non-finite values (stat_boxplot).
#> Warning: Removed 14 rows containing missing values (geom_point).
```

Created on 2022-02-12 by the reprex package (v2.0.1)

Compared to the optimal solution, I couldn't get the boxes at fixed positions and of the same width (it is proportional to the number of observation). The position of the boxes make sense, however, because it is sensible to put them around the middle value of the corresponding group. I'd like to reduce the box width, though, but the width option seems to have no effect.

Body:
I have a two continuous variables, one of which I have categorized in two groups. I want a scatterplot of the original variables over a boxplot of the categorized variable:

library(ggplot2)
data(cancer, package="survival")
lung$age2 <- lung$age >= 75

## Boxplot
ggplot(lung, aes(x=age2, y=wt.loss)) +
  geom_boxplot()
#> Warning: Removed 14 rows containing non-finite values (stat_boxplot).

## Scatterplot
ggplot(lung, aes(x=age, y=wt.loss)) +
  geom_point()
#> Warning: Removed 14 rows containing missing values (geom_point).

Created on 2022-02-11 by the reprex package (v2.0.1)

I want the two graphs together, with the boxplot drawn at 50 and 70. Is that possible? ggplot2 preferred.

Body:
I found this post that shows how to create a boxplot with a numeric x-axis. That is an acceptable solution to my problem, although not perfect:

library(ggplot2)
data(cancer, package="survival")
lung$age2 <- ifelse(lung$age < 75, 50, 70)
ggplot(lung) +
  geom_boxplot(aes(x=age, y=wt.loss, group=age2)) +
  geom_point(aes(x=age, y=wt.loss))
#> Warning: Removed 14 rows containing non-finite values (stat_boxplot).
#> Warning: Removed 14 rows containing missing values (geom_point).

Created on 2022-02-12 by the reprex package (v2.0.1)

Compared to the optimal solution, I couldn't get the boxes at fixed positions and of the same width (it is proportional to the number of observation). The position of the boxes make sense, however, because it is sensible to put them around the middle value of the corresponding group. I'd like to reduce the box width, though, but the width option seems to have no effect.


问:
Get the current date using date-fns in ISO-8601 format
I want to get a ISO-8601 format of last hour:minute:secounds from the current day using date-fns lib:

I'm using:
endOfDay(new Date());

Fri Sep 14 2018 23:59:59 GMT-0300

So add toISOString() to get it in ISO format:
endOfDay(new Date()).toISOString()

Result:
2018-09-15T02:59:59.999Z

When I need:

2018-09-14T23:59:59.999Z

答:
```<code>format(endOfDay(new Date()), "yyyy-MM-dd'T'HH:mm:ss'Z'")
</code>```

This method worked for me

Body:
format(endOfDay(new Date()), "yyyy-MM-dd'T'HH:mm:ss'Z'")

This method worked for me


问:
How to Remove Title Bar from Flutter app built for windows?
I've made a simple flutter app for windows, when I run it shows the default Titlebar that windows has. How can I remove it ??</p>

答:
Using this package bitsdojo_window do the following:

Inside your application folder, go to windows\runner\main.cpp and add these two lines at the beginning of the file:

```<code>#include <bitsdojo_window_windows/bitsdojo_window_plugin.h>
auto bdw = bitsdojo_window_configure(BDW_CUSTOM_FRAME | BDW_HIDE_ON_STARTUP);
</code>```

Now go to lib\main.dart and add this code in the main function right after runApp(MyApp()); :

```<code>void main() {
  runApp(MyApp());

  // Add this code below

  doWhenWindowReady(() {
    appWindow.show();
  });
}
</code>```

You can also customize the window with something like:

```<code>  doWhenWindowReady(() {
    final initialSize = Size(600, 450);
    appWindow.minSize = initialSize;
    appWindow.size = initialSize;
    appWindow.alignment = Alignment.center;
    appWindow.show();
  });
</code>```

To implement your own title buttons and text, you can use these methods from the package:

```<code>appWindow.title(title);
appWindow.close();
appWindow.maximize();
appWindow.minimize();
</code>```

You can also give the properties of the title bar to any widget (like dragging and double click for maximize) by wraping it inside MoveWindow() widget.

Body:
Using this package bitsdojo_window do the following:

Inside your application folder, go to windows\runner\main.cpp and add these two lines at the beginning of the file:

#include <bitsdojo_window_windows/bitsdojo_window_plugin.h>
auto bdw = bitsdojo_window_configure(BDW_CUSTOM_FRAME | BDW_HIDE_ON_STARTUP);

Now go to lib\main.dart and add this code in the main function right after runApp(MyApp()); :

void main() {
  runApp(MyApp());

  // Add this code below

  doWhenWindowReady(() {
    appWindow.show();
  });
}

You can also customize the window with something like:

  doWhenWindowReady(() {
    final initialSize = Size(600, 450);
    appWindow.minSize = initialSize;
    appWindow.size = initialSize;
    appWindow.alignment = Alignment.center;
    appWindow.show();
  });

To implement your own title buttons and text, you can use these methods from the package:

appWindow.title(title);
appWindow.close();
appWindow.maximize();
appWindow.minimize();

You can also give the properties of the title bar to any widget (like dragging and double click for maximize) by wraping it inside MoveWindow() widget.


问:
docker-compose Error: FileNotFoundError: [Errno 2] No such file or directory
I am trying to compose a Docker file with a YML file as below.

```<code>version: '3.6'
services:
  postgres:
    image: postgres:12
    restart: always
    volumes:
    - db_data:/var/lib/postgresql/data
    environment:
      POSTGRES_PASSWORD: postgrespassword
  graphql-engine:
    image: hasura/graphql-engine:v2.0.3
    ports:
    - "8080:8080"
    depends_on:
    - "postgres"
    restart: always
    environment:
      HASURA_GRAPHQL_METADATA_DATABASE_URL: postgres://postgres:postgrespassword@postgres:5432/postgres
      ## enable the console served by server
      HASURA_GRAPHQL_ENABLE_CONSOLE: "true" # set to "false" to disable console
      ## enable debugging mode. It is recommended to disable this in production
      HASURA_GRAPHQL_DEV_MODE: "true"
      HASURA_GRAPHQL_ENABLED_LOG_TYPES: startup, http-log, webhook-log, websocket-log, query-log
      ## uncomment next line to set an admin secret
      # HASURA_GRAPHQL_ADMIN_SECRET: myadminsecretkey
volumes:
  db_data:
</code>```

But am getting the following error:

```<code>hasura-ais docker-compose up -d
Traceback (most recent call last):
  File "site-packages/urllib3/connectionpool.py", line 677, in urlopen
  File "site-packages/urllib3/connectionpool.py", line 392, in _make_request
  File "http/client.py", line 1252, in request
  File "http/client.py", line 1298, in _send_request
  File "http/client.py", line 1247, in endheaders
  File "http/client.py", line 1026, in _send_output
  File "http/client.py", line 966, in send
  File "site-packages/docker/transport/unixconn.py", line 43, in connect
FileNotFoundError: [Errno 2] No such file or directory

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "site-packages/requests/adapters.py", line 449, in send
  File "site-packages/urllib3/connectionpool.py", line 727, in urlopen
  File "site-packages/urllib3/util/retry.py", line 403, in increment
  File "site-packages/urllib3/packages/six.py", line 734, in reraise
  File "site-packages/urllib3/connectionpool.py", line 677, in urlopen
  File "site-packages/urllib3/connectionpool.py", line 392, in _make_request
  File "http/client.py", line 1252, in request
  File "http/client.py", line 1298, in _send_request
  File "http/client.py", line 1247, in endheaders
  File "http/client.py", line 1026, in _send_output
  File "http/client.py", line 966, in send
  File "site-packages/docker/transport/unixconn.py", line 43, in connect
urllib3.exceptions.ProtocolError: ('Connection aborted.', FileNotFoundError(2, 'No such file or directory'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "site-packages/docker/api/client.py", line 205, in _retrieve_server_version
  File "site-packages/docker/api/daemon.py", line 181, in version
  File "site-packages/docker/utils/decorators.py", line 46, in inner
  File "site-packages/docker/api/client.py", line 228, in _get
  File "site-packages/requests/sessions.py", line 543, in get
  File "site-packages/requests/sessions.py", line 530, in request
  File "site-packages/requests/sessions.py", line 643, in send
  File "site-packages/requests/adapters.py", line 498, in send
requests.exceptions.ConnectionError: ('Connection aborted.', FileNotFoundError(2, 'No such file or directory'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "docker-compose", line 3, in <module>
  File "compose/cli/main.py", line 67, in main
  File "compose/cli/main.py", line 123, in perform_command
  File "compose/cli/command.py", line 69, in project_from_options
  File "compose/cli/command.py", line 132, in get_project
  File "compose/cli/docker_client.py", line 43, in get_client
  File "compose/cli/docker_client.py", line 170, in docker_client
  File "site-packages/docker/api/client.py", line 188, in __init__
  File "site-packages/docker/api/client.py", line 213, in _retrieve_server_version
docker.errors.DockerException: Error while fetching server API version: ('Connection aborted.', FileNotFoundError(2, 'No such file or directory'))
[18722] Failed to execute script docker-compose
</code>```

答:
I had the same issue while using volumes. I created the folders inside the mounted volume and that fixed it.

Inside my docker, I had a folder like this:

```<code>/data/logs
/data/files
</code>```

and was mounting my local empty /data folder. It was fixed after creating logs and files folders inside my local /data.

Body:
I am trying to compose a Docker file with a YML file as below.

version: '3.6'
services:
  postgres:
    image: postgres:12
    restart: always
    volumes:
    - db_data:/var/lib/postgresql/data
    environment:
      POSTGRES_PASSWORD: postgrespassword
  graphql-engine:
    image: hasura/graphql-engine:v2.0.3
    ports:
    - "8080:8080"
    depends_on:
    - "postgres"
    restart: always
    environment:
      HASURA_GRAPHQL_METADATA_DATABASE_URL: postgres://postgres:postgrespassword@postgres:5432/postgres
      ## enable the console served by server
      HASURA_GRAPHQL_ENABLE_CONSOLE: "true" # set to "false" to disable console
      ## enable debugging mode. It is recommended to disable this in production
      HASURA_GRAPHQL_DEV_MODE: "true"
      HASURA_GRAPHQL_ENABLED_LOG_TYPES: startup, http-log, webhook-log, websocket-log, query-log
      ## uncomment next line to set an admin secret
      # HASURA_GRAPHQL_ADMIN_SECRET: myadminsecretkey
volumes:
  db_data:

But am getting the following error:

hasura-ais docker-compose up -d
Traceback (most recent call last):
  File "site-packages/urllib3/connectionpool.py", line 677, in urlopen
  File "site-packages/urllib3/connectionpool.py", line 392, in _make_request
  File "http/client.py", line 1252, in request
  File "http/client.py", line 1298, in _send_request
  File "http/client.py", line 1247, in endheaders
  File "http/client.py", line 1026, in _send_output
  File "http/client.py", line 966, in send
  File "site-packages/docker/transport/unixconn.py", line 43, in connect
FileNotFoundError: [Errno 2] No such file or directory

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "site-packages/requests/adapters.py", line 449, in send
  File "site-packages/urllib3/connectionpool.py", line 727, in urlopen
  File "site-packages/urllib3/util/retry.py", line 403, in increment
  File "site-packages/urllib3/packages/six.py", line 734, in reraise
  File "site-packages/urllib3/connectionpool.py", line 677, in urlopen
  File "site-packages/urllib3/connectionpool.py", line 392, in _make_request
  File "http/client.py", line 1252, in request
  File "http/client.py", line 1298, in _send_request
  File "http/client.py", line 1247, in endheaders
  File "http/client.py", line 1026, in _send_output
  File "http/client.py", line 966, in send
  File "site-packages/docker/transport/unixconn.py", line 43, in connect
urllib3.exceptions.ProtocolError: ('Connection aborted.', FileNotFoundError(2, 'No such file or directory'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "site-packages/docker/api/client.py", line 205, in _retrieve_server_version
  File "site-packages/docker/api/daemon.py", line 181, in version
  File "site-packages/docker/utils/decorators.py", line 46, in inner
  File "site-packages/docker/api/client.py", line 228, in _get
  File "site-packages/requests/sessions.py", line 543, in get
  File "site-packages/requests/sessions.py", line 530, in request
  File "site-packages/requests/sessions.py", line 643, in send
  File "site-packages/requests/adapters.py", line 498, in send
requests.exceptions.ConnectionError: ('Connection aborted.', FileNotFoundError(2, 'No such file or directory'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "docker-compose", line 3, in <module>
  File "compose/cli/main.py", line 67, in main
  File "compose/cli/main.py", line 123, in perform_command
  File "compose/cli/command.py", line 69, in project_from_options
  File "compose/cli/command.py", line 132, in get_project
  File "compose/cli/docker_client.py", line 43, in get_client
  File "compose/cli/docker_client.py", line 170, in docker_client
  File "site-packages/docker/api/client.py", line 188, in __init__
  File "site-packages/docker/api/client.py", line 213, in _retrieve_server_version
docker.errors.DockerException: Error while fetching server API version: ('Connection aborted.', FileNotFoundError(2, 'No such file or directory'))
[18722] Failed to execute script docker-compose

Body:
I had the same issue while using volumes. I created the folders inside the mounted volume and that fixed it.

Inside my docker, I had a folder like this:

/data/logs
/data/files

and was mounting my local empty /data folder. It was fixed after creating logs and files folders inside my local /data.


问:
Where to find 'webpack.config.js' - BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default
I am getting the following errors on my browser concerning webpack5.

I have located answers in here but the authors are directing to a file called 'webpack.config.js' which apparently exists in the root folder of my app.  The problem is, I cannot find such a file in the root folder of my app.  Please can someone advise?

答:
You likely can't see the config file because you built your app using create-react-app so configuration is managed for you. Try installing stream-browserify npm install stream-browserify

You could also use something like https://www.npmjs.com/package/@craco/craco which allows you to keep react bundled up but also gives you access to change webpack configuration.

The last option would be to downgrade.


问:
Enum String Name from Value
I have an enum construct like this:

```<code>public enum EnumDisplayStatus
{
    None    = 1,
    Visible = 2,
    Hidden  = 3,
    MarkedForDeletion = 4
}
</code>```

In my database, the enumerations are referenced by value. My question is, how can I turn the number representation of the enum back to the string name.

For example, given 2 the result should be Visible.

答:
Given:

```<code>enum Colors {
    Red = 1,
    Green = 2,
    Blue = 3
};
</code>```

In .NET 4.7 the following

```<code>Console.WriteLine( Enum.GetName( typeof(Colors), Colors.Green ) );
Console.WriteLine( Enum.GetName( typeof(Colors), 3 ) );
</code>```

will display

```<code>Green
Blue
</code>```

In .NET 6 the above still works, but also:

```<code>Console.WriteLine( Enum.GetName( Colors.Green ) );
Console.WriteLine( Enum.GetName( (Colors)3 ) );
</code>```

will display:

```<code>Green
Blue
</code>```

OwnerDisplayName: enfovd the oppressor

Title: Enum String Name from Value

Body:
I have an enum construct like this:

public enum EnumDisplayStatus
{
    None    = 1,
    Visible = 2,
    Hidden  = 3,
    MarkedForDeletion = 4
}

In my database, the enumerations are referenced by value. My question is, how can I turn the number representation of the enum back to the string name.

For example, given 2 the result should be Visible.

Body:
Given:

enum Colors {
    Red = 1,
    Green = 2,
    Blue = 3
};

In .NET 4.7 the following

Console.WriteLine( Enum.GetName( typeof(Colors), Colors.Green ) );
Console.WriteLine( Enum.GetName( typeof(Colors), 3 ) );

will display

Green
Blue

In .NET 6 the above still works, but also:

Console.WriteLine( Enum.GetName( Colors.Green ) );
Console.WriteLine( Enum.GetName( (Colors)3 ) );

will display:

Green
Blue


问:
Best practices for link logging in JavaScript?
Basically, onclick will trigger exclusively on left clicks.

Most places recommend onmouseup, because it triggers on left, middle, and right clicks.  The right clicks can of course be filtered out.  However, it is still possible to generate false positives from onmouseup by left or middle click dragging from text to the link.

Is there a more direct way in JavaScript that will be triggered if and only if an external link is followed?  Or is onmouseup the only practical solution?

答: You could try something with window.onbeforeunload. Have it call a function that does your bidding. What are you wanting to detect?