问:
pytorch loss value not change
I wrote a module based on this article: http://www.wildml.com/2015/12/implementing-a-cnn-for-text-classification-in-tensorflow/

The idea is pass the input into multiple streams then concat together and connect to a FC layer. I divided my source code into 3 custom modules: TextClassifyCnnNet >> FlatCnnLayer >> FilterLayer

FilterLayer:

```<code>class FilterLayer(nn.Module):
    def __init__(self, filter_size, embedding_size, sequence_length, out_channels=128):
        super(FilterLayer, self).__init__()

        self.model = nn.Sequential(
            nn.Conv2d(1, out_channels, (filter_size, embedding_size)),
            nn.ReLU(inplace=True),
            nn.MaxPool2d((sequence_length - filter_size + 1, 1), stride=1)
        )

        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
                m.weight.data.normal_(0, math.sqrt(2. / n))

    def forward(self, x):
        return self.model(x)
</code>```

FlatCnnLayer:

```<code>class FlatCnnLayer(nn.Module):
    def __init__(self, embedding_size, sequence_length, filter_sizes=[3, 4, 5], out_channels=128):
        super(FlatCnnLayer, self).__init__()

        self.filter_layers = nn.ModuleList(
            [FilterLayer(filter_size, embedding_size, sequence_length, out_channels=out_channels) for
             filter_size in filter_sizes])

    def forward(self, x):
        pools = []
        for filter_layer in self.filter_layers:
            out_filter = filter_layer(x)
            # reshape from (batch_size, out_channels, h, w) to (batch_size, h, w, out_channels)
            pools.append(out_filter.view(out_filter.size()[0], 1, 1, -1))
        x = torch.cat(pools, dim=3)

        x = x.view(x.size()[0], -1)
        x = F.dropout(x, p=dropout_prob, training=True)

        return x
</code>```

TextClassifyCnnNet (main module):

```<code>class TextClassifyCnnNet(nn.Module):
    def __init__(self, embedding_size, sequence_length, num_classes, filter_sizes=[3, 4, 5], out_channels=128):
        super(TextClassifyCnnNet, self).__init__()

        self.flat_layer = FlatCnnLayer(embedding_size, sequence_length, filter_sizes=filter_sizes,
                                       out_channels=out_channels)

        self.model = nn.Sequential(
            self.flat_layer,
            nn.Linear(out_channels * len(filter_sizes), num_classes)
        )

    def forward(self, x):
        x = self.model(x)

        return x

def fit(net, data, save_path):
    if torch.cuda.is_available():
        net = net.cuda()

    for param in list(net.parameters()):
        print(type(param.data), param.size())

    optimizer = optim.Adam(net.parameters(), lr=0.01, weight_decay=0.1)

    X_train, X_test = data['X_train'], data['X_test']
    Y_train, Y_test = data['Y_train'], data['Y_test']

    X_valid, Y_valid = data['X_valid'], data['Y_valid']

    n_batch = len(X_train) // batch_size

    for epoch in range(1, n_epochs + 1):  # loop over the dataset multiple times
        net.train()
        start = 0
        end = batch_size

        for batch_idx in range(1, n_batch + 1):
            # get the inputs
            x, y = X_train[start:end], Y_train[start:end]
            start = end
            end = start + batch_size

            # zero the parameter gradients
            optimizer.zero_grad()

            # forward + backward + optimize
            predicts = _get_predict(net, x)
            loss = _get_loss(predicts, y)
            loss.backward()
            optimizer.step()

            if batch_idx % display_step == 0:
                print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
                    epoch, batch_idx * len(x), len(X_train), 100. * batch_idx / (n_batch + 1), loss.data[0]))

        # print statistics
        if epoch % display_step == 0 or epoch == 1:
            net.eval()
            valid_predicts = _get_predict(net, X_valid)
            valid_loss = _get_loss(valid_predicts, Y_valid)
            valid_accuracy = _get_accuracy(valid_predicts, Y_valid)
            print('\r[%d] loss: %.3f - accuracy: %.2f' % (epoch, valid_loss.data[0], valid_accuracy * 100))

    print('\rFinished Training\n')

    net.eval()

    test_predicts = _get_predict(net, X_test)
    test_loss = _get_loss(test_predicts, Y_test).data[0]
    test_accuracy = _get_accuracy(test_predicts, Y_test)
    print('Test loss: %.3f - Test accuracy: %.2f' % (test_loss, test_accuracy * 100))

    torch.save(net.flat_layer.state_dict(), save_path)

def _get_accuracy(predicts, labels):
    predicts = torch.max(predicts, 1)[1].data[0]
    return np.mean(predicts == labels)

def _get_predict(net, x):
    # wrap them in Variable
    inputs = torch.from_numpy(x).float()
    # convert to cuda tensors if cuda flag is true
    if torch.cuda.is_available:
        inputs = inputs.cuda()
    inputs = Variable(inputs)
    return net(inputs)

def _get_loss(predicts, labels):
    labels = torch.from_numpy(labels).long()
    # convert to cuda tensors if cuda flag is true
    if torch.cuda.is_available:
        labels = labels.cuda()
    labels = Variable(labels)
    return F.cross_entropy(predicts, labels)
</code>```

It seems that parameters 're just updated slightly each epoch, the accuracy remains for all the process. While with the same implementation and the same params in Tensorflow, it runs correctly.

I'm new to Pytorch, so maybe my instructions has something wrong, please help me to find out. Thank you!

P.s: I try to use F.nll_loss + F.log_softmax instead of F.cross_entropy. Theoretically, it should return the same, but in fact another result is printed out (but it still be a wrong loss value)

答:
In my case, I was facing the same error. On my laptop without GPU the training was fine. When I tried on GPU the model didn’t change the accuracy and loss after the first epochs. I was using nn.CrossEntropyLoss() with Adam.
Changing Adam with SGD worked for me.
I am sharing this, anyone may suffer from this.</p>

Title: pytorch loss value not change

Body:
I wrote a module based on this article: http://www.wildml.com/2015/12/implementing-a-cnn-for-text-classification-in-tensorflow/

The idea is pass the input into multiple streams then concat together and connect to a FC layer. I divided my source code into 3 custom modules: TextClassifyCnnNet >> FlatCnnLayer >> FilterLayer

FilterLayer:

class FilterLayer(nn.Module):
    def __init__(self, filter_size, embedding_size, sequence_length, out_channels=128):
        super(FilterLayer, self).__init__()

        self.model = nn.Sequential(
            nn.Conv2d(1, out_channels, (filter_size, embedding_size)),
            nn.ReLU(inplace=True),
            nn.MaxPool2d((sequence_length - filter_size + 1, 1), stride=1)
        )

        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
                m.weight.data.normal_(0, math.sqrt(2. / n))

    def forward(self, x):
        return self.model(x)

FlatCnnLayer:

class FlatCnnLayer(nn.Module):
    def __init__(self, embedding_size, sequence_length, filter_sizes=[3, 4, 5], out_channels=128):
        super(FlatCnnLayer, self).__init__()

        self.filter_layers = nn.ModuleList(
            [FilterLayer(filter_size, embedding_size, sequence_length, out_channels=out_channels) for
             filter_size in filter_sizes])

    def forward(self, x):
        pools = []
        for filter_layer in self.filter_layers:
            out_filter = filter_layer(x)
            # reshape from (batch_size, out_channels, h, w) to (batch_size, h, w, out_channels)
            pools.append(out_filter.view(out_filter.size()[0], 1, 1, -1))
        x = torch.cat(pools, dim=3)

        x = x.view(x.size()[0], -1)
        x = F.dropout(x, p=dropout_prob, training=True)

        return x

TextClassifyCnnNet (main module):

class TextClassifyCnnNet(nn.Module):
    def __init__(self, embedding_size, sequence_length, num_classes, filter_sizes=[3, 4, 5], out_channels=128):
        super(TextClassifyCnnNet, self).__init__()

        self.flat_layer = FlatCnnLayer(embedding_size, sequence_length, filter_sizes=filter_sizes,
                                       out_channels=out_channels)

        self.model = nn.Sequential(
            self.flat_layer,
            nn.Linear(out_channels * len(filter_sizes), num_classes)
        )

    def forward(self, x):
        x = self.model(x)

        return x

def fit(net, data, save_path):
    if torch.cuda.is_available():
        net = net.cuda()

    for param in list(net.parameters()):
        print(type(param.data), param.size())

    optimizer = optim.Adam(net.parameters(), lr=0.01, weight_decay=0.1)

    X_train, X_test = data['X_train'], data['X_test']
    Y_train, Y_test = data['Y_train'], data['Y_test']

    X_valid, Y_valid = data['X_valid'], data['Y_valid']

    n_batch = len(X_train) // batch_size

    for epoch in range(1, n_epochs + 1):  # loop over the dataset multiple times
        net.train()
        start = 0
        end = batch_size

        for batch_idx in range(1, n_batch + 1):
            # get the inputs
            x, y = X_train[start:end], Y_train[start:end]
            start = end
            end = start + batch_size

            # zero the parameter gradients
            optimizer.zero_grad()

            # forward + backward + optimize
            predicts = _get_predict(net, x)
            loss = _get_loss(predicts, y)
            loss.backward()
            optimizer.step()

            if batch_idx % display_step == 0:
                print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
                    epoch, batch_idx * len(x), len(X_train), 100. * batch_idx / (n_batch + 1), loss.data[0]))

        # print statistics
        if epoch % display_step == 0 or epoch == 1:
            net.eval()
            valid_predicts = _get_predict(net, X_valid)
            valid_loss = _get_loss(valid_predicts, Y_valid)
            valid_accuracy = _get_accuracy(valid_predicts, Y_valid)
            print('\r[%d] loss: %.3f - accuracy: %.2f' % (epoch, valid_loss.data[0], valid_accuracy * 100))

    print('\rFinished Training\n')

    net.eval()

    test_predicts = _get_predict(net, X_test)
    test_loss = _get_loss(test_predicts, Y_test).data[0]
    test_accuracy = _get_accuracy(test_predicts, Y_test)
    print('Test loss: %.3f - Test accuracy: %.2f' % (test_loss, test_accuracy * 100))

    torch.save(net.flat_layer.state_dict(), save_path)

def _get_accuracy(predicts, labels):
    predicts = torch.max(predicts, 1)[1].data[0]
    return np.mean(predicts == labels)

def _get_predict(net, x):
    # wrap them in Variable
    inputs = torch.from_numpy(x).float()
    # convert to cuda tensors if cuda flag is true
    if torch.cuda.is_available:
        inputs = inputs.cuda()
    inputs = Variable(inputs)
    return net(inputs)

def _get_loss(predicts, labels):
    labels = torch.from_numpy(labels).long()
    # convert to cuda tensors if cuda flag is true
    if torch.cuda.is_available:
        labels = labels.cuda()
    labels = Variable(labels)
    return F.cross_entropy(predicts, labels)

It seems that parameters 're just updated slightly each epoch, the accuracy remains for all the process. While with the same implementation and the same params in Tensorflow, it runs correctly.

I'm new to Pytorch, so maybe my instructions has something wrong, please help me to find out. Thank you!

P.s: I try to use F.nll_loss + F.log_softmax instead of F.cross_entropy. Theoretically, it should return the same, but in fact another result is printed out (but it still be a wrong loss value)


来源: stackexchange

问:
Not able to login to Debian 8 GCP VM
Can anyone please help me with this? I'm not able to access a Debian 8 GCP VM via SSH and also the serial console. That VM had an additional disk and after restart I'm not able to SSH. I even tried to connect to it via serial port and it showed me the below message.</p>
```<code>You are in emerg
Cannot open access to console, the root account is locked.
See sulogin(8) man page for more details
</code>```

答:
You cannot recover the virtual machine - just the data.

Create a new instance. Detach the disk(s) and attach to the new instance. Copy your data to the new instance. Optionally delete the old instance and disks.

ContentLicense: CC BY-SA 4.0

Title: Not able to login to Debian 8 GCP VM

Body:
Can anyone please help me with this? I'm not able to access a Debian 8 GCP VM via SSH and also the serial console. That VM had an additional disk and after restart I'm not able to SSH. I even tried to connect to it via serial port and it showed me the below message.

You are in emerg
Cannot open access to console, the root account is locked.
See sulogin(8) man page for more details


问:
Consuming a Kafka Topic from Salesforce
We have a microservice architecture and we want to publish events into Kafka topics to then be consumed by Salesforce. What is the best approach to do this ? Is there any example Apex code that do that ?

Best Regards.

答:
Please note that most Salesforce Kafka connectors are using the Salesforce Streaming API for which following limits apply and might be very limiting:

https://developer.salesforce.com/docs/atlas.en-us.188.0.api_streaming.meta/api_streaming/limits.htm

Title: Consuming a Kafka Topic from Salesforce


问:
How to add a unique tag to each log in logging.properties
My standard configuration of Tomcat 8.5 splits the logs into

Catalina,

manager,

localhost ,

host-manager

My task is to add to each file unique tags:
CatalinaTag, mngTag, localTag, hostMngTag

I tried to find a solution on the internet but without any success.

My propse of logging.properties look like this:

```<code>handlers = 1catalina.mypackage.CatalinaConsoleHandler, 2localhost.mypackage.LocalhostConsoleHandler, 3manager.mypackage.ManagerConsoleHandler, 4host-manager.mypackage.LocalhostConsoleHandler, java.util.logging.ConsoleHandler
.handlers = 1catalina.mypackage.CatalinaConsoleHandler, java.util.logging.ConsoleHandler

1catalina.mypackage.CatalinaConsoleHandler.directory = /.../logs
1catalina.mypackage.CatalinaConsoleHandler.prefix = catalina.
1catalina.mypackage.CatalinaConsoleHandler.formatter = mypackage.CatalinaFormatter
mypackage.CatalinaFormatter.format = [CatalinaTag %1$tF %1$tT] [%4$-7s] %5$s %n

2localhost.mypackage.LocalhostConsoleHandler.directory = /.../logs
2localhost.mypackage.LocalhostConsoleHandler.prefix = localhost.
2localhost.mypackage.LocalhostConsoleHandler.formatter =mypackage.LocalhostFormatter
mypackage.LocalhostFormatter.format = [localhostTag %1$tF %1$tT] [%4$-7s] %5$s %n

3manager.mypackage.ManagerConsoleHandler.directory = /.../logs
3manager.mypackage.ManagerConsoleHandler.prefix = manager.
3manager.mypackage.ManagerConsoleHandler.formatter =mypackage.ManagerFormatter
mypackage.ManagerFormatter.format = [manager %1$tF %1$tT] [%4$-7s] %5$s %n

4host-manager.mypackage.LocalhostConsoleHandler.directory = /.../logs
4host-manager.mypackage.LocalhostConsoleHandler.prefix = host-manager.
4host-manager.mypackage.LocalhostConsoleHandler.formatter =mypackage.HostManagerFormatter
mypackage.HostManagerFormatter.format = [manager %1$tF %1$tT] [%4$-7s] %5$s %n

############################################################
# Facility specific properties.
# Provides extra control for each logger.
############################################################

org.apache.catalina.core.ContainerBase.[Catalina].[localhost].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].[localhost].handlers = 2localhost.mypackage.LocalhostConsoleHandler

org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/manager].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/manager].handlers = 3manager.mypackage.ManagerConsoleHandler

org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/host-manager].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/host-manager].handlers = 4host-manager.mypackage.LocalhostConsoleHandler
</code>```

Here is an example of *ConsoleHandler

```<code>package mypackage;

import java.util.logging.ConsoleHandler;

public class CatalinaConsoleHandler extends ConsoleHandler {
}
</code>```

Here an example of *Formatter

```<code>package mypackage;

import java.util.logging.SimpleFormatter;

public class CatalinaFormatter extends SimpleFormatter {
}
</code>```

But so far I am not able to do it. Do you have any idea why?

Thank you for any help!

答:
If you were using the original java.util.logging, your approach of subclassing ConsoleHandler (or rather FileHandler) and SimpleFormatter multiple times would be the correct one: JUL allows only one instance of every Handler and Formatter class. This approach will work, but you need to add mypackage.CatalinaConsoleHandler and company to the system classloader (cf. Tomcat classloaders).

However there is a much easier approach: Tomcat has its own extensions to JUL (cf. documentation), which allow you to:

add a prefix to each handler name and create multiple handlers of the same class. The prefix must start with a digit (e.g. 1catalina.). Prefixed properties apply only to the specific handler, while non-prefixed properties apply to all handlers.

use property placeholders ${...} which will be replaced with the appropriate Java system property. There are also three special properties (classloader.serverName, classloader.hostName and classloader.webappName) that resolve the name of the engine, host and context respectively.

Therefore you can use:

```<code># List of all handler names:
handlers = 1catalina.org.apache.juli.AsyncFileHandler, 2localhost.org.apache.juli.AsyncFileHandler
# Handlers attached to the root logger:
.handlers = 1catalina.org.apache.juli.AsyncFileHandler

# These properties apply to all handlers
org.apache.juli.AsyncFileHandler.directory = ${catalina.base}/logs
org.apache.juli.AsyncFileHandler.formatter = java.util.logging.SimpleFormatter

# These properties apply only to `1catalina.org.apache.juli.AsyncFileHandler`
1catalina.org.apache.juli.AsyncFileHandler.prefix = catalina.
1catalina.java.util.logging.SimpleFormatter.format = [CatalinaTag %1$tF %1$tT] [%4$-7s] %5$s %n

# These properties apply only to `2localhost.org.apache.juli.AsyncFileHandler`
2localhost.org.apache.juli.AsyncFileHandler.prefix = localhost.
2localhost.java.util.logging.SimpleFormatter.format = [LocalhostTag %1$tF %1$tT] [%4$-7s] %5$s %n
</code>```

Body:
My standard configuration of Tomcat 8.5 splits the logs into

Catalina,

manager,

localhost ,

host-manager

My task is to add to each file unique tags:
CatalinaTag, mngTag, localTag, hostMngTag

I tried to find a solution on the internet but without any success.

My propse of logging.properties look like this:

handlers = 1catalina.mypackage.CatalinaConsoleHandler, 2localhost.mypackage.LocalhostConsoleHandler, 3manager.mypackage.ManagerConsoleHandler, 4host-manager.mypackage.LocalhostConsoleHandler, java.util.logging.ConsoleHandler
.handlers = 1catalina.mypackage.CatalinaConsoleHandler, java.util.logging.ConsoleHandler

1catalina.mypackage.CatalinaConsoleHandler.directory = /.../logs
1catalina.mypackage.CatalinaConsoleHandler.prefix = catalina.
1catalina.mypackage.CatalinaConsoleHandler.formatter = mypackage.CatalinaFormatter
mypackage.CatalinaFormatter.format = [CatalinaTag %1$tF %1$tT] [%4$-7s] %5$s %n

2localhost.mypackage.LocalhostConsoleHandler.directory = /.../logs
2localhost.mypackage.LocalhostConsoleHandler.prefix = localhost.
2localhost.mypackage.LocalhostConsoleHandler.formatter =mypackage.LocalhostFormatter
mypackage.LocalhostFormatter.format = [localhostTag %1$tF %1$tT] [%4$-7s] %5$s %n

3manager.mypackage.ManagerConsoleHandler.directory = /.../logs
3manager.mypackage.ManagerConsoleHandler.prefix = manager.
3manager.mypackage.ManagerConsoleHandler.formatter =mypackage.ManagerFormatter
mypackage.ManagerFormatter.format = [manager %1$tF %1$tT] [%4$-7s] %5$s %n

4host-manager.mypackage.LocalhostConsoleHandler.directory = /.../logs
4host-manager.mypackage.LocalhostConsoleHandler.prefix = host-manager.
4host-manager.mypackage.LocalhostConsoleHandler.formatter =mypackage.HostManagerFormatter
mypackage.HostManagerFormatter.format = [manager %1$tF %1$tT] [%4$-7s] %5$s %n

############################################################
# Facility specific properties.
# Provides extra control for each logger.
############################################################

org.apache.catalina.core.ContainerBase.[Catalina].[localhost].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].[localhost].handlers = 2localhost.mypackage.LocalhostConsoleHandler

org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/manager].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/manager].handlers = 3manager.mypackage.ManagerConsoleHandler

org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/host-manager].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/host-manager].handlers = 4host-manager.mypackage.LocalhostConsoleHandler

Here is an example of *ConsoleHandler

package mypackage;

import java.util.logging.ConsoleHandler;

public class CatalinaConsoleHandler extends ConsoleHandler {
}

Here an example of *Formatter

package mypackage;

import java.util.logging.SimpleFormatter;

public class CatalinaFormatter extends SimpleFormatter {
}

But so far I am not able to do it. Do you have any idea why?

Thank you for any help!

Body:
If you were using the original java.util.logging, your approach of subclassing ConsoleHandler (or rather FileHandler) and SimpleFormatter multiple times would be the correct one: JUL allows only one instance of every Handler and Formatter class. This approach will work, but you need to add mypackage.CatalinaConsoleHandler and company to the system classloader (cf. Tomcat classloaders).

However there is a much easier approach: Tomcat has its own extensions to JUL (cf. documentation), which allow you to:

add a prefix to each handler name and create multiple handlers of the same class. The prefix must start with a digit (e.g. 1catalina.). Prefixed properties apply only to the specific handler, while non-prefixed properties apply to all handlers.

use property placeholders ${...} which will be replaced with the appropriate Java system property. There are also three special properties (classloader.serverName, classloader.hostName and classloader.webappName) that resolve the name of the engine, host and context respectively.

Therefore you can use:

# List of all handler names:
handlers = 1catalina.org.apache.juli.AsyncFileHandler, 2localhost.org.apache.juli.AsyncFileHandler
# Handlers attached to the root logger:
.handlers = 1catalina.org.apache.juli.AsyncFileHandler

# These properties apply to all handlers
org.apache.juli.AsyncFileHandler.directory = ${catalina.base}/logs
org.apache.juli.AsyncFileHandler.formatter = java.util.logging.SimpleFormatter

# These properties apply only to `1catalina.org.apache.juli.AsyncFileHandler`
1catalina.org.apache.juli.AsyncFileHandler.prefix = catalina.
1catalina.java.util.logging.SimpleFormatter.format = [CatalinaTag %1$tF %1$tT] [%4$-7s] %5$s %n

# These properties apply only to `2localhost.org.apache.juli.AsyncFileHandler`
2localhost.org.apache.juli.AsyncFileHandler.prefix = localhost.
2localhost.java.util.logging.SimpleFormatter.format = [LocalhostTag %1$tF %1$tT] [%4$-7s] %5$s %n


问:
running a batch file from C#
UPDATE
** STILL LOOKING FOR A CORRECT ANSWER **
I have the following code in my windows service and I want to run a batch file. I want the command prompt window up so I can see progress

here is my code but my batch file code doesnt work

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;

    namespace Watcher
    {
        public partial class Watcher : ServiceBase
        {
            public Watcher()
            {
                InitializeComponent();
            FolderWatcher.Created += FolderWatcher_Created;
            FolderWatcher.Deleted += FolderWatcher_Deleted;
            FolderWatcher.Renamed += FolderWatcher_Renamed;
            }

            protected override void OnStart(string[] args)
            {

                          // Start the child process.
            Process p = new Process();
            // Redirect the output stream of the child process.
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.FileName = "C:\\myFile.bat";
            p.Start();
            // Do not wait for the child process to exit before
            // reading to the end of its redirected stream.
            // p.WaitForExit();
            // Read the output stream first and then wait.
            string output = p.StandardOutput.ReadToEnd();
            p.WaitForExit();

            }

            protected override void OnStop()
            {
            }

            private void FolderWatcher_Created(object sender, System.IO.FileSystemEventArgs e)
            {
                TextWriter writer = new StreamWriter("C:\\folder\\FolderLog.txt", true);
                writer.WriteLine(DateTime.Now + " A new folder/file with name " + e.Name + " has been created. ");
                writer.Close();
            }

            private void FolderWatcher_Deleted(object sender, System.IO.FileSystemEventArgs e)
            {
                TextWriter writer = new StreamWriter("C:\\folder\\FolderLog.txt", true);
                writer.WriteLine(DateTime.Now + " A new folder/file with name " + e.Name + " has been deleted. ");
                writer.Close();
            }

            private void FolderWatcher_Renamed(object sender, System.IO.RenamedEventArgs e)
            {
                TextWriter writer = new StreamWriter("C:\\folder\\log.txt", true);
                writer.WriteLine(DateTime.Now + " A new folder/file with name " + e.Name + " has been renamed. ");
                writer.Close();
            }

        }
    }
</code>```

It does not execute the batch file. I am a newbie in .net and C# and I am not sure what to do from here.
thanks

答: i am doubting your service or the bat file. modify the source code to open a notepad! check if notepad shows up!! if yes then we can investigate further! </p>

ContentLicense: CC BY-SA 3.0

Title: running a batch file from C#

Body:
UPDATE
** STILL LOOKING FOR A CORRECT ANSWER **
I have the following code in my windows service and I want to run a batch file. I want the command prompt window up so I can see progress

here is my code but my batch file code doesnt work

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;

    namespace Watcher
    {
        public partial class Watcher : ServiceBase
        {
            public Watcher()
            {
                InitializeComponent();
            FolderWatcher.Created += FolderWatcher_Created;
            FolderWatcher.Deleted += FolderWatcher_Deleted;
            FolderWatcher.Renamed += FolderWatcher_Renamed;
            }

            protected override void OnStart(string[] args)
            {

                          // Start the child process.
            Process p = new Process();
            // Redirect the output stream of the child process.
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.FileName = "C:\\myFile.bat";
            p.Start();
            // Do not wait for the child process to exit before
            // reading to the end of its redirected stream.
            // p.WaitForExit();
            // Read the output stream first and then wait.
            string output = p.StandardOutput.ReadToEnd();
            p.WaitForExit();

            }

            protected override void OnStop()
            {
            }

            private void FolderWatcher_Created(object sender, System.IO.FileSystemEventArgs e)
            {
                TextWriter writer = new StreamWriter("C:\\folder\\FolderLog.txt", true);
                writer.WriteLine(DateTime.Now + " A new folder/file with name " + e.Name + " has been created. ");
                writer.Close();
            }

            private void FolderWatcher_Deleted(object sender, System.IO.FileSystemEventArgs e)
            {
                TextWriter writer = new StreamWriter("C:\\folder\\FolderLog.txt", true);
                writer.WriteLine(DateTime.Now + " A new folder/file with name " + e.Name + " has been deleted. ");
                writer.Close();
            }

            private void FolderWatcher_Renamed(object sender, System.IO.RenamedEventArgs e)
            {
                TextWriter writer = new StreamWriter("C:\\folder\\log.txt", true);
                writer.WriteLine(DateTime.Now + " A new folder/file with name " + e.Name + " has been renamed. ");
                writer.Close();
            }

        }
    }

It does not execute the batch file. I am a newbie in .net and C# and I am not sure what to do from here.
thanks


问:
How to find Records between startDate and endDate - Nodejs, mongodb
There are 4 records in my database.

```<code>{"_id":{"$oid":"6200b15e91f762376cd43ac3"},"startDate":{"$date":"2021-01-01T00:00:00.000Z"},"endDate":{"$date":"2021-01-28T18:29:59.059Z"},"__v":0}
{"_id":{"$oid":"6200b15e91f762376cd43ac4"},"startDate":{"$date":"2021-01-01T00:00:00.000Z"},"endDate":{"$date":"2021-01-23T18:29:59.059Z"},"__v":0}
{"_id":{"$oid":"6200b15e91f762376cd43ac5"},"startDate":{"$date":"2021-01-05T00:00:00.000Z"},"endDate":{"$date":"2021-01-28T18:29:59.059Z"},"__v":0}
{"_id":{"$oid":"6200b15e91f762376cd43ac6"},"startDate":{"$date":"2021-01-05T00:00:00.000Z"},"endDate":{"$date":"2021-01-25T18:29:59.059Z"},"__v":0}
</code>```

My UI looks like this:

My mongodb query is as follows: (what I have tried)

```<code>data.find({
                    "$or": [
                      {"startDate": {"$gte": startDate}},
                      {"endDate": {"$lte": endDate}}
                    ]
                  });
</code>```

When is search using the query above, I get only 1 record, That is: {"_id":{"$oid":"6200b15e91f762376cd43ac3"},"startDate":{"$date":"2021-01-01T00:00:00.000Z"},"endDate":{"$date":"2021-01-28T18:29:59.059Z"},"__v":0} instead of all 4.

While sending from UI, I convert it is:
req.query:

```<code>dateStart: '2021-01-01',
dateEnd: '2021-01-28',
</code>```

And then convert it to new Date() format:

```<code>let startDate = new Date(req.query.dateStart);
let endDate = new Date(req.query.dateEnd);
</code>```

I don't know what wrong I am going in the query. Need Help! Thank you!

答:
Since you are expecting all 4 records to be returned, for the end date you should be querying using the time before the date 2021-01-28 ends which is 2021-01-28T23:59:59.999Z instead of when the date starts which is 2021-01-28T00:00:00.000Z.

Here's a resource on timestamps format.

So a query like this would work:

```<code>db.collection.find({
  startDate: {
    $gte: {
      "$date": "2021-01-01T00:00:00.000Z"
    }
  },
  endDate: {
    $lte: {
      "$date": "2021-01-28T23:59:59.999Z"
    }
  }
})
</code>```

Body:
There are 4 records in my database.

{"_id":{"$oid":"6200b15e91f762376cd43ac3"},"startDate":{"$date":"2021-01-01T00:00:00.000Z"},"endDate":{"$date":"2021-01-28T18:29:59.059Z"},"__v":0}
{"_id":{"$oid":"6200b15e91f762376cd43ac4"},"startDate":{"$date":"2021-01-01T00:00:00.000Z"},"endDate":{"$date":"2021-01-23T18:29:59.059Z"},"__v":0}
{"_id":{"$oid":"6200b15e91f762376cd43ac5"},"startDate":{"$date":"2021-01-05T00:00:00.000Z"},"endDate":{"$date":"2021-01-28T18:29:59.059Z"},"__v":0}
{"_id":{"$oid":"6200b15e91f762376cd43ac6"},"startDate":{"$date":"2021-01-05T00:00:00.000Z"},"endDate":{"$date":"2021-01-25T18:29:59.059Z"},"__v":0}

My UI looks like this:

My mongodb query is as follows: (what I have tried)

data.find({
                    "$or": [
                      {"startDate": {"$gte": startDate}},
                      {"endDate": {"$lte": endDate}}
                    ]
                  });

When is search using the query above, I get only 1 record, That is: {"_id":{"$oid":"6200b15e91f762376cd43ac3"},"startDate":{"$date":"2021-01-01T00:00:00.000Z"},"endDate":{"$date":"2021-01-28T18:29:59.059Z"},"__v":0} instead of all 4.

While sending from UI, I convert it is:
req.query:

dateStart: '2021-01-01',
dateEnd: '2021-01-28',

And then convert it to new Date() format:

let startDate = new Date(req.query.dateStart);
let endDate = new Date(req.query.dateEnd);

I don't know what wrong I am going in the query. Need Help! Thank you!

Body:
Since you are expecting all 4 records to be returned, for the end date you should be querying using the time before the date 2021-01-28 ends which is 2021-01-28T23:59:59.999Z instead of when the date starts which is 2021-01-28T00:00:00.000Z.

Here's a resource on timestamps format.

So a query like this would work:

db.collection.find({
  startDate: {
    $gte: {
      "$date": "2021-01-01T00:00:00.000Z"
    }
  },
  endDate: {
    $lte: {
      "$date": "2021-01-28T23:59:59.999Z"
    }
  }
})


问:
Reduce time /space complexity of simple loop
So basically if i have an iteration like this in python
Ive editted the question to include my full code

```<code>class Solution:
    def myPow(self, x: float, n: int) -> float:
        temp = [];
        span = range(1,abs(n))
        if n ==0:
            return 1
        if abs(n)==1:
            temp.append(x)
        else:
            for y in span:
                if y == 1:
                    temp = []
                    temp.append(x*x)
                else:
                    temp.append(temp[-1] * x)
        if(n < 0):
            return 1/temp[-1]
        else:
            return temp[-1]
</code>```

The problem link is : Pow(x,n)-leetcode
How can I modify this to conserve memory and time. Is there another data structure i can use. Im just learning python....

------------EDIT------------
ive modified the code to use a variable instead of a list for the temp data

```<code>class Solution:
    def myPow(self, x: float, n: int) -> float:
        span = range(1,abs(n))
        if n ==0:
            return 1
        if abs(n)==1:
            temp = x
        else:
            for y in span:
                if y == 1:
                    temp = x*x
                else:
                    temp = temp * x
        if(n < 0):
            return 1/temp
        else:
            return temp
</code>```

I still have a problem with my time complexity.
Its working for many testcases, however when it trys to run with x = 0.00001 and n = 2147483647. The time limit issue arises

答:
Instead of iterating from 1 to n, use divide-and-conquer: divide the exponent by 2 and use recursion to get that power, and then square that result. If n was odd, multiply one time more with x:

```<code>class Solution:
    def myPow(self, x: float, n: int) -> float:
        if n == 0:
            return 1
        if n == 1:
            return x
        if n < 0:
            return self.myPow(1/x, -n)
        temp = self.myPow(x, n // 2)
        temp *= temp
        if n % 2:
            temp *= x
        return temp
</code>```

Body:
So basically if i have an iteration like this in python
Ive editted the question to include my full code

class Solution:
    def myPow(self, x: float, n: int) -> float:
        temp = [];
        span = range(1,abs(n))
        if n ==0:
            return 1
        if abs(n)==1:
            temp.append(x)
        else:
            for y in span:
                if y == 1:
                    temp = []
                    temp.append(x*x)
                else:
                    temp.append(temp[-1] * x)
        if(n < 0):
            return 1/temp[-1]
        else:
            return temp[-1]

The problem link is : Pow(x,n)-leetcode
How can I modify this to conserve memory and time. Is there another data structure i can use. Im just learning python....

------------EDIT------------
ive modified the code to use a variable instead of a list for the temp data

class Solution:
    def myPow(self, x: float, n: int) -> float:
        span = range(1,abs(n))
        if n ==0:
            return 1
        if abs(n)==1:
            temp = x
        else:
            for y in span:
                if y == 1:
                    temp = x*x
                else:
                    temp = temp * x
        if(n < 0):
            return 1/temp
        else:
            return temp

I still have a problem with my time complexity.
Its working for many testcases, however when it trys to run with x = 0.00001 and n = 2147483647. The time limit issue arises

Body:
Instead of iterating from 1 to n, use divide-and-conquer: divide the exponent by 2 and use recursion to get that power, and then square that result. If n was odd, multiply one time more with x:

class Solution:
    def myPow(self, x: float, n: int) -> float:
        if n == 0:
            return 1
        if n == 1:
            return x
        if n < 0:
            return self.myPow(1/x, -n)
        temp = self.myPow(x, n // 2)
        temp *= temp
        if n % 2:
            temp *= x
        return temp


问:
Bluetooth Programming in Raspberry Pi 4 using Bluez and dbus. Every thing is working good it just RPI is taking more than 90ms to receive 8 floats
I'm working on a project in which Rpi will receive 8 floats from Arduino nano ble. Arduino is working as peripheral device and sending 8 floats through Bluetooth. Arduino code is as shown bellow.

```<code>#include <Arduino_LSM9DS1.h>  // C:\Users\16312\Documents\Arduino\libraries\Arduino_LSM9DS1\src
#include <ArduinoBLE.h>
String localName = "testPeripheral";

#define BLE_UUID_SENSOR_DATA_SERVICE              "2BEEF31A-B10D-271C-C9EA-35D865C1F48A"
#define BLE_UUID_MULTI_SENSOR_DATA                "4664E7A1-5A13-BFFF-4636-7D0A4B16496C"

#define NUMBER_OF_SENSORS 8

union multi_sensor_data
{
  struct __attribute__( ( packed ) )
  {
    float values[NUMBER_OF_SENSORS];
  };
  uint8_t bytes[ NUMBER_OF_SENSORS * sizeof( float ) ];
};

union multi_sensor_data multiSensorData;

BLEService sensorDataService( BLE_UUID_SENSOR_DATA_SERVICE );
BLECharacteristic multiSensorDataCharacteristic( BLE_UUID_MULTI_SENSOR_DATA, BLERead | BLENotify, sizeof multiSensorData.bytes );

static long previousMillis = 0;
#define UPDATE_INTERVALL 50

float iter;
float dt;
void setup() {
  Serial.begin(9600);
  //while (!Serial);

  initBLE();

  if (!IMU.begin()) {
    Serial.println("Failed to initialize IMU!");
    while (1);
  }
  iter = 0;
}

void serial_print_xyz(float x, float y, float z) {
  int num_digits = 6;
  Serial.print(x, num_digits);  Serial.print('\t');
  Serial.print(y, num_digits);  Serial.print('\t');
  Serial.print(z, num_digits);  Serial.print('\t');
}

void serial_print_1(float val) {
  int num_digits = 6;
  Serial.print(val, num_digits);  Serial.print('\t');
}

void serial_print_1(int val) {
  Serial.print(val);  Serial.print('\t');
}

void serial_print_endln() {
  Serial.print("end");   Serial.println();
}

void loop() {
  //comment below line to remove serial print of master address

  dt = millis()-previousMillis;
  float acc_x, acc_y, acc_z;
  float mag_x, mag_y, mag_z;
  // Magnetic field seems to read at a slower rate than acceleration?
  if (IMU.accelerationAvailable() && IMU.magneticFieldAvailable()) {
    if ( millis() - previousMillis > UPDATE_INTERVALL )
    {
      previousMillis =  millis();
      // Read measurements
      IMU.readAcceleration(acc_x, acc_y, acc_z);
      IMU.readMagneticField(mag_x, mag_y, mag_z);
      iter++;
      // Export measurements
      checkCentralConnect();  //check if slave is connected to Master

      updateIMU(acc_x, acc_y, acc_z, mag_x, mag_y, mag_z);

      Serial.print("start\t");
      serial_print_1(iter);
      serial_print_1(dt);
      serial_print_xyz(acc_x, acc_y, acc_z);
      serial_print_xyz(mag_x, mag_y, mag_z);
      serial_print_endln();
    }
  }

}

void initBLE()
{
  // begin initialization
  if (!BLE.begin()) {
    Serial.println("starting BLE failed!");
  }

  // set advertised local name and service UUID:
  BLE.setDeviceName( "Arduino Nano 33 BLE" );
  BLE.setLocalName( "Arduino Nano 33 BLE" );
  BLE.setAdvertisedService( sensorDataService );

  // BLE add characteristics
  sensorDataService.addCharacteristic( multiSensorDataCharacteristic );

  // add service
  BLE.addService( sensorDataService );

  // set the initial value for the characeristic:
  multiSensorDataCharacteristic.writeValue( multiSensorData.bytes, sizeof multiSensorData.bytes );

  // start advertising
  BLE.advertise();

  String address = BLE.address();
  Serial.print("Local mac address is: ");
  Serial.println(address);
  Serial.println("LocalName: Arduino Nano 33 BLE");
}

void checkCentralConnect()
{
  // listen for BLE centrals to connect:
  BLEDevice central = BLE.central();

  // if a central is connected to peripheral print mac address
  if (central) {
    //Serial.print("Connected to central: ");
    // print the central's MAC address:
    //Serial.print(central.address());
  }
}

void updateIMU(float accX, float accY, float accZ, float magX, float magY, float magZ)
{

  multiSensorData.values[0]  = accX;
  multiSensorData.values[1]  = accY;
  multiSensorData.values[2]  = accZ;

  multiSensorData.values[3]  = magX;
  multiSensorData.values[4]  = magY;
  multiSensorData.values[5]  = magZ;
  multiSensorData.values[6]  = dt;
  multiSensorData.values[7]  = iter;

  multiSensorDataCharacteristic.writeValue( multiSensorData.bytes, sizeof multiSensorData.bytes );
}
</code>```

In this code you can see the Arduino is sending data on serial port also and out of this 8 floats 2 floats are iteration and execution time of one loop, so by examine serial output from Arduino i can tell how much time Arduino is taking to send data over Bluetooth. And what i found is Arduino is taking approx 50ms for a loop but in this 50 ms, IMU sensors are taking 48 to 49ms in each loop(if i remove code that is used to get values from IMU then execution time for a loop is 1ms only). Arduino is taking only 1ms to send data through Bluetooth. But on other hand the RPI is taking more than 90ms to receive this 8 floats from Arduino. I'm using BlueZ stack for Bluetooth communication in Linux and Python Dbus module to communicate with BlueZ using python. I attached Bluetooth scanner and data reader code bellow. When class is initializes it scans for devices and if found Arduino it will connect with it. after initialization is done code starts reading characteristics values. I'm using while loop to read values continuously but I'm not able to understand why RPI is taking more than 90ms just to read 8 float values(Check main loop code in the bottom part of python code). I'm very new to python and Dbus programming please help me figure out how can i increase the Bluetooth data transfer speed in RPI. If there is another method and I'm using wrong or old method please just provide a link to the documentation through which i can understand what is the issue.

```<code>#!/usr/bin/python3
from gi.repository import GLib
import bluetooth_utils
import bluetooth_constants
import dbus
import dbus.mainloop.glib
import sys
#import pydbus
import struct
from allDefData import defData

sys.path.insert(0, '.')

adapter_interface = None
mainloop = None
timer_id = None

devices = {}

class bleScan():

    def __init__(self, defD):
        # dbus initialisation steps
        self.defD = defD
        self.adapter_path = bluetooth_constants.BLUEZ_NAMESPACE + bluetooth_constants.ADAPTER_NAME
        self.ArdunoBleD = lambda: None
        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        self.bus = dbus.SystemBus()
        self.get_through_list_connected_devices()

        print(hasattr(self.ArdunoBleD, 'Name'))
        while(not hasattr(self.ArdunoBleD, 'Name')):
            print("Scanning")
            self.discover_devices(self.bus, 2000)
            if hasattr(self.ArdunoBleD, 'Name') and defD.ArdBleName in self.ArdunoBleD.Name:

                print("Scanning Stoped")
                break
            else:
                print("Not found Rescanning")
        char_proxy = self.bus.get_object(bluetooth_constants.BLUEZ_SERVICE_NAME, '/org/bluez/hci0/dev_1B_4E_C8_D6_CC_06/service000a/char000b')
        self.char_interface = dbus.Interface(char_proxy, bluetooth_constants.GATT_CHARACTERISTIC_INTERFACE)

    def Som(self, interfaces, path):

        if bluetooth_constants.GATT_SERVICE_INTERFACE in interfaces:
            properties = interfaces[bluetooth_constants.GATT_SERVICE_INTERFACE]
            print("-------------------------------------------------------------- ------------------")
            print("SVC path :", path)
            if 'UUID' in properties:
                uuid = properties['UUID']
            if uuid == bluetooth_constants.TEMPERATURE_SVC_UUID:
                found_ts = True
                ts_path = path
            print("SVC UUID : ", bluetooth_utils.dbus_to_python(uuid))
            print("SVC name : ", bluetooth_utils.get_name_from_uuid(uuid))
            return
        if bluetooth_constants.GATT_CHARACTERISTIC_INTERFACE in interfaces:
            properties = interfaces[bluetooth_constants.GATT_CHARACTERISTIC_INTERFACE]
            print(" CHR path :", path)
            if 'UUID' in properties:
                uuid = properties['UUID']
            if uuid == bluetooth_constants.TEMPERATURE_CHR_UUID:
                found_tc = True
            tc_path = path
            print(" CHR UUID : ", bluetooth_utils.dbus_to_python(uuid))
            print(" CHR name : ", bluetooth_utils.get_name_from_uuid(uuid))
            flags = ""
            for flag in properties['Flags']:
                flags = flags + flag + ","
            print(" CHR flags : ", flags)
            return
        if bluetooth_constants.GATT_DESCRIPTOR_INTERFACE in interfaces:
            properties =interfaces[bluetooth_constants.GATT_DESCRIPTOR_INTERFACE]
            print(" DSC path :", path)
            if 'UUID' in properties:
                uuid = properties['UUID']
            print(" DSC UUID : ", bluetooth_utils.dbus_to_python(uuid))
            print(" DSC name : ", bluetooth_utils.get_name_from_uuid(uuid))
            return

    def get_through_list_connected_devices(self):
        bus = self.bus
        proxy = bus.get_object(bluetooth_constants.BLUEZ_SERVICE_NAME, '/')
        interface = dbus.Interface(proxy, bluetooth_constants.DBUS_OM_IFACE)
        mngd_objs = interface.GetManagedObjects()
        for path, interfaces in mngd_objs.items():
            print(path)

            for ainterface in interfaces:
                print(ainterface)
                if ainterface == bluetooth_constants.DEVICE_INTERFACE:
                    device_properties = interfaces[bluetooth_constants.DEVICE_INTERFACE]
                    #if path not in devices:
                    devices[path] = device_properties
                    dev = devices[path]
                    try:
                        adr_name_Conn_inDev = ('Address' and 'Name' and 'Connected' in dev)
                        arduinoName_isCorrect = self.defD.ArdBleName in bluetooth_utils.dbus_to_python(dev['Name'])
                        isConnected = bluetooth_utils.dbus_to_python(device_properties['Connected'])

                    except:
                        adr_name_Conn_inDev = False
                        arduinoName_isCorrect = False
                        isConnected = False

                    if adr_name_Conn_inDev and arduinoName_isCorrect and isConnected:
                        self.ArdunoBleD.Name = bluetooth_utils.dbus_to_python(dev['Name'])
                        self.ArdunoBleD.Address = bluetooth_utils.dbus_to_python(dev['Address'])
                        #self.ArdunoBleD.RSSI = bluetooth_utils.dbus_to_python(dev['RSSI'])
                        self.ArdunoBleD.Path = path
                        self.Som(interfaces , path)
                        print("Found: Arduino Nano Ble in Connected Dev")
                    elif adr_name_Conn_inDev and arduinoName_isCorrect and not isConnected:
                        print("Not found in connected Devices")
                        print("Connecting...")
                        self.connect(path)
                        if self.isConnected(path):
                            self.ArdunoBleD.Name = bluetooth_utils.dbus_to_python(dev['Name'])
                            self.ArdunoBleD.Address = bluetooth_utils.dbus_to_python(dev['Address'])
                            # self.ArdunoBleD.RSSI = bluetooth_utils.dbus_to_python(dev['RSSI'])
                            self.ArdunoBleD.Path = path
                            self.Som(interfaces, path)

                    # if 'Address' in dev:
                    #     print("EXI bdaddr: ", bluetooth_utils.dbus_to_python(device_properties['Address']))
                    # if 'Name' in device_properties:
                    #     print("Name: ", bluetooth_utils.dbus_to_python(device_properties['Name']))
                    # if 'Connected' in device_properties:
                    #     print("Con: ", bluetooth_utils.dbus_to_python(device_properties['Connected']))

    def isConnected(self, device_path):
        bus = self.bus
        proxy = bus.get_object(bluetooth_constants.BLUEZ_SERVICE_NAME, device_path)
        interface = dbus.Interface(proxy, 'org.freedesktop.DBus.Properties')
        print("----------------")
        return interface.Get(bluetooth_constants.DEVICE_INTERFACE, 'Connected')

    def connect(self, device_path):
        bus = self.bus

        device_proxy = bus.get_object(bluetooth_constants.BLUEZ_SERVICE_NAME, device_path)
        device_interface = dbus.Interface(device_proxy, bluetooth_constants.DEVICE_INTERFACE)
        #p_interface = dbus.Interface(device_proxy, bluetooth_constants.DEVICE_INTERFACE)
        try:
            device_interface.Connect()
        except Exception as e:
            print("Failed to connect")
            print(e.get_dbus_name())
            print(e.get_dbus_message())
            if ("UnknownObject" in e.get_dbus_name()):
                print("Try scanning first to resolve this problem")
                return bluetooth_constants.RESULT_EXCEPTION
        else:
            print("Connected OK")
            return bluetooth_constants.RESULT_OK

    def interfaces_added(self, path, interfaces):
        # interfaces is an array of dictionary entries
        if not bluetooth_constants.DEVICE_INTERFACE in interfaces:
            return

        device_properties = interfaces[bluetooth_constants.DEVICE_INTERFACE]
        print(path)
        if path not in devices:
            print("NEW path :", path)
            devices[path] = device_properties
            dev = devices[path]

            if ('Address' and 'Name' and 'RSSI' in dev) and self.defD.ArdBleName in bluetooth_utils.dbus_to_python(
                    dev['Name']):

                self.connect(path)
                if self.isConnected(path):
                    self.ArdunoBleD.Name = bluetooth_utils.dbus_to_python(dev['Name'])
                    self.ArdunoBleD.Address = bluetooth_utils.dbus_to_python(dev['Address'])
                    self.ArdunoBleD.RSSI = bluetooth_utils.dbus_to_python(dev['RSSI'])
                    self.ArdunoBleD.Path = path
                    self.Som(interfaces, path)
                # self.ArdunoBleD.Name = bluetooth_utils.dbus_to_python(dev['Name'])
                # self.ArdunoBleD.Address = bluetooth_utils.dbus_to_python(dev['Address'])
                # self.ArdunoBleD.RSSI = bluetooth_utils.dbus_to_python(dev['RSSI'])
                # self.ArdunoBleD.Path = path
                print("Found: Arduino Nano Ble")

                self.discovery_timeout()
        print("------------------------------")

    def interfaces_removed(self, path, interfaces):

        # interfaces is an array of dictionary strings in this signal
        if not bluetooth_constants.DEVICE_INTERFACE in interfaces:
            return
        if path in devices:
            dev = devices[path]
        if 'Address' in dev:
            print("DEL bdaddr: ",
              bluetooth_utils.dbus_to_python(dev['Address']))
        else:
            print("DEL path : ", path)
        print("Rem",path)
        del devices[path]

    def discovery_timeout(self):
        global adapter_interface

        global mainloop
        global timer_id
        GLib.source_remove(timer_id)
        mainloop.quit()
        adapter_interface.StopDiscovery()
        bus = dbus.SystemBus()
        bus.remove_signal_receiver(self.interfaces_added, "InterfacesAdded")
        bus.remove_signal_receiver(self.interfaces_removed, "InterfacesRemoved")
        return True

    def read_temperature(self):

        char_interface = self.char_interface
        try:
            self.value = char_interface.ReadValue({})
        except Exception as e:
            print("Failed to read temperature")
            print(e.get_dbus_name())
            print(e.get_dbus_message())
            return bluetooth_constants.RESULT_EXCEPTION
        # else:
        #     self.temperature = bluetooth_utils.dbus_to_python(self.value[0])
        #     #print("Temperature=" + str(self.temperature ) + "C")
        #     return bluetooth_constants.RESULT_OK

    def discover_devices(self, bus, timeout):
        global adapter_interface
        global mainloop
        global timer_id

        # acquire an adapter proxy object and its Adapter1 interface so we can
        # call its methods
        adapter_object = bus.get_object(bluetooth_constants.BLUEZ_SERVICE_NAME, self.adapter_path)
        adapter_interface = dbus.Interface(adapter_object, bluetooth_constants.ADAPTER_INTERFACE)
        # register signal handler functions so we can asynchronously report
        # discovered devices
        # InterfacesAdded signal is emitted by BlueZ when an advertising packet
        # from a device it doesn't
        # already know about is received
        bus.add_signal_receiver(self.interfaces_added, dbus_interface=bluetooth_constants.DBUS_OM_IFACE,
                                signal_name="InterfacesAdded")
        bus.add_signal_receiver(self.interfaces_removed,
                                dbus_interface=bluetooth_constants.DBUS_OM_IFACE,
                                signal_name="InterfacesRemoved")

        mainloop = GLib.MainLoop()
        timer_id = GLib.timeout_add(timeout, self.discovery_timeout)
        adapter_interface.StartDiscovery(byte_arrays=True)
        mainloop.run()
import time
if __name__ == '__main__':

    defD = defData()
    Dev = bleScan(defD)

    while(True):
        if hasattr(Dev.ArdunoBleD, 'Name') and Dev.isConnected(Dev.ArdunoBleD.Path):
            time1 = time.time()
            Dev.read_temperature()
            print("hmm", Dev.value)
            s = struct.unpack('8f', bytearray(Dev.value))
            print(s)
            dt2 = time.time() - time1
            print(dt2)
        else:
            print("Er")

</code>```

Output of Arduino is as Bellow

```<code>start   309.000000  52.000000   0.033325    0.993530    -0.032715   0.329590    -1.257324   -1.013184   end
start   310.000000  50.000000   0.033569    0.993408    -0.034668   0.305176    -1.354980   -2.331543   end
</code>```

8 Numbers between start and end are the 8 floats which is Arduino is sending over Bluetooth and first float is iteration and second is the execution time of one loop in ms.

Output of Python code is as shown bellow.

```<code>hmm dbus.Array([dbus.Byte(0), dbus.Byte(0), dbus.Byte(234), dbus.Byte(60), dbus.Byte(0), dbus.Byte(56), dbus.Byte(126), dbus.Byte(63), dbus.Byte(0), dbus.Byte(128), dbus.Byte(101), dbus.Byte(189), dbus.Byte(0), dbus.Byte(128), dbus.Byte(59), dbus.Byte(62), dbus.Byte(0), dbus.Byte(32), dbus.Byte(25), dbus.Byte(191), dbus.Byte(0), dbus.Byte(224), dbus.Byte(43), dbus.Byte(191), dbus.Byte(0), dbus.Byte(0), dbus.Byte(72), dbus.Byte(66), dbus.Byte(0), dbus.Byte(104), dbus.Byte(178), dbus.Byte(69)], signature=dbus.Signature('y'))
(0.028564453125, 0.9930419921875, -0.0560302734375, 0.18310546875, -0.59814453125, -0.67138671875, 50.0, 5709.0)
0.09242081642150879
----------------

hmm dbus.Array([dbus.Byte(0), dbus.Byte(0), dbus.Byte(231), dbus.Byte(60), dbus.Byte(0), dbus.Byte(144), dbus.Byte(126), dbus.Byte(63), dbus.Byte(0), dbus.Byte(128), dbus.Byte(99), dbus.Byte(189), dbus.Byte(0), dbus.Byte(0), dbus.Byte(97), dbus.Byte(190), dbus.Byte(0), dbus.Byte(128), dbus.Byte(9), dbus.Byte(191), dbus.Byte(0), dbus.Byte(160), dbus.Byte(215), dbus.Byte(191), dbus.Byte(0), dbus.Byte(0), dbus.Byte(68), dbus.Byte(66), dbus.Byte(0), dbus.Byte(120), dbus.Byte(178), dbus.Byte(69)], signature=dbus.Signature('y'))
(0.0281982421875, 0.994384765625, -0.0555419921875, -0.2197265625, -0.537109375, -1.6845703125, 49.0, 5711.0)
0.092437744140625
----------------
</code>```

答:
To speed things up use Indications or Notifications on the RPi end. These are a way for a GATT Client to subscribe to data provided by a GATT Server. A Notification is an unacknowledged message or update while an Indication is an acknowledged message or update. As you are going to be updating so frequently it would seem sensible to go with notifications.
This would be done in the MainLoop rather than a While loop. This is covered in BlueZ GATT API https://git.kernel.org/pub/scm/bluetooth/bluez.git/tree/doc/gatt-api.txt#n181

This should be enough to get you the speed-up you are looking for. If you still need more then there is AcquireNotify.

BlueZ D-Bus goes through various OS layers when doing notifications which is known to slow the rate at which data can be updated. To overcome this, in later versions, BlueZ introduced AcquireNotify which opens a socket to bypass some of the layers to speed things up.

Body:
I'm working on a project in which Rpi will receive 8 floats from Arduino nano ble. Arduino is working as peripheral device and sending 8 floats through Bluetooth. Arduino code is as shown bellow.

#include <Arduino_LSM9DS1.h>  // C:\Users\16312\Documents\Arduino\libraries\Arduino_LSM9DS1\src
#include <ArduinoBLE.h>
String localName = "testPeripheral";

#define BLE_UUID_SENSOR_DATA_SERVICE              "2BEEF31A-B10D-271C-C9EA-35D865C1F48A"
#define BLE_UUID_MULTI_SENSOR_DATA                "4664E7A1-5A13-BFFF-4636-7D0A4B16496C"

#define NUMBER_OF_SENSORS 8

union multi_sensor_data
{
  struct __attribute__( ( packed ) )
  {
    float values[NUMBER_OF_SENSORS];
  };
  uint8_t bytes[ NUMBER_OF_SENSORS * sizeof( float ) ];
};

union multi_sensor_data multiSensorData;

BLEService sensorDataService( BLE_UUID_SENSOR_DATA_SERVICE );
BLECharacteristic multiSensorDataCharacteristic( BLE_UUID_MULTI_SENSOR_DATA, BLERead | BLENotify, sizeof multiSensorData.bytes );

static long previousMillis = 0;
#define UPDATE_INTERVALL 50

float iter;
float dt;
void setup() {
  Serial.begin(9600);
  //while (!Serial);

  initBLE();

  if (!IMU.begin()) {
    Serial.println("Failed to initialize IMU!");
    while (1);
  }
  iter = 0;
}

void serial_print_xyz(float x, float y, float z) {
  int num_digits = 6;
  Serial.print(x, num_digits);  Serial.print('\t');
  Serial.print(y, num_digits);  Serial.print('\t');
  Serial.print(z, num_digits);  Serial.print('\t');
}

void serial_print_1(float val) {
  int num_digits = 6;
  Serial.print(val, num_digits);  Serial.print('\t');
}

void serial_print_1(int val) {
  Serial.print(val);  Serial.print('\t');
}

void serial_print_endln() {
  Serial.print("end");   Serial.println();
}

void loop() {
  //comment below line to remove serial print of master address

  dt = millis()-previousMillis;
  float acc_x, acc_y, acc_z;
  float mag_x, mag_y, mag_z;
  // Magnetic field seems to read at a slower rate than acceleration?
  if (IMU.accelerationAvailable() && IMU.magneticFieldAvailable()) {
    if ( millis() - previousMillis > UPDATE_INTERVALL )
    {
      previousMillis =  millis();
      // Read measurements
      IMU.readAcceleration(acc_x, acc_y, acc_z);
      IMU.readMagneticField(mag_x, mag_y, mag_z);
      iter++;
      // Export measurements
      checkCentralConnect();  //check if slave is connected to Master

      updateIMU(acc_x, acc_y, acc_z, mag_x, mag_y, mag_z);

      Serial.print("start\t");
      serial_print_1(iter);
      serial_print_1(dt);
      serial_print_xyz(acc_x, acc_y, acc_z);
      serial_print_xyz(mag_x, mag_y, mag_z);
      serial_print_endln();
    }
  }

}

void initBLE()
{
  // begin initialization
  if (!BLE.begin()) {
    Serial.println("starting BLE failed!");
  }

  // set advertised local name and service UUID:
  BLE.setDeviceName( "Arduino Nano 33 BLE" );
  BLE.setLocalName( "Arduino Nano 33 BLE" );
  BLE.setAdvertisedService( sensorDataService );

  // BLE add characteristics
  sensorDataService.addCharacteristic( multiSensorDataCharacteristic );

  // add service
  BLE.addService( sensorDataService );

  // set the initial value for the characeristic:
  multiSensorDataCharacteristic.writeValue( multiSensorData.bytes, sizeof multiSensorData.bytes );

  // start advertising
  BLE.advertise();

  String address = BLE.address();
  Serial.print("Local mac address is: ");
  Serial.println(address);
  Serial.println("LocalName: Arduino Nano 33 BLE");
}

void checkCentralConnect()
{
  // listen for BLE centrals to connect:
  BLEDevice central = BLE.central();

  // if a central is connected to peripheral print mac address
  if (central) {
    //Serial.print("Connected to central: ");
    // print the central's MAC address:
    //Serial.print(central.address());
  }
}

void updateIMU(float accX, float accY, float accZ, float magX, float magY, float magZ)
{

  multiSensorData.values[0]  = accX;
  multiSensorData.values[1]  = accY;
  multiSensorData.values[2]  = accZ;

  multiSensorData.values[3]  = magX;
  multiSensorData.values[4]  = magY;
  multiSensorData.values[5]  = magZ;
  multiSensorData.values[6]  = dt;
  multiSensorData.values[7]  = iter;

  multiSensorDataCharacteristic.writeValue( multiSensorData.bytes, sizeof multiSensorData.bytes );
}

In this code you can see the Arduino is sending data on serial port also and out of this 8 floats 2 floats are iteration and execution time of one loop, so by examine serial output from Arduino i can tell how much time Arduino is taking to send data over Bluetooth. And what i found is Arduino is taking approx 50ms for a loop but in this 50 ms, IMU sensors are taking 48 to 49ms in each loop(if i remove code that is used to get values from IMU then execution time for a loop is 1ms only). Arduino is taking only 1ms to send data through Bluetooth. But on other hand the RPI is taking more than 90ms to receive this 8 floats from Arduino. I'm using BlueZ stack for Bluetooth communication in Linux and Python Dbus module to communicate with BlueZ using python. I attached Bluetooth scanner and data reader code bellow. When class is initializes it scans for devices and if found Arduino it will connect with it. after initialization is done code starts reading characteristics values. I'm using while loop to read values continuously but I'm not able to understand why RPI is taking more than 90ms just to read 8 float values(Check main loop code in the bottom part of python code). I'm very new to python and Dbus programming please help me figure out how can i increase the Bluetooth data transfer speed in RPI. If there is another method and I'm using wrong or old method please just provide a link to the documentation through which i can understand what is the issue.

#!/usr/bin/python3
from gi.repository import GLib
import bluetooth_utils
import bluetooth_constants
import dbus
import dbus.mainloop.glib
import sys
#import pydbus
import struct
from allDefData import defData

sys.path.insert(0, '.')

adapter_interface = None
mainloop = None
timer_id = None

devices = {}

class bleScan():

    def __init__(self, defD):
        # dbus initialisation steps
        self.defD = defD
        self.adapter_path = bluetooth_constants.BLUEZ_NAMESPACE + bluetooth_constants.ADAPTER_NAME
        self.ArdunoBleD = lambda: None
        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        self.bus = dbus.SystemBus()
        self.get_through_list_connected_devices()

        print(hasattr(self.ArdunoBleD, 'Name'))
        while(not hasattr(self.ArdunoBleD, 'Name')):
            print("Scanning")
            self.discover_devices(self.bus, 2000)
            if hasattr(self.ArdunoBleD, 'Name') and defD.ArdBleName in self.ArdunoBleD.Name:

                print("Scanning Stoped")
                break
            else:
                print("Not found Rescanning")
        char_proxy = self.bus.get_object(bluetooth_constants.BLUEZ_SERVICE_NAME, '/org/bluez/hci0/dev_1B_4E_C8_D6_CC_06/service000a/char000b')
        self.char_interface = dbus.Interface(char_proxy, bluetooth_constants.GATT_CHARACTERISTIC_INTERFACE)

    def Som(self, interfaces, path):

        if bluetooth_constants.GATT_SERVICE_INTERFACE in interfaces:
            properties = interfaces[bluetooth_constants.GATT_SERVICE_INTERFACE]
            print("-------------------------------------------------------------- ------------------")
            print("SVC path :", path)
            if 'UUID' in properties:
                uuid = properties['UUID']
            if uuid == bluetooth_constants.TEMPERATURE_SVC_UUID:
                found_ts = True
                ts_path = path
            print("SVC UUID : ", bluetooth_utils.dbus_to_python(uuid))
            print("SVC name : ", bluetooth_utils.get_name_from_uuid(uuid))
            return
        if bluetooth_constants.GATT_CHARACTERISTIC_INTERFACE in interfaces:
            properties = interfaces[bluetooth_constants.GATT_CHARACTERISTIC_INTERFACE]
            print(" CHR path :", path)
            if 'UUID' in properties:
                uuid = properties['UUID']
            if uuid == bluetooth_constants.TEMPERATURE_CHR_UUID:
                found_tc = True
            tc_path = path
            print(" CHR UUID : ", bluetooth_utils.dbus_to_python(uuid))
            print(" CHR name : ", bluetooth_utils.get_name_from_uuid(uuid))
            flags = ""
            for flag in properties['Flags']:
                flags = flags + flag + ","
            print(" CHR flags : ", flags)
            return
        if bluetooth_constants.GATT_DESCRIPTOR_INTERFACE in interfaces:
            properties =interfaces[bluetooth_constants.GATT_DESCRIPTOR_INTERFACE]
            print(" DSC path :", path)
            if 'UUID' in properties:
                uuid = properties['UUID']
            print(" DSC UUID : ", bluetooth_utils.dbus_to_python(uuid))
            print(" DSC name : ", bluetooth_utils.get_name_from_uuid(uuid))
            return

    def get_through_list_connected_devices(self):
        bus = self.bus
        proxy = bus.get_object(bluetooth_constants.BLUEZ_SERVICE_NAME, '/')
        interface = dbus.Interface(proxy, bluetooth_constants.DBUS_OM_IFACE)
        mngd_objs = interface.GetManagedObjects()
        for path, interfaces in mngd_objs.items():
            print(path)

            for ainterface in interfaces:
                print(ainterface)
                if ainterface == bluetooth_constants.DEVICE_INTERFACE:
                    device_properties = interfaces[bluetooth_constants.DEVICE_INTERFACE]
                    #if path not in devices:
                    devices[path] = device_properties
                    dev = devices[path]
                    try:
                        adr_name_Conn_inDev = ('Address' and 'Name' and 'Connected' in dev)
                        arduinoName_isCorrect = self.defD.ArdBleName in bluetooth_utils.dbus_to_python(dev['Name'])
                        isConnected = bluetooth_utils.dbus_to_python(device_properties['Connected'])

                    except:
                        adr_name_Conn_inDev = False
                        arduinoName_isCorrect = False
                        isConnected = False

                    if adr_name_Conn_inDev and arduinoName_isCorrect and isConnected:
                        self.ArdunoBleD.Name = bluetooth_utils.dbus_to_python(dev['Name'])
                        self.ArdunoBleD.Address = bluetooth_utils.dbus_to_python(dev['Address'])
                        #self.ArdunoBleD.RSSI = bluetooth_utils.dbus_to_python(dev['RSSI'])
                        self.ArdunoBleD.Path = path
                        self.Som(interfaces , path)
                        print("Found: Arduino Nano Ble in Connected Dev")
                    elif adr_name_Conn_inDev and arduinoName_isCorrect and not isConnected:
                        print("Not found in connected Devices")
                        print("Connecting...")
                        self.connect(path)
                        if self.isConnected(path):
                            self.ArdunoBleD.Name = bluetooth_utils.dbus_to_python(dev['Name'])
                            self.ArdunoBleD.Address = bluetooth_utils.dbus_to_python(dev['Address'])
                            # self.ArdunoBleD.RSSI = bluetooth_utils.dbus_to_python(dev['RSSI'])
                            self.ArdunoBleD.Path = path
                            self.Som(interfaces, path)

                    # if 'Address' in dev:
                    #     print("EXI bdaddr: ", bluetooth_utils.dbus_to_python(device_properties['Address']))
                    # if 'Name' in device_properties:
                    #     print("Name: ", bluetooth_utils.dbus_to_python(device_properties['Name']))
                    # if 'Connected' in device_properties:
                    #     print("Con: ", bluetooth_utils.dbus_to_python(device_properties['Connected']))

    def isConnected(self, device_path):
        bus = self.bus
        proxy = bus.get_object(bluetooth_constants.BLUEZ_SERVICE_NAME, device_path)
        interface = dbus.Interface(proxy, 'org.freedesktop.DBus.Properties')
        print("----------------")
        return interface.Get(bluetooth_constants.DEVICE_INTERFACE, 'Connected')

    def connect(self, device_path):
        bus = self.bus

        device_proxy = bus.get_object(bluetooth_constants.BLUEZ_SERVICE_NAME, device_path)
        device_interface = dbus.Interface(device_proxy, bluetooth_constants.DEVICE_INTERFACE)
        #p_interface = dbus.Interface(device_proxy, bluetooth_constants.DEVICE_INTERFACE)
        try:
            device_interface.Connect()
        except Exception as e:
            print("Failed to connect")
            print(e.get_dbus_name())
            print(e.get_dbus_message())
            if ("UnknownObject" in e.get_dbus_name()):
                print("Try scanning first to resolve this problem")
                return bluetooth_constants.RESULT_EXCEPTION
        else:
            print("Connected OK")
            return bluetooth_constants.RESULT_OK

    def interfaces_added(self, path, interfaces):
        # interfaces is an array of dictionary entries
        if not bluetooth_constants.DEVICE_INTERFACE in interfaces:
            return

        device_properties = interfaces[bluetooth_constants.DEVICE_INTERFACE]
        print(path)
        if path not in devices:
            print("NEW path :", path)
            devices[path] = device_properties
            dev = devices[path]

            if ('Address' and 'Name' and 'RSSI' in dev) and self.defD.ArdBleName in bluetooth_utils.dbus_to_python(
                    dev['Name']):

                self.connect(path)
                if self.isConnected(path):
                    self.ArdunoBleD.Name = bluetooth_utils.dbus_to_python(dev['Name'])
                    self.ArdunoBleD.Address = bluetooth_utils.dbus_to_python(dev['Address'])
                    self.ArdunoBleD.RSSI = bluetooth_utils.dbus_to_python(dev['RSSI'])
                    self.ArdunoBleD.Path = path
                    self.Som(interfaces, path)
                # self.ArdunoBleD.Name = bluetooth_utils.dbus_to_python(dev['Name'])
                # self.ArdunoBleD.Address = bluetooth_utils.dbus_to_python(dev['Address'])
                # self.ArdunoBleD.RSSI = bluetooth_utils.dbus_to_python(dev['RSSI'])
                # self.ArdunoBleD.Path = path
                print("Found: Arduino Nano Ble")

                self.discovery_timeout()
        print("------------------------------")

    def interfaces_removed(self, path, interfaces):

        # interfaces is an array of dictionary strings in this signal
        if not bluetooth_constants.DEVICE_INTERFACE in interfaces:
            return
        if path in devices:
            dev = devices[path]
        if 'Address' in dev:
            print("DEL bdaddr: ",
              bluetooth_utils.dbus_to_python(dev['Address']))
        else:
            print("DEL path : ", path)
        print("Rem",path)
        del devices[path]

    def discovery_timeout(self):
        global adapter_interface

        global mainloop
        global timer_id
        GLib.source_remove(timer_id)
        mainloop.quit()
        adapter_interface.StopDiscovery()
        bus = dbus.SystemBus()
        bus.remove_signal_receiver(self.interfaces_added, "InterfacesAdded")
        bus.remove_signal_receiver(self.interfaces_removed, "InterfacesRemoved")
        return True

    def read_temperature(self):

        char_interface = self.char_interface
        try:
            self.value = char_interface.ReadValue({})
        except Exception as e:
            print("Failed to read temperature")
            print(e.get_dbus_name())
            print(e.get_dbus_message())
            return bluetooth_constants.RESULT_EXCEPTION
        # else:
        #     self.temperature = bluetooth_utils.dbus_to_python(self.value[0])
        #     #print("Temperature=" + str(self.temperature ) + "C")
        #     return bluetooth_constants.RESULT_OK

    def discover_devices(self, bus, timeout):
        global adapter_interface
        global mainloop
        global timer_id

        # acquire an adapter proxy object and its Adapter1 interface so we can
        # call its methods
        adapter_object = bus.get_object(bluetooth_constants.BLUEZ_SERVICE_NAME, self.adapter_path)
        adapter_interface = dbus.Interface(adapter_object, bluetooth_constants.ADAPTER_INTERFACE)
        # register signal handler functions so we can asynchronously report
        # discovered devices
        # InterfacesAdded signal is emitted by BlueZ when an advertising packet
        # from a device it doesn't
        # already know about is received
        bus.add_signal_receiver(self.interfaces_added, dbus_interface=bluetooth_constants.DBUS_OM_IFACE,
                                signal_name="InterfacesAdded")
        bus.add_signal_receiver(self.interfaces_removed,
                                dbus_interface=bluetooth_constants.DBUS_OM_IFACE,
                                signal_name="InterfacesRemoved")

        mainloop = GLib.MainLoop()
        timer_id = GLib.timeout_add(timeout, self.discovery_timeout)
        adapter_interface.StartDiscovery(byte_arrays=True)
        mainloop.run()
import time
if __name__ == '__main__':

    defD = defData()
    Dev = bleScan(defD)

    while(True):
        if hasattr(Dev.ArdunoBleD, 'Name') and Dev.isConnected(Dev.ArdunoBleD.Path):
            time1 = time.time()
            Dev.read_temperature()
            print("hmm", Dev.value)
            s = struct.unpack('8f', bytearray(Dev.value))
            print(s)
            dt2 = time.time() - time1
            print(dt2)
        else:
            print("Er")

Output of Arduino is as Bellow

start   309.000000  52.000000   0.033325    0.993530    -0.032715   0.329590    -1.257324   -1.013184   end
start   310.000000  50.000000   0.033569    0.993408    -0.034668   0.305176    -1.354980   -2.331543   end

8 Numbers between start and end are the 8 floats which is Arduino is sending over Bluetooth and first float is iteration and second is the execution time of one loop in ms.

Output of Python code is as shown bellow.

hmm dbus.Array([dbus.Byte(0), dbus.Byte(0), dbus.Byte(234), dbus.Byte(60), dbus.Byte(0), dbus.Byte(56), dbus.Byte(126), dbus.Byte(63), dbus.Byte(0), dbus.Byte(128), dbus.Byte(101), dbus.Byte(189), dbus.Byte(0), dbus.Byte(128), dbus.Byte(59), dbus.Byte(62), dbus.Byte(0), dbus.Byte(32), dbus.Byte(25), dbus.Byte(191), dbus.Byte(0), dbus.Byte(224), dbus.Byte(43), dbus.Byte(191), dbus.Byte(0), dbus.Byte(0), dbus.Byte(72), dbus.Byte(66), dbus.Byte(0), dbus.Byte(104), dbus.Byte(178), dbus.Byte(69)], signature=dbus.Signature('y'))
(0.028564453125, 0.9930419921875, -0.0560302734375, 0.18310546875, -0.59814453125, -0.67138671875, 50.0, 5709.0)
0.09242081642150879
----------------

hmm dbus.Array([dbus.Byte(0), dbus.Byte(0), dbus.Byte(231), dbus.Byte(60), dbus.Byte(0), dbus.Byte(144), dbus.Byte(126), dbus.Byte(63), dbus.Byte(0), dbus.Byte(128), dbus.Byte(99), dbus.Byte(189), dbus.Byte(0), dbus.Byte(0), dbus.Byte(97), dbus.Byte(190), dbus.Byte(0), dbus.Byte(128), dbus.Byte(9), dbus.Byte(191), dbus.Byte(0), dbus.Byte(160), dbus.Byte(215), dbus.Byte(191), dbus.Byte(0), dbus.Byte(0), dbus.Byte(68), dbus.Byte(66), dbus.Byte(0), dbus.Byte(120), dbus.Byte(178), dbus.Byte(69)], signature=dbus.Signature('y'))
(0.0281982421875, 0.994384765625, -0.0555419921875, -0.2197265625, -0.537109375, -1.6845703125, 49.0, 5711.0)
0.092437744140625
----------------


问:
Python Regex re.compile query
I'm trying to find get a list of required names from list of names using a regex query.

csv file:  FYI, I converted Countries from Capital to small letters

searchList:

```<code>['AU.LS1_james.aus',
'AU.LS1_scott.aus',
'AP.LS1_amanda.usa',
'AP.LS1_john.usa',
'LA.LS1_harsha.ind',
'LA.LS1_vardhan.ind',
'IECAU13_peter-tu.can',
'LONSA13_smith.gbp']
</code>```

Format of the searchList: [(region)(Category)]_[EmployeeName].[country]

(region)(Category) is concatenated.

I'm trying to get a list of each group like this,

```<code>[
['AU.LS1_james.aus', 'AU.LS1_scott.aus'],
['AP.LS1_amanda.usa', 'AP.LS1_john.usa'],
['LA.LS1_harsha.ind', 'LA.LS1_vardhan.ind']
]
</code>```

Using the following regex query: \<({region}).*\{country}\>

```<code>for region, country in regionCountry:
    query = f"\<({region}).*\{country}\>"
    r = re.compile(query)
    group = list(filter(r.match, searchList))
</code>```

I tried  re.search  as well, but the  group is always  None

FYI: I also tried this query in notepad++ find using regex functionality.
<img src="https://i.stack.imgur.com/r9xeT.png" alt="NOTEPAD++ query: <(AU.LS1).*.aus> " />

Can Anyone Tell where it's going wrong in my script.? Thank you

答:
I thank you all for trying to assist my question. This answer worked out well for my usage. For some reason python doesn't like \< and \>. so i just removed them and it worked fine. I didn't expect that there could be some limitations using re library.

Answer:
f({region}).*\{country}

Title: Python Regex re.compile query

Body:
I'm trying to find get a list of required names from list of names using a regex query.

csv file:  FYI, I converted Countries from Capital to small letters

searchList:

['AU.LS1_james.aus',
'AU.LS1_scott.aus',
'AP.LS1_amanda.usa',
'AP.LS1_john.usa',
'LA.LS1_harsha.ind',
'LA.LS1_vardhan.ind',
'IECAU13_peter-tu.can',
'LONSA13_smith.gbp']

Format of the searchList: [(region)(Category)]_[EmployeeName].[country]

(region)(Category) is concatenated.

I'm trying to get a list of each group like this,

[
['AU.LS1_james.aus', 'AU.LS1_scott.aus'],
['AP.LS1_amanda.usa', 'AP.LS1_john.usa'],
['LA.LS1_harsha.ind', 'LA.LS1_vardhan.ind']
]

Using the following regex query: \<({region}).*\{country}\>

for region, country in regionCountry:
    query = f"\<({region}).*\{country}\>"
    r = re.compile(query)
    group = list(filter(r.match, searchList))

I tried  re.search  as well, but the  group is always  None

FYI: I also tried this query in notepad++ find using regex functionality.
<img src="https://i.stack.imgur.com/r9xeT.png" alt="NOTEPAD++ query: <(AU.LS1).*.aus> " />

Can Anyone Tell where it's going wrong in my script.? Thank you


问:
With p5.js, how to use dates for line graph x-axis
I would like to plot stock prices over time, and my x-axis data is day-month-year.
I can re-format how the date is presented in Excel, but is there an 'easy' way to use this type of data in a p5.js line graph?
Thanks!</p>

答:
I'd recommend looking into grafica. Here is a nice example that uses it in a p5 sketch (not mine), I found this on Google, it was made by 'piecesofuk':

```<code>function setup() {
  createCanvas(400, 400);
        // Create a new plot and set its position on the screen
        points = [];
        seed = 100 * random();

        for (i = 0; i < 100; i++) {
            points[i] = new GPoint(i, 10 * noise(0.1 * i + seed));
        }
        plot = new GPlot(this);
        plot.setPos(0, 0);
        plot.setOuterDim(width, height);

        // Add the points
        plot.setPoints(points);

        // Set the plot title and the axis labels
        plot.setTitleText("A very simple example");
        plot.getXAxis().setAxisLabelText("x axis");
        plot.getYAxis().setAxisLabelText("y axis");

        // Draw it!
        plot.defaultDraw();
}

function draw() {
//  background(220);
}
</code>```

Results in this:

Body:
I'd recommend looking into grafica. Here is a nice example that uses it in a p5 sketch (not mine), I found this on Google, it was made by 'piecesofuk':

function setup() {
  createCanvas(400, 400);
        // Create a new plot and set its position on the screen
        points = [];
        seed = 100 * random();

        for (i = 0; i < 100; i++) {
            points[i] = new GPoint(i, 10 * noise(0.1 * i + seed));
        }
        plot = new GPlot(this);
        plot.setPos(0, 0);
        plot.setOuterDim(width, height);

        // Add the points
        plot.setPoints(points);

        // Set the plot title and the axis labels
        plot.setTitleText("A very simple example");
        plot.getXAxis().setAxisLabelText("x axis");
        plot.getYAxis().setAxisLabelText("y axis");

        // Draw it!
        plot.defaultDraw();
}

function draw() {
//  background(220);
}

Results in this:


问:
How to set up a specific seedvalue in gds.beta.node2vec.write?
I'm running node2vec in neo4j but when the algorithm runs again with the same parameters, the result changes. So, I read the configuration and I see that there is a seedvalue.
I tried to set the seedvalue in a specific number, but nothing changes..

https://github.com/aditya-grover/node2vec/issues/83

答:
If you check the documentation you can see that the randomSeed parameters is available. However, the results are still non-deterministic as per the docs:

Seed value used to generate the random walks, which are used as the
training set of the neural network. Note, that the generated
embeddings are still nondeterministic.


问:
How to convert XML schemas (XSD) with 'choice' to RAML/YAML
I would like to ask how to convert XML schemas (XSD) to RAML/YAML schemas especially if my xml schemas has attributes like 'choice'.

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema
 xmlns:xs="http://www.w3.org/2001/XMLSchema">
 <xs:element
 name="employee">
       <xs:complexType>
          <xs:sequence>
             <xs:element name="name" type="xs:string" />
             <xs:element name="department">
                <xs:complexType>
                   <xs:sequence>
                      <xs:element name="departmentname" type="xs:string" />
                      <xs:element name="address" type="xs:string" />
                   </xs:sequence>
                </xs:complexType>
             </xs:element>
             <xs:element name="experience">
                <xs:complexType>
                   <xs:choice>
                      <xs:element name="title" type="xs:string" />
                      <xs:element name="note" type="xs:string" minOccurs="0" />
                      <xs:element name="year" type="xs:positiveInteger" />
                      <xs:element name="grade" type="xs:decimal" />
                   </xs:choice>
                </xs:complexType>
             </xs:element>
          </xs:sequence>
          <xs:attribute name="employeeid" type="xs:string" use="required" />
       </xs:complexType>
   </xs:element>
</xs:schema>
```

答: For RAML you need to be familiar with both specifications and try to translate the definitions from the XML Schema into a RAML specification. Specifically for the choice you could probably translate it to a union type. There are some tools that attempt to perform the conversion automatically, however since both standards are different there may be mismatches and you need to be prepared to complete the translation by hand.


问:
Unable to use Environment.GetResourceString static method
```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            var x = Environment.GetResourceString("test"); //compile-time error
        }
    }
}
</code>```

The error is: 'System.Environment' does not contain a definition for 'GetResourceString'.

EDIT: OP has stated that he's using the Compact Framework, v3.5.

I dont get the picture, what's wrong with my code? Thanks!

答:
You cannot access Environment.GetResourceString, but if you need access to mscorlib's internal error message, define your own implementation of that.

```<code>using System;
using System.Globalization;
using System.Reflection;
using System.Resources;

static class EnvironmentEx
{
    // Mscorlib's resources.
    private static ResourceSet resources = null;

    // Gets mscorlib's internal error message.
    public static string GetResourceString(string name)
    {
        if (resources == null)
        {
            var assembly = Assembly.GetAssembly(typeof(object));
            var assemblyName = assembly.GetName().Name;
            var manager = new ResourceManager(assemblyName, assembly);
            resources = manager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
        }
        return resources.GetString(name ?? throw new ArgumentNullException(nameof(name)));
    }

    // Gets parametrized mscorlib's internal error message.
    public static string GetResourceString(string name, params object[] args)
    {
        return string.Format(GetResourceString(name), args);
    }

    static void Main()
    {
        string message = GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper", -1, 1);
        // message = "Argument must be between -1 and 1".
    }
}
</code>```

P. S. Here a list of all messages with their ID.

ContentLicense: CC BY-SA 2.5

Body:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            var x = Environment.GetResourceString("test"); //compile-time error
        }
    }
}

The error is: 'System.Environment' does not contain a definition for 'GetResourceString'.

EDIT: OP has stated that he's using the Compact Framework, v3.5.

I dont get the picture, what's wrong with my code? Thanks!

Body:
You cannot access Environment.GetResourceString, but if you need access to mscorlib's internal error message, define your own implementation of that.

using System;
using System.Globalization;
using System.Reflection;
using System.Resources;

static class EnvironmentEx
{
    // Mscorlib's resources.
    private static ResourceSet resources = null;

    // Gets mscorlib's internal error message.
    public static string GetResourceString(string name)
    {
        if (resources == null)
        {
            var assembly = Assembly.GetAssembly(typeof(object));
            var assemblyName = assembly.GetName().Name;
            var manager = new ResourceManager(assemblyName, assembly);
            resources = manager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
        }
        return resources.GetString(name ?? throw new ArgumentNullException(nameof(name)));
    }

    // Gets parametrized mscorlib's internal error message.
    public static string GetResourceString(string name, params object[] args)
    {
        return string.Format(GetResourceString(name), args);
    }

    static void Main()
    {
        string message = GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper", -1, 1);
        // message = "Argument must be between -1 and 1".
    }
}

P. S. Here a list of all messages with their ID.


问:
Remove file location from document print using Javascript
I am using Javascript to print a div contents it works fine but it also prints the file location on top-right position which gives an odd impression on the output. here i attached the snap of it.

Thanks.

答: Your browser controls this. There are no javascript functions to control this (and likely never will be due to potential for abuse)</p>


问:
Combine equivalent of RxSwift's bind(to:)
I'm an experienced RxSwift user, and had a good working MVVM structure in RxSwift. I'm new to Combine, but I can't for the love of God figure out how to do something similar in Combine. The biggest blocker is a bind(to:) equivalent in Combine. I don't know how to chain the result of 1 variable to another.

Here is what I would do in RxSwift:

```<code>protocol UseCase {
  func execute(id: Int) -> Single<CustomClass>
}

class DefaultUseCase: UseCase {
  func execute(id: Int) -> Single<CustomClass> {
    // Do network call and return in Single format
  }
}

class ViewModel {

  struct Input {
    let load = PublishRelay<Void>()
  }

  struct Output {
    let isButtonEnabled: Driver<Bool>
  }

  let disposeBag = DisposeBag()
  let input = Input()
  let output: Output

  init(id: Int, useCase: UseCase = DefaultUseCase()) {
    let isButtonEnabled = BehaviorRelay<Bool>(value: false)

    let action = Action<Void, CustomClass> { id in
      return useCase.execute(id: id)
    }

    self.output = Output(isButtonEnabled: isButtonEnabled.asDriver())

    input
      .load
      .bind(to: useCase.inputs)
      .disposed(by: disposeBag)

    action
      .elements
      .map { // map CustomClass to Bool }
      .bind(to: isButtonEnabled)
      .disposed(by: disposeBag)
  }
}
</code>```

The action class is from this framework: https://github.com/RxSwiftCommunity/Action

I cannot figure out how to do something similar in Combine, I've already read some tutorials, but it doesn't make sense to me. It looks like you need what feels like a thousand variables to just put through 1 value to your view/viewController with a viewModel.

I a seeking a piece of code that does exactly the same as the piece of RxSwift code above, but in Combine with some explanation.

答:
First, let's simplify your view model:

```<code>class ViewModel {

    struct Input {
        let load = PublishRelay<Void>()
    }

    struct Output {
        let isButtonEnabled: Driver<Bool>
    }

    let input = Input()
    let output: Output

    init(id: Int, useCase: UseCase = DefaultUseCase()) {
        let isButtonEnabled = input.load
            .flatMapLatest { [useCase] in
                useCase.execute(id: id)
                    .map { _ in /* map CustomClass to Bool */ true }
                    .catchAndReturn(false)
            }
            .asDriver(onErrorRecover: { _ in fatalError() })

        self.output = Output(isButtonEnabled: isButtonEnabled)
    }
}
</code>```

I'm not a fan of your Input struct here but I'm working with it...

Once you do that, it's easy to see how to translate it:

```<code>class ViewModelʹ {
    struct Input {
        let load = PassthroughSubject<Void, Never>()
    }
    struct Output {
        let isButtonEnabled: AnyPublisher<Bool, Never>
    }

    let input = Input()
    let output: Output

    init(id: Int, useCase: UseCase) {
        let isButtonEnabled = input.load
            .map { [useCase] in
                useCase.execute(id: id)
                    .map { _ in /* map CustomClass to Bool */ true }
                    .catch { _ in Just(false) }
            }
            .switchToLatest()
            .eraseToAnyPublisher()

        self.output = Output(isButtonEnabled: isButtonEnabled)
    }
}
</code>```

UPDATE IN RESPONSE TO COMMENTS

Here is how you would go about using the use case response for multiple outputs (This compiles in iOS 13):

```<code>class ViewModelʹ {
    struct Input {
        let load = PassthroughSubject<Void, Never>()
    }
    struct Output {
        let isButtonEnabled: AnyPublisher<Bool, Never>
        let somethingElse: AnyPublisher<String, Never>
    }

    let input = Input()
    let output: Output

    init(id: Int, useCase: UseCase) {
        let result = input.load
            .map { [useCase] in
                useCase.execute(id: id)
                    .catch { _ in Empty() }
            }
            .switchToLatest()
            .share()

        let isButtonEnabled = result
            .map { _ in /* map CustomClass to Bool */ true }
            .eraseToAnyPublisher()

        let somethingElse = result
            .map { _ in /* map CustomClass to String */ "" }
            .eraseToAnyPublisher()

        self.output = Output(
            isButtonEnabled: isButtonEnabled,
            somethingElse: somethingElse
        )
    }
}
</code>```

Of course, a lot depends on how you want to handle errors. The above swallows them, but you might want to expose them for yet another output.

All of this is turning into a general tutorial rather than answering a question though.

Body:
I'm an experienced RxSwift user, and had a good working MVVM structure in RxSwift. I'm new to Combine, but I can't for the love of God figure out how to do something similar in Combine. The biggest blocker is a bind(to:) equivalent in Combine. I don't know how to chain the result of 1 variable to another.

Here is what I would do in RxSwift:

protocol UseCase {
  func execute(id: Int) -> Single<CustomClass>
}

class DefaultUseCase: UseCase {
  func execute(id: Int) -> Single<CustomClass> {
    // Do network call and return in Single format
  }
}

class ViewModel {

  struct Input {
    let load = PublishRelay<Void>()
  }

  struct Output {
    let isButtonEnabled: Driver<Bool>
  }

  let disposeBag = DisposeBag()
  let input = Input()
  let output: Output

  init(id: Int, useCase: UseCase = DefaultUseCase()) {
    let isButtonEnabled = BehaviorRelay<Bool>(value: false)

    let action = Action<Void, CustomClass> { id in
      return useCase.execute(id: id)
    }

    self.output = Output(isButtonEnabled: isButtonEnabled.asDriver())

    input
      .load
      .bind(to: useCase.inputs)
      .disposed(by: disposeBag)

    action
      .elements
      .map { // map CustomClass to Bool }
      .bind(to: isButtonEnabled)
      .disposed(by: disposeBag)
  }
}

The action class is from this framework: https://github.com/RxSwiftCommunity/Action

I cannot figure out how to do something similar in Combine, I've already read some tutorials, but it doesn't make sense to me. It looks like you need what feels like a thousand variables to just put through 1 value to your view/viewController with a viewModel.

I a seeking a piece of code that does exactly the same as the piece of RxSwift code above, but in Combine with some explanation.

Body:
First, let's simplify your view model:

class ViewModel {

    struct Input {
        let load = PublishRelay<Void>()
    }

    struct Output {
        let isButtonEnabled: Driver<Bool>
    }

    let input = Input()
    let output: Output

    init(id: Int, useCase: UseCase = DefaultUseCase()) {
        let isButtonEnabled = input.load
            .flatMapLatest { [useCase] in
                useCase.execute(id: id)
                    .map { _ in /* map CustomClass to Bool */ true }
                    .catchAndReturn(false)
            }
            .asDriver(onErrorRecover: { _ in fatalError() })

        self.output = Output(isButtonEnabled: isButtonEnabled)
    }
}

I'm not a fan of your Input struct here but I'm working with it...

Once you do that, it's easy to see how to translate it:

class ViewModelʹ {
    struct Input {
        let load = PassthroughSubject<Void, Never>()
    }
    struct Output {
        let isButtonEnabled: AnyPublisher<Bool, Never>
    }

    let input = Input()
    let output: Output

    init(id: Int, useCase: UseCase) {
        let isButtonEnabled = input.load
            .map { [useCase] in
                useCase.execute(id: id)
                    .map { _ in /* map CustomClass to Bool */ true }
                    .catch { _ in Just(false) }
            }
            .switchToLatest()
            .eraseToAnyPublisher()

        self.output = Output(isButtonEnabled: isButtonEnabled)
    }
}

UPDATE IN RESPONSE TO COMMENTS

Here is how you would go about using the use case response for multiple outputs (This compiles in iOS 13):

class ViewModelʹ {
    struct Input {
        let load = PassthroughSubject<Void, Never>()
    }
    struct Output {
        let isButtonEnabled: AnyPublisher<Bool, Never>
        let somethingElse: AnyPublisher<String, Never>
    }

    let input = Input()
    let output: Output

    init(id: Int, useCase: UseCase) {
        let result = input.load
            .map { [useCase] in
                useCase.execute(id: id)
                    .catch { _ in Empty() }
            }
            .switchToLatest()
            .share()

        let isButtonEnabled = result
            .map { _ in /* map CustomClass to Bool */ true }
            .eraseToAnyPublisher()

        let somethingElse = result
            .map { _ in /* map CustomClass to String */ "" }
            .eraseToAnyPublisher()

        self.output = Output(
            isButtonEnabled: isButtonEnabled,
            somethingElse: somethingElse
        )
    }
}

Of course, a lot depends on how you want to handle errors. The above swallows them, but you might want to expose them for yet another output.

All of this is turning into a general tutorial rather than answering a question though.