问:
Getting a string from JSON response and adding 1 to it
I have a RESTful GET request from a ticketing system. It gets the most recent ticket number entered in the system, and prints it for the user. What I need to do is then take the number it gives, and add one to it for a POST request. For example, here's my code:

```<code>response = requests.get(url=url, headers=headers)
    data2 = response.json()
    ntickId = data2[0]['id']
    if tickId < ntickId:
        pprint(f"The most recent ticket is: {ntickId}. Press any key to continue.")
        input(" ")
        pprint(f"Your new ticket number will be: " + int({ntickId})+1)
</code>```

Earlier, I entered the number 468516. Here's my output:

```<code>Please Enter Event Ticket ID: 468516
'The most recent ticket is: 468999. Press any key to continue.
</code>```

So far so good. So, ideally I'd expect 469000 to be the new ticket number. Here's what I got instead:

```<code>pprint(f"Your new ticket number will be: " + int({ntickId})+1)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'set'
</code>```

I'm not sure how to go about this.

答:
It should be:

```<code>pprint(f"Your new ticket number will be: {int(ntickId)+1}")
</code>```

Note, given that you compare tickId and ntickId conversion to int is most likely not necessary  because ntickId is already an int. You may edit your question to include sample JSON response from the API. In this case:

```<code>pprint(f"Your new ticket number will be: {ntickId+1}")
</code>```

Body:
I have a RESTful GET request from a ticketing system. It gets the most recent ticket number entered in the system, and prints it for the user. What I need to do is then take the number it gives, and add one to it for a POST request. For example, here's my code:

response = requests.get(url=url, headers=headers)
    data2 = response.json()
    ntickId = data2[0]['id']
    if tickId < ntickId:
        pprint(f"The most recent ticket is: {ntickId}. Press any key to continue.")
        input(" ")
        pprint(f"Your new ticket number will be: " + int({ntickId})+1)

Earlier, I entered the number 468516. Here's my output:

Please Enter Event Ticket ID: 468516
'The most recent ticket is: 468999. Press any key to continue.

So far so good. So, ideally I'd expect 469000 to be the new ticket number. Here's what I got instead:

pprint(f"Your new ticket number will be: " + int({ntickId})+1)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'set'

I'm not sure how to go about this.

Body:
It should be:

pprint(f"Your new ticket number will be: {int(ntickId)+1}")

Note, given that you compare tickId and ntickId conversion to int is most likely not necessary  because ntickId is already an int. You may edit your question to include sample JSON response from the API. In this case:

pprint(f"Your new ticket number will be: {ntickId+1}")


来源: stackexchange

问:
Why does my array print more than I want?
I'm trying to write an array in c++, which consist of 10 integers that are all 1, unless changed through keyboard input. For some reason my code prints out way more than 10 integers and I'm not sure why.

```<code>int main()
{
    int index, value;
    int count = 0;
    int myData [10];
    for (int i = 0; i < sizeof(myData); i++)
    {
        myData[i] = 1;
    }

    do
    {
        for (int i = 0; i < sizeof(myData); i++)
        {
            std::cout << myData[i] << " ";
        }

        std::cout << "Input index: ";
        std::cin >> index;
        std::cout << "Input value: ";
        std::cin >> value;

        myData[index] = value;

    } while ((0 <= index) && (index <= sizeof(myData)));

    std::cout << "Index out of range. Exit." << std::endl;

    return 0;
}
</code>```

EDIT
I got it to work thank you :D but for some reason now I'm getting a buffer overflow. Anyway to fix this?

答:
As Silvio said, it stores number of bytes.
You can also use a pointer as well

So your condition in for loop can look like

```<code>for (size_t i = 0; i < (sizeof(myData)/sizeof(*myData); ++i)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to write an array in c++, which consist of 10 integers that are all 1, unless changed through keyboard input. For some reason my code prints out way more than 10 integers and I'm not sure why.

int main()
{
    int index, value;
    int count = 0;
    int myData [10];
    for (int i = 0; i < sizeof(myData); i++)
    {
        myData[i] = 1;
    }

    do
    {
        for (int i = 0; i < sizeof(myData); i++)
        {
            std::cout << myData[i] << " ";
        }

        std::cout << "Input index: ";
        std::cin >> index;
        std::cout << "Input value: ";
        std::cin >> value;

        myData[index] = value;

    } while ((0 <= index) && (index <= sizeof(myData)));

    std::cout << "Index out of range. Exit." << std::endl;

    return 0;
}

EDIT
I got it to work thank you :D but for some reason now I'm getting a buffer overflow. Anyway to fix this?

Body:
As Silvio said, it stores number of bytes.
You can also use a pointer as well

So your condition in for loop can look like

for (size_t i = 0; i < (sizeof(myData)/sizeof(*myData); ++i)


问:
How to automatically delete old records from sql server database?
I'm making a web application in aspnet, and I created a table in the database to insert notifications. I would like to know if there is any way to automatically delete data from this table that is older than 30 days. Is there any way this can be done?</p>

答:
Build a Stored Procedure with T-SQL that remove your older data than 30 days.

Assign procedure to SQL Server Agent.

Run server agent every day at specific hours.

With that way, your procedure will run every day and will delete your older data than 30 days according to the Procedure that you write.


问:
Adding stratified variable to a dataframe in R
I have some data that I want to split into 4 equal parts based on the group.

My dataframe looks like this:

X
Group

1
1

2
1

3
1

4
1

5
1

6
1

7
2

8
2

9
3

10
3

11
3

12
3

13
3

14
3

15
3

16
3

Now I thought about adding a thrid column to mark which data belong to which split, like this:

X
Group
Split

1
1
1

2
1
3

3
1
2

4
1
4

5
1
4

6
1
2

7
2
3

8
2
1

9
3
1

10
3
2

11
3
3

12
3
4

13
3
1

14
3
2

15
3
3

16
3
4

I don't need to actually split the dataset, because the data are videos and I just have to mark how (which person) has to watch them.

I know how I can generate random numbers, but I need them to be stratified to the group.

I know how I can get a stratified sample, but thats not I want, because I want to distribute ALL data (videos in this case) but in a stratified fashion.

Can you help me how to achieve this?

Thank you!

edit: I changed to example to unequally sized groups.

答:
You can easily do these kind of stratified operations using dplyr::group_by():

```<code>library(tidyverse)

df <- data.frame(
    X = 1:12,
    Group = c(rep(1,4), rep(2,4), rep(3,4))
)

df %>%
  group_by(Group) %>%
  mutate(Split = sample(seq_along(X), size = n(), replace = FALSE) %% 4 + 1) %>%
  ungroup()
</code>```

Body:
You can easily do these kind of stratified operations using dplyr::group_by():

library(tidyverse)

df <- data.frame(
    X = 1:12,
    Group = c(rep(1,4), rep(2,4), rep(3,4))
)

df %>%
  group_by(Group) %>%
  mutate(Split = sample(seq_along(X), size = n(), replace = FALSE) %% 4 + 1) %>%
  ungroup()


问:
Expo Push Notifications on Android
I have Expo Push Notifications working in the Expo Go app as well as iOS builds. However, it does not work on Android and I get this message when running getExpoPushTokenAsync():

```<code>Error: Encountered an exception while calling native method: Exception occurred while executing exported method getDevicePushTokenAsync on module ExpoPushTokenManager: Please set your project ID. A valid Firebase project ID is required to communicate with Firebase server APIs: It identifies your project with Google.
</code>```

I have followed all the steps listed in the documentation: my google-services.json is referenced in app.json and I double checked all the information there, including the project ID.

I tried to get the native device token via getDevicePushTokenAsync() and it worked, however even if I want to use the firebase notifications without Expo I get the same error further down when trying to set a firebase notification listener.

The problem may be linked with the fact that a firebase app is already running with the JS SDK (for realtimeDB and stoage) using other configs when I call getExpoPushTokenAsync(), I could maybe initialize a secondary Firebase App with the google-services.json config (which works, I tried it) but I do not see any way to force Expo Notifications to use this app.

Any idea of what is going on?
Thanks!

答:
So I fixed the issue if anyone still needs an answer:

I was updating my app with the google-services.json file through Expo over-the-air updates, but I needed to submit a whole new release on Goole Play Console and go through the whole verification process again in order for the file to be taken into account. Now they deployed my new release with the exact same code and it works.

Title: Expo Push Notifications on Android

Body:
I have Expo Push Notifications working in the Expo Go app as well as iOS builds. However, it does not work on Android and I get this message when running getExpoPushTokenAsync():

Error: Encountered an exception while calling native method: Exception occurred while executing exported method getDevicePushTokenAsync on module ExpoPushTokenManager: Please set your project ID. A valid Firebase project ID is required to communicate with Firebase server APIs: It identifies your project with Google.

I have followed all the steps listed in the documentation: my google-services.json is referenced in app.json and I double checked all the information there, including the project ID.

I tried to get the native device token via getDevicePushTokenAsync() and it worked, however even if I want to use the firebase notifications without Expo I get the same error further down when trying to set a firebase notification listener.

The problem may be linked with the fact that a firebase app is already running with the JS SDK (for realtimeDB and stoage) using other configs when I call getExpoPushTokenAsync(), I could maybe initialize a secondary Firebase App with the google-services.json config (which works, I tried it) but I do not see any way to force Expo Notifications to use this app.

Any idea of what is going on?
Thanks!


问:
Constructing register map using templated class
I'm working on modelling some hardware in SystemC (although that's not relevant to the question). The goal is to be able to declare a bunch of registers in a block (class) which are used directly in the class implementation. The external software/firmware will access the registers through a register map to decode based on address. So the HW block as part of its constructor will initialize the register map (not shown below). The issue arises from the fact that some registers need to trigger an action. To do this is seems appropriate to have method in the HW class that is called if the register is written.

The simplified class hierarchy is as follows

```<code>class regBase {
public:
    regBase(uint64_t _address, std::string _name) :
        m_address(_address),
        m_name(_name) { }
    regBase() {};
    void setAddress(uint64_t _address) { m_address = _address;}
    virtual void write(uint32_t newval) = 0;  //virtual methods to be overridden in template
    virtual uint32_t read(void) = 0;
    virtual int size(void) = 0;
private:
    uint64_t m_address;
    std::string m_name;
};

template <class REG>
class hwRegister : public regBase
{
public:
    uint32_t read(void) override
    {
        return m_val.value();
    }
    void write(uint32_t newval) override
    {
        m_val.setValue(newval);
    }
    int size(void) override
    {
        return (m_val.size());
    }
private:
    REG m_val;
};

typedef std::function<void(uint64_t, uint32_t)> writeCallback_t;
struct reg_entry {
    reg_entry(int _size, regBase *_reg) :
       m_reg(_reg), m_size(_size) {}
    reg_entry() {}
    regBase *m_reg;
    int m_size;
    writeCallback_t m_callback;
};

typedef boost::ptr_map<int, std::shared_ptr<reg_entry> > reg_map_t;
class RegMap {
public:
    void write(uint64_t address, uint32_t val) {

        auto it = m_register_map.find(address);
        if (it==m_register_map.end())
        {
            BOOST_ASSERT_MSG(false, "Invalid address");
        }
        auto entry = *it->second;
        entry->m_reg->write(val);
        if (entry->m_callback)
            entry->m_callback(address, val);
    };
    void setCallback(uint64_t address, writeCallback_t newcallback)
    {
        auto it = m_register_map.find(address);
        if (it==m_register_map.end())
        {
            BOOST_ASSERT_MSG(false, "Invalid address");
        }
        (*it->second)->m_callback = newcallback;
    };
    void addReg(uint64_t address, regBase *reg) {
        auto entry = std::make_shared<reg_entry>(reg->size(), reg);
        entry->m_callback = nullptr;
        entry->m_reg = reg;

        m_register_map[address] = entry;
    }
private:
    reg_map_t m_register_map;

};
</code>```

I want to in the implementation of HW block, add myReg to myMap and be able to add a callback if necessary for a given register. The issue is around the callback. Does the declaration of the callback look right? Do I need to use std::bind and placeholders?
Ok, updated with compiling code.

答:
[this](uint64_t address, uint32_t val) { myCallback(address, val); } worked</p>
```<code>struct my_reg_st {
    uint64_t data;
    uint64_t size(void) { return 8; };
    void setValue(uint32_t val) { data = val; };
    uint64_t value(void) {return data; };
};

class test {
public:
    test() {
        myMap.addReg(0, &myReg);
        // use lambda function for callback. Note that use of intermediate f is only for readability
        writeCallback_t f = [this](uint64_t address, uint32_t val) { myRegCallback(address, val); };
        myMap.setCallback(0, f);
    }
    void myRegCallback(uint64_t address, uint32_t value);
    void write(uint64_t address, uint32_t val) { myMap.write(address, val); };
private:
    hwRegister<my_reg_st> myReg;
    RegMap myMap;
};
</code>```

Body:
I'm working on modelling some hardware in SystemC (although that's not relevant to the question). The goal is to be able to declare a bunch of registers in a block (class) which are used directly in the class implementation. The external software/firmware will access the registers through a register map to decode based on address. So the HW block as part of its constructor will initialize the register map (not shown below). The issue arises from the fact that some registers need to trigger an action. To do this is seems appropriate to have method in the HW class that is called if the register is written.

The simplified class hierarchy is as follows

class regBase {
public:
    regBase(uint64_t _address, std::string _name) :
        m_address(_address),
        m_name(_name) { }
    regBase() {};
    void setAddress(uint64_t _address) { m_address = _address;}
    virtual void write(uint32_t newval) = 0;  //virtual methods to be overridden in template
    virtual uint32_t read(void) = 0;
    virtual int size(void) = 0;
private:
    uint64_t m_address;
    std::string m_name;
};

template <class REG>
class hwRegister : public regBase
{
public:
    uint32_t read(void) override
    {
        return m_val.value();
    }
    void write(uint32_t newval) override
    {
        m_val.setValue(newval);
    }
    int size(void) override
    {
        return (m_val.size());
    }
private:
    REG m_val;
};

typedef std::function<void(uint64_t, uint32_t)> writeCallback_t;
struct reg_entry {
    reg_entry(int _size, regBase *_reg) :
       m_reg(_reg), m_size(_size) {}
    reg_entry() {}
    regBase *m_reg;
    int m_size;
    writeCallback_t m_callback;
};

typedef boost::ptr_map<int, std::shared_ptr<reg_entry> > reg_map_t;
class RegMap {
public:
    void write(uint64_t address, uint32_t val) {

        auto it = m_register_map.find(address);
        if (it==m_register_map.end())
        {
            BOOST_ASSERT_MSG(false, "Invalid address");
        }
        auto entry = *it->second;
        entry->m_reg->write(val);
        if (entry->m_callback)
            entry->m_callback(address, val);
    };
    void setCallback(uint64_t address, writeCallback_t newcallback)
    {
        auto it = m_register_map.find(address);
        if (it==m_register_map.end())
        {
            BOOST_ASSERT_MSG(false, "Invalid address");
        }
        (*it->second)->m_callback = newcallback;
    };
    void addReg(uint64_t address, regBase *reg) {
        auto entry = std::make_shared<reg_entry>(reg->size(), reg);
        entry->m_callback = nullptr;
        entry->m_reg = reg;

        m_register_map[address] = entry;
    }
private:
    reg_map_t m_register_map;

};

I want to in the implementation of HW block, add myReg to myMap and be able to add a callback if necessary for a given register. The issue is around the callback. Does the declaration of the callback look right? Do I need to use std::bind and placeholders?
Ok, updated with compiling code.

Body:
[this](uint64_t address, uint32_t val) { myCallback(address, val); } worked

struct my_reg_st {
    uint64_t data;
    uint64_t size(void) { return 8; };
    void setValue(uint32_t val) { data = val; };
    uint64_t value(void) {return data; };
};

class test {
public:
    test() {
        myMap.addReg(0, &myReg);
        // use lambda function for callback. Note that use of intermediate f is only for readability
        writeCallback_t f = [this](uint64_t address, uint32_t val) { myRegCallback(address, val); };
        myMap.setCallback(0, f);
    }
    void myRegCallback(uint64_t address, uint32_t value);
    void write(uint64_t address, uint32_t val) { myMap.write(address, val); };
private:
    hwRegister<my_reg_st> myReg;
    RegMap myMap;
};


问:
jQuery .fadeOut problems in FireFox 6.0
So far, I have the fadeIn working, but the fadeOut has not been quite right.  Right now, as soon as the mouse leaves the hover area, it doesn't look like any fadeOut is happening at all.  I would like to have a smooth fade out that completes before the next animation (the next fadeIn) begins and doesn't queue up.  Basically this is over some links that are within  tags.  I'm in the home stretch now!

P.S. I know I'm not using .hover.  I'd rather stick with mouseover and mouseleave for now, or even mouseout.  Please accomodate this small request.

```<code><script>
    $("a").mouseover(function () {
        $("div").fadeIn(0, function () {
            $("span").fadeIn(3000,0.0);
        });
        return false;
    });

    $dequeue;

    $("a").mouseleave(function () {
        $("span").fadeOut(3000,0.0);
    });
</script>

<!DOCTYPE html>

<html>
<head>
<script type="text/javascript" src="jQuery.js"></script>
</head>
<body>

<a href="#">MouseOver!</a>

<div>

<h3><span>Sample Text</span></h3>

</div>
</body>
</html>
</code>```

Edit: 08/18/2011

I realized that there may be script conflicting with the one above.  I have an additional jquery script running on the same page.  By itself it works fine, but when I add the script for the text box (above) the .fadeOut on both images and text becomes ignored or at the very least, inconsistent.

2nd jQuery script:

```<code><script>
$(document).ready(function(){

$(".latest_img").fadeTo("slow", 0.0);
$(".latest_img").hover(function(){
$(this).fadeTo(1000, 1.0).dequeue();

},function(){
$(this).fadeTo(1000, 0.0).dequeue();
});
});
</script>
</code>```

Here is an example of one of the four "targets" that should prompt the text and image to display (there are four text boxes accompanying four images - each get shown by a mouseover on the target).

HTML:

```<code><div class="gallerycontainer">
<div width="100%" height="30%">

<a class="thumbnail" href="#thumb"><h2 class="ftb" id="tg1">Target A</h2>

<span class="txspan">
<img src="img/ima.jpg" class="latest_img" id="images" />
<h3 class="text"><br>Textbox content for Target A</h3></span></a>

</div>
</div>
</code>```

答: $dequeue is the wrong syntax. It needs to be $.dequeue and be passed an element ie $.dequeue(elem). Also you are not using a queue statment so dequeue is inappropriate. stop() would be wise on both fades. no need to pass any arguments to stop() default should work fine.</p>

Title: jQuery .fadeOut problems in FireFox 6.0

Body:
So far, I have the fadeIn working, but the fadeOut has not been quite right.  Right now, as soon as the mouse leaves the hover area, it doesn't look like any fadeOut is happening at all.  I would like to have a smooth fade out that completes before the next animation (the next fadeIn) begins and doesn't queue up.  Basically this is over some links that are within  tags.  I'm in the home stretch now!

P.S. I know I'm not using .hover.  I'd rather stick with mouseover and mouseleave for now, or even mouseout.  Please accomodate this small request.

<!DOCTYPE html>

MouseOver!

Sample Text

Edit: 08/18/2011

I realized that there may be script conflicting with the one above.  I have an additional jquery script running on the same page.  By itself it works fine, but when I add the script for the text box (above) the .fadeOut on both images and text becomes ignored or at the very least, inconsistent.

2nd jQuery script:

Here is an example of one of the four "targets" that should prompt the text and image to display (there are four text boxes accompanying four images - each get shown by a mouseover on the target).

HTML:

Target A

Textbox content for Target A

ContentLicense: CC BY-SA 3.0


问:
Difference between super() and {parent_class_name} in case of update class property
I've wrote the following code to explain what I've found using super(). :

With Parent.set_prop():

```<code>class Parent:
    parent_prop = None

    @classmethod
    def set_prop(cls, value):
        cls.parent_prop = value

class Child1(Parent):
    @classmethod
    def set_prop(cls, value):
        print("Child1 set parent prop")
        Parent.set_prop(value)

class Child2(Parent):
    pass

cls1 = Child1()
cls2 = Child2()
cls1.set_prop(10)

print(cls1.parent_prop)
print(cls2.parent_prop)
</code>```

With super().set_prop()

```<code>class Parent:
    parent_prop = None

    @classmethod
    def set_prop(cls, value):
        cls.parent_prop = value

class Child1(Parent):
    @classmethod
    def set_prop(cls, value):
        print("Child1 set parent prop")
        super().set_prop(value)

class Child2(Parent):
    pass

cls1 = Child1()
cls2 = Child2()
cls1.set_prop(10)

print(cls1.parent_prop)
print(cls2.parent_prop)
</code>```

The result of the first execution is:

```<code>Child1 set parent prop
10
10
</code>```

The result of the second execution is:

```<code>Child1 set parent prop
10
None
</code>```

I didn't expect any differences between both. Why calling the set_prop method with super() doesn't set the value for all instances of the class?

答:
The difference is obvious when you add a print(cls) to Parent.set_prop :

    @classmethod
    def set_prop(cls, value):
        print(cls)
        cls.parent_prop = value
```
<p>When ran in case 1 :</p>
```Child1 set parent prop
<class '__main__.Parent'>
10
10
```
<p>When ran in case 2 :</p>
```Child1 set parent prop
<class '__main__.Child1'>
10
None
```

That's because super does not give you the parent class, but a proxy which will call the parent's methods (using a special __getitem__) but with the same parameters, here the same value for cls which is Child1 in the second case, but simply Parent in the first case.

Body:
I've wrote the following code to explain what I've found using super(). :

With Parent.set_prop():

class Parent:
    parent_prop = None

    @classmethod
    def set_prop(cls, value):
        cls.parent_prop = value

class Child1(Parent):
    @classmethod
    def set_prop(cls, value):
        print("Child1 set parent prop")
        Parent.set_prop(value)

class Child2(Parent):
    pass

cls1 = Child1()
cls2 = Child2()
cls1.set_prop(10)

print(cls1.parent_prop)
print(cls2.parent_prop)

With super().set_prop()

class Parent:
    parent_prop = None

    @classmethod
    def set_prop(cls, value):
        cls.parent_prop = value

class Child1(Parent):
    @classmethod
    def set_prop(cls, value):
        print("Child1 set parent prop")
        super().set_prop(value)

class Child2(Parent):
    pass

cls1 = Child1()
cls2 = Child2()
cls1.set_prop(10)

print(cls1.parent_prop)
print(cls2.parent_prop)

The result of the first execution is:

Child1 set parent prop
10
10

The result of the second execution is:

Child1 set parent prop
10
None

I didn't expect any differences between both. Why calling the set_prop method with super() doesn't set the value for all instances of the class?

Body:
The difference is obvious when you add a print(cls) to Parent.set_prop :

    @classmethod
    def set_prop(cls, value):
        print(cls)
        cls.parent_prop = value

When ran in case 1 :

Child1 set parent prop
<class '__main__.Parent'>
10
10

When ran in case 2 :

Child1 set parent prop
<class '__main__.Child1'>
10
None

That's because super does not give you the parent class, but a proxy which will call the parent's methods (using a special __getitem__) but with the same parameters, here the same value for cls which is Child1 in the second case, but simply Parent in the first case.


问:
Angular Material and Kendo doesn't work with Module Federation Plugin: Bootstrap call not found
I built a microfrontend application using Angular CLI and Module Federation Plugin.
When I try to install Angular Material or Kendo, I've got this problem:
Bootstrap call not found

I followed this link  to resolve this problem. Unfortunately, I've got further problems:

When I install Angular Material, I've got this error:

Your project is not using the default builders for "build". The Angular Material schematics cannot add a theme to the workspace configuration if the builder has been changed.

When I install Kendo, I've got this error:

Skipping installation: Package already installed. File node_modules/@progress/kendo-angular-buttons/package.json does not exist.

答:
I found the solution. Before installing the libraries, I replaced the contents of main.ts with the contents of bootstrap.ts:

main.ts:

```<code>/*import('./bootstrap')
    .catch(err => console.error(err));
*/

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.error(err));
</code>```

After installing the libraries, I restored its contents:

```<code>import('./bootstrap')
    .catch(err => console.error(err));
</code>```

This isn't the best solution, but it works!

Body:
I found the solution. Before installing the libraries, I replaced the contents of main.ts with the contents of bootstrap.ts:

main.ts:

/*import('./bootstrap')
    .catch(err => console.error(err));
*/

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.error(err));

After installing the libraries, I restored its contents:

import('./bootstrap')
    .catch(err => console.error(err));

This isn't the best solution, but it works!


问:
npx react-native run-android build failing
I have just created a react-native project and followed all the docs. when I am trying to run  npx react-native run-android I am getting the following error
enter image description here

resolved the above error. now the error is coming like this
enter image description here

答: Solved it by deleting .gradle directory in app/android folder.</p>


问:
render page after for loop is finished node.js
I'm having an async problem, and I've followed a lot of articles online to try and get this issue fixed, but it hasn't done anything.

```<code> async function getNumOfSessionForTrainerClientList(req, res, rows, allowedToAddMoreClients, alertMessage) {

      let sessionData2 = []
      var getNumOfSessionForTrainerClientList = "select * from SCHEDULE WHERE CLIENT_USERNAME = ? AND ASSIGNED_TRAINER = ?"
      mysqlconn.connect(async function(err) {
          if (err) {
            console.error('Database connection failed: ' + err.stack);
            return;
          }
        for (var i = 0; i < rows.length; i++) {
        mysqlconn.query(getNumOfSessionForTrainerClientList, [rows[i].USERNAME, req.session.username], async function(err, sessionData) {
            if (err) {
                console.log(err);
            } else {
                for (var x = 0; x < sessionData.length; x++) {
                    sessionData2.push(sessionData[x].SESSION_STATUS)
                    console.log(sessionData2)
                }

            }

        })
}

})
await res.render('trainerclientlist.ejs', {data: rows, trainerFirstName: req.session.firstname, trainerLastName: req.session.lastname, allowedToAddMoreClients: allowedToAddMoreClients, profilePhoto: req.session.profilePhoto, alertMessage: req.session.selectedalertmessage, sessionData: sessionData2})
console.log(sessionData2)

}
</code>```

what happens is that console.log(sessionData2) happens AFTER the page is rendered, await res.render('trainerclientlist.ejs', {data: rows, trainerFirstName: req.session.firstname, trainerLastName: req.session.lastname, allowedToAddMoreClients: allowedToAddMoreClients, profilePhoto: req.session.profilePhoto, alertMessage: req.session.selectedalertmessage, sessionData: sessionData2}). How can i fix this?

答:
for (var i = 0; i < rows.length; i++) { // I'd avoid this line
// This will force query x-amount of times,
  mysqlconn.query(getNumOfSessionForTrainerClientList, [rows[i].USERNAME, req.session.username], async function(err, sessionData) {
    if (err) {
      console.log(err);
    } else {
      // this could had been returned 200ms ->5s from when it's called
      for (var x = 0; x < sessionData.length; x++) {
        sessionData2.push(sessionData[x].SESSION_STATUS)
        console.log(sessionData2)
      }
      // I'd make your res.render call here or call for the next query till all are finished and when none left, now call res.render here...
    }

  })
}
// probably took 1-20ms to complete the loop and so sessionData2 is not ready..
console.log(sessionData);```

The issue I see is that you run a loop around a query call, that does not wait for each callback, but fires each query and sometime in the future the callback is received. Given this happens all to fast, you can imagine the MySQL server responded back with a delay and it was that exactly that makes sessionData undefined. If you put a setTimeout of 5 seconds it should be defined because enough time was given (but don't do this... bad idea).

The biggest fix you can make is to set this up so you do not have to loop through rows.length... then you can simply run the res.render when MySQL responds back.

Body:
I'm having an async problem, and I've followed a lot of articles online to try and get this issue fixed, but it hasn't done anything.

 async function getNumOfSessionForTrainerClientList(req, res, rows, allowedToAddMoreClients, alertMessage) {

      let sessionData2 = []
      var getNumOfSessionForTrainerClientList = "select * from SCHEDULE WHERE CLIENT_USERNAME = ? AND ASSIGNED_TRAINER = ?"
      mysqlconn.connect(async function(err) {
          if (err) {
            console.error('Database connection failed: ' + err.stack);
            return;
          }
        for (var i = 0; i < rows.length; i++) {
        mysqlconn.query(getNumOfSessionForTrainerClientList, [rows[i].USERNAME, req.session.username], async function(err, sessionData) {
            if (err) {
                console.log(err);
            } else {
                for (var x = 0; x < sessionData.length; x++) {
                    sessionData2.push(sessionData[x].SESSION_STATUS)
                    console.log(sessionData2)
                }

            }

        })
}

})
await res.render('trainerclientlist.ejs', {data: rows, trainerFirstName: req.session.firstname, trainerLastName: req.session.lastname, allowedToAddMoreClients: allowedToAddMoreClients, profilePhoto: req.session.profilePhoto, alertMessage: req.session.selectedalertmessage, sessionData: sessionData2})
console.log(sessionData2)

}

what happens is that console.log(sessionData2) happens AFTER the page is rendered, await res.render('trainerclientlist.ejs', {data: rows, trainerFirstName: req.session.firstname, trainerLastName: req.session.lastname, allowedToAddMoreClients: allowedToAddMoreClients, profilePhoto: req.session.profilePhoto, alertMessage: req.session.selectedalertmessage, sessionData: sessionData2}). How can i fix this?

Body:
for (var i = 0; i < rows.length; i++) { // I'd avoid this line
// This will force query x-amount of times,
  mysqlconn.query(getNumOfSessionForTrainerClientList, [rows[i].USERNAME, req.session.username], async function(err, sessionData) {
    if (err) {
      console.log(err);
    } else {
      // this could had been returned 200ms ->5s from when it's called
      for (var x = 0; x < sessionData.length; x++) {
        sessionData2.push(sessionData[x].SESSION_STATUS)
        console.log(sessionData2)
      }
      // I'd make your res.render call here or call for the next query till all are finished and when none left, now call res.render here...
    }

  })
}
// probably took 1-20ms to complete the loop and so sessionData2 is not ready..
console.log(sessionData);

The issue I see is that you run a loop around a query call, that does not wait for each callback, but fires each query and sometime in the future the callback is received. Given this happens all to fast, you can imagine the MySQL server responded back with a delay and it was that exactly that makes sessionData undefined. If you put a setTimeout of 5 seconds it should be defined because enough time was given (but don't do this... bad idea).

The biggest fix you can make is to set this up so you do not have to loop through rows.length... then you can simply run the res.render when MySQL responds back.


问:
How to speed up HTML video on mobile
I have a website and it has a slider that contains a video tag. It worked on desktop well but it's so slowly on mobile.

In mobile, it's playing smaller(MB) video but it's so slowly. The problem website is https://www.drapebutik.com/

What can I do to speed it up?

答: I would compress the video or use a caching mechanism, this way it would require fewer resources to load and be processed efficiently.</p>

Title: How to speed up HTML video on mobile


问:
Boost::asio::strand merges multiple handlers into one
I am currently using boost 1.70 and I was trying to implement io service loop to have a custom call between each invoked handle, and I couldn't get it to work. After some examination, I gained suspicion there are multiples handles executed in one call of "run_one" function. So I wrote a test code:

```<code>#include <boost/asio/io_service.hpp>
#include <boost/asio/strand.hpp>
#include <boost/asio/post.hpp>

#include <thread>
#include <mutex>

class StrandPost
{
private:
    boost::asio::io_service           service_;
    boost::asio::io_service::work     work_;
    boost::asio::io_service::strand   strand_;

    std::thread                       module_thread_;
    void Run() {
        auto run_one = [this]() {
            std::cout << " ---- Running one ----" << std::endl;
            auto retval = service_.run_one();
            return retval;
        };

        while (run_one());
        std::cout << " ---- Ending run ----" << std::endl;
    }

public:
    StrandPost()
        : service_()
        , work_(service_)
        , strand_(service_)
        , module_thread_(&StrandPost::Run, this)
    {}

    ~StrandPost() {
        service_.stop();
        if (module_thread_.joinable()) {
            module_thread_.join();
        }
    }

    void PlanOutput(const std::string& string) {
        boost::asio::post(strand_,[string](){
            std::cout << string  <<std::endl;
        });
//        boost::asio::post(service_,[string](){
//            std::cout << string  <<std::endl;
//        });
    }
};

} // -----  end anonymous namespace   -----

int main() {
    StrandPost strand;

    strand.PlanOutput("First message");
    strand.PlanOutput("Second message");
    strand.PlanOutput("Third message");
    strand.PlanOutput("Fourth message");

    std::this_thread::sleep_for(std::chrono::seconds(1));
    return 0;
}
</code>```

And the output of that code confirmed my theory, because it was:

---- Running one ----

First message

---- Running one ----

Second message

Third message

Fourth message

---- Running one ----

---- Ending run ----

When using "io_service" directly, it works as expected, but when using "strand", after the first handle, multiple handles are executed as one.

So, the strand effectively merged several handlers into one.
My question is:

Is this bug or is this intentional? Am I doing something wrong?

If this is a bug, is it reported? Because I could not find a mention of this anywhere.

答:
I'm fairly certain this is intentional.  The strand itself is a queue of jobs, that only one thread at a time can perform.

When io_service::run_one runs, it causes the thread to run the strand ready queue.  I believe the 'only one once' logic isn't passed through to the strand's processing loop.  Think of it it this way, the io_service is told to do one handler, but the strand's handler runs several jobs in sequence before returning.

The best fix for your issue is, if you're going to have your own io_service in your class, is don't use the strand at all, and post directly to the io_service.  Then you'll have the behavior you desire.

Body:
I am currently using boost 1.70 and I was trying to implement io service loop to have a custom call between each invoked handle, and I couldn't get it to work. After some examination, I gained suspicion there are multiples handles executed in one call of "run_one" function. So I wrote a test code:

#include <boost/asio/io_service.hpp>
#include <boost/asio/strand.hpp>
#include <boost/asio/post.hpp>

#include <thread>
#include <mutex>

class StrandPost
{
private:
    boost::asio::io_service           service_;
    boost::asio::io_service::work     work_;
    boost::asio::io_service::strand   strand_;

    std::thread                       module_thread_;
    void Run() {
        auto run_one = [this]() {
            std::cout << " ---- Running one ----" << std::endl;
            auto retval = service_.run_one();
            return retval;
        };

        while (run_one());
        std::cout << " ---- Ending run ----" << std::endl;
    }

public:
    StrandPost()
        : service_()
        , work_(service_)
        , strand_(service_)
        , module_thread_(&StrandPost::Run, this)
    {}

    ~StrandPost() {
        service_.stop();
        if (module_thread_.joinable()) {
            module_thread_.join();
        }
    }

    void PlanOutput(const std::string& string) {
        boost::asio::post(strand_,[string](){
            std::cout << string  <<std::endl;
        });
//        boost::asio::post(service_,[string](){
//            std::cout << string  <<std::endl;
//        });
    }
};

} // -----  end anonymous namespace   -----

int main() {
    StrandPost strand;

    strand.PlanOutput("First message");
    strand.PlanOutput("Second message");
    strand.PlanOutput("Third message");
    strand.PlanOutput("Fourth message");

    std::this_thread::sleep_for(std::chrono::seconds(1));
    return 0;
}

And the output of that code confirmed my theory, because it was:

---- Running one ----

First message

---- Running one ----

Second message

Third message

Fourth message

---- Running one ----

---- Ending run ----

When using "io_service" directly, it works as expected, but when using "strand", after the first handle, multiple handles are executed as one.

So, the strand effectively merged several handlers into one.
My question is:

Is this bug or is this intentional? Am I doing something wrong?

If this is a bug, is it reported? Because I could not find a mention of this anywhere.


问:
Strange behavior of ^= assignment operator chains in javascript
I was playing with the XOR trick for swapping values of variables, it works fine if I write it in 3 (or 2) lines, but not when I write it in 1 line, which shows some strange behavior of the ^= operator. What is going on here? Why are the 1-line and 3-line versions not equivalent?

let a = 55, b = 31;
console.log('values to swap:', a, b);

// swap with XOR trick
a ^= b;
b ^= a;
a ^= b;
console.log('swap in 3 lines', a, b);
// output: 31 55

// swap in 1 line
a = 55; b = 31;
a ^= b ^= a ^= b;
console.log('swap in 1 line', a, b);
// output: 0 55

// swap in 2 lines
// chaining only 2 ^= operations works as expected
a = 55; b = 31;
console.log('b ^= a ^= b returns ', b ^= a ^= b);
a ^= b;
console.log('swap in 2 lines', a, b);```

I tested it in Chrome and Safari, got same results.

答:
It is not possible. In JavaScript, expressions are evaluated left-to-right. You have to put this (a ^= b ^= a) && (b ^= a) equation.

That means that your condition is evaluated like this:

```<code>   a ^= b ^= a ^= b;
=> a = a ^ (b = b ^ (a = a ^ b))
=> a = 55 ^ (b = 31 ^ (a = 55 ^ 31))
=> a = 55 ^ (b = 31 ^ 40)
=> a = 55 ^ 55 = 0
   b = 31 ^ 40 = 55
</code>```

Body:
I was playing with the XOR trick for swapping values of variables, it works fine if I write it in 3 (or 2) lines, but not when I write it in 1 line, which shows some strange behavior of the ^= operator. What is going on here? Why are the 1-line and 3-line versions not equivalent?

let a = 55, b = 31;
console.log('values to swap:', a, b);

// swap with XOR trick
a ^= b;
b ^= a;
a ^= b;
console.log('swap in 3 lines', a, b);
// output: 31 55

// swap in 1 line
a = 55; b = 31;
a ^= b ^= a ^= b;
console.log('swap in 1 line', a, b);
// output: 0 55

// swap in 2 lines
// chaining only 2 ^= operations works as expected
a = 55; b = 31;
console.log('b ^= a ^= b returns ', b ^= a ^= b);
a ^= b;
console.log('swap in 2 lines', a, b);

I tested it in Chrome and Safari, got same results.

Body:
It is not possible. In JavaScript, expressions are evaluated left-to-right. You have to put this (a ^= b ^= a) && (b ^= a) equation.

That means that your condition is evaluated like this:

   a ^= b ^= a ^= b;
=> a = a ^ (b = b ^ (a = a ^ b))
=> a = 55 ^ (b = 31 ^ (a = 55 ^ 31))
=> a = 55 ^ (b = 31 ^ 40)
=> a = 55 ^ 55 = 0
   b = 31 ^ 40 = 55


问:
Solving an equation in Python
i'm trying to solve an equation but I don't know the way to do this. I've got a vector x wich is actually a matrix type and I would like to solve the equation x.transpose()*v=0 where v is another vector

Can someone help me?

I thank you in advance

答:
x.T*v is another way of writing the dot product between vectors x and v, so it sounds like you want to find a vector v which is orthogonal to x.  For the general case, there are infinitely many solutions (in 3 dimensions, imagine any vector v in the plane perpendicular to x).

You have said in your comment you know there are a lot of possible solutions, and how can you get one, so here is one for you:

```<code>v = 0
</code>```

Title: Solving an equation in Python

Body:
x.T*v is another way of writing the dot product between vectors x and v, so it sounds like you want to find a vector v which is orthogonal to x.  For the general case, there are infinitely many solutions (in 3 dimensions, imagine any vector v in the plane perpendicular to x).

You have said in your comment you know there are a lot of possible solutions, and how can you get one, so here is one for you:

v = 0


问:
Error while installing pytq5 with pip: Preparing metadata (pyproject.toml) did not run successfully
I try to install pytq5 with pip and get this error

```<code>$ python3 -m pip install PyQt5
Collecting PyQt5
  Using cached PyQt5-5.15.6.tar.gz (3.2 MB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Preparing metadata (pyproject.toml) ... error
  error: subprocess-exited-with-error

  × Preparing metadata (pyproject.toml) did not run successfully.
  │ exit code: 1
  ╰─> [29 lines of output]
      Traceback (most recent call last):
        File "/Users/olivierskonieczny/Desktop/app/python/ObjectDetection/envs/lib/python3.9/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 156, in prepare_metadata_for_build_wheel
          hook = backend.prepare_metadata_for_build_wheel
      AttributeError: module 'sipbuild.api' has no attribute 'prepare_metadata_for_build_wheel'

      During handling of the above exception, another exception occurred:

      Traceback (most recent call last):
        File "/Users/olivierskonieczny/Desktop/app/python/ObjectDetection/envs/lib/python3.9/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 363, in <module>
          main()
        ...
        ...
        ...
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.
</code>```

I still can install other packages like lxml but can't install pytq5. I'm installing everything in virtual environment.

Any ideas ??

答:
I faced the same problem these days. When you have a look at PyPi download site, you can read in the Installation chapter that you need "Qt's qmake tool on PATH". After installing Qt's development files everything worked fine for me. So first install it and make sure it's on your PATH and than try again.

```<code>sudo apt-get install qtbase5-dev
pip install pyqt5
</code>```

PS: I think it has nothing to do with your python or pip version. I tried many versions and had this problem every time. It's just missing, corrupted or not found header development files from qt5.

Regards,
Vali

Body:
I try to install pytq5 with pip and get this error

$ python3 -m pip install PyQt5
Collecting PyQt5
  Using cached PyQt5-5.15.6.tar.gz (3.2 MB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Preparing metadata (pyproject.toml) ... error
  error: subprocess-exited-with-error

  × Preparing metadata (pyproject.toml) did not run successfully.
  │ exit code: 1
  ╰─> [29 lines of output]
      Traceback (most recent call last):
        File "/Users/olivierskonieczny/Desktop/app/python/ObjectDetection/envs/lib/python3.9/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 156, in prepare_metadata_for_build_wheel
          hook = backend.prepare_metadata_for_build_wheel
      AttributeError: module 'sipbuild.api' has no attribute 'prepare_metadata_for_build_wheel'

      During handling of the above exception, another exception occurred:

      Traceback (most recent call last):
        File "/Users/olivierskonieczny/Desktop/app/python/ObjectDetection/envs/lib/python3.9/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 363, in <module>
          main()
        ...
        ...
        ...
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

I still can install other packages like lxml but can't install pytq5. I'm installing everything in virtual environment.

Any ideas ??

Body:
I faced the same problem these days. When you have a look at PyPi download site, you can read in the Installation chapter that you need "Qt's qmake tool on PATH". After installing Qt's development files everything worked fine for me. So first install it and make sure it's on your PATH and than try again.

sudo apt-get install qtbase5-dev
pip install pyqt5

PS: I think it has nothing to do with your python or pip version. I tried many versions and had this problem every time. It's just missing, corrupted or not found header development files from qt5.

Regards,
Vali


问:
How to generate this kind of random curves?
Is it possible to generate this kind of random curves?

I've tried IMagick bezier curves (see http://www.php.net/manual/en/function.imagickdraw-bezier.php), but even with 20-30 points they do not look like this. Here is my sample http://mechanicalzilla.com/sandbox/imagick/curve.php

Thank you.

答:
One way to approach this would be to first generate a set of random curves and then use a physics solver to apply repulsion forces between them to avoid clumping.

Here's a quick proof of concept:

I created this using a very niche tool (for anyone interested: Kangaroo Physics solver, a plugin for Grasshopper, visual scripting language for Rhinoceros3d) but you can probably recreate the same concept in any mainstream programming language, eg. Python.


问:
Pheanstalk responds BAD_FORMAT
While using Pheanstalk and Beanstalkd I get this error.

```<code>Pheanstalk\Exception\ServerBadFormatException
BAD_FORMAT in response to 'put 1024 0 18446744073709551615 363'
</code>```

Beanstalkd is running and I can access it from the terminal.

Any ideas?

答:
The 64 bit versions of PHP sets PHP_INT_MAX as 9223372036854775807.

18446744073709551615 is bigger....

From quick calculations, 9,223,372,036,854,775,807 appears to be well over 292 billion years.

Title: Pheanstalk responds BAD_FORMAT

Body:
While using Pheanstalk and Beanstalkd I get this error.

Pheanstalk\Exception\ServerBadFormatException
BAD_FORMAT in response to 'put 1024 0 18446744073709551615 363'

Beanstalkd is running and I can access it from the terminal.

Any ideas?


问:
Can I check modelstate without modelbinding?
I'm getting my feet wet with the Entity Framework and am wondering if there is a way for me to check model state without model binding happening.

Say I create a user primarily from code, is there a way for me to check to make sure it is valid according to my predefined data annotations before I update?

```<code>    public ActionResult Index()
    {
        User u = new User();
        u.Username = "test";
        u.Password = "test";
        u.Email = "test";

        DefaultContext db = new DefaultContext();

        if (ModelState.IsValid)
        {
            db.Users.Add(u);
            db.SaveChanges();
            Response.Write(u.Id);
        }
        else
            // model is not valid

        return View();
    }
</code>```

The above code does not work because there is no binding happening. Or maybe I am confused of the process.

Thanks.

答:
ModelState won't be available because it's set up by the model binder.  The ModelBinder didn't bind a model so it didn't run validation thus ModelState will be empty.

But that doesn't stop you from using attributes and performing validation.

Assuming you are using the DataAnnotation attributes, you can run the validation without model binding.

Given this class:

```<code>public class Widget
{
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    public decimal Price { get; set; }
}
</code>```

You can do this:

```<code>        var widget = new Widget
                        {
                            Id = 12,
                            Price = 15.57M
                        };

        var context = new ValidationContext(widget, null, null);
        var results = new List<ValidationResult>();
        if( Validator.TryValidateObject( widget, context, results, true ) )
        {
            //Validation Successful
        }
        else
        {
            //Validation Failed
        }
</code>```

The Name property was not set and the TryValidateObject() will fail.  The results collection will have the actual error that occurred.

Body:
I'm getting my feet wet with the Entity Framework and am wondering if there is a way for me to check model state without model binding happening.

Say I create a user primarily from code, is there a way for me to check to make sure it is valid according to my predefined data annotations before I update?

    public ActionResult Index()
    {
        User u = new User();
        u.Username = "test";
        u.Password = "test";
        u.Email = "test";

        DefaultContext db = new DefaultContext();

        if (ModelState.IsValid)
        {
            db.Users.Add(u);
            db.SaveChanges();
            Response.Write(u.Id);
        }
        else
            // model is not valid

        return View();
    }

The above code does not work because there is no binding happening. Or maybe I am confused of the process.

Thanks.

Body:
ModelState won't be available because it's set up by the model binder.  The ModelBinder didn't bind a model so it didn't run validation thus ModelState will be empty.

But that doesn't stop you from using attributes and performing validation.

Assuming you are using the DataAnnotation attributes, you can run the validation without model binding.

Given this class:

public class Widget
{
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    public decimal Price { get; set; }
}

You can do this:

        var widget = new Widget
                        {
                            Id = 12,
                            Price = 15.57M
                        };

        var context = new ValidationContext(widget, null, null);
        var results = new List<ValidationResult>();
        if( Validator.TryValidateObject( widget, context, results, true ) )
        {
            //Validation Successful
        }
        else
        {
            //Validation Failed
        }

The Name property was not set and the TryValidateObject() will fail.  The results collection will have the actual error that occurred.


问:
Using matplotlib to draw a path given cartesian coordinates
I'm new to matplotlib and numpy and am trying to plot some array data to something like this:

but it currently looks like this:

My code is extremely basic but basically the image above is what I'd like to be able to do. I'm not too concerned yet with drawing gridlines but  the plot should be proportional. I've looked at some examples on the mathplotlib website but can't find something similar enough.
I wonder if pyplot is not the correct procedure or if my array is not formatted correctly?

```<code>import numpy as np
from matplotlib import pyplot as plt

data = [(2, 2), (3, 2), (4, 1), (4, 0), (3, 0), (3, 1), (4, 2),
        (4, 3), (4, 4), (3, 3), (3, 4), (2, 4), (2, 3), (1, 4),
        (0, 4), (0, 3), (1, 3), (0, 2), (1, 2), (0, 1), (0, 0),
        (1, 0), (1, 1), (2, 0), (2, 1)]

data = np.asarray(data)
print(data)
plt.ylim(0, 4)
plt.xlim(0, 4)
plt.axis([0, 4, 0, 4])
plt.plot(data)
plt.show()
</code>```

答:
To complete other answers, here is the closest I got in a reasonable amount of time to your desired output :

import numpy as np
from matplotlib import pyplot as plt

data = [(2, 2), (3, 2), (4, 1), (4, 0), (3, 0), (3, 1), (4, 2),
        (4, 3), (4, 4), (3, 3), (3, 4), (2, 4), (2, 3), (1, 4),
        (0, 4), (0, 3), (1, 3), (0, 2), (1, 2), (0, 1), (0, 0),
        (1, 0), (1, 1), (2, 0), (2, 1)]

data = np.asarray(data)
print(data)

# make axis equal and turn them off
plt.axis('equal')
plt.axis('off')

for i in range(5):
    # horizontal and vertical background lines
    plt.plot([i,i], [0,4], linewidth=0.5, color='black')
    plt.plot([0,4], [i,i], linewidth=0.5, color='black')
plt.plot(data[:,0], data[:,1], 'b') # line segments
plt.scatter(data[:,0], data[:,1], c='b') # markers

plt.show()
```
<p><strong>Output:</strong></p>
<p><img src="https://i.stack.imgur.com/YFEFA.png" alt="output" /></p>
<hr />
<p><strong>Edit</strong></p>
<p>From this question, you can add numbers at each marker through <code>plt.annotate</code>. Just add this after <code>plt.scatter</code> :</p>
<pre class="lang-py prettyprint-override"><code>offset = np.array([0.1, 0.1])
for i in range(data.shape[0]):
    # For each marker
    plt.annotate(str(i+1), data[i]+offset)
</code>```

Output:

Edit #2:

As a bonus, here is my attempt as getting the closest possible to the reference figure:

import numpy as np
from matplotlib import pyplot as plt

data = [(2, 2), (3, 2), (4, 1), (4, 0), (3, 0), (3, 1), (4, 2),
        (4, 3), (4, 4), (3, 3), (3, 4), (2, 4), (2, 3), (1, 4),
        (0, 4), (0, 3), (1, 3), (0, 2), (1, 2), (0, 1), (0, 0),
        (1, 0), (1, 1), (2, 0), (2, 1)]

data = np.asarray(data)
print(data)

# make axis equal and turn them off
plt.axis('equal')
plt.axis('off')

for i in range(5):
    # horizontal and vertical background lines
    plt.plot([i,i], [0,4], linewidth=1.5, color='#b3b3b3', zorder=1)
    plt.plot([0,4], [i,i], linewidth=1.5, color='#b3b3b3', zorder=1)

plt.plot(data[:,0], data[:,1], '#274b8b', linewidth=2.5, zorder=2) # line segments
plt.scatter(data[np.arange(len(data))!=7,0], data[np.arange(len(data))!=7,1], s=60, c='#4472c4', edgecolors='#2e569c', zorder=3) # markers
# marker for point 7 is not plotted in reference figure

# Individual points numbers, not in reference figure so commented
# offset = np.array([0.1, 0.1])
# for i in range(data.shape[0]):
    # # For each marker
    # plt.annotate(str(i+1), data[i]+offset)

for i in range(5):
    plt.annotate(str(i), [i-0.05, -0.25]) # X axis numbers
    plt.annotate(str(i), [-0.2, i-0.07]) # Y axis numbers

plt.show()
```

Body:
I'm new to matplotlib and numpy and am trying to plot some array data to something like this:

but it currently looks like this:

My code is extremely basic but basically the image above is what I'd like to be able to do. I'm not too concerned yet with drawing gridlines but  the plot should be proportional. I've looked at some examples on the mathplotlib website but can't find something similar enough.
I wonder if pyplot is not the correct procedure or if my array is not formatted correctly?

import numpy as np
from matplotlib import pyplot as plt

data = [(2, 2), (3, 2), (4, 1), (4, 0), (3, 0), (3, 1), (4, 2),
        (4, 3), (4, 4), (3, 3), (3, 4), (2, 4), (2, 3), (1, 4),
        (0, 4), (0, 3), (1, 3), (0, 2), (1, 2), (0, 1), (0, 0),
        (1, 0), (1, 1), (2, 0), (2, 1)]

data = np.asarray(data)
print(data)
plt.ylim(0, 4)
plt.xlim(0, 4)
plt.axis([0, 4, 0, 4])
plt.plot(data)
plt.show()

Body:
To complete other answers, here is the closest I got in a reasonable amount of time to your desired output :

import numpy as np
from matplotlib import pyplot as plt

data = [(2, 2), (3, 2), (4, 1), (4, 0), (3, 0), (3, 1), (4, 2),
        (4, 3), (4, 4), (3, 3), (3, 4), (2, 4), (2, 3), (1, 4),
        (0, 4), (0, 3), (1, 3), (0, 2), (1, 2), (0, 1), (0, 0),
        (1, 0), (1, 1), (2, 0), (2, 1)]

data = np.asarray(data)
print(data)

# make axis equal and turn them off
plt.axis('equal')
plt.axis('off')

for i in range(5):
    # horizontal and vertical background lines
    plt.plot([i,i], [0,4], linewidth=0.5, color='black')
    plt.plot([0,4], [i,i], linewidth=0.5, color='black')
plt.plot(data[:,0], data[:,1], 'b') # line segments
plt.scatter(data[:,0], data[:,1], c='b') # markers

plt.show()

Output:

Edit

From this question, you can add numbers at each marker through plt.annotate. Just add this after plt.scatter :

offset = np.array([0.1, 0.1])
for i in range(data.shape[0]):
    # For each marker
    plt.annotate(str(i+1), data[i]+offset)

Output:

Edit #2:

As a bonus, here is my attempt as getting the closest possible to the reference figure:

import numpy as np
from matplotlib import pyplot as plt

data = [(2, 2), (3, 2), (4, 1), (4, 0), (3, 0), (3, 1), (4, 2),
        (4, 3), (4, 4), (3, 3), (3, 4), (2, 4), (2, 3), (1, 4),
        (0, 4), (0, 3), (1, 3), (0, 2), (1, 2), (0, 1), (0, 0),
        (1, 0), (1, 1), (2, 0), (2, 1)]

data = np.asarray(data)
print(data)

# make axis equal and turn them off
plt.axis('equal')
plt.axis('off')

for i in range(5):
    # horizontal and vertical background lines
    plt.plot([i,i], [0,4], linewidth=1.5, color='#b3b3b3', zorder=1)
    plt.plot([0,4], [i,i], linewidth=1.5, color='#b3b3b3', zorder=1)

plt.plot(data[:,0], data[:,1], '#274b8b', linewidth=2.5, zorder=2) # line segments
plt.scatter(data[np.arange(len(data))!=7,0], data[np.arange(len(data))!=7,1], s=60, c='#4472c4', edgecolors='#2e569c', zorder=3) # markers
# marker for point 7 is not plotted in reference figure

# Individual points numbers, not in reference figure so commented
# offset = np.array([0.1, 0.1])
# for i in range(data.shape[0]):
    # # For each marker
    # plt.annotate(str(i+1), data[i]+offset)

for i in range(5):
    plt.annotate(str(i), [i-0.05, -0.25]) # X axis numbers
    plt.annotate(str(i), [-0.2, i-0.07]) # Y axis numbers

plt.show()


问:
Element wise multiplication of 2 pandas series containing matrices as elements
Suppose I have 2 pandas series, a and b, where the elements are matrices as follows

```<code>a = pd.Series([np.array([[1,2], [3,4]]), np.array([[1,2], [3,4]])])

b = pd.Series([np.array([[1,2], [3,4]]), np.array([[1,2], [3,4]])])

</code>```

I would like to multiply the series elements of a with b such that the output looks like:

output of series multiplication

I have the following solution which works:

```<code>
c = []

for i in range(a.shape[0]):

    c.append(np.matmul(a[i], b[i]))

</code>```

however, this requires a for loop and outputs a list rather than a .Series. Any ideas how this could be done in a more compact form? Thanks.

Body:
Suppose I have 2 pandas series, a and b, where the elements are matrices as follows

a = pd.Series([np.array([[1,2], [3,4]]), np.array([[1,2], [3,4]])])

b = pd.Series([np.array([[1,2], [3,4]]), np.array([[1,2], [3,4]])])

I would like to multiply the series elements of a with b such that the output looks like:

output of series multiplication

I have the following solution which works:

c = []

for i in range(a.shape[0]):

    c.append(np.matmul(a[i], b[i]))

however, this requires a for loop and outputs a list rather than a .Series. Any ideas how this could be done in a more compact form? Thanks.

Body:
IIUC use:

c = []

for i in range(a.shape[0]):

    c.append(np.matmul(a[i], b[i]))

print (pd.Series(c))

0    [[7, 10], [15, 22]]
1    [[7, 10], [15, 22]]
dtype: object

Or:

print (pd.Series([np.matmul(a[i], b[i]) for i in range(a.shape[0])]))

0    [[7, 10], [15, 22]]
1    [[7, 10], [15, 22]]
dtype: object


问:
Expected ASGI message 'websocket.accept' or 'websocket.close', but got 'http.response.start'
I want to connect websockets, but I get an error at startup.

uvicorn app:app --reload --ws websockets

requirements

OS: Linux Ubuntu 20.04 LTS

Python 3.8.6

Browser: Chrome 88.0.4324.182

fastapi==0.63.0

python-engineio==4.0.0

python-socketio==5.0.4

starlette==0.13.6

uvicorn==0.13.3

websockets==8.1

app.py

```<code>from typing import Optional

import socketio
from fastapi import FastAPI, Query, WebSocket

sio = socketio.AsyncServer(
    async_mode="asgi", cors_allowed_origins="*", logger=True, engineio_logger=True
)
app = FastAPI(debug=True)
app_socketio = socketio.ASGIApp(sio)
app.mount(path="/", app=app_socketio)

@app.websocket("/items/{item_id}/ws")
async def websocket_endpoint(
    websocket: WebSocket,
    item_id: str,
    q: Optional[int] = None,
):
    # pylint: disable=C0103,W0613
    await websocket.accept()
    while True:
        data: str = await websocket.receive_text()
</code>```

react-app

```<code>const Index: React.FC = () => {
    var ws = new WebSocket('ws://127.0.0.1:8000/items/1/ws')
}
</code>```

Traceback

```<code>Traceback (most recent call last):
  File "/home/m0nte-cr1st0/.virtualenvs/hypercube/lib/python3.8/site-packages/uvicorn/protocols/websockets/websockets_impl.py", line 157, in run_asgi
    result = await self.app(self.scope, self.asgi_receive, self.asgi_send)
  File "/home/m0nte-cr1st0/.virtualenvs/hypercube/lib/python3.8/site-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
    return await self.app(scope, receive, send)
  File "/home/m0nte-cr1st0/.virtualenvs/hypercube/lib/python3.8/site-packages/fastapi/applications.py", line 199, in __call__
    await super().__call__(scope, receive, send)
  File "/home/m0nte-cr1st0/.virtualenvs/hypercube/lib/python3.8/site-packages/starlette/applications.py", line 111, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/home/m0nte-cr1st0/.virtualenvs/hypercube/lib/python3.8/site-packages/starlette/middleware/errors.py", line 146, in __call__
    await self.app(scope, receive, send)
  File "/home/m0nte-cr1st0/.virtualenvs/hypercube/lib/python3.8/site-packages/starlette/exceptions.py", line 58, in __call__
    await self.app(scope, receive, send)
  File "/home/m0nte-cr1st0/.virtualenvs/hypercube/lib/python3.8/site-packages/starlette/routing.py", line 566, in __call__
    await route.handle(scope, receive, send)
  File "/home/m0nte-cr1st0/.virtualenvs/hypercube/lib/python3.8/site-packages/starlette/routing.py", line 376, in handle
    await self.app(scope, receive, send)
  File "/home/m0nte-cr1st0/.virtualenvs/hypercube/lib/python3.8/site-packages/engineio/async_drivers/asgi.py", line 65, in __call__
    await self.not_found(receive, send)
  File "/home/m0nte-cr1st0/.virtualenvs/hypercube/lib/python3.8/site-packages/engineio/async_drivers/asgi.py", line 110, in not_found
    await send({'type': 'http.response.start',
  File "/home/m0nte-cr1st0/.virtualenvs/hypercube/lib/python3.8/site-packages/uvicorn/protocols/websockets/websockets_impl.py", line 209, in asgi_send
    raise RuntimeError(msg % message_type)
RuntimeError: Expected ASGI message 'websocket.accept' or 'websocket.close', but got 'http.response.start'.
</code>```

答:
```<code>const Index: React.FC = () => {
var ws = new WebSocket('ws://127.0.0.1:8000/items/1/ws')
</code>```

}

make this function async and await and try again

Body:
I want to connect websockets, but I get an error at startup.

uvicorn app:app --reload --ws websockets

requirements

OS: Linux Ubuntu 20.04 LTS

Python 3.8.6

Browser: Chrome 88.0.4324.182

fastapi==0.63.0

python-engineio==4.0.0

python-socketio==5.0.4

starlette==0.13.6

uvicorn==0.13.3

websockets==8.1

app.py

from typing import Optional

import socketio
from fastapi import FastAPI, Query, WebSocket

sio = socketio.AsyncServer(
    async_mode="asgi", cors_allowed_origins="*", logger=True, engineio_logger=True
)
app = FastAPI(debug=True)
app_socketio = socketio.ASGIApp(sio)
app.mount(path="/", app=app_socketio)

@app.websocket("/items/{item_id}/ws")
async def websocket_endpoint(
    websocket: WebSocket,
    item_id: str,
    q: Optional[int] = None,
):
    # pylint: disable=C0103,W0613
    await websocket.accept()
    while True:
        data: str = await websocket.receive_text()

react-app

const Index: React.FC = () => {
    var ws = new WebSocket('ws://127.0.0.1:8000/items/1/ws')
}

Traceback

Traceback (most recent call last):
  File "/home/m0nte-cr1st0/.virtualenvs/hypercube/lib/python3.8/site-packages/uvicorn/protocols/websockets/websockets_impl.py", line 157, in run_asgi
    result = await self.app(self.scope, self.asgi_receive, self.asgi_send)
  File "/home/m0nte-cr1st0/.virtualenvs/hypercube/lib/python3.8/site-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
    return await self.app(scope, receive, send)
  File "/home/m0nte-cr1st0/.virtualenvs/hypercube/lib/python3.8/site-packages/fastapi/applications.py", line 199, in __call__
    await super().__call__(scope, receive, send)
  File "/home/m0nte-cr1st0/.virtualenvs/hypercube/lib/python3.8/site-packages/starlette/applications.py", line 111, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/home/m0nte-cr1st0/.virtualenvs/hypercube/lib/python3.8/site-packages/starlette/middleware/errors.py", line 146, in __call__
    await self.app(scope, receive, send)
  File "/home/m0nte-cr1st0/.virtualenvs/hypercube/lib/python3.8/site-packages/starlette/exceptions.py", line 58, in __call__
    await self.app(scope, receive, send)
  File "/home/m0nte-cr1st0/.virtualenvs/hypercube/lib/python3.8/site-packages/starlette/routing.py", line 566, in __call__
    await route.handle(scope, receive, send)
  File "/home/m0nte-cr1st0/.virtualenvs/hypercube/lib/python3.8/site-packages/starlette/routing.py", line 376, in handle
    await self.app(scope, receive, send)
  File "/home/m0nte-cr1st0/.virtualenvs/hypercube/lib/python3.8/site-packages/engineio/async_drivers/asgi.py", line 65, in __call__
    await self.not_found(receive, send)
  File "/home/m0nte-cr1st0/.virtualenvs/hypercube/lib/python3.8/site-packages/engineio/async_drivers/asgi.py", line 110, in not_found
    await send({'type': 'http.response.start',
  File "/home/m0nte-cr1st0/.virtualenvs/hypercube/lib/python3.8/site-packages/uvicorn/protocols/websockets/websockets_impl.py", line 209, in asgi_send
    raise RuntimeError(msg % message_type)
RuntimeError: Expected ASGI message 'websocket.accept' or 'websocket.close', but got 'http.response.start'.

Body:
const Index: React.FC = () => {
var ws = new WebSocket('ws://127.0.0.1:8000/items/1/ws')

}

make this function async and await and try again


问:
How to update Rundeck project setting using CLI
I want  update project settings for existing Rundeck Project. For example : add resources / nodes to the Rundeck project using CLI. How do I do that?</p>

答:
Here more useful Rundeck CLI project commands:

```<code># create project
rd projects create -p project1

# get project configuration
rd projects configure get -p project1

# Configure nodes from remote URL (GitLab)
rd projects configure update -p project1 -- \
  --resources.source.1.type=url \
  --resources.source.1.config.url='https://git.i.example.com/api/v4/projects/3/repository/files/project1%2Fdev%2Fnodes.json/raw?ref=master&private_token=1234567890' \
  --resources.source.1.config.timeout=10 \
  --resources.source.1.config.cache=false
</code>```

See also Rundeck CLI documentation and project parameter.

Body:
Here more useful Rundeck CLI project commands:

# create project
rd projects create -p project1

# get project configuration
rd projects configure get -p project1

# Configure nodes from remote URL (GitLab)
rd projects configure update -p project1 -- \
  --resources.source.1.type=url \
  --resources.source.1.config.url='https://git.i.example.com/api/v4/projects/3/repository/files/project1%2Fdev%2Fnodes.json/raw?ref=master&private_token=1234567890' \
  --resources.source.1.config.timeout=10 \
  --resources.source.1.config.cache=false

See also Rundeck CLI documentation and project parameter.


问:
Python - Polars - value counts on string column
How to apply word count on Polars DataFrame
I have a string column and I want to make a word count on all text.
Thanks

DataFrame example:

```<code>0                             Would never order again.
1    I'm not sure it gives me any type of glow and ...
2    Goes on smoothly a bit sticky and color is clo...
3        Preferisco altri prodotti della stessa marca.
4         The moisturizing advertised is non-existent.
</code>```

If I am using pandas it goes like this

```<code>df.Description.str.split(expand=True).stack().value_counts().reset_index()
</code>```

Results:

```<code>           index  0
0             the  2
1             and  2
2           brown  2
3              is  2
4             any  1
5             The  1
6    moisturizing  1
7            like  1
8             I'm  1
9             not  1
10         closer  1
11         stessa  1
12       prodotti  1
13  non-existent.  1
14     advertised  1
15              I  1
16             of  1
17          order  1
</code>```

...

答:
You can do something like this:

csv = """
0,                            Would never order again.
1,   I'm not sure it gives me any type of glow and ...
2,   Goes on smoothly a bit sticky and color is clo...
3,       Preferisco altri prodotti della stessa marca.
4,        The moisturizing advertised is non-existent.
""".encode()

(pl.read_csv(csv, has_header=False, new_columns=["idx", "lines"])
    .select(pl.col("lines").str.split(" ").flatten().alias("words"))
    .groupby("words").agg(pl.count())
    .sort("count", reverse=True)
    .filter(pl.col("words").str.lengths() > 0)
)

```
<p>Or like this:</p>
<pre class="lang-py prettyprint-override"><code>(pl.read_csv(csv, has_header=False, new_columns=["idx", "lines"])
    .select(pl.col("lines").str.split(" ").flatten().alias("words"))
    .to_series()
    .value_counts()
    .filter(pl.col("words").str.lengths() > 0)
)
</code>```

Both output:

```<code>shape: (35, 2)
┌────────┬───────┐
│ words  ┆ count │
│ ---    ┆ ---   │
│ str    ┆ u32   │
╞════════╪═══════╡
│ is     ┆ 2     │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ and    ┆ 2     │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ order  ┆ 1     │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ it     ┆ 1     │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ ...    ┆ ...   │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ Goes   ┆ 1     │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ The    ┆ 1     │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ stessa ┆ 1     │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ altri  ┆ 1     │
└────────┴───────┘

</code>```
```<code></code>```

Body:
How to apply word count on Polars DataFrame
I have a string column and I want to make a word count on all text.
Thanks

DataFrame example:

0                             Would never order again.
1    I'm not sure it gives me any type of glow and ...
2    Goes on smoothly a bit sticky and color is clo...
3        Preferisco altri prodotti della stessa marca.
4         The moisturizing advertised is non-existent.

If I am using pandas it goes like this

df.Description.str.split(expand=True).stack().value_counts().reset_index()

Results:

           index  0
0             the  2
1             and  2
2           brown  2
3              is  2
4             any  1
5             The  1
6    moisturizing  1
7            like  1
8             I'm  1
9             not  1
10         closer  1
11         stessa  1
12       prodotti  1
13  non-existent.  1
14     advertised  1
15              I  1
16             of  1
17          order  1

...

Body:
You can do something like this:

csv = """
0,                            Would never order again.
1,   I'm not sure it gives me any type of glow and ...
2,   Goes on smoothly a bit sticky and color is clo...
3,       Preferisco altri prodotti della stessa marca.
4,        The moisturizing advertised is non-existent.
""".encode()

(pl.read_csv(csv, has_header=False, new_columns=["idx", "lines"])
    .select(pl.col("lines").str.split(" ").flatten().alias("words"))
    .groupby("words").agg(pl.count())
    .sort("count", reverse=True)
    .filter(pl.col("words").str.lengths() > 0)
)

Or like this:

(pl.read_csv(csv, has_header=False, new_columns=["idx", "lines"])
    .select(pl.col("lines").str.split(" ").flatten().alias("words"))
    .to_series()
    .value_counts()
    .filter(pl.col("words").str.lengths() > 0)
)

Both output:

shape: (35, 2)
┌────────┬───────┐
│ words  ┆ count │
│ ---    ┆ ---   │
│ str    ┆ u32   │
╞════════╪═══════╡
│ is     ┆ 2     │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ and    ┆ 2     │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ order  ┆ 1     │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ it     ┆ 1     │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ ...    ┆ ...   │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ Goes   ┆ 1     │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ The    ┆ 1     │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ stessa ┆ 1     │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ altri  ┆ 1     │
└────────┴───────┘


问:
ioredis - I can't filter data
First, I created a form. Every time users type an entry, it shouldn't be overwritten. so it needs to be added as an extra, I found the append command in redis and applied it. But now I don't know how to filter and fetch the data.

Append command, here I am making the data JSON

```<code>const newEntry = {
      owner_id,
      message,
      created_at: Date.now(),
      score: 1,
      ip: 'NA',
    }
await redis.append('features', JSON.stringify(newEntry))
</code>```

JSON example, I need to filter with owner_id:

```<code>{"owner_id":30902468,"message":"test","created_at":1643755923014,"score":1,"ip":"NA"}
</code>```

Redis docs here

ioredis

答:
The APPEND works on strings, it's not exactly what you are looking for...

You can use lists and create a list for each user:

const newEntry = {
  owner_id,
  message,
  created_at: Date.now(),
  score: 1,
  ip: 'NA'
};

await redis.rpush(`features:${owner_id}`, JSON.stringify(newEntry));

await redis.lrange(`features:${owner_id}`, 0, -1);
```

In case you need to run more complicated queries, you should consider RediSearch + RedisJSON

Title: ioredis - I can't filter data

Body:
First, I created a form. Every time users type an entry, it shouldn't be overwritten. so it needs to be added as an extra, I found the append command in redis and applied it. But now I don't know how to filter and fetch the data.

Append command, here I am making the data JSON

const newEntry = {
      owner_id,
      message,
      created_at: Date.now(),
      score: 1,
      ip: 'NA',
    }
await redis.append('features', JSON.stringify(newEntry))

JSON example, I need to filter with owner_id:

{"owner_id":30902468,"message":"test","created_at":1643755923014,"score":1,"ip":"NA"}

Redis docs here

ioredis

Body:
The APPEND works on strings, it's not exactly what you are looking for...

You can use lists and create a list for each user:

const newEntry = {
  owner_id,
  message,
  created_at: Date.now(),
  score: 1,
  ip: 'NA'
};

await redis.rpush(`features:${owner_id}`, JSON.stringify(newEntry));

await redis.lrange(`features:${owner_id}`, 0, -1);

In case you need to run more complicated queries, you should consider RediSearch + RedisJSON


问:
SpringBoot fully executable jar without dependencies inside
NOTE: Please, before marking this question as a duplicate make sure you know the difference between executable JAR and fully executable SpringBoot JAR.

The official Spring Boot documentation describes how to build fully executable JAR. Then generated JAR file can be linked from /etc/init.d/ and started/stopped/restarted/statused as a normal unix service without additional scripts or tools like JSVC.

But the generated JAR contains all libraries and can be big enough in size (in my case 70Mb+).

I want to generate such fully executable JAR without libraries, but then to be able to run it as SystemV service on Linux and link external libraries (JARs) somehow.

UPDATE

I want to reduce the artifact size in order to speed up deploy->test->fix cycle. Sometimes I'm working via mobile network and big file size can decrease my job speed dramatically.

In case there is no a simple configuration property or a profile or a command line option I would use a kind of hack.

At the beginning, I can generate a build containing all dependencies.
Then I can unzip it and move all libraries to a special folder.

Then I need to pack it again as fully executable somehow and run with pointing to the folder with libraries.

I don't think this can be done with jar utility because file utility recognizes fully executable jar as data

```<code>$ file fully-executable.jar
file fully-executable: data
</code>```

unlike the usual jar

```<code>$ file usual.jar
usual.jar: Java Jar file data (zip)
</code>```

答:
I can use this setting to create spring boot jar without dependency jars.

Copy dependency jars to dist/lib

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <executions>
        <execution>
            <id>copy-dependencies</id>
            <phase>package</phase>
            <goals>
                <goal>copy-dependencies</goal>
            </goals>
            <configuration>
                <includeScope>runtime</includeScope>
                <outputDirectory>${project.build.directory}/dist/lib</outputDirectory>
            </configuration>
        </execution>
    </executions>
</plugin>
</code>```

Specify 'lib' as classpath prefix, so MAINFEST.MF will be created like this:

Class-Path:lib/httpcore-nio-4.4.14.jar lib/guava-24.1.1-jre.jar...

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <configuration>
        <archive>
            <manifest>
                <addClasspath>true</addClasspath>
                <classpathPrefix>lib/</classpathPrefix>
                <mainClass>com.xxx.MyMainClass</mainClass>
            </manifest>
        </archive>
        <outputDirectory>${project.build.directory}/dist</outputDirectory>
    </configuration>
</plugin>
</code>```

Let spring boot plugin includes dependency which is not existing, will cause spring boot jar exclude all dependencies.

```<code><plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <executions>
        <execution>
            <goals>
                <goal>repackage</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <layout>ZIP</layout>
        <includes>
            <include>
                <groupId>not-exist-in-my-project</groupId>
                <artifactId>not-exist-in-my-project</artifactId>
            </include>
        </includes>
        <outputDirectory>${project.build.directory}/dist</outputDirectory>
    </configuration>
</plugin>
</code>```

Body:
NOTE: Please, before marking this question as a duplicate make sure you know the difference between executable JAR and fully executable SpringBoot JAR.

The official Spring Boot documentation describes how to build fully executable JAR. Then generated JAR file can be linked from /etc/init.d/ and started/stopped/restarted/statused as a normal unix service without additional scripts or tools like JSVC.

But the generated JAR contains all libraries and can be big enough in size (in my case 70Mb+).

I want to generate such fully executable JAR without libraries, but then to be able to run it as SystemV service on Linux and link external libraries (JARs) somehow.

UPDATE

I want to reduce the artifact size in order to speed up deploy->test->fix cycle. Sometimes I'm working via mobile network and big file size can decrease my job speed dramatically.

In case there is no a simple configuration property or a profile or a command line option I would use a kind of hack.

At the beginning, I can generate a build containing all dependencies.
Then I can unzip it and move all libraries to a special folder.

Then I need to pack it again as fully executable somehow and run with pointing to the folder with libraries.

I don't think this can be done with jar utility because file utility recognizes fully executable jar as data

$ file fully-executable.jar
file fully-executable: data

unlike the usual jar

$ file usual.jar
usual.jar: Java Jar file data (zip)

Body:
I can use this setting to create spring boot jar without dependency jars.

Copy dependency jars to dist/lib

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <executions>
        <execution>
            <id>copy-dependencies</id>
            <phase>package</phase>
            <goals>
                <goal>copy-dependencies</goal>
            </goals>
            <configuration>
                <includeScope>runtime</includeScope>
                <outputDirectory>${project.build.directory}/dist/lib</outputDirectory>
            </configuration>
        </execution>
    </executions>
</plugin>

Specify 'lib' as classpath prefix, so MAINFEST.MF will be created like this:

Class-Path:lib/httpcore-nio-4.4.14.jar lib/guava-24.1.1-jre.jar...

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <configuration>
        <archive>
            <manifest>
                <addClasspath>true</addClasspath>
                <classpathPrefix>lib/</classpathPrefix>
                <mainClass>com.xxx.MyMainClass</mainClass>
            </manifest>
        </archive>
        <outputDirectory>${project.build.directory}/dist</outputDirectory>
    </configuration>
</plugin>

Let spring boot plugin includes dependency which is not existing, will cause spring boot jar exclude all dependencies.

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <executions>
        <execution>
            <goals>
                <goal>repackage</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <layout>ZIP</layout>
        <includes>
            <include>
                <groupId>not-exist-in-my-project</groupId>
                <artifactId>not-exist-in-my-project</artifactId>
            </include>
        </includes>
        <outputDirectory>${project.build.directory}/dist</outputDirectory>
    </configuration>
</plugin>


问:
Scilab/Matlab binary search algorithm
I'm trying to solve a problem
"Construct an algorithm that, for a non-randomly ordered one-dimensional array, determines the multiplicity of occurrences of a given value. Note: use a binary search algorithm for this purpose"

I came up with the idea of searching for the first appearance of the given value, and then using the while loop I will check how many times it appeared.

I wrote some code that works but I have the following problems with it

```<code>
function tab=tablica(N)
    tab=floor(N*rand(1,N))
endfunction

function tab=tablicaP(N)
    tab=gsort(tablica(N),'g','i')
endfunction

function wynik=szukam(T,X)
    P=1
    K=length(T)
    s=0
    i=0
    while P<=K
        s=floor((P+K)/2)
        if T(s) == X then
            //wynik = s
            if T(s) == 1 then
               // wynik = s
                break
             else
             if T(s-1) == X then
                 K = s -1
             else
                // wynik = s
                 break
             end
          end
        elseif T(s) < X then
            P = s+1
        else
            K=s-1
            end
    end

while T(s) == X  do
    i=i+1
     s=s+1
   end

wynik = i
endfunction

</code>```

But while trying to search for 8 i got this error, and honestly i dont know what to do with this

```<code>at line    28 of function szukam ( C:\Users\Tragu\Desktop\algorytm11.sce line 42 )

Invalid index.
</code>```

Also sometimes while trying to reach first index in table i get this error

```<code> tab2  =

   0.   4.   5.   5.   5.   6.   6.   6.   7.   8.   8.   8.   9.   9.   10.   11.   11.   12.   18.   18.

--> szukam(tab2,8)
 ans  =

   3.

--> szukam(tab2,0)
at line    14 of function szukam ( C:\Users\Tragu\Desktop\algorytm11.sce line 28 )

Invalid index.```

So my main issue is somewhat related to first and last index of table.
Any tips or how to deal with that?
```

答:
You have to use successive binary search to find both start and end of your sequence. Here your last loop falls back to O(n) complexity. Here is a working code (BTW your code fails because you do not take into account limiting cases, below s==1 and e==n):

```<code>a=[0 4 5 5 5 6 6 6 7 8 8 8 9 9 10 11];
n=length(a);
k=[1 n];
v=8;

while k(2) >= k(1)
    s=floor(mean(k));
    if (s==1 || a(s-1)<v) && a(s)==v
        break
    elseif a(s)<v
        k(1)=s+1;
    else
        k(2)=s-1;
    end
end

if k(2) >= k(1)
    k=[s n];
    while k(2) >= k(1)
        e=floor(mean(k));
        if (e==n || a(e+1)>v) && a(e)==v
            break
        elseif a(e)<=v
            k(1)=e+1;
        else
            k(2)=e-1;
        end
    end
end

disp(s,e)

   10.

   12.
</code>```

If the value is not found k(1) > k(2). You can find recursive implementations there: https://www.geeksforgeeks.org/find-first-and-last-positions-of-an-element-in-a-sorted-array/

Title: Scilab/Matlab binary search algorithm

Body:
I'm trying to solve a problem
"Construct an algorithm that, for a non-randomly ordered one-dimensional array, determines the multiplicity of occurrences of a given value. Note: use a binary search algorithm for this purpose"

I came up with the idea of searching for the first appearance of the given value, and then using the while loop I will check how many times it appeared.

I wrote some code that works but I have the following problems with it

function tab=tablica(N)
    tab=floor(N*rand(1,N))
endfunction

function tab=tablicaP(N)
    tab=gsort(tablica(N),'g','i')
endfunction

function wynik=szukam(T,X)
    P=1
    K=length(T)
    s=0
    i=0
    while P<=K
        s=floor((P+K)/2)
        if T(s) == X then
            //wynik = s
            if T(s) == 1 then
               // wynik = s
                break
             else
             if T(s-1) == X then
                 K = s -1
             else
                // wynik = s
                 break
             end
          end
        elseif T(s) < X then
            P = s+1
        else
            K=s-1
            end
    end

while T(s) == X  do
    i=i+1
     s=s+1
   end

wynik = i
endfunction

But while trying to search for 8 i got this error, and honestly i dont know what to do with this

at line    28 of function szukam ( C:\Users\Tragu\Desktop\algorytm11.sce line 42 )

Invalid index.

Also sometimes while trying to reach first index in table i get this error

 tab2  =

   0.   4.   5.   5.   5.   6.   6.   6.   7.   8.   8.   8.   9.   9.   10.   11.   11.   12.   18.   18.

--> szukam(tab2,8)
 ans  =

   3.

--> szukam(tab2,0)
at line    14 of function szukam ( C:\Users\Tragu\Desktop\algorytm11.sce line 28 )

Invalid index.```

So my main issue is somewhat related to first and last index of table.
Any tips or how to deal with that?

Body:
You have to use successive binary search to find both start and end of your sequence. Here your last loop falls back to O(n) complexity. Here is a working code (BTW your code fails because you do not take into account limiting cases, below s==1 and e==n):

a=[0 4 5 5 5 6 6 6 7 8 8 8 9 9 10 11];
n=length(a);
k=[1 n];
v=8;

while k(2) >= k(1)
    s=floor(mean(k));
    if (s==1 || a(s-1)<v) && a(s)==v
        break
    elseif a(s)<v
        k(1)=s+1;
    else
        k(2)=s-1;
    end
end

if k(2) >= k(1)
    k=[s n];
    while k(2) >= k(1)
        e=floor(mean(k));
        if (e==n || a(e+1)>v) && a(e)==v
            break
        elseif a(e)<=v
            k(1)=e+1;
        else
            k(2)=e-1;
        end
    end
end

disp(s,e)

   10.

   12.

If the value is not found k(1) > k(2). You can find recursive implementations there: https://www.geeksforgeeks.org/find-first-and-last-positions-of-an-element-in-a-sorted-array/


问:
SQLAlchemy async event listen engine.sync_engine SET string parameter replacement
I am trying to listen to the engine_connect event, grab the cursor on that connection, then issue a SET query, however I can't seem to get the parameter replacement to work. I ONLY have this issue with async engine which uses from sqlalchemy.dialects.postgresql.asyncpg import AsyncAdapt_asyncpg_cursor as its cursor.
Notice that I am able to use parameter substitution in a SELECT query, but not in a SET query.

Here's the error:

```<code>sqlalchemy.dialects.postgresql.asyncpg.ProgrammingError: <class 'asyncpg.exceptions.PostgresSyntaxError'>: syntax error at or near "$1"
</code>```

and heres a code snippet to reproduce

import asyncio

from sqlalchemy import event
from sqlalchemy.engine import make_url
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker

db_url = make_url('postgresql://xxx:yyy@127.0.0.1/my_db')

async_db_url = db_url.set(drivername="postgresql+asyncpg")
engine = create_async_engine(
    async_db_url,
    pool_timeout=5,
    pool_pre_ping=True,
    pool_recycle=600,
    future=True,
)

async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False, future=True,)

def foobar_engine_connect_listener(connection, branch):
    identity = "arn:aws:sts::123456:assumed-role/thing_1"
    cursor = connection.connection.cursor()

    # THIS WORKS
    cursor.execute(
        "select %s", (identity,)
    )

    # THIS THROWS THE ERROR
    cursor.execute(
        "set session iam.identity = %s", (identity,)
    )

event.listens_for(engine.sync_engine, "engine_connect")(foobar_engine_connect_listener)

async def go():
    async with async_session() as session:
        await session.execute('select 1')

if __name__ == "__main__":
    asyncio.run(go())

```

答:
The solution ended up being set_config with %s param format:

cursor.execute("select set_config('iam.identity', %s, false)", (identity,))

```

Body:
I am trying to listen to the engine_connect event, grab the cursor on that connection, then issue a SET query, however I can't seem to get the parameter replacement to work. I ONLY have this issue with async engine which uses from sqlalchemy.dialects.postgresql.asyncpg import AsyncAdapt_asyncpg_cursor as its cursor.
Notice that I am able to use parameter substitution in a SELECT query, but not in a SET query.

Here's the error:

sqlalchemy.dialects.postgresql.asyncpg.ProgrammingError: <class 'asyncpg.exceptions.PostgresSyntaxError'>: syntax error at or near "$1"

and heres a code snippet to reproduce

import asyncio

from sqlalchemy import event
from sqlalchemy.engine import make_url
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker

db_url = make_url('postgresql://xxx:yyy@127.0.0.1/my_db')

async_db_url = db_url.set(drivername="postgresql+asyncpg")
engine = create_async_engine(
    async_db_url,
    pool_timeout=5,
    pool_pre_ping=True,
    pool_recycle=600,
    future=True,
)

async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False, future=True,)

def foobar_engine_connect_listener(connection, branch):
    identity = "arn:aws:sts::123456:assumed-role/thing_1"
    cursor = connection.connection.cursor()

    # THIS WORKS
    cursor.execute(
        "select %s", (identity,)
    )

    # THIS THROWS THE ERROR
    cursor.execute(
        "set session iam.identity = %s", (identity,)
    )

event.listens_for(engine.sync_engine, "engine_connect")(foobar_engine_connect_listener)

async def go():
    async with async_session() as session:
        await session.execute('select 1')

if __name__ == "__main__":
    asyncio.run(go())


问:
Download a file in D
How do I download a file in D? I have checked out the standard library, and the sample. I would rather use phobos with the newest dmd2 than tango. All I need to do is download a file (hopefully using std.socket and std.socketstream). Could also use etc.c.curl.</p>

答:
etc.c.curl provides the C bindings for curl, so you could use that. That's really the only way that I know of to do it using Phobos at the moment, unless you want to do it with std.socket and handle the HTTP requests and responses yourself (which I assume that you don't really want to do).

However, a D wrapper for the C curl bindings is currently in review in the digitalmars.D newsgroup, which would give you a D API for interacting with curl. Assuming that it passes review (which it probably will, though it may change a fair bit during the review process), it'll end up in Phobos. Once it's merged in, it'll be in the following release. So, it'll probably be in either 2.055 or 2.056, depending on when 2.055 gets released.

Until then, however, you're pretty much going to need to either use the C bindings or download the D curl wrapper currently under review. You can find the documentation here and the code here if you want to try it out. If you do that however, it would be much appreciated if you chimed in on the review in the newsgroup to give feedback on it so that it can be appropriately ironed out and improved prior to inclusion in Phobos.

Title: Download a file in D


问:
html - Pictures not showing up on Heroku?
I deployed my static HTML website to Heroku using this tutorial (http://www.lemiffe.com/how-to-deploy-a-static-page-to-heroku-the-easy-way/) and my pictures won't show up ? It works perfect locally so I don't really understand why it doesn't when it's deployed on Heroku ?

I've also looked up every other solution that stackoverflow has to offer and nothing worked for me. Any help is really appreciated

Here is the order of my folders/files (folders are capitalized):

```<code>-RESUMEAPPCOPY
  -home.html
  -portfolio.html
  -index.php
  -aboutme.html
-PUBLIC
  -IMG
  -JS
  -CSS
</code>```

Code for image:

```<code> <img src="/Users/erv/Desktop/MyProjects/resumeappcopy/public/img/PennUnitedWebsite.PNG" alt="PUSA-Icon" class="img-rounded" style="height: 300px;"/>
</code>```

Whenever I inspect the element on Heroku it says :

```<code>Failed to load resource: the server responded with a status of 404 (Not Found)
</code>```

and where the picture is supposed to be I have the typical broken image link picture

答: I had the same problem: case-sensitive png files. But to fix the issue I suggest lowerCasing them AND changing the name of the image file. This way you can be safe (and more organized in your versions) when you commit them to git and push to heroku</p>

Body:
I deployed my static HTML website to Heroku using this tutorial (http://www.lemiffe.com/how-to-deploy-a-static-page-to-heroku-the-easy-way/) and my pictures won't show up ? It works perfect locally so I don't really understand why it doesn't when it's deployed on Heroku ?

I've also looked up every other solution that stackoverflow has to offer and nothing worked for me. Any help is really appreciated

Here is the order of my folders/files (folders are capitalized):

-RESUMEAPPCOPY
  -home.html
  -portfolio.html
  -index.php
  -aboutme.html
-PUBLIC
  -IMG
  -JS
  -CSS

Code for image:

Whenever I inspect the element on Heroku it says :

Failed to load resource: the server responded with a status of 404 (Not Found)

and where the picture is supposed to be I have the typical broken image link picture