问:
ROS subscriber to socket in python
Hi everyone I would like to implement a python ros node that subscribes to a topic (odom in my case) and retransmits part of the message on a socket. I have already implemented such a thing:

```<code>#!/usr/bin/env python
import rospy
from std_msgs.msg import String
import socket
import sys
from nav_msgs.msg import Odometry
import struct
from time import sleep
import socket, threading

class ClientThread(threading.Thread):
    def __init__(self,clientAddress,clientsocket):
        threading.Thread.__init__(self)
        self.csocket = clientsocket
        print ("New connection added: ", clientAddress)
        rospy.init_node('serverOdom', anonymous=True)
        rospy.Subscriber('odom',Odometry, callback)
        print ("New subscriber 'severOdom' added: ")

    def run(self):
        rospy.spin()

def callback(msg):
    string=str(msg.pose.pose.position.x)+"\n"+str(msg.pose.pose.position.y)+"\n"
    try:
        ##How i can refeer to the socket??
        self.csocket.send(string.encode())
        print (string)
    except socket.error:
        print ("Error client lost")
        ##How to exit from spin()??

if __name__ == '__main__':
    LOCALHOST = "192.168.2.150"
    PORT = 5005
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind((LOCALHOST, PORT))
    print("Server started")
    print("Waiting for client request..")
    while True:
        server.listen(1)
        clientsock, clientAddress = server.accept()
        newthread = ClientThread(clientAddress, clientsock)
        newthread.start()
</code>```

now I have two problems:
The first one that inside the callback function I can't use

```<code>self.csocket.send(string.encode())
</code>```

and i don't know how to send the string to the client.

The second is that if the client disconnects I cannot exit the callback function

some idea? I'm a beginner with python and ros, thanks in advance

EDIT:
I founded a solution. maybe it's not elegant but it works.

```<code>#!/usr/bin/env python
import rospy
from std_msgs.msg import String
import socket
import sys
from nav_msgs.msg import Odometry
import struct
from time import sleep
import socket, threading

class ClientThread(threading.Thread):
    def __init__(self,clientAddress,clientsocket):
        threading.Thread.__init__(self)
        self.csocket = clientsocket
        print ("New connection added: ", clientAddress)
        rospy.init_node('serverOdom', anonymous=True)
        rospy.Subscriber('odom',Odometry, callback)
        print ("New subscriber 'severOdom' added: ")

    def run(self):
        while True:
            msg = rospy.wait_for_message("odom", Odometry, timeout=None)
            string=str(msg.pose.pose.position.x)+"\n"+str(msg.pose.pose.position.y)+"\n"
            try:
                self.csocket.send(string.encode())
            except socket.error:
                print ("Error client lost", clientAddress)
                return

def callback(msg):
    pass

if __name__ == '__main__':
    LOCALHOST = ""
    PORT = 5005
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind((LOCALHOST, PORT))
    print("Server started")
    print("Waiting for client request..")
    while True:
        sleep(2)
        server.listen(5)
        clientsock, clientAddress = server.accept()
        newthread = ClientThread(clientAddress, clientsock)
        newthread.start()
</code>```

I needed more clients to connect and that when the connection with a client was lost (for example because the client was closed) the thread created by the server ended.
with my solution for each thread created by the server a subscriber is also created, probably it would be better to use a single subscriber for all the threads created, but for now I have not been able to do it.

答:
If you define the callback as a member of ClientThread, you can access self. Ex

```<code>class ClientThread(...):
    def callback(self, msg):
        self.csocket.send(string.encode())
</code>```

Also, your control flow is all wonky. All the init for the node should happen in main; that's why your confused. Ex of a python node.

Also, your code doesn't quite make sense, as it seems to be both the server and the client. Ex. here is a light rewrite, but it doesn't really make sense & won't behave right. (Except the ros parts should be correct). Like, it seems that you're trying to use threading... to do the job of ros, in which each node is like a thread already.

```<code># server_odom.py

# Ros imports
import rospy
from std_msgs.msg import String
from nav_msgs.msg import Ododmetry

# Sys imports
import sys
import socket
import struct
import threading
from time import sleep

class ClientThread(threading.Thread):
    def __init__(self,clientAddress,clientsocket):
        threading.Thread.__init__(self)
        self.csocket = clientsocket
        print ("New connection added: ", clientAddress)
        rospy.init_node('serverOdom', anonymous=True)
        rospy.Subscriber('odom',Odometry, self.callback)
        print ("New subscriber 'severOdom' added: ")

    def run(self):
        rospy.spin()

    def callback(self, msg):
        string=str(msg.pose.pose.position.x)+"\n"+str(msg.pose.pose.position.y)+"\n"
        try:
            self.csocket.send(string.encode())
            print (string)
        except socket.error:
            print ("Error client lost")
            return

if __name__ == '__main__':
    LOCALHOST = ""
    PORT = 5005
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind((LOCALHOST, PORT))
    print("Server started")
    print("Waiting for client request..")
    while True:
        sleep(2)
        server.listen(5)
        clientsock, clientAddress = server.accept()
        newthread = ClientThread(clientAddress, clientsock)
        newthread.start()
</code>```

If you just mean to format an odometry message to a string or serial buffer, it's significantly less code.

```<code># server_odom_min.py

# Ros imports
import rospy
from std_msgs.msg import String
from nav_msgs.msg import Ododmetry

str_pub = None

def callback(self, msg):
    s = String()
    s.data = str(msg.pose.pose.position.x)+"\n"+str(msg.pose.pose.position.y)+"\n"
    if str_pub:
        str_pub.publish(s)

if __name__ == '__main__':
    rospy.init_node('server_odom_min')
    rospy.Subscriber('odom', Odometry, callback)
    str_pub = rospy.Publisher('odom/string', String, queue_size = 1)
    rospy.spin()
</code>```

Edit (in response to edit):
I see what you're doing now, my bad; the second example doesn't really apply to this question. I edited my first example to reflect what you mean.

Title: ROS subscriber to socket in python

Body:
Hi everyone I would like to implement a python ros node that subscribes to a topic (odom in my case) and retransmits part of the message on a socket. I have already implemented such a thing:

#!/usr/bin/env python
import rospy
from std_msgs.msg import String
import socket
import sys
from nav_msgs.msg import Odometry
import struct
from time import sleep
import socket, threading

class ClientThread(threading.Thread):
    def __init__(self,clientAddress,clientsocket):
        threading.Thread.__init__(self)
        self.csocket = clientsocket
        print ("New connection added: ", clientAddress)
        rospy.init_node('serverOdom', anonymous=True)
        rospy.Subscriber('odom',Odometry, callback)
        print ("New subscriber 'severOdom' added: ")

    def run(self):
        rospy.spin()

def callback(msg):
    string=str(msg.pose.pose.position.x)+"\n"+str(msg.pose.pose.position.y)+"\n"
    try:
        ##How i can refeer to the socket??
        self.csocket.send(string.encode())
        print (string)
    except socket.error:
        print ("Error client lost")
        ##How to exit from spin()??

if __name__ == '__main__':
    LOCALHOST = "192.168.2.150"
    PORT = 5005
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind((LOCALHOST, PORT))
    print("Server started")
    print("Waiting for client request..")
    while True:
        server.listen(1)
        clientsock, clientAddress = server.accept()
        newthread = ClientThread(clientAddress, clientsock)
        newthread.start()

now I have two problems:
The first one that inside the callback function I can't use

self.csocket.send(string.encode())

and i don't know how to send the string to the client.

The second is that if the client disconnects I cannot exit the callback function

some idea? I'm a beginner with python and ros, thanks in advance

EDIT:
I founded a solution. maybe it's not elegant but it works.

#!/usr/bin/env python
import rospy
from std_msgs.msg import String
import socket
import sys
from nav_msgs.msg import Odometry
import struct
from time import sleep
import socket, threading

class ClientThread(threading.Thread):
    def __init__(self,clientAddress,clientsocket):
        threading.Thread.__init__(self)
        self.csocket = clientsocket
        print ("New connection added: ", clientAddress)
        rospy.init_node('serverOdom', anonymous=True)
        rospy.Subscriber('odom',Odometry, callback)
        print ("New subscriber 'severOdom' added: ")

    def run(self):
        while True:
            msg = rospy.wait_for_message("odom", Odometry, timeout=None)
            string=str(msg.pose.pose.position.x)+"\n"+str(msg.pose.pose.position.y)+"\n"
            try:
                self.csocket.send(string.encode())
            except socket.error:
                print ("Error client lost", clientAddress)
                return

def callback(msg):
    pass

if __name__ == '__main__':
    LOCALHOST = ""
    PORT = 5005
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind((LOCALHOST, PORT))
    print("Server started")
    print("Waiting for client request..")
    while True:
        sleep(2)
        server.listen(5)
        clientsock, clientAddress = server.accept()
        newthread = ClientThread(clientAddress, clientsock)
        newthread.start()

I needed more clients to connect and that when the connection with a client was lost (for example because the client was closed) the thread created by the server ended.
with my solution for each thread created by the server a subscriber is also created, probably it would be better to use a single subscriber for all the threads created, but for now I have not been able to do it.

Body:
If you define the callback as a member of ClientThread, you can access self. Ex

class ClientThread(...):
    def callback(self, msg):
        self.csocket.send(string.encode())

Also, your control flow is all wonky. All the init for the node should happen in main; that's why your confused. Ex of a python node.

Also, your code doesn't quite make sense, as it seems to be both the server and the client. Ex. here is a light rewrite, but it doesn't really make sense & won't behave right. (Except the ros parts should be correct). Like, it seems that you're trying to use threading... to do the job of ros, in which each node is like a thread already.

# server_odom.py

# Ros imports
import rospy
from std_msgs.msg import String
from nav_msgs.msg import Ododmetry

# Sys imports
import sys
import socket
import struct
import threading
from time import sleep

class ClientThread(threading.Thread):
    def __init__(self,clientAddress,clientsocket):
        threading.Thread.__init__(self)
        self.csocket = clientsocket
        print ("New connection added: ", clientAddress)
        rospy.init_node('serverOdom', anonymous=True)
        rospy.Subscriber('odom',Odometry, self.callback)
        print ("New subscriber 'severOdom' added: ")

    def run(self):
        rospy.spin()

    def callback(self, msg):
        string=str(msg.pose.pose.position.x)+"\n"+str(msg.pose.pose.position.y)+"\n"
        try:
            self.csocket.send(string.encode())
            print (string)
        except socket.error:
            print ("Error client lost")
            return

if __name__ == '__main__':
    LOCALHOST = ""
    PORT = 5005
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind((LOCALHOST, PORT))
    print("Server started")
    print("Waiting for client request..")
    while True:
        sleep(2)
        server.listen(5)
        clientsock, clientAddress = server.accept()
        newthread = ClientThread(clientAddress, clientsock)
        newthread.start()

If you just mean to format an odometry message to a string or serial buffer, it's significantly less code.

# server_odom_min.py

# Ros imports
import rospy
from std_msgs.msg import String
from nav_msgs.msg import Ododmetry

str_pub = None

def callback(self, msg):
    s = String()
    s.data = str(msg.pose.pose.position.x)+"\n"+str(msg.pose.pose.position.y)+"\n"
    if str_pub:
        str_pub.publish(s)

if __name__ == '__main__':
    rospy.init_node('server_odom_min')
    rospy.Subscriber('odom', Odometry, callback)
    str_pub = rospy.Publisher('odom/string', String, queue_size = 1)
    rospy.spin()

Edit (in response to edit):
I see what you're doing now, my bad; the second example doesn't really apply to this question. I edited my first example to reflect what you mean.


来源: stackexchange

问:
how can you Given two integers a and b, which can be positive or negative,and find the sum of all the numbers between including them too and return it
function getSum( a , b){
} //so how do you get along this</p>

答:
I think you can simply use the formula in this topic. This doesn't even require to use a for loop. In your code you use a instead of alpha and b instead of beta.

var num_1 = 20;
var num_2 = 30;

console.log( getSum(num_1, num_2) );

function getSum(a,b) {
    return (a+b)*(b-a+1)/2
}```

ContentLicense: CC BY-SA 4.0


问:
Perl tar file creates directory recursively
I am taring the directory contents using Archive::Tar module.

My scripts is below:

```<code>#!/usr/bin/perl -w

use strict;
use warnings;
use Archive::Tar;
use File::Find;
use Data::Dumper;

my $home_dir = "C:/Users/Documents/Vinod/Perl_Scripts/test/";

my $src_location = $home_dir."LOG_DIR";
my $dst_location = $home_dir."file.tar.gz";

my @inventory = ();
find (sub { push @inventory, $File::Find::name }, $src_location);

print "Files:".Dumper(\@inventory);

my $tar = Archive::Tar->new();

$tar->add_files( @inventory );

$tar->write( $dst_location , 9 );
</code>```

Script is able to create file.tar.gz file in location C:/Users/Documents/Vinod/Perl_Scripts/test/.

But when I extract the file.tar.gz manually it creates a whole path recursively once again. So LOG_DIR contents would be visible in the location C:/Users/Documents/Vinod/Perl_Scripts/test/file.tar/file/Users/Documents/Vinod/Perl_Scripts/test/LOG_DIR/

How can I have the contents which is inside C:/Users/Documents/Vinod/Perl_Scripts/test/LOG_DIR/ in C:/Users/Documents/Vinod/Perl_Scripts/test/file.tar/file/ while extracting it.

答:
If you don't want to recreate the full path, chdir into the home directory, and make the source dir relative:</p>

```<code>my $home_dir = "C:/Users/Documents/Vinod/Perl_Scripts/test/";

chdir $home_dir;
my $src_location = "LOG_DIR";
my $dst_location = $home_dir."file.tar.gz";
</code>```

Body:
I am taring the directory contents using Archive::Tar module.

My scripts is below:

#!/usr/bin/perl -w

use strict;
use warnings;
use Archive::Tar;
use File::Find;
use Data::Dumper;

my $home_dir = "C:/Users/Documents/Vinod/Perl_Scripts/test/";

my $src_location = $home_dir."LOG_DIR";
my $dst_location = $home_dir."file.tar.gz";

my @inventory = ();
find (sub { push @inventory, $File::Find::name }, $src_location);

print "Files:".Dumper(\@inventory);

my $tar = Archive::Tar->new();

$tar->add_files( @inventory );

$tar->write( $dst_location , 9 );

Script is able to create file.tar.gz file in location C:/Users/Documents/Vinod/Perl_Scripts/test/.

But when I extract the file.tar.gz manually it creates a whole path recursively once again. So LOG_DIR contents would be visible in the location C:/Users/Documents/Vinod/Perl_Scripts/test/file.tar/file/Users/Documents/Vinod/Perl_Scripts/test/LOG_DIR/

How can I have the contents which is inside C:/Users/Documents/Vinod/Perl_Scripts/test/LOG_DIR/ in C:/Users/Documents/Vinod/Perl_Scripts/test/file.tar/file/ while extracting it.

Body:
If you don't want to recreate the full path, chdir into the home directory, and make the source dir relative:

my $home_dir = "C:/Users/Documents/Vinod/Perl_Scripts/test/";

chdir $home_dir;
my $src_location = "LOG_DIR";
my $dst_location = $home_dir."file.tar.gz";


问:
Resizing numpy arrays to use train_test_split sklearn function?
I am trying to splits my data using test_train_split from sklearn. My data consists of a numpy.ndarray for both images and facial points. However I have realized they are both different shapes with the images being ((2811, 250, 250, 3), and the face points being (2811, 68, 2)). I am unsure how to go about re-scaling these so that they are the same size. Any suggestions?

```<code>reg= linear_model.LinearRegression()
x_train, x_test, y_train, y_test = train_test_split(img, points, test_size=0.2)
reg.fit(x_train,y_train)
</code>```

Below is the error message I got

```<code>---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-55-ae4bf08b45bb> in <module>()
----> 1 reg.fit(x_train,y_train)

2 frames
/usr/local/lib/python3.6/dist-packages/sklearn/linear_model/_base.py in fit(self, X, y, sample_weight)
    490         n_jobs_ = self.n_jobs
    491         X, y = check_X_y(X, y, accept_sparse=['csr', 'csc', 'coo'],
--> 492                          y_numeric=True, multi_output=True)
    493
    494         if sample_weight is not None:

/usr/local/lib/python3.6/dist-packages/sklearn/utils/validation.py in check_X_y(X, y, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, multi_output, ensure_min_samples, ensure_min_features, y_numeric, warn_on_dtype, estimator)
    753                     ensure_min_features=ensure_min_features,
    754                     warn_on_dtype=warn_on_dtype,
--> 755                     estimator=estimator)
    756     if multi_output:
    757         y = check_array(y, 'csr', force_all_finite=True, ensure_2d=False,

/usr/local/lib/python3.6/dist-packages/sklearn/utils/validation.py in check_array(array, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, warn_on_dtype, estimator)
    572         if not allow_nd and array.ndim >= 3:
    573             raise ValueError("Found array with dim %d. %s expected <= 2."
--> 574                              % (array.ndim, estimator_name))
    575
    576         if force_all_finite:

ValueError: Found array with dim 4. Estimator expected <= 2.

</code>```

答:
You can reshape your features and labels to be <= 2D.

N = img.shape[0]
img = np.reshape(img, (N, -1)) # flattens the image to a vector of appropriate dimension
points = np.reshape(points, (N, -1)) # flattens the target

x_train, x_test, y_train, y_test = train_test_split(img, points, test_size=0.2)
reg.fit(x_train,y_train)
```

Body:
I am trying to splits my data using test_train_split from sklearn. My data consists of a numpy.ndarray for both images and facial points. However I have realized they are both different shapes with the images being ((2811, 250, 250, 3), and the face points being (2811, 68, 2)). I am unsure how to go about re-scaling these so that they are the same size. Any suggestions?

reg= linear_model.LinearRegression()
x_train, x_test, y_train, y_test = train_test_split(img, points, test_size=0.2)
reg.fit(x_train,y_train)

Below is the error message I got

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-55-ae4bf08b45bb> in <module>()
----> 1 reg.fit(x_train,y_train)

2 frames
/usr/local/lib/python3.6/dist-packages/sklearn/linear_model/_base.py in fit(self, X, y, sample_weight)
    490         n_jobs_ = self.n_jobs
    491         X, y = check_X_y(X, y, accept_sparse=['csr', 'csc', 'coo'],
--> 492                          y_numeric=True, multi_output=True)
    493
    494         if sample_weight is not None:

/usr/local/lib/python3.6/dist-packages/sklearn/utils/validation.py in check_X_y(X, y, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, multi_output, ensure_min_samples, ensure_min_features, y_numeric, warn_on_dtype, estimator)
    753                     ensure_min_features=ensure_min_features,
    754                     warn_on_dtype=warn_on_dtype,
--> 755                     estimator=estimator)
    756     if multi_output:
    757         y = check_array(y, 'csr', force_all_finite=True, ensure_2d=False,

/usr/local/lib/python3.6/dist-packages/sklearn/utils/validation.py in check_array(array, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, warn_on_dtype, estimator)
    572         if not allow_nd and array.ndim >= 3:
    573             raise ValueError("Found array with dim %d. %s expected <= 2."
--> 574                              % (array.ndim, estimator_name))
    575
    576         if force_all_finite:

ValueError: Found array with dim 4. Estimator expected <= 2.


问:
How to view a regression tree?
I am wanting to visualize my decision tree applied to regression (only this plot for classification worked) what is going wrong that only the values appear but not the tree built itself?

答:
For a simpler approach, try:

```<code>from sklearn import tree
from sklearn.tree import DecisionTreeClassifier
.
.
.
clf = DecisionTreeClassifier()
clf.fit(X,y)

clf.plot_tree()
</code>```

Theplot_tree() method uses matplotlib tools to make a tree visualizer.
For a fancier approach, you can plot the tree using graphviz. Check out this article about this topic:

https://towardsdatascience.com/visualizing-decision-trees-with-python-scikit-learn-graphviz-matplotlib-1c50b4aa68dc

Title: How to view a regression tree?

Body:
For a simpler approach, try:

from sklearn import tree
from sklearn.tree import DecisionTreeClassifier
.
.
.
clf = DecisionTreeClassifier()
clf.fit(X,y)

clf.plot_tree()

Theplot_tree() method uses matplotlib tools to make a tree visualizer.
For a fancier approach, you can plot the tree using graphviz. Check out this article about this topic:

https://towardsdatascience.com/visualizing-decision-trees-with-python-scikit-learn-graphviz-matplotlib-1c50b4aa68dc


问:
Tensorflow: How do you monitor GPU performance during model training in real-time?
I am new to Ubuntu and GPUs and have recently been using a new PC with Ubuntu 16.04 and 4 NVIDIA 1080ti GPUs in our lab. The machine also has an i7 16 core processor.

I have some basic questions:

Tensorflow is installed for GPU. I presume then, that it automatically prioritises GPU usage? If so, does it use all 4 together or does it use 1 and then recruit another if needed?

Can I monitor in real-time, the GPU use/activity during training of a model?

I fully understand this is basic hardware stuff but clear definitive answers to these specific questions would be great.

EDIT:

Based on this output - it this really saying that nearly all the memory on each one of my GPUs is being used?

答:
Try this command:

```<code>nvidia-smi --query-gpu=utilization.gpu --format=csv --loop=1
</code>```

Here is a demo:

ContentLicense: CC BY-SA 3.0

Body:
Try this command:

nvidia-smi --query-gpu=utilization.gpu --format=csv --loop=1

Here is a demo:


问:
Meteor | Helper function. How to print attribute values of returned element on HTML
I am using Meteor JS for UI development of a project. There is a helper method which takes a input parameter and return an object.

Helper Function:

```<code>"getPhoneName": function (param) {
        let myObj = PhoneRegister.findOne({"_id": param});
        //This myObj contains  name, _id, modelNumber
        return myObj;
    }
</code>```

How i am using it on HTML

```<code><span>{{getPhoneName 'id_1234'}}</span> //This line is obviously prints the [[Object]]

    Here i am not getting solution how to print modelNumber. I have tried following :
1.{{getPhoneName 'id_1234'.modelNumber}}
2.{{getPhoneName 'id_1234'}}.modelNumber
</code>```

Can someone help? If you need more information please let me know.

答:
If you only want one property, you could simply return myObj.property; and display it as you already did with {{getPhoneName 'id_1234'}}.

But if you want to access multiple properties, you can return the object in an array and then use each or each-in Blaze's built-in block like this :

Helper:

```<code>"getPhoneName": function (param) {
        let myObj = PhoneRegister.findOne({"_id": param});
        //This myObj contains  name, _id, modelNumber
        return [myObj];  // Returning an array in order to use each or each-in
    }
</code>```

HTML (with each):

```<code>{{#each getPhoneName 'id_1234'}}
    <span>{{this.property1}}</span>
    <span>{{this.property2}}</span>
{{/each}
</code>```

You can also take a look at {{#let}}, in some cases it's useful too.

Body:
I am using Meteor JS for UI development of a project. There is a helper method which takes a input parameter and return an object.

Helper Function:

"getPhoneName": function (param) {
        let myObj = PhoneRegister.findOne({"_id": param});
        //This myObj contains  name, _id, modelNumber
        return myObj;
    }

How i am using it on HTML

{{getPhoneName 'id_1234'}} //This line is obviously prints the [[Object]]

    Here i am not getting solution how to print modelNumber. I have tried following :
1.{{getPhoneName 'id_1234'.modelNumber}}
2.{{getPhoneName 'id_1234'}}.modelNumber

Can someone help? If you need more information please let me know.

Body:
If you only want one property, you could simply return myObj.property; and display it as you already did with {{getPhoneName 'id_1234'}}.

But if you want to access multiple properties, you can return the object in an array and then use each or each-in Blaze's built-in block like this :

Helper:

"getPhoneName": function (param) {
        let myObj = PhoneRegister.findOne({"_id": param});
        //This myObj contains  name, _id, modelNumber
        return [myObj];  // Returning an array in order to use each or each-in
    }

HTML (with each):

{{#each getPhoneName 'id_1234'}}
    <span>{{this.property1}}</span>
    <span>{{this.property2}}</span>
{{/each}

You can also take a look at {{#let}}, in some cases it's useful too.


问:
Unknown behaviour of HOOKS in PyTorch
I have a straightforward and simple CNN below,

```<code># creat a dummy deep net
class Net(nn.Module):

    def __init__(self):
        super(Net, self).__init__()

        self.conv1 = nn.Conv2d(1,2, kernel_size=3, stride=1, padding=1, bias=True)
        self.conv2 = nn.Conv2d(2,3, kernel_size=3, stride=1, padding=1, bias=True)
        self.conv3 = nn.Conv2d(3,1, kernel_size=3, stride=1, padding=1, bias=True)
        self.seq = nn.Sequential(
                    nn.Conv2d(1,5, kernel_size=3, stride=1, padding=1, bias=True),
                    nn.LeakyReLU(negative_slope=0.2, inplace=True),
                    nn.Conv2d(5,1, kernel_size=3, stride=1, padding=1, bias=True),
                    )
        self.relu = nn.LeakyReLU(negative_slope=0.2, inplace=True)

    def forward(self, x):

        out = self.relu(self.conv1(x))
        out = self.conv3(self.conv2(out))
        out = out + x
        out = self.seq(x)

        return out
</code>```

5 hooks have been applied to each layer for the forward pass.

```<code>Hooked 0 to Conv2d(1, 2, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
Hooked 1 to Conv2d(2, 3, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
Hooked 2 to Conv2d(3, 1, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
Hooked 3 to Sequential(
  (0): Conv2d(1, 5, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (1): LeakyReLU(negative_slope=0.2, inplace=True)
  (2): Conv2d(5, 1, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
)
Hooked 4 to LeakyReLU(negative_slope=0.2, inplace=True)
</code>```

These hooks have been created using following class

```<code># ------------------The Hook class begins to calculate each layer stats
class Hook():
    def __init__(self, module, backward=False):
        if backward==False:
            self.hook = module.register_forward_hook(self.hook_fn)
        else:
            self.hook = module.register_backward_hook(self.hook_fn)

        self.inputMean = []
        self.outputMean = []

    def hook_fn(self, module, input, output):
        self.inputMean.append(input[0][0,...].mean().item())#calculate only for 1st image in the batch
        print('\nIn hook class input {}'.format(input[0].size()))
        self.outputMean.append(output[0][0,...].mean().item())
        print('In hook class outout {}'.format(output[0].size()))

# create hooks on each layer
hookF = []
for i,layer in enumerate(list(net.children())):
    print('Hooked to {}'.format(layer))
    hookF.append(Hook(layer))
</code>```

Please note between Hook 1 and Hook 2 there is no ReLU
self.conv3(self.conv2(out)). Thus OUTPUT of HOOK1 is INPUT to HOOK2 and should be identical. BUT THIS DOES NOT TURNS OUT TO BE WHY? Below is output for HOOK1 and HOOK2

```<code>Hook of layer 1 (HOOK on layer 1 which is self.conv2)
... OutputMean: [0.2381615787744522, 0.2710852324962616, 0.30706286430358887, 0.26064932346343994, 0.24395985901355743]

 Hook of layer 2 (HOOK on layer 2 which is self.conv3)
InputMean: [0.13127394020557404, 0.1611362248659134, 0.1457807868719101, 0.17380955815315247, 0.1537724733352661], OutputMean: ...
</code>```

These two values should have been the same but do not turn out to be.

------ The Full code is shown below -------

```<code>import torch
import torch.nn as nn

# creat a dummy deep net
class Net(nn.Module):

    def __init__(self):
        super(Net, self).__init__()

        self.conv1 = nn.Conv2d(1,2, kernel_size=3, stride=1, padding=1, bias=True)
        self.conv2 = nn.Conv2d(2,3, kernel_size=3, stride=1, padding=1, bias=True)
        self.conv3 = nn.Conv2d(3,1, kernel_size=3, stride=1, padding=1, bias=True)
        self.seq = nn.Sequential(
                    nn.Conv2d(1,5, kernel_size=3, stride=1, padding=1, bias=True),
                    nn.LeakyReLU(negative_slope=0.2, inplace=True),
                    nn.Conv2d(5,1, kernel_size=3, stride=1, padding=1, bias=True),
                    )
        self.relu = nn.LeakyReLU(negative_slope=0.2, inplace=True)

    def forward(self, x):

        out = self.relu(self.conv1(x))
        out = self.conv3(self.conv2(out))
        out = out + x
        out = self.seq(x)

        return out

net = Net()
print(net)
criterion = nn.MSELoss()

# ------------------The Hook class begins to calculate each layer stats
class Hook():
    def __init__(self, module, backward=False):
        if backward==False:
            self.hook = module.register_forward_hook(self.hook_fn)
        else:
            self.hook = module.register_backward_hook(self.hook_fn)

        self.inputMean = []
        self.outputMean = []

    def hook_fn(self, module, input, output):
        self.inputMean.append(input[0][0,...].mean().item())#calculate only for 1st image in the batch
        print('\nIn hook class input {}'.format(input[0].size()))
        self.outputMean.append(output[0][0,...].mean().item())
        print('In hook class outout {}'.format(output[0].size()))

# create hooks on each layer
hookF = []
for i,layer in enumerate(list(net.children())):
    print('Hooked to {}'.format(layer))
    hookF.append(Hook(layer))

optimizer = torch.optim.Adam(net.parameters())

# Do 5 forward pass
for _ in range(5):
    print('Iteration --------')
    data = torch.rand(2,1,10,10)*10
    print('Input mean is {}'.format(data[0,...].mean()))
    target = data.clone()

    out = net(data)
    loss = criterion(out, target)
    print('backward')
    loss.backward()
    optimizer.step()
    optimizer.zero_grad()

for i,h in enumerate(hookF):
    print('\n Hook of layer {}'.format(i))
    print('InputMean: {}, OutputMean: {}'.format(h.inputMean, h.outputMean))
    h.hook.remove()
</code>```

答:
The problem is that in your Conv2d layer input is a tuple and output is a torch.Tensor. Therefore output[0][0,...] is selecting the first item from dim 0 in the tensor whereas input[0][0,...] is selecting the first item from the tuple.

You just need to change output[0][0,...] to output[0,...].

Title: Unknown behaviour of HOOKS in PyTorch

Body:
I have a straightforward and simple CNN below,

# creat a dummy deep net
class Net(nn.Module):

    def __init__(self):
        super(Net, self).__init__()

        self.conv1 = nn.Conv2d(1,2, kernel_size=3, stride=1, padding=1, bias=True)
        self.conv2 = nn.Conv2d(2,3, kernel_size=3, stride=1, padding=1, bias=True)
        self.conv3 = nn.Conv2d(3,1, kernel_size=3, stride=1, padding=1, bias=True)
        self.seq = nn.Sequential(
                    nn.Conv2d(1,5, kernel_size=3, stride=1, padding=1, bias=True),
                    nn.LeakyReLU(negative_slope=0.2, inplace=True),
                    nn.Conv2d(5,1, kernel_size=3, stride=1, padding=1, bias=True),
                    )
        self.relu = nn.LeakyReLU(negative_slope=0.2, inplace=True)

    def forward(self, x):

        out = self.relu(self.conv1(x))
        out = self.conv3(self.conv2(out))
        out = out + x
        out = self.seq(x)

        return out

5 hooks have been applied to each layer for the forward pass.

Hooked 0 to Conv2d(1, 2, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
Hooked 1 to Conv2d(2, 3, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
Hooked 2 to Conv2d(3, 1, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
Hooked 3 to Sequential(
  (0): Conv2d(1, 5, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (1): LeakyReLU(negative_slope=0.2, inplace=True)
  (2): Conv2d(5, 1, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
)
Hooked 4 to LeakyReLU(negative_slope=0.2, inplace=True)

These hooks have been created using following class

# ------------------The Hook class begins to calculate each layer stats
class Hook():
    def __init__(self, module, backward=False):
        if backward==False:
            self.hook = module.register_forward_hook(self.hook_fn)
        else:
            self.hook = module.register_backward_hook(self.hook_fn)

        self.inputMean = []
        self.outputMean = []

    def hook_fn(self, module, input, output):
        self.inputMean.append(input[0][0,...].mean().item())#calculate only for 1st image in the batch
        print('\nIn hook class input {}'.format(input[0].size()))
        self.outputMean.append(output[0][0,...].mean().item())
        print('In hook class outout {}'.format(output[0].size()))

# create hooks on each layer
hookF = []
for i,layer in enumerate(list(net.children())):
    print('Hooked to {}'.format(layer))
    hookF.append(Hook(layer))

Please note between Hook 1 and Hook 2 there is no ReLU
self.conv3(self.conv2(out)). Thus OUTPUT of HOOK1 is INPUT to HOOK2 and should be identical. BUT THIS DOES NOT TURNS OUT TO BE WHY? Below is output for HOOK1 and HOOK2

Hook of layer 1 (HOOK on layer 1 which is self.conv2)
... OutputMean: [0.2381615787744522, 0.2710852324962616, 0.30706286430358887, 0.26064932346343994, 0.24395985901355743]

 Hook of layer 2 (HOOK on layer 2 which is self.conv3)
InputMean: [0.13127394020557404, 0.1611362248659134, 0.1457807868719101, 0.17380955815315247, 0.1537724733352661], OutputMean: ...

These two values should have been the same but do not turn out to be.

------ The Full code is shown below -------

import torch
import torch.nn as nn

# creat a dummy deep net
class Net(nn.Module):

    def __init__(self):
        super(Net, self).__init__()

        self.conv1 = nn.Conv2d(1,2, kernel_size=3, stride=1, padding=1, bias=True)
        self.conv2 = nn.Conv2d(2,3, kernel_size=3, stride=1, padding=1, bias=True)
        self.conv3 = nn.Conv2d(3,1, kernel_size=3, stride=1, padding=1, bias=True)
        self.seq = nn.Sequential(
                    nn.Conv2d(1,5, kernel_size=3, stride=1, padding=1, bias=True),
                    nn.LeakyReLU(negative_slope=0.2, inplace=True),
                    nn.Conv2d(5,1, kernel_size=3, stride=1, padding=1, bias=True),
                    )
        self.relu = nn.LeakyReLU(negative_slope=0.2, inplace=True)

    def forward(self, x):

        out = self.relu(self.conv1(x))
        out = self.conv3(self.conv2(out))
        out = out + x
        out = self.seq(x)

        return out

net = Net()
print(net)
criterion = nn.MSELoss()

# ------------------The Hook class begins to calculate each layer stats
class Hook():
    def __init__(self, module, backward=False):
        if backward==False:
            self.hook = module.register_forward_hook(self.hook_fn)
        else:
            self.hook = module.register_backward_hook(self.hook_fn)

        self.inputMean = []
        self.outputMean = []

    def hook_fn(self, module, input, output):
        self.inputMean.append(input[0][0,...].mean().item())#calculate only for 1st image in the batch
        print('\nIn hook class input {}'.format(input[0].size()))
        self.outputMean.append(output[0][0,...].mean().item())
        print('In hook class outout {}'.format(output[0].size()))

# create hooks on each layer
hookF = []
for i,layer in enumerate(list(net.children())):
    print('Hooked to {}'.format(layer))
    hookF.append(Hook(layer))

optimizer = torch.optim.Adam(net.parameters())

# Do 5 forward pass
for _ in range(5):
    print('Iteration --------')
    data = torch.rand(2,1,10,10)*10
    print('Input mean is {}'.format(data[0,...].mean()))
    target = data.clone()

    out = net(data)
    loss = criterion(out, target)
    print('backward')
    loss.backward()
    optimizer.step()
    optimizer.zero_grad()

for i,h in enumerate(hookF):
    print('\n Hook of layer {}'.format(i))
    print('InputMean: {}, OutputMean: {}'.format(h.inputMean, h.outputMean))
    h.hook.remove()


问:
Generating a list of uniquely name elements based on a for i in range statement
I have:

```<code>Number = 4
for i in range(1, Number):
    grwth = ('r'+'C')
print(grwth)
</code>```

But what I want is for 'rC' to have a unique name each time it is printed. So, if Number is entered to be 4, grwth should be a list of [rC, rC2, rC3, rC4] Like that. Is that possible to do ?

答:
There are a few ways to get at that. Here's one using list comprehension and string formatting.

number = 4
grwth = [f"rC{i}" for i in range(1, number + 1)]
```

Body:
I have:

Number = 4
for i in range(1, Number):
    grwth = ('r'+'C')
print(grwth)

But what I want is for 'rC' to have a unique name each time it is printed. So, if Number is entered to be 4, grwth should be a list of [rC, rC2, rC3, rC4] Like that. Is that possible to do ?


问:
Hadoop Docker container could only be replicated to 0 nodes instead of minReplication (=1)
I tried different docker images for Hadoop containers but none of them work when I try to write files to HDFS. I always get
error:

Caused by: org.apache.hadoop.ipc.RemoteException(java.io.IOException):
  File
  /t/_temporary/0/_temporary/attempt_20200528153700_0001_m_000006_7/part-00006-34c8bc6d-68a3-4177-bfbf-5f225b28c157-c000.snappy.parquet could only be replicated to 0 nodes instead of minReplication (=1).
  There are 3 datanode(s) running and 3 node(s) are excluded in this
  operation.

What I tried so far?

Formatted Namenode as mentioned under similar questions.

Exposed needed ports, 8088, 50070, 9000, 50010.

Already have enough space in Datanode.

Updated host file, mapped 127.0.0.1 to container name.

I'm running app on my local computer, Docker containers running on local as well.

After creating basic Dataframe, I'm trying to write.

```<code>df.write.save('hdfs://hadoop-master:9000/t', format='parquet', mode='append'
</code>```

It took almost 2 minutes, then throws error.

WebUI is fine. I can put file to HDFS with commands in container.

It seems like network/connection problem to me, but couldn't find out.

答:
I didn't solve problem but found a quick solution.

TL;TR

MacOS may cause this problem.

Built new Debian server on GCP, installed docker, its images and Python codes which I tested. It worked fine, but still I am getting error when I try to connect from my local machine.

But still need an answer, I share it for someone who needs quick solution.

Body:
I tried different docker images for Hadoop containers but none of them work when I try to write files to HDFS. I always get
error:

Caused by: org.apache.hadoop.ipc.RemoteException(java.io.IOException):
  File
  /t/_temporary/0/_temporary/attempt_20200528153700_0001_m_000006_7/part-00006-34c8bc6d-68a3-4177-bfbf-5f225b28c157-c000.snappy.parquet could only be replicated to 0 nodes instead of minReplication (=1).
  There are 3 datanode(s) running and 3 node(s) are excluded in this
  operation.

What I tried so far?

Formatted Namenode as mentioned under similar questions.

Exposed needed ports, 8088, 50070, 9000, 50010.

Already have enough space in Datanode.

Updated host file, mapped 127.0.0.1 to container name.

I'm running app on my local computer, Docker containers running on local as well.

After creating basic Dataframe, I'm trying to write.

df.write.save('hdfs://hadoop-master:9000/t', format='parquet', mode='append'

It took almost 2 minutes, then throws error.

WebUI is fine. I can put file to HDFS with commands in container.

It seems like network/connection problem to me, but couldn't find out.


问:
Postgresql - query problem
I have a variable which is in this format 2011-05-13.
I want to make a query that adds one day to this variable and searches for days like this in the database.

I made this query but it doesnt work.

```<code>select phone from employee where date like (select date '2011-05-13' + 1) %
</code>```

Can anyone help?

答:
You need an INTERVAL:

```<code>SELECT phone FROM employee WHERE datefield = (date '2011-05-13' + INTERVAL '1 DAY') ;
</code>```

Edit: Don't use LIKE when you're working with dates, there is no LIKE for a date.

Title: Postgresql - query problem

Body:
I have a variable which is in this format 2011-05-13.
I want to make a query that adds one day to this variable and searches for days like this in the database.

I made this query but it doesnt work.

select phone from employee where date like (select date '2011-05-13' + 1) %

Can anyone help?

Body:
You need an INTERVAL:

SELECT phone FROM employee WHERE datefield = (date '2011-05-13' + INTERVAL '1 DAY') ;

Edit: Don't use LIKE when you're working with dates, there is no LIKE for a date.


问:
How can I set a single proxy for a requests session object?
I'm using the Python requests package to send http requests. I want to add a single proxy to the requests session object. eg.

```<code>session = requests.Session()
session.proxies = {...} # Here I want to add a single proxy
</code>```

Currently I am looping through a bunch of proxies, and at each iteration a new session is made. I only want to set a single proxy for each iteration.

The only example I see in the documentation is:

```<code>proxies = {
    "http": "http://10.10.1.10:3128",
    "https": "http://10.10.1.10:1080",
}

requests.get("http://example.org", proxies=proxies)
</code>```

I've tried to follow this, but to no avail. Here is my code from the script:

```<code># eg. line = 59.43.102.33:80
r = s.get('http://icanhazip.com', proxies={'http': 'http://' + line})
</code>```

But I get an error:

```<code>requests.packages.urllib3.exceptions.LocationParseError: Failed to parse 59.43.102.33:80
</code>```

How is it possible to set a single proxy on a session object?

答:
There are other ways you can set proxies, apart from the solutions you have got so far:</p>

```<code>import requests

with requests.Session() as s:
    # either like this
    s.proxies = {'https': 'http://105.234.154.195:8888', 'http': 'http://199.188.92.69:8000'}
    # or like this
    s.proxies['https'] = 'http://105.234.154.195:8888'
    r = s.get(link)
</code>```

Body:
I'm using the Python requests package to send http requests. I want to add a single proxy to the requests session object. eg.

session = requests.Session()
session.proxies = {...} # Here I want to add a single proxy

Currently I am looping through a bunch of proxies, and at each iteration a new session is made. I only want to set a single proxy for each iteration.

The only example I see in the documentation is:

proxies = {
    "http": "http://10.10.1.10:3128",
    "https": "http://10.10.1.10:1080",
}

requests.get("http://example.org", proxies=proxies)

I've tried to follow this, but to no avail. Here is my code from the script:

# eg. line = 59.43.102.33:80
r = s.get('http://icanhazip.com', proxies={'http': 'http://' + line})

But I get an error:

requests.packages.urllib3.exceptions.LocationParseError: Failed to parse 59.43.102.33:80

How is it possible to set a single proxy on a session object?

Body:
There are other ways you can set proxies, apart from the solutions you have got so far:

import requests

with requests.Session() as s:
    # either like this
    s.proxies = {'https': 'http://105.234.154.195:8888', 'http': 'http://199.188.92.69:8000'}
    # or like this
    s.proxies['https'] = 'http://105.234.154.195:8888'
    r = s.get(link)


问:
Unity Hub constantly keeps asking for the same update, but downgrades after computer restart
Right now, my Unity Hub is version 2.1.2. Every time I start the program up, it asks me for an update to version 2.2.2. Every time I install the update, it does install correctly and the application sticks to that new version until I restart my computer. After a restart, it goes back to version 2.1.2, and Unity Hub asks me for that 2.2.2 update AGAIN.
This has been happenning to me for a few months now. Any idea what the issue might be and how to fix it?</p>

答: Eventually, all I did was just completely reinstall (uninstall, along with Unity) the Unity Hub, and I didn't run into this issue again. Strange...</p>


问:
AddThis button will not work inside AJAX, but will work normally
Basically, this is what I'm doing.
User visits site, loads "index.html"
Within index.html, it automatically loads, through AJAX, "details.html" into a DIV.
I put an ADDTHIS button on "details.html".  However, for some reason , the roll-over doesn't work.

When I visit details.html in the browser, the roll-over works. I'm guessing it's because of the AJAX?

```<code><a class="addthis_button"  href="http://www.addthis.com/bookmark.php?v=250&pub=xa-4adf7e45288f5b21">
<img src="http://s7.addthis.com/static/btn/sm-share-en.gif" width="83" height="16" alt="Bookmark and Share" style="border:0;margin-top:16px;"/></a>
<script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#pub=xa-4adf7e45288f5b21"></script>
</code>```

答:
I had the same problem. Fixed it with the following code. I hope that fixes it for you too.

Original Method:

```<code>    var script = 'http://s7.addthis.com/js/300/addthis_widget.js?domready=1';
    if (window.addthis){
        window.addthis = null;
    }
    $.getScript( script );
</code>```

New Method:

```<code><script>
var script = 'http://s7.addthis.com/js/250/addthis_widget.js#domready=1';
if (window.addthis) {
    window.addthis = null;
    window._adr = null;
    window._atc = null;
    window._atd = null;
    window._ate = null;
    window._atr = null;
    window._atw = null;
}
$.getScript(script);
</script>
</code>```

In AJAX REQUEST you can use like this:-

```<code>$.ajax({
    url:Url,
    type: 'POST',
    cache: false,
    success: function(res){
        var script = 'http://s7.addthis.com/js/250/addthis_widget.js#domready=1';
        if (window.addthis) {
            window.addthis = null;
            window._adr = null;
            window._atc = null;
            window._atd = null;
            window._ate = null;
            window._atr = null;
            window._atw = null;
        }
        $.getScript(script);
        // your custom code
    }
});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I had the same problem. Fixed it with the following code. I hope that fixes it for you too.

Original Method:

    var script = 'http://s7.addthis.com/js/300/addthis_widget.js?domready=1';
    if (window.addthis){
        window.addthis = null;
    }
    $.getScript( script );

New Method:

<script>
var script = 'http://s7.addthis.com/js/250/addthis_widget.js#domready=1';
if (window.addthis) {
    window.addthis = null;
    window._adr = null;
    window._atc = null;
    window._atd = null;
    window._ate = null;
    window._atr = null;
    window._atw = null;
}
$.getScript(script);
</script>

In AJAX REQUEST you can use like this:-

$.ajax({
    url:Url,
    type: 'POST',
    cache: false,
    success: function(res){
        var script = 'http://s7.addthis.com/js/250/addthis_widget.js#domready=1';
        if (window.addthis) {
            window.addthis = null;
            window._adr = null;
            window._atc = null;
            window._atd = null;
            window._ate = null;
            window._atr = null;
            window._atw = null;
        }
        $.getScript(script);
        // your custom code
    }
});


问:
How to promisify Mongo/Mongoose find
As part of another question I am trying to promisify a mongo/mongoose find query. I found little help via the search bar. The query is below, I am running this query as part of a controller in express. Setup is route -> userController.monitor which needs to contain the query

In getting help for the other question I was asked to promisify find so that you can use await for it (like const incidents = Incident.find({fooID}).exec(); though SO search and my attempts at promisifying it myself have failed.

Query:

```<code>Incident.find({fooID})
.exec((err, incidents) => {
// do something
})
</code>```

Note a findOne will not work in this case because multiple documents will be returned almost all the time

Edit

Incident.find({ monitorID, createdAt: {$gte: sevenAgo} })

答:
You can create a promisified version of your find function using the promisify function in the util module of node.js

const { promisify } = require('util')

const promisifiedIncidentFindExec = payload => {
  const query = Incident.find(payload)
  return promisify(query.exec).call(query)
}

const incidents = await promisifiedIncidentFindExec({
  monitorID: 'monitorID',
  createdAt: { $gte: 'sevenAgo' },
})
// do something
```

Title: How to promisify Mongo/Mongoose find

Body:
As part of another question I am trying to promisify a mongo/mongoose find query. I found little help via the search bar. The query is below, I am running this query as part of a controller in express. Setup is route -> userController.monitor which needs to contain the query

In getting help for the other question I was asked to promisify find so that you can use await for it (like const incidents = Incident.find({fooID}).exec(); though SO search and my attempts at promisifying it myself have failed.

Query:

Incident.find({fooID})
.exec((err, incidents) => {
// do something
})

Note a findOne will not work in this case because multiple documents will be returned almost all the time

Edit

Incident.find({ monitorID, createdAt: {$gte: sevenAgo} })


问:
How can I convert a 2D RGB array into a dds file using C++?
I've got a 2D array of RGB values that represent a plane's painted vertices. I'd like to store the final vertex colours of the plane in a .dds file so I can load the .dds file later on as a texture.

How might I approach this?

答:
Thanks to Chuck in the comments, I've found this solution works for me. There are likely improvements to be made. The approach can be broken into a few steps.

Step one is to deal with capturing the device context and D3D device to use for rendering, and setting the correct texture description to be used when creating the texture to be captured using SaveDDSTextureToFile (ScreenGrab). The below description works when each float contains four byte values for each colour and for the alpha value.

```<code>void DisplayChunk::SaveVertexColours(std::shared_ptr<DX::DeviceResources> DevResources)
{
    // Setup D3DDeviceContext and D3DDevice
    auto devicecontext = DevResources->GetD3DDeviceContext();
    auto device = DevResources->GetD3DDevice();
    // Create Texture2D and Texture2D Description
    ID3D11Texture2D* terrain_texture;
    D3D11_TEXTURE2D_DESC texture_desc;
    // Set up a texture description
    texture_desc.Width = TERRAINRESOLUTION;
    texture_desc.Height = TERRAINRESOLUTION;
    texture_desc.MipLevels = texture_desc.ArraySize = 1;
    texture_desc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
    texture_desc.SampleDesc.Count = 1;
    texture_desc.SampleDesc.Quality = 0;
    texture_desc.Usage = D3D11_USAGE_DYNAMIC;
    texture_desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
    texture_desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    texture_desc.MiscFlags = 0;
</code>```

Step two is to create a vector of floats and populate it with the relevant RGBA values. The reason I used a vector was for convenience in terms of pushing the separate float values for R, G, B, and A each iteration. This way at each vertex position you can push back the required sixteen byte values (four from each float as discussed above).

```<code>    // Create vertex colour vector
    std::vector<float> colour_vector;
    for (int i = 0; i < TERRAINRESOLUTION; i++) {
        for (int j = 0; j < TERRAINRESOLUTION; j++) {
            colour_vector.push_back((float)m_terrainGeometry[i][j].color.x);
            colour_vector.push_back((float)m_terrainGeometry[i][j].color.y);
            colour_vector.push_back((float)m_terrainGeometry[i][j].color.z);
            colour_vector.push_back((float)m_terrainGeometry[i][j].color.w);
        }
    }
</code>```

Step three is to fill a buffer with the vertex RGBA values. Buffer size must be equal to the total number of bytes required for storage, which is four bytes per float, four floats per vertex, and TERRAINTRESOLUTION * TERRAINTRESOLUTION vertices. Example of a 10 x 10 terrain: 4(bytes) x 4(floats) x 10(width) x 10(height) = 1600 bytes to store RGBA of each vertex.

```<code>    // Initialise buffer parameters
    const int components = 4;
    const int length = components * TERRAINRESOLUTION * TERRAINRESOLUTION;
    // Fill buffer with vertex colours
    float* buffer = new float[length * sizeof(float)];
    for (int i = 0; i < length; i++)
        buffer[i] = colour_vector[i];
</code>```

Final step is to create the texture data using the contents of the buffer created above. pSysMem required a pointer to the buffer, used as the initialisation data. SysMemPitch must be set to the size of one row. Using CreateTexture2D, a new texture can be created using the stored byte values. SaveDDSTextureToFile allows for saving the texture resource to an external .dds file. Don't forget to delete the buffer after use.

```<code>    // Set the texture data using the buffer contents
    D3D11_SUBRESOURCE_DATA texture_data;
    texture_data.pSysMem = (void*)buffer;
    texture_data.SysMemPitch = TERRAINRESOLUTION * components * sizeof(float);
    // Create the texture using the terrain colour data
    device->CreateTexture2D(&texture_desc, &texture_data, &terrain_texture);
    // Save the texture to a .dds file
    HRESULT hr = SaveDDSTextureToFile(devicecontext, terrain_texture, L"terrain_output.dds");
    // Delete the buffer
    delete[] buffer;
}
</code>```

Some resources I used whilst implementing:

(DDS Guide)

(ScreenGrab Source)

(ScreenGrab Example)

(Creating textures in DirectX)

(Addressing scheme example (navigating buffer/array correctly))

Body:
Thanks to Chuck in the comments, I've found this solution works for me. There are likely improvements to be made. The approach can be broken into a few steps.

Step one is to deal with capturing the device context and D3D device to use for rendering, and setting the correct texture description to be used when creating the texture to be captured using SaveDDSTextureToFile (ScreenGrab). The below description works when each float contains four byte values for each colour and for the alpha value.

void DisplayChunk::SaveVertexColours(std::shared_ptr<DX::DeviceResources> DevResources)
{
    // Setup D3DDeviceContext and D3DDevice
    auto devicecontext = DevResources->GetD3DDeviceContext();
    auto device = DevResources->GetD3DDevice();
    // Create Texture2D and Texture2D Description
    ID3D11Texture2D* terrain_texture;
    D3D11_TEXTURE2D_DESC texture_desc;
    // Set up a texture description
    texture_desc.Width = TERRAINRESOLUTION;
    texture_desc.Height = TERRAINRESOLUTION;
    texture_desc.MipLevels = texture_desc.ArraySize = 1;
    texture_desc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
    texture_desc.SampleDesc.Count = 1;
    texture_desc.SampleDesc.Quality = 0;
    texture_desc.Usage = D3D11_USAGE_DYNAMIC;
    texture_desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
    texture_desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    texture_desc.MiscFlags = 0;

Step two is to create a vector of floats and populate it with the relevant RGBA values. The reason I used a vector was for convenience in terms of pushing the separate float values for R, G, B, and A each iteration. This way at each vertex position you can push back the required sixteen byte values (four from each float as discussed above).

    // Create vertex colour vector
    std::vector<float> colour_vector;
    for (int i = 0; i < TERRAINRESOLUTION; i++) {
        for (int j = 0; j < TERRAINRESOLUTION; j++) {
            colour_vector.push_back((float)m_terrainGeometry[i][j].color.x);
            colour_vector.push_back((float)m_terrainGeometry[i][j].color.y);
            colour_vector.push_back((float)m_terrainGeometry[i][j].color.z);
            colour_vector.push_back((float)m_terrainGeometry[i][j].color.w);
        }
    }

Step three is to fill a buffer with the vertex RGBA values. Buffer size must be equal to the total number of bytes required for storage, which is four bytes per float, four floats per vertex, and TERRAINTRESOLUTION * TERRAINTRESOLUTION vertices. Example of a 10 x 10 terrain: 4(bytes) x 4(floats) x 10(width) x 10(height) = 1600 bytes to store RGBA of each vertex.

    // Initialise buffer parameters
    const int components = 4;
    const int length = components * TERRAINRESOLUTION * TERRAINRESOLUTION;
    // Fill buffer with vertex colours
    float* buffer = new float[length * sizeof(float)];
    for (int i = 0; i < length; i++)
        buffer[i] = colour_vector[i];

Final step is to create the texture data using the contents of the buffer created above. pSysMem required a pointer to the buffer, used as the initialisation data. SysMemPitch must be set to the size of one row. Using CreateTexture2D, a new texture can be created using the stored byte values. SaveDDSTextureToFile allows for saving the texture resource to an external .dds file. Don't forget to delete the buffer after use.

    // Set the texture data using the buffer contents
    D3D11_SUBRESOURCE_DATA texture_data;
    texture_data.pSysMem = (void*)buffer;
    texture_data.SysMemPitch = TERRAINRESOLUTION * components * sizeof(float);
    // Create the texture using the terrain colour data
    device->CreateTexture2D(&texture_desc, &texture_data, &terrain_texture);
    // Save the texture to a .dds file
    HRESULT hr = SaveDDSTextureToFile(devicecontext, terrain_texture, L"terrain_output.dds");
    // Delete the buffer
    delete[] buffer;
}

Some resources I used whilst implementing:

(DDS Guide)

(ScreenGrab Source)

(ScreenGrab Example)

(Creating textures in DirectX)

(Addressing scheme example (navigating buffer/array correctly))


问:
How to query for city name as well as length of the smallest city name from the same table
My code is this but gives error, don't know why. Please help!</p>

```<code>select city,
       min(length(city))
from station
group by length(city)=min(length(city))
order by city asc;
</code>```

答:
If you just want the city with the shortest name, you can simply order by and limit:

```<code>select city, char_length(city) city_length
from station
order by city_length
limit 1
</code>```

This returns just one row. On the other hand, if you want to allow bottom ties, then you can filter with a subquery, like so:

```<code>select city, char_length(city) city_length
from station
where char_length(city) = (select min(char_length(city)) from station)
</code>```

Body:
My code is this but gives error, don't know why. Please help!

select city,
       min(length(city))
from station
group by length(city)=min(length(city))
order by city asc;

Body:
If you just want the city with the shortest name, you can simply order by and limit:

select city, char_length(city) city_length
from station
order by city_length
limit 1

This returns just one row. On the other hand, if you want to allow bottom ties, then you can filter with a subquery, like so:

select city, char_length(city) city_length
from station
where char_length(city) = (select min(char_length(city)) from station)


问:
How to import a js file from src to public folder/service worker file
I have to set my firebase config to initialize it in my service worker, but i want to pass it with my config file, because I have more than one project and which one with it's respective firebase config. I was using this solution:

```<code>import project from '../src/config';
importScripts('https://www.gstatic.com/firebasejs/7.6.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.6.0/firebase-messaging.js');

firebase.initializeApp(project.firebaseConfig);
const messaging = firebase.messaging();
</code>```

But now I'm receiving the following message:

```<code>Uncaught SyntaxError: Cannot use import statement outside a module
</code>```

Do someone know a workaround to this?

答:
By default firebase will try to get it own Service Worker, but you can change it with useServiceWorker.
With this function you can select your own Service Worker.

So I setted a new Service Worker getting the name of the project like this:

```<code>navigator.serviceWorker.register(`./firebase-messaging-sw-${project.name_project.toLowerCase()}.js`, {
      scope: '/firebase-cloud-messaging-push-scope'
    })
</code>```

and after I just registered it

```<code>.then(function (registration) {
      if (registration) {
        messaging.useServiceWorker(registration)
      }
</code>```

I had to create in the public folder a service worker for each one of my projects, but worked.

Hope that will help you too

Body:
I have to set my firebase config to initialize it in my service worker, but i want to pass it with my config file, because I have more than one project and which one with it's respective firebase config. I was using this solution:

import project from '../src/config';
importScripts('https://www.gstatic.com/firebasejs/7.6.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.6.0/firebase-messaging.js');

firebase.initializeApp(project.firebaseConfig);
const messaging = firebase.messaging();

But now I'm receiving the following message:

Uncaught SyntaxError: Cannot use import statement outside a module

Do someone know a workaround to this?

Body:
By default firebase will try to get it own Service Worker, but you can change it with useServiceWorker.
With this function you can select your own Service Worker.

So I setted a new Service Worker getting the name of the project like this:

navigator.serviceWorker.register(`./firebase-messaging-sw-${project.name_project.toLowerCase()}.js`, {
      scope: '/firebase-cloud-messaging-push-scope'
    })

and after I just registered it

.then(function (registration) {
      if (registration) {
        messaging.useServiceWorker(registration)
      }

I had to create in the public folder a service worker for each one of my projects, but worked.

Hope that will help you too


问:
Apache Tiles like framework but with no xml configuration
Apache Tiles framework is great. But one thing I hate about it is the large xml configuration file that I have to maintain, even if partitioned, I just hate placing programmatic and presentation information inside configuration files.

I just don't get it? How did struts/tiles authors reach this obsessive tendency to place so much presentation logic inside configuration files?

I'm searching for a framework like Tiles but without the bloody XML configuration. Anyone can help in listing layout frameworks based on the Composite View model that compete with Tiles.

答: The layout tags provided by stripes are excellent. Require no configuration at all and easy to comprehend and start using. They are so great to an extent that I think they should be extracted from stripes and maintained as a separate project on there own github project space.</p>


问:
Is there some way that I can that i can add up the random values and print it?
Random is obviously needed, but it makes it harder to gather the values. =) This is an unnecessary comment.

```<code>import random
class Die:
    def __init__ (self, face, face_value):
        self.face = face
        self.face_value = face_value
    def roll(self):
</code>```

I have tried making the class do this twice, but for some reason it does not work.

```<code>        self.face = random.randint(1, 6)
        if self.face == 1:
            face = ( ' ------\n|       |\n|   o   |\n|       |\n ------')
            num = 1
        elif self.face == 2:
            face =  (' ------\n|       |\n| o   o |\n|       |\n ------')
            num = 2
        elif self.face == 3:
             face =  (' ------\n|   o   |\n|   o   |\n|   o   |\n ------')
            num = 3
        elif self.face == 4:
            face =  (' ------\n| o   o |\n| o   o |\n|       |\n ------')
            num = 4
        elif self.face == 5:
            face =  (' ------\n| o   o |\n| o   o |\n|   o   |\n ------')
            num = 5
        elif self.face == 6:
            face = (' ------\n| o   o |\n| o   o |\n| o   o |\n ------' )
            num = 6
        return print(face)
 **My goal is to add up the two random values that I get from the Die class, I have tried to put two rolls in that class, but then it has the same output still. **
from DieClass import Die
user = input('Do you want to play this Dicegame?')
num = random.randint(1,6)
</code>```

I only need this num so that I have some value to put into the class.

```<code>if num == 1:
    face = ( ' ------\n|       |\n|   o   |\n|       |\n ------')
elif num == 2:
    face =  (' ------\n|       |\n| o   o |\n|       |\n ------')
elif num == 3:
    face =  (' ------\n|   o   |\n|   o   |\n|   o   |\n ------')
elif num == 4:
    face =  (' ------\n| o   o |\n| o   o |\n|       |\n ------')
elif num == 5:
    face =  (' ------\n| o   o |\n| o   o |\n|   o   |\n ------')
elif num == 6:
    face = (' ------\n| o   o |\n| o   o |\n| o   o |\n ------' )

class Dicegame(Die):
    def __init__ (self, name):
        self.name = name

    def play(self):
        Die1 = Die(face, num)
        return Die1.roll()
</code>```

I am trying to make this code more efficient, if you have any suggestions tell me

```<code>if user == 'yes' or 'yep' or 'y' or 'Yes' or 'YES!' or 'YES' or 'Yurp' or 'Yeppers' or
'si'or'1':
    while user != 5:
        user = input('Press 1 to roll, 2 to quit.')
        if user == '1':
            Dice1 = Dicegame('name')
            Dice1.play()
            Dice2 = Dicegame('bob')
            Dice2.play()
            print('')
            print('Thanks for playing!')
            print('')
        elif user == '2':
            print('Thanks for playing!')
            print('')
            exit()
</code>```

答:
A lookup dictionary will simplify the code a whole lot.</p>

```<code>import random

FACES = {
    1: " ------\n|       |\n|   o   |\n|       |\n ------",
    2: " ------\n|       |\n| o   o |\n|       |\n ------",
    3: " ------\n|   o   |\n|   o   |\n|   o   |\n ------",
    4: " ------\n| o   o |\n| o   o |\n|       |\n ------",
    5: " ------\n| o   o |\n| o   o |\n|   o   |\n ------",
    6: " ------\n| o   o |\n| o   o |\n| o   o |\n ------",
}

YES_REPLIES = {
    'yes', 'yep', 'y', 'Yes', 'YES!', 'YES', 'Yurp', 'Yeppers', 'si', '1'
}

class Die:
    def __init__(self, face, face_value):
        self.face = face
        self.face_value = face_value

    def roll(self):
        num = self.face = random.randint(1, 6)
        face = FACES[num]
        print(face)
        return num

class Dicegame(Die):
    def __init__(self, name):
        self.name = name

    def play(self):
        num = random.randint(1, 6)
        face = FACES[num]

        Die1 = Die(face, num)
        return Die1.roll()

user = input('Do you want to play this Dicegame? ')
if user in YES_REPLIES:
    while True:
        user = input('Press 1 to roll, 2 to quit. ')
        if user == '1':
            Dice1 = Dicegame('name')
            a = Dice1.play()
            Dice2 = Dicegame('bob')
            b = Dice2.play()
            print(f'Your total is {a+b}')
            print('Thanks for playing!')
            print('')
        elif user == '2':
            print('Thanks for playing!')
            print('')
            break

</code>```

Body:
Random is obviously needed, but it makes it harder to gather the values. =) This is an unnecessary comment.

import random
class Die:
    def __init__ (self, face, face_value):
        self.face = face
        self.face_value = face_value
    def roll(self):

I have tried making the class do this twice, but for some reason it does not work.

        self.face = random.randint(1, 6)
        if self.face == 1:
            face = ( ' ------\n|       |\n|   o   |\n|       |\n ------')
            num = 1
        elif self.face == 2:
            face =  (' ------\n|       |\n| o   o |\n|       |\n ------')
            num = 2
        elif self.face == 3:
             face =  (' ------\n|   o   |\n|   o   |\n|   o   |\n ------')
            num = 3
        elif self.face == 4:
            face =  (' ------\n| o   o |\n| o   o |\n|       |\n ------')
            num = 4
        elif self.face == 5:
            face =  (' ------\n| o   o |\n| o   o |\n|   o   |\n ------')
            num = 5
        elif self.face == 6:
            face = (' ------\n| o   o |\n| o   o |\n| o   o |\n ------' )
            num = 6
        return print(face)
 **My goal is to add up the two random values that I get from the Die class, I have tried to put two rolls in that class, but then it has the same output still. **
from DieClass import Die
user = input('Do you want to play this Dicegame?')
num = random.randint(1,6)

I only need this num so that I have some value to put into the class.

if num == 1:
    face = ( ' ------\n|       |\n|   o   |\n|       |\n ------')
elif num == 2:
    face =  (' ------\n|       |\n| o   o |\n|       |\n ------')
elif num == 3:
    face =  (' ------\n|   o   |\n|   o   |\n|   o   |\n ------')
elif num == 4:
    face =  (' ------\n| o   o |\n| o   o |\n|       |\n ------')
elif num == 5:
    face =  (' ------\n| o   o |\n| o   o |\n|   o   |\n ------')
elif num == 6:
    face = (' ------\n| o   o |\n| o   o |\n| o   o |\n ------' )

class Dicegame(Die):
    def __init__ (self, name):
        self.name = name

    def play(self):
        Die1 = Die(face, num)
        return Die1.roll()

I am trying to make this code more efficient, if you have any suggestions tell me

if user == 'yes' or 'yep' or 'y' or 'Yes' or 'YES!' or 'YES' or 'Yurp' or 'Yeppers' or
'si'or'1':
    while user != 5:
        user = input('Press 1 to roll, 2 to quit.')
        if user == '1':
            Dice1 = Dicegame('name')
            Dice1.play()
            Dice2 = Dicegame('bob')
            Dice2.play()
            print('')
            print('Thanks for playing!')
            print('')
        elif user == '2':
            print('Thanks for playing!')
            print('')
            exit()

Body:
A lookup dictionary will simplify the code a whole lot.

import random

FACES = {
    1: " ------\n|       |\n|   o   |\n|       |\n ------",
    2: " ------\n|       |\n| o   o |\n|       |\n ------",
    3: " ------\n|   o   |\n|   o   |\n|   o   |\n ------",
    4: " ------\n| o   o |\n| o   o |\n|       |\n ------",
    5: " ------\n| o   o |\n| o   o |\n|   o   |\n ------",
    6: " ------\n| o   o |\n| o   o |\n| o   o |\n ------",
}

YES_REPLIES = {
    'yes', 'yep', 'y', 'Yes', 'YES!', 'YES', 'Yurp', 'Yeppers', 'si', '1'
}

class Die:
    def __init__(self, face, face_value):
        self.face = face
        self.face_value = face_value

    def roll(self):
        num = self.face = random.randint(1, 6)
        face = FACES[num]
        print(face)
        return num

class Dicegame(Die):
    def __init__(self, name):
        self.name = name

    def play(self):
        num = random.randint(1, 6)
        face = FACES[num]

        Die1 = Die(face, num)
        return Die1.roll()

user = input('Do you want to play this Dicegame? ')
if user in YES_REPLIES:
    while True:
        user = input('Press 1 to roll, 2 to quit. ')
        if user == '1':
            Dice1 = Dicegame('name')
            a = Dice1.play()
            Dice2 = Dicegame('bob')
            b = Dice2.play()
            print(f'Your total is {a+b}')
            print('Thanks for playing!')
            print('')
        elif user == '2':
            print('Thanks for playing!')
            print('')
            break


问:
Check if a entry start with http
I'm writing a python code and using tkinter but i know how to check if a entry is empty before click the button, now i want to know how to check if the entry start with http after click the button and before running the program.

Thanks in advance

答:
As @Olvin Roght said in the comments, this should work:

e = Entry(master)
e.pack()
def get():
    string2 = e.get()
    if string2.startswith("http"):
       #what ever you need
```

Also, you can't check the entry before running the program. Please edit your question to include more detail.

Hope this helps!

Title: Check if a entry start with http

Body:
As @Olvin Roght said in the comments, this should work:

e = Entry(master)
e.pack()
def get():
    string2 = e.get()
    if string2.startswith("http"):
       #what ever you need

Also, you can't check the entry before running the program. Please edit your question to include more detail.

Hope this helps!


问:
Can't figure out why no trades are executed
I'm trying to execute a long entry when the 3 conditions are true (redCandleDirection, isRsiLow, isUnderBollinger) but it won't work. I've tried manually setting them all to true and still no entries are executed. I'm fairly confident due to this that there's an error in my logic but I can't find it. Any help would be greatly appreciated.

The conditions and when they are checked:

```<code>redCandleDirection = ((close[0] < open[0]) and (close[1] < open[1]) and (close[2] < open[2]) and (close[3] < open[3]) and (close[4] < open[4]))
isRsiLow = (d <= 10)
isUnderBollinger = (crossover(src, lower))
entryLong = false

isLongEntry(redCandleDirection, isRsiLow, isUnderBollinger) =>
    if (redCandleDirection)
        if (isRsiLow)
            if (isUnderBollinger)
                entryLong = true
            else
                entryLong = false
        else
            entryLong = false
    else
        entryLong = false
    entryLong

if isLongEntry(redCandleDirection, isRsiLow, isUnderBollinger)
    strategy.entry(id="Entry Long", long=true)
    strategy.exit(id="Exit Long", from_entry="Entry Long", qty_percent=100, limit=sma, stop=close[1])
</code>```

The full code, if you need it:

```<code>// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © PatrickML
// @ ChuckBanger

//@version=4
strategy(title="Bollinger Bands w/ Limit and Trailing Stop", shorttitle="BB w/ L + TS",
   overlay=true,  pyramiding=1, default_qty_type=strategy.percent_of_equity, default_qty_value=50, initial_capital=1000.0)

length = input(title="Length", type=input.integer, defval=20, minval=1)
regular = input(title="Regular BB Or CBMA?", type=input.bool, defval=true)
src = input(title="Source", type=input.source, defval=close)
mult = input(title="Multipler", type=input.float, defval=2.3, minval=.001, maxval=50, step=.1)
emaLen = input(title="EMA Length", type=input.integer, defval=20, minval=1)
emaGL = input(title="EMA Gain Limit", type=input.integer, defval=50, minval=1)
highlight = input(title="Highlight On/Off", type=input.bool, defval=true)

smaLen = input(title="SMA Length", type=input.integer, defval=9, minval=1)
sma = sma(close, smaLen)

direction = input(0, title = "Strategy Direction", type=input.integer, minval=-1, maxval=1)

strategy.risk.allow_entry_in(direction == 0 ? strategy.direction.all : (direction < 0 ? strategy.direction.short : strategy.direction.long))

//strategy.risk.max_drawdown(50, strategy.percent_of_equity)

///STOCH.RSI///
smoothK = input(3, minval=1, title="Stochastic %K Smoothing")
smoothD = input(3, minval=1, title="Stochastic %K Moving Average")
lengthRSI = input(14, minval=1, title="RSI Length")
lengthStoch = input(14, minval=1, title="Stochastic Length")
RSIprice = close
rsi1 = rsi(RSIprice, lengthRSI)
k = sma(stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)
d = sma(k, smoothD)

calc_hma(src, length) =>
    hullma = wma(2*wma(src, length/2)-wma(src, length), round(sqrt(length)))
    hullma

calc_cbma(price, length, emaLength, emaGainLimit) =>
    alpha = 2 / (emaLength + 1)
    ema = ema(price, emaLength)
    int leastError = 1000000

    float ec = 0
    float bestGain = 0

    for i = emaGainLimit to emaGainLimit
        gain = i / 10
        ec := alpha * ( ema + gain * (price - nz(ec[1])) ) + (1 - alpha) * nz(ec[1])
        error = price - ec
        if (abs(error) < leastError)
            leastError = abs(error)
            bestGain = gain

    ec := alpha * ( ema + bestGain * (price - nz(ec[1])) ) + (1 - alpha) * nz(ec[1])
    hull = calc_hma(price, length)

    cbma = (ec + hull) / 2
    cbma

cbma = calc_cbma(src, length, emaLen, emaGL)
basis = regular ? sma(src, length) : cbma
dev = mult * stdev(src, length)
upper = basis + dev
lower = basis - dev
cbmaColor = fixnan(highlight and not regular ? cbma > high ? color.purple : cbma < low ? color.aqua : na : color.red)
plot(basis, color=cbmaColor)
plot(sma, color=color.orange)
p1 = plot(upper, color=color.blue)
p2 = plot(lower, color=color.blue)
fill(p1, p2)

redCandleDirection = ((close[0] < open[0]) and (close[1] < open[1]) and (close[2] < open[2]) and (close[3] < open[3]) and (close[4] < open[4]))
isRsiLow = (d <= 10)
isUnderBollinger = (crossover(src, lower))
entryLong = false

isLongEntry(redCandleDirection, isRsiLow, isUnderBollinger) =>
    if (redCandleDirection)
        if (isRsiLow)
            if (isUnderBollinger)
                entryLong = true
            else
                entryLong = false
        else
            entryLong = false
    else
        entryLong = false
    entryLong

if isLongEntry(redCandleDirection, isRsiLow, isUnderBollinger)
    strategy.entry(id="Entry Long", long=true)
    strategy.exit(id="Exit Long", from_entry="Entry Long", qty_percent=100, limit=sma, stop=close[1])
</code>```

答:
This should help you get started. You cannot use the = operator in a local block to reassign a value to a variable, otherwise you're creating a new local instance of that variable. Need to use := instead.

```<code>// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © PatrickML
// @ ChuckBanger

//@version=4
strategy(title="Bollinger Bands w/ Limit and Trailing Stop", shorttitle="BB w/ L + TS",
   overlay=true,  pyramiding=1, default_qty_type=strategy.percent_of_equity, default_qty_value=50, initial_capital=1000.0)

length = input(title="Length", type=input.integer, defval=20, minval=1)
regular = input(title="Regular BB Or CBMA?", type=input.bool, defval=true)
src = input(title="Source", type=input.source, defval=close)
mult = input(title="Multipler", type=input.float, defval=2.3, minval=.001, maxval=50, step=.1)
emaLen = input(title="EMA Length", type=input.integer, defval=20, minval=1)
emaGL = input(title="EMA Gain Limit", type=input.integer, defval=50, minval=1)
highlight = input(title="Highlight On/Off", type=input.bool, defval=true)

smaLen = input(title="SMA Length", type=input.integer, defval=9, minval=1)
sma = sma(close, smaLen)

direction = input(0, title = "Strategy Direction", type=input.integer, minval=-1, maxval=1)

strategy.risk.allow_entry_in(direction == 0 ? strategy.direction.all : (direction < 0 ? strategy.direction.short : strategy.direction.long))

//strategy.risk.max_drawdown(50, strategy.percent_of_equity)

///STOCH.RSI///
smoothK = input(3, minval=1, title="Stochastic %K Smoothing")
smoothD = input(3, minval=1, title="Stochastic %K Moving Average")
lengthRSI = input(14, minval=1, title="RSI Length")
lengthStoch = input(14, minval=1, title="Stochastic Length")
RSIprice = close
rsi1 = rsi(RSIprice, lengthRSI)
k = sma(stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)
d = sma(k, smoothD)

calc_hma(src, length) =>
    hullma = wma(2*wma(src, length/2)-wma(src, length), round(sqrt(length)))
    hullma

calc_cbma(price, length, emaLength, emaGainLimit) =>
    alpha = 2 / (emaLength + 1)
    ema = ema(price, emaLength)
    int leastError = 1000000

    float ec = 0
    float bestGain = 0

    for i = emaGainLimit to emaGainLimit
        gain = i / 10
        ec := alpha * ( ema + gain * (price - nz(ec[1])) ) + (1 - alpha) * nz(ec[1])
        error = price - ec
        if (abs(error) < leastError)
            leastError := int(abs(error))
            bestGain := gain

    ec := alpha * ( ema + bestGain * (price - nz(ec[1])) ) + (1 - alpha) * nz(ec[1])
    hull = calc_hma(price, length)

    cbma = (ec + hull) / 2
    cbma

cbma = calc_cbma(src, length, emaLen, emaGL)
basis = regular ? sma(src, length) : cbma
dev = mult * stdev(src, length)
upper = basis + dev
lower = basis - dev
cbmaColor = fixnan(highlight and not regular ? cbma > high ? color.purple : cbma < low ? color.aqua : na : color.red)
plot(basis, color=cbmaColor)
plot(sma, color=color.orange)
p1 = plot(upper, color=color.blue)
p2 = plot(lower, color=color.blue)
fill(p1, p2)

redCandleDirection = ((close[0] < open[0]) and (close[1] < open[1]) and (close[2] < open[2]) and (close[3] < open[3]) and (close[4] < open[4]))
isRsiLow = (d <= 10)
isUnderBollinger = (crossover(src, lower))

isLongEntry(redCandleDirection, isRsiLow, isUnderBollinger) =>
    _entryLong = false
    if (redCandleDirection)
        if (isRsiLow)
            if (isUnderBollinger)
                _entryLong := true
            else
                _entryLong := false
        else
            _entryLong := false
    else
        _entryLong := false
    _entryLong

if isLongEntry(redCandleDirection, isRsiLow, isUnderBollinger)
    strategy.entry(id="Entry Long", long=true)
    strategy.exit(id="Exit Long", from_entry="Entry Long", qty_percent=100, limit=sma, stop=close[1])
</code>```

Body:
I'm trying to execute a long entry when the 3 conditions are true (redCandleDirection, isRsiLow, isUnderBollinger) but it won't work. I've tried manually setting them all to true and still no entries are executed. I'm fairly confident due to this that there's an error in my logic but I can't find it. Any help would be greatly appreciated.

The conditions and when they are checked:

redCandleDirection = ((close[0] < open[0]) and (close[1] < open[1]) and (close[2] < open[2]) and (close[3] < open[3]) and (close[4] < open[4]))
isRsiLow = (d <= 10)
isUnderBollinger = (crossover(src, lower))
entryLong = false

isLongEntry(redCandleDirection, isRsiLow, isUnderBollinger) =>
    if (redCandleDirection)
        if (isRsiLow)
            if (isUnderBollinger)
                entryLong = true
            else
                entryLong = false
        else
            entryLong = false
    else
        entryLong = false
    entryLong

if isLongEntry(redCandleDirection, isRsiLow, isUnderBollinger)
    strategy.entry(id="Entry Long", long=true)
    strategy.exit(id="Exit Long", from_entry="Entry Long", qty_percent=100, limit=sma, stop=close[1])

The full code, if you need it:

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © PatrickML
// @ ChuckBanger

//@version=4
strategy(title="Bollinger Bands w/ Limit and Trailing Stop", shorttitle="BB w/ L + TS",
   overlay=true,  pyramiding=1, default_qty_type=strategy.percent_of_equity, default_qty_value=50, initial_capital=1000.0)

length = input(title="Length", type=input.integer, defval=20, minval=1)
regular = input(title="Regular BB Or CBMA?", type=input.bool, defval=true)
src = input(title="Source", type=input.source, defval=close)
mult = input(title="Multipler", type=input.float, defval=2.3, minval=.001, maxval=50, step=.1)
emaLen = input(title="EMA Length", type=input.integer, defval=20, minval=1)
emaGL = input(title="EMA Gain Limit", type=input.integer, defval=50, minval=1)
highlight = input(title="Highlight On/Off", type=input.bool, defval=true)

smaLen = input(title="SMA Length", type=input.integer, defval=9, minval=1)
sma = sma(close, smaLen)

direction = input(0, title = "Strategy Direction", type=input.integer, minval=-1, maxval=1)

strategy.risk.allow_entry_in(direction == 0 ? strategy.direction.all : (direction < 0 ? strategy.direction.short : strategy.direction.long))

//strategy.risk.max_drawdown(50, strategy.percent_of_equity)

///STOCH.RSI///
smoothK = input(3, minval=1, title="Stochastic %K Smoothing")
smoothD = input(3, minval=1, title="Stochastic %K Moving Average")
lengthRSI = input(14, minval=1, title="RSI Length")
lengthStoch = input(14, minval=1, title="Stochastic Length")
RSIprice = close
rsi1 = rsi(RSIprice, lengthRSI)
k = sma(stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)
d = sma(k, smoothD)

calc_hma(src, length) =>
    hullma = wma(2*wma(src, length/2)-wma(src, length), round(sqrt(length)))
    hullma

calc_cbma(price, length, emaLength, emaGainLimit) =>
    alpha = 2 / (emaLength + 1)
    ema = ema(price, emaLength)
    int leastError = 1000000

    float ec = 0
    float bestGain = 0

    for i = emaGainLimit to emaGainLimit
        gain = i / 10
        ec := alpha * ( ema + gain * (price - nz(ec[1])) ) + (1 - alpha) * nz(ec[1])
        error = price - ec
        if (abs(error) < leastError)
            leastError = abs(error)
            bestGain = gain

    ec := alpha * ( ema + bestGain * (price - nz(ec[1])) ) + (1 - alpha) * nz(ec[1])
    hull = calc_hma(price, length)

    cbma = (ec + hull) / 2
    cbma

cbma = calc_cbma(src, length, emaLen, emaGL)
basis = regular ? sma(src, length) : cbma
dev = mult * stdev(src, length)
upper = basis + dev
lower = basis - dev
cbmaColor = fixnan(highlight and not regular ? cbma > high ? color.purple : cbma < low ? color.aqua : na : color.red)
plot(basis, color=cbmaColor)
plot(sma, color=color.orange)
p1 = plot(upper, color=color.blue)
p2 = plot(lower, color=color.blue)
fill(p1, p2)

redCandleDirection = ((close[0] < open[0]) and (close[1] < open[1]) and (close[2] < open[2]) and (close[3] < open[3]) and (close[4] < open[4]))
isRsiLow = (d <= 10)
isUnderBollinger = (crossover(src, lower))
entryLong = false

isLongEntry(redCandleDirection, isRsiLow, isUnderBollinger) =>
    if (redCandleDirection)
        if (isRsiLow)
            if (isUnderBollinger)
                entryLong = true
            else
                entryLong = false
        else
            entryLong = false
    else
        entryLong = false
    entryLong

if isLongEntry(redCandleDirection, isRsiLow, isUnderBollinger)
    strategy.entry(id="Entry Long", long=true)
    strategy.exit(id="Exit Long", from_entry="Entry Long", qty_percent=100, limit=sma, stop=close[1])

Body:
This should help you get started. You cannot use the = operator in a local block to reassign a value to a variable, otherwise you're creating a new local instance of that variable. Need to use := instead.

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © PatrickML
// @ ChuckBanger

//@version=4
strategy(title="Bollinger Bands w/ Limit and Trailing Stop", shorttitle="BB w/ L + TS",
   overlay=true,  pyramiding=1, default_qty_type=strategy.percent_of_equity, default_qty_value=50, initial_capital=1000.0)

length = input(title="Length", type=input.integer, defval=20, minval=1)
regular = input(title="Regular BB Or CBMA?", type=input.bool, defval=true)
src = input(title="Source", type=input.source, defval=close)
mult = input(title="Multipler", type=input.float, defval=2.3, minval=.001, maxval=50, step=.1)
emaLen = input(title="EMA Length", type=input.integer, defval=20, minval=1)
emaGL = input(title="EMA Gain Limit", type=input.integer, defval=50, minval=1)
highlight = input(title="Highlight On/Off", type=input.bool, defval=true)

smaLen = input(title="SMA Length", type=input.integer, defval=9, minval=1)
sma = sma(close, smaLen)

direction = input(0, title = "Strategy Direction", type=input.integer, minval=-1, maxval=1)

strategy.risk.allow_entry_in(direction == 0 ? strategy.direction.all : (direction < 0 ? strategy.direction.short : strategy.direction.long))

//strategy.risk.max_drawdown(50, strategy.percent_of_equity)

///STOCH.RSI///
smoothK = input(3, minval=1, title="Stochastic %K Smoothing")
smoothD = input(3, minval=1, title="Stochastic %K Moving Average")
lengthRSI = input(14, minval=1, title="RSI Length")
lengthStoch = input(14, minval=1, title="Stochastic Length")
RSIprice = close
rsi1 = rsi(RSIprice, lengthRSI)
k = sma(stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)
d = sma(k, smoothD)

calc_hma(src, length) =>
    hullma = wma(2*wma(src, length/2)-wma(src, length), round(sqrt(length)))
    hullma

calc_cbma(price, length, emaLength, emaGainLimit) =>
    alpha = 2 / (emaLength + 1)
    ema = ema(price, emaLength)
    int leastError = 1000000

    float ec = 0
    float bestGain = 0

    for i = emaGainLimit to emaGainLimit
        gain = i / 10
        ec := alpha * ( ema + gain * (price - nz(ec[1])) ) + (1 - alpha) * nz(ec[1])
        error = price - ec
        if (abs(error) < leastError)
            leastError := int(abs(error))
            bestGain := gain

    ec := alpha * ( ema + bestGain * (price - nz(ec[1])) ) + (1 - alpha) * nz(ec[1])
    hull = calc_hma(price, length)

    cbma = (ec + hull) / 2
    cbma

cbma = calc_cbma(src, length, emaLen, emaGL)
basis = regular ? sma(src, length) : cbma
dev = mult * stdev(src, length)
upper = basis + dev
lower = basis - dev
cbmaColor = fixnan(highlight and not regular ? cbma > high ? color.purple : cbma < low ? color.aqua : na : color.red)
plot(basis, color=cbmaColor)
plot(sma, color=color.orange)
p1 = plot(upper, color=color.blue)
p2 = plot(lower, color=color.blue)
fill(p1, p2)

redCandleDirection = ((close[0] < open[0]) and (close[1] < open[1]) and (close[2] < open[2]) and (close[3] < open[3]) and (close[4] < open[4]))
isRsiLow = (d <= 10)
isUnderBollinger = (crossover(src, lower))

isLongEntry(redCandleDirection, isRsiLow, isUnderBollinger) =>
    _entryLong = false
    if (redCandleDirection)
        if (isRsiLow)
            if (isUnderBollinger)
                _entryLong := true
            else
                _entryLong := false
        else
            _entryLong := false
    else
        _entryLong := false
    _entryLong

if isLongEntry(redCandleDirection, isRsiLow, isUnderBollinger)
    strategy.entry(id="Entry Long", long=true)
    strategy.exit(id="Exit Long", from_entry="Entry Long", qty_percent=100, limit=sma, stop=close[1])


问:
From date to tuple Python
I have like input: 12/12/2019
and I want this output: (12,12,2019)
I tried this code but it doesn't work because they consider "/" as a division :

```<code>date= 12/12/2019
date=str(date).split("/")
print(tuple(date))
</code>```

Title: From date to tuple Python

Body:
I have like input: 12/12/2019
and I want this output: (12,12,2019)
I tried this code but it doesn't work because they consider "/" as a division :

date= 12/12/2019
date=str(date).split("/")
print(tuple(date))

Body:
>>> tuple(map(int, "12/12/2019".split("/")))
(12, 12, 2019)


问:
BeautifulSoup uncomment a comment by id
I want to use BeautifulSoup to change a html below to uncomment by comment tag id.

```<code><div class="foo">
 cat dog sheep goat
 <!--<p id="p1">test</p>-->
 <p id="p2">
  test
 </p>
</div>
</code>```

This is my expected result below:

```<code><div class="foo">
 cat dog sheep goat
 <p id="p1">test</p>
 <p id="p2">
  test
 </p>
</div>
</code>```

This is my python code I use BeautifulSoup, but I don't know how to complete this function.

```<code>from bs4 import BeautifulSoup,Comment

data = """<div class="foo">
cat dog sheep goat
<p id='p1'>test</p>
<p id='p2'>test</p>
</div>"""
soup = BeautifulSoup(data, 'html.parser')

for comment in soup(text=lambda text: isinstance(text, Comment)):
    if 'id="p1"' in comment.string:
        # I don't know how to complete it here.
        # This is my incorrect solution
        # It will output "<p id="p1">test</p>",
        # not "<p id='p1'>test</p>"
        comment.replace_with(comment.string.replace("<!--", "").replace("-->", ""))
        break
</code>```

Ask for help

答:
Have you considered just using regex instead of bs4?

Maybe this can get you started.

>>> re.search("", '')
<re.Match object; span=(0, 26), match=''>
>>> re.search("", '').group(1)
'
test
'
>>> regex = re.compile("")
>>> regex.sub('
test
', '')
'
test
'
```

Title: BeautifulSoup uncomment a comment by id

Body:
I want to use BeautifulSoup to change a html below to uncomment by comment tag id.

 cat dog sheep goat

  test

This is my expected result below:

 cat dog sheep goat

test

  test

This is my python code I use BeautifulSoup, but I don't know how to complete this function.

from bs4 import BeautifulSoup,Comment

data = """

cat dog sheep goat

test

test

"""
soup = BeautifulSoup(data, 'html.parser')

for comment in soup(text=lambda text: isinstance(text, Comment)):
    if 'id="p1"' in comment.string:
        # I don't know how to complete it here.
        # This is my incorrect solution
        # It will output "
test
",
        # not "
test
"
        comment.replace_with(comment.string.replace("", ""))
        break

Ask for help

Body:
Have you considered just using regex instead of bs4?

Maybe this can get you started.

>>> re.search("<!--((.*)p1(.*))-->", '<!--<p id="p1">test</p>-->')
<re.Match object; span=(0, 26), match='<!--<p id="p1">test</p>-->'>
>>> re.search("<!--((.*)p1(.*))-->", '<!--<p id="p1">test</p>-->').group(1)
'<p id="p1">test</p>'
>>> regex = re.compile("<!--((.*)p1(.*))-->")
>>> regex.sub('<p id="p1">test</p>', '<!--<p id="p1">test</p>-->')
'<p id="p1">test</p>'


问:
Making PropertyMock wrap an existing property - Python
I want to test that an instance variable is "set" to specific values (i.e. multiple times) when a Python method is called.

Replacing the instance variable with a PropertyMock allows me to view the mock_calls and verify what values the property was set to.  However, PropertyMock doesn't behave like a normal variable.  When you set a value on it and try to read it, you get back another Mock.  Is there a way to receive the value back instead?

Here's a contrived example:

import time
from unittest.mock import PropertyMock, call

class Machine:

    def __init__(self):
        self.mode = "idle"

    def start(self):

        # Update mode
        self.mode = "running"

        # Do some work, e.g. drive a motor for 0.5 sec
        time.sleep(0.5)

        # Restore mode
        if self.mode == "running":         # Should always be True, but isn't when using PropertyMock
            self.mode = "idle"

class Test_Machine:

    def test(self):

        # Create a machine
        real_machine = Machine()

        # Mock the 'mode' property
        mocked_property = PropertyMock()
        type(real_machine).mode = mocked_property

        # Call the method to test
        real_machine.start()

        print(mocked_property.mock_calls)                         # [call('running'), call(), call().__eq__('running')]
        assert call("running") == mocked_property.mock_calls[0]   # Success
        assert call("idle") == mocked_property.mock_calls[-1]     # Fails here

```

答:
I'm sure there is a better way to do this, but if you are just interested in the calls of the property setter, and want the getter to behave as the original property, you could override PropertyMock to behave like that:

```<code>class MyPropertyMock(PropertyMock):
    def __init__(self, value=None):
        super().__init__()
        self.value = value

    def __get__(self, obj, obj_type):
        return self.value  # the mock will not register these calls

    def __set__(self, obj, val):
        self.value = val
        super().__set__(obj, val)  # ensure the mock behavior in the setter

class Test_Machine:
    def test(self):
        real_machine = Machine()
        mocked_property = MyPropertyMock(real_machine.value)
        Machine.mode = mocked_property

        real_machine.start()

        print(mocked_property.mock_calls)  # [call('running'), call('idle')]
        ...
</code>```

Body:
I'm sure there is a better way to do this, but if you are just interested in the calls of the property setter, and want the getter to behave as the original property, you could override PropertyMock to behave like that:

class MyPropertyMock(PropertyMock):
    def __init__(self, value=None):
        super().__init__()
        self.value = value

    def __get__(self, obj, obj_type):
        return self.value  # the mock will not register these calls

    def __set__(self, obj, val):
        self.value = val
        super().__set__(obj, val)  # ensure the mock behavior in the setter

class Test_Machine:
    def test(self):
        real_machine = Machine()
        mocked_property = MyPropertyMock(real_machine.value)
        Machine.mode = mocked_property

        real_machine.start()

        print(mocked_property.mock_calls)  # [call('running'), call('idle')]
        ...