问:
In Plotly, how to change axis titles dynamically when switching between different graphs using an Update button
I have 3 separate scatter plots that can be selected using buttons, with only the dependent variable changing between them. How do I code the yaxis_title to change with each button selected? I haven't found any demonstration of this in their tutorials. I have attached code from the sample tutorial as an example.

```<code>import plotly.graph_objects as go

import pandas as pd

# Load dataset
df = pd.read_csv(
  "https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv")

df.columns = [col.replace("AAPL.", "") for col in df.columns]

# Initialize figure
fig = go.Figure()

# Add Traces

fig.add_trace(
go.Scatter(x=list(df.index),
           y=list(df.High),
           name="High",
           line=dict(color="#33CFA5")))

fig.add_trace(
go.Scatter(x=list(df.index),
           y=[df.High.mean()] * len(df.index),
           name="High Average",
           visible=False,
           line=dict(color="#33CFA5", dash="dash")))

fig.add_trace(
go.Scatter(x=list(df.index),
           y=list(df.Low),
           name="Low",
           line=dict(color="#F06A6A")))

fig.add_trace(
go.Scatter(x=list(df.index),
           y=[df.Low.mean()] * len(df.index),
           name="Low Average",
           visible=False,
           line=dict(color="#F06A6A", dash="dash")))

# Add Annotations and Buttons
high_annotations = [dict(x="2016-03-01",
                     y=df.High.mean(),
                     xref="x", yref="y",
                     text="High Average:<br> %.2f" % df.High.mean(),
                     ax=0, ay=-40),
                dict(x=df.High.idxmax(),
                     y=df.High.max(),
                     xref="x", yref="y",
                     text="High Max:<br> %.2f" % df.High.max(),
                     ax=0, ay=-40)]
low_annotations = [dict(x="2015-05-01",
                    y=df.Low.mean(),
                    xref="x", yref="y",
                    text="Low Average:<br> %.2f" % df.Low.mean(),
                    ax=-40, ay=40),
               dict(x=df.High.idxmin(),
                    y=df.Low.min(),
                    xref="x", yref="y",
                    text="Low Min:<br> %.2f" % df.Low.min(),
                    ax=0, ay=40)]

fig.update_layout(
   updatemenus=[
    dict(
        type="buttons",
        direction="right",
        active=0,
        x=0.57,
        y=1.2,
        buttons=list([
            dict(label="None",
                 method="update",
                 args=[{"visible": [True, False, True, False]},
                       {"title": "Yahoo",
                        "annotations": []}]),
            dict(label="High",
                 method="update",
                 args=[{"visible": [True, True, False, False]},
                       {"title": "Yahoo High",
                        "annotations": high_annotations}]),
            dict(label="Low",
                 method="update",
                 args=[{"visible": [False, False, True, True]},
                       {"title": "Yahoo Low",
                        "annotations": low_annotations}]),
            dict(label="Both",
                 method="update",
                 args=[{"visible": [True, True, True, True]},
                       {"title": "Yahoo",
                        "annotations": high_annotations + low_annotations}]),
        ]),
    )
])

# Set title
fig.update_layout(
    title_text="Yahoo",
    xaxis_domain=[0.05, 1.0]
)

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

答:
Changing the xy-Axis Titles with Dropdown Menu Here are the same questions as you and the answers.</p>

```<code>        buttons=list([
        dict(label="None",
             method="update",
             args=[{"visible": [True, False, True, False]},
                   {"title": "Yahoo",
                    "xaxis": {"title": "Date"},
                    "yaxis": {"title": "High Price - Dollars"},
                    "annotations": []}]),
</code>```

Body:
I have 3 separate scatter plots that can be selected using buttons, with only the dependent variable changing between them. How do I code the yaxis_title to change with each button selected? I haven't found any demonstration of this in their tutorials. I have attached code from the sample tutorial as an example.

import plotly.graph_objects as go

import pandas as pd

# Load dataset
df = pd.read_csv(
  "https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv")

df.columns = [col.replace("AAPL.", "") for col in df.columns]

# Initialize figure
fig = go.Figure()

# Add Traces

fig.add_trace(
go.Scatter(x=list(df.index),
           y=list(df.High),
           name="High",
           line=dict(color="#33CFA5")))

fig.add_trace(
go.Scatter(x=list(df.index),
           y=[df.High.mean()] * len(df.index),
           name="High Average",
           visible=False,
           line=dict(color="#33CFA5", dash="dash")))

fig.add_trace(
go.Scatter(x=list(df.index),
           y=list(df.Low),
           name="Low",
           line=dict(color="#F06A6A")))

fig.add_trace(
go.Scatter(x=list(df.index),
           y=[df.Low.mean()] * len(df.index),
           name="Low Average",
           visible=False,
           line=dict(color="#F06A6A", dash="dash")))

# Add Annotations and Buttons
high_annotations = [dict(x="2016-03-01",
                     y=df.High.mean(),
                     xref="x", yref="y",
                     text="High Average:
 %.2f" % df.High.mean(),
                     ax=0, ay=-40),
                dict(x=df.High.idxmax(),
                     y=df.High.max(),
                     xref="x", yref="y",
                     text="High Max:
 %.2f" % df.High.max(),
                     ax=0, ay=-40)]
low_annotations = [dict(x="2015-05-01",
                    y=df.Low.mean(),
                    xref="x", yref="y",
                    text="Low Average:
 %.2f" % df.Low.mean(),
                    ax=-40, ay=40),
               dict(x=df.High.idxmin(),
                    y=df.Low.min(),
                    xref="x", yref="y",
                    text="Low Min:
 %.2f" % df.Low.min(),
                    ax=0, ay=40)]

fig.update_layout(
   updatemenus=[
    dict(
        type="buttons",
        direction="right",
        active=0,
        x=0.57,
        y=1.2,
        buttons=list([
            dict(label="None",
                 method="update",
                 args=[{"visible": [True, False, True, False]},
                       {"title": "Yahoo",
                        "annotations": []}]),
            dict(label="High",
                 method="update",
                 args=[{"visible": [True, True, False, False]},
                       {"title": "Yahoo High",
                        "annotations": high_annotations}]),
            dict(label="Low",
                 method="update",
                 args=[{"visible": [False, False, True, True]},
                       {"title": "Yahoo Low",
                        "annotations": low_annotations}]),
            dict(label="Both",
                 method="update",
                 args=[{"visible": [True, True, True, True]},
                       {"title": "Yahoo",
                        "annotations": high_annotations + low_annotations}]),
        ]),
    )
])

# Set title
fig.update_layout(
    title_text="Yahoo",
    xaxis_domain=[0.05, 1.0]
)

fig.show()

Body:
Changing the xy-Axis Titles with Dropdown Menu Here are the same questions as you and the answers.

        buttons=list([
        dict(label="None",
             method="update",
             args=[{"visible": [True, False, True, False]},
                   {"title": "Yahoo",
                    "xaxis": {"title": "Date"},
                    "yaxis": {"title": "High Price - Dollars"},
                    "annotations": []}]),


来源: stackexchange

问:
How to avoid writing same code over again in UIViewController in Swift?
I have the following piece of code that I write in every UIViewController:

```<code>var navBar = self.navigationController?.navigationBar
    navBar?.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
</code>```

I don't want to write these in every UIViewController that I create. I am lazy and I don't want to repeat myself. I can't add it in extension. So what can I do to not have to write this piece of code when I create UIViewController?

答:
You can use the default implementation protocol in this case.

Create default implementation protocol:

```<code>import Foundation
import UIKit

protocol TitleSetupable: AnyObject {
    func setupTitle()
}

extension TitleSetupable where Self: UIViewController {
    func setupTitle() {
        var navBar = self.navigationController?.navigationBar
        navBar?.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
    }
}
</code>```

Use in your ViewController:

```<code>class YourViewController: UIViewController, TitleSetupable {
    override func viewDidLoad() {
        super.viewDidLoad()
        setupTitle()
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following piece of code that I write in every UIViewController:

var navBar = self.navigationController?.navigationBar
    navBar?.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]

I don't want to write these in every UIViewController that I create. I am lazy and I don't want to repeat myself. I can't add it in extension. So what can I do to not have to write this piece of code when I create UIViewController?

Body:
You can use the default implementation protocol in this case.

Create default implementation protocol:

import Foundation
import UIKit

protocol TitleSetupable: AnyObject {
    func setupTitle()
}

extension TitleSetupable where Self: UIViewController {
    func setupTitle() {
        var navBar = self.navigationController?.navigationBar
        navBar?.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
    }
}

Use in your ViewController:

class YourViewController: UIViewController, TitleSetupable {
    override func viewDidLoad() {
        super.viewDidLoad()
        setupTitle()
    }
}


问:
Swiftui - only show a percentage of a view
I have a RoundedRectangle, and my objective is to lay another RoundedRectangle over it such that the overlay shows a "percentage complete". I can't seem to find the proper incantation to do so, though.

I think that ideally, the overlay should somehow only show a percentage of itself. Resizing itself to match the percentage skews the shape of the overlay.

```<code>import PlaygroundSupport

struct ContentView: View {

    @State private var value: Double = 0

    var body: some View {
        GeometryReader { geom in
            VStack {
                Slider(value: self.$value, in: 0...1, step: 0.01)

                ZStack {
                    ZStack(alignment: .leading) {

                        // The main rectangle
                        RoundedRectangle(cornerRadius: 10)
                            .fill(Color.blue)
                            .frame(width: geom.size.width,
                                   height: 200)

                        // The progress indicator...
                        RoundedRectangle(cornerRadius: 10)
                            .fill(Color.red)
                            .opacity(0.5)
                            .frame(width: CGFloat(self.value) * geom.size.width,
                                   height: 200)
                    }

                    Text("\(Int(self.value * 100)) %")
                }
            }
        }
        .padding()
    }
}

PlaygroundPage.current.setLiveView(ContentView())
</code>```

In the above playground, if you look at 1, 2, or even 3 %, you can see that the red overlay is out of the blue background rectangle bounds in the upper and lower left. See image below.

I feel like this is not the proper solution, but I also couldn't find the right mix of things (trying scaleEffect, a bunch of offset and position math) to really nail it.

To me, like I said above, it feels like the overlay should be able to say "only make my left-most 40% visible" when the value is 0.4.

That was long-winded, I apologize for that. If you've read this far, and have any advice to impart, I'd be incredibly appreciative.

Thanks!

答:
If I correctly understood your concern, here is a solution. Tested with Xcode 11.4 / iOS 13.4.

```<code>ZStack {
    ZStack(alignment: .leading) {

        // The main rectangle
        RoundedRectangle(cornerRadius: 10)
            .fill(Color.blue)
            .frame(width: geom.size.width,
                   height: 200)

        // The progress indicator...
        RoundedRectangle(cornerRadius: 10)
            .fill(Color.red)
            .opacity(0.5)
            .frame(width: CGFloat(self.value) * geom.size.width,
                   height: 200)
    }
    .clipShape(RoundedRectangle(cornerRadius: 10))    // << here !!
</code>```

Body:
I have a RoundedRectangle, and my objective is to lay another RoundedRectangle over it such that the overlay shows a "percentage complete". I can't seem to find the proper incantation to do so, though.

I think that ideally, the overlay should somehow only show a percentage of itself. Resizing itself to match the percentage skews the shape of the overlay.

import PlaygroundSupport

struct ContentView: View {

    @State private var value: Double = 0

    var body: some View {
        GeometryReader { geom in
            VStack {
                Slider(value: self.$value, in: 0...1, step: 0.01)

                ZStack {
                    ZStack(alignment: .leading) {

                        // The main rectangle
                        RoundedRectangle(cornerRadius: 10)
                            .fill(Color.blue)
                            .frame(width: geom.size.width,
                                   height: 200)

                        // The progress indicator...
                        RoundedRectangle(cornerRadius: 10)
                            .fill(Color.red)
                            .opacity(0.5)
                            .frame(width: CGFloat(self.value) * geom.size.width,
                                   height: 200)
                    }

                    Text("\(Int(self.value * 100)) %")
                }
            }
        }
        .padding()
    }
}

PlaygroundPage.current.setLiveView(ContentView())

In the above playground, if you look at 1, 2, or even 3 %, you can see that the red overlay is out of the blue background rectangle bounds in the upper and lower left. See image below.

I feel like this is not the proper solution, but I also couldn't find the right mix of things (trying scaleEffect, a bunch of offset and position math) to really nail it.

To me, like I said above, it feels like the overlay should be able to say "only make my left-most 40% visible" when the value is 0.4.

That was long-winded, I apologize for that. If you've read this far, and have any advice to impart, I'd be incredibly appreciative.

Thanks!

Body:
If I correctly understood your concern, here is a solution. Tested with Xcode 11.4 / iOS 13.4.

ZStack {
    ZStack(alignment: .leading) {

        // The main rectangle
        RoundedRectangle(cornerRadius: 10)
            .fill(Color.blue)
            .frame(width: geom.size.width,
                   height: 200)

        // The progress indicator...
        RoundedRectangle(cornerRadius: 10)
            .fill(Color.red)
            .opacity(0.5)
            .frame(width: CGFloat(self.value) * geom.size.width,
                   height: 200)
    }
    .clipShape(RoundedRectangle(cornerRadius: 10))    // << here !!


问:
how to update an object using useEffect in Reactjs and Typescript
I am very new to Reactjs + Typescript and i am trying to figure out why i am getting the error below.

React 16.9

```<code>const STEP_STATUS = {
  COMPLETED: "Completed",
  INCOMPLETE: "Incomplete",
};

const Foo = () => {
  const [state, setState] = useState({
    step: 1,
    firstName: '',
    lastName: '',
    status: STEP_STATUS["INCOMPLETE"],
  });

const nextStep = () => {
    setState({...state, step: state.step + 1});
  }

useEffect(() => {
    if (state.step + 1 !== state.step) {
      // setState(prev => {...prev, state.step = STEP_STATUS["COMPLETED"]}); // I tried this too
      setState(...state, state.status = STEP_STATUS["COMPLETED"]);
    } else {
      console.log("error");  // don't mind this line
    }
  }, [state]);
</code>```

I am trying to create a side effect using useEffect, after pressing the button nextStep(which brings the user to the next page), I want to update the status of current page to "Completed" before we get to the next page.

I might really be doing this wrong.

Any help would be very helpful.

current error

```<code>×
TypeError: state is not iterable
  53 | useEffect(() => {
  54 |   if (state.step + 1 !== state.step) {
  55 |     // setState(prev => {...prev, state.step = STEP_STATUS["COMPLETED"]});
> 56 |     setState(...state, state.status = STEP_STATUS["COMPLETED"]);
     | ^  57 |   } else {
  58 |     console.log("error");
  59 |   }
</code>```

答:
You need to put object braces around the call of setState as follow:

```<code>setState({...state, status: STEP_STATUS["COMPLETED"]})
</code>```

also it's recommended to update using the prevState values passed to setState in order to prevent clousers.

Body:
I am very new to Reactjs + Typescript and i am trying to figure out why i am getting the error below.

React 16.9

const STEP_STATUS = {
  COMPLETED: "Completed",
  INCOMPLETE: "Incomplete",
};

const Foo = () => {
  const [state, setState] = useState({
    step: 1,
    firstName: '',
    lastName: '',
    status: STEP_STATUS["INCOMPLETE"],
  });

const nextStep = () => {
    setState({...state, step: state.step + 1});
  }

useEffect(() => {
    if (state.step + 1 !== state.step) {
      // setState(prev => {...prev, state.step = STEP_STATUS["COMPLETED"]}); // I tried this too
      setState(...state, state.status = STEP_STATUS["COMPLETED"]);
    } else {
      console.log("error");  // don't mind this line
    }
  }, [state]);

I am trying to create a side effect using useEffect, after pressing the button nextStep(which brings the user to the next page), I want to update the status of current page to "Completed" before we get to the next page.

I might really be doing this wrong.

Any help would be very helpful.

current error

×
TypeError: state is not iterable
  53 | useEffect(() => {
  54 |   if (state.step + 1 !== state.step) {
  55 |     // setState(prev => {...prev, state.step = STEP_STATUS["COMPLETED"]});
> 56 |     setState(...state, state.status = STEP_STATUS["COMPLETED"]);
     | ^  57 |   } else {
  58 |     console.log("error");
  59 |   }

Body:
You need to put object braces around the call of setState as follow:

setState({...state, status: STEP_STATUS["COMPLETED"]})

also it's recommended to update using the prevState values passed to setState in order to prevent clousers.


问:
sb admin 2 bootstrap login image stuck
I have been trying for the past two hours to change the image on the login page from a dog to something else, checked all the files, both css and scss and changed the link everywhere, but still see this dog! I even tried deleting the code parts but still dog remained on its place, and no cache cleaning on browser helped either. Any ideas what could it be and what should i do?</p>

答:
This is caused by a local or server-level cache. Always ensure you are performing a hard-refresh on your browser when you want to see changes you have made to your code. This is especially true when editing CSS files.

To perform a hard refresh just use Ctrl + Shift + R

Title: sb admin 2 bootstrap login image stuck


答:
I don't think it is a good idea to use the entire state as the dependency array on the useEffect hook. This will actually lead to an inifinite loop at the updating of state within the useEffect hook will result it to be triggered over and over again.

Looking at what you are trying to achieve, I believe state.step should be on the dependency array instead. In addition, you are using the wrong syntax for referencing properties within an object. Instead of using equal (=), you should be using the colon(:) instead.

```<code>useEffect(() => {
  setState({
    ...state,
    status: STEP_STATUS["COMPLETED"]
  });
}, [state.step]);
</code>```

If you are trying to make use of the callback within setState instead, you can modify to this:

```<code>setState((prevState) => ({
  ...prevState,
  status: STEP_STATUS["COMPLETED"]
}));
</code>```

Title: how to update an object using useEffect in Reactjs and Typescript

Body:
I don't think it is a good idea to use the entire state as the dependency array on the useEffect hook. This will actually lead to an inifinite loop at the updating of state within the useEffect hook will result it to be triggered over and over again.

Looking at what you are trying to achieve, I believe state.step should be on the dependency array instead. In addition, you are using the wrong syntax for referencing properties within an object. Instead of using equal (=), you should be using the colon(:) instead.

useEffect(() => {
  setState({
    ...state,
    status: STEP_STATUS["COMPLETED"]
  });
}, [state.step]);

If you are trying to make use of the callback within setState instead, you can modify to this:

setState((prevState) => ({
  ...prevState,
  status: STEP_STATUS["COMPLETED"]
}));


问:
Prevent scrolling when mouse enters WPF ComboBox dropdown
When a ComboBox has a large number of items, its dropdown will become scrollable. When the user invokes this dropdown, and moves the mouse cursor to enter the bounds of the dropdown from the bottom, the dropdown immediately scrolls one or more items down the list (from goobering: also happens when exiting the bounds via the bottom edge).

This scrolling is not intuitive, as the list does not scroll upwards when entering the bounds from the top.

How can we disable the automatic scrolling behavior?

In Visual Studio this behavior can be observed via the member dropdown on the code editor's navigation bar (CTRL+F2).

答:
I'd same issue in my application so I've styled the Combobox's PART_Popup to solve the issue in this way:

```<code><Popup x:Name="PART_Popup"
       IsOpen="{TemplateBinding IsDropDownOpen}"
       AllowsTransparency="True"
       Focusable="False"
       PopupAnimation="Slide">

    <Grid MinWidth="{TemplateBinding ActualWidth}"
          MaxHeight="{TemplateBinding MaxDropDownHeight}">

        <Border x:Name="dropDownBorder"
                Background="White"
                BorderThickness="1"
                BorderBrush="Gray"
                Margin="0 2 0 0"/>

        <ScrollViewer SnapsToDevicePixels="True">
            <VirtualizingStackPanel IsItemsHost="True"
                                    KeyboardNavigation.DirectionalNavigation="Contained" />
        </ScrollViewer>

    </Grid>
</Popup>
</code>```

If you add Margin in ScrollViewer (eg.<ScrollViewer Margin="1" ...) it'd start scrolling down automatically.

ContentLicense: CC BY-SA 3.0

Body:
I'd same issue in my application so I've styled the Combobox's PART_Popup to solve the issue in this way:

<Popup x:Name="PART_Popup"
       IsOpen="{TemplateBinding IsDropDownOpen}"
       AllowsTransparency="True"
       Focusable="False"
       PopupAnimation="Slide">

    <Grid MinWidth="{TemplateBinding ActualWidth}"
          MaxHeight="{TemplateBinding MaxDropDownHeight}">

        <Border x:Name="dropDownBorder"
                Background="White"
                BorderThickness="1"
                BorderBrush="Gray"
                Margin="0 2 0 0"/>

        <ScrollViewer SnapsToDevicePixels="True">
            <VirtualizingStackPanel IsItemsHost="True"
                                    KeyboardNavigation.DirectionalNavigation="Contained" />
        </ScrollViewer>

    </Grid>
</Popup>

If you add Margin in ScrollViewer (eg.<ScrollViewer Margin="1" ...) it'd start scrolling down automatically.


问:
LLVM Instruction Scheduling in RISC-V
I am looking at instruction scheduling in LLVM for RISC-V backend. I understood there are two ways of scheduling (ScheduleDAGRRList & MachineScheduler). From debug logs i can RISC-V uses ScheduleDAGRRList approach.

Is MachineScheduler is better than ScheduleDAGRRList? If so, how can i enable MachineScheduler for RISC-V ?

I tried llc -enable-misched file.ll, but with no luck.

答:
The RISC-V backend added support for the Machine Scheduler (MISched) in LLVM release 10.0.

https://releases.llvm.org/10.0.0/docs/ReleaseNotes.html

The TableGen SchedMachineModel descriptions in RISCVSchedRocket64.td describe it as an in-order processor.

```<code>// Rocket machine model for scheduling and other instruction cost heuristics.
def Rocket64Model : SchedMachineModel {
  let MicroOpBufferSize = 0; // Explicitly set to zero since Rocket is in-order.
  let IssueWidth = 1;        // 1 micro-ops are dispatched per cycle.
  let LoadLatency = 3;
  let MispredictPenalty = 3;
}
</code>```

You can enable machine scheduling for rocket-rv64 with:

```<code>-O3 -mllvm -enable-misched -mllvm -enable-post-misched -mcpu=rocket-rv64
</code>```

Title: LLVM Instruction Scheduling in RISC-V

Body:
The RISC-V backend added support for the Machine Scheduler (MISched) in LLVM release 10.0.

https://releases.llvm.org/10.0.0/docs/ReleaseNotes.html

The TableGen SchedMachineModel descriptions in RISCVSchedRocket64.td describe it as an in-order processor.

// Rocket machine model for scheduling and other instruction cost heuristics.
def Rocket64Model : SchedMachineModel {
  let MicroOpBufferSize = 0; // Explicitly set to zero since Rocket is in-order.
  let IssueWidth = 1;        // 1 micro-ops are dispatched per cycle.
  let LoadLatency = 3;
  let MispredictPenalty = 3;
}

You can enable machine scheduling for rocket-rv64 with:

-O3 -mllvm -enable-misched -mllvm -enable-post-misched -mcpu=rocket-rv64


问:
Encapsulation not initialized properly?
I was just playing around to know more about encapsulation and found out that we cannot print out values that has been encapsulated, we have to define a seperate method that prints the value out, but here in my code i tried to print out an attribute of my class and it worked, so is there a mistake in my encapsulation?

code :

```<code>class Time:
    timethytom = 'Best'

    def __init__(self, hours, minutes):
        self.__hours = hours
        self.__minutes = minutes

    def setTime(self,hour,minute):
        self.__hours = hour
        self.__minutes = minute

    def getTime(self):
        print(f'Time is {self.__hours}hr {self.__minutes}min')

    def addTime(self, hour1, hour2, minute1, minute2):
        print(f'{hour1+hour2} hours and {minute1+minute2} minutes')

time1 = Time(10, 20)

time1.setTime(20,5)
time1.hours = 55
time1.getTime()

print(time1.hours)

</code>```

Thanks in advance :)

答:
In Python, you can create a public variables in the class from out of the class, something like this:

```<code>class xyz:
  pass

x = xyz()
x.y=10
print(x.y) #This will print 10
</code>```

When you wrote this line time1.hours = 55, actually you have created a variable named hours in the object time1 which is not the same as the variable __hours defined in the class.

Title: Encapsulation not initialized properly?

Body:
I was just playing around to know more about encapsulation and found out that we cannot print out values that has been encapsulated, we have to define a seperate method that prints the value out, but here in my code i tried to print out an attribute of my class and it worked, so is there a mistake in my encapsulation?

code :

class Time:
    timethytom = 'Best'

    def __init__(self, hours, minutes):
        self.__hours = hours
        self.__minutes = minutes

    def setTime(self,hour,minute):
        self.__hours = hour
        self.__minutes = minute

    def getTime(self):
        print(f'Time is {self.__hours}hr {self.__minutes}min')

    def addTime(self, hour1, hour2, minute1, minute2):
        print(f'{hour1+hour2} hours and {minute1+minute2} minutes')

time1 = Time(10, 20)

time1.setTime(20,5)
time1.hours = 55
time1.getTime()

print(time1.hours)

Thanks in advance :)

Body:
In Python, you can create a public variables in the class from out of the class, something like this:

class xyz:
  pass

x = xyz()
x.y=10
print(x.y) #This will print 10

When you wrote this line time1.hours = 55, actually you have created a variable named hours in the object time1 which is not the same as the variable __hours defined in the class.


问:
Passing variables from a shell script to a GNU screen
I have a linux shell script that looks like this:

```<code>tron="/home/duke/aa/bin/armagetronad-dedicated"
var="/home/duke/aa/servers/$1/var/"
log="${var}logs/all_console_logs.log"
userconfigdir="${var}customize/config/"
parser="${var}customize/parser-rpg.php"
ladderlog="${var}ladderlog.txt"
cmds="${var}cmd.txt"

screen -S $1 -X kill
screen -d -m -S $1
screen -S $1 -X stuff 'tail -n0 -f -s 0.01 $cmds | (while true; do $tron --userconfigdir $userconfigdir --vardir $var; done) | tee -a $log
'
</code>```

However, when passing variables to the screen session using stuff, it's actually sending "$cmds" instead of the value inside $cmds. Is it possible to bring the variables into the screen session too?

答:
Single quotes suppresses variable substitution.  Will this work instead for the last line?</p>

```<code>screen -S $1 -X stuff "tail -n0 -f -s 0.01 $cmds | (while true; do $tron --userconfigdir $userconfigdir --vardir $var; done) | tee -a $log"
</code>```

Body:
I have a linux shell script that looks like this:

tron="/home/duke/aa/bin/armagetronad-dedicated"
var="/home/duke/aa/servers/$1/var/"
log="${var}logs/all_console_logs.log"
userconfigdir="${var}customize/config/"
parser="${var}customize/parser-rpg.php"
ladderlog="${var}ladderlog.txt"
cmds="${var}cmd.txt"

screen -S $1 -X kill
screen -d -m -S $1
screen -S $1 -X stuff 'tail -n0 -f -s 0.01 $cmds | (while true; do $tron --userconfigdir $userconfigdir --vardir $var; done) | tee -a $log
'

However, when passing variables to the screen session using stuff, it's actually sending "$cmds" instead of the value inside $cmds. Is it possible to bring the variables into the screen session too?

Body:
Single quotes suppresses variable substitution.  Will this work instead for the last line?

screen -S $1 -X stuff "tail -n0 -f -s 0.01 $cmds | (while true; do $tron --userconfigdir $userconfigdir --vardir $var; done) | tee -a $log"


问:
Is it possible to update the assigned Azure DSC configuration to a VM via ARM Template?
I need to change the Azure DSC configuration that has been previously assigned to a VM.

I'm trying to do this programatically because it's part of an automation I'm developing and because of this, I'm using ARM Templates.

However, redeploying the same VM DSC extension by ARM Template results in an error stating a VM can't have two of the same extensions, which sounds logical.

What I want to know if it's possible to, by ARM Template, "update" or "modify" the current extension with just one setting changed: The configuration name.

Is this possible?

答: Sure - you can update the existing VM extension by providing new configuration in your ARM template. As you have found out, you cannot use a different name for the extension - that would result in two VM extensions of the same type on the VM. Instead, you need to reuse the same name of the existing VM extension when performing the update.</p>


问:
Active font-weight with JS + CSS
I need to know how to activate font-weight on the page (I'm using JavaScript).

Example: If I'm on the teachers page, the  Teachers  font-weight should be bold like shown in image below.

<!DOCTYPE html>

       {% block head %}
           <title>Private Classes</title>
       {% endblock %}

       <link rel="stylesheet" href="/styles.css">

               Teachers
               Students

       {% block content %}
       {% endblock %}

```

答:
```<code>const currentPage = location.pathname
const menuItems = document.querySelectorAll("header .links a")

for (item of menuItems) {
    if (currentPage.includes(item.getAttribute("href"))) {
        item.classList.add("active")
    }
}
</code>```

Title: Active font-weight with JS + CSS


问:
Struggling to install jenssegers/mongodb 3.6 for Laravel 5.7
I'm trying to install the package for working with mongodb, but getting these problems with packages:

```<code>pavel@pavel:~/Project/$ ../../composer.phar require jenssegers/mongodb
Using version ^3.6 for jenssegers/mongodb
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - amirhb/laravel-mongodb-log 1.2 requires jenssegers/mongodb 3.4.5 -> satisfiable by jenssegers/mongodb[v3.4.5] but these conflict with your requirements or minimum-stability.
    - amirhb/laravel-mongodb-log 1.2 requires jenssegers/mongodb 3.4.5 -> satisfiable by jenssegers/mongodb[v3.4.5] but these conflict with your requirements or minimum-stability.
    - amirhb/laravel-mongodb-log 1.2 requires jenssegers/mongodb 3.4.5 -> satisfiable by jenssegers/mongodb[v3.4.5] but these conflict with your requirements or minimum-stability.
    - Installation request for amirhb/laravel-mongodb-log (locked at 1.2, required as ^1.1) -> satisfiable by amirhb/laravel-mongodb-log[1.2].

Installation failed, reverting ./composer.json to its original content.
</code>```

How to eliminate them?

答: It means that you have installed a package named amirhb/laravel-mongodb-log v1.2 which requires jenssegers/mongodb 3.4.5 but you are trying to install jenssegers/mongodb 3.6 which makes them to conflict in version what you can do is either install a higher version of amirhb/laravel-mongodb-log or install jenssegers/mongodb 3.4.5 and NOT the 3.6 one

Body:
I'm trying to install the package for working with mongodb, but getting these problems with packages:

pavel@pavel:~/Project/$ ../../composer.phar require jenssegers/mongodb
Using version ^3.6 for jenssegers/mongodb
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - amirhb/laravel-mongodb-log 1.2 requires jenssegers/mongodb 3.4.5 -> satisfiable by jenssegers/mongodb[v3.4.5] but these conflict with your requirements or minimum-stability.
    - amirhb/laravel-mongodb-log 1.2 requires jenssegers/mongodb 3.4.5 -> satisfiable by jenssegers/mongodb[v3.4.5] but these conflict with your requirements or minimum-stability.
    - amirhb/laravel-mongodb-log 1.2 requires jenssegers/mongodb 3.4.5 -> satisfiable by jenssegers/mongodb[v3.4.5] but these conflict with your requirements or minimum-stability.
    - Installation request for amirhb/laravel-mongodb-log (locked at 1.2, required as ^1.1) -> satisfiable by amirhb/laravel-mongodb-log[1.2].

Installation failed, reverting ./composer.json to its original content.

How to eliminate them?


问:
How to tell the difference between the active and passive buzzer in Freenove arduino kit
I bought a Freenove ultimate starter kit, and it comes with two buzzers. It says that one is active and the other one is passive, and the active buzzer had a sticky label on it. The only differences are that on one the pins are slightly higher and lower, and one has a green bottom and the other one does not, where you can see the curcuit board through. im new to stack overflow, so any answers would be appreciated.</p>

答: According to the tutorial documentation, the active buzzer has a "waterproof coating" on the pin side, so the one with the exposed solder points is the passive buzzer.</p>


问:
Use Enums across functions and classes in a PowerShell Module
I'm creating a PowerShell module that I would like to use enums across several functions (that will be exported, if that matters) and classes in the module.  The only way I can see to do this is to put all of the code in a single file.  That's not an easy maintenance story, however.  I want a module file structure similar to the following:

As you can see in the code, Class1 has the Enum1 property flagged as "Unable to find type [Enum1]."

Deploy-MyResource:

function Deploy-MyResource {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true)]
        [Enum1] $EnumParam,

        [Parameter(Mandatory=$true)]
        [Class1] $ClassParam
    )

    $class2 = [Class2]::new()

    if($class2.Prop1 -eq $ClassParam.Prop1) {
        Write-Output "Matches"
    }
    else {
        Write-Output "No match."
    }
}
```

<p>Class1:</p>

<pre class="lang-bsh prettyprint-override"><code>Class Class1 {
    [string] $Prop1
    [int] $Prop2
    [Enum1] $EnumProp

    DoSomething() {
        Write-Output "Did something using $($this.Prop1), $($this.Prop2), & $($this.EnumProp)"
    }
}
</code>```

Enum1:

enum Enum1 {
    ValueOne
    ValueTwo
}
```

<p>Here are my PSD1 and PSM1:</p>

<p><img src="https://i.stack.imgur.com/jic7k.png" alt="enter image description here"></p>

<p>PSD1:</p>

<pre class="lang-bsh prettyprint-override"><code>
@{

    # Script module or binary module file associated with this manifest.
    RootModule         = 'Module1.psm1'

    # Version number of this module.
    # NOTE keep version in sync with Module1.nuspec
    ModuleVersion      = '2.7.2'

    # ID used to uniquely identify this module
    GUID               = '24EC97AC-42B1-4719-9EF2-F49C14F8D148'

    # Author of this module
    Author             = 'Me'

    # Company or vendor of this module
    CompanyName        = 'Me'

    # Description of the functionality provided by this module
    Description        = 'Example module for Stack post'

    # Minimum version of the Windows PowerShell engine required by this module
    PowerShellVersion  = '5.1'

    # Modules that must be imported into the global environment prior to importing this module
    RequiredModules    = @()

    # Assemblies that must be loaded prior to importing this module
    RequiredAssemblies = @('System.Web')

    # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
    FunctionsToExport  = @('Deploy-MyResource')

    # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
    CmdletsToExport    = @()

    # Variables to export from this module
    VariablesToExport  = @()

    # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
    AliasesToExport    = @()

    # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
    PrivateData        = @{

        PSData = @{
            #region Unused PSData

            # Tags applied to this module. These help with module discovery in online galleries.
            # Tags = @()

            # A URL to the license for this module.
            # LicenseUri = ''

            # A URL to the main website for this project.
            # ProjectUri = ''

            # A URL to an icon representing this module.
            # IconUri = ''

            # ReleaseNotes of this module
            # ReleaseNotes = ''

            #endregion Unused PSData
        } # End of PSData hashtable

    } # End of PrivateData hashtable

    #region Unused Props

    # Copyright statement for this module
    # Copyright = '(c) 2019 appliedis.com. All rights reserved.'

    # Supported PSEditions
    # CompatiblePSEditions = @()

    # Name of the Windows PowerShell host required by this module
    # PowerShellHostName = ''

    # Minimum version of the Windows PowerShell host required by this module
    # PowerShellHostVersion = ''

    # Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
    # DotNetFrameworkVersion = ''

    # Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
    # CLRVersion = ''

    # Processor architecture (None, X86, Amd64) required by this module
    # ProcessorArchitecture = ''

    # Script files (.ps1) that are run in the caller's environment prior to importing this module.
    # ScriptsToProcess = @()

    # Type files (.ps1xml) to be loaded when importing this module
    # TypesToProcess = @()

    # Format files (.ps1xml) to be loaded when importing this module
    # FormatsToProcess = 'Module1.Format.ps1xml'

    # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
    # NestedModules = @()

    # DSC resources to export from this module
    # DscResourcesToExport = @()

    # List of all modules packaged with this module
    # ModuleList = @()

    # List of all files packaged with this module
    # FileList = @()

    # HelpInfo URI of this module
    # HelpInfoURI = ''

    # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
    # DefaultCommandPrefix = ''

    #endregion Unused Props
}
</code>```

PSM1:

# Get public and private function definition files.
$Private = @( Get-ChildItem -Path $PSScriptRoot\Function\private\*.ps1 -Recurse -ErrorAction SilentlyContinue )
$Public  = @( Get-ChildItem -Path $PSScriptRoot\Functions\public\*.ps1 -Recurse -ErrorAction SilentlyContinue )

# Dot source the files
Foreach($import in @($Private + $Public))
{
    Try
    {
        Set-StrictMode -Version Latest
        . $import.fullname
    }
    Catch
    {
        Write-Error -Message "Failed to import function $($import.fullname): $_"
    }
}

# Export the public functions
Foreach($import in $Public)
{
    Try
    {
        Export-ModuleMember -Function $import.BaseName
    }
    Catch
    {
        Write-Error -Message "Failed to import function $($import.fullname): $_"
    }
}

```

<p>This is what I get when I try to use the module:</p>

<p><img src="https://i.stack.imgur.com/Pg3JB.png" alt="enter image description here"></p>

<p>Use-Module (outside of the Module1 folder):</p>

<pre class="lang-bsh prettyprint-override"><code>Using module .\Module1

$class1 = [Class1]::new()

Deploy-MyResource -EnumParam ValueOne -ClassParam $class1
</code>```

What am I missing?  All of the examples about modules and classes I'm finding are all in a single file.

I've created a repo on GitHub with the code here: https://github.com/SPSamL/PowerShell-Module-With-Classes

答:
Whichever classes you would like to use across multiple functions or modules, put inside a single module file.
Afterward, you can utilize the using command: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_using?view=powershell-7 to import the namespace.

To load classes from a PowerShell module:

using module <module-name>

Body:
I'm creating a PowerShell module that I would like to use enums across several functions (that will be exported, if that matters) and classes in the module.  The only way I can see to do this is to put all of the code in a single file.  That's not an easy maintenance story, however.  I want a module file structure similar to the following:

As you can see in the code, Class1 has the Enum1 property flagged as "Unable to find type [Enum1]."

Deploy-MyResource:

function Deploy-MyResource {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true)]
        [Enum1] $EnumParam,

        [Parameter(Mandatory=$true)]
        [Class1] $ClassParam
    )

    $class2 = [Class2]::new()

    if($class2.Prop1 -eq $ClassParam.Prop1) {
        Write-Output "Matches"
    }
    else {
        Write-Output "No match."
    }
}

Class1:

Class Class1 {
    [string] $Prop1
    [int] $Prop2
    [Enum1] $EnumProp

    DoSomething() {
        Write-Output "Did something using $($this.Prop1), $($this.Prop2), & $($this.EnumProp)"
    }
}

Enum1:

enum Enum1 {
    ValueOne
    ValueTwo
}

Here are my PSD1 and PSM1:

PSD1:

@{

    # Script module or binary module file associated with this manifest.
    RootModule         = 'Module1.psm1'

    # Version number of this module.
    # NOTE keep version in sync with Module1.nuspec
    ModuleVersion      = '2.7.2'

    # ID used to uniquely identify this module
    GUID               = '24EC97AC-42B1-4719-9EF2-F49C14F8D148'

    # Author of this module
    Author             = 'Me'

    # Company or vendor of this module
    CompanyName        = 'Me'

    # Description of the functionality provided by this module
    Description        = 'Example module for Stack post'

    # Minimum version of the Windows PowerShell engine required by this module
    PowerShellVersion  = '5.1'

    # Modules that must be imported into the global environment prior to importing this module
    RequiredModules    = @()

    # Assemblies that must be loaded prior to importing this module
    RequiredAssemblies = @('System.Web')

    # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
    FunctionsToExport  = @('Deploy-MyResource')

    # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
    CmdletsToExport    = @()

    # Variables to export from this module
    VariablesToExport  = @()

    # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
    AliasesToExport    = @()

    # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
    PrivateData        = @{

        PSData = @{
            #region Unused PSData

            # Tags applied to this module. These help with module discovery in online galleries.
            # Tags = @()

            # A URL to the license for this module.
            # LicenseUri = ''

            # A URL to the main website for this project.
            # ProjectUri = ''

            # A URL to an icon representing this module.
            # IconUri = ''

            # ReleaseNotes of this module
            # ReleaseNotes = ''

            #endregion Unused PSData
        } # End of PSData hashtable

    } # End of PrivateData hashtable

    #region Unused Props

    # Copyright statement for this module
    # Copyright = '(c) 2019 appliedis.com. All rights reserved.'

    # Supported PSEditions
    # CompatiblePSEditions = @()

    # Name of the Windows PowerShell host required by this module
    # PowerShellHostName = ''

    # Minimum version of the Windows PowerShell host required by this module
    # PowerShellHostVersion = ''

    # Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
    # DotNetFrameworkVersion = ''

    # Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
    # CLRVersion = ''

    # Processor architecture (None, X86, Amd64) required by this module
    # ProcessorArchitecture = ''

    # Script files (.ps1) that are run in the caller's environment prior to importing this module.
    # ScriptsToProcess = @()

    # Type files (.ps1xml) to be loaded when importing this module
    # TypesToProcess = @()

    # Format files (.ps1xml) to be loaded when importing this module
    # FormatsToProcess = 'Module1.Format.ps1xml'

    # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
    # NestedModules = @()

    # DSC resources to export from this module
    # DscResourcesToExport = @()

    # List of all modules packaged with this module
    # ModuleList = @()

    # List of all files packaged with this module
    # FileList = @()

    # HelpInfo URI of this module
    # HelpInfoURI = ''

    # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
    # DefaultCommandPrefix = ''

    #endregion Unused Props
}

PSM1:

# Get public and private function definition files.
$Private = @( Get-ChildItem -Path $PSScriptRoot\Function\private\*.ps1 -Recurse -ErrorAction SilentlyContinue )
$Public  = @( Get-ChildItem -Path $PSScriptRoot\Functions\public\*.ps1 -Recurse -ErrorAction SilentlyContinue )

# Dot source the files
Foreach($import in @($Private + $Public))
{
    Try
    {
        Set-StrictMode -Version Latest
        . $import.fullname
    }
    Catch
    {
        Write-Error -Message "Failed to import function $($import.fullname): $_"
    }
}

# Export the public functions
Foreach($import in $Public)
{
    Try
    {
        Export-ModuleMember -Function $import.BaseName
    }
    Catch
    {
        Write-Error -Message "Failed to import function $($import.fullname): $_"
    }
}

This is what I get when I try to use the module:

Use-Module (outside of the Module1 folder):

Using module .\Module1

$class1 = [Class1]::new()

Deploy-MyResource -EnumParam ValueOne -ClassParam $class1

What am I missing?  All of the examples about modules and classes I'm finding are all in a single file.

I've created a repo on GitHub with the code here: https://github.com/SPSamL/PowerShell-Module-With-Classes


问:
How to add a column to array?
I have an array:

Then I used talib to calculate the EMA by x=talib.EMA(ar[:,[2][0]].astype(np.double), 2), I am not sure if this is the right way though, because I need [0] after specify all rows of column 2, then I get:

How can I add it to the last column of orginal array so it looks like this?

Thanks

答:
Use: np.concatenate((arr, x[:, None]), axis = 1)

Check the doc of numpy.concatenate.

Note that [:, None] is used to create an empty new axis for the array x.

Title: How to add a column to array?


问:
ifelse condition: is in top n
Usually when i need a subset on geom_label() i use ifelse() and i specify a number as below:

library(tidyverse)

data = starwars %>% filter(mass < 500)

data %>%
  ggplot(aes(x = mass, y = height, label = ifelse(birth_year > 100, name, NA))) +
  geom_point() +
  geom_label()
#> Warning: Removed 54 rows containing missing values (geom_label).
```

Created on 2020-05-31 by the reprex package (v0.3.0)

But with the dataset i'm working on, i need a dynamic solution, something like ifelse("birth_year is in top n", name, NA).

Thoughts?

答:
Something like this? To get top 4 values.</p>

```<code>library(ggplot2)

data %>%
  ggplot(aes(x = mass, y = height, label = ifelse(birth_year >= sort(birth_year, decreasing = TRUE)[4], name, NA))) +
  geom_point() +
  geom_label()
</code>```

Title: ifelse condition: is in top n

Body:
Usually when i need a subset on geom_label() i use ifelse() and i specify a number as below:

library(tidyverse)

data = starwars %>% filter(mass < 500)

data %>%
  ggplot(aes(x = mass, y = height, label = ifelse(birth_year > 100, name, NA))) +
  geom_point() +
  geom_label()
#> Warning: Removed 54 rows containing missing values (geom_label).

Created on 2020-05-31 by the reprex package (v0.3.0)

But with the dataset i'm working on, i need a dynamic solution, something like ifelse("birth_year is in top n", name, NA).

Thoughts?

Body:
Something like this? To get top 4 values.

library(ggplot2)

data %>%
  ggplot(aes(x = mass, y = height, label = ifelse(birth_year >= sort(birth_year, decreasing = TRUE)[4], name, NA))) +
  geom_point() +
  geom_label()


问:
Using specific dataframe cell values to create a consolidated new dataframe
So this is an assignment from my python class. We have a dataframe that contains information about a machine. Every minute the machine stands still (as in: no product is being produced for whatever reason) it creates a new row in a dataframe containing the reason.

This is what the first standstill looks like in the DF (text looks weird because I had to translate it from german):

We see that Reason 1 for the standstill started at 2020-03-02 at 14:04 and was rectified at 14:07.

The assignment now is to create a new dataframe to consolidate this information, so that it would look somewhat like this:

I had the idea to use .shift() in order to check for the beginning and the end of a new Standstillreason. The column "SAP?" (Same as previous?) checks wether the Standstillreason in the current row is the same as in the previous. Same goes for "SAN?" (Same as next?) regarding the next row.

```<code>df["SAP?"] = df.Standstillreason.eq(df.Standstillreason.shift())
df["SAN?"] = df.Standstillreason.eq(df.Standstillreason.shift(periods=-1))
</code>```

Everytime SAP = False, it means that the row contains the start of a new Standstillreason.
If SAN = False, the row contains the end of the current reason.

What I'm trying to do now is to extract the needed information to put it in the consolidated df. I thought of somewhat like this:

```<code>for index, row in df.iterrows():
    if row["SAP?"] == False:
        df_consolidated["Standstillreason"] = row["Standstillreason"]
</code>```

But so far this hasn't worked. I'm not even sure wether I'm having the right approach to the problem.

答:
If the reasons are all different, then simply

```<code>df.groupby("Standstillreason").agg({"Date":["first","last"], "Time":["first", "last"]})
</code>```

Should work.

If not, it is a bit more complicated. You want to create too dataframes, one with SAP equal to true, and the other with SAN true, and get the first from the second df, and the last from the first, then concat together.

Body:
So this is an assignment from my python class. We have a dataframe that contains information about a machine. Every minute the machine stands still (as in: no product is being produced for whatever reason) it creates a new row in a dataframe containing the reason.

This is what the first standstill looks like in the DF (text looks weird because I had to translate it from german):

We see that Reason 1 for the standstill started at 2020-03-02 at 14:04 and was rectified at 14:07.

The assignment now is to create a new dataframe to consolidate this information, so that it would look somewhat like this:

I had the idea to use .shift() in order to check for the beginning and the end of a new Standstillreason. The column "SAP?" (Same as previous?) checks wether the Standstillreason in the current row is the same as in the previous. Same goes for "SAN?" (Same as next?) regarding the next row.

df["SAP?"] = df.Standstillreason.eq(df.Standstillreason.shift())
df["SAN?"] = df.Standstillreason.eq(df.Standstillreason.shift(periods=-1))

Everytime SAP = False, it means that the row contains the start of a new Standstillreason.
If SAN = False, the row contains the end of the current reason.

What I'm trying to do now is to extract the needed information to put it in the consolidated df. I thought of somewhat like this:

for index, row in df.iterrows():
    if row["SAP?"] == False:
        df_consolidated["Standstillreason"] = row["Standstillreason"]

But so far this hasn't worked. I'm not even sure wether I'm having the right approach to the problem.

Body:
If the reasons are all different, then simply

df.groupby("Standstillreason").agg({"Date":["first","last"], "Time":["first", "last"]})

Should work.

If not, it is a bit more complicated. You want to create too dataframes, one with SAP equal to true, and the other with SAN true, and get the first from the second df, and the last from the first, then concat together.


问:
If data has linear frelationship, won't linear regression lead to zero in-sample error
I am using the Learning from Data textbook by Yaser Abu-Mostafa et al.  I am curious about the following statement in the linear regression chapter and would like to verify that my understanding is correct.

After talking about the "pseudo-inverse" way to get the "best weights" (best for minimizing squared error), i.e w_lin = (X^T X)^-1 X^T y

The statement is "The linear regression weight vector is an attempt to map the inputs X to the outputs y.  However, w_lin does not produce y exactly, but produces an estimate X w_lin which differs from y due to in sample error.

If the data is on a hyper-plane, won't X w_lin exactly match y (i.e in-sample error = 0)?   I.e above statement is only talking about data that is not linearly separable.

答:
Here, 'w_lin' is the not the same for all data points (all pairs of (X,y)).

The linear regression model finds the best possible weight vector (or best possible 'w_lin') considering all data points such that X*w_lin  gives a result very close to 'y' for any data point.

Hence the error will not be zero unless all data points line on a straight line.


问:
Query array of dictionary in mongodb
I have a collection  db.orders in mongodb, this is a example:

```<code>{
        "_id" : ObjectId("5ed269e0f18b5c0d33150ce1"),
        "user" : ObjectId("5ed16ace5b16a6100c1ae744"),
        "cart" : {
                "items" : [
                        {
                                "item" : {
                                        "_id" : "5ed16847fb395528f07f2d19",
                                        "tipo" : "anillo",
                                        "imagePath" : "../images/anillos/anillo1.png",
                                        "title" : "Anillo Geo",
                                        "description" : "Anillo en bronce con baño en oro de 24k",
                                        "price" : 25,
                                        "qty" : 1
                                }
                        },
                        {
                                "item" : {
                                        "_id" : "5ed16847fb395528f07f2d2e",
                                        "tipo" : "collar",
                                        "imagePath" : "../images/collares/collar10.png",
                                        "title" : "Cadenita Pendulo cuarzos naturales",
                                        "description" : "Cadenita en bronce con baño en oro de 18k.",
                                        "price" : 20,
                                        "qty" : 1
                                }
                        },
                        {
                                "item" : {
                                        "_id" : "5ed16847fb395528f07f2d26",
                                        "tipo" : "anillo",
                                        "imagePath" : "../images/anillos/anillo14.png",
                                        "title" : "Anillo mandala de cristales",
                                        "description" : "Anillo en bronce con baño en oro de 24k, incluye estuche de madera ",
                                        "price" : 20,
                                        "qty" : 1
                                }
                        }
                ],
                "totalQty" : 3,
                "totalPrice" : 65
        },
        "address" : "carrera 9/ Madrid",
        "city" :  "Madrid",
        "name" : "Marcela R",
        "paymentId" : "ch_1GoIGGByvh8EqLzfNGV02e3e",
        "oderdate" : ISODate("2020-05-30T14:12:48.624Z"),
        "__v" : 0
}
</code>```

I need to know how many title: "Anillo geo" and generally how many cart.items.item.title have been sold. I try different methods but I end up with something like this:

```<code>{
        "_id" : ObjectId("5ed27fee825300b7d182355d"),
        "cart" : {
                "items" : [
                        {
                                "title" : "Anillo Geo",
                                "price" : 25,
                                "qty" : 1,
                                "tipo" : "anillo"
                        },
                        {
                                "title" : "Cadenita Pendulo cuarzos naturales",
                                "price" : 29,
                                "qty" : 1,
                                "tipo" : "collar"
                        },
                        {
                                "title" : "Anillo mandala de cristales",
                                "price" : 29,
                                "qty" : 1,
                                "tipo" : "anillo"
                        }
                ]
        }
}
</code>```

But I need a query that give me something like:

```<code>{"_id" : Anillo Geo, count: 5}
{"_id" : Cadenita Pendulo cuarzos naturales, count: 8}...
</code>```

Anyone have any idea of how to do this query?
Kind regards!!

答:
Basically you need to unwind cart.items array & group on _id + title to count no.of titles got repeated for an _id document.

```<code>db.collection.aggregate([
  {
    $unwind: "$cart.items"
  },
  {
    $group: {
      _id: { _id: "$_id", title: "$cart.items.item.title" },
      count: { $sum: 1 }
    }
  },
  /** transform fields the way you want in output */
  {
    $project: { _id: "$_id._id", title: "$_id.title", count: 1 }
  }
])
</code>```

Test : mongoplayground

Note :

If possible try to use $match as first stage to do this operation on a single doc i.e; for a single user or at-least lesser docs rather than on an entire collection.

Title: Query array of dictionary in mongodb

Body:
I have a collection  db.orders in mongodb, this is a example:

{
        "_id" : ObjectId("5ed269e0f18b5c0d33150ce1"),
        "user" : ObjectId("5ed16ace5b16a6100c1ae744"),
        "cart" : {
                "items" : [
                        {
                                "item" : {
                                        "_id" : "5ed16847fb395528f07f2d19",
                                        "tipo" : "anillo",
                                        "imagePath" : "../images/anillos/anillo1.png",
                                        "title" : "Anillo Geo",
                                        "description" : "Anillo en bronce con baño en oro de 24k",
                                        "price" : 25,
                                        "qty" : 1
                                }
                        },
                        {
                                "item" : {
                                        "_id" : "5ed16847fb395528f07f2d2e",
                                        "tipo" : "collar",
                                        "imagePath" : "../images/collares/collar10.png",
                                        "title" : "Cadenita Pendulo cuarzos naturales",
                                        "description" : "Cadenita en bronce con baño en oro de 18k.",
                                        "price" : 20,
                                        "qty" : 1
                                }
                        },
                        {
                                "item" : {
                                        "_id" : "5ed16847fb395528f07f2d26",
                                        "tipo" : "anillo",
                                        "imagePath" : "../images/anillos/anillo14.png",
                                        "title" : "Anillo mandala de cristales",
                                        "description" : "Anillo en bronce con baño en oro de 24k, incluye estuche de madera ",
                                        "price" : 20,
                                        "qty" : 1
                                }
                        }
                ],
                "totalQty" : 3,
                "totalPrice" : 65
        },
        "address" : "carrera 9/ Madrid",
        "city" :  "Madrid",
        "name" : "Marcela R",
        "paymentId" : "ch_1GoIGGByvh8EqLzfNGV02e3e",
        "oderdate" : ISODate("2020-05-30T14:12:48.624Z"),
        "__v" : 0
}

I need to know how many title: "Anillo geo" and generally how many cart.items.item.title have been sold. I try different methods but I end up with something like this:

{
        "_id" : ObjectId("5ed27fee825300b7d182355d"),
        "cart" : {
                "items" : [
                        {
                                "title" : "Anillo Geo",
                                "price" : 25,
                                "qty" : 1,
                                "tipo" : "anillo"
                        },
                        {
                                "title" : "Cadenita Pendulo cuarzos naturales",
                                "price" : 29,
                                "qty" : 1,
                                "tipo" : "collar"
                        },
                        {
                                "title" : "Anillo mandala de cristales",
                                "price" : 29,
                                "qty" : 1,
                                "tipo" : "anillo"
                        }
                ]
        }
}

But I need a query that give me something like:

{"_id" : Anillo Geo, count: 5}
{"_id" : Cadenita Pendulo cuarzos naturales, count: 8}...

Anyone have any idea of how to do this query?
Kind regards!!

Body:
Basically you need to unwind cart.items array & group on _id + title to count no.of titles got repeated for an _id document.

db.collection.aggregate([
  {
    $unwind: "$cart.items"
  },
  {
    $group: {
      _id: { _id: "$_id", title: "$cart.items.item.title" },
      count: { $sum: 1 }
    }
  },
  /** transform fields the way you want in output */
  {
    $project: { _id: "$_id._id", title: "$_id.title", count: 1 }
  }
])

Test : mongoplayground

Note :

If possible try to use $match as first stage to do this operation on a single doc i.e; for a single user or at-least lesser docs rather than on an entire collection.


问:
Centering and image size in split screen
I'm working on a project using split screen CSS and I'm having trouble both with image size and positioning. I've used the .centered CSS as instructed by W3schools, but it keeps offsetting the image and text to the right of the 'left split'. What am I doing wrong. I'm trying to center the image and the accompany
 text. W3schools shows one solution, which I've worked around for a few hours. I'm a newbie to coding and not really sure how to search for a solution. Any advice and pointers would be welcomed.

Bid on items to support local & National Organizations

Bid on these Items

Star Wars Script

Value:

$15,000

Donor:

George Lucas

Opening Bid:

$10,000

Bid Increment:

$1,000

Supporting:

Feeding America

                                    <button type="button" class="btn btn-success">Bid</button>

Signed Air Jordans

Value:

$10,000

Donor:

Michael Jordan

Opening Bid:

$3,000

Bid Increment:

$500

Supporting:

Americans Thrive

                                <button type="button" class="btn btn-success">Bid</button>

Tiger's Sunday Jersey

Value:

$1,000

Donor:

Tiger Woods

Opening Bid:

$500

Bid Increment:

$100

Supporting:

Salvation Army America

                                <button type="button" class="btn btn-success">Bid</button>

Lakers-Celtics Floor Seats

Value:

$1,000

Donor:

The LA Lakers

Opening Bid:

$300

Bid Increment:

$100

Supporting:

Operation Hope

                                    <button type="button" class="btn btn-success">Bid</button>

Signed Joshua Tree

Value:

$1,000

Donor:

Bono/U2

Opening Bid:

$300

Bid Increment:

$100

Supporting:

Operation Hope

                                    <button type="button" class="btn btn-success">Bid</button>

Signed Chipper Jones Bat

Value:

$500

Donor:

Chipper Jones

Opening Bid:

$100

Bid Increment:

$50

Supporting:

Bread For Tomorrow

                                <button type="button" class="btn btn-success">Bid</button>

```

答:
Setting horizontal margin to auto will do trick for you, it needs a width to be specified.

.split {
  width: 49%;
  height: 400px;
  border: 1px solid #999;
  float: left;
}

.centered {
  background: #ccc;
  width: 80%;
  margin: 10px auto;
}

.centered img {
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="split">
  <div class="centered">
    <img src="https://i.picsum.photos/id/83/200/100.jpg" />
  </div>
</div>
<div class="split">

</div></code>```

Body:
Setting horizontal margin to auto will do trick for you, it needs a width to be specified.

.split {
  width: 49%;
  height: 400px;
  border: 1px solid #999;
  float: left;
}

.centered {
  background: #ccc;
  width: 80%;
  margin: 10px auto;
}

.centered img {
  width: 100%;
}

<div class="split">
  <div class="centered">
    <img src="https://i.picsum.photos/id/83/200/100.jpg" />
  </div>
</div>
<div class="split">

</div>


问:
Returning value from asynchronous JavaScript method?
I have run into a problem where I can't seem to get a value from an asynchronous JavaScript method I am running in Jquery. My Jquery looks like this:

```<code>$(document).ready( function() {
$('#splash_image_upload').change( function() {
    var file = this.files[0];
    var blob_string = create_blob(file);
    alert(blob_string);
 });
</code>```

I am able to access the value that comes from the 'onload' event but I cannot seem to return the actual value. I have tried this:`

```<code>function create_blob(file) {
    var reader = new FileReader();
    reader.onload = (function() { return function(e) { return e.target.result; }; })();
    reader.readAsDataURL(file);
}
</code>```

Every time I execute this function the value of the 'blob_str' variable is 'undefined' presumably because the assignment is done before the function is finished. I am not really sure how to go about this. Is there a way I can return this value from this function??

答:
Your best bet is to pass a callback to create_blob and let the callback do whatever needs to be done, something like this:

```<code>create_blob(file, function(blob_string) { alert(blob_string) });

function create_blob(file, callback) {
    var reader = new FileReader();
    reader.onload = function() { callback(reader.result) };
    reader.readAsDataURL(file);
}
</code>```

This sort of chicanery is pretty standard with asynchronous calls (AJAX in particular). You could wire up some fragile mess of timers in an attempt for force synchronically but fighting the natural style of an API is a losing battle.

Body:
I have run into a problem where I can't seem to get a value from an asynchronous JavaScript method I am running in Jquery. My Jquery looks like this:

$(document).ready( function() {
$('#splash_image_upload').change( function() {
    var file = this.files[0];
    var blob_string = create_blob(file);
    alert(blob_string);
 });

I am able to access the value that comes from the 'onload' event but I cannot seem to return the actual value. I have tried this:`

function create_blob(file) {
    var reader = new FileReader();
    reader.onload = (function() { return function(e) { return e.target.result; }; })();
    reader.readAsDataURL(file);
}

Every time I execute this function the value of the 'blob_str' variable is 'undefined' presumably because the assignment is done before the function is finished. I am not really sure how to go about this. Is there a way I can return this value from this function??

Body:
Your best bet is to pass a callback to create_blob and let the callback do whatever needs to be done, something like this:

create_blob(file, function(blob_string) { alert(blob_string) });

function create_blob(file, callback) {
    var reader = new FileReader();
    reader.onload = function() { callback(reader.result) };
    reader.readAsDataURL(file);
}

This sort of chicanery is pretty standard with asynchronous calls (AJAX in particular). You could wire up some fragile mess of timers in an attempt for force synchronically but fighting the natural style of an API is a losing battle.


问:
Fixing Indexing when Appending Dataframes
I am appending three CSVs:

```<code>
df = pd.read_csv("places_1.csv")
temp = pd.read_csv("places_2.csv")
df = df.append(temp)
temp = pd.read_csv("places_3.csv")
df = df.append(temp)
print(df.head(20))
</code>```

the joined table looks like:

```<code>  location  device_count  population
0        A            11         NaN
1        B            12         NaN
2        C            13         NaN
3        D            14         NaN
4        E            15         NaN
0        F            21         NaN
1        G            22         NaN
2        H            23         NaN
3        I            24         NaN
4        J            25         NaN
0        K            31         NaN
1        L            32         NaN
2        M            33         NaN
3        N            34         NaN
4        O            35         NaN
</code>```

As you can see the indices are not unique.

When I call this iloc function to multiply the population column by 2:

```<code>df2 = df.copy
for index, row in df.iterrows():
    df.iloc[index, df.columns.get_loc('population')] = row['device_count'] * 2
</code>```

I get the following erronious result:

```<code>  location  device_count  population
0        A            11        62.0
1        B            12        64.0
2        C            13        66.0
3        D            14        68.0
4        E            15        70.0
0        F            21         NaN
1        G            22         NaN
2        H            23         NaN
3        I            24         NaN
4        J            25         NaN
0        K            31         NaN
1        L            32         NaN
2        M            33         NaN
3        N            34         NaN
4        O            35         NaN
</code>```

For each CSV it is overwriting the indexes of the first CSV
I have also tried creating a new column of integers and calling df.set_index(). That did not work.

Any tips?

答: First, use ignore_index, second, don't use append, use pd.concat([temp1, temp2, temp3], ignore_index=True).

Body:
I am appending three CSVs:

df = pd.read_csv("places_1.csv")
temp = pd.read_csv("places_2.csv")
df = df.append(temp)
temp = pd.read_csv("places_3.csv")
df = df.append(temp)
print(df.head(20))

the joined table looks like:

  location  device_count  population
0        A            11         NaN
1        B            12         NaN
2        C            13         NaN
3        D            14         NaN
4        E            15         NaN
0        F            21         NaN
1        G            22         NaN
2        H            23         NaN
3        I            24         NaN
4        J            25         NaN
0        K            31         NaN
1        L            32         NaN
2        M            33         NaN
3        N            34         NaN
4        O            35         NaN

As you can see the indices are not unique.

When I call this iloc function to multiply the population column by 2:

df2 = df.copy
for index, row in df.iterrows():
    df.iloc[index, df.columns.get_loc('population')] = row['device_count'] * 2

I get the following erronious result:

  location  device_count  population
0        A            11        62.0
1        B            12        64.0
2        C            13        66.0
3        D            14        68.0
4        E            15        70.0
0        F            21         NaN
1        G            22         NaN
2        H            23         NaN
3        I            24         NaN
4        J            25         NaN
0        K            31         NaN
1        L            32         NaN
2        M            33         NaN
3        N            34         NaN
4        O            35         NaN

For each CSV it is overwriting the indexes of the first CSV
I have also tried creating a new column of integers and calling df.set_index(). That did not work.

Any tips?


问:
Spring boot: enforce best practices
I am setting up a project and wondering if there any way to enforce repository instance access from service layer only? </p>

答:
We may create the Test to achieve the requirement. I have created the same in one of the projects which validate that Services and repositories should not depend on the web layer. You can modify the packages according to the requirements.

```<code>import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;

import com.tngtech.archunit.core.domain.JavaClasses;
import com.tngtech.archunit.core.importer.ClassFileImporter;
import com.tngtech.archunit.core.importer.ImportOption;
import org.junit.jupiter.api.Test;

class ArchTest {

    @Test
    void servicesAndRepositoriesShouldNotDependOnWebLayer() {
        JavaClasses importedClasses = new ClassFileImporter()
            .withImportOption(ImportOption.Predefined.DO_NOT_INCLUDE_TESTS)
            .importPackages("com.learning.springboot");

        noClasses()
            .that()
            .resideInAnyPackage("com.learning.springboot.service..")
            .or()
            .resideInAnyPackage("com.learning.springboot.repository..")
            .should()
            .dependOnClassesThat()
            .resideInAnyPackage("..com.learning.springboot.web..")
            .because("Services and repositories should not depend on web layer")
            .check(importedClasses);
    }
}
</code>```

Title: Spring boot: enforce best practices

Body:
We may create the Test to achieve the requirement. I have created the same in one of the projects which validate that Services and repositories should not depend on the web layer. You can modify the packages according to the requirements.

import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;

import com.tngtech.archunit.core.domain.JavaClasses;
import com.tngtech.archunit.core.importer.ClassFileImporter;
import com.tngtech.archunit.core.importer.ImportOption;
import org.junit.jupiter.api.Test;

class ArchTest {

    @Test
    void servicesAndRepositoriesShouldNotDependOnWebLayer() {
        JavaClasses importedClasses = new ClassFileImporter()
            .withImportOption(ImportOption.Predefined.DO_NOT_INCLUDE_TESTS)
            .importPackages("com.learning.springboot");

        noClasses()
            .that()
            .resideInAnyPackage("com.learning.springboot.service..")
            .or()
            .resideInAnyPackage("com.learning.springboot.repository..")
            .should()
            .dependOnClassesThat()
            .resideInAnyPackage("..com.learning.springboot.web..")
            .because("Services and repositories should not depend on web layer")
            .check(importedClasses);
    }
}


问:
How to sort a pandas dataframe on two (or more) different columns, in a particular order

Note

df2 is the only thing that can be used here - using df or df1 would be to use data that isn't possible. The data is received as df2, it wants to be manipulated to the form of df1. Neither df1 or df can be used as part of of the solution (as df1 is the solution).

Setup test data

this is just setup for this post.

# sample data
reps = {1: "dog", 2: "ant", 3: "cat", 6: "orange", 7: "apple", 8: "grape"}
df = pd.DataFrame(
    {"one": [1, 1, 1, 2, 2, 2, 3, 3, 3], "two": [6, 7, 8, 6, 7, 8, 6, 7, 8]}
)
df = df.replace(reps).copy()
df1 = df.copy()
df2 = df.sample(frac=1, random_state=1).replace(reps).reset_index(drop=True)
```

<h1>Problem</h1>

<p>Sort <code>df1</code> so that it is in the same order as <code>df1</code>.</p>

<p><code>df2</code>:</p>

```   one     two
0  cat   grape
1  dog   grape
2  cat  orange
3  cat   apple
4  dog   apple
5  dog  orange
6  ant   apple
7  ant  orange
8  ant   grape
```

<p><code>df1</code></p>

```   one     two
0  dog  orange
1  dog   apple
2  dog   grape
3  ant  orange
4  ant   apple
5  ant   grape
6  cat  orange
7  cat   apple
8  cat   grape
```

<h2>Conditions</h2>

<p>You can not use <code>df1</code> as part of a solution, or <code>df</code>, the data is <code>df2</code>, and
it needs to be sorted into the ordering of <code>df1</code>.</p>

<h1>Attempt</h1>

<p>I have tried with <code>pd.Categorical</code>, but couldn't make something work.</p>

<pre class="lang-py prettyprint-override"><code>order_one = ["dog", "ant", "cat"]
order_two = ["orange", "apple", "grape"]

df2 = (
    df2.groupby(["two"])
    .apply(lambda a: a.iloc[pd.Categorical(a["one"], order_one).argsort()])
    .reset_index(drop=True)
)

df2 = (
    df2.groupby(["one"])
    .apply(lambda a: a.iloc[pd.Categorical(a["two"], order_two).argsort()])
    .reset_index(drop=True)
)
</code>```

Edit

The solution should be based purely on df2, df1 is just part of the test data and to demonstrate how df2 should be sorted. A solution that uses df1 is not viable as this is the result of sorting df2, I can't use that as part of a solution

答:
Technically you are not sorting, since the order is not ascending or descending or alphabetical. You want to order df_2 with some user-specified ordering. You can do this by generating a numerical index based on your custom order, then sorting by that.

```<code>order_one = ["dog", "ant", "cat"]
order_two = ["orange", "apple", "grape"]

# Create dictionaries that define order
order_map_one = dict(zip(order_one, range(len(order_one))))
order_map_two = dict(zip(order_two, range(len(order_two))))

# Generate a temp column that maps numerical rank onto column values
df_2['order_one_rank'] = df['one'].map(order_map_one)
df_2['order_two_rank'] = df['two'].map(order_map_two)

# Sort by these temp columns
df_2.sort_values(['order_one_rank', 'order_two_rank'], inplace=True)

# Then delete the temp columns to recover the original df_2
df_2.drop('order_one_rank', 1, inplace=True)
df_2.drop('order_two_rank', 1, inplace=True)
</code>```

That should leave df_2 in the order you are looking for.

Body:
Note

df2 is the only thing that can be used here - using df or df1 would be to use data that isn't possible. The data is received as df2, it wants to be manipulated to the form of df1. Neither df1 or df can be used as part of of the solution (as df1 is the solution).

Setup test data

this is just setup for this post.

# sample data
reps = {1: "dog", 2: "ant", 3: "cat", 6: "orange", 7: "apple", 8: "grape"}
df = pd.DataFrame(
    {"one": [1, 1, 1, 2, 2, 2, 3, 3, 3], "two": [6, 7, 8, 6, 7, 8, 6, 7, 8]}
)
df = df.replace(reps).copy()
df1 = df.copy()
df2 = df.sample(frac=1, random_state=1).replace(reps).reset_index(drop=True)

Problem

Sort df1 so that it is in the same order as df1.

df2:

   one     two
0  cat   grape
1  dog   grape
2  cat  orange
3  cat   apple
4  dog   apple
5  dog  orange
6  ant   apple
7  ant  orange
8  ant   grape

df1

   one     two
0  dog  orange
1  dog   apple
2  dog   grape
3  ant  orange
4  ant   apple
5  ant   grape
6  cat  orange
7  cat   apple
8  cat   grape

Conditions

You can not use df1 as part of a solution, or df, the data is df2, and
it needs to be sorted into the ordering of df1.

Attempt

I have tried with pd.Categorical, but couldn't make something work.

order_one = ["dog", "ant", "cat"]
order_two = ["orange", "apple", "grape"]

df2 = (
    df2.groupby(["two"])
    .apply(lambda a: a.iloc[pd.Categorical(a["one"], order_one).argsort()])
    .reset_index(drop=True)
)

df2 = (
    df2.groupby(["one"])
    .apply(lambda a: a.iloc[pd.Categorical(a["two"], order_two).argsort()])
    .reset_index(drop=True)
)

Edit

The solution should be based purely on df2, df1 is just part of the test data and to demonstrate how df2 should be sorted. A solution that uses df1 is not viable as this is the result of sorting df2, I can't use that as part of a solution

Body:
Technically you are not sorting, since the order is not ascending or descending or alphabetical. You want to order df_2 with some user-specified ordering. You can do this by generating a numerical index based on your custom order, then sorting by that.

order_one = ["dog", "ant", "cat"]
order_two = ["orange", "apple", "grape"]

# Create dictionaries that define order
order_map_one = dict(zip(order_one, range(len(order_one))))
order_map_two = dict(zip(order_two, range(len(order_two))))

# Generate a temp column that maps numerical rank onto column values
df_2['order_one_rank'] = df['one'].map(order_map_one)
df_2['order_two_rank'] = df['two'].map(order_map_two)

# Sort by these temp columns
df_2.sort_values(['order_one_rank', 'order_two_rank'], inplace=True)

# Then delete the temp columns to recover the original df_2
df_2.drop('order_one_rank', 1, inplace=True)
df_2.drop('order_two_rank', 1, inplace=True)

That should leave df_2 in the order you are looking for.


问:
Is a private member secure in javascript?
I'm following freecodecamp JavaScript oop course. The course describes how you should declare a private variable inside objects for cases like passwords and bank accounts which cannot be changed from outside. the only access to private variables is through public method that has access to the private variable. then it gives this demo code to illustrate the point.

```<code>function Bird() {
  let hatchedEgg = 10; // private variable

  /* publicly available method that a bird object can use */
  this.getHatchedEggCount = function() {
    return hatchedEgg;
  };
}
let ducky = new Bird();
ducky.getHatchedEggCount(); // returns 10
</code>```

What i don't understand is how can the hatchedEgg variable be called as secured.
As a user/hacker all i have to do is to guess the variable name that is being returned from the function getHatchedEggCount() . in this case hatchedEgg (which is not too difficult for a hacker) and then i can use this line to modify the private variable;

```<code>Bird.hatchedEgg = 20;
console.log(Bird) // returns { [Function: Bird] hatchedEgg : 20 }
</code>```

Am i missing something ?

```<code>//-------------- Clarification Edit
</code>```

Apparently the problem was with the freecodecamp console (A Bug) , it was changing the value of a private variable .
if you want you can try pasting the above code in this link and you will see. freecodeConsoleLink

答:
Calling  ducky.hatchedEgg (I guess you mean this instead of Bird.hatchedEgg)  directly won't give you any result (undefined to be precise). That's the whole point of the example i.e the private variables are not accessible directly from outside. They are accessed by a method which in turn could be/could not be exposed to outside. Security comes from that.

Update I re-read the question again and what you're doing is this: You're attaching a property hatchedEgg to Bird and setting a value to it.

Bird.hatchedEgg = 20

However, this hatchedEgg is NOT the same as let hatchedEgg = 10; that's originally defined within the function.

ducky.getHatchedEggCount(); will still give you 10. Bird.hatchedEgg will give you 20 as you're attaching a property hatchedEgg to object Bird which is NOT the same as hatchedEgg declared inside the function Bird.

Also, functions first-class object and you can add/remove properties to it just like you'd do with any other object. However, in the last post, I intentionally tried to make distinction between function Bird and object Bird, to make the things clear. It's just like saying, arrays are objects too. But you maintain a distiction in the conversations so as to simply the things. Anyway, updating this as I think that led to some sort of confusion.

Body:
I'm following freecodecamp JavaScript oop course. The course describes how you should declare a private variable inside objects for cases like passwords and bank accounts which cannot be changed from outside. the only access to private variables is through public method that has access to the private variable. then it gives this demo code to illustrate the point.

function Bird() {
  let hatchedEgg = 10; // private variable

  /* publicly available method that a bird object can use */
  this.getHatchedEggCount = function() {
    return hatchedEgg;
  };
}
let ducky = new Bird();
ducky.getHatchedEggCount(); // returns 10

What i don't understand is how can the hatchedEgg variable be called as secured.
As a user/hacker all i have to do is to guess the variable name that is being returned from the function getHatchedEggCount() . in this case hatchedEgg (which is not too difficult for a hacker) and then i can use this line to modify the private variable;

Bird.hatchedEgg = 20;
console.log(Bird) // returns { [Function: Bird] hatchedEgg : 20 }

Am i missing something ?

//-------------- Clarification Edit

Apparently the problem was with the freecodecamp console (A Bug) , it was changing the value of a private variable .
if you want you can try pasting the above code in this link and you will see. freecodeConsoleLink


问:
Implementing a cache
I'm trying to implement a transparent cache that can load a specific object when it's not available, or return an already existing object indexed by (name).

I've tried running this:

```<code>loader' objs name = case findObj objs name of
  Nothing →  (new_obj, loader' new_objs)
  Just obj →  (obj, loader' objs)
  where
    new_objs = [(name, new_obj)] ++ objs
    new_obj = readObj name
loader = loader' []
</code>```

but I'm getting a

```
Occurs check: cannot construct the infinite type:
  t = (ObjType, String -> t)
```

which looks exactly like something I want :)

How can I fix the function so that it compiles?

Clarifications:

As requested, signatures (findObj either returns a known value found via a key, or Nothing, readObj creates a new obj for a key):

```<code>findObj :: [(String, ObjType)] -> String -> Maybe ObjType
readObj :: String -> ObjType
</code>```

And yes - I need a cache, because the keys are filenames and I don't want to read+parse the file each time some object is needed.

答: You might want to look at this implementation of caching in haskell.</p>

OwnerDisplayName: viraptor

ContentLicense: CC BY-SA 2.5

Title: Implementing a cache

Body:
I'm trying to implement a transparent cache that can load a specific object when it's not available, or return an already existing object indexed by (name).

I've tried running this:

loader' objs name = case findObj objs name of
  Nothing →  (new_obj, loader' new_objs)
  Just obj →  (obj, loader' objs)
  where
    new_objs = [(name, new_obj)] ++ objs
    new_obj = readObj name
loader = loader' []

but I'm getting a

Occurs check: cannot construct the infinite type:
  t = (ObjType, String -> t)

which looks exactly like something I want :)

How can I fix the function so that it compiles?

Clarifications:

As requested, signatures (findObj either returns a known value found via a key, or Nothing, readObj creates a new obj for a key):

findObj :: [(String, ObjType)] -> String -> Maybe ObjType
readObj :: String -> ObjType

And yes - I need a cache, because the keys are filenames and I don't want to read+parse the file each time some object is needed.

LastEditorDisplayName: David Segonds

OwnerDisplayName: MarkusQ


问:
Display event emitter value in html template with async pipe
I have a child component that selects a file with a 2 way data binding called file$ so the parent can receive the selected file.

The parent needs to receive the file when it is emitted, but the child also needs to display the file name in the template.

For some reason the file name is not being displayed in the child's html template. Why is this? I have subscribed to the file$ event emitter and console logged the emitted value which is indeed a file.

in child component .ts:

```<code>@Output() public file$ = new EventEmitter<any>(true);

private setDocument(uploadedFile: File): void {
    if (this.isFilesizeValid && this.isFileExtensionValid) {
        this.file$.emit(uploadedFile);
        this.isFileValidAndUploaded = true;
    }
}
</code>```

in child component .html:

{{file$.name | async}}

In parent file .html:

```<code>      <cb-drag-and-drop-file fxFlex
                             [allowedFileTypes]="[FILE_TYPE_ENUM.Xlsx]"
                             [(file$)]="file">
      </cb-drag-and-drop-file>
</code>```

In parent file .ts:

```<code>public file;
</code>```

答:
file$.name itself is not an observable, so piping it through async will not work.

This is probably what you are looking for:

```<code>{{file$ | async}}?.name
</code>```

The ?. is needed because the async pipe returns null before the observable emits.

It is also worth mentioning that EventEmitter is an Angular concept and technically not guaranteed to always be implemented as an observable. source

Body:
I have a child component that selects a file with a 2 way data binding called file$ so the parent can receive the selected file.

The parent needs to receive the file when it is emitted, but the child also needs to display the file name in the template.

For some reason the file name is not being displayed in the child's html template. Why is this? I have subscribed to the file$ event emitter and console logged the emitted value which is indeed a file.

in child component .ts:

@Output() public file$ = new EventEmitter<any>(true);

private setDocument(uploadedFile: File): void {
    if (this.isFilesizeValid && this.isFileExtensionValid) {
        this.file$.emit(uploadedFile);
        this.isFileValidAndUploaded = true;
    }
}

in child component .html:

{{file$.name | async}}

In parent file .html:

      <cb-drag-and-drop-file fxFlex
                             [allowedFileTypes]="[FILE_TYPE_ENUM.Xlsx]"
                             [(file$)]="file">
      </cb-drag-and-drop-file>

In parent file .ts:

public file;

Body:
file$.name itself is not an observable, so piping it through async will not work.

This is probably what you are looking for:

{{file$ | async}}?.name

The ?. is needed because the async pipe returns null before the observable emits.

It is also worth mentioning that EventEmitter is an Angular concept and technically not guaranteed to always be implemented as an observable. source


问:
C# inventory updating stock
I am building an app with a SQL Server database. I have a main table of products (tblProducts) with a column that holds the quantity in hand (quantity). Another table holds the orders (tblOrders) that come from the supplier.

When an order comes in, I add the order to my database (tblOrders) and then I edit tblProducts to add to the quantity column the new received product.
As far, everything is good.

My question: after let's say 1 year of many many orders, with a lot of edits in quantity, do you guys, periodically check all orders to check if the quantity in main table tblProducts is correct ? Or do I just assume that it is always correct?

What procedures do you use for updating this kind of database? Do you sum all orders every time when you need quantity in hand?

Thanks!

答:
This is really up to how you want to implement it.

Trusting that the values will always check out (with adequate testing to ensure only stable code will see production) is the easiest and the fastest way, but might be vulnerable to data corruption, and thus, not that recommended.

Always summing up the orders is the safest way and correct way, but will become increasingly slower as the size of your tables grow. If this is not an issue for you, then this is the recommended option.

What I consider a good intermediate method is to have a separate tblProductLogs table which stores the stock of an item at a specific timestamp. You can sum the inventory at set periods (daily, hourly, up to you), and when you want to retrieve the current inventory stock you only need to sum the values that were registered after the last log entry for that item, saving you query time. This could be made more safe if update operations were disabled on the log table, since you won't need to modify the entries there. This is faster than the second option, and somewhat more stable than the first.

Title: C# inventory updating stock


问:
Python storing and plotting data
I am trying to categorize a csv data with 600000 rows and 2 columns into a few types of data. Is there any possible way that I could apply something like array in C so that I could use ply.scatter(x,y) , where x and y correspond to columns of each type, to plot them out?

The way I am currently using is to store them into different files and then open it with plt(float(row[0]), float(row[1])).

答: Use pandas, with x and y two different columns, and then use df.plot.scatter(...) as documented here.

Title: Python storing and plotting data


答:
Since you're changing all Flag values to 1:

```<code>import pandas as pd

df = pd.read_csv('path/to/csv.csv')
df['Flag'] = 1
df.to_csv('path/to/csv.csv', index=False)
</code>```

If, however, you don't want to update all Flag values, check out either loc or iloc for accessing specific parts of your DataFrame.

Title: Insert values of rows above python

Body:
I have a csv below:

ID    Date          Time       Flag
1     14/05/2018    00:01:00   NaN
1     14/05/2018    00:02:00   NaN
1     14/05/2018    00:03:00   NaN
1     14/05/2018    00:04:00   NaN
1     14/05/2018    00:05:00   NaN
1     14/05/2018    00:06:00   NaN
1     14/05/2018    00:07:00   NaN
1     14/05/2018    00:08:00   NaN
1     15/05/2018    00:01:00   1
1     15/05/2018    00:02:00   1
1     16/05/2018    00:01:00   1
1     16/05/2018    00:02:00   1

2     10/07/2018    00:03:00   NaN
2     10/07/2018    00:04:00   NaN
2     10/07/2018    00:05:00   NaN
2     10/07/2018    00:06:00   NaN
2     10/07/2018    00:07:00   NaN
2     10/07/2018    00:08:00   NaN
2     11/07/2018    00:01:00   1
2     11/07/2018    00:02:00   1
2     12/07/2018    00:01:00   1
2     12/07/2018    00:02:00   1

I want to update NaN for only 4 rows above the first row (of only the first day and first time of that day) with Flag=1 for each ID.

Expected csv:

1     14/05/2018    00:01:00   NaN
1     14/05/2018    00:02:00   NaN
1     14/05/2018    00:03:00   NaN
1     14/05/2018    00:04:00   NaN
1     14/05/2018    00:05:00   1
1     14/05/2018    00:06:00   1
1     14/05/2018    00:07:00   1
1     14/05/2018    00:08:00   1
1     15/05/2018    00:01:00   1
1     15/05/2018    00:02:00   1
1     16/05/2018    00:01:00   1
1     16/05/2018    00:02:00   1

2     10/07/2018    00:03:00   NaN
2     10/07/2018    00:04:00   NaN
2     10/07/2018    00:05:00   1
2     10/07/2018    00:06:00   1
2     10/07/2018    00:07:00   1
2     10/07/2018    00:08:00   1
2     11/07/2018    00:01:00   1
2     11/07/2018    00:02:00   1
2     12/07/2018    00:01:00   1
2     12/07/2018    00:02:00   1

How can I do that. Thanks.

Body:
Since you're changing all Flag values to 1:

import pandas as pd

df = pd.read_csv('path/to/csv.csv')
df['Flag'] = 1
df.to_csv('path/to/csv.csv', index=False)

If, however, you don't want to update all Flag values, check out either loc or iloc for accessing specific parts of your DataFrame.