问:
Disable checkstyle validation for specific variables
I am working in a PHP project that uses checkstyle to validate the code. I have a problem with a part of the code that reads XML's with simplexml, the XML is all in uppercase and for example:

```<code>$response = simplexml_load_string($xml);
$code = $response->CODE; // checkstyle won't validate this because it is in uppercase
</code>```

this piece of code gives me warnings because the variable name is in uppercase (the variables are required to be in camelcase). There are lots of warnings in the code because of this.

The question is: can I disable checking specific variables, or an entire region of code? How?

Thank you very much.

答:
I dont know how to do that with checkstyle, but PHPCS can also create reports in CheckStyle format. So if you are not fixed on using Checkstyle, you could switch. With PHPCS you can add pseudo annotations into the code to skip checking, e.g.

```<code>// @codingStandardsIgnoreFile
</code>```

or just portions on code

```<code>$response = simplexml_load_string($xml);
// @codingStandardsIgnoreStart
$code = $response->CODE;
// @codingStandardsIgnoreEnd
echo $code->asXml();
</code>```

Also check for http://phpqatools.org and http://jenkins-php.org/ for additional QA tools.

Body:
I am working in a PHP project that uses checkstyle to validate the code. I have a problem with a part of the code that reads XML's with simplexml, the XML is all in uppercase and for example:

$response = simplexml_load_string($xml);
$code = $response->CODE; // checkstyle won't validate this because it is in uppercase

this piece of code gives me warnings because the variable name is in uppercase (the variables are required to be in camelcase). There are lots of warnings in the code because of this.

The question is: can I disable checking specific variables, or an entire region of code? How?

Thank you very much.

Body:
I dont know how to do that with checkstyle, but PHPCS can also create reports in CheckStyle format. So if you are not fixed on using Checkstyle, you could switch. With PHPCS you can add pseudo annotations into the code to skip checking, e.g.

// @codingStandardsIgnoreFile

or just portions on code

$response = simplexml_load_string($xml);
// @codingStandardsIgnoreStart
$code = $response->CODE;
// @codingStandardsIgnoreEnd
echo $code->asXml();

Also check for http://phpqatools.org and http://jenkins-php.org/ for additional QA tools.


来源: stackexchange

问:
How to pass a templated function parameter with a subclass of the templated type in C++?
Compiling the following contrived example:

```<code>class Base
{};

class Derived : public Base
{};

template< typename T >
class A
{};

class B
{
public:

    static void f( const A< Base >& ) {}
};

int main()
{
    A< Base > tb;
    A< Derived > td;

    B::f( tb );
    B::f( td );

    return 0;
}
</code>```

using g++-8 gives me the following error:

```<code>error: no matching function for call to 'B::f(A<Derived>&)'
 B::f( td );
note:   no known conversion for argument 1 from 'A<Derived>' to 'const A<Base>&'
</code>```

Why?

Since Derived is-a Base and it doesn't override any of Base's stuff, why can't I give a Derived in the place of a Base in the templated function parameter?

答:
Template instances, like A<Base> and A<Derived>, are different types. In particular they do not have any inheritance relationship even if Base and Derived do.

There are quite a few ways you can make what you want work.

First, you could make A<Derived> explicitly derive from A<Base>, but that means adding a whole class definition.

```<code>template<>
class A<Derived> : public A<Base>
{};
</code>```

Second, you can provide an implicit conversion from A<Derived> to A<Base> in the form of a constructor template. You can use std::enable_if and std::is_base_of to only allow A<T> where T is derived from Base, or directly std::is_same if you only want to consider this particular Derived type.

```<code>template<typename T>
class A
{
    template<typename U, typename = std::enable_if_t<std::is_base_of_v<T, U>>>
    A(A<U> const& other);
};
</code>```

Third, you can provide an implicit conversion in the form of an operator template, in much the same way.

```<code>template<typename T>
class A
{
    template<typename U, typename = std::enable_if_t<std::is_base_of_v<U, T>>>
    operator U();
};
</code>```

Fourth, you can make f a function template and restrict what types it takes.

```<code>template<typename T, typename = std::enable_if_t<std::is_base_of_v<Base, T>>>
static void f(A<T> const& a);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Compiling the following contrived example:

class Base
{};

class Derived : public Base
{};

template< typename T >
class A
{};

class B
{
public:

    static void f( const A< Base >& ) {}
};

int main()
{
    A< Base > tb;
    A< Derived > td;

    B::f( tb );
    B::f( td );

    return 0;
}

using g++-8 gives me the following error:

error: no matching function for call to 'B::f(A<Derived>&)'
 B::f( td );
note:   no known conversion for argument 1 from 'A<Derived>' to 'const A<Base>&'

Why?

Since Derived is-a Base and it doesn't override any of Base's stuff, why can't I give a Derived in the place of a Base in the templated function parameter?

Body:
Template instances, like A<Base> and A<Derived>, are different types. In particular they do not have any inheritance relationship even if Base and Derived do.

There are quite a few ways you can make what you want work.

First, you could make A<Derived> explicitly derive from A<Base>, but that means adding a whole class definition.

template<>
class A<Derived> : public A<Base>
{};

Second, you can provide an implicit conversion from A<Derived> to A<Base> in the form of a constructor template. You can use std::enable_if and std::is_base_of to only allow A<T> where T is derived from Base, or directly std::is_same if you only want to consider this particular Derived type.

template<typename T>
class A
{
    template<typename U, typename = std::enable_if_t<std::is_base_of_v<T, U>>>
    A(A<U> const& other);
};

Third, you can provide an implicit conversion in the form of an operator template, in much the same way.

template<typename T>
class A
{
    template<typename U, typename = std::enable_if_t<std::is_base_of_v<U, T>>>
    operator U();
};

Fourth, you can make f a function template and restrict what types it takes.

template<typename T, typename = std::enable_if_t<std::is_base_of_v<Base, T>>>
static void f(A<T> const& a);


问:
How to ideally create multiple apps under same project in Flutter?
I am working on a project which requires an admin app and a customer app. Both these apps will have many things on common like the theme, images, fonts, widgets, packages, etc. So what is the ideal way to do this?

If I create two separate projects, if there is a requirement to update the theme, I need to update it on two separate projects. How to handle the situation ideally?

答: I think the appropriate solution is to create a package that contains similar codes so that you can use it in both projects, If it is only about icons, themes, etc., then you should use Flavor, Take a look at this article https://medium.com/@salvatoregiordanoo/flavoring-flutter-392aaa875f36


问:
TFRecord Reads and Memory Usage
I have a simple question about reading a TFRecord:

Lets say you have a record which has 10 features - each being large numpy array. When you read the record, are all 10 numpy arrays loaded into memory? or is a feature only loaded into memory with you read that particular feature -- allowing me to read 1 feature and never load the other 9 arrays into memory?

Thanks!

答:
No, you don't have to load all features present in the TFRecord file into memory.

You can be selective by parsing with a custom feature description: https://www.tensorflow.org/tutorials/load_data/tfrecord#reading_a_tfrecord_file

Title: TFRecord Reads and Memory Usage


问:
Creating a groupby column based on ids and category
I have a table below where i need to create a column of "Relevant" and "Non-Relevant" based on IDs.

The table looks like something below:

```<code>
+----+--------------+--------+
| ID |  Experience  | Length |
+----+--------------+--------+
|  1 | Relevant     |      2 |
|  1 | Non-Relevant |      1 |
|  4 | Relevant     |      3 |
|  4 | Relevant     |      4 |
|  4 | Non-Relevant |      0 |
|  5 | Relevant     |      1 |
|  5 | Relevant     |      1 |
+----+--------------+--------+

</code>```

This is the output I am trying to get

```<code>+----+----------+--------------+
| ID | Relevant | Non-Relevant |
+----+----------+--------------+
|  1 |        2 |            1 |
|  4 |        7 |            0 |
|  5 |        2 |            0 |
+----+----------+--------------+
</code>```

答:
```<code>import pandas as pd
df = pd.DataFrame({'id': [1, 1, 4, 4, 4, 5, 5], 'exp': [x for x in 'rnrrnrr'], 'len':[2, 1, 3, 4, 0, 1, 1]})

pd.pivot_table(df, index='id', values='len', columns='exp', aggfunc='sum', fill_value=0)
</code>```

Documentation: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.pivot_table.html

Body:
I have a table below where i need to create a column of "Relevant" and "Non-Relevant" based on IDs.

The table looks like something below:

+----+--------------+--------+
| ID |  Experience  | Length |
+----+--------------+--------+
|  1 | Relevant     |      2 |
|  1 | Non-Relevant |      1 |
|  4 | Relevant     |      3 |
|  4 | Relevant     |      4 |
|  4 | Non-Relevant |      0 |
|  5 | Relevant     |      1 |
|  5 | Relevant     |      1 |
+----+--------------+--------+

This is the output I am trying to get

+----+----------+--------------+
| ID | Relevant | Non-Relevant |
+----+----------+--------------+
|  1 |        2 |            1 |
|  4 |        7 |            0 |
|  5 |        2 |            0 |
+----+----------+--------------+

Body:
import pandas as pd
df = pd.DataFrame({'id': [1, 1, 4, 4, 4, 5, 5], 'exp': [x for x in 'rnrrnrr'], 'len':[2, 1, 3, 4, 0, 1, 1]})

pd.pivot_table(df, index='id', values='len', columns='exp', aggfunc='sum', fill_value=0)

Documentation: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.pivot_table.html


问:
Self syntax in iPhone development
What is the difference between the following two approaches for the self syntax to access the object properties:-

Approach 1:-

```<code>    self.effortView = [[EffortView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
    self.effortView.effortTableView = [[UITableView alloc]initWithFrame:CGRectMake(25, 25, 300, 420) style:UITableViewStyleGrouped];
</code>```

Approach 2:-

```<code>    effortView = [[EffortView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
    effortView.effortTableView = [[UITableView alloc]initWithFrame:CGRectMake(25, 25, 300, 420) style:UITableViewStyleGrouped];
</code>```

effortView is defined as a property, and synthesized, to the Class addressed as self in Approach 1. Both of the approaches work.

I am using Xcode 4.0 iPhone SDK 4.3 on Mac 10.6.6.

Please enlighten me.

Thank you All

答:
In the first syntax:

```<code>self.effortView = [[EffortView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
self.effortView.effortTableView = [[UITableView alloc]initWithFrame:CGRectMake(25, 25, 300, 420) style:UITableViewStyleGrouped];
</code>```

you are accessing both ivars through their accessor methods (usually, effortView to get, setEffortView to set).

In the second syntax:

```<code>effortView = [[EffortView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
effortView.effortTableView = [[UITableView alloc]initWithFrame:CGRectMake(25, 25, 300, 420) style:UITableViewStyleGrouped];
</code>```

you are accessing the effortView ivar directly (pointer assignment), while you are accessing effortTableView through its property accessor.

The difference is that using an accessor you obtain additional behavior. Like, with the standard set accessors generated by the @synthesize keyword for a retain property:

```<code>@property (nonatomic, retain) NSObject* property;
</code>```

you get automatic retain count management (i.e., retain count will be automatically incremented on the assigned object; if the ivar had already a value, the object pointed to will have its retain count decreased). What this implies is that in your first example, you are causing 2 memory leaks. Indeed, (if the properties are declared as retain property) assigning to them will increase their retain count; but [[alloc] init] already gives back an object with a retain count of 1, so you don't need to increment it once more. Correct would be:

```<code>self.effortView = [[[EffortView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)] autorelease];
self.effortView.effortTableView = [[[UITableView alloc]initWithFrame:CGRectMake(25, 25, 300, 420) style:UITableViewStyleGrouped] autorelease];
</code>```

Overall, properties make much easier to deal with retain count management and are the suggested way to go with it, but you have to be aware of their "retain count" semantics and account for that.

I would suggest this article as an interesting reading.

ContentLicense: CC BY-SA 3.0

Title: Self syntax in iPhone development

Body:
What is the difference between the following two approaches for the self syntax to access the object properties:-

Approach 1:-

    self.effortView = [[EffortView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
    self.effortView.effortTableView = [[UITableView alloc]initWithFrame:CGRectMake(25, 25, 300, 420) style:UITableViewStyleGrouped];

Approach 2:-

    effortView = [[EffortView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
    effortView.effortTableView = [[UITableView alloc]initWithFrame:CGRectMake(25, 25, 300, 420) style:UITableViewStyleGrouped];

effortView is defined as a property, and synthesized, to the Class addressed as self in Approach 1. Both of the approaches work.

I am using Xcode 4.0 iPhone SDK 4.3 on Mac 10.6.6.

Please enlighten me.

Thank you All

Body:
In the first syntax:

self.effortView = [[EffortView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
self.effortView.effortTableView = [[UITableView alloc]initWithFrame:CGRectMake(25, 25, 300, 420) style:UITableViewStyleGrouped];

you are accessing both ivars through their accessor methods (usually, effortView to get, setEffortView to set).

In the second syntax:

effortView = [[EffortView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
effortView.effortTableView = [[UITableView alloc]initWithFrame:CGRectMake(25, 25, 300, 420) style:UITableViewStyleGrouped];

you are accessing the effortView ivar directly (pointer assignment), while you are accessing effortTableView through its property accessor.

The difference is that using an accessor you obtain additional behavior. Like, with the standard set accessors generated by the @synthesize keyword for a retain property:

@property (nonatomic, retain) NSObject* property;

you get automatic retain count management (i.e., retain count will be automatically incremented on the assigned object; if the ivar had already a value, the object pointed to will have its retain count decreased). What this implies is that in your first example, you are causing 2 memory leaks. Indeed, (if the properties are declared as retain property) assigning to them will increase their retain count; but [[alloc] init] already gives back an object with a retain count of 1, so you don't need to increment it once more. Correct would be:

self.effortView = [[[EffortView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)] autorelease];
self.effortView.effortTableView = [[[UITableView alloc]initWithFrame:CGRectMake(25, 25, 300, 420) style:UITableViewStyleGrouped] autorelease];

Overall, properties make much easier to deal with retain count management and are the suggested way to go with it, but you have to be aware of their "retain count" semantics and account for that.

I would suggest this article as an interesting reading.


答:
To create the dataframe:

```<code>ID = [1,1,4,4,4,5,5]
Experience = ['Relevant', 'Non-Relevant', 'Relevant', 'Relevant', 'Non-Relevant',
'Relevant', 'Relevant']
length = [2,1,3,4,0,1,1]

dictionary = {'ID' : ID,
             'Experience' : Experience,
             'Length' : length}
</code>```

To group it and then unstack:

```<code>df.groupby(by=['ID','Experience']).sum().unstack()['Length'].fillna(0)
</code>```

Title: Creating a groupby column based on ids and category

Body:
To create the dataframe:

ID = [1,1,4,4,4,5,5]
Experience = ['Relevant', 'Non-Relevant', 'Relevant', 'Relevant', 'Non-Relevant',
'Relevant', 'Relevant']
length = [2,1,3,4,0,1,1]

dictionary = {'ID' : ID,
             'Experience' : Experience,
             'Length' : length}

To group it and then unstack:

df.groupby(by=['ID','Experience']).sum().unstack()['Length'].fillna(0)


问:
Conditional JSON Sub-Schema
I am trying to use the if-then-else statement in JSON but it's unsuccessful for now.

```<code>{
"type": "object",
"minProperties": 2,
"maxProperties": 2,
"properties": {
    "human": {
        "enum": [
            "Kids",
            "Adults"
        ]
    }
},

"if": {
    "properties": {
        "human": {
            "const": "Adults"
        }
    }
},
"then": {
    "properties": {
        "shoe_size": {
            "type": "number",
            "minimum": 7,
            "maximum": 11
        }
    },
    "else": {
        "properties": {
            "shoe_size": {
                "type": "number",
                "minimum": 2,
                "maximum": 6
            }
        }
    }
},
"required": [
    "shoe_size",
    "human"
]
}
</code>```

and as a result I should get something like:

```<code>{
 "human": "Adults",
 "shoe_size": 10
 }
</code>```

Why are the values for the shoe_sizes not bounded to the mininum/maximum I assigned it to?

Thanks for the help.

答:
I think you have a nesting error, else must be on the same level as if and then:

{
  "type": "object",
  "minProperties": 2,
  "maxProperties": 2,
  "properties": {
    "human": {
      "enum": [
        "Kids",
        "Adults"
      ]
    }
  },

  "if": {
    "properties": {
      "human": {
        "const": "Adults"
      }
    }
  },
  "then": {
    "properties": {
      "shoe_size": {
        "type": "number",
        "minimum": 7,
        "maximum": 11
      }
    }
  },
  "else": {
    "properties": {
      "shoe_size": {
        "type": "number",
        "minimum": 2,
        "maximum": 6
      }
    }
  },
  "required": [
    "shoe_size",
    "human"
  ]
}```

Title: Conditional JSON Sub-Schema

Body:
I am trying to use the if-then-else statement in JSON but it's unsuccessful for now.

{
"type": "object",
"minProperties": 2,
"maxProperties": 2,
"properties": {
    "human": {
        "enum": [
            "Kids",
            "Adults"
        ]
    }
},

"if": {
    "properties": {
        "human": {
            "const": "Adults"
        }
    }
},
"then": {
    "properties": {
        "shoe_size": {
            "type": "number",
            "minimum": 7,
            "maximum": 11
        }
    },
    "else": {
        "properties": {
            "shoe_size": {
                "type": "number",
                "minimum": 2,
                "maximum": 6
            }
        }
    }
},
"required": [
    "shoe_size",
    "human"
]
}

and as a result I should get something like:

{
 "human": "Adults",
 "shoe_size": 10
 }

Why are the values for the shoe_sizes not bounded to the mininum/maximum I assigned it to?

Thanks for the help.


问:
Dynamic Canvas Control
I would like to change Figure according to selected QRadiobutton. In my real code , I tried various way to do that with and without signal(Also, checked other topics.).
To make it looks less compilcated, I rearrange my code for question.

I hope someone can help me to overcome this situation.

Here is my codes;
figure.py

```<code>from PyQt5.QtWidgets import*

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas

from matplotlib.figure import Figure

from numpy import arange, sin, cos, pi

class MainCanvas(FigureCanvas):
    """Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.)."""

    def __init__(self, parent=None, width=5, height=4, dpi=100):
        fig = Figure(figsize=(width, height), dpi=dpi)
        self.axes = fig.add_subplot(111)

        FigureCanvas.__init__(self, fig)
        self.setParent(parent)

        FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding)

        FigureCanvas.updateGeometry(self)

        t = arange(0.0, 5.0, 0.01)
        s = sin(2 * pi * t)
        self.axes.plot(t, s, color="red", linestyle="solid")

if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    ui = MainCanvas()
    ui.show()
    sys.exit(app.exec_())
</code>```

main.py

```<code>from PyQt5.QtWidgets import *
from figure import MainCanvas

class RadioButton(QWidget):
    def __init__(self):
        super().__init__()

        self.main_cavnas = MainCanvas()

        self.InitUi()

    def InitUi(self):
        groups = {"Functions": ("Sinus", "Cosines"),
                  "Colors": ("Red", "Green"),
                  "Line Styles": ("Solid", "Dashed")
                  }

        widget_layout = QVBoxLayout()

        main_group = QGroupBox("Operations")
        main_group_layout = QHBoxLayout()

        for group, buttons in groups.items():
            group_box = QGroupBox(group)
            group_layout = QVBoxLayout()
            for button_text in buttons:
                button = QRadioButton(button_text)
                button.setObjectName("radiobutton_%s" % button_text.lower())
                if button_text == "Sinus" or button_text == "Red" or button_text == "Solid":
                    button.setChecked(True)

                group_layout.addWidget(button)

            group_box.setLayout(group_layout)
            main_group_layout.addWidget(group_box)

        main_group.setLayout(main_group_layout)
        widget_layout.addWidget(self.main_cavnas)
        widget_layout.addWidget(main_group)

        self.setLayout(widget_layout)

if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    ui = RadioButton()
    ui.show()
    sys.exit(app.exec_())
</code>```

答:
The logic is to detect the change of state of the buttons, then obtain the information, clean the canvas and redraw.</p>

```<code>from PyQt5 import QtCore, QtWidgets

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

import numpy as np

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        fig = Figure(figsize=(5, 4), dpi=100)
        self.canvas = FigureCanvas(fig)

        groups = {
            "Functions": (("Sinus", np.sin), ("Cosines", np.cos)),
            "Colors": (("Red", "red"), ("Green", "green")),
            "Line Styles": (("Solid", "solid"), ("Dashed", "dashed")),
        }

        main_group = QtWidgets.QGroupBox("Operations")
        main_group_layout = QtWidgets.QHBoxLayout(main_group)

        self.group_btns = []

        for group_title, v in groups.items():
            group = QtWidgets.QGroupBox(group_title)
            main_group_layout.addWidget(group)
            vlay = QtWidgets.QVBoxLayout(group)
            group_btn = QtWidgets.QButtonGroup(self)
            self.group_btns.append(group_btn)
            for (text, value) in v:
                radio = QtWidgets.QRadioButton(text)
                radio.setProperty("prop", value)
                vlay.addWidget(radio)
                group_btn.addButton(radio)
                if text in ("Sinus", "Red", "Solid"):
                    radio.setChecked(True)

        for group_btn in self.group_btns:
            group_btn.buttonToggled.connect(self.update_canvas)

        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(self.canvas, stretch=1)
        lay.addWidget(main_group)

        self.update_canvas()

    @QtCore.pyqtSlot()
    def update_canvas(self):
        func, color, style = (
            group.checkedButton().property("prop") for group in self.group_btns
        )
        t = np.arange(0.0, 5.0, 0.01)
        s = func(2 * np.pi * t)

        self.canvas.figure.clear()
        ax = self.canvas.figure.subplots()
        ax.plot(t, s, color=color, linestyle=style)
        self.canvas.draw()

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    ui = Widget()
    ui.show()
    sys.exit(app.exec_())
</code>```

Title: Dynamic Canvas Control

Body:
I would like to change Figure according to selected QRadiobutton. In my real code , I tried various way to do that with and without signal(Also, checked other topics.).
To make it looks less compilcated, I rearrange my code for question.

I hope someone can help me to overcome this situation.

Here is my codes;
figure.py

from PyQt5.QtWidgets import*

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas

from matplotlib.figure import Figure

from numpy import arange, sin, cos, pi

class MainCanvas(FigureCanvas):
    """Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.)."""

    def __init__(self, parent=None, width=5, height=4, dpi=100):
        fig = Figure(figsize=(width, height), dpi=dpi)
        self.axes = fig.add_subplot(111)

        FigureCanvas.__init__(self, fig)
        self.setParent(parent)

        FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding)

        FigureCanvas.updateGeometry(self)

        t = arange(0.0, 5.0, 0.01)
        s = sin(2 * pi * t)
        self.axes.plot(t, s, color="red", linestyle="solid")

if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    ui = MainCanvas()
    ui.show()
    sys.exit(app.exec_())

main.py

from PyQt5.QtWidgets import *
from figure import MainCanvas

class RadioButton(QWidget):
    def __init__(self):
        super().__init__()

        self.main_cavnas = MainCanvas()

        self.InitUi()

    def InitUi(self):
        groups = {"Functions": ("Sinus", "Cosines"),
                  "Colors": ("Red", "Green"),
                  "Line Styles": ("Solid", "Dashed")
                  }

        widget_layout = QVBoxLayout()

        main_group = QGroupBox("Operations")
        main_group_layout = QHBoxLayout()

        for group, buttons in groups.items():
            group_box = QGroupBox(group)
            group_layout = QVBoxLayout()
            for button_text in buttons:
                button = QRadioButton(button_text)
                button.setObjectName("radiobutton_%s" % button_text.lower())
                if button_text == "Sinus" or button_text == "Red" or button_text == "Solid":
                    button.setChecked(True)

                group_layout.addWidget(button)

            group_box.setLayout(group_layout)
            main_group_layout.addWidget(group_box)

        main_group.setLayout(main_group_layout)
        widget_layout.addWidget(self.main_cavnas)
        widget_layout.addWidget(main_group)

        self.setLayout(widget_layout)

if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    ui = RadioButton()
    ui.show()
    sys.exit(app.exec_())

Body:
The logic is to detect the change of state of the buttons, then obtain the information, clean the canvas and redraw.

from PyQt5 import QtCore, QtWidgets

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

import numpy as np

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        fig = Figure(figsize=(5, 4), dpi=100)
        self.canvas = FigureCanvas(fig)

        groups = {
            "Functions": (("Sinus", np.sin), ("Cosines", np.cos)),
            "Colors": (("Red", "red"), ("Green", "green")),
            "Line Styles": (("Solid", "solid"), ("Dashed", "dashed")),
        }

        main_group = QtWidgets.QGroupBox("Operations")
        main_group_layout = QtWidgets.QHBoxLayout(main_group)

        self.group_btns = []

        for group_title, v in groups.items():
            group = QtWidgets.QGroupBox(group_title)
            main_group_layout.addWidget(group)
            vlay = QtWidgets.QVBoxLayout(group)
            group_btn = QtWidgets.QButtonGroup(self)
            self.group_btns.append(group_btn)
            for (text, value) in v:
                radio = QtWidgets.QRadioButton(text)
                radio.setProperty("prop", value)
                vlay.addWidget(radio)
                group_btn.addButton(radio)
                if text in ("Sinus", "Red", "Solid"):
                    radio.setChecked(True)

        for group_btn in self.group_btns:
            group_btn.buttonToggled.connect(self.update_canvas)

        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(self.canvas, stretch=1)
        lay.addWidget(main_group)

        self.update_canvas()

    @QtCore.pyqtSlot()
    def update_canvas(self):
        func, color, style = (
            group.checkedButton().property("prop") for group in self.group_btns
        )
        t = np.arange(0.0, 5.0, 0.01)
        s = func(2 * np.pi * t)

        self.canvas.figure.clear()
        ax = self.canvas.figure.subplots()
        ax.plot(t, s, color=color, linestyle=style)
        self.canvas.draw()

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    ui = Widget()
    ui.show()
    sys.exit(app.exec_())


问:
How to embed matplotlib graph in Django webpage?
So, bear with me as I'm VERY new to Django, Python, and web-development in general. What I want to do is display a graph that I've made using matplotlib. I had it working to where the home page automatically redirects to the png of the graph (basically a tab in the browser with the graph displayed). However, now what I want is to see the actual homepage with the graph simply embedded. In other words, I want to see the navigation bar, etc. and then the graph in the body of the site.

So far, I've searched and I sort of have an idea of how to accomplish this. What I'm thinking is having a special view that simply returns the graph. Then, somehow accessing this png image from an img src tag in my template that I will use to display my data.

Graph Code:

```<code>from django.shortcuts import render
import urllib
import json
from django.http import HttpResponse
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import datetime as dt
import pdb

def index(request):
    stock_price_url = 'https://www.quandl.com/api/v3/datatables/WIKI/PRICES.json?ticker=GOOGL&date.gte=20151101&qopts.columns=date,close&api_key=KEY'

    date = []
    price = []

    #pdb.set_trace()
    source_code = urllib.request.urlopen(stock_price_url).read().decode()

    json_root = json.loads(source_code)
    json_datatable = json_root["datatable"]
    json_data = json_datatable["data"]

    for day in json_data:
        date.append(dt.datetime.strptime(day[0], '%Y-%m-%d'))
        price.append(day[1])

    fig=Figure()
    ax = fig.add_subplot(1,1,1)

    ax.plot(date, price, '-')

    ax.set_xlabel('Date')
    ax.set_ylabel('Price')
    ax.set_title("Google Stock")

    canvas = FigureCanvas(fig)
    response = HttpResponse(content_type='image/png')
    #canvas.print_png(response)
    return response
</code>```

Template Code:

```<code>{% extends "home/header.html" %}
  {% block content %}
  <p>Search a stock to begin!</p>
  <img src="home/graph.py" />

  {% endblock %}
</code>```

What I'm getting now:

Current Page

答:
I searched quite a bit until I found a solution that worked for me when it comes to rendering a matplotlib image on a Django page. Often, simply a lengthy string was printed instead of a visualization being produced. So, what finally worked for me was the following:

First, the imports:

```<code>import matplotlib.pyplot as plt
from io import StringIO
import numpy as np
</code>```

The dummy function returning a graphic is the following:

```<code>def return_graph():

    x = np.arange(0,np.pi*3,.1)
    y = np.sin(x)

    fig = plt.figure()
    plt.plot(x,y)

    imgdata = StringIO()
    fig.savefig(imgdata, format='svg')
    imgdata.seek(0)

    data = imgdata.getvalue()
    return data
</code>```

This one can be called by some other function using and rendering the image returned by return_graph():

```<code>def home(request):
    context['graph'] = return_graph()
    return render(request, 'x/dashboard.html', context)
</code>```

And in the dashboard.html file, the graphic is embedded by the following command:

```<code>{{ graph|safe }}
</code>```

Body:
So, bear with me as I'm VERY new to Django, Python, and web-development in general. What I want to do is display a graph that I've made using matplotlib. I had it working to where the home page automatically redirects to the png of the graph (basically a tab in the browser with the graph displayed). However, now what I want is to see the actual homepage with the graph simply embedded. In other words, I want to see the navigation bar, etc. and then the graph in the body of the site.

So far, I've searched and I sort of have an idea of how to accomplish this. What I'm thinking is having a special view that simply returns the graph. Then, somehow accessing this png image from an img src tag in my template that I will use to display my data.

Graph Code:

from django.shortcuts import render
import urllib
import json
from django.http import HttpResponse
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import datetime as dt
import pdb

def index(request):
    stock_price_url = 'https://www.quandl.com/api/v3/datatables/WIKI/PRICES.json?ticker=GOOGL&date.gte=20151101&qopts.columns=date,close&api_key=KEY'

    date = []
    price = []

    #pdb.set_trace()
    source_code = urllib.request.urlopen(stock_price_url).read().decode()

    json_root = json.loads(source_code)
    json_datatable = json_root["datatable"]
    json_data = json_datatable["data"]

    for day in json_data:
        date.append(dt.datetime.strptime(day[0], '%Y-%m-%d'))
        price.append(day[1])

    fig=Figure()
    ax = fig.add_subplot(1,1,1)

    ax.plot(date, price, '-')

    ax.set_xlabel('Date')
    ax.set_ylabel('Price')
    ax.set_title("Google Stock")

    canvas = FigureCanvas(fig)
    response = HttpResponse(content_type='image/png')
    #canvas.print_png(response)
    return response

Template Code:

{% extends "home/header.html" %}
  {% block content %}

Search a stock to begin!

  {% endblock %}

What I'm getting now:

Current Page

Body:
I searched quite a bit until I found a solution that worked for me when it comes to rendering a matplotlib image on a Django page. Often, simply a lengthy string was printed instead of a visualization being produced. So, what finally worked for me was the following:

First, the imports:

import matplotlib.pyplot as plt
from io import StringIO
import numpy as np

The dummy function returning a graphic is the following:

def return_graph():

    x = np.arange(0,np.pi*3,.1)
    y = np.sin(x)

    fig = plt.figure()
    plt.plot(x,y)

    imgdata = StringIO()
    fig.savefig(imgdata, format='svg')
    imgdata.seek(0)

    data = imgdata.getvalue()
    return data

This one can be called by some other function using and rendering the image returned by return_graph():

def home(request):
    context['graph'] = return_graph()
    return render(request, 'x/dashboard.html', context)

And in the dashboard.html file, the graphic is embedded by the following command:

{{ graph|safe }}


问:
How to toggle style in JavaScript
I'd like to toggle stylein JavaScript. Not familiar with JavaScript but could I somehow toggle this:

```<code>document.body.style.overflow = 'hidden'
</code>```

It's part of this function:

```<code><a id="mobile-nav" href="#">
  <div class="container1" onclick="myFunction(this)">
    <div class="bar1"></div>
    <div class="bar2"></div>
    <div class="bar3"></div>
  </div>
</a>
</code>```

```<code>function myFunction(x) {
  x.classList.toggle('change');
  document.body.style.overflow = 'hidden'
}
</code>```

I'd like it to apply when I press it, and not apply when I press it again.   At the moment it applies when i initiate the function, but doesn't stop applying when I retoggle the function.

答:
```<code>document.body.style.overflow = document.body.style.overflow ? null : 'hidden';
</code>```

Title: How to toggle style in JavaScript

Body:
I'd like to toggle stylein JavaScript. Not familiar with JavaScript but could I somehow toggle this:

document.body.style.overflow = 'hidden'

It's part of this function:

function myFunction(x) {
  x.classList.toggle('change');
  document.body.style.overflow = 'hidden'
}

I'd like it to apply when I press it, and not apply when I press it again.   At the moment it applies when i initiate the function, but doesn't stop applying when I retoggle the function.


问:
Web Application to know database update
My web application (ASP.NET 4) connects to a database (SQL Server 2005). For every new row inserted in a certain table, I want the web app can do some process (like send  an email to me with new data).

How do I implement the system? My first though is having web app check the table SN column, and have a variable lastProcessedSN. And keep polling every minute. Is it possible to have DB notify web app when there's a new row being inserted?

Please advise, thanks.

EDIT:
Sending an email is just an example, not the exact thing I want to do. So this question is focusing on how to implement the trigger on MSSQL table insert to call my program.

答:
you could use SqlDependency`s see

http://www.codeproject.com/KB/database/chatter.aspx

&

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldependency.aspx

Title: Web Application to know database update


问:
Transparent background on react-navigation not applying correctly
I am currently trying to make a linear gradient background on my app and it works as intended but on the right header there's some container that I can't access. Any ideas? I tried changing the headerRightContainerStyle but that only affects the button on the right and not that empty space. It's weird how only the right side is affected too because the header's left side is the effect I desire

Image: https://ibb.co/cYKj1XV

Code:

```<code>...
  const navigation = useNavigation();

  useLayoutEffect(() => {
    navigation.setOptions({
      title: "Users Page",
      headerStyle: {
        backgroundColor: "transparent",
      },
      headerRightContainerStyle: {
        backgroundColor: "red",
      },
      headerRight: () => <Button title="Next" color={colors.blue} />,
    });
  }, []);

  return (
    <LinearGradient
      colors={gradientColorsBackground}
      style={styles.gradientBackground}
    >
      <SafeAreaView style={styles.container}>
        <KeyboardAvoidingView
          style={styles.keyboardAvoidingContainer}
          behavior="padding"
        >
          <KeyboardAwareFlatList
            style={styles.usersList}
            data={users}
            keyExtractor={(item) => `${item.id}`}
            renderItem={({ item }) => <Person name={item.name} id={item.id} />}
          />
          <TextInput
            style={styles.input}
            autoFocus={false}
            blurOnSubmit={false}
            placeholder="Type people's names"
            onSubmitEditing={({ nativeEvent: { text } }) => addUser(text)}
            autoCorrect={false}
          />
        </KeyboardAvoidingView>
      </SafeAreaView>
    </LinearGradient>
  );
};
const styles = StyleSheet.create({
  container: {
    flex: 1,
    width: "100%",
  },
  gradientBackground: {
    flex: 1,
    width: "100%",
    height: "100%",
    alignItems: "center",
  },
  input: {
    height: 50,
    backgroundColor: "orange",
    width: "100%",
    borderStyle: "solid",
    borderWidth: 3,
  },
  keyboardAvoidingContainer: {
    flex: 1,
  },
  usersList: {
    flex: 1,
    width: "100%",
    backgroundColor: colors.blue,
  },
});
...
</code>```

答:
Looks like you just need to set headerTransparent: true.

```<code>  useLayoutEffect(() => {
    navigation.setOptions({
      title: "Users Page",
      headerTransparent: true,
      headerRight: () => <Button title="Next" color={colors.blue} />,
    });
  }, []);
</code>```

Docs: https://reactnavigation.org/docs/4.x/stack-navigator/#headertransparent

Example here: https://snack.expo.io/M230FOH!Q

Body:
I am currently trying to make a linear gradient background on my app and it works as intended but on the right header there's some container that I can't access. Any ideas? I tried changing the headerRightContainerStyle but that only affects the button on the right and not that empty space. It's weird how only the right side is affected too because the header's left side is the effect I desire

Image: https://ibb.co/cYKj1XV

Code:

...
  const navigation = useNavigation();

  useLayoutEffect(() => {
    navigation.setOptions({
      title: "Users Page",
      headerStyle: {
        backgroundColor: "transparent",
      },
      headerRightContainerStyle: {
        backgroundColor: "red",
      },
      headerRight: () => <Button title="Next" color={colors.blue} />,
    });
  }, []);

  return (
    <LinearGradient
      colors={gradientColorsBackground}
      style={styles.gradientBackground}
    >
      <SafeAreaView style={styles.container}>
        <KeyboardAvoidingView
          style={styles.keyboardAvoidingContainer}
          behavior="padding"
        >
          <KeyboardAwareFlatList
            style={styles.usersList}
            data={users}
            keyExtractor={(item) => `${item.id}`}
            renderItem={({ item }) => <Person name={item.name} id={item.id} />}
          />
          <TextInput
            style={styles.input}
            autoFocus={false}
            blurOnSubmit={false}
            placeholder="Type people's names"
            onSubmitEditing={({ nativeEvent: { text } }) => addUser(text)}
            autoCorrect={false}
          />
        </KeyboardAvoidingView>
      </SafeAreaView>
    </LinearGradient>
  );
};
const styles = StyleSheet.create({
  container: {
    flex: 1,
    width: "100%",
  },
  gradientBackground: {
    flex: 1,
    width: "100%",
    height: "100%",
    alignItems: "center",
  },
  input: {
    height: 50,
    backgroundColor: "orange",
    width: "100%",
    borderStyle: "solid",
    borderWidth: 3,
  },
  keyboardAvoidingContainer: {
    flex: 1,
  },
  usersList: {
    flex: 1,
    width: "100%",
    backgroundColor: colors.blue,
  },
});
...

Body:
Looks like you just need to set headerTransparent: true.

  useLayoutEffect(() => {
    navigation.setOptions({
      title: "Users Page",
      headerTransparent: true,
      headerRight: () => <Button title="Next" color={colors.blue} />,
    });
  }, []);

Docs: https://reactnavigation.org/docs/4.x/stack-navigator/#headertransparent

Example here: https://snack.expo.io/M230FOH!Q


问:
React access state after render with functional components
I'm a bit of a newbie with React functional components, I have a child and parent components with some state that gets updated with useEffect, which state apparently resets back to its initial values after render.

Parent has a list of users it passes to its child:

Parent:

```<code>const Parent = () => {
   const [users, setUsers] = useState([])
   const getUsers = () => {
   setUsers(["pedro", "juan"])
  }
    useEffect(() => {
        getUsers()
    }, []);

   return <div>
    <Child users={users} />
}
</code>```

Child:

```<code>const Child = () => {
   const [users, setUsers] = useState([])
  useEffect(() => {
    setUsers(props.users)
  }, [[...props.users]]);
}
</code>```

If I for any reason try to access state (users) from either my child or parent components I get my initial value, which is an empty array, not my updated value from getUsers(), generally with a Parent Class component I'd have no trouble accessing that info, but it seems like functional components behave diffently? or is it caused by the useEffect? generally I'd use a class component for the parent but some libraries I use rely on Hooks, so I'm kind of forced to use functional components.

答:
it doesnt make sense to me that at Child you do const [users, setUsers] = useState([]). why dont you pass down users and setUsers through props? your child's setUser will update only its local users' state value, not parent's. overall, duplicating parent state all around its children is not good, you better consume it and updating it through props.

also, once you do [[...props.users]], you are creating a new array reference every update, so your function at useEffect will run on every update no matter what. useEffect doesnt do deep compare for arrays/objects. you better do [props.users].

Body:
I'm a bit of a newbie with React functional components, I have a child and parent components with some state that gets updated with useEffect, which state apparently resets back to its initial values after render.

Parent has a list of users it passes to its child:

Parent:

const Parent = () => {
   const [users, setUsers] = useState([])
   const getUsers = () => {
   setUsers(["pedro", "juan"])
  }
    useEffect(() => {
        getUsers()
    }, []);

   return

    <Child users={users} />
}

Child:

const Child = () => {
   const [users, setUsers] = useState([])
  useEffect(() => {
    setUsers(props.users)
  }, [[...props.users]]);
}

If I for any reason try to access state (users) from either my child or parent components I get my initial value, which is an empty array, not my updated value from getUsers(), generally with a Parent Class component I'd have no trouble accessing that info, but it seems like functional components behave diffently? or is it caused by the useEffect? generally I'd use a class component for the parent but some libraries I use rely on Hooks, so I'm kind of forced to use functional components.


问:
Adding a sequence
I have a dataframe that (simplified) looks something like this:

```<code>Index     Studio Event
1
2          MovieStart
3
4
5
6
7           MovieEnd
8
9
10          MovieStart
11
12
13
14
15          MovieEnd
</code>```

I would like to create a third column that creates a sequence from 0 and increment of 50 that begins when the StudioEvent = MovieStart and ends when StudioEvent = MovieEnd. So something like this:

```<code>Index     Studio Event    Sequence
1
2          MovieStart      0
3                          50
4                          100
5                          150
6                          200
7           MovieEnd       250
8
9
10          MovieStart     0
11                         50
12                         100
13                         150
14                         200
15          MovieEnd       250
</code>```

Any idea how I can do it? Thank you in advance.

答:
An option using data.table:

```<code>#identify indices between MovieStart and MovieEnd
DT[, cs := cumsum(StudioEvent=="MovieStart") - cumsum(StudioEvent=="MovieEnd")]

#perform rolling join to find the start of movies for MovieEnd and indices between MovieStart and MovieEnd
DT[StudioEvent=="MovieEnd" | cs == 1L,
    ms := DT[StudioEvent=="MovieStart"][.SD, on=.(Index), roll=Inf, x.Index]
]

#generate sequence
DT[, Sequence := (Index - ms) * 50]
</code>```

output:

```<code>    Index StudioEvent cs ms Sequence
 1:     1              0 NA       NA
 2:     2  MovieStart  1  2        0
 3:     3              1  2       50
 4:     4              1  2      100
 5:     5              1  2      150
 6:     6              1  2      200
 7:     7    MovieEnd  0  2      250
 8:     8              0 NA       NA
 9:     9              0 NA       NA
10:    10  MovieStart  1 10        0
11:    11              1 10       50
12:    12              1 10      100
13:    13              1 10      150
14:    14              1 10      200
15:    15    MovieEnd  0 10      250
</code>```

data:

```<code>library(data.table)
DT <- fread("Index,StudioEvent
1,
2,MovieStart
3,
4,
5,
6,
7,MovieEnd
8,
9,
10,MovieStart
11,
12,
13,
14,
15,MovieEnd")
</code>```

Title: Adding a sequence

Body:
I have a dataframe that (simplified) looks something like this:

Index     Studio Event
1
2          MovieStart
3
4
5
6
7           MovieEnd
8
9
10          MovieStart
11
12
13
14
15          MovieEnd

I would like to create a third column that creates a sequence from 0 and increment of 50 that begins when the StudioEvent = MovieStart and ends when StudioEvent = MovieEnd. So something like this:

Index     Studio Event    Sequence
1
2          MovieStart      0
3                          50
4                          100
5                          150
6                          200
7           MovieEnd       250
8
9
10          MovieStart     0
11                         50
12                         100
13                         150
14                         200
15          MovieEnd       250

Any idea how I can do it? Thank you in advance.

Body:
An option using data.table:

#identify indices between MovieStart and MovieEnd
DT[, cs := cumsum(StudioEvent=="MovieStart") - cumsum(StudioEvent=="MovieEnd")]

#perform rolling join to find the start of movies for MovieEnd and indices between MovieStart and MovieEnd
DT[StudioEvent=="MovieEnd" | cs == 1L,
    ms := DT[StudioEvent=="MovieStart"][.SD, on=.(Index), roll=Inf, x.Index]
]

#generate sequence
DT[, Sequence := (Index - ms) * 50]

output:

    Index StudioEvent cs ms Sequence
 1:     1              0 NA       NA
 2:     2  MovieStart  1  2        0
 3:     3              1  2       50
 4:     4              1  2      100
 5:     5              1  2      150
 6:     6              1  2      200
 7:     7    MovieEnd  0  2      250
 8:     8              0 NA       NA
 9:     9              0 NA       NA
10:    10  MovieStart  1 10        0
11:    11              1 10       50
12:    12              1 10      100
13:    13              1 10      150
14:    14              1 10      200
15:    15    MovieEnd  0 10      250

data:

library(data.table)
DT <- fread("Index,StudioEvent
1,
2,MovieStart
3,
4,
5,
6,
7,MovieEnd
8,
9,
10,MovieStart
11,
12,
13,
14,
15,MovieEnd")


问:
String manipulation, removing a single comma
UPDATE 1:

This is how I am attempting to build the string:

```<code>header('Content-type:application/json');

function getdata($the_query)
{
    $connection = mysql_connect('server', 'user', 'pass') or die (mysql_error());
    $db = mysql_select_db('db_name', $connection) or die (mysql_error());

    $results = mysql_query($the_query) or die(mysql_error());

    $the_data = "{
            \"rss\": {
                \"channels\" : [
                    {
                        \"title\" : \"".$title."\",
                        \"link\": \"http://www.mycompany.com/external.php\",
                        \"description\": \"company description goes here\",";

                        while($row = mysql_fetch_array($results))
                        {
                            extract($row);

                            $the_data .= "\"items\" : [
                                {
                                    \"title\": \"".$title."\",
                                    \"link\": \"".$link."\",
                                    \"guid\": \"".$link."\",
                                    \"pubDate\": \"".$date."\",
                                    \"description\": \"".$description."\"
                                } ],";
                        }

                    $the_data .= "} ]
                }
                 }";

    mysql_close($connection);

    return $the_data;
}
</code>```

ORIGINAL QUESTION:

I have a string similar to this:

```<code>$mystring = "{
      \"rss\": {
        \"channels\" : [
          {
            \"title" : \"title goes here\",
            \"link": \"link goes here\",
            \"description": \"description goes here\",
            \"items\" : [
              {
                \"title\": \"title goes here\",
                \"link\": \"url goes here\",
                \"guid\": \"id goes here\",
                \"pubDate\": \"data goes her\",
                \"description\": \"description goes here\"
              } ],
            \"items\" : [
              {
                \"title\": \"title goes here\",
                \"link\": \"url goes here\",
                \"guid\": \"id goes here\",
                \"pubDate\": \"data goes her\",
                \"description\": \"description goes here\"
              } ],
            \"items\" : [
              {
                \"title\": \"title goes here\",
                \"link\": \"url goes here\",
                \"guid\": \"id goes here\",
                \"pubDate\": \"data goes her\",
                \"description\": \"description goes here\"
              } ],
         } ]
      }
    }";
</code>```

How do I remove the last comma?

答:
As mentioned in the comments, you might be approaching it the wrong way.

But if you really want to do it this way, the following will remove the last comma:

```<code>$mystring = preg_replace("/,(?![^,]*,)/",'',$mystring);
</code>```

Body:
UPDATE 1:

This is how I am attempting to build the string:

header('Content-type:application/json');

function getdata($the_query)
{
    $connection = mysql_connect('server', 'user', 'pass') or die (mysql_error());
    $db = mysql_select_db('db_name', $connection) or die (mysql_error());

    $results = mysql_query($the_query) or die(mysql_error());

    $the_data = "{
            \"rss\": {
                \"channels\" : [
                    {
                        \"title\" : \"".$title."\",
                        \"link\": \"http://www.mycompany.com/external.php\",
                        \"description\": \"company description goes here\",";

                        while($row = mysql_fetch_array($results))
                        {
                            extract($row);

                            $the_data .= "\"items\" : [
                                {
                                    \"title\": \"".$title."\",
                                    \"link\": \"".$link."\",
                                    \"guid\": \"".$link."\",
                                    \"pubDate\": \"".$date."\",
                                    \"description\": \"".$description."\"
                                } ],";
                        }

                    $the_data .= "} ]
                }
                 }";

    mysql_close($connection);

    return $the_data;
}

ORIGINAL QUESTION:

I have a string similar to this:

$mystring = "{
      \"rss\": {
        \"channels\" : [
          {
            \"title" : \"title goes here\",
            \"link": \"link goes here\",
            \"description": \"description goes here\",
            \"items\" : [
              {
                \"title\": \"title goes here\",
                \"link\": \"url goes here\",
                \"guid\": \"id goes here\",
                \"pubDate\": \"data goes her\",
                \"description\": \"description goes here\"
              } ],
            \"items\" : [
              {
                \"title\": \"title goes here\",
                \"link\": \"url goes here\",
                \"guid\": \"id goes here\",
                \"pubDate\": \"data goes her\",
                \"description\": \"description goes here\"
              } ],
            \"items\" : [
              {
                \"title\": \"title goes here\",
                \"link\": \"url goes here\",
                \"guid\": \"id goes here\",
                \"pubDate\": \"data goes her\",
                \"description\": \"description goes here\"
              } ],
         } ]
      }
    }";

How do I remove the last comma?

Body:
As mentioned in the comments, you might be approaching it the wrong way.

But if you really want to do it this way, the following will remove the last comma:

$mystring = preg_replace("/,(?![^,]*,)/",'',$mystring);


问:
count upper case and lowercase separately in a dictionary in Python
I was trying to do the following exercise:
Consider the sentence 'Jim quickly realized that the beautiful gowns are expensive'. Create a dictionary count_letters with keys consisting of each unique letter in the sentence and values consisting of the number of times each letter is used in this sentence. Count upper case and lower case letters separately in the dictionary.

Below is my code, and I think it's doing what the exercise is asking, but for some reason it still says that I did not do it right. Any ideas, anyone?

```<code>sentence = 'Jim quickly realized that the beautiful gowns are expensive'
count_letters = {}
cnt_lowercase = 0
cnt_uppercase = 0
#write your code here!
for c in sentence:
    if c.islower():
        if (c in count_letters) == False:
            count_letters[c]={c:sentence.count(c)}
            cnt_lowercase += 1
    if c.isupper():
        if (c in count_letters) == False:
            count_letters[c]={c:sentence.count(c)}
            cnt_uppercase += 1
print(str(cnt_lowercase))
print(str(cnt_uppercase))
print(count_letters)
</code>```

答:
This is my suggest with list comprehensions

Note: Count upper case and lower case letters separately in the
  dictionary.

```<code>sentence = 'Jim quickly realized that the beautiful gowns are expensive'

alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

count_letters_upper = ([[letter, sentence.count(letter)] for letter in set(sentence) if letter in alphabet if letter.isupper()])

count_letters_lower = ([[letter, sentence.count(letter)] for letter in set(sentence) if letter in alphabet if letter.islower()])
</code>```

Body:
I was trying to do the following exercise:
Consider the sentence 'Jim quickly realized that the beautiful gowns are expensive'. Create a dictionary count_letters with keys consisting of each unique letter in the sentence and values consisting of the number of times each letter is used in this sentence. Count upper case and lower case letters separately in the dictionary.

Below is my code, and I think it's doing what the exercise is asking, but for some reason it still says that I did not do it right. Any ideas, anyone?

sentence = 'Jim quickly realized that the beautiful gowns are expensive'
count_letters = {}
cnt_lowercase = 0
cnt_uppercase = 0
#write your code here!
for c in sentence:
    if c.islower():
        if (c in count_letters) == False:
            count_letters[c]={c:sentence.count(c)}
            cnt_lowercase += 1
    if c.isupper():
        if (c in count_letters) == False:
            count_letters[c]={c:sentence.count(c)}
            cnt_uppercase += 1
print(str(cnt_lowercase))
print(str(cnt_uppercase))
print(count_letters)

Body:
This is my suggest with list comprehensions

Note: Count upper case and lower case letters separately in the
  dictionary.

sentence = 'Jim quickly realized that the beautiful gowns are expensive'

alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

count_letters_upper = ([[letter, sentence.count(letter)] for letter in set(sentence) if letter in alphabet if letter.isupper()])

count_letters_lower = ([[letter, sentence.count(letter)] for letter in set(sentence) if letter in alphabet if letter.islower()])


问:
adding and substracting time in Javascript
I'm trying to add five minutes to the current time using milliseconds and am baffled why adding and subtracting give such different results:

const now = new Date();
const gimmeFive = now + 300000;
const takeFive = now - 300000;
```

<p>Respectively give:</p>

```"Sun May 31 2020 23:06:48 GMT+0100 (British Summer Time)300000"

1590962508207
```

Why does subtraction work, but not addition? How can I add time?

Added clarification per stack overflow prompt: while the Q here overlapped with Add 10 seconds to a Date, it differed in seeking to understand why the add and subtract operators show different behaviours (as explained by RobG, for which, much thanks!)

答:
Try this Date.now()+300000 and Date.now()-300000

P.S. put everything on your constants of course

```<code>typeof (new Date)   // returns "object"
typeof (Date.now()) // returns "number"

/* --------------------------------- //
SO, of course, you cannot add or subtract numbers from,
and to objects. Follow the rules, make calculations with
numbers and everything will be OK.
*/

// your code might look like this
const now = Date.now();
const gimmeFive = now + 300000;
const takeFive = now - 300000;
</code>```

Date.now() method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC. Instead you can use new Date().getTime() – it will also return you a number in milliseconds.

Body:
I'm trying to add five minutes to the current time using milliseconds and am baffled why adding and subtracting give such different results:

const now = new Date();
const gimmeFive = now + 300000;
const takeFive = now - 300000;

Respectively give:

"Sun May 31 2020 23:06:48 GMT+0100 (British Summer Time)300000"

1590962508207

Why does subtraction work, but not addition? How can I add time?

Added clarification per stack overflow prompt: while the Q here overlapped with Add 10 seconds to a Date, it differed in seeking to understand why the add and subtract operators show different behaviours (as explained by RobG, for which, much thanks!)

Body:
Try this Date.now()+300000 and Date.now()-300000

P.S. put everything on your constants of course

typeof (new Date)   // returns "object"
typeof (Date.now()) // returns "number"

/* --------------------------------- //
SO, of course, you cannot add or subtract numbers from,
and to objects. Follow the rules, make calculations with
numbers and everything will be OK.
*/

// your code might look like this
const now = Date.now();
const gimmeFive = now + 300000;
const takeFive = now - 300000;

Date.now() method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC. Instead you can use new Date().getTime() – it will also return you a number in milliseconds.


问:
How to use TextField from Django in JavaScript?
I have a Django model:

```<code>class MyModel(models.Model):
    charField = models.CharField(maxLength=200)
    textField = models.TextField()
</code>```

and an HTML template with a JS function that displays charField and textField like this:

```<code>document.getElementById("someElement").innerHTML = "{{ myObject.charField }}";
document.getElementById("someOtherElement").innerHTML = "{{ myObject.textField }}";
</code>```

The former works fine, but the latter doesn't. I assume the problem is the fact that it is a TextField because there is no other difference between the two. How can I fix this?

答:
For a <textarea> you should use .value, so:

```<code>document.getElementById("someOtherElement")<b>.value</b> = "{{ myObject.textField }}";</code>```

for
, you should ineed use .innerHTML.

Note that both are not a good idea since Django will HTML encode the values, and thus thus can result in ", &, etc. in the values. You should use the |escapejs template filter [Django-doc]:

```<code>document.getElementById("someElement").innerHTML = "{{ myObject.charField<b>|escapejs</b> }}";
document.getElementById("someOtherElement").innerHTML = "{{ myObject.textField<b>|escapejs</b> }}";</code>```

Body:
I have a Django model:

class MyModel(models.Model):
    charField = models.CharField(maxLength=200)
    textField = models.TextField()

and an HTML template with a JS function that displays charField and textField like this:

document.getElementById("someElement").innerHTML = "{{ myObject.charField }}";
document.getElementById("someOtherElement").innerHTML = "{{ myObject.textField }}";

The former works fine, but the latter doesn't. I assume the problem is the fact that it is a TextField because there is no other difference between the two. How can I fix this?

Body:
For a <textarea> you should use .value, so:

document.getElementById("someOtherElement").value = "{{ myObject.textField }}";

for <div>, you should ineed use .innerHTML.

Note that both are not a good idea since Django will HTML encode the values, and thus thus can result in &quot;, &amp;, etc. in the values. You should use the |escapejs template filter [Django-doc]:

document.getElementById("someElement").innerHTML = "{{ myObject.charField|escapejs }}";
document.getElementById("someOtherElement").innerHTML = "{{ myObject.textField|escapejs }}";


问:
How to implement a custom dataset to pytorch project
I’d like to train a NN with a given dataset (all including some kind of object, for example: a dog), after the training the NN should help me classifying my images (downloaded from instagram) as “image includes a dog (with probability:0.XX)” or “image doesn’t include a dog (with probability: 0.XX)”.

Obviously images from instagram-images do not always have the same size (but they all have the same format (.jpg) due to filtering), and the images from my dataset do not have the same size as well.

While testing, I'm getting this Error:

```<code>    Traceback (most recent call last):
  File "/venv/nn.py", line 129, in <module>
    train(model=globalModel, hardware=hw, train_loader=loader, optimizer=optimizer, epoch=1)
  File "/venv/nn.py", line 74, in train
    for batch_idx, (data, target) in enumerate(train_loader):
  File "\venv\lib\site-packages\torch\utils\data\dataloader.py", line 345, in __next__
    data = self._next_data()
  File "\venv\lib\site-packages\torch\utils\data\dataloader.py", line 384, in _next_data
    index = self._next_index()  # may raise StopIteration
  File "\venv\lib\site-packages\torch\utils\data\dataloader.py", line 339, in _next_index
    return next(self._sampler_iter)  # may raise StopIteration
  File "\venv\lib\site-packages\torch\utils\data\sampler.py", line 200, in __iter__
    for idx in self.sampler:
  File "\venv\lib\site-packages\torch\utils\data\sampler.py", line 62, in __iter__
    return iter(range(len(self.data_source)))
TypeError: object of type 'type' has no len()
</code>```

with this code: https://pastebin.com/DcvbeMcq

Does anyone know how to implement a custom dataset right?

答:
I fixed all previous bugs and errors. At the moment I'm trying to Label my Input data manually via PyTorch:

```<code>train_data = torchvision.datasets.ImageFolder(root=TRAIN_DATA_PATH, transform=TRANSFORM)
</code>```

In the Folder TRAIN_DATA_PATH are many pictures of, for example, dogs.
How can I manually label them all as "dogs" ?
I tried to implement the train data as traindataloader to label them, but it doesn't work until now.

```<code>train_data_loader = torch.utils.data.DataLoader(train_data, batch_size=BATCH_SIZE, shuffle=True)
</code>```

Since I just want to get my evaluation data predicted as "dog (1)" or "not dog (0)", I have to label all of my dog images as "1" or "dog".
But how can I do that?

Thanks to every reader!

Updated code (testing level): https://hastebin.com/axuvupihed.py

Body:
I’d like to train a NN with a given dataset (all including some kind of object, for example: a dog), after the training the NN should help me classifying my images (downloaded from instagram) as “image includes a dog (with probability:0.XX)” or “image doesn’t include a dog (with probability: 0.XX)”.

Obviously images from instagram-images do not always have the same size (but they all have the same format (.jpg) due to filtering), and the images from my dataset do not have the same size as well.

While testing, I'm getting this Error:

    Traceback (most recent call last):
  File "/venv/nn.py", line 129, in <module>
    train(model=globalModel, hardware=hw, train_loader=loader, optimizer=optimizer, epoch=1)
  File "/venv/nn.py", line 74, in train
    for batch_idx, (data, target) in enumerate(train_loader):
  File "\venv\lib\site-packages\torch\utils\data\dataloader.py", line 345, in __next__
    data = self._next_data()
  File "\venv\lib\site-packages\torch\utils\data\dataloader.py", line 384, in _next_data
    index = self._next_index()  # may raise StopIteration
  File "\venv\lib\site-packages\torch\utils\data\dataloader.py", line 339, in _next_index
    return next(self._sampler_iter)  # may raise StopIteration
  File "\venv\lib\site-packages\torch\utils\data\sampler.py", line 200, in __iter__
    for idx in self.sampler:
  File "\venv\lib\site-packages\torch\utils\data\sampler.py", line 62, in __iter__
    return iter(range(len(self.data_source)))
TypeError: object of type 'type' has no len()

with this code: https://pastebin.com/DcvbeMcq

Does anyone know how to implement a custom dataset right?

Body:
I fixed all previous bugs and errors. At the moment I'm trying to Label my Input data manually via PyTorch:

train_data = torchvision.datasets.ImageFolder(root=TRAIN_DATA_PATH, transform=TRANSFORM)

In the Folder TRAIN_DATA_PATH are many pictures of, for example, dogs.
How can I manually label them all as "dogs" ?
I tried to implement the train data as traindataloader to label them, but it doesn't work until now.

train_data_loader = torch.utils.data.DataLoader(train_data, batch_size=BATCH_SIZE, shuffle=True)

Since I just want to get my evaluation data predicted as "dog (1)" or "not dog (0)", I have to label all of my dog images as "1" or "dog".
But how can I do that?

Thanks to every reader!

Updated code (testing level): https://hastebin.com/axuvupihed.py


问:
What is the difference between the * operator at the end of struct name vs in front of struct name?
I am following a C tutorial for a Linked List and I am building the node. However, I do not understand why the * operator comes at the end of the node variable versus in front of it. I thought pointers came in front of the word. So which is the pointer? "next" or "node"?

```<code>struct node {
    int value;
    // next pointer, should point to the next node in the list
    struct node* next; // pointer of structure type
};
</code>```

Thank you.

答:
struct node is the type so it comes in front of that, like int* num, only in this case type int is only one word.

Another hint to this is that variable names can only have one word.

So struct node* (pointer to struct node) is the type, and next is the name of the variable.

See here

Body:
I am following a C tutorial for a Linked List and I am building the node. However, I do not understand why the * operator comes at the end of the node variable versus in front of it. I thought pointers came in front of the word. So which is the pointer? "next" or "node"?

struct node {
    int value;
    // next pointer, should point to the next node in the list
    struct node* next; // pointer of structure type
};

Thank you.


答:
new Date() returns an object. You should not be adding or subtracting time directly on the object.

Instead, you can use Date.now() which returns the current time in milliseconds elapsed since Jan 1 1970.

```<code>const now = Date.now();
const gimmeFive = now + 300000;
const takeFive = now - 300000;

console.log(new Date(gimmeFive)); // Sun May 31 2020 18:42:20 GMT-0400 (Eastern Daylight Time)
console.log(new Date(takeFive)); // Sun May 31 2020 18:32:20 GMT-0400 (Eastern Daylight Time)
</code>```

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

That being said, if it is possible in your project, I suggest working with momentjs. It is truly a life saver when it comes to manipulating dates.

I hope this helps. Cheers.

Title: adding and substracting time in Javascript

Body:
new Date() returns an object. You should not be adding or subtracting time directly on the object.

Instead, you can use Date.now() which returns the current time in milliseconds elapsed since Jan 1 1970.

const now = Date.now();
const gimmeFive = now + 300000;
const takeFive = now - 300000;

console.log(new Date(gimmeFive)); // Sun May 31 2020 18:42:20 GMT-0400 (Eastern Daylight Time)
console.log(new Date(takeFive)); // Sun May 31 2020 18:32:20 GMT-0400 (Eastern Daylight Time)

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

That being said, if it is possible in your project, I suggest working with momentjs. It is truly a life saver when it comes to manipulating dates.

I hope this helps. Cheers.


问:
Expand Transition is not smooth
I have a problem with strange behavior for expand transition. Transition is not smooth for some reason. It stops for a moment before disappearing - just like:

Template is as simple as

<template>
  <v-expand-transition>
    <v-alert
      v-if="visible"
      prominent
      type="error">
      <v-row align="center">
        <v-col class="grow">
          {{message}}
        </v-col>
        <v-col class="shrink">
          <v-btn @click="invoke">{{button}}</v-btn>
        </v-col>
      </v-row>
    </v-alert>
  </v-expand-transition>
</template>
```

How to fix it?
I'm on latest stable chrome for windows (83.0.4103.61 x64)

答:
As @ssc-hrep3 mentioned in comments the code should look like:

  <v-expand-transition>

      <v-alert
        prominent
        type="error">
```

And that's it

Title: Expand Transition is not smooth

Body:
I have a problem with strange behavior for expand transition. Transition is not smooth for some reason. It stops for a moment before disappearing - just like:

Template is as simple as

<template>
  <v-expand-transition>
    <v-alert
      v-if="visible"
      prominent
      type="error">
      <v-row align="center">
        <v-col class="grow">
          {{message}}
        </v-col>
        <v-col class="shrink">
          <v-btn @click="invoke">{{button}}</v-btn>
        </v-col>
      </v-row>
    </v-alert>
  </v-expand-transition>
</template>

How to fix it?
I'm on latest stable chrome for windows (83.0.4103.61 x64)

Body:
As @ssc-hrep3 mentioned in comments the code should look like:

  <v-expand-transition>
    <div v-if="visible">
      <v-alert
        prominent
        type="error">

And that's it


问:
CMake Errors -Using Conan in the yuzu generator
I am using vs code and CMake to generator the yuzu project, but the CMakeList.txt always report error on the conan code since line 127 ,and I have already install the conan in the CMD with pip command.

Yuzu project and the CMakeList.txt

CMake output

```<code>[proc] run command: "C:\Program Files\CMake\bin\cmake.EXE" --no-warn-unused-cli "-Dcmake.cmakePath:STRING=C:/Program Files/CMake/bin/cmake" -Dcmake.configureOnOpen:BOOL=TRUE "-Dcmake.generator:STRING=MinGW Makefiles" -DCMAKE_EXPORT_COMPILE_COMMANDS:BOOL=TRUE -He:/Visual_Studio_Code/yuzu_emulator/yuzu -Be:/Visual_Studio_Code/yuzu_emulator/yuzu/build -G "Visual Studio 16 2019" -T host=x86 -A win32
[cmake] Not searching for unused variables given on the command line.
[cmake] -- Target architecture: x86
[cmake] -- Could NOT find Boost (missing: Boost_INCLUDE_DIR) (Required is at least version "1.71")
[cmake] -- Could NOT find Catch2 (missing: Catch2_INCLUDE_DIR Catch2_VERSION) (Required is at least version "2.11")
[cmake] -- Could NOT find fmt (missing: fmt_LIBRARY fmt_INCLUDE_DIR fmt_VERSION) (Required is at least version "6.2")
[cmake] -- Could NOT find OpenSSL, try to set the path to OpenSSL root folder in the system variable OPENSSL_ROOT_DIR (missing: OPENSSL_CRYPTO_LIBRARY OPENSSL_INCLUDE_DIR) (Required is at least version "1.1")
[cmake] -- Could NOT find lz4 (missing: lz4_LIBRARY lz4_INCLUDE_DIR) (Required is at least version "1.8")
[cmake] -- Could NOT find nlohmann_json (missing: nlohmann_json_INCLUDE_DIR nlohmann_json_VERSION) (Required is at least version "3.7")
[cmake] -- Could NOT find opus (missing: opus_LIBRARY opus_INCLUDE_DIR) (Required is at least version "1.3")
[cmake] -- Could NOT find ZLIB (missing: ZLIB_LIBRARY ZLIB_INCLUDE_DIR) (Required is at least version "1.2")
[cmake] -- Could NOT find zstd (missing: zstd_LIBRARY zstd_INCLUDE_DIR zstd_VERSION) (Required is at least version "1.4")
[cmake] CMake Warning at CMakeLists.txt:217 (find_package):
[cmake]   By not providing "FindQt5.cmake" in CMAKE_MODULE_PATH this project has
[cmake]   asked CMake to find a package configuration file provided by "Qt5", but
[cmake]   CMake did not find one.
[cmake]
[cmake]   Could not find a package configuration file provided by "Qt5" (requested
[cmake]   version 5.9) with any of the following names:
[cmake]
[cmake]     Qt5Config.cmake
[cmake]     qt5-config.cmake
[cmake]
[cmake]   Add the installation prefix of "Qt5" to CMAKE_PREFIX_PATH or set "Qt5_DIR"
[cmake]   to a directory containing one of the above files.  If "Qt5" provides a
[cmake]   separate development package or SDK, be sure it has been installed.
[cmake]
[cmake]
[cmake] CMake Warning at CMakeLists.txt:229 (find_package):
[cmake]   By not providing "FindSDL2.cmake" in CMAKE_MODULE_PATH this project has
[cmake]   asked CMake to find a package configuration file provided by "SDL2", but
[cmake]   CMake did not find one.
[cmake]
[cmake]   Could not find a package configuration file provided by "SDL2" with any of
[cmake]   the following names:
[cmake]
[cmake]     SDL2Config.cmake
[cmake]     sdl2-config.cmake
[cmake]
[cmake]   Add the installation prefix of "SDL2" to CMAKE_PREFIX_PATH or set
[cmake]   "SDL2_DIR" to a directory containing one of the above files.  If "SDL2"
[cmake]   provides a separate development package or SDK, be sure it has been
[cmake]   installed.
[cmake]
[cmake]
[cmake] -- Packages boost/1.72.0;catch2/2.11.0;fmt/6.2.0;openssl/1.1.1f;lz4/1.9.2;nlohmann_json/3.7.3;opus/1.3.1;zlib/1.2.11;zstd/1.4.4;qt/5.14.1@bincrafters/stable;sdl2/2.0.12@bincrafters/stable not found!
[cmake] -- Configuring incomplete, errors occurred!
[cmake] See also "E:/Visual_Studio_Code/yuzu_emulator/yuzu/build/CMakeFiles/CMakeOutput.log".
[cmake] See also "E:/Visual_Studio_Code/yuzu_emulator/yuzu/build/CMakeFiles/CMakeError.log".
[cmake] CMake Error at CMakeLists.txt:252 (conan_check):
[cmake]   Unknown CMake command "conan_check".
</code>```

generally its a problem that the CMakeList.txt file can't run the code about the conan and the lib can't be auto download, but how can i sovle the porblem, bro??????The project do not offer the conan.cmake. im a web developer,not familiar with the c++ proj construct.

答:
The CMakeLists.txt of the yuzu repository (found at the parent directory) requires version 1.24.0 of conan, while the latest is 1.25.2. I assume you have installed the latest version.

Change line 252 from:

```<code>conan_check(VERSION 1.24.0 REQUIRED)
</code>```

to:

```<code>conan_check(VERSION 1.25.2 REQUIRED)
</code>```

and it should work.

Do not forget to delete the cmake cache in your build folder.

Body:
I am using vs code and CMake to generator the yuzu project, but the CMakeList.txt always report error on the conan code since line 127 ,and I have already install the conan in the CMD with pip command.

Yuzu project and the CMakeList.txt

CMake output

[proc] run command: "C:\Program Files\CMake\bin\cmake.EXE" --no-warn-unused-cli "-Dcmake.cmakePath:STRING=C:/Program Files/CMake/bin/cmake" -Dcmake.configureOnOpen:BOOL=TRUE "-Dcmake.generator:STRING=MinGW Makefiles" -DCMAKE_EXPORT_COMPILE_COMMANDS:BOOL=TRUE -He:/Visual_Studio_Code/yuzu_emulator/yuzu -Be:/Visual_Studio_Code/yuzu_emulator/yuzu/build -G "Visual Studio 16 2019" -T host=x86 -A win32
[cmake] Not searching for unused variables given on the command line.
[cmake] -- Target architecture: x86
[cmake] -- Could NOT find Boost (missing: Boost_INCLUDE_DIR) (Required is at least version "1.71")
[cmake] -- Could NOT find Catch2 (missing: Catch2_INCLUDE_DIR Catch2_VERSION) (Required is at least version "2.11")
[cmake] -- Could NOT find fmt (missing: fmt_LIBRARY fmt_INCLUDE_DIR fmt_VERSION) (Required is at least version "6.2")
[cmake] -- Could NOT find OpenSSL, try to set the path to OpenSSL root folder in the system variable OPENSSL_ROOT_DIR (missing: OPENSSL_CRYPTO_LIBRARY OPENSSL_INCLUDE_DIR) (Required is at least version "1.1")
[cmake] -- Could NOT find lz4 (missing: lz4_LIBRARY lz4_INCLUDE_DIR) (Required is at least version "1.8")
[cmake] -- Could NOT find nlohmann_json (missing: nlohmann_json_INCLUDE_DIR nlohmann_json_VERSION) (Required is at least version "3.7")
[cmake] -- Could NOT find opus (missing: opus_LIBRARY opus_INCLUDE_DIR) (Required is at least version "1.3")
[cmake] -- Could NOT find ZLIB (missing: ZLIB_LIBRARY ZLIB_INCLUDE_DIR) (Required is at least version "1.2")
[cmake] -- Could NOT find zstd (missing: zstd_LIBRARY zstd_INCLUDE_DIR zstd_VERSION) (Required is at least version "1.4")
[cmake] CMake Warning at CMakeLists.txt:217 (find_package):
[cmake]   By not providing "FindQt5.cmake" in CMAKE_MODULE_PATH this project has
[cmake]   asked CMake to find a package configuration file provided by "Qt5", but
[cmake]   CMake did not find one.
[cmake]
[cmake]   Could not find a package configuration file provided by "Qt5" (requested
[cmake]   version 5.9) with any of the following names:
[cmake]
[cmake]     Qt5Config.cmake
[cmake]     qt5-config.cmake
[cmake]
[cmake]   Add the installation prefix of "Qt5" to CMAKE_PREFIX_PATH or set "Qt5_DIR"
[cmake]   to a directory containing one of the above files.  If "Qt5" provides a
[cmake]   separate development package or SDK, be sure it has been installed.
[cmake]
[cmake]
[cmake] CMake Warning at CMakeLists.txt:229 (find_package):
[cmake]   By not providing "FindSDL2.cmake" in CMAKE_MODULE_PATH this project has
[cmake]   asked CMake to find a package configuration file provided by "SDL2", but
[cmake]   CMake did not find one.
[cmake]
[cmake]   Could not find a package configuration file provided by "SDL2" with any of
[cmake]   the following names:
[cmake]
[cmake]     SDL2Config.cmake
[cmake]     sdl2-config.cmake
[cmake]
[cmake]   Add the installation prefix of "SDL2" to CMAKE_PREFIX_PATH or set
[cmake]   "SDL2_DIR" to a directory containing one of the above files.  If "SDL2"
[cmake]   provides a separate development package or SDK, be sure it has been
[cmake]   installed.
[cmake]
[cmake]
[cmake] -- Packages boost/1.72.0;catch2/2.11.0;fmt/6.2.0;openssl/1.1.1f;lz4/1.9.2;nlohmann_json/3.7.3;opus/1.3.1;zlib/1.2.11;zstd/1.4.4;qt/5.14.1@bincrafters/stable;sdl2/2.0.12@bincrafters/stable not found!
[cmake] -- Configuring incomplete, errors occurred!
[cmake] See also "E:/Visual_Studio_Code/yuzu_emulator/yuzu/build/CMakeFiles/CMakeOutput.log".
[cmake] See also "E:/Visual_Studio_Code/yuzu_emulator/yuzu/build/CMakeFiles/CMakeError.log".
[cmake] CMake Error at CMakeLists.txt:252 (conan_check):
[cmake]   Unknown CMake command "conan_check".

generally its a problem that the CMakeList.txt file can't run the code about the conan and the lib can't be auto download, but how can i sovle the porblem, bro??????The project do not offer the conan.cmake. im a web developer,not familiar with the c++ proj construct.

Body:
The CMakeLists.txt of the yuzu repository (found at the parent directory) requires version 1.24.0 of conan, while the latest is 1.25.2. I assume you have installed the latest version.

Change line 252 from:

conan_check(VERSION 1.24.0 REQUIRED)

to:

conan_check(VERSION 1.25.2 REQUIRED)

and it should work.

Do not forget to delete the cmake cache in your build folder.


问:
React native view auto height
I have a component with 3 views inside, one in the top, other in the middle, and the last one in the bottom. The view in the middle has a specific height. I want the others to adapt their height. Know this has to be easy but I am not too good with flex...

Here is my code:

```<code>export default function Cropper({ photo }) {
  const { colors } = useTheme();

  const [height, setHeight] = useState(WINDOW_HEIGHT / 2);

  return (
    <View style={styles.container}>
      <BlurView intensity={100} style={{ flex: 1 }} /> {/* auto height */}
      <View style={[styles.cropper, { height: height }]} />
      <BlurView intensity={100} style={{ flex: 1 }} /> {/* auto height */}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: "column",
    alignItems: "flex-start",
    backgroundColor: "red",
  },
  cropper: {
    width: "100%",
  },
});
</code>```

答:
change

```<code><View style={[styles.cropper,{height:height}]}/>
</code>```

to

```<code><View style={styles.sec}/>
</code>```

and change

```<code>cropper:{width:'100%'}
</code>```

to

```<code>cropper: {
    width: '100%',
    height: Dimensions.get('window').height/2,
}
</code>```

and add

```<code>import { Dimensions } from 'react-native'
</code>```

Title: React native view auto height

Body:
I have a component with 3 views inside, one in the top, other in the middle, and the last one in the bottom. The view in the middle has a specific height. I want the others to adapt their height. Know this has to be easy but I am not too good with flex...

Here is my code:

export default function Cropper({ photo }) {
  const { colors } = useTheme();

  const [height, setHeight] = useState(WINDOW_HEIGHT / 2);

  return (
    <View style={styles.container}>
      <BlurView intensity={100} style={{ flex: 1 }} /> {/* auto height */}
      <View style={[styles.cropper, { height: height }]} />
      <BlurView intensity={100} style={{ flex: 1 }} /> {/* auto height */}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: "column",
    alignItems: "flex-start",
    backgroundColor: "red",
  },
  cropper: {
    width: "100%",
  },
});

Body:
change

<View style={[styles.cropper,{height:height}]}/>

to

<View style={styles.sec}/>

and change

cropper:{width:'100%'}

to

cropper: {
    width: '100%',
    height: Dimensions.get('window').height/2,
}

and add

import { Dimensions } from 'react-native'


问:
geom_text() on faceted panels causes changes in symbol mapping
I am building a faceted plot where each panel has 3 different sets of points, each with a different shape. Everything works fine, until I try to add some text to each panel using geom_text(). When I include geom_text()in the plot, I get an error message that I have "insufficient values in a manual scale: 4 are needed but only 3 are provided".  I can correct this problem by adding additional shapes and colors, but I cannot control the re-mapping of the shape/color factors that occurs when I add geom_text().

Here is the script that I am running:

```<code>library(ggplot2)
library(RColorBrewer)
library(cowplot)

make_hist_df <- function (vals, breaks, expt, type) {
  hist_d <- hist(vals,breaks=breaks,plot=FALSE)
  hist_d_nz<-hist_d$counts > 0
  n_d_nz<-length(hist_d$counts[hist_d_nz])
  hist_df <- data.frame(expt=character(n_d_nz), counts=numeric(n_d_nz), mids=numeric(n_d_nz),type=character(n_d_nz))
  hist_df$counts <- hist_d$counts[hist_d_nz]
  hist_df$mids <- hist_d$mids[hist_d_nz]
  hist_df$expt = expt
  hist_df$type = type

  return(hist_df)
  }

## get some normal distributions
n1<-rnorm(n=10000, mean=5,sd=1)
n2<-rnorm(n=5000,mean=15,sd=1)
n3<-rnorm(n=2000,mean=25,sd=1)

breaks=seq(0,30,0.5)

tot_hist_df = rbind(
  make_hist_df(n1,breaks,expt='one',type='low'),
  make_hist_df(n2,breaks,expt='one',type='mid'),
  make_hist_df(n3,breaks,expt='one',type='high')
  )

tot_hist_df = rbind(tot_hist_df,
  make_hist_df(n1,breaks,expt='two',type='low'),
  make_hist_df(n2,breaks,expt='two',type='mid'),
  make_hist_df(n3,breaks,expt='two',type='high')
  )

tot_hist_df$expt<-factor(tot_hist_df$expt,levels=c('one','two'), ordered=TRUE)
tot_hist_df$type<-factor(tot_hist_df$type,levels=c('low','mid','high'), ordered=TRUE)

s.open_circ<-1
s.closed_circ<-16
s.triangle <- 2
s.plus<-4
s.dot <- 20
sb.shapes   = c(s.open_circ, s.triangle, s.closed_circ)
sb.shapes_l = c(s.open_circ, s.triangle, s.closed_circ, s.dot)

q_set <- c('N1','N2','N3')
n_q <- length(q_set)

sb.colors <-brewer.pal(max(3,n_q),'Dark2') # 'Dark2', 'Set2', 'Paired'
sb.colors_l <- c(sb.colors,'black')

sb.sizes = rep(1.25,n_q)

## plot out without labels
p1 <- ggplot(data=tot_hist_df,aes(x=mids, y=counts, shape=type, color=type))+geom_point() +
  scale_color_manual(values=sb.colors) +
  scale_shape_manual(values=sb.shapes) +
  facet_wrap(~expt, ncol=2)

## make a label dataframe
hist_label=data.frame(expt=c('one','two'), lab=c('mean 5, 20','mean 5, 20 - dup'),type=c('xlab','xlab'))
hist_label$expt <- factor(hist_label$expt,levels=c('one','two'),ordered=TRUE)
hist_label$type <- factor(hist_label$type,levels=c('low','mid','high','xlab'),ordered=TRUE)

## plot out without labels
p2 <- ggplot(data=tot_hist_df,aes(x=mids, y=counts, shape=type, color=type))+geom_point() +
  geom_text(data=hist_label, aes(x=10,y=1000,label=lab)) +
  scale_color_manual(values=sb.colors_l) +
  scale_shape_manual(values=sb.shapes_l) +
  facet_wrap(~expt, ncol=2)

plot_grid(p1,p2,ncol=1)
</code>```

And here is the output that it produces: bad plot

Both the colors and shapes differ between the top and bottom panel.

I do not understand why geom_text() is remapping the factor levels specified by "type", after I have explicitly specified them for both the plotted data and for the label data structure.  This remapping (to something that looks alphabetical) throws off both the colors and the shapes.

答:
Thank you for the reproducible example. It was much clearer to understand what was happening now.

The remapping behaviour you describe is because while learning the discrete values (training the scale), it doesn't smartly update the labels it learned from the histogram data with the labels it learns from the text data. To fix this bit, you can manually set the limits of the scale.

```<code>ggplot(data=tot_hist_df,
       aes(x=mids, y=counts, shape=type, color=type))+
  geom_point() +
  geom_text(data=hist_label,
            aes(x=10,y=1000,label=lab)) +
  scale_color_manual(values=sb.colors_l, limits = levels(hist_label$type)) +
  scale_shape_manual(values=sb.shapes_l, limits = levels(hist_label$type)) +
  facet_wrap(~expt, ncol=2)
</code>```

EDIT:

Or alternatively, you can set drop = FALSE in the manual scales:

```<code>ggplot(data=tot_hist_df,
       aes(x=mids, y=counts, shape=type, color=type))+
  geom_point() +
  geom_text(data=hist_label,
            aes(x=10,y=1000,label=lab)) +
  scale_color_manual(values=sb.colors_l, drop = FALSE) +
  scale_shape_manual(values=sb.shapes_l, drop = FALSE) +
  facet_wrap(~expt, ncol=2)
</code>```

END EDIT

Below follow a few tips that you might find useful. The first is that you can use named vectors in manual discrete scales, that will keep the link between the symbol and the colour/shape regardless of whether the symbol is in the data.

This is also useful when you have to make multiple similar plots and you don't know whether only a subset of categories is present in any single plot.

Notice in the plot below the colours are correctly matched to the data, and no legend item is shown for the not used not_in_data symbol/colour mapping.

```<code>my_colours <- setNames(object = c(brewer.pal(3, 'Dark2'), 'black', 'blue'),
                       nm = c(levels(hist_label$type), "not_in_data"))
my_shapes <- setNames(object = c(1, 2, 16, NA),
                      nm = levels(hist_label$type))

ggplot(data=tot_hist_df,
       aes(x=mids, y=counts, shape=type, color=type))+
  geom_point() +
  geom_text(data=hist_label,
            aes(x=10,y=1000,label=lab)) +
  scale_color_manual(values=my_colours) +
  scale_shape_manual(values=my_shapes) +
  facet_wrap(~expt, ncol=2)
</code>```

The second tip is that you can escape having to include the text in the legend by having the text layer not inherit the main plot's aesthetics (which assigns shape and color to the text layer, which it probably doesn't need). Also note that since the scale doesn't need to update for the text's colour and shape, the correct order of factor levels from the histogram is restored.

```<code>ggplot(data=tot_hist_df,
       aes(x=mids, y=counts, shape=type, color=type)) +
  geom_point() +
  geom_text(data=hist_label,
            aes(x=10,y=1000, label=lab),
            inherit.aes = FALSE) +
  scale_color_manual(values=my_colours) +
  scale_shape_manual(values=my_shapes) +
  facet_wrap(~expt, ncol=2)
</code>```

An alternative way to achieve the same thing, it to define not aesthetics in the main plot call, but call them in the point layer instead (plot is identical to above).

```<code>ggplot(data=tot_hist_df) +
  geom_point(aes(x=mids, y=counts, shape=type, color=type)) +
  geom_text(data=hist_label,
            aes(x=10,y=1000, label = lab)) +
  scale_color_manual(values=sb.colors) +
  scale_shape_manual(values=sb.shapes) +
  facet_wrap(~expt, ncol=2)
</code>```

I hope that helped!

Body:
I am building a faceted plot where each panel has 3 different sets of points, each with a different shape. Everything works fine, until I try to add some text to each panel using geom_text(). When I include geom_text()in the plot, I get an error message that I have "insufficient values in a manual scale: 4 are needed but only 3 are provided".  I can correct this problem by adding additional shapes and colors, but I cannot control the re-mapping of the shape/color factors that occurs when I add geom_text().

Here is the script that I am running:

library(ggplot2)
library(RColorBrewer)
library(cowplot)

make_hist_df <- function (vals, breaks, expt, type) {
  hist_d <- hist(vals,breaks=breaks,plot=FALSE)
  hist_d_nz<-hist_d$counts > 0
  n_d_nz<-length(hist_d$counts[hist_d_nz])
  hist_df <- data.frame(expt=character(n_d_nz), counts=numeric(n_d_nz), mids=numeric(n_d_nz),type=character(n_d_nz))
  hist_df$counts <- hist_d$counts[hist_d_nz]
  hist_df$mids <- hist_d$mids[hist_d_nz]
  hist_df$expt = expt
  hist_df$type = type

  return(hist_df)
  }

## get some normal distributions
n1<-rnorm(n=10000, mean=5,sd=1)
n2<-rnorm(n=5000,mean=15,sd=1)
n3<-rnorm(n=2000,mean=25,sd=1)

breaks=seq(0,30,0.5)

tot_hist_df = rbind(
  make_hist_df(n1,breaks,expt='one',type='low'),
  make_hist_df(n2,breaks,expt='one',type='mid'),
  make_hist_df(n3,breaks,expt='one',type='high')
  )

tot_hist_df = rbind(tot_hist_df,
  make_hist_df(n1,breaks,expt='two',type='low'),
  make_hist_df(n2,breaks,expt='two',type='mid'),
  make_hist_df(n3,breaks,expt='two',type='high')
  )

tot_hist_df$expt<-factor(tot_hist_df$expt,levels=c('one','two'), ordered=TRUE)
tot_hist_df$type<-factor(tot_hist_df$type,levels=c('low','mid','high'), ordered=TRUE)

s.open_circ<-1
s.closed_circ<-16
s.triangle <- 2
s.plus<-4
s.dot <- 20
sb.shapes   = c(s.open_circ, s.triangle, s.closed_circ)
sb.shapes_l = c(s.open_circ, s.triangle, s.closed_circ, s.dot)

q_set <- c('N1','N2','N3')
n_q <- length(q_set)

sb.colors <-brewer.pal(max(3,n_q),'Dark2') # 'Dark2', 'Set2', 'Paired'
sb.colors_l <- c(sb.colors,'black')

sb.sizes = rep(1.25,n_q)

## plot out without labels
p1 <- ggplot(data=tot_hist_df,aes(x=mids, y=counts, shape=type, color=type))+geom_point() +
  scale_color_manual(values=sb.colors) +
  scale_shape_manual(values=sb.shapes) +
  facet_wrap(~expt, ncol=2)

## make a label dataframe
hist_label=data.frame(expt=c('one','two'), lab=c('mean 5, 20','mean 5, 20 - dup'),type=c('xlab','xlab'))
hist_label$expt <- factor(hist_label$expt,levels=c('one','two'),ordered=TRUE)
hist_label$type <- factor(hist_label$type,levels=c('low','mid','high','xlab'),ordered=TRUE)

## plot out without labels
p2 <- ggplot(data=tot_hist_df,aes(x=mids, y=counts, shape=type, color=type))+geom_point() +
  geom_text(data=hist_label, aes(x=10,y=1000,label=lab)) +
  scale_color_manual(values=sb.colors_l) +
  scale_shape_manual(values=sb.shapes_l) +
  facet_wrap(~expt, ncol=2)

plot_grid(p1,p2,ncol=1)

And here is the output that it produces: bad plot

Both the colors and shapes differ between the top and bottom panel.

I do not understand why geom_text() is remapping the factor levels specified by "type", after I have explicitly specified them for both the plotted data and for the label data structure.  This remapping (to something that looks alphabetical) throws off both the colors and the shapes.

Body:
Thank you for the reproducible example. It was much clearer to understand what was happening now.

The remapping behaviour you describe is because while learning the discrete values (training the scale), it doesn't smartly update the labels it learned from the histogram data with the labels it learns from the text data. To fix this bit, you can manually set the limits of the scale.

ggplot(data=tot_hist_df,
       aes(x=mids, y=counts, shape=type, color=type))+
  geom_point() +
  geom_text(data=hist_label,
            aes(x=10,y=1000,label=lab)) +
  scale_color_manual(values=sb.colors_l, limits = levels(hist_label$type)) +
  scale_shape_manual(values=sb.shapes_l, limits = levels(hist_label$type)) +
  facet_wrap(~expt, ncol=2)

EDIT:

Or alternatively, you can set drop = FALSE in the manual scales:

ggplot(data=tot_hist_df,
       aes(x=mids, y=counts, shape=type, color=type))+
  geom_point() +
  geom_text(data=hist_label,
            aes(x=10,y=1000,label=lab)) +
  scale_color_manual(values=sb.colors_l, drop = FALSE) +
  scale_shape_manual(values=sb.shapes_l, drop = FALSE) +
  facet_wrap(~expt, ncol=2)

END EDIT

Below follow a few tips that you might find useful. The first is that you can use named vectors in manual discrete scales, that will keep the link between the symbol and the colour/shape regardless of whether the symbol is in the data.

This is also useful when you have to make multiple similar plots and you don't know whether only a subset of categories is present in any single plot.

Notice in the plot below the colours are correctly matched to the data, and no legend item is shown for the not used not_in_data symbol/colour mapping.

my_colours <- setNames(object = c(brewer.pal(3, 'Dark2'), 'black', 'blue'),
                       nm = c(levels(hist_label$type), "not_in_data"))
my_shapes <- setNames(object = c(1, 2, 16, NA),
                      nm = levels(hist_label$type))

ggplot(data=tot_hist_df,
       aes(x=mids, y=counts, shape=type, color=type))+
  geom_point() +
  geom_text(data=hist_label,
            aes(x=10,y=1000,label=lab)) +
  scale_color_manual(values=my_colours) +
  scale_shape_manual(values=my_shapes) +
  facet_wrap(~expt, ncol=2)

The second tip is that you can escape having to include the text in the legend by having the text layer not inherit the main plot's aesthetics (which assigns shape and color to the text layer, which it probably doesn't need). Also note that since the scale doesn't need to update for the text's colour and shape, the correct order of factor levels from the histogram is restored.

ggplot(data=tot_hist_df,
       aes(x=mids, y=counts, shape=type, color=type)) +
  geom_point() +
  geom_text(data=hist_label,
            aes(x=10,y=1000, label=lab),
            inherit.aes = FALSE) +
  scale_color_manual(values=my_colours) +
  scale_shape_manual(values=my_shapes) +
  facet_wrap(~expt, ncol=2)

An alternative way to achieve the same thing, it to define not aesthetics in the main plot call, but call them in the point layer instead (plot is identical to above).

ggplot(data=tot_hist_df) +
  geom_point(aes(x=mids, y=counts, shape=type, color=type)) +
  geom_text(data=hist_label,
            aes(x=10,y=1000, label = lab)) +
  scale_color_manual(values=sb.colors) +
  scale_shape_manual(values=sb.shapes) +
  facet_wrap(~expt, ncol=2)

I hope that helped!