问:
How can I safely reset Hangfire to a clean state?
I have a server with Hangfire installed. I haven't checked it for a while and it seems one recurring job has gone rogue. It stopped working and then it has stacked up with retries resulting in a complete lock it seems.

I would like to clear my database and start over. Can i just delete the data from all tables or should I drop the tables and let Hangfire recreate them for me? Am I risking anything by doing this?

Hangfire.State using entire Azure Basic database 2GB of space.

答:
Oracle version:</p>
```<code>TRUNCATE TABLE HANGFIRE.HF_AGGREGATED_COUNTER;
TRUNCATE TABLE HANGFIRE.HF_Counter;
TRUNCATE TABLE HANGFIRE.HF_Job_Parameter;
TRUNCATE TABLE HANGFIRE.HF_Job_Queue;
TRUNCATE TABLE HANGFIRE.HF_List;
TRUNCATE TABLE HANGFIRE.HF_JOB_State;
TRUNCATE TABLE HANGFIRE.HF_hash;
TRUNCATE TABLE HangFire.HF_set;
TRUNCATE TABLE HangFire.HF_server;
DELETE FROM HANGFIRE.HF_Job;
</code>```

Body:
Oracle version:

TRUNCATE TABLE HANGFIRE.HF_AGGREGATED_COUNTER;
TRUNCATE TABLE HANGFIRE.HF_Counter;
TRUNCATE TABLE HANGFIRE.HF_Job_Parameter;
TRUNCATE TABLE HANGFIRE.HF_Job_Queue;
TRUNCATE TABLE HANGFIRE.HF_List;
TRUNCATE TABLE HANGFIRE.HF_JOB_State;
TRUNCATE TABLE HANGFIRE.HF_hash;
TRUNCATE TABLE HangFire.HF_set;
TRUNCATE TABLE HangFire.HF_server;
DELETE FROM HANGFIRE.HF_Job;


来源: stackexchange

问:
CSS Flex item spanning two rows without fixed height
I am trying to create a flex container layout whereby one of the flex items should span two rows. See image below for a better explanation:

Here is my markup:

```<code><div class="container">
    <div class="item item-1">ITEM 1</div>
    <div class="item item-2">ITEM 2</div>
    <div class="item item-3">ITEM 3</div>
</div>
</code>```

I cannot seem to achieve this, I have tried using flex-wrap and different combinations of the flex property.

I was able to achieve this by putting ITEM 1 & ITEM 2 in a separate
, but this presents a problem on a smaller screen, whereby ITEM 3 needs to appear BETWEEN ITEM 1 & ITEM 2. So I would rather keep the markup as is and use the order property to move things around as necessary.

答:
i dont know if its a good solution but
put two item3 codes one in the individual div (item1&2) and one outside then put the one in the div to display none in non-small screens and switch between them with mediaquery</p>
```<code>@media (max-width: 40rem) {
.item3 {
display: none;
}
.mobile-item3{
display: block;
}
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to create a flex container layout whereby one of the flex items should span two rows. See image below for a better explanation:

Here is my markup:

ITEM 1

ITEM 2

ITEM 3

I cannot seem to achieve this, I have tried using flex-wrap and different combinations of the flex property.

I was able to achieve this by putting ITEM 1 & ITEM 2 in a separate
, but this presents a problem on a smaller screen, whereby ITEM 3 needs to appear BETWEEN ITEM 1 & ITEM 2. So I would rather keep the markup as is and use the order property to move things around as necessary.

Body:
i dont know if its a good solution but
put two item3 codes one in the individual div (item1&2) and one outside then put the one in the div to display none in non-small screens and switch between them with mediaquery

@media (max-width: 40rem) {
.item3 {
display: none;
}
.mobile-item3{
display: block;
}
}


问:
How do I crop a video steam that's already been resized?
I'm using PILs ImageGrab function to capture an application window in real-time for image detection with OpenCV. I've managed to scale the captured window down to increase the speed of image detection. However, I'm getting a number of false positives I can't seem to avoid. I actually only need to capture a small section of the window 761 34 1142 68

```<code>while True:
    # Grab PSS Window and find size
    window = pygetwindow.getWindowsWithTitle('App')[0]
    x1 = window.left
    y1 = window.top
    height = window.height
    width = window.width
    x2 = x1 + width
    y2 = y1 + height
    # Actual Video Loop, cropped down to the specific window,
    # resized to 1/2 size, and converted to BGR for OpenCV
    haystack_img = ImageGrab.grab(bbox=(x1, y1, x2, y2))
    (width, height) = (haystack_img.width // 2, haystack_img.height // 2)
    haystack_img_resized = haystack_img.resize((width, height))

    ########### Line in Question ##############
    haystack_img_cropped = haystack_img_resized[761: 34, 1142:68]

    haystack_img_np = np.array(haystack_img_cropped)
    haystack = cv.cvtColor(haystack_img_np, cv.COLOR_BGR2GRAY)
    cv.imshow("Screen", haystack)
</code>```

I tried using OpenCV to slice  the image but I get the error:

```<code>C:\Users\coyle\OneDrive\froggy-pirate-master\avoidShips>C:/Users/coyle/AppData/Local/Programs/Python/Python39/python.exe c:/Users/coyle/OneDrive/froggy-pirate-master/avoidShips/avoidShipActual/test7.py
Traceback (most recent call last):
  File "c:\Users\test7.py", line 103, in <module>
    objectDetection(ships_to_avoid, 0.92)
  File "c:\Users\test7.py", line 61, in objectDetection
    haystack_img_cropped = haystack_img_resized[761:34, 1142:68]
TypeError: 'Image' object is not subscriptable
</code>```

And I tried the .crop method:

```<code> haystack_img_resized = haystack_img.resize((width, height))
 haystack_img_resized.crop((761,34,1164,65))
 haystack_img_np = np.array(haystack_img_resized)
</code>```

which produces no error but hasn't actually cropped anything.

How do I crop my video stream?

答:
Not sure why, but loading the cropped image into a variable and using that variable worked.</p>
```<code>crop = haystack_img_resized.crop((761,34,1164,65))
haystack_img_np = np.array(crop)
</code>```

Body:
I'm using PILs ImageGrab function to capture an application window in real-time for image detection with OpenCV. I've managed to scale the captured window down to increase the speed of image detection. However, I'm getting a number of false positives I can't seem to avoid. I actually only need to capture a small section of the window 761 34 1142 68

while True:
    # Grab PSS Window and find size
    window = pygetwindow.getWindowsWithTitle('App')[0]
    x1 = window.left
    y1 = window.top
    height = window.height
    width = window.width
    x2 = x1 + width
    y2 = y1 + height
    # Actual Video Loop, cropped down to the specific window,
    # resized to 1/2 size, and converted to BGR for OpenCV
    haystack_img = ImageGrab.grab(bbox=(x1, y1, x2, y2))
    (width, height) = (haystack_img.width // 2, haystack_img.height // 2)
    haystack_img_resized = haystack_img.resize((width, height))

    ########### Line in Question ##############
    haystack_img_cropped = haystack_img_resized[761: 34, 1142:68]

    haystack_img_np = np.array(haystack_img_cropped)
    haystack = cv.cvtColor(haystack_img_np, cv.COLOR_BGR2GRAY)
    cv.imshow("Screen", haystack)

I tried using OpenCV to slice  the image but I get the error:

C:\Users\coyle\OneDrive\froggy-pirate-master\avoidShips>C:/Users/coyle/AppData/Local/Programs/Python/Python39/python.exe c:/Users/coyle/OneDrive/froggy-pirate-master/avoidShips/avoidShipActual/test7.py
Traceback (most recent call last):
  File "c:\Users\test7.py", line 103, in <module>
    objectDetection(ships_to_avoid, 0.92)
  File "c:\Users\test7.py", line 61, in objectDetection
    haystack_img_cropped = haystack_img_resized[761:34, 1142:68]
TypeError: 'Image' object is not subscriptable

And I tried the .crop method:

 haystack_img_resized = haystack_img.resize((width, height))
 haystack_img_resized.crop((761,34,1164,65))
 haystack_img_np = np.array(haystack_img_resized)

which produces no error but hasn't actually cropped anything.

How do I crop my video stream?

Body:
Not sure why, but loading the cropped image into a variable and using that variable worked.

crop = haystack_img_resized.crop((761,34,1164,65))
haystack_img_np = np.array(crop)


问:
Assert to compare two lists of objects C#
I am currently trying to learn how to use unit testing, and I have created the actual list of 3 animal objects and the expected list of 3 animal objects. The question is how do I Assert to check the lists are equal? I have tried CollectionAssert.AreEqual and Assert.AreEqual but to no avail. Any help would be appreciated.

The test method:

```<code>  [TestMethod]
    public void createAnimalsTest2()
    {
        animalHandler animalHandler = new animalHandler();
        // arrange
        List<Animal> expected = new List<Animal>();
        Animal dog = new Dog("",0);
        Animal cat = new Cat("",0);
        Animal mouse = new Mouse("",0);
        expected.Add(dog);
        expected.Add(cat);
        expected.Add(mouse);
        //actual
        List<Animal> actual = animalHandler.createAnimals("","","",0,0,0);

        //assert
        //this is the line that does not evaluate as true
        Assert.Equals(expected ,actual);

    }
</code>```

答:
I modified method AssertListEquals() and used standard Assert.All()</p>
```<code>    public static void AssertListEquals<TE, TA>(IEnumerable<TE> expected, IEnumerable<TA> actual, Action<TE, TA> asserter)
    {
        if (expected == null && actual == null) return;
        Assert.NotNull(expected);
        Assert.NotNull(actual);

        Assert.True(
            actual.Count() == expected.Count(),
            $"Lists have different sizes. Expected list: {expected.Count()}, actual list: {actual.Count()}");

        var i = 0;
        Assert.All(expected, e =>
        {
            try
            {
                asserter(e, actual.Skip(i).First());
            }
            finally
            {
                i++;
            }
        });
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am currently trying to learn how to use unit testing, and I have created the actual list of 3 animal objects and the expected list of 3 animal objects. The question is how do I Assert to check the lists are equal? I have tried CollectionAssert.AreEqual and Assert.AreEqual but to no avail. Any help would be appreciated.

The test method:

  [TestMethod]
    public void createAnimalsTest2()
    {
        animalHandler animalHandler = new animalHandler();
        // arrange
        List<Animal> expected = new List<Animal>();
        Animal dog = new Dog("",0);
        Animal cat = new Cat("",0);
        Animal mouse = new Mouse("",0);
        expected.Add(dog);
        expected.Add(cat);
        expected.Add(mouse);
        //actual
        List<Animal> actual = animalHandler.createAnimals("","","",0,0,0);

        //assert
        //this is the line that does not evaluate as true
        Assert.Equals(expected ,actual);

    }

Body:
I modified method AssertListEquals() and used standard Assert.All()

    public static void AssertListEquals<TE, TA>(IEnumerable<TE> expected, IEnumerable<TA> actual, Action<TE, TA> asserter)
    {
        if (expected == null && actual == null) return;
        Assert.NotNull(expected);
        Assert.NotNull(actual);

        Assert.True(
            actual.Count() == expected.Count(),
            $"Lists have different sizes. Expected list: {expected.Count()}, actual list: {actual.Count()}");

        var i = 0;
        Assert.All(expected, e =>
        {
            try
            {
                asserter(e, actual.Skip(i).First());
            }
            finally
            {
                i++;
            }
        });
    }


问:
Is there a way to not inherit "virtualness" of a function in a subclass?
Is it possible in C++ to have a class override a virtual function, but only have virtual dispatch when the function is called through the superclass (ie. not when it is called on something statically typed as the subclass)? I know this isn't what happens, but is there any way to achieve something close?

The reason for wanting this is that I have two classes which both expose a flush() function. The vast majority of the time in my program, I am calling flush() directly on a subclass object that I know the type of, so I don't need virtual dispatch. However I want to add a superclass into the mix so that very infrequently I can pass a reference to an instance of either one of the classes into a doSomethingThenFlush() function, which would call flush() virtually.

I know I could use templates instead of virtual functions, and I know I could have two different functions (eg. flushVirtual() which just called flushNonVirtual(), and call flushNonVirtual() everywhere I don't need virtual dispatch). But these both seem a bit like throwing code at a problem which is largely syntactical. Is there any more elegant way to achieve this?

Perhaps more importantly, does anyone know why virtualness is inherited in C++?

```<code>struct Base
{
  virtual ~Base(){}
  virtual void func();
};

struct Derived : public Base
{
  void func(){}
};

void callVirtually(Base &base)
{
  base.func();//this will use virtual dispatch
}

void callStatically(Derived &derived)
{
  derived.func();//I don't want/need this to use virtual dispatch
}

int main()
{
  Derived derived;
  callVirtually(derived);
  callStatically(derived);
}
</code>```

答:
In C++03, no.

As others said, it is a compiler optimization (and a frequently used one) to de-virtualize he call whenever it can assess that the runtime type of the object.

However, in C++0x we get two new keywords: override and final and both can be applied to member functions (final can also be applied to a class).

override: specify that this function overrides a virtual function in a base class, useful to get warned when this is not the case

final: specify that this function (virtual) cannot be overriden in children classes.

Your class would thus become:

```<code>struct Derived : public Base
{
  void func() final {}
};
</code>```

Note: using final does not mandate that the compiler devirtualize function calls (from the Standard point of view), but any compiler worth its salt should do so.

Body:
Is it possible in C++ to have a class override a virtual function, but only have virtual dispatch when the function is called through the superclass (ie. not when it is called on something statically typed as the subclass)? I know this isn't what happens, but is there any way to achieve something close?

The reason for wanting this is that I have two classes which both expose a flush() function. The vast majority of the time in my program, I am calling flush() directly on a subclass object that I know the type of, so I don't need virtual dispatch. However I want to add a superclass into the mix so that very infrequently I can pass a reference to an instance of either one of the classes into a doSomethingThenFlush() function, which would call flush() virtually.

I know I could use templates instead of virtual functions, and I know I could have two different functions (eg. flushVirtual() which just called flushNonVirtual(), and call flushNonVirtual() everywhere I don't need virtual dispatch). But these both seem a bit like throwing code at a problem which is largely syntactical. Is there any more elegant way to achieve this?

Perhaps more importantly, does anyone know why virtualness is inherited in C++?

struct Base
{
  virtual ~Base(){}
  virtual void func();
};

struct Derived : public Base
{
  void func(){}
};

void callVirtually(Base &base)
{
  base.func();//this will use virtual dispatch
}

void callStatically(Derived &derived)
{
  derived.func();//I don't want/need this to use virtual dispatch
}

int main()
{
  Derived derived;
  callVirtually(derived);
  callStatically(derived);
}

Body:
In C++03, no.

As others said, it is a compiler optimization (and a frequently used one) to de-virtualize he call whenever it can assess that the runtime type of the object.

However, in C++0x we get two new keywords: override and final and both can be applied to member functions (final can also be applied to a class).

override: specify that this function overrides a virtual function in a base class, useful to get warned when this is not the case

final: specify that this function (virtual) cannot be overriden in children classes.

Your class would thus become:

struct Derived : public Base
{
  void func() final {}
};

Note: using final does not mandate that the compiler devirtualize function calls (from the Standard point of view), but any compiler worth its salt should do so.


问:
How to read from console stream in Flutter in release app?
For crash analysis reasons, I would like to read the complete console output from my release flutter-app, so that I can send it to me in case of a crash or an exception.

In my case, I have some debugPrint(...)s, print(...)s and log(...)s in my code, that help my in debug mode.
Is there any way to read that output when I'm in release mode?

Edit: Trying to avoid any external services, like Firebase.

Thanks in advance!

答:
You can probably use Firebase Crashlytics.

It will allow you to get the error when a crash occurs.

For the debugPrint it only print when the app is in debug mode, so there is no way to use this function to display any information on a release app.


问:
Organize CMake project the right way
I'm a newbie to CMake and I have several doubts about how to organize my project.

As of now, I have the following structure:

```<code>(0)SomeProject
|-- (1)test
|   |
|   |-- CMakeLists.txt
|   `-- tests.cpp
|
|-- (1)src
|   |-- (2)communication
|   |   |-- CMakeLists.txt
|   |   |-- comm.cpp
|   |   `-- comm.hpp
|   |
|   |-- (2)core
|   |   |-- CMakeLists.txt
|   |   |-- core.cpp
|   |   `-- core.hpp
|   |
|   |-- (2)components
|   |   |-- CMakeLists.txt
|   |   |-- component.hpp
|   |   |
|   |   |-- componentA
|   |   |   |-- compA.cpp
|   |   |   `-- compA.hpp
|   |   `-- componentB
|   |       |-- compB.cpp
|   |       `-- compB.hpp
|   |
|   |-- (2)utils
|   |   |-- CMakeLists.txt
|   |   |-- logging.hpp
|   |   `-- other_util.hpp
|   |
|   |-- (2)exceptions
|   |   |-- CMakeLists.txt
|   |   |-- exceptionA.hpp
|   |   |-- exceptionB.hpp
|   |   `-- exceptionC.hpp
|   |
|   |-- CMakeLists.txt
|   `-- main.cpp
|
|-- CMakeLists.txt
</code>```

The root CMake file (level 0) has the following lines:

```<code>add_subdirectory(src)
add_subdirectory(test)
</code>```

And the level 1 CMake files also add all the level 2 subdirectories.

In each level 2 directory, I have the same structure, for example considering the "components" folder:

```<code>add_library(compA componentA/compA.cpp componentA.hpp)
target_link_libraries(compA communication exceptions)

add_library(compB componentB/compB.cpp componentB.hpp)
target_link_libraries(compB communication exceptions utils)
</code>```

And lastly, in the level 1 src CMake file:

```<code>add_subdirectory(utils)
add_subdirectory(exceptions)
add_subdirectory(communication)
add_subdirectory(compA)
add_subdirectory(compB)
add_subdirectory(core)

add_executable(project_executable main.cpp)

target_link_libraries(project_executable utils exceptions communication compA compB core)
</code>```

I'm thinking that this is not the right approach, in particular:

Is it correct to add everything as a library?

Is it correct to create a library including only header files?

Any suggestion would be greatly appreciated. Thanks in advance.

答:
the right way

There is no "right way™" or "correct way", there is no bad or wrong. Create a structure that is the best for you for the specific application/use that you are working with.

Is it correct to add everything as a library?

Yes, it gives a nice overview and comfy feeling that you are working with small parts separately.

Is it correct to create a library including only header files?

Yes, INTERFACE libraries are for that.

Any suggestion would be greatly appreciated

Always use PUBLIC/INTERFACE/PRIVATE with target_link_libraries.

Split long lines.

```<code>target_link_libraries(project_executable PRIVATE
    utils
    exceptions
    communication
    compA
    compB
    core
)
</code>```

Title: Organize CMake project the right way

Body:
I'm a newbie to CMake and I have several doubts about how to organize my project.

As of now, I have the following structure:

(0)SomeProject
|-- (1)test
|   |
|   |-- CMakeLists.txt
|   `-- tests.cpp
|
|-- (1)src
|   |-- (2)communication
|   |   |-- CMakeLists.txt
|   |   |-- comm.cpp
|   |   `-- comm.hpp
|   |
|   |-- (2)core
|   |   |-- CMakeLists.txt
|   |   |-- core.cpp
|   |   `-- core.hpp
|   |
|   |-- (2)components
|   |   |-- CMakeLists.txt
|   |   |-- component.hpp
|   |   |
|   |   |-- componentA
|   |   |   |-- compA.cpp
|   |   |   `-- compA.hpp
|   |   `-- componentB
|   |       |-- compB.cpp
|   |       `-- compB.hpp
|   |
|   |-- (2)utils
|   |   |-- CMakeLists.txt
|   |   |-- logging.hpp
|   |   `-- other_util.hpp
|   |
|   |-- (2)exceptions
|   |   |-- CMakeLists.txt
|   |   |-- exceptionA.hpp
|   |   |-- exceptionB.hpp
|   |   `-- exceptionC.hpp
|   |
|   |-- CMakeLists.txt
|   `-- main.cpp
|
|-- CMakeLists.txt

The root CMake file (level 0) has the following lines:

add_subdirectory(src)
add_subdirectory(test)

And the level 1 CMake files also add all the level 2 subdirectories.

In each level 2 directory, I have the same structure, for example considering the "components" folder:

add_library(compA componentA/compA.cpp componentA.hpp)
target_link_libraries(compA communication exceptions)

add_library(compB componentB/compB.cpp componentB.hpp)
target_link_libraries(compB communication exceptions utils)

And lastly, in the level 1 src CMake file:

add_subdirectory(utils)
add_subdirectory(exceptions)
add_subdirectory(communication)
add_subdirectory(compA)
add_subdirectory(compB)
add_subdirectory(core)

add_executable(project_executable main.cpp)

target_link_libraries(project_executable utils exceptions communication compA compB core)

I'm thinking that this is not the right approach, in particular:

Is it correct to add everything as a library?

Is it correct to create a library including only header files?

Any suggestion would be greatly appreciated. Thanks in advance.

Body:
the right way

There is no "right way™" or "correct way", there is no bad or wrong. Create a structure that is the best for you for the specific application/use that you are working with.

Is it correct to add everything as a library?

Yes, it gives a nice overview and comfy feeling that you are working with small parts separately.

Is it correct to create a library including only header files?

Yes, INTERFACE libraries are for that.

Any suggestion would be greatly appreciated

Always use PUBLIC/INTERFACE/PRIVATE with target_link_libraries.

Split long lines.

target_link_libraries(project_executable PRIVATE
    utils
    exceptions
    communication
    compA
    compB
    core
)


问:
how to make a regular grid base on some irregular points in python
I have a numpy array of x and y coordinates and want to make it regular. The array is sorted based on its x values (first column):

```<code>import numpy as np
Irregular_points = np.array([[1.1,5.], [0.85,7.1], [0.9,9], [1.1,11], [1.,13.1],
                   [1.9,5.2], [2.,6.9], [1.95,9], [2.1,11.1], [2.,13.1],
                   [3.0,5.1], [3.1,7.0], [3.,9], [3.0,11.], [3.1,12.8]])
</code>```

I want to firtly find out which points have almost the same x values: it will be the first five rows, middle five rows and last five rows. One signal for finding these points is that y value decreases when I go to the next group. Then, I want to replace the x values of each group with the average value. For example in the fisrt five rows x values are 1.1, 0.85, 0.9, 1.1 and 1. and the average is 0.98. I want to do the same for next two parts.

For y values I again want to find similar ones which fall into five groups and then replace them with average of each group. y values of the first group are 5., 5.2 and 5.1 and average is 5.1. Finally, my points should be like the following array:

```<code>Regular_points = np.array([[0.98,5.1], [0.98,7.0], [0.98,9.0], [0.98,11.03], [0.98,13.0],
                   [1.98,5.1], [1.98,7.0], [1.98,9.0], [1.98,11.03], [1.98,13.0],
                   [3.04,5.1], [3.04,7.0], [3.04,9.0], [3.04,11.03], [3.04,13.0]])
</code>```

I tried to round numbers but it did not work for real cases and I need to make these averages. I very much appreciate any help. The figure clearly shows what I want. Red dots are irregular points but by replacing averages, blue dots can be resulted.

答:
You could use a cluster algorithm like KMeans:</p>
```<code>import numpy as np
from sklearn.cluster import KMeans

irregular_points = np.array([[1.1,5.], [0.85,7.1], [0.9,9], [1.1,11], [1.,13.1],
                   [1.9,5.2], [2.,6.9], [1.95,9], [2.1,11.1], [2.,13.1],
                   [3.0,5.1], [3.1,7.0], [3.,9], [3.0,11.], [3.1,12.8]])

kmeans_x = KMeans(n_clusters=3).fit(irregular_points[:, 0, np.newaxis])
kmeans_y = KMeans(n_clusters=5).fit(irregular_points[:, 1, np.newaxis])

clusters_x = kmeans_x.predict(irregular_points[:, 0, np.newaxis])
clusters_y = kmeans_y.predict(irregular_points[:, 1, np.newaxis])

regular_points_x = kmeans_x.cluster_centers_[clusters_x]
regular_points_y = kmeans_y.cluster_centers_[clusters_y]

regular_points = np.asarray([[regular_points_x[i], regular_points_y[i]] for i in range(irregular_points.shape[0])])
>>>
array([[[ 0.99      ,  5.1       ],
        [ 0.99      ,  7.        ],
        [ 0.99      ,  9.        ],
        [ 0.99      , 11.03333333],
        [ 0.99      , 13.        ]],

       [[ 1.99      ,  5.1       ],
        [ 1.99      ,  7.        ],
        [ 1.99      ,  9.        ],
        [ 1.99      , 11.03333333],
        [ 1.99      , 13.        ]],

       [[ 3.04      ,  5.1       ],
        [ 3.04      ,  7.        ],
        [ 3.04      ,  9.        ],
        [ 3.04      , 11.03333333],
        [ 3.04      , 13.        ]]])

</code>```

Body:
I have a numpy array of x and y coordinates and want to make it regular. The array is sorted based on its x values (first column):

import numpy as np
Irregular_points = np.array([[1.1,5.], [0.85,7.1], [0.9,9], [1.1,11], [1.,13.1],
                   [1.9,5.2], [2.,6.9], [1.95,9], [2.1,11.1], [2.,13.1],
                   [3.0,5.1], [3.1,7.0], [3.,9], [3.0,11.], [3.1,12.8]])

I want to firtly find out which points have almost the same x values: it will be the first five rows, middle five rows and last five rows. One signal for finding these points is that y value decreases when I go to the next group. Then, I want to replace the x values of each group with the average value. For example in the fisrt five rows x values are 1.1, 0.85, 0.9, 1.1 and 1. and the average is 0.98. I want to do the same for next two parts.

For y values I again want to find similar ones which fall into five groups and then replace them with average of each group. y values of the first group are 5., 5.2 and 5.1 and average is 5.1. Finally, my points should be like the following array:

Regular_points = np.array([[0.98,5.1], [0.98,7.0], [0.98,9.0], [0.98,11.03], [0.98,13.0],
                   [1.98,5.1], [1.98,7.0], [1.98,9.0], [1.98,11.03], [1.98,13.0],
                   [3.04,5.1], [3.04,7.0], [3.04,9.0], [3.04,11.03], [3.04,13.0]])

I tried to round numbers but it did not work for real cases and I need to make these averages. I very much appreciate any help. The figure clearly shows what I want. Red dots are irregular points but by replacing averages, blue dots can be resulted.

Body:
You could use a cluster algorithm like KMeans:

import numpy as np
from sklearn.cluster import KMeans

irregular_points = np.array([[1.1,5.], [0.85,7.1], [0.9,9], [1.1,11], [1.,13.1],
                   [1.9,5.2], [2.,6.9], [1.95,9], [2.1,11.1], [2.,13.1],
                   [3.0,5.1], [3.1,7.0], [3.,9], [3.0,11.], [3.1,12.8]])

kmeans_x = KMeans(n_clusters=3).fit(irregular_points[:, 0, np.newaxis])
kmeans_y = KMeans(n_clusters=5).fit(irregular_points[:, 1, np.newaxis])

clusters_x = kmeans_x.predict(irregular_points[:, 0, np.newaxis])
clusters_y = kmeans_y.predict(irregular_points[:, 1, np.newaxis])

regular_points_x = kmeans_x.cluster_centers_[clusters_x]
regular_points_y = kmeans_y.cluster_centers_[clusters_y]

regular_points = np.asarray([[regular_points_x[i], regular_points_y[i]] for i in range(irregular_points.shape[0])])
>>>
array([[[ 0.99      ,  5.1       ],
        [ 0.99      ,  7.        ],
        [ 0.99      ,  9.        ],
        [ 0.99      , 11.03333333],
        [ 0.99      , 13.        ]],

       [[ 1.99      ,  5.1       ],
        [ 1.99      ,  7.        ],
        [ 1.99      ,  9.        ],
        [ 1.99      , 11.03333333],
        [ 1.99      , 13.        ]],

       [[ 3.04      ,  5.1       ],
        [ 3.04      ,  7.        ],
        [ 3.04      ,  9.        ],
        [ 3.04      , 11.03333333],
        [ 3.04      , 13.        ]]])


问:
Displaying website visitors on a map in real-time
I want to develop a webpage (in ASP.NET, C#) with a world map which can display pop-up bubbles whenever someone visits and logs in to our company's website. The bubbles should appear in real-time, and it should display the user's name and location.
Whenever the user logs in to our website, we have name and other personal information available in our database for that user.

Please suggest ways to implement this.

Thanks!

Updated:

By real-time update I mean a page with the map which gets refreshed as soon as any general public visits the home page, or one of our clients logs in to our website. These clients have login IDs provided by us to login to our website and they can be anywhere in the world.

Is there any way I can get to know when someone logs in to our website, and display the user's location on the map? Is it possible to do this without entering the login information in the database?

答:
If you want to zoom arbitrary in/out of map then you should use map web services from Google or Microsoft. All these services allows you to put some pin (or images/tags) at some longitude/latitudes in the map, so you can use that for showing bubbles.

If you are OK with fixed resolution maps - for example, with map of say of 1000x1000 pixels, you can only show location with that accuracy. If this is acceptable then you can go with such approach because it will be faster (because you can cache map images at browser side etc) because there can be some lag in accessing map services.

You need to define what do you mean by real time updates? Who will access your web page - general public over internet or some inside people on corporate n/w having great connectivity to your server? Essentially, you have two ways to propagate updates from web server to browser - either you can do polling (that firing a async web service from browser or refreshing the entire web page at periodic intervals) or you can use long running HTTP requests (aka COMET). Advantage with later is that updates can be more real time/frequent - there are few implementations available for ASP.NET - see this SO thread for the same: Comet implementation for ASP.NET?


问:
Draw dynamic Circle with connected line responsive
i wanted to create a circle with connected Line responsive design

when i resize the screen

But my expectation would be like this can anyone help me?

here is my code of HTML and CSS:

 M1

 M2

 M3

 M4

 M5

 M6

 M7

 M8

 M9

 M10

 M11

```
</div>
</div>
</p>
<p>its dynamic data using angular.
for Example</p>
```

 {{a.code}}

```

答:
If you know what break points you want (ie at what width you want to have what number of columns) this can be done in pure CSS.

This snippet has two sets. The first is for widths >600px and the second for widths <=600px with 10 columns per row in the first set and 5 columns per row in the second set.

It uses a grid and reverses the order of columns occupied by alternate rows using the CSS nth-child facility.

<!doctype html>

  <meta name="viewport" content="width=device-width, initial-scale=1">

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

```

Note: this answer builds on and partly generalises the answer to the question at Draw Circle with connected line responsive which had more specific, i.e. limiting, conditions.

Body:
i wanted to create a circle with connected Line responsive design

when i resize the screen

But my expectation would be like this can anyone help me?

here is my code of HTML and CSS:

 M1

 M2

 M3

 M4

 M5

 M6

 M7

 M8

 M9

 M10

 M11

its dynamic data using angular.
for Example

 {{a.code}}

Body:
If you know what break points you want (ie at what width you want to have what number of columns) this can be done in pure CSS.

This snippet has two sets. The first is for widths >600px and the second for widths <=600px with 10 columns per row in the first set and 5 columns per row in the second set.

It uses a grid and reverses the order of columns occupied by alternate rows using the CSS nth-child facility.

<!doctype html>
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    body {
      width: 100vw;
    }

    .container {
      display: flex;
      justify-content: center;
      width: 90vw;
      margin: 0 auto;
    }

    .circles {
      width: 100%;
      display: grid;
      grid-template-columns: repeat(var(--cols), 1fr);
      --gap: 4vw;
      gap: var(--gap);
      grid-auto-flow: dense;
    }

    .circles>* {
      width: 100%;
      background-color: navy;
      color: white;
      border-radius: 50%;
      display: flex;
      justify-content: center;
      align-items: center;
      aspect-ratio: 1 / 1;
      display inline-block;
      position: relative;
    }

    .circles>*::after {
      content: '';
      position: absolute;
      width: var(--gap);
      height: 1px;
      background-color: navy;
      top: 50%;
      transform: translateY(-50%);
      left: 100%;
    }

    @media (min-width: 600px) {
      .circles {
        --cols: 10;
      }
      .circles>*:nth-child(20n-10)::after {
        top: 100%;
        left: 50%;
        transform: translateX(-50%);
        height: var(--gap);
        width: 1px;
      }
      .circles>*:nth-child(20n-9) {
        grid-column: 10;
      }
      .circles>*:nth-child(20n-9)::after {
        display: none;
      }
      .circles>*:nth-child(20n-8) {
        grid-column: 9;
      }
      .circles>*:nth-child(20n-7) {
        grid-column: 8;
      }
      .circles>*:nth-child(20n-6) {
        grid-column: 7;
      }
      .circles>*:nth-child(20n-5) {
        grid-column: 6;
      }
      .circles>*:nth-child(20n-4) {
        grid-column: 5;
      }
      .circles>*:nth-child(20n-3) {
        grid-column: 4;
      }
      .circles>*:nth-child(20n-2) {
        grid-column: 3;
      }
      .circles>*:nth-child(20n-1) {
        grid-column: 2;
      }
      .circles>*:nth-child(20n) {
        grid-column: 1;
      }
      .circles>*:nth-child(20n-8):last-child::after,
      .circles>*:nth-child(20n-7):last-child::after,
      .circles>*:nth-child(20n-6):last-child::after,
      .circles>*:nth-child(20n-5):last-child::after,
      .circles>*:nth-child(20n-4):last-child::after,
      .circles>*:nth-child(20n-3):last-child::after,
      .circles>*:nth-child(20n-2):last-child::after,
      .circles>*:nth-child(20n-1):last-child::after,
      .circles>*:nth-child(20n):last-child::after {
        display: inline-block;
      }
      .circles>*:nth-child(20n+1)::before {
        display: inline-block;
        left: 50%;
        transform: translate(-50%, -100%);
        width: 1px;
        height: var(--gap);
        top: 0;
        content: '';
        position: absolute;
        background-color: navy;
      }
    }

    @media (max-width: 600px) {
      .circles {
        --cols: 5;
      }
      .circles>*:nth-child(10n-5)::after {
        top: 100%;
        left: 50%;
        transform: translateX(-50%);
        height: var(--gap);
        width: 1px;
      }
      .circles>*:nth-child(10n-4) {
        grid-column: 5;
      }
      .circles>*:nth-child(10n-4)::after {
        display: none;
      }
      .circles>*:nth-child(10n-3) {
        grid-column: 4;
      }
      .circles>*:nth-child(10n-2) {
        grid-column: 3;
      }
      .circles>*:nth-child(10n-1) {
        grid-column: 2;
      }
      .circles>*:nth-child(10n) {
        grid-column: 1;
      }
      .circles>*:nth-child(10n-3):last-child::after,
      .circles>*:nth-child(10n-2):last-child::after,
      .circles>*:nth-child(10n-1):last-child::after,
      .circles>*:nth-child(10n):last-child::after {
        display: inline-block;
      }
      .circles>*:nth-child(10n+1)::before {
        display: inline-block;
        left: 50%;
        transform: translate(-50%, -100%);
        width: 1px;
        height: var(--gap);
        top: 0;
        content: '';
        position: absolute;
        background-color: navy;
      }
    }

    .circles>*:first-child::before,
    .circles>*:last-child::after {
      display: none;
    }
  </style>
</head>

<body>
  <div class="container">
    <ul class="circles">
      <li>1</li>
      <li>2</li>
      <li>3</li>
      <li>4</li>
      <li>5</li>
      <li>6</li>
      <li>7</li>
      <li>8</li>
      <li>9</li>
      <li>10</li>
      <li>11</li>
      <li>12</li>
      <li>13</li>
      <li>14</li>
      <li>15</li>
      <li>16</li>
      <li>17</li>
      <li>18</li>
      <li>19</li>
      <li>20</li>
      <li>21</li>
      <li>22</li>
      <li>23</li>
    </ul>
  </div>
</body>

</html>

Note: this answer builds on and partly generalises the answer to the question at Draw Circle with connected line responsive which had more specific, i.e. limiting, conditions.


问:
Full image is not showing in the background
I have a image which I want to completely show as background image .

As you can see in the below image , the girl & the dog is not completely shown:

original image

Is there any css property to completely so the image as the background ? or I have to resize the image ?

Here's my css:

```<code>*{
      margin: 0;
      padding: 0;
}
body{
      background-image: url('../public/images/bg0.jpg');
      height: 100vh;
      background-repeat: no-repeat;
      background-size: cover;
      object-fit: contain;
      transition: background-image 1.5s linear;
}
#__next{
      height: 100%;
}
</code>```

答: Using "background-size: cover;" the browser will expand the background photo so it will cover the whole website body. You could use "background-size: contain;" to see the whole image, but it will not cover the whole website. The best solution is to resize the image.</p>

Body:
I have a image which I want to completely show as background image .

As you can see in the below image , the girl & the dog is not completely shown:

original image

Is there any css property to completely so the image as the background ? or I have to resize the image ?

Here's my css:

*{
      margin: 0;
      padding: 0;
}
body{
      background-image: url('../public/images/bg0.jpg');
      height: 100vh;
      background-repeat: no-repeat;
      background-size: cover;
      object-fit: contain;
      transition: background-image 1.5s linear;
}
#__next{
      height: 100%;
}


问:
error in replaceAll() method
i have error in String st=str.replaceAll(" ","");
But include the import java.lang.String.*;
After adding this line again same error repeated..
So please anyone help me to solve the error..

```<code>String st=str.replaceAll(" ","");
</code>```

答:
If I understood you properly, you used the line twice, like this:

```<code>// in scope of some method:
String st=str.replaceAll(" ","");
//....
String st=str.replaceAll(" ","");
</code>```

This is not legal, because you declared a variable with the same name in the same scope twice, instead, it should be:

```<code>// in scope of some method:
String st=str.replaceAll(" ","");
//....
st=str.replaceAll(" ","");
</code>```

or:

```<code>// in scope of some method:
String st=str.replaceAll(" ","");
//....
String st1=str.replaceAll(" ","");
</code>```

Title: error in replaceAll() method

Body:
i have error in String st=str.replaceAll(" ","");
But include the import java.lang.String.*;
After adding this line again same error repeated..
So please anyone help me to solve the error..

String st=str.replaceAll(" ","");

Body:
If I understood you properly, you used the line twice, like this:

// in scope of some method:
String st=str.replaceAll(" ","");
//....
String st=str.replaceAll(" ","");

This is not legal, because you declared a variable with the same name in the same scope twice, instead, it should be:

// in scope of some method:
String st=str.replaceAll(" ","");
//....
st=str.replaceAll(" ","");

or:

// in scope of some method:
String st=str.replaceAll(" ","");
//....
String st1=str.replaceAll(" ","");


问:
Open a new Firefox Window with a Profile already open | Bash, Linux
I want to create a Macro so that I can open frequently used websites.
I have a studying macro and a personal macro. The code looks like this:

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

firefox -P "Profile A" -no-remote -new-tab -url "link" -new-tab -url "link" -new-tab -url "link" &
</code>```

However, if I want to run this script with a Profile thats already open I get the following error

Firefox is already running, but is not responding. To use Firefox, you
must first close the existing Firefox process, restart your device, or
use a different profile.

I want to be able to open tabs with an already opened profile

What should I do?

PS: Running Ubuntu (POP OS)

答:
I removed the option -no-remote from my KDE desktop shortcuts (I use different profiles), scripts and keystroke associations and that fixed the problem.

The other options you are using to invoke firefox should work as expected.

Body:
I want to create a Macro so that I can open frequently used websites.
I have a studying macro and a personal macro. The code looks like this:

#!/usr/bin/bash

firefox -P "Profile A" -no-remote -new-tab -url "link" -new-tab -url "link" -new-tab -url "link" &

However, if I want to run this script with a Profile thats already open I get the following error

Firefox is already running, but is not responding. To use Firefox, you
must first close the existing Firefox process, restart your device, or
use a different profile.

I want to be able to open tabs with an already opened profile

What should I do?

PS: Running Ubuntu (POP OS)


问:
How to update kdb table transversely
I have these two tables:

```<code>tab:([]col1:`abc`def`ghe`abc;val_00:`a`b`c`e;val_01:`d`e`f`t;val_02:`g`h`e`g;val_03:`r`t`y`o)
tab2:([]col1:`abc`abc`abc`abc`def`def`def`ghe`ghe`ghe;col2:0 1 2 3 4 5 6 7 8 9;col3:`Ashley`Peter`John`Molly`Apple`Orange`Banana`Robin`Tony`Bob)
</code>```

and this is the result I am looking for:

```<code>tabResult:([]col1:`abc`def`ghe`abc;val_00:`Ashley`b`c`Ashley;val_01:`Peter`e`f`Peter;val_02:`John`h`e`John;val_03:`Molly`t`y`Molly)

    col1    val_00  val_01  val_02  val_03
    abc     Ashley  Peter   John    Molly
    def     b       e        h      t
    ghe     c       f        e      y
    abc     Ashley  Peter   John    Molly
</code>```

I would like to update tab depending on tab2. If col1=`abc,col2=1</code> in <code>tab2</code>, I would like to update <code>val_01</code> to <code>`Peter in tab, and if col1 =`abc,col2=2</code> in <code>tab2</code>, I would like to update <code>val_02</code> field with <code>`John in tab etc.

This is what I have so far:

```<code>{![tab;enlist(=;`col1;enlist x);0b;(enlist y)!enlist z]} . (`abc;`val_01;)
</code>```

The function above works if the field is numerical and I use a number as the last arg. However, I am not sure how to update symbols and how to generalise this function for all tables.

答:
If I'm understanding your request correctly, you're trying to update a field that has a long type with values that are of symbol type. This is going to fail with a 'type error as column values are expected to be uniform in type. What you can alternatively do is create new columns for the symbol entries, and after that select the columns you want.

Is something like this what you had in mind? I've assumed that the column name is determined by its col2 value in tab. Also it looks like you have two val_01 columns in your tab input, I assumed one of these was supposed to be val_02.

```<code>q)(uj/){![tab;enlist(=;`col1;enlist x);0b;(enlist`$"val_0",string[y],"_sym")!enlist enlist z]}.'flip tab2`col1`col2`col3
col1 val_00 val_01 val_02 val_03 val_01_sym val_02_sym val_03_sym val_04_sym val_05_sym val_06_sym val_07_sym val_08_sym val_09_sym
-----------------------------------------------------------------------------------------------------------------------------------
abc  1      2      2      3      Peter
def  2      2      3      2
ghe  3      3      1      1
abc  1      2      2      3                 John
def  2      2      3      2
ghe  3      3      1      1
abc  1      2      2      3                            Molly
def  2      2      3      2
ghe  3      3      1      1
abc  1      2      2      3
def  2      2      3      2                                       Apple
ghe  3      3      1      1
abc  1      2      2      3
def  2      2      3      2                                                  Orange
ghe  3      3      1      1
abc  1      2      2      3
def  2      2      3      2                                                             Banana
ghe  3      3      1      1
abc  1      2      2      3
def  2      2      3      2
ghe  3      3      1      1                                                                        Robin
abc  1      2      2      3
def  2      2      3      2
ghe  3      3      1      1                                                                                Tony
abc  1      2      2      3
def  2      2      3      2
ghe  3      3      1      1                                                                                Bob
</code>```

EDIT:

Based on your comments, I've amended my solution:

```<code>q)cols[tab]#{![x;enlist(=;`col1;enlist y`col1);0b;(enlist`$"val_0",string y`col2)!enlist enlist y`col3]}/[tab;tab2]
col1 val_00 val_01 val_02 val_03
--------------------------------
abc  Ashley Peter  John   Molly
def  b      e      h      t
ghe  c      f      e      y
abc  Ashley Peter  John   Molly
</code>```

Title: How to update kdb table transversely

Body:
I have these two tables:

tab:([]col1:`abc`def`ghe`abc;val_00:`a`b`c`e;val_01:`d`e`f`t;val_02:`g`h`e`g;val_03:`r`t`y`o)
tab2:([]col1:`abc`abc`abc`abc`def`def`def`ghe`ghe`ghe;col2:0 1 2 3 4 5 6 7 8 9;col3:`Ashley`Peter`John`Molly`Apple`Orange`Banana`Robin`Tony`Bob)

and this is the result I am looking for:

tabResult:([]col1:`abc`def`ghe`abc;val_00:`Ashley`b`c`Ashley;val_01:`Peter`e`f`Peter;val_02:`John`h`e`John;val_03:`Molly`t`y`Molly)

    col1    val_00  val_01  val_02  val_03
    abc     Ashley  Peter   John    Molly
    def     b       e        h      t
    ghe     c       f        e      y
    abc     Ashley  Peter   John    Molly

I would like to update tab depending on tab2. If col1=`abc,col2=1</code> in <code>tab2</code>, I would like to update <code>val_01</code> to <code>`Peter in tab, and if col1 =`abc,col2=2</code> in <code>tab2</code>, I would like to update <code>val_02</code> field with <code>`John in tab etc.

This is what I have so far:

{![tab;enlist(=;`col1;enlist x);0b;(enlist y)!enlist z]} . (`abc;`val_01;)

The function above works if the field is numerical and I use a number as the last arg. However, I am not sure how to update symbols and how to generalise this function for all tables.

Body:
If I'm understanding your request correctly, you're trying to update a field that has a long type with values that are of symbol type. This is going to fail with a 'type error as column values are expected to be uniform in type. What you can alternatively do is create new columns for the symbol entries, and after that select the columns you want.

Is something like this what you had in mind? I've assumed that the column name is determined by its col2 value in tab. Also it looks like you have two val_01 columns in your tab input, I assumed one of these was supposed to be val_02.

q)(uj/){![tab;enlist(=;`col1;enlist x);0b;(enlist`$"val_0",string[y],"_sym")!enlist enlist z]}.'flip tab2`col1`col2`col3
col1 val_00 val_01 val_02 val_03 val_01_sym val_02_sym val_03_sym val_04_sym val_05_sym val_06_sym val_07_sym val_08_sym val_09_sym
-----------------------------------------------------------------------------------------------------------------------------------
abc  1      2      2      3      Peter
def  2      2      3      2
ghe  3      3      1      1
abc  1      2      2      3                 John
def  2      2      3      2
ghe  3      3      1      1
abc  1      2      2      3                            Molly
def  2      2      3      2
ghe  3      3      1      1
abc  1      2      2      3
def  2      2      3      2                                       Apple
ghe  3      3      1      1
abc  1      2      2      3
def  2      2      3      2                                                  Orange
ghe  3      3      1      1
abc  1      2      2      3
def  2      2      3      2                                                             Banana
ghe  3      3      1      1
abc  1      2      2      3
def  2      2      3      2
ghe  3      3      1      1                                                                        Robin
abc  1      2      2      3
def  2      2      3      2
ghe  3      3      1      1                                                                                Tony
abc  1      2      2      3
def  2      2      3      2
ghe  3      3      1      1                                                                                Bob

EDIT:

Based on your comments, I've amended my solution:

q)cols[tab]#{![x;enlist(=;`col1;enlist y`col1);0b;(enlist`$"val_0",string y`col2)!enlist enlist y`col3]}/[tab;tab2]
col1 val_00 val_01 val_02 val_03
--------------------------------
abc  Ashley Peter  John   Molly
def  b      e      h      t
ghe  c      f      e      y
abc  Ashley Peter  John   Molly


问:
Angular - using a date pipe with ngModel
I am getting the following error in my console - "Error: InvalidPipeArgument: 'Unable to convert "[object Object]" into a date' for pipe 'DatePipe'".

I have a calendar input, which should allow the user to select a date and then pass on that date in a certain format, 'dd/MM/yyyy'. I want the date selected to show in the calendar input once they have selected a date.

I realise I cannot have two way binding on the [ngModel] if I have a pipe there so I'm using
(ngModelChange). If I remove the #createdByCutOffDate="ngModel" then the error is removed but I cannot see the selected date show in the calendar input.

I also tried the updateCreatedByCutOffDate() method taking a date type or string.

this.createdByCutOffDate is in the following format - 'Thu Feb 17 2022 00:00:00 GMT+0000 (Greenwich Mean Time)'

component.html

```<code>
<input type="date"
       id="createdByCutOffDate"
       [ngModel]="createdByCutOffDate | date:'dd/MM/yyyy'"
       #createdByCutOffDate="ngModel"
       (ngModelChange)="updateCreatedByCutOffDate($event)" />
</code>```

component.ts

```<code>
createdByCutOffDate: Date;

updateCreatedByCutOffDate(date: string) {
    this.createdByCutOffDate = new Date(date);

    }
</code>```

答:
createdByCutOffDate is a Date object that has its methods and properties.

So to solve your problem, use "createdByCutOffDate.date | date:'dd/MM/yyyy'" instead of "createdByCutOffDate | date:'dd/MM/yyyy'"

Body:
I am getting the following error in my console - "Error: InvalidPipeArgument: 'Unable to convert "[object Object]" into a date' for pipe 'DatePipe'".

I have a calendar input, which should allow the user to select a date and then pass on that date in a certain format, 'dd/MM/yyyy'. I want the date selected to show in the calendar input once they have selected a date.

I realise I cannot have two way binding on the [ngModel] if I have a pipe there so I'm using
(ngModelChange). If I remove the #createdByCutOffDate="ngModel" then the error is removed but I cannot see the selected date show in the calendar input.

I also tried the updateCreatedByCutOffDate() method taking a date type or string.

this.createdByCutOffDate is in the following format - 'Thu Feb 17 2022 00:00:00 GMT+0000 (Greenwich Mean Time)'

component.html

<input type="date"
       id="createdByCutOffDate"
       [ngModel]="createdByCutOffDate | date:'dd/MM/yyyy'"
       #createdByCutOffDate="ngModel"
       (ngModelChange)="updateCreatedByCutOffDate($event)" />

component.ts

createdByCutOffDate: Date;

updateCreatedByCutOffDate(date: string) {
    this.createdByCutOffDate = new Date(date);

    }


问:
Email Validation ASP.NET WebForms Border
I have textbox and two validation (RequiredFieldValidator & RegularExpressionValidator) as bellow

```<code><asp:TextBox runat="server" ID="txtEmailFrom" CssClass="form-control"></asp:TextBox>
<asp:RequiredFieldValidator
    ID="RequiredFieldValidator3"
    runat="server"
    ErrorMessage="Field Required"
    ControlToValidate="txtEmailFrom"
    Display="Dynamic"
    ForeColor="Red"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator
    ID="regexEmailValid"
    runat="server"
    ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
    ControlToValidate="txtEmailFrom"
    ForeColor="Red"
    Display="Dynamic"
    ErrorMessage="Invalid Email Format"></asp:RegularExpressionValidator>
</code>```

But with error I need the border of field to highlight with red. And for that the code bellow is written:

```<code>function ValidatorUpdateDisplay(val) {
        if (typeof (val.display) == "string") {
            if (val.display == "None") {
                return;
            }
            if (val.display == "Dynamic") {
                val.style.display = val.isvalid ? "none" : "inline";
                return;
            }
        }
        val.style.visibility = val.isvalid ? "hidden" : "visible";
        if (val.isvalid) {
            document.getElementById(val.controltovalidate).style.border = '1px solid #333';
        }
        else {
            document.getElementById(val.controltovalidate).style.border = '1px solid red';
        }
    }
</code>```

The function is working only with RequiredFieldValidatior. I need to work with both (RequiredFieldValidator & RegularExpressionValidator) validation.

Thank you in advance.

答:
Maybe you can set a breakpoint in your javascript function?

I suspect it gets called twice. You are using two validators on your ControlToValidate, one of them is valid, the other invalid. The javascript gets executed once by every validator, it handles both the situation where a validator is not valid, and where one is valid.

So apparently in your case the RequiredFieldValidator 'wins' and gets executed last.

I don't think overriding the framework function ValidatorUpdateDisplay is the right choice here. Given you are using ASP.NET WebForms, maybe an option is to include the Ajax Control Toolkit. It has a ValidatorCallout extension. I assume you could use this extension also without the 'callout', but only the HighlightCssClass-option.

http://www.ajaxtoolkit.net/ValidatorCallout/ValidatorCallout.aspx

Body:
I have textbox and two validation (RequiredFieldValidator & RegularExpressionValidator) as bellow

<asp:TextBox runat="server" ID="txtEmailFrom" CssClass="form-control"></asp:TextBox>
<asp:RequiredFieldValidator
    ID="RequiredFieldValidator3"
    runat="server"
    ErrorMessage="Field Required"
    ControlToValidate="txtEmailFrom"
    Display="Dynamic"
    ForeColor="Red"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator
    ID="regexEmailValid"
    runat="server"
    ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
    ControlToValidate="txtEmailFrom"
    ForeColor="Red"
    Display="Dynamic"
    ErrorMessage="Invalid Email Format"></asp:RegularExpressionValidator>

But with error I need the border of field to highlight with red. And for that the code bellow is written:

function ValidatorUpdateDisplay(val) {
        if (typeof (val.display) == "string") {
            if (val.display == "None") {
                return;
            }
            if (val.display == "Dynamic") {
                val.style.display = val.isvalid ? "none" : "inline";
                return;
            }
        }
        val.style.visibility = val.isvalid ? "hidden" : "visible";
        if (val.isvalid) {
            document.getElementById(val.controltovalidate).style.border = '1px solid #333';
        }
        else {
            document.getElementById(val.controltovalidate).style.border = '1px solid red';
        }
    }

The function is working only with RequiredFieldValidatior. I need to work with both (RequiredFieldValidator & RegularExpressionValidator) validation.

Thank you in advance.


问:
Android Studio emulator System UI keeps crashing every 10 or so hours of use
I'm using Android Studio Arctic Fox 2020.3.1 Patch 4 to run an emulator for developing a react-native app. For some reason the emulator starts freezing and misbehaving after around 10 hours of work. It keeps displaying a message about the System UI not responding and gives me an option to wait or to close the program. Whatever I do it keeps appearing.

I usually fix it by wiping the emulators data from the AVD manager in Android Studio, but it's a big waste of time since I have to reinstall expo and start the whole phone from 0.

Thank you in advance.

答:
Try these.

Restart android studio and computer.

In android studio go to files invalidate cache and restart.

Create another AVD.

otherwise you need to use physical device.


问:
I have a mistake for the installation of Matplotlib
When I try to install matplotlib with the command pip install matplotlib
I have this erreur :

```<code>WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1129)'))': /simple/matplotlib/
Could not fetch URL https://pypi.org/simple/matplotlib/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/matplotlib/ (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1129)'))) - skipping
ERROR: Could not find a version that satisfies the requirement matplotlib (from versions: none)
ERROR: No matching distribution found for matplotlib
</code>```

I use python 3.9.5 64-bit, pip 21.1.2 and I use a Macbook M1 (I don't know if it's important). I have to use matplotlib for my science class and I don't understand this mistake.
thank you in advance for your answers !

答:
Try this command</p>
```<code>pip install matplotlib --trusted-host pypi.org
</code>```

Body:
When I try to install matplotlib with the command pip install matplotlib
I have this erreur :

WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1129)'))': /simple/matplotlib/
Could not fetch URL https://pypi.org/simple/matplotlib/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/matplotlib/ (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1129)'))) - skipping
ERROR: Could not find a version that satisfies the requirement matplotlib (from versions: none)
ERROR: No matching distribution found for matplotlib

I use python 3.9.5 64-bit, pip 21.1.2 and I use a Macbook M1 (I don't know if it's important). I have to use matplotlib for my science class and I don't understand this mistake.
thank you in advance for your answers !

Body:
Try this command

pip install matplotlib --trusted-host pypi.org


问:
How to put a newline in ant property
This doesn't seem to work:

```<code><property name="foo" value="\n bar \n"/>
</code>```

I use the property value in the body of an e-mail message (which is sent as plain text):

```<code><mail ...>
  <message>some text${foo}</message>
</code>```

and I get literal "\n" in the e-mail output.

答:
These all work for me:</p>

```<code><property name="foo" value="bar${line.separator}bazz"/>

<property name="foo">bar
bazz2</property>

<property name="foo" value="bar
bazz"/>
</code>```

Title: How to put a newline in ant property

Body:
This doesn't seem to work:

<property name="foo" value="\n bar \n"/>

I use the property value in the body of an e-mail message (which is sent as plain text):

<mail ...>
  <message>some text${foo}</message>

and I get literal "\n" in the e-mail output.

Body:
These all work for me:

<property name="foo" value="bar${line.separator}bazz"/>

<property name="foo">bar
bazz2</property>

<property name="foo" value="bar&#10;bazz"/>


问:
map() function throwing null error for response in Angular 6
I am trying to implement Angular 2 code in Angular 6 app and below is the code I am trying to implement.

https://www.c-sharpcorner.com/article/server-side-paging-in-kendo-grid-for-angular-2/

In the below code, I am getting error as null for json

private getEmployee(state: any): Observable<GridDataResult>{
    let params = new URLSearchParams();
    params.set('Skip', state.skip);
    params.set('Take', state.take)
    return this.http
        .get(this.BASE_URL, { search: params })
        .map(response => response.json())
        .map(response => (<GridDataResult>{
            data: response.EmployeeList,
            total: response.Count
        }));

}
```
<p>The error is as below when I run the app</p>
<p><img src="https://i.stack.imgur.com/kR7le.jpg" alt="Json Error" /></p>
<p>Could you please tell me why it is throwing these 2 errors</p>
<p>Here is the subscription for the above code snippet.</p>
```public query(state): void {
    this.getEmployee(state)
        .subscribe(x =>super.next(x));
}
```
<p>In the <code>C#</code> code, I am return the <code>data</code> and <code>total</code> as below...</p>
```if (resultList.Count > 0)
{
    var result = new
    {
        data = resultList.ToArray(),
        total= resultList[0].TotalRecords
    };
    var jsonData = JsonConvert.SerializeObject(result);
    return jsonData;
}
```

I get the below error when I implemented as you suggested @StepUp

EDIT

It is not able to recognize the data we get from dataJson as mentioned in the Answer because it is a constant. Should we need to create a mapping class in Angular side?

答:
I'm more used to Promises so here is my way of implementation with Promises :

```<code>private async getEmployee(state: any): Promise<GridDataResult> {
  let params = new URLSearchParams();
  params.set('Skip', state.skip);
  params.set('Take', state.take);
  const dataJson = await this.http.get(this.BASE_URL, { search: params }).toPromise();

  // Don't forget to check if dataJson is null, otherwise dataJson.EmployeeList will throw
  // EDIT
  const dataGridResult: GridDataResult = {
        data: dataJson.EmployeeList,
        total: dataJson.Count
  }

  return dataGridResult;

 }

public async query(state): Promise<void> {
    const dataGridResult:GridDataResult = await this.getEmployee(state);
    super.next(dataGridResult);
}
</code>```

EDIT

I added a type <{ EmployeeList: any[], Count: any}> with properties typed with any. Replace it by something more precise if possible.

```<code>const dataJson = <{ EmployeeList: any[], Count: any}> await this.http.get(this.BASE_URL, { search: params }).toPromise();
</code>```

Body:
I am trying to implement Angular 2 code in Angular 6 app and below is the code I am trying to implement.

https://www.c-sharpcorner.com/article/server-side-paging-in-kendo-grid-for-angular-2/

In the below code, I am getting error as null for json

private getEmployee(state: any): Observable<GridDataResult>{
    let params = new URLSearchParams();
    params.set('Skip', state.skip);
    params.set('Take', state.take)
    return this.http
        .get(this.BASE_URL, { search: params })
        .map(response => response.json())
        .map(response => (<GridDataResult>{
            data: response.EmployeeList,
            total: response.Count
        }));

}

The error is as below when I run the app

Could you please tell me why it is throwing these 2 errors

Here is the subscription for the above code snippet.

public query(state): void {
    this.getEmployee(state)
        .subscribe(x =>super.next(x));
}

In the C# code, I am return the data and total as below...

if (resultList.Count > 0)
{
    var result = new
    {
        data = resultList.ToArray(),
        total= resultList[0].TotalRecords
    };
    var jsonData = JsonConvert.SerializeObject(result);
    return jsonData;
}

I get the below error when I implemented as you suggested @StepUp

EDIT

It is not able to recognize the data we get from dataJson as mentioned in the Answer because it is a constant. Should we need to create a mapping class in Angular side?

Body:
I'm more used to Promises so here is my way of implementation with Promises :

private async getEmployee(state: any): Promise<GridDataResult> {
  let params = new URLSearchParams();
  params.set('Skip', state.skip);
  params.set('Take', state.take);
  const dataJson = await this.http.get(this.BASE_URL, { search: params }).toPromise();

  // Don't forget to check if dataJson is null, otherwise dataJson.EmployeeList will throw
  // EDIT
  const dataGridResult: GridDataResult = {
        data: dataJson.EmployeeList,
        total: dataJson.Count
  }

  return dataGridResult;

 }

public async query(state): Promise<void> {
    const dataGridResult:GridDataResult = await this.getEmployee(state);
    super.next(dataGridResult);
}

EDIT

I added a type <{ EmployeeList: any[], Count: any}> with properties typed with any. Replace it by something more precise if possible.

const dataJson = <{ EmployeeList: any[], Count: any}> await this.http.get(this.BASE_URL, { search: params }).toPromise();


问:
Full video background using video.js
I'm trying to make a full screen video background that always shows the full size even on window resize.

here it's the site:
http://webkunst.comeze.com/test/

this is the problem I have:

on wide screen it shows like this:
http://webkunst.comeze.com/test/wide.png

and on vertical screen it shows like this:
http://webkunst.comeze.com/test/vertical.png

As you can see it always put some black bars to the video instead of resizing the video to the full of the screen.

This is my markup:

```<code>           <div id="full-background">
                <video class="video-js vjs-fullscreen"  autoplay preload="auto"  poster="http://video-js.zencoder.com/oceans-clip.png" data-setup="{}">
                    <source src="video/1.mp4" type='video/mp4' />
                </video>
            </div>
</code>```

with this css:

```<code>#full-background {
  z-index: -999;
  min-height: 100%;
  min-width: 1024px;
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
}

.video-js.vjs-fullscreen {
  position: fixed;
  overflow: hidden;
  z-index: 1000;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  width: 100% !important;
  height: 100% !important;
  _position: absolute;
  /* IE6 Full-window (underscore hack) */

}
</code>```

I'm using the video.js plugin:
http://videojs.com/

Any ideas and how to make the video full size without showing black bars on the side or top/bottom?

答:
Use object-fit. Don't forget to set a height for the parent div.</p>
```<code> .video-js {
    width: 100%;
    height: 100%;
  }
  .video-js .vjs-tech {
    object-fit: cover;
  }
</code>```

Title: Full video background using video.js

Body:
I'm trying to make a full screen video background that always shows the full size even on window resize.

here it's the site:
http://webkunst.comeze.com/test/

this is the problem I have:

on wide screen it shows like this:
http://webkunst.comeze.com/test/wide.png

and on vertical screen it shows like this:
http://webkunst.comeze.com/test/vertical.png

As you can see it always put some black bars to the video instead of resizing the video to the full of the screen.

This is my markup:

                <video class="video-js vjs-fullscreen"  autoplay preload="auto"  poster="http://video-js.zencoder.com/oceans-clip.png" data-setup="{}">
                    <source src="video/1.mp4" type='video/mp4' />
                </video>

with this css:

#full-background {
  z-index: -999;
  min-height: 100%;
  min-width: 1024px;
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
}

.video-js.vjs-fullscreen {
  position: fixed;
  overflow: hidden;
  z-index: 1000;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  width: 100% !important;
  height: 100% !important;
  _position: absolute;
  /* IE6 Full-window (underscore hack) */

}

I'm using the video.js plugin:
http://videojs.com/

Any ideas and how to make the video full size without showing black bars on the side or top/bottom?

Body:
Use object-fit. Don't forget to set a height for the parent div.

 .video-js {
    width: 100%;
    height: 100%;
  }
  .video-js .vjs-tech {
    object-fit: cover;
  }


问:
Using the space next to tabs for displaying text and images
I have a QTabWidget as my 'central widget' and I would like to use the space that's left over after the tabs have been placed for displaying some text and an image (area in blue below):

I'm looking for pointers to solutions that will allow me to best make use this space; any ideas?

答: You can separate the QTabWidget into a QTabBar and a QStackedWidget, and connect them using connect(tab_bar, &QTabBar::currentChanged, stacked_widget, &QStackedWidget::setCurrentIndex);. Then, you can add whatever next to the tab bar like this.


问:
Adding 2 IconButtons next to the image
I'm having a problem with my project. I need confirmation from the user for the location of this image. I want to make an object like this, would you be an investor?enter image description here</p>

答:
Here is pseudo code</p>
```<code>Column(
    Image(),
    Row(
        Button(),
        Button(),
    )
)
</code>```

Title: Adding 2 IconButtons next to the image

Body:
Here is pseudo code

Column(
    Image(),
    Row(
        Button(),
        Button(),
    )
)


问:
Insert plugin into a fluid template?
The extension ke_search has a search field plugin that I want to insert into my fluidtemplate and show on every page. I am very new in this and don't know how to start. Any help is appreciated.</p>

答:
There is on more option if you only want the search input but no results e.g. in a header or footer. I could only test this in a TYPO3 11.5 with indexed_search though! The general approach might also work with ke_search.

My TypoScript setup:

```<code>plugin.tx_indexedsearch.settings {
    targetPid = 17
    displayAdvancedSearchLink = 0
}

lib.search = FLUIDTEMPLATE
lib.search{
    file = EXT:mysitepackage/Resources/Private/Partials/IndexedSearch/Form.html
    settings < plugin.tx_indexedsearch.settings
}

// Custom templates for indexed search.
plugin.tx_indexedsearch.view {
    templateRootPaths {
        0 = EXT:indexed_search/Resources/Private/Templates/
        10 = {$plugin.tx_indexedsearch.view.templateRootPath}
        20 = EXT:mysitepackage/Resources/Private/Templates/IndexedSearch/
    }

    partialRootPaths {
        0 = EXT:indexed_search/Resources/Private/Partials/
        10 = {$plugin.tx_indexedsearch.view.partialRootPath}
        20 = EXT:mysitepackage/Resources/Private/Partials/IndexedSearch/
    }
}
</code>```

Then I copied public/typo3/sysext/indexed_search/Resources/Private/Partials/Form.html to my folder public/typo3conf/ext/mysitepackage/Resources/Private/Partials/IndexedSearch/Form.html.

In the copied file you have to add some attributes to the form tag: extensionName="IndexedSearch", pluginName="pi2"and controller="Search" so that in the end the form tag looks like this:

```<code><f:form action="search" method="post" pageUid="{settings.targetPid}" extensionName="IndexedSearch" pluginName="pi2" controller="Search">
</code>```

Now you can add this to any fluid template to add a search input:

```<code><f:cObject typoscriptObjectPath="lib.search" />
</code>```

Title: Insert plugin into a fluid template?

Body:
There is on more option if you only want the search input but no results e.g. in a header or footer. I could only test this in a TYPO3 11.5 with indexed_search though! The general approach might also work with ke_search.

My TypoScript setup:

plugin.tx_indexedsearch.settings {
    targetPid = 17
    displayAdvancedSearchLink = 0
}

lib.search = FLUIDTEMPLATE
lib.search{
    file = EXT:mysitepackage/Resources/Private/Partials/IndexedSearch/Form.html
    settings < plugin.tx_indexedsearch.settings
}

// Custom templates for indexed search.
plugin.tx_indexedsearch.view {
    templateRootPaths {
        0 = EXT:indexed_search/Resources/Private/Templates/
        10 = {$plugin.tx_indexedsearch.view.templateRootPath}
        20 = EXT:mysitepackage/Resources/Private/Templates/IndexedSearch/
    }

    partialRootPaths {
        0 = EXT:indexed_search/Resources/Private/Partials/
        10 = {$plugin.tx_indexedsearch.view.partialRootPath}
        20 = EXT:mysitepackage/Resources/Private/Partials/IndexedSearch/
    }
}

Then I copied public/typo3/sysext/indexed_search/Resources/Private/Partials/Form.html to my folder public/typo3conf/ext/mysitepackage/Resources/Private/Partials/IndexedSearch/Form.html.

In the copied file you have to add some attributes to the form tag: extensionName="IndexedSearch", pluginName="pi2"and controller="Search" so that in the end the form tag looks like this:

<f:form action="search" method="post" pageUid="{settings.targetPid}" extensionName="IndexedSearch" pluginName="pi2" controller="Search">

Now you can add this to any fluid template to add a search input:

<f:cObject typoscriptObjectPath="lib.search" />


问:
How to change icon when accordion summary is expanded?
I want to change the icon based on whether the accordion is expanded or not.

I see that on the material ui page that the CSS have .Mui-expanded which can see whether expanded={true} or false, but how can I use this to set a different icon when expanded is true or false.

So I want to set IconA if expand is true and IconB if expand is false.

```<code>expandIcon={<IconA/>}
</code>```

答:
The solution mentioned above https://stackoverflow.com/a/63691313/11603006 is absolutely right but has the disadvantage that you must use a useState hook to show a different icon when the accordion is collapsed/expanded. This makes it however difficult (impossible?) to specify a custom expandIcon globally in the Theme. Therefore Mui should in my opinion pass the expand state to the expandIcon prop. There is a feature request for this https://github.com/mui/material-ui/issues/18326 but it has not been implemented yet. As a workaround and an alternative to the above solution, which has the benefit that it can be used in the theme globaly, it is possible to provide a custom icon in that way:

```<code>  const CustomExpandIcon = () => {
    return (
      <Box
        sx={{
          '.Mui-expanded & > .collapsIconWrapper': {
            display: 'none',
          },
          '.expandIconWrapper': {
            display: 'none',
          },
          '.Mui-expanded & > .expandIconWrapper': {
            display: 'block',
          },
        }}
      >
        <div className="expandIconWrapper">
          <MinusIcon />
        </div>
        <div className="collapsIconWrapper">
          <PlusIcon />
        </div>
      </Box>
    )
  }
</code>```

See: https://codesandbox.io/s/basicaccordion-material-demo-forked-2916o

Body:
I want to change the icon based on whether the accordion is expanded or not.

I see that on the material ui page that the CSS have .Mui-expanded which can see whether expanded={true} or false, but how can I use this to set a different icon when expanded is true or false.

So I want to set IconA if expand is true and IconB if expand is false.

expandIcon={<IconA/>}

Body:
The solution mentioned above https://stackoverflow.com/a/63691313/11603006 is absolutely right but has the disadvantage that you must use a useState hook to show a different icon when the accordion is collapsed/expanded. This makes it however difficult (impossible?) to specify a custom expandIcon globally in the Theme. Therefore Mui should in my opinion pass the expand state to the expandIcon prop. There is a feature request for this https://github.com/mui/material-ui/issues/18326 but it has not been implemented yet. As a workaround and an alternative to the above solution, which has the benefit that it can be used in the theme globaly, it is possible to provide a custom icon in that way:

  const CustomExpandIcon = () => {
    return (
      <Box
        sx={{
          '.Mui-expanded & > .collapsIconWrapper': {
            display: 'none',
          },
          '.expandIconWrapper': {
            display: 'none',
          },
          '.Mui-expanded & > .expandIconWrapper': {
            display: 'block',
          },
        }}
      >
        <div className="expandIconWrapper">
          <MinusIcon />
        </div>
        <div className="collapsIconWrapper">
          <PlusIcon />
        </div>
      </Box>
    )
  }

See: https://codesandbox.io/s/basicaccordion-material-demo-forked-2916o


问:
How do you add dataclasses as valid index values to a plotly chart?
I am trying to switch from the matplotlib pandas plotting backend to plotly. However, I am being held back by a common occurrence of this error:

```<code>TypeError: Object of type Quarter is not JSON serializable
</code>```

Where Quarter is a dataclass in my codebase.

For a minimal example, consider:

```<code>@dataclass
class Foo:
    val:int

df = pd.DataFrame({'x': [Foo(i) for i in range(10)], 'y':list(range(10))})

df.plot.scatter(x='x', y='y')
</code>```

As expected, the above returns:

```<code>TypeError: Object of type Foo is not JSON serializable
</code>```

Now, I don't expect plotly to be magical, but adding a __float__ magic method allows the Foo objects to be used with the matplotlib backend:

```<code># This works
@dataclass
class Foo:
    val:int

    def __float__(self):
        return float(self.val)

df = pd.DataFrame({'x': [Foo(i) for i in range(10)], 'y':list(range(10))})

df.plot.scatter(x='x', y='y')
</code>```

How can I update my dataclass to allow for it to be used with the plotly backend?

答:
You can get pandas to cast to float before invoking plotting backend.

```<code>from dataclasses import dataclass
import pandas as pd

@dataclass
class Foo:
    val:int

    def __float__(self):
        return float(self.val)

df = pd.DataFrame({'x': [Foo(i) for i in range(10)], 'y':list(range(10))})
df["x"].astype(float)

pd.options.plotting.backend = "plotly"

df.assign(x=lambda d: d["x"].astype(float)).plot.scatter(x='x', y='y')
</code>```

monkey patching

if you don't want to change code, you can monkey patch the plotly implementation of pandas plotting API

https://pandas.pydata.org/pandas-docs/stable/development/extending.html#plotting-backends

```<code>from dataclasses import dataclass
import pandas as pd
import wrapt, json
import plotly

@wrapt.patch_function_wrapper(plotly, 'plot')
def new_plot(wrapped, instance, args, kwargs):
    try:
        json.dumps(args[0][kwargs["x"]])
    except TypeError:
        args[0][kwargs["x"]] = args[0][kwargs["x"]].astype(float)
    return wrapped(*args, **kwargs)

@dataclass
class Foo:
    val:int

    def __float__(self):
        return float(self.val)

df = pd.DataFrame({'x': [Foo(i) for i in range(10)], 'y':list(range(10))})
df["x"].astype(float)

pd.options.plotting.backend = "plotly"

df.plot.scatter(x='x', y='y')

</code>```

Body:
I am trying to switch from the matplotlib pandas plotting backend to plotly. However, I am being held back by a common occurrence of this error:

TypeError: Object of type Quarter is not JSON serializable

Where Quarter is a dataclass in my codebase.

For a minimal example, consider:

@dataclass
class Foo:
    val:int

df = pd.DataFrame({'x': [Foo(i) for i in range(10)], 'y':list(range(10))})

df.plot.scatter(x='x', y='y')

As expected, the above returns:

TypeError: Object of type Foo is not JSON serializable

Now, I don't expect plotly to be magical, but adding a __float__ magic method allows the Foo objects to be used with the matplotlib backend:

# This works
@dataclass
class Foo:
    val:int

    def __float__(self):
        return float(self.val)

df = pd.DataFrame({'x': [Foo(i) for i in range(10)], 'y':list(range(10))})

df.plot.scatter(x='x', y='y')

How can I update my dataclass to allow for it to be used with the plotly backend?

Body:
You can get pandas to cast to float before invoking plotting backend.

from dataclasses import dataclass
import pandas as pd

@dataclass
class Foo:
    val:int

    def __float__(self):
        return float(self.val)

df = pd.DataFrame({'x': [Foo(i) for i in range(10)], 'y':list(range(10))})
df["x"].astype(float)

pd.options.plotting.backend = "plotly"

df.assign(x=lambda d: d["x"].astype(float)).plot.scatter(x='x', y='y')

monkey patching

if you don't want to change code, you can monkey patch the plotly implementation of pandas plotting API

https://pandas.pydata.org/pandas-docs/stable/development/extending.html#plotting-backends

from dataclasses import dataclass
import pandas as pd
import wrapt, json
import plotly

@wrapt.patch_function_wrapper(plotly, 'plot')
def new_plot(wrapped, instance, args, kwargs):
    try:
        json.dumps(args[0][kwargs["x"]])
    except TypeError:
        args[0][kwargs["x"]] = args[0][kwargs["x"]].astype(float)
    return wrapped(*args, **kwargs)

@dataclass
class Foo:
    val:int

    def __float__(self):
        return float(self.val)

df = pd.DataFrame({'x': [Foo(i) for i in range(10)], 'y':list(range(10))})
df["x"].astype(float)

pd.options.plotting.backend = "plotly"

df.plot.scatter(x='x', y='y')


问:
Equivalent Xml for Json
I came across this service from stackoverflow

https://api.stackexchange.com/2.3/questions?fromdate=1519862400&todate=1522368000&order=desc&sort=activity&site=stackoverflow&tagged=python

I believe the source is from a database. How do I build an Xml to spit me out data in similar format?

I use the below logical lines

xmldoc.Load(xmlFileName);
Newtonsoft.Json.JsonConver.SerializeXmlNode(xmldoc);

Any recommendation of how to build the Xml which is a reverse process? My solutions are heavily dependant on Xml and flatFiles

答:
According to https://api.stackexchange.com/docs the StackExchange API only supports JSON output, not XML. So you will have to convert the JSON to XML.

My own preference is to do this conversion "by hand" using XSLT 3.0 rather than using a standard library, because standard libraries often give you XML that's rather difficult to work with.

Title: Equivalent Xml for Json


问:
Pass Single Instance of Model to Multiple View Models in same Module for different views
I am working on a project using PRISM where I have left navigation implemented as Tree View and any click event happens raise event using event aggergation to Enrolment Module which has multiple view model for multiple views (like Wizard Applicaiton where you can go through many views to collect data). I want to have a common or shared or singleton model which can be passed across this view models and save at the end.... users can click on any link any navigation at any time and it should save data in to this singleton model expsosed through different view model. Do you have any samples which are doing something like this... or can you type up a quick one on how to do it? OR it is not possible to do it at all. I am following all patterns from Brian Lagunas's Pluralsight Video for PRISM so try to use that way....</p>

答:
When you use Prism you also have a Dependency Injection Container, usually Unity or MEF. To solve your problem you can register your model as singleton to those DI containers. Every view model that asks the DI container to resolve their dependecy, in our special case the model, will get the singleton instance back from the DI container.

Unity example: You register your model as singleton instance:

```<code>public void Initialize( )
{
    container.RegisterInstance<Model>(new Model(), new ContainerControlledLifetimeManager( ));
}
</code>```

Now you can resolve your dependencies in your view model:

```<code>public ViewModel(IUnityContainer container)
{
    Model model = container.Resolve<Model>();
}
</code>```

Body:
When you use Prism you also have a Dependency Injection Container, usually Unity or MEF. To solve your problem you can register your model as singleton to those DI containers. Every view model that asks the DI container to resolve their dependecy, in our special case the model, will get the singleton instance back from the DI container.

Unity example: You register your model as singleton instance:

public void Initialize( )
{
    container.RegisterInstance<Model>(new Model(), new ContainerControlledLifetimeManager( ));
}

Now you can resolve your dependencies in your view model:

public ViewModel(IUnityContainer container)
{
    Model model = container.Resolve<Model>();
}


问:
How to upload text file to FTP from Databricks notebook
I tried to find a solution but nothing. I am new in this, so please help me if you know the solution.
Thanks!</p>

答:
I have found a workaround for accessing the files outside Databricks (using sftp software like WinSCP/FileZilla).
These are the steps I followed -

I downloaded the awscli using this documentation https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html in Databricks's cluster's terminal.

I ran this command in my Databricks notebook -

!aws s3api put-object-acl --bucket S3-bucket-name --key
path/to-s3/file.txt --acl bucket-owner-full-control

By doing these 2 steps I was able to access the file outside Databricks.


问:
Python Web Scraping - Failed to extract a name list from the website
I failed to extract the first column "Name" from the website. Is there anyone who can help? The website address is: https://www.dianashippinginc.com/the-fleet/

'''

```<code>chromedriver_location = ""
driver = webdriver.Chrome(chromedriver_location)
driver.get('https://www.dianashippinginc.com/fleet-employment-table/')

cookie_address = '//*[@id="ccc-notify-accept"]/span'
name_address = '/html/body/div[3]/div/div/div[2]/table/tbody/tr[3]/td[2]/span'

driver.find_element_by_xpath(cookie_address).click()
driver.find_element_by_xpath(name_address)
</code>```

'''

答:
```<code>import scrapy

class MySpider(scrapy.Spider):
    name = 'myspider'
    start_urls = [r'https://www.dianashippinginc.com/the-fleet/']

    def parse(self, response):
        names = response.xpath('//div[@class="fleet-vessels__table_cell--norm-btn"]/text()').getall()
        # Process the names list to be as you want (remove tab characters, ranking numbers etc.)
        yield names
</code>```

Body:
I failed to extract the first column "Name" from the website. Is there anyone who can help? The website address is: https://www.dianashippinginc.com/the-fleet/

'''

chromedriver_location = ""
driver = webdriver.Chrome(chromedriver_location)
driver.get('https://www.dianashippinginc.com/fleet-employment-table/')

cookie_address = '//*[@id="ccc-notify-accept"]/span'
name_address = '/html/body/div[3]/div/div/div[2]/table/tbody/tr[3]/td[2]/span'

driver.find_element_by_xpath(cookie_address).click()
driver.find_element_by_xpath(name_address)

'''


问:
TypeError: onSelect() is not a function in ReactJS, using functional component
I have following code.

I'm trying to store a value in my state and every time the user goes to the previous step he can see what he has selected and after that he can change and move on to the next step.

At the first step, everything works good. For example, the user selects the second text and proceeds to the next step, and when he returns to this step, he sees that the second text has already been selected...

The problem is with the second step, I write all the same, but it doesn't work for the second step.

The error says onSelect is not a function in src/component/SelectCard.js. Please help me solve this problem.

Here is my code.

App file

```<code> export default function App() {
     const [selected, setSelected] = useState(1);
     const [term, setTerm] = useState(1);

     const [current, setCurrent] = useState(0);

     const [data, setData] = useState({
       firstName: "bob",
       lastName: "Forest",
       age: 47
     });
      const steps = [
        {
          title: "Package Choose",
          content: (
            <PackageChoose
              setCurrent={setCurrent}
              data={data}
              setData={setData}
              selected={selected}
              setSelected={setSelected}
            />
         ),
          id: 0
        },
        {
          title: "Term",
          content: (
            <Term
              setCurrent={setCurrent}
              data={data}
              selected={term}
              setSelected={setTerm}
            />
          ),
          id: 1
        },
        {
          title: "Last step",
          content: <LastStep setCurrent={setCurrent} data={data} />,
          id: 2
        }
      ];
      return (
        <div className="App">
          <div>{steps[current].content}</div>
        </div>
      );
    }
</code>```

first step package choose file

```<code>    const PackageChoose = ({
      setCurrent,
      data,
      setData,
      setSelected,
      selected
    }) => {
      return (
        <div>
          <div
            onClick={() => {
              setData({ ...data, packageType: "choice" });
            }}
          >
            <SelectCard
              id={1}
              selected={selected}
              onSelect={setSelected}
              text="text 1"
            />
          </div>
          <div
            onClick={() => {
              setData({ ...data, packageType: "select" });
            }}
          >
            <SelectCard
              id={2}
              selected={selected}
              onSelect={setSelected}
              text="text 2"
             />
          </div>
          <button onClick={() => setCurrent(1)}>Next</button>
        </div>
      );
   };
</code>```

second step Term file

```<code>   const Term = ({ setCurrent, data, setData, term, setTerm }) => {
      return (
        <div>
          <button onClick={() => setCurrent(0)}>Prev</button>
          <div
            onClick={() => {
              setData({ ...data, termType: "30 day" });
            }}
          >
            <SelectCard
              id={1}
              selected={term}
              onSelect={setTerm}
              text=" term text 1"
            />
         </div>
          <div
            onClick={() => {
              setData({ ...data, termType: "90 day" });
            }}
          >
            <SelectCard
              id={2}
              selected={term}
              onSelect={setTerm}
              text="term text 2"
            />
          </div>
          <button onClick={() => setCurrent(2)}>Next</button>
            </div>
      );
    };
</code>```

SelectCard file , in this file I am using onSelect

```<code>   const SelectCard = ({ id, selected, onSelect, text }) => {
      const myClassName =
        id === selected
          ? Styles.selectCardWrapperActives
          : Styles.selectCardWrapper;

      return (
        <div className={classNames(myClassName)} onClick={() => onSelect(id)}>
          <div> {text} </div>
        </div>
      );
     };
</code>```

Please help me to understand how can I fix this problem in my code.

Thanks.

答:
I fixed it. Please look.

Your issue in props that you passed.

https://codesandbox.io/s/little-leftpad-3owuu

Body:
I have following code.

I'm trying to store a value in my state and every time the user goes to the previous step he can see what he has selected and after that he can change and move on to the next step.

At the first step, everything works good. For example, the user selects the second text and proceeds to the next step, and when he returns to this step, he sees that the second text has already been selected...

The problem is with the second step, I write all the same, but it doesn't work for the second step.

The error says onSelect is not a function in src/component/SelectCard.js. Please help me solve this problem.

Here is my code.

App file

 export default function App() {
     const [selected, setSelected] = useState(1);
     const [term, setTerm] = useState(1);

     const [current, setCurrent] = useState(0);

     const [data, setData] = useState({
       firstName: "bob",
       lastName: "Forest",
       age: 47
     });
      const steps = [
        {
          title: "Package Choose",
          content: (
            <PackageChoose
              setCurrent={setCurrent}
              data={data}
              setData={setData}
              selected={selected}
              setSelected={setSelected}
            />
         ),
          id: 0
        },
        {
          title: "Term",
          content: (
            <Term
              setCurrent={setCurrent}
              data={data}
              selected={term}
              setSelected={setTerm}
            />
          ),
          id: 1
        },
        {
          title: "Last step",
          content: <LastStep setCurrent={setCurrent} data={data} />,
          id: 2
        }
      ];
      return (

{steps[current].content}

      );
    }

first step package choose file

    const PackageChoose = ({
      setCurrent,
      data,
      setData,
      setSelected,
      selected
    }) => {
      return (

 {
              setData({ ...data, packageType: "choice" });
            }}
          >
            <SelectCard
              id={1}
              selected={selected}
              onSelect={setSelected}
              text="text 1"
            />

 {
              setData({ ...data, packageType: "select" });
            }}
          >
            <SelectCard
              id={2}
              selected={selected}
              onSelect={setSelected}
              text="text 2"
             />

          <button onClick={() => setCurrent(1)}>Next</button>

      );
   };

second step Term file

   const Term = ({ setCurrent, data, setData, term, setTerm }) => {
      return (

          <button onClick={() => setCurrent(0)}>Prev</button>

 {
              setData({ ...data, termType: "30 day" });
            }}
          >
            <SelectCard
              id={1}
              selected={term}
              onSelect={setTerm}
              text=" term text 1"
            />

 {
              setData({ ...data, termType: "90 day" });
            }}
          >
            <SelectCard
              id={2}
              selected={term}
              onSelect={setTerm}
              text="term text 2"
            />

          <button onClick={() => setCurrent(2)}>Next</button>

      );
    };

SelectCard file , in this file I am using onSelect

   const SelectCard = ({ id, selected, onSelect, text }) => {
      const myClassName =
        id === selected
          ? Styles.selectCardWrapperActives
          : Styles.selectCardWrapper;

      return (

 onSelect(id)}>

 {text}

      );
     };

Please help me to understand how can I fix this problem in my code.

Thanks.