问:
problem mooving woocommerce to another domain
I have a woocommerce website installed and work normally , I want to change the theme without make changes on the website so all still ( products , pages, ...etc) .
I want to copy the same website into another domain to do changes without stop my first website .

this what i have do :
1- copy all files from the old to new website.
2- import database frm the old .
3- past into the new domain all files
4- import the tables of the old database  to the new database
5- change the wp-config to work with the new database
6- change the domain into table : wp_options
and i launch the new domain : the first page is ok without errors
but when i enter to preview product i have error that page dosen't exist , and all other pages the same error . can any one help me ??? any ideas ?

答:
When moving a WordPress site a few things to make it easier.

Manually, zip up uploads/plugins/theme or if you have some crazy thing going on wp-content. Generally, nothing else needs to be moved. (this excludes things like robots.txt etc you may have to move)

After importing the DB you need to run a search and replace to swap out the domain. It is used in more places than you think.

Go to settings and re-save permalinks twice. - This fixes most issues with pages not loading/404.

There are plugins out there that make this easier.

Updraft - Don't need the paid version. Can setup new site then add files and import them.

All in One WP Migration - Haven't seen anything this doesn't move but can be slow and harder with large sites.


来源: stackexchange

问:
Module files don't return non-zero exit codes to bash if the module fails to load. How can you make a conditional in bash with that?
I'm new here, so I apologize in advance if I'm not following the protocol, but the message said to ask a new question. I had asked an earlier question: How can a bash script try to load one module file and if that fails, load another?, but it is not a duplicate of Bash conditional based on exit code of command as marked.

The reason is that the module load  does not return a non-zero exit code if it fails to load. These are the Environment Modules that I am trying to use.

For example,

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

if module load fake_module; then
    echo "Should never have gotten here"
else
    echo "This is what I should see."
fi
</code>```

results in

```<code>ModuleCmd_Load.c(213):ERROR:105: Unable to locate a modulefile for 'fake_module'
Should never have gotten here
</code>```

How can I attempt to load fake_module and if that fails attempt to do something else? This is specifically in a bash script. Thank you!

Edit: I want to be clear that I don't have the ability to modify the module files directly.

答:
Use the command output/error instead of its return value, and check for the keyword ERROR matches your output/error

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

RES=$( { module load fake_module; } 2>&1 )
if [[ "$RES" != *"ERROR"* ]]; then
    echo "Should never have gotten here"  # the command has no errors
else
    echo "This is what I should see."   # the command has an error
fi
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm new here, so I apologize in advance if I'm not following the protocol, but the message said to ask a new question. I had asked an earlier question: How can a bash script try to load one module file and if that fails, load another?, but it is not a duplicate of Bash conditional based on exit code of command as marked.

The reason is that the module load  does not return a non-zero exit code if it fails to load. These are the Environment Modules that I am trying to use.

For example,

#!/bin/bash

if module load fake_module; then
    echo "Should never have gotten here"
else
    echo "This is what I should see."
fi

results in

ModuleCmd_Load.c(213):ERROR:105: Unable to locate a modulefile for 'fake_module'
Should never have gotten here

How can I attempt to load fake_module and if that fails attempt to do something else? This is specifically in a bash script. Thank you!

Edit: I want to be clear that I don't have the ability to modify the module files directly.

Body:
Use the command output/error instead of its return value, and check for the keyword ERROR matches your output/error

#!/bin/bash

RES=$( { module load fake_module; } 2>&1 )
if [[ "$RES" != *"ERROR"* ]]; then
    echo "Should never have gotten here"  # the command has no errors
else
    echo "This is what I should see."   # the command has an error
fi


问:
How do I compare a raw time in Java?
For example suppose I have

```<code>String endTime = "16:30:45";
</code>```

How would I determine whether right now is before this time?

答:
Since Java has no builtin support for pure time values (just combined time/date values), you're probably better off implementing the comparison yourself. If the time is formatted as HH:mm:ss, this should do the trick:

```<code>boolean beforeNow =
    endTime.compareTo(
        new SimpleDateFormat("HH:mm:ss").format(new Date())) < 0;
</code>```

The code does not handle date changes. I am not sure if you want to treat 23:00 to be before or after 01:00, but the code consider both times to be on the same date, e.g. 23:00 is after 01:00.

ContentLicense: CC BY-SA 3.0

Title: How do I compare a raw time in Java?

Body:
For example suppose I have

String endTime = "16:30:45";

How would I determine whether right now is before this time?

Body:
Since Java has no builtin support for pure time values (just combined time/date values), you're probably better off implementing the comparison yourself. If the time is formatted as HH:mm:ss, this should do the trick:

boolean beforeNow =
    endTime.compareTo(
        new SimpleDateFormat("HH:mm:ss").format(new Date())) < 0;

The code does not handle date changes. I am not sure if you want to treat 23:00 to be before or after 01:00, but the code consider both times to be on the same date, e.g. 23:00 is after 01:00.


问:
How do I make a while loop to ask the user if they want to restart the program
I'm trying to create a text  to speech program that keeps looping until the user decides to quit; here's my code:</p>

```<code># IMPORT
import gtts as gTTS
import os

# TTS
myText = input("Enter your text: ")

language = 'en'

output = gTTS.gTTS(text=myText, lang=language, slow=False,)

output.save("output.mp3")

os.system("start output.mp3")

# Restart
restart = False
while restart == False:
    question = raw_input(input("Do you want to continue yes / no ? ")
if question = "yes"
    print(myText)
else:
    quit

</code>```

答:
I'm not sure if it is the code format in the question but I believe that the problem is in the identation of the if condition. Try this instead:</p>

```<code>while restart == False:
    question = raw_input(input("Do you want to continue yes / no ? ")
    if question == "yes"
        print(myText)
    else:
        restart=True
</code>```

Body:
I'm trying to create a text  to speech program that keeps looping until the user decides to quit; here's my code:

# IMPORT
import gtts as gTTS
import os

# TTS
myText = input("Enter your text: ")

language = 'en'

output = gTTS.gTTS(text=myText, lang=language, slow=False,)

output.save("output.mp3")

os.system("start output.mp3")

# Restart
restart = False
while restart == False:
    question = raw_input(input("Do you want to continue yes / no ? ")
if question = "yes"
    print(myText)
else:
    quit

Body:
I'm not sure if it is the code format in the question but I believe that the problem is in the identation of the if condition. Try this instead:

while restart == False:
    question = raw_input(input("Do you want to continue yes / no ? ")
    if question == "yes"
        print(myText)
    else:
        restart=True


问:
How to incrementally sample without replacement?
Python has my_sample = random.sample(range(100), 10) to randomly sample without replacement from [0, 100).

Suppose I have sampled n such numbers and now I want to sample one more without replacement (without including any of the previously sampled n), how to do so super efficiently?

update: changed from "reasonably efficiently" to "super efficiently" (but ignoring constant factors)

答:
It's surprising this is not already implemented in one of the core functions, but here is the clean version, that returns the sampled values and the list without replacement:

def sample_n_points_without_replacement(n, set_of_points):
    sampled_point_indices = random.sample(range(len(set_of_points)), n)
    sampled_point_indices.sort(reverse=True)
    sampled_points = [set_of_points[sampled_point_index] for sampled_point_index in sampled_point_indices]
    for sampled_point_index in sampled_point_indices:
        del(set_of_points[sampled_point_index])
    return sampled_points, set_of_points
```


问:
Python pathing when building/using modules
(Using python ver 3.8)

So in a module I've made, I have this function:

```<code>#Auxillary function that returns True if plugin type is valid, else raise error
def checkTypeValid(pluginType):
    with open('PluginTypes.csv') as validTypes:
        reader = csv.reader(validTypes)
        for validType in reader:
            if validType[0] == pluginType:
                return(True)
        raise ValueError('Plugin Type %s does not exist' % pluginType)
</code>```

And when I run it it works fine.

However when I call this function from Neuron.py using: from Plugins import PluginManager, it gives the error 'No such file in directory'. I'm at a complete loss at what to do. Also am having issues importing from sibling folders, but I've just been working around that so far.

File structure:

答:
Well that will not work as Plugins is in a separate package unrelated to the NeuralNetwork package.

Each folder you have makes a package if it has a __init __.py file in in what that means is that you can then import that package from python.

For instance

```<code>Programs

|----- Package1
            file1.py
            __ init __.py
|------Package2
            file2.py
            __init __.py
</code>```

In this setup there are two independent packages which do not know of each other. Therefore you cannot import from Package1 from Package2 and vice versa. However if you change the structure to be like this, that is making Programs into a package by adding in __ init __.py

```<code>Programs

|----- Package1
            file1.py
            __ init __.py
|------Package2
            file2.py
            __init __.py
__init __.py
</code>```

so that now Programs is also a package and Package1 and Package2 are both within the same package, then from file1.py you can do the following

```<code>import Programs.Package2.file2
</code>```

The downside of doing this is that when importing, each file would contain references to the packages around it. That is, the packages do depend on each other and cannot work unless all packages are present.

However, if the packages are truly independent, one other method is to add the package you want to use in your sys.path by doing the following

```<code>import sys
sys.path.append("/path/to/my/package")
</code>```

I have tried this and I have the following file structure

mod1.py has the following code

```<code>from program.module2.mod2 import hello

hello()
</code>```

mod2.py has the following code

```<code>def hello():
    print("hello")
</code>```

main.py has the following code

```<code>from program.module1 import mod1
</code>```

from the command line, I go to one folder above program and I type in the following

```<code>PS C:\temp\example> ls

    Directory: C:\temp\example

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----        21/02/2020    15:10                .vs
d-----        21/02/2020    15:10                program

PS C:\temp\example> python -m program.main
hello
</code>```

Body:
(Using python ver 3.8)

So in a module I've made, I have this function:

#Auxillary function that returns True if plugin type is valid, else raise error
def checkTypeValid(pluginType):
    with open('PluginTypes.csv') as validTypes:
        reader = csv.reader(validTypes)
        for validType in reader:
            if validType[0] == pluginType:
                return(True)
        raise ValueError('Plugin Type %s does not exist' % pluginType)

And when I run it it works fine.

However when I call this function from Neuron.py using: from Plugins import PluginManager, it gives the error 'No such file in directory'. I'm at a complete loss at what to do. Also am having issues importing from sibling folders, but I've just been working around that so far.

File structure:

Body:
Well that will not work as Plugins is in a separate package unrelated to the NeuralNetwork package.

Each folder you have makes a package if it has a __init __.py file in in what that means is that you can then import that package from python.

For instance

Programs

|----- Package1
            file1.py
            __ init __.py
|------Package2
            file2.py
            __init __.py

In this setup there are two independent packages which do not know of each other. Therefore you cannot import from Package1 from Package2 and vice versa. However if you change the structure to be like this, that is making Programs into a package by adding in __ init __.py

Programs

|----- Package1
            file1.py
            __ init __.py
|------Package2
            file2.py
            __init __.py
__init __.py

so that now Programs is also a package and Package1 and Package2 are both within the same package, then from file1.py you can do the following

import Programs.Package2.file2

The downside of doing this is that when importing, each file would contain references to the packages around it. That is, the packages do depend on each other and cannot work unless all packages are present.

However, if the packages are truly independent, one other method is to add the package you want to use in your sys.path by doing the following

import sys
sys.path.append("/path/to/my/package")

I have tried this and I have the following file structure

mod1.py has the following code

from program.module2.mod2 import hello

hello()

mod2.py has the following code

def hello():
    print("hello")

main.py has the following code

from program.module1 import mod1

from the command line, I go to one folder above program and I type in the following

PS C:\temp\example> ls

    Directory: C:\temp\example

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----        21/02/2020    15:10                .vs
d-----        21/02/2020    15:10                program

PS C:\temp\example> python -m program.main
hello


问:
Navigate to a particular master list item sapui5
I have a Master-Detail page. After doing some transaction ( editing some data ) on the detail page, I want to stay on that item of Master list with the refreshed data. But after editing and refreshing the model, the page navigates to the first item of the Master list rather than staying on the same item of the master list and it's detail page. Below is the code after editing the data :

Detail.controller.js :

```<code>    update: function (evt) {
            that.oDataModel.update("/RaiseQuerySet('" + that.detailModel.getData().EICNO + "')",
            this.data, null, function (data) {

                                MessageBox.success("Your query has been updated", {
                                    onClose: function (sAction) {
                                        that.cancelIndent();
                                        that.refreshPage();

                                    }
                                });

    }

    refreshPage: function () {
        var that = this;
        $.ajax({
            url: "/sap/opu/odata/sap/ZHR_V_CARE_SRV/EmpQueryInitSet('10002001')?$expand=QueryLoginToQueryList/QueryToLog",
            method: "GET",
            dataType: "json",
            success: function (data) {
                that.getView().getModel("totalModel").setData(data.d.QueryLoginToQueryList);

                that.router.navTo('DetailPage', {
                    QueryNo: that.detailModel.getData().EICNO
                });
            //
            that.totalModel.refresh(true);
                that.detailModel.refresh(true);
            }
        });
    },

cancelIndent: function (evt) {
        this.detailModel.refresh(true);
    }
</code>```

DetailModel is used to populate the data in the detail page and totalModel is used to populate the data in the master page.

答:
This can happen if inside the manifest.json file you have 2 targets linked with route DetailPage.

From the behavior you explained, I would say that is the case.

The master detail templates from WebIDE usually have a logic inside the ListSelector.js file on which every time the master list it’s displayed it selects the first item automatically.

Body:
I have a Master-Detail page. After doing some transaction ( editing some data ) on the detail page, I want to stay on that item of Master list with the refreshed data. But after editing and refreshing the model, the page navigates to the first item of the Master list rather than staying on the same item of the master list and it's detail page. Below is the code after editing the data :

Detail.controller.js :

    update: function (evt) {
            that.oDataModel.update("/RaiseQuerySet('" + that.detailModel.getData().EICNO + "')",
            this.data, null, function (data) {

                                MessageBox.success("Your query has been updated", {
                                    onClose: function (sAction) {
                                        that.cancelIndent();
                                        that.refreshPage();

                                    }
                                });

    }

    refreshPage: function () {
        var that = this;
        $.ajax({
            url: "/sap/opu/odata/sap/ZHR_V_CARE_SRV/EmpQueryInitSet('10002001')?$expand=QueryLoginToQueryList/QueryToLog",
            method: "GET",
            dataType: "json",
            success: function (data) {
                that.getView().getModel("totalModel").setData(data.d.QueryLoginToQueryList);

                that.router.navTo('DetailPage', {
                    QueryNo: that.detailModel.getData().EICNO
                });
            //
            that.totalModel.refresh(true);
                that.detailModel.refresh(true);
            }
        });
    },

cancelIndent: function (evt) {
        this.detailModel.refresh(true);
    }

DetailModel is used to populate the data in the detail page and totalModel is used to populate the data in the master page.


问:
Erlang/OTP: Synchronous vs. Asynchronous messaging
One of the things that attracted me to Erlang in the first place is the Actor model; the idea that different processes run concurrently and interact via asynchronous messaging.

I'm just starting to get my teeth into OTP and in particular looking at gen_server.  All the examples I've seen - and granted they are tutorial type examples - use handle_call() rather than handle_cast() to implement module behaviour.

I find that a little confusing.  As far as I can tell, handle_call is a synchronous operation: the caller is blocked until the callee completes and returns.  Which seems to run counter to the async message passing philosophy.

I'm about to start a new OTP application. This seems like a fundamental architectural decision so I want to be sure I understand before embarking.

My questions are:

In real practice do people tend to use handle_call rather than handle_cast?

If so, what's the scalability impact when multiple clients can call the same process/module?

答:
Depends on your situation.

If you want to get a result, handle_call is really common. If you're not interested in the result of the call, use handle_cast. When handle_call is used, the caller will block, yes. This is most of time okay. Let's take a look at an example.

If you have a web server, that returns contents of files to clients, you'll be able to handle multiple clients. Each client have to wait for the contents of files to be read, so using handle_call in such a scenario would be perfectly fine (stupid example aside).

When you really need the behavior of sending a request, doing some other processing and then getting the reply later, typically two calls are used (for example, one cast and the one call to get the result) or normal message passing. But this is a fairly rare case.

Using handle_call will block the process for the duration of the call. This will lead to clients queuing up to get their replies and thus the whole thing will run in sequence.

If you want parallel code, you have to write parallel code. The only way to do that is to run multiple processes.

So, to summarize:

Using handle_call will block the caller and occupy the process called for the duration of the call.

If you want parallel activities to go on, you have to parallelize. The only way to do that is by starting more processes, and suddenly call vs cast is not such a big issue any more (in fact, it's more comfortable with call).


问:
Can I trust MQTT when phone in power safe mode
I have simple Paho MQTT Android client application:

```<code>public class PahoExampleActivity extends AppCompatActivity {

    MqttAndroidClient mqttAndroidClient;

    final String serverUri = "ssl://myserver:8887";

    String clientId = "ExampleAndroidClient";
    final String subscriptionTopic = "aaa/";
    final String publishTopic = "exampleAndroidPublishTopic";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Timber.plant(new  Timber.DebugTree());
        Timber.plant(new FileLoggingTree(this));
        Timber.tag(Utils.TIMBER_TAG).v("starting");

        setContentView(R.layout.activity_main);

        mqttAndroidClient = new MqttAndroidClient(getApplicationContext(), serverUri, clientId);
        mqttAndroidClient.setCallback(new MqttCallbackExtended() {
            @Override
            public void connectComplete(boolean reconnect, String serverURI) {

                if (reconnect) {
                    Timber.tag(Utils.TIMBER_TAG).v("Reconnected to : " + serverURI);
                    // Because Clean Session is true, we need to re-subscribe
                    subscribeToTopic();
                } else {
                    Timber.tag(Utils.TIMBER_TAG).v("Connected to: " + serverURI);

                }
            }

            @Override
            public void connectionLost(Throwable cause) {
                Timber.tag(Utils.TIMBER_TAG).v("The Connection was lost.");

            }

            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                Timber.tag(Utils.TIMBER_TAG).v("Incoming message: " + new String(message.getPayload()));
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {

            }
        });

        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setAutomaticReconnect(true);
        mqttConnectOptions.setCleanSession(false);

        mqttConnectOptions.setKeepAliveInterval(300);
        mqttConnectOptions.setUserName("a");
        mqttConnectOptions.setPassword("a".toCharArray());

        try {
            mqttConnectOptions.setSocketFactory(SocketFactoryMQ.getSocketFactory(this,""));
        } catch (KeyStoreException e) {
            Timber.e ( e);

        } catch (NoSuchAlgorithmException e) {
            Timber.tag(Utils.TIMBER_TAG).e ( e);
        } catch (IOException e) {
            Timber.tag(Utils.TIMBER_TAG).e ( e);
        } catch (KeyManagementException e) {
            Timber.tag(Utils.TIMBER_TAG).e ( e);
        } catch (CertificateException e) {
            Timber.tag(Utils.TIMBER_TAG).e ( e);
        } catch (UnrecoverableKeyException e) {
            Timber.tag(Utils.TIMBER_TAG).e ( e);
        }

        try {
            //addToHistory("Connecting to " + serverUri);
            mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();
                    disconnectedBufferOptions.setBufferEnabled(true);
                    disconnectedBufferOptions.setBufferSize(100);
                    disconnectedBufferOptions.setPersistBuffer(false);
                    disconnectedBufferOptions.setDeleteOldestMessages(false);
                    mqttAndroidClient.setBufferOpts(disconnectedBufferOptions);
                    subscribeToTopic();
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    Timber.tag(Utils.TIMBER_TAG).v("Failed to connect to: " + serverUri);
                }
            });

        } catch (MqttException ex){
            ex.printStackTrace();
        }

    }

    public void subscribeToTopic(){
        try {
            mqttAndroidClient.subscribe(subscriptionTopic, 0, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    Timber.tag(Utils.TIMBER_TAG).v("Subscribed!");
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    Timber.tag(Utils.TIMBER_TAG).v("Failed to subscribe");
                }
            });

            mqttAndroidClient.subscribe(subscriptionTopic, 0, new IMqttMessageListener() {
                @Override
                public void messageArrived(String topic, MqttMessage message) throws Exception {
                    // message Arrived!
                    Timber.tag(Utils.TIMBER_TAG).v("Message: " + topic + " : " + new String(message.getPayload()));
                    sendNotification(topic,new String(message.getPayload()));
                }
            });

        } catch (MqttException ex){
            System.err.println("Exception whilst subscribing");
            ex.printStackTrace();
        }
    }

    public void sendNotification(String title, String message) {

        ...

    }

}
</code>```

Everything works fine when phone is connected to charger or active. My application miss
MQTT messages when phone is disconnected from charger and is closed (I call it power safe mode). In this situation after some time phone starts to miss MQTT messages. According to log taken from phone we can see that messages appear when phone is waked up:

```<code>Thu Feb 20 2020 at 02:41:27:776 pm  Message:  aaa/ : 2
Thu Feb 20 2020 at 02:41:49:537 pm  Message:  aaa/ : 3
Thu Feb 20 2020 at 02:44:26:972 pm  Message:  aaa/ : 2
Thu Feb 20 2020 at 02:44:47:913 pm  Message:  aaa/ : 3
Thu Feb 20 2020 at 02:45:20:876 pm  Message:  aaa/ : 4
Thu Feb 20 2020 at 02:46:01:322 pm  Message:  aaa/ : 5
Thu Feb 20 2020 at 02:46:52:873 pm  Message:  aaa/ : 6
Thu Feb 20 2020 at 02:47:09:993 pm  The Connection was lost.
Thu Feb 20 2020 at 02:54:44:263 pm  Reconnected to : ssl://myserver:8887
Thu Feb 20 2020 at 02:54:44:357 pm  Subscribed!
Thu Feb 20 2020 at 02:54:48:196 pm  MainActivity.onStart
Thu Feb 20 2020 at 02:55:28:465 pm  MainActivity.onStop
Thu Feb 20 2020 at 02:55:33:080 pm  Message:  aaa/ : 12
Thu Feb 20 2020 at 02:57:35:070 pm  Message:  aaa/ : 13
Thu Feb 20 2020 at 02:58:30:264 pm  The Connection was lost.
Thu Feb 20 2020 at 03:02:54:001 pm  Reconnected to : ssl://myserver:8887
Thu Feb 20 2020 at 03:02:54:103 pm  Subscribed!
</code>```

Messages 7-11 just not reached my device. How to solve this problem?

UPD

After change QOS 0 to QOS 1 I got all messages. Messages starting from 10 came at the same time after some delay. From first glance 5 min. delay is not relevant, but I'm not sure how big delay it might be. For example 30 min. delay is not appropriate.

```<code>Thu Feb 20 2020 at 06:20:54:411 pm  Message: aaa/ : 2
Thu Feb 20 2020 at 06:21:16:221 pm  Message: aaa/ : 3
Thu Feb 20 2020 at 06:21:48:173 pm  Message: aaa/ : 4
Thu Feb 20 2020 at 06:22:29:642 pm  Message: aaa/ : 5
Thu Feb 20 2020 at 06:23:21:571 pm  Message: aaa/ : 6
Thu Feb 20 2020 at 06:24:23:327 pm  Message: aaa/ : 7
Thu Feb 20 2020 at 06:25:34:278 pm  Message: aaa/ : 8
Thu Feb 20 2020 at 06:26:56:309 pm  Message: aaa/ : 9
Thu Feb 20 2020 at 06:27:16:408 pm  The Connection was lost.
Thu Feb 20 2020 at 06:32:27:667 pm  MainActivity.onStart
Thu Feb 20 2020 at 06:32:37:320 pm  Reconnected to : ssl://myserver:8887
Thu Feb 20 2020 at 06:32:37:390 pm  Message: aaa/ : 10
Thu Feb 20 2020 at 06:32:37:442 pm  Subscribed!
Thu Feb 20 2020 at 06:32:37:450 pm  Message: aaa/ : 11
Thu Feb 20 2020 at 06:32:37:498 pm  Message: aaa/ : 12
Thu Feb 20 2020 at 06:32:38:084 pm  MainActivity.onStop
Thu Feb 20 2020 at 06:34:02:431 pm  Message: aaa/ : 13
</code>```

答:
You have subscribed to the topic at QOS 0 which is "fire and forget", no effort will be made to make sure the message is actually delivered.

```<code>mqttAndroidClient.subscribe(subscriptionTopic, 0, new IMqttMessageListener() {...
</code>```

If you want assured delivery you need to use QOS 1 (At least once) or QOS 2 (Once and only once)

```<code>mqttAndroidClient.subscribe(subscriptionTopic, 1, new IMqttMessageListener() {...
</code>```

Body:
I have simple Paho MQTT Android client application:

public class PahoExampleActivity extends AppCompatActivity {

    MqttAndroidClient mqttAndroidClient;

    final String serverUri = "ssl://myserver:8887";

    String clientId = "ExampleAndroidClient";
    final String subscriptionTopic = "aaa/";
    final String publishTopic = "exampleAndroidPublishTopic";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Timber.plant(new  Timber.DebugTree());
        Timber.plant(new FileLoggingTree(this));
        Timber.tag(Utils.TIMBER_TAG).v("starting");

        setContentView(R.layout.activity_main);

        mqttAndroidClient = new MqttAndroidClient(getApplicationContext(), serverUri, clientId);
        mqttAndroidClient.setCallback(new MqttCallbackExtended() {
            @Override
            public void connectComplete(boolean reconnect, String serverURI) {

                if (reconnect) {
                    Timber.tag(Utils.TIMBER_TAG).v("Reconnected to : " + serverURI);
                    // Because Clean Session is true, we need to re-subscribe
                    subscribeToTopic();
                } else {
                    Timber.tag(Utils.TIMBER_TAG).v("Connected to: " + serverURI);

                }
            }

            @Override
            public void connectionLost(Throwable cause) {
                Timber.tag(Utils.TIMBER_TAG).v("The Connection was lost.");

            }

            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                Timber.tag(Utils.TIMBER_TAG).v("Incoming message: " + new String(message.getPayload()));
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {

            }
        });

        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setAutomaticReconnect(true);
        mqttConnectOptions.setCleanSession(false);

        mqttConnectOptions.setKeepAliveInterval(300);
        mqttConnectOptions.setUserName("a");
        mqttConnectOptions.setPassword("a".toCharArray());

        try {
            mqttConnectOptions.setSocketFactory(SocketFactoryMQ.getSocketFactory(this,""));
        } catch (KeyStoreException e) {
            Timber.e ( e);

        } catch (NoSuchAlgorithmException e) {
            Timber.tag(Utils.TIMBER_TAG).e ( e);
        } catch (IOException e) {
            Timber.tag(Utils.TIMBER_TAG).e ( e);
        } catch (KeyManagementException e) {
            Timber.tag(Utils.TIMBER_TAG).e ( e);
        } catch (CertificateException e) {
            Timber.tag(Utils.TIMBER_TAG).e ( e);
        } catch (UnrecoverableKeyException e) {
            Timber.tag(Utils.TIMBER_TAG).e ( e);
        }

        try {
            //addToHistory("Connecting to " + serverUri);
            mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();
                    disconnectedBufferOptions.setBufferEnabled(true);
                    disconnectedBufferOptions.setBufferSize(100);
                    disconnectedBufferOptions.setPersistBuffer(false);
                    disconnectedBufferOptions.setDeleteOldestMessages(false);
                    mqttAndroidClient.setBufferOpts(disconnectedBufferOptions);
                    subscribeToTopic();
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    Timber.tag(Utils.TIMBER_TAG).v("Failed to connect to: " + serverUri);
                }
            });

        } catch (MqttException ex){
            ex.printStackTrace();
        }

    }

    public void subscribeToTopic(){
        try {
            mqttAndroidClient.subscribe(subscriptionTopic, 0, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    Timber.tag(Utils.TIMBER_TAG).v("Subscribed!");
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    Timber.tag(Utils.TIMBER_TAG).v("Failed to subscribe");
                }
            });

            mqttAndroidClient.subscribe(subscriptionTopic, 0, new IMqttMessageListener() {
                @Override
                public void messageArrived(String topic, MqttMessage message) throws Exception {
                    // message Arrived!
                    Timber.tag(Utils.TIMBER_TAG).v("Message: " + topic + " : " + new String(message.getPayload()));
                    sendNotification(topic,new String(message.getPayload()));
                }
            });

        } catch (MqttException ex){
            System.err.println("Exception whilst subscribing");
            ex.printStackTrace();
        }
    }

    public void sendNotification(String title, String message) {

        ...

    }

}

Everything works fine when phone is connected to charger or active. My application miss
MQTT messages when phone is disconnected from charger and is closed (I call it power safe mode). In this situation after some time phone starts to miss MQTT messages. According to log taken from phone we can see that messages appear when phone is waked up:

Thu Feb 20 2020 at 02:41:27:776 pm  Message:  aaa/ : 2
Thu Feb 20 2020 at 02:41:49:537 pm  Message:  aaa/ : 3
Thu Feb 20 2020 at 02:44:26:972 pm  Message:  aaa/ : 2
Thu Feb 20 2020 at 02:44:47:913 pm  Message:  aaa/ : 3
Thu Feb 20 2020 at 02:45:20:876 pm  Message:  aaa/ : 4
Thu Feb 20 2020 at 02:46:01:322 pm  Message:  aaa/ : 5
Thu Feb 20 2020 at 02:46:52:873 pm  Message:  aaa/ : 6
Thu Feb 20 2020 at 02:47:09:993 pm  The Connection was lost.
Thu Feb 20 2020 at 02:54:44:263 pm  Reconnected to : ssl://myserver:8887
Thu Feb 20 2020 at 02:54:44:357 pm  Subscribed!
Thu Feb 20 2020 at 02:54:48:196 pm  MainActivity.onStart
Thu Feb 20 2020 at 02:55:28:465 pm  MainActivity.onStop
Thu Feb 20 2020 at 02:55:33:080 pm  Message:  aaa/ : 12
Thu Feb 20 2020 at 02:57:35:070 pm  Message:  aaa/ : 13
Thu Feb 20 2020 at 02:58:30:264 pm  The Connection was lost.
Thu Feb 20 2020 at 03:02:54:001 pm  Reconnected to : ssl://myserver:8887
Thu Feb 20 2020 at 03:02:54:103 pm  Subscribed!

Messages 7-11 just not reached my device. How to solve this problem?

UPD

After change QOS 0 to QOS 1 I got all messages. Messages starting from 10 came at the same time after some delay. From first glance 5 min. delay is not relevant, but I'm not sure how big delay it might be. For example 30 min. delay is not appropriate.

Thu Feb 20 2020 at 06:20:54:411 pm  Message: aaa/ : 2
Thu Feb 20 2020 at 06:21:16:221 pm  Message: aaa/ : 3
Thu Feb 20 2020 at 06:21:48:173 pm  Message: aaa/ : 4
Thu Feb 20 2020 at 06:22:29:642 pm  Message: aaa/ : 5
Thu Feb 20 2020 at 06:23:21:571 pm  Message: aaa/ : 6
Thu Feb 20 2020 at 06:24:23:327 pm  Message: aaa/ : 7
Thu Feb 20 2020 at 06:25:34:278 pm  Message: aaa/ : 8
Thu Feb 20 2020 at 06:26:56:309 pm  Message: aaa/ : 9
Thu Feb 20 2020 at 06:27:16:408 pm  The Connection was lost.
Thu Feb 20 2020 at 06:32:27:667 pm  MainActivity.onStart
Thu Feb 20 2020 at 06:32:37:320 pm  Reconnected to : ssl://myserver:8887
Thu Feb 20 2020 at 06:32:37:390 pm  Message: aaa/ : 10
Thu Feb 20 2020 at 06:32:37:442 pm  Subscribed!
Thu Feb 20 2020 at 06:32:37:450 pm  Message: aaa/ : 11
Thu Feb 20 2020 at 06:32:37:498 pm  Message: aaa/ : 12
Thu Feb 20 2020 at 06:32:38:084 pm  MainActivity.onStop
Thu Feb 20 2020 at 06:34:02:431 pm  Message: aaa/ : 13

Body:
You have subscribed to the topic at QOS 0 which is "fire and forget", no effort will be made to make sure the message is actually delivered.

mqttAndroidClient.subscribe(subscriptionTopic, 0, new IMqttMessageListener() {...

If you want assured delivery you need to use QOS 1 (At least once) or QOS 2 (Once and only once)

mqttAndroidClient.subscribe(subscriptionTopic, 1, new IMqttMessageListener() {...


问:
Hook query retruning empty object inside useEffect but not after it Why?
So I have a query hook from which I wish to populate a state variable with data. The problem is, within useEffect the query is being returned as an {} object but after useEffect properly returns data (See image). I attempted to place useEffect after all the variable definitions but that issued a hook render error. What am I overlooking here and how do I resolve this?

```<code>  // Single Item Query
  const { data: singledItemData, error: errorSingleItem, loading: loadingSingleItem } = useQuery(
    SINGLE_ITEM_QUERY, {
      variables: {
        id: props.id,
      }
    }
  );

  useEffect(() => {
    console.log("singledItemData in useEffect = ", singledItemData);
    if (singledItemData.item) {
      setColor(singledItemData.item.color.name);
    }
  }, []);

  // User hook variables
  if (!user) return null;
  if (user.error) return <Error error={user.error} />;

  // Single Item Query variables

  if (loadingSingleItem) return <p>Loading...</p>;
  if (!singledItemData.item) return <p>No Item Found for ID {props.id}</p>;

  console.log("Single Item Data = ", singledItemData);
</code>```

答:
When a component using useQuery mounts it starts a network request which is asynchronous. Your useEffect hook however is executed once after the component has mounted (due to the empty dependency list). At this time the request most likely hasn't even finished so no data is available. As soon as the request finishes your component will re-render again (triggered by the state update in the useQuery hook) with the received data. But this time your useEffect callback will not be called again. Add singledItemData to the dependency list to see the change or just console.log in the outer scope so see the changes of every render.

So this is no bug but the expected behaviour.

Body:
So I have a query hook from which I wish to populate a state variable with data. The problem is, within useEffect the query is being returned as an {} object but after useEffect properly returns data (See image). I attempted to place useEffect after all the variable definitions but that issued a hook render error. What am I overlooking here and how do I resolve this?

  // Single Item Query
  const { data: singledItemData, error: errorSingleItem, loading: loadingSingleItem } = useQuery(
    SINGLE_ITEM_QUERY, {
      variables: {
        id: props.id,
      }
    }
  );

  useEffect(() => {
    console.log("singledItemData in useEffect = ", singledItemData);
    if (singledItemData.item) {
      setColor(singledItemData.item.color.name);
    }
  }, []);

  // User hook variables
  if (!user) return null;
  if (user.error) return <Error error={user.error} />;

  // Single Item Query variables

  if (loadingSingleItem) return
Loading...
;
  if (!singledItemData.item) return
No Item Found for ID {props.id}
;

  console.log("Single Item Data = ", singledItemData);


答: since you started the loop with a set boolean value, you could set your variable "restart" to "true" ( restart = true) to leave the loop</p>

Title: How do I make a while loop to ask the user if they want to restart the program


问:
How to map over Applicative form?
I want to map over Applicative form.

The type of map-like function would be like below:

```<code>mapX :: (Applicative f) => (f a -> f b) -> f [a] -> f [b]
</code>```

used as:

```<code>result :: (Applicative f) => f [b]
result = mapX f xs
  where f  :: f a -> f b
        f = ...
        xs :: f[a]
        xs = ...
</code>```

As the background of this post, I try to write fluid simulation program using Applicative style referring to Paul Haduk's "The Haskell School of Expression", and I want to express the simulation with Applicative style as below:

```<code>x, v, a :: Sim VArray
x = x0 +: integral (v * dt)
v = v0 +: integral (a * dt)
a = (...calculate acceleration with x v...)

instance Applicative Sim where
  ...
</code>```

where Sim type means the process of simulation computation and VArray means Array of Vector (x,y,z). X, v a are the arrays of position, velocity and acceleration, respectively.

Mapping over Applicative form comes when definining a.

I've found one answer to my question.

After all, my question is "How to lift high-order functions (like map
:: (a -> b) -> [a] -> [b]) to the Applicative world?" and the answer
I've found is "To build them using lifted first-order functions."

For example, the "mapX" is defined with lifted first-order functions
(headA, tailA, consA, nullA, condA) as below:

```<code>mapX :: (f a -> f b) -> f [a] -> f [b]
mapX f xs0 = condA (nullA xs0) (pure []) (consA (f x) (mapA f xs))
 where
   x = headA xs0
   xs = tailA xs0

headA = liftA head

tailA = liftA tail

consA = liftA2 (:)

nullA = liftA null

condA b t e = liftA3 aux b t e
  where aux b t e = if b then t else e
</code>```

答:
Here is a session in ghci where I define mapX the way you wanted it.

```<code>Prelude>
Prelude> import Control.Applicative
Prelude Control.Applicative> :t pure
pure :: Applicative f => a -> f a
Prelude Control.Applicative> :t (<*>)
(<*>) :: Applicative f => f (a -> b) -> f a -> f b
Prelude Control.Applicative> let mapX fun ma = pure fun <*> ma
Prelude Control.Applicative> :t mapX
mapX :: Applicative f => (a -> b) -> f a -> f b
</code>```

I must however add that fmap is better to use, since Functor is less expressive than Applicative (that means that using fmap will work more often).

```<code>Prelude> :t fmap
fmap :: Functor f => (a -> b) -> f a -> f b
</code>```

edit:
Oh, you have some other signature for mapX, anyway, you maybe meant the one I suggested (fmap)?

Title: How to map over Applicative form?

Body:
I want to map over Applicative form.

The type of map-like function would be like below:

mapX :: (Applicative f) => (f a -> f b) -> f [a] -> f [b]

used as:

result :: (Applicative f) => f [b]
result = mapX f xs
  where f  :: f a -> f b
        f = ...
        xs :: f[a]
        xs = ...

As the background of this post, I try to write fluid simulation program using Applicative style referring to Paul Haduk's "The Haskell School of Expression", and I want to express the simulation with Applicative style as below:

x, v, a :: Sim VArray
x = x0 +: integral (v * dt)
v = v0 +: integral (a * dt)
a = (...calculate acceleration with x v...)

instance Applicative Sim where
  ...

where Sim type means the process of simulation computation and VArray means Array of Vector (x,y,z). X, v a are the arrays of position, velocity and acceleration, respectively.

Mapping over Applicative form comes when definining a.

I've found one answer to my question.

After all, my question is "How to lift high-order functions (like map
:: (a -> b) -> [a] -> [b]) to the Applicative world?" and the answer
I've found is "To build them using lifted first-order functions."

For example, the "mapX" is defined with lifted first-order functions
(headA, tailA, consA, nullA, condA) as below:

mapX :: (f a -> f b) -> f [a] -> f [b]
mapX f xs0 = condA (nullA xs0) (pure []) (consA (f x) (mapA f xs))
 where
   x = headA xs0
   xs = tailA xs0

headA = liftA head

tailA = liftA tail

consA = liftA2 (:)

nullA = liftA null

condA b t e = liftA3 aux b t e
  where aux b t e = if b then t else e

Body:
Here is a session in ghci where I define mapX the way you wanted it.

Prelude>
Prelude> import Control.Applicative
Prelude Control.Applicative> :t pure
pure :: Applicative f => a -> f a
Prelude Control.Applicative> :t (<*>)
(<*>) :: Applicative f => f (a -> b) -> f a -> f b
Prelude Control.Applicative> let mapX fun ma = pure fun <*> ma
Prelude Control.Applicative> :t mapX
mapX :: Applicative f => (a -> b) -> f a -> f b

I must however add that fmap is better to use, since Functor is less expressive than Applicative (that means that using fmap will work more often).

Prelude> :t fmap
fmap :: Functor f => (a -> b) -> f a -> f b

edit:
Oh, you have some other signature for mapX, anyway, you maybe meant the one I suggested (fmap)?


问:
Add "1 january" to each row of a column containing years
I have a dataset in R studio with a column (YEAR_OF_BIRTH) where each row contains a year (yyyy format), and I would like to create a new column containing the year, but adding 01-01- to each row.

Does someone know how I can do this ?

Thanks in advance!

答:
```<code>df$new_column <- paste0("01-01-", df$YEAR_OF_BIRTH)
</code>```

Or if you want it as date datatype:

```<code>df$new_column <- as.Date(paste0("01-01-", df$YEAR_OF_BIRTH), format="%d-%m-%Y")
</code>```

Disclaimer:
This is borderline adding fictional information to a data set. I assume you have a good reason to put all these dates to first of january ;)

OwnerDisplayName: Margaux David

Body:
df$new_column <- paste0("01-01-", df$YEAR_OF_BIRTH)

Or if you want it as date datatype:

df$new_column <- as.Date(paste0("01-01-", df$YEAR_OF_BIRTH), format="%d-%m-%Y")

Disclaimer:
This is borderline adding fictional information to a data set. I assume you have a good reason to put all these dates to first of january ;)


问:
The most pythonic way to parse specific sub-string in a string?
I have the following log and want to extract the second "DDD-xxxxx" ID from each entry (if exist a second DDD id):

```<code>cs:444 - br:/main/j_DDD-50535/DDD-68009
cs:445 - br:/main/j_DDD-50535/j_DDD-70220
cs:446 - br:/main/j_DDD-50535/j_DDD-70117
cs:447-Merge from branch: /main/j_DDD-50544/j_DDD-61183
Requested by: Smith, John (UserID1)
cs:448-Merge from branch: /main/j_DDD-4822
Requested by: Grant, Huge (userID2)
cs:449-Daily automated release of 3.5.5.4
</code>```

Using regex I found a workaround to get them but I think it should be possible to get much easier:

```<code>def read_log():
    log_file_name = "log"
    with open(log_file_name, "r") as file:
        log_file = file.read().split("cs:")
    return log_file

def key_creator():
    log_data = read_log()

    keys = []
    for line in log_data:
        # print(line)
        if line[:5].isdigit():
            search = re.search('/j_(.*)\n', line)
            if hasattr(search, "group"):
                search = search.group(1).split('/j_')

                if 1 < len(search) and search[1][:3] == "DDD":
                    keys.append(search[1])
                    print(line)
    return keys

key_creator()
</code>```

Edit: Just to clarify:
 - the string DDD can be followed by indeterminate number of digits, (DDD-23, DDD-342, DDD-4842, DDD-44332... would be possibles entries as well)

答:
```<code>def key_creator():
    log_data = read_log()
    keys = []
    for line in log_data:
        s = re.findall(r'(DDD-\d+)', line)
        if s and len(s)>1:
            keys.append(s[1])
    return keys
</code>```

Body:
I have the following log and want to extract the second "DDD-xxxxx" ID from each entry (if exist a second DDD id):

cs:444 - br:/main/j_DDD-50535/DDD-68009
cs:445 - br:/main/j_DDD-50535/j_DDD-70220
cs:446 - br:/main/j_DDD-50535/j_DDD-70117
cs:447-Merge from branch: /main/j_DDD-50544/j_DDD-61183
Requested by: Smith, John (UserID1)
cs:448-Merge from branch: /main/j_DDD-4822
Requested by: Grant, Huge (userID2)
cs:449-Daily automated release of 3.5.5.4

Using regex I found a workaround to get them but I think it should be possible to get much easier:

def read_log():
    log_file_name = "log"
    with open(log_file_name, "r") as file:
        log_file = file.read().split("cs:")
    return log_file

def key_creator():
    log_data = read_log()

    keys = []
    for line in log_data:
        # print(line)
        if line[:5].isdigit():
            search = re.search('/j_(.*)\n', line)
            if hasattr(search, "group"):
                search = search.group(1).split('/j_')

                if 1 < len(search) and search[1][:3] == "DDD":
                    keys.append(search[1])
                    print(line)
    return keys

key_creator()

Edit: Just to clarify:
 - the string DDD can be followed by indeterminate number of digits, (DDD-23, DDD-342, DDD-4842, DDD-44332... would be possibles entries as well)


问:
Daily Coding Problem 260 : Reconstruct a jumbled array - Intuition?
I'm going through the question below.

The sequence [0, 1, ..., N] has been jumbled, and the only clue you have for its order is an array representing whether each number is larger or smaller than the last. Given this information, reconstruct an array that is consistent with it.

For example, given [None, +, +, -, +], you could return [1, 2, 3, 0, 4].

I went through the solution on this post but still unable to understand it as to why this solution works. I don't think I would be able to come up with the solution if I had this in front of me during an interview. Can anyone explain the intuition behind it? Thanks in advance!

答:
This answer tries to give a general strategy to find an algorithm to tackle this type of problems. It is not trying to prove why the given solution is correct, but lying out a route towards such a solution.

A tried and tested way to tackle this kind of problem (actually a wide range of problems), is to start with small examples and work your way up. This works for puzzles, but even so for problems encountered in reality.

First, note that the question is formulated deliberately to not point you in the right direction too easily. It makes you think there is some magic involved. How can you reconstruct a list of N numbers given only the list of plusses and minuses?

Well, you can't. For 10 numbers, there are 10! = 3628800 possible permutations. And there are only 2⁹ = 512 possible lists of signs. It's a very huge difference. Most original lists will be completely different after reconstruction.

Here's an overview of how to approach the problem:

Start with very simple examples

Try to work your way up, adding a bit of complexity

If you see something that seems a dead end, try increasing complexity in another way; don't spend too much time with situations where you don't see progress

While exploring alternatives, revisit old dead ends, as you might have gained new insights

Try whether recursion could work:

given a solution for N, can we easily construct a solution for N+1?

or even better: given a solution for N, can we easily construct a solution for 2N?

Given a recursive solution, can it be converted to an iterative solution?

Does the algorithm do some repetitive work that can be postponed to the end?

....

So, let's start simple (writing 0 for the None at the start):

very short lists are easy to guess:

'0++' → 0 1 2 → clearly only one solution

'0--' → 2 1 0 → only one solution

'0-+' → 1 0 2 or 2 0 1 → hey, there is no unique outcome, though the question only asks for one of the possible outcomes

lists with only plusses:

'0++++++' → 0 1 2 3 4 5 6 → only possibility

lists with only minuses:

'0-------'→ 7 6 5 4 3 2 1 0 → only possibility

lists with one minus, the rest plusses:

'0-++++' → 1 0 2 3 4 5 or 5 0 1 2 3 4 or ...

'0+-+++' → 0 2 1 3 4 5 or 5 0 1 2 3 4 or ...

→ no very obvious pattern seem to emerge

maybe some recursion could help?

given a solution for N, appending one sign more?

appending a plus is easy: just repeat the solution and append the largest plus 1

appending a minus, after some thought: increase all the numbers by 1 and append a zero

→ hey, we have a working solution, but maybe not the most efficient one

the algorithm just appends to an existing list, no need to really write it recursively (although the idea is expressed recursively)

appending a plus can be improved, by storing the largest number in a variable so it doesn't need to be searched at every step; no further improvements seem necessary

appending a minus is more troublesome: the list needs to be traversed with each append

what if instead of appending a zero, we append -1, and do the adding at the end?

this clearly works when there is only one minus

when two minus signs are encountered, the first time append -1, the second time -2

→ hey, this works for any number of minuses encountered, just store its counter in a variable and sum with it at the end of the algorithm

This is in bird's eye view one possible route towards coming up with a solution. Many routes lead to Rome. Introducing negative numbers might seem tricky, but it is a logical conclusion after contemplating the recursive algorithm for a while.


问:
Set Vector of Eigen Matrices to 0
I'm adapting the Hough Transform for a special application, and for this I need to store a lot of Eigen Matrixes in a vector and I need them all to be 0 at the beginning.
This is how I have initialized this:

```<code>typedef Eigen::Matrix<int,30,150> HoughMatrix
std::vector<HoughMatrix> hough_spaces(num_spaces)
</code>```

My question now is, what is the fastest way to make all elements of all those Matrixes equal to 0?
I tried looping over each Vector element and do:

```<code>hough_spaces[i].setZero()
</code>```

But that was rather slow. Is there a faster way? Or a way to directly initialize them as 0?
Thank you for your help

答:
First of all, Eigen::Matrix<int,30,150> will by default be aligned to 16 bytes, which on 64bit systems or with C++17 will most likely work properly, but you may otherwise face some caveats.
An easy way to workaround any issues regarding alignment is to write

```<code>typedef Eigen::Matrix<int,30,150, Eigen::DontAlign> HoughMatrix;
</code>```

Now the idiomatic way to write what you want would be to write

```<code>std::vector<HoughMatrix> hough_spaces(num_spaces, HoughMatrix::Zero());
</code>```

However, this will result in a loop of memcpy calls (at least for gcc and clang: https://godbolt.org/z/ULixBm).

Alternatively, you could create a vector of uninitialized HoughMatrixes and apply std::memset on them:

```<code>std::vector<HoughMatrix> hough_spaces(num_spaces);
std::memset(hough_spaces.data(), 0, num_spaces*sizeof(HoughMatrix));
</code>```

Note that for that to run without Eigen having to loop through all elements requires to have HoughMatrix not aligned (as shown at the beginning) or to disable alignment-assertions: https://godbolt.org/z/nDJqV5

If you don't actually need the std::vector functionality (mostly the ability to copy and resize), you could just allocate some memory using calloc and free it after usage. To be leak-safe, this can be encapsulated into a std::unique_ptr:

```<code>// unique_ptr with custom deallocator (use a typedef, if you need this more often):
std::unique_ptr<HoughMatrix[], void(&)(void*)> hough_spaces(static_cast<HoughMatrix*>(std::calloc(num_spaces, sizeof(HoughMatrix))), std::free);
if(!hough_spaces) throw std::bad_alloc(); // Useful, if you actually handle bad-allocs. If you ignore failed callocs, you'll likely segfault when accessing the data.
</code>```

Clang and gcc will optimize this into a single calloc/free pair:
https://godbolt.org/z/m4rzRq

A totally different approach would be to try using a 3D Tensor instead of a vector of matrices:

```<code>typedef Eigen::Tensor<int, 3> HoughSpace;
HoughSpace hough_spaces(num_spaces,30,150);
hough_spaces.setZero();
</code>```

Looking at the generated assembly this looks semi-optimal though, even with -O3 -DNDEBUG.

Overall, note that benchmarking anything memory-related may be misleading. E.g., the call to calloc may return nearly instantaneous but on a lower level point to unallocated pages, which makes actually accessing them the first time more expensive.

Title: Set Vector of Eigen Matrices to 0

Body:
I'm adapting the Hough Transform for a special application, and for this I need to store a lot of Eigen Matrixes in a vector and I need them all to be 0 at the beginning.
This is how I have initialized this:

typedef Eigen::Matrix<int,30,150> HoughMatrix
std::vector<HoughMatrix> hough_spaces(num_spaces)

My question now is, what is the fastest way to make all elements of all those Matrixes equal to 0?
I tried looping over each Vector element and do:

hough_spaces[i].setZero()

But that was rather slow. Is there a faster way? Or a way to directly initialize them as 0?
Thank you for your help

Body:
First of all, Eigen::Matrix<int,30,150> will by default be aligned to 16 bytes, which on 64bit systems or with C++17 will most likely work properly, but you may otherwise face some caveats.
An easy way to workaround any issues regarding alignment is to write

typedef Eigen::Matrix<int,30,150, Eigen::DontAlign> HoughMatrix;

Now the idiomatic way to write what you want would be to write

std::vector<HoughMatrix> hough_spaces(num_spaces, HoughMatrix::Zero());

However, this will result in a loop of memcpy calls (at least for gcc and clang: https://godbolt.org/z/ULixBm).

Alternatively, you could create a vector of uninitialized HoughMatrixes and apply std::memset on them:

std::vector<HoughMatrix> hough_spaces(num_spaces);
std::memset(hough_spaces.data(), 0, num_spaces*sizeof(HoughMatrix));

Note that for that to run without Eigen having to loop through all elements requires to have HoughMatrix not aligned (as shown at the beginning) or to disable alignment-assertions: https://godbolt.org/z/nDJqV5

If you don't actually need the std::vector functionality (mostly the ability to copy and resize), you could just allocate some memory using calloc and free it after usage. To be leak-safe, this can be encapsulated into a std::unique_ptr:

// unique_ptr with custom deallocator (use a typedef, if you need this more often):
std::unique_ptr<HoughMatrix[], void(&)(void*)> hough_spaces(static_cast<HoughMatrix*>(std::calloc(num_spaces, sizeof(HoughMatrix))), std::free);
if(!hough_spaces) throw std::bad_alloc(); // Useful, if you actually handle bad-allocs. If you ignore failed callocs, you'll likely segfault when accessing the data.

Clang and gcc will optimize this into a single calloc/free pair:
https://godbolt.org/z/m4rzRq

A totally different approach would be to try using a 3D Tensor instead of a vector of matrices:

typedef Eigen::Tensor<int, 3> HoughSpace;
HoughSpace hough_spaces(num_spaces,30,150);
hough_spaces.setZero();

Looking at the generated assembly this looks semi-optimal though, even with -O3 -DNDEBUG.

Overall, note that benchmarking anything memory-related may be misleading. E.g., the call to calloc may return nearly instantaneous but on a lower level point to unallocated pages, which makes actually accessing them the first time more expensive.


问:
How to load specific entries into userform from worksheet (and browse between them)?
My worksheet has 2 user forms. One to enter new data into sheet and another to browse through specific entries, only showing a few pieces for the user to confirm they have the right entry to download to PDF.

I need the 2nd userform (above) to load the latest entry where the value in column (K) is 'yes'. And then display the txtdossier (D), txtdate (A), and txtcontainer number (C). And then either manually input a txtDossier number and have the related info show, or be able to browse through the entries with prev/next.

What is the best way to not only show an entry when condition in column K is met, but also to adjust as new entries are added to the sheet.

The only way I know how to do it now is to manually add every new entry into the code.

I.e.
UserForm2.txtDossier.Text = CStr(Range("c5").Value)

Please add comments when possible, my understanding of VBA is below basic still.

```<code>Private Sub UserForm_Initialize()

Me.txtDate.Enabled = False
Me.txtDate.BackColor = RGB(224, 224, 224)
Me.txtContainer.Enabled = False
Me.txtContainer.BackColor = RGB(224, 224, 224)

Dim LastRow As Long
Dim Doss As String
Dim Datum As String
Dim Container As String
Dim FaseJa As String

Dim ws As Worksheet
Set ws = Worksheets("Meting Fase 2 lijst")

LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

End Sub
</code>```

答:
This code won't solve your problem, but is too long to fit in a comment.

Assuming your form is called UserForm2 and contains these controls:  txtDossier, txtDate and txtContainer then you can add the following code to a normal module.

As @Czeskleba said - to solve your problem we'd have to write the code for you, which isn't what this site is about.  Have a look at FIND to track down the records you're looking for.  Excel Macro Mastery also has good explanations on how to use it.

```<code>Public Sub Test()

    'Open first instance of form.

    Dim frm As UserForm2
    Set frm = New UserForm2

    With frm
        .Caption = "First Displayed Form"
        .txtDossier = ThisWorkbook.Worksheets("Sheet1").Range("B1")
        With .txtDate
            .Value = Format(Date, "dd-mmm-yy")
            .Enabled = False
        End With
        .txtContainer = "Some data in here"
        .Show
    End With

    'Open second instance of form.
    'If forms ShowModal property is set to TRUE then this code will run after first form is (manually) closed.
    'If ShowModal is set to FALSE then two forms will appear.

    Dim frm2 As UserForm2
    Set frm2 = New UserForm2

    With frm2
        With .txtDossier
            .BackColor = RGB(224, 224, 224)
        End With
        .Caption = "Second Displayed Form"
        .txtDate = Format(DateSerial(2019, 12, 25), "ddd dd-mmm-yy")
        .txtContainer.Enabled = False
        .Show
    End With

End Sub
</code>```

Body:
My worksheet has 2 user forms. One to enter new data into sheet and another to browse through specific entries, only showing a few pieces for the user to confirm they have the right entry to download to PDF.

I need the 2nd userform (above) to load the latest entry where the value in column (K) is 'yes'. And then display the txtdossier (D), txtdate (A), and txtcontainer number (C). And then either manually input a txtDossier number and have the related info show, or be able to browse through the entries with prev/next.

What is the best way to not only show an entry when condition in column K is met, but also to adjust as new entries are added to the sheet.

The only way I know how to do it now is to manually add every new entry into the code.

I.e.
UserForm2.txtDossier.Text = CStr(Range("c5").Value)

Please add comments when possible, my understanding of VBA is below basic still.

Private Sub UserForm_Initialize()

Me.txtDate.Enabled = False
Me.txtDate.BackColor = RGB(224, 224, 224)
Me.txtContainer.Enabled = False
Me.txtContainer.BackColor = RGB(224, 224, 224)

Dim LastRow As Long
Dim Doss As String
Dim Datum As String
Dim Container As String
Dim FaseJa As String

Dim ws As Worksheet
Set ws = Worksheets("Meting Fase 2 lijst")

LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

End Sub

Body:
This code won't solve your problem, but is too long to fit in a comment.

Assuming your form is called UserForm2 and contains these controls:  txtDossier, txtDate and txtContainer then you can add the following code to a normal module.

As @Czeskleba said - to solve your problem we'd have to write the code for you, which isn't what this site is about.  Have a look at FIND to track down the records you're looking for.  Excel Macro Mastery also has good explanations on how to use it.

Public Sub Test()

    'Open first instance of form.

    Dim frm As UserForm2
    Set frm = New UserForm2

    With frm
        .Caption = "First Displayed Form"
        .txtDossier = ThisWorkbook.Worksheets("Sheet1").Range("B1")
        With .txtDate
            .Value = Format(Date, "dd-mmm-yy")
            .Enabled = False
        End With
        .txtContainer = "Some data in here"
        .Show
    End With

    'Open second instance of form.
    'If forms ShowModal property is set to TRUE then this code will run after first form is (manually) closed.
    'If ShowModal is set to FALSE then two forms will appear.

    Dim frm2 As UserForm2
    Set frm2 = New UserForm2

    With frm2
        With .txtDossier
            .BackColor = RGB(224, 224, 224)
        End With
        .Caption = "Second Displayed Form"
        .txtDate = Format(DateSerial(2019, 12, 25), "ddd dd-mmm-yy")
        .txtContainer.Enabled = False
        .Show
    End With

End Sub


问:
Print Matching line and one line before from the matched line
looking forward to print Matching line in a file on Linux host and one line before from the matched line included into one line.

Below is just the content from the log file:

```<code>[2020/02/18 08:25:21.229198,  1] ../source3/lib/smbldap.c:1206(get_cached_ldap_connect)
  Connection to LDAP server failed for the 1 try!
[2020/02/18 08:25:21.229221,  2] ../source3/passdb/pdb_ldap_util.c:287(smbldap_search_domain_info)
  smbldap_search_domain_info: Problem during LDAPsearch: Timed out
</code>```

What i have tried:

I have tried following with grep and sed which somehow works..

```<code>$ egrep -B 1 "failed|Timed" /var/log/samba/smbd.log.old |tr -d "\n" | sed "s/--/\n/g"

[2020/02/18 08:25:21.229198,  1] ../source3/lib/smbldap.c:1206(get_cached_ldap_connect)  Connection to LDAP server failed for the 1 try!
[2020/02/18 08:25:21.229221,  2] ../source3/passdb/pdb_ldap_util.c:287(smbldap_search_domain_info) smbldap_search_domain_info: Problem during LDAPsearch: Timed out
</code>```

This does not looks to be a cleaner solution, i'm looking forward some expert one lines, one liner is acceptable with awk, sed, grep or even python.

答:
This might work for you (GNU sed):

```<code>sed -n 'N;/\n.*\(failed\|Timed\)/s/\n//p;D' file
</code>```

Turn off implicit printing. Append the next line. If the appended line contains failed or Timed, delete the newline and print the result. Delete the first line in the pattern space and repeat.

Body:
looking forward to print Matching line in a file on Linux host and one line before from the matched line included into one line.

Below is just the content from the log file:

[2020/02/18 08:25:21.229198,  1] ../source3/lib/smbldap.c:1206(get_cached_ldap_connect)
  Connection to LDAP server failed for the 1 try!
[2020/02/18 08:25:21.229221,  2] ../source3/passdb/pdb_ldap_util.c:287(smbldap_search_domain_info)
  smbldap_search_domain_info: Problem during LDAPsearch: Timed out

What i have tried:

I have tried following with grep and sed which somehow works..

$ egrep -B 1 "failed|Timed" /var/log/samba/smbd.log.old |tr -d "\n" | sed "s/--/\n/g"

[2020/02/18 08:25:21.229198,  1] ../source3/lib/smbldap.c:1206(get_cached_ldap_connect)  Connection to LDAP server failed for the 1 try!
[2020/02/18 08:25:21.229221,  2] ../source3/passdb/pdb_ldap_util.c:287(smbldap_search_domain_info) smbldap_search_domain_info: Problem during LDAPsearch: Timed out

This does not looks to be a cleaner solution, i'm looking forward some expert one lines, one liner is acceptable with awk, sed, grep or even python.

Body:
This might work for you (GNU sed):

sed -n 'N;/\n.*\(failed\|Timed\)/s/\n//p;D' file

Turn off implicit printing. Append the next line. If the appended line contains failed or Timed, delete the newline and print the result. Delete the first line in the pattern space and repeat.


问:
Angular showing json object in html table
Hello guys i have json data from firestore and i want to display these data in html table.

This is my customer-list.component.html

```<code><body>
  <div class="container">
    <div class="title">
      <h3>Customer Table</h3>
    </div>
    <div class="row">
      <div class="col-md-12">
      </div>
      <div class="col-lg-8 col-md-10 ml-auto mr-auto">
        <div class="table-responsive">
          <table class="table">
            <thead>
              <tr>
                <th class="text-center">#</th>
                <th>Name</th>
                <th>Age</th>
                <th>Active</th>
              </tr>
            </thead>
            <tbody>
              <div *ngFor="let customer of customers" style="width: 300px;">
                <app-customer-details [customer]='customer'></app-customer-details>
              </div>
        <div style="margin-top:20px;">
          <button type="button" class="button btn-danger" (click)='deleteCustomers()'>Delete All</button>
        </div>
        </tbody>
        </table>
      </div>
      </div>
</code>```

Seems like there is nothing wrong in there.

This is my customer-details.component.html

```<code><div *ngIf="customer">
<tr>
   <td>
       <label>First Name: </label> {{customer.name}}
     </td>
     <td>
       <label>Age: </label> {{customer.age}}
     </td>
     <td>
       <label>Active: </label> {{customer.active}}
     </td>
     <span class="button is-small btn-primary" *ngIf='customer.active' (click)='updateActive(false)'>Inactive</span>

     <span class="button is-small btn-primary" *ngIf='!customer.active' (click)='updateActive(true)'>Active</span>

     <span class="button is-small btn-danger" (click)='deleteCustomer()'>Delete</span>
</tr>
</div>
</code>```

But my table output is :

Thanks for answers.

答:
Don´t limit the width of a customer´s component to 300px, like you did here:</p>

```<code><div *ngFor="let customer of customers" style="width: 300px;">
</code>```

Body:
Hello guys i have json data from firestore and i want to display these data in html table.

This is my customer-list.component.html

Customer Table

                #
                Name
                Age
                Active

                <app-customer-details [customer]='customer'></app-customer-details>

          <button type="button" class="button btn-danger" (click)='deleteCustomers()'>Delete All</button>

Seems like there is nothing wrong in there.

This is my customer-details.component.html

       First Name:  {{customer.name}}

       Age:  {{customer.age}}

       Active:  {{customer.active}}

     Inactive

     Active

     Delete

But my table output is :

Thanks for answers.

Body:
Don´t limit the width of a customer´s component to 300px, like you did here:

<div *ngFor="let customer of customers" style="width: 300px;">


问:
How to change order inside foreach using wp_enqueue_script?
I have a created a for each loop to load all the script files from my build folder dynamically in the footer with for development and production mode. This way I don't need to manually replace the script files.

But I have a problem, I don't know how to change the order of the files to a specific order.

It should be: Runtime, Vendors, Main.

This is my PHP code:

```<code>// First check if "JS" folder exist to prevent errors.
if(is_dir(THEME_DIR_ASSETS . '/js')) {
    // Enqueue all scripts.
    function nm_enqueue_scripts() {
    $directoryJS = new DirectoryIterator(THEME_DIR_ASSETS . '/js');

        wp_deregister_script('jquery');
        wp_enqueue_script('jquery', 'https://code.jquery.com/jquery-2.2.4.min.js', array(), null, false);

        foreach ($directoryJS as $file) {
            if (pathinfo($file, PATHINFO_EXTENSION) === 'js') {
            $fullName = basename($file);
            $name = substr(basename($fullName), 0, strpos(basename($fullName), '.'));

            wp_enqueue_script($name, THEME_DIR_JS . '/' . $fullName, $name, null, true);
            }
        }
    }
    add_action('wp_enqueue_scripts', 'nm_enqueue_scripts');
}
</code>```

How can I do this?

答:
You would need to specify the dependencies of each file to be able to enqueue them in an order you want.
So in the $directoryJS data, you can set dependencies of each script so that it looks like this:

```<code>$directoryJS = [
[
'script_name' => 'some-name'
'script_url' => 'path to script',
'deps' => [ 'other-file-name']
],
[
'script_name' => 'other-file-name'
'script_url' => 'path to other script',
'deps' => [ ]
]
]
</code>```

In the foreach statement the enqueue script function will look like this:
wp_enqueue_script($script_name, THEME_DIR_JS . '/' . $fullName, $deps, '', true);.

In this case WP will enqueue 'other-file-name' script before 'some-name' script.

Body:
I have a created a for each loop to load all the script files from my build folder dynamically in the footer with for development and production mode. This way I don't need to manually replace the script files.

But I have a problem, I don't know how to change the order of the files to a specific order.

It should be: Runtime, Vendors, Main.

This is my PHP code:

// First check if "JS" folder exist to prevent errors.
if(is_dir(THEME_DIR_ASSETS . '/js')) {
    // Enqueue all scripts.
    function nm_enqueue_scripts() {
    $directoryJS = new DirectoryIterator(THEME_DIR_ASSETS . '/js');

        wp_deregister_script('jquery');
        wp_enqueue_script('jquery', 'https://code.jquery.com/jquery-2.2.4.min.js', array(), null, false);

        foreach ($directoryJS as $file) {
            if (pathinfo($file, PATHINFO_EXTENSION) === 'js') {
            $fullName = basename($file);
            $name = substr(basename($fullName), 0, strpos(basename($fullName), '.'));

            wp_enqueue_script($name, THEME_DIR_JS . '/' . $fullName, $name, null, true);
            }
        }
    }
    add_action('wp_enqueue_scripts', 'nm_enqueue_scripts');
}

How can I do this?

Body:
You would need to specify the dependencies of each file to be able to enqueue them in an order you want.
So in the $directoryJS data, you can set dependencies of each script so that it looks like this:

$directoryJS = [
[
'script_name' => 'some-name'
'script_url' => 'path to script',
'deps' => [ 'other-file-name']
],
[
'script_name' => 'other-file-name'
'script_url' => 'path to other script',
'deps' => [ ]
]
]

In the foreach statement the enqueue script function will look like this:
wp_enqueue_script($script_name, THEME_DIR_JS . '/' . $fullName, $deps, '', true);.

In this case WP will enqueue 'other-file-name' script before 'some-name' script.


问:
react native scrollview not scrolling on android
I have the following component:

```<code>export default class StoreComponent extends Component {
  render() {
    return (
      <View style={styles.container}>
        <ScrollView contentContainerStyle={styles.scroll}>
          <StoreCarouselComponent />
          <StoreDiscountComponent />
          <StoreDetailsComponent />
        </ScrollView>
      </View>
    );
  }
}
</code>```

with this style

```<code>import { StyleSheet, Dimensions, } from 'react-native';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#ffffff',
  },
  scroll: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center'
  },
  image: {
    width: Dimensions.get('window').width,
    height: 350,
  },
  box: {
    width: Dimensions.get('window').width - 30,
    position: 'absolute',
    shadowColor: '#000000',
    shadowOpacity: 0.34,
    shadowRadius: 5,
    shadowOffset: {
      width: 0,
      height: 10
    },
    elevation: 10,
    borderTopLeftRadius: 10,
    borderTopRightRadius: 10,
    borderBottomLeftRadius: 10,
    borderBottomRightRadius: 10,
    borderColor: 'lightgrey',
    backgroundColor: '#ffffff',
    padding: 10,
    marginTop: 410,

  },
  boxDiscount: {
    width: Dimensions.get('window').width - 30,
    position: 'absolute',
    shadowColor: '#000000',
    shadowOpacity: 0.34,
    shadowRadius: 5,
    shadowOffset: {
      width: 0,
      height: 10
    },
    elevation: 10,
    borderTopLeftRadius: 10,
    borderTopRightRadius: 10,
    borderBottomLeftRadius: 10,
    borderBottomRightRadius: 10,
    borderColor: 'lightgrey',
    backgroundColor: '#253241',
    padding: 10,
    marginTop: 320,
  },
  title: {
    fontSize: 30
  },
  distance: {
    fontSize: 20,
    color: '#767676'
  },
  distanceElement: {
    fontSize: 20,
    color: '#44D9E6'
  },
  address: {
    fontSize: 20,
    color: '#767676'
  },
  category: {
    fontSize: 20,
    color: '#767676',
  },
  categoryElement: {
    fontSize: 20,
    color: '#44D9E6',
  },
  hr: {
    borderBottomColor: 'lightgrey',
    borderBottomWidth: 1,
  },
  icons: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
  }
});

export default styles;
</code>```

my scrollview works on ios but on android don't and I don't understand why

here a an image of the app and as you can see I need to scroll on android:

答: use flex: 1 inside style={styles.container} and delete it from .scroll

Body:
I have the following component:

export default class StoreComponent extends Component {
  render() {
    return (
      <View style={styles.container}>
        <ScrollView contentContainerStyle={styles.scroll}>
          <StoreCarouselComponent />
          <StoreDiscountComponent />
          <StoreDetailsComponent />
        </ScrollView>
      </View>
    );
  }
}

with this style

import { StyleSheet, Dimensions, } from 'react-native';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#ffffff',
  },
  scroll: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center'
  },
  image: {
    width: Dimensions.get('window').width,
    height: 350,
  },
  box: {
    width: Dimensions.get('window').width - 30,
    position: 'absolute',
    shadowColor: '#000000',
    shadowOpacity: 0.34,
    shadowRadius: 5,
    shadowOffset: {
      width: 0,
      height: 10
    },
    elevation: 10,
    borderTopLeftRadius: 10,
    borderTopRightRadius: 10,
    borderBottomLeftRadius: 10,
    borderBottomRightRadius: 10,
    borderColor: 'lightgrey',
    backgroundColor: '#ffffff',
    padding: 10,
    marginTop: 410,

  },
  boxDiscount: {
    width: Dimensions.get('window').width - 30,
    position: 'absolute',
    shadowColor: '#000000',
    shadowOpacity: 0.34,
    shadowRadius: 5,
    shadowOffset: {
      width: 0,
      height: 10
    },
    elevation: 10,
    borderTopLeftRadius: 10,
    borderTopRightRadius: 10,
    borderBottomLeftRadius: 10,
    borderBottomRightRadius: 10,
    borderColor: 'lightgrey',
    backgroundColor: '#253241',
    padding: 10,
    marginTop: 320,
  },
  title: {
    fontSize: 30
  },
  distance: {
    fontSize: 20,
    color: '#767676'
  },
  distanceElement: {
    fontSize: 20,
    color: '#44D9E6'
  },
  address: {
    fontSize: 20,
    color: '#767676'
  },
  category: {
    fontSize: 20,
    color: '#767676',
  },
  categoryElement: {
    fontSize: 20,
    color: '#44D9E6',
  },
  hr: {
    borderBottomColor: 'lightgrey',
    borderBottomWidth: 1,
  },
  icons: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
  }
});

export default styles;

my scrollview works on ios but on android don't and I don't understand why

here a an image of the app and as you can see I need to scroll on android:


问:
Eclipse Flash Builder 4: Syntax customization?
Using Flash Builder 4 (FB), is there a way to customize syntax highlighting for variable scope (member, parameter, local)?

I've heard this is possible in other Eclipse plugins and wondering if it is possible with FB or if not is there an easy way to add it manually?

Cheers,
Jono

答:
No.
Even in version 4.5, syntax highlighting is still the same primitive, useless crap.</p>

ContentLicense: CC BY-SA 2.5


问:
excel formula, detect building number in address
I have a column with addresses. I need a formula in excel to detect whether this data has a building number in the address line 1. Please see below sample data. I am trying to detect if this is a good address format or not in excel. This will help with my analysis. For example, H street below does not have a building number but 104 Washington Dr does have a building number. How can I build a formula to do this? Thanks!

答:
Try this:

```<code>=IF(SUMPRODUCT(COUNTIF(A2;"*"&{"1";"2";"3";"4";"5";"6";"7";"8";"9";"0"} & "*"))>0;"Yes";"No")
</code>```

This is how it works:

COUNTIF(A2;"*"&{"1";"2";"3";"4";"5";"6";"7";"8";"9";"0"} & "*") will return an array of 0 and 1 if any number is present at any part of the string (we use wildcards * before and after)

We sum up the array from step 1 with SUMPRODUCT.

If the final sum is 0, it means NO, otherway means YES, because at least one number is present.

Body:
Try this:

=IF(SUMPRODUCT(COUNTIF(A2;"*"&{"1";"2";"3";"4";"5";"6";"7";"8";"9";"0"} & "*"))>0;"Yes";"No")

This is how it works:

COUNTIF(A2;"*"&{"1";"2";"3";"4";"5";"6";"7";"8";"9";"0"} & "*") will return an array of 0 and 1 if any number is present at any part of the string (we use wildcards * before and after)

We sum up the array from step 1 with SUMPRODUCT.

If the final sum is 0, it means NO, otherway means YES, because at least one number is present.


答:
This is happening because you are passing an empty array as the second parameter of useEffect hook. This will make the hook only run once, on mount. If you want to run every time singledItemData changes, you need to pass it in the array.</p>

```<code>  useEffect(() => {
    console.log("singledItemData in useEffect = ", singledItemData);
    if (singledItemData.item) {
      setColor(singledItemData.item.color.name);
    }
  }, [singledItemData]);
</code>```

Title: Hook query retruning empty object inside useEffect but not after it Why?

Body:
So I have a query hook from which I wish to populate a state variable with data. The problem is, within useEffect the query is being returned as an {} object but after useEffect properly returns data (See image). I attempted to place useEffect after all the variable definitions but that issued a hook render error. What am I overlooking here and how do I resolve this?

  // Single Item Query
  const { data: singledItemData, error: errorSingleItem, loading: loadingSingleItem } = useQuery(
    SINGLE_ITEM_QUERY, {
      variables: {
        id: props.id,
      }
    }
  );

  useEffect(() => {
    console.log("singledItemData in useEffect = ", singledItemData);
    if (singledItemData.item) {
      setColor(singledItemData.item.color.name);
    }
  }, []);

  // User hook variables
  if (!user) return null;
  if (user.error) return <Error error={user.error} />;

  // Single Item Query variables

  if (loadingSingleItem) return
Loading...
;
  if (!singledItemData.item) return
No Item Found for ID {props.id}
;

  console.log("Single Item Data = ", singledItemData);

Body:
This is happening because you are passing an empty array as the second parameter of useEffect hook. This will make the hook only run once, on mount. If you want to run every time singledItemData changes, you need to pass it in the array.

  useEffect(() => {
    console.log("singledItemData in useEffect = ", singledItemData);
    if (singledItemData.item) {
      setColor(singledItemData.item.color.name);
    }
  }, [singledItemData]);


问:
Extracting Nupkg files using command line
Firstly, I do not want to use Visual Studio at all when dealing with the certain .nupkg files.

I know there is a tool called NuGet Package Explorer and this can export nupkg files to a certain file location using a gui, but I'm looking to setup a MSBuild task to run and unpack about 50 .nupkg files, using the command line.

My question is, is there a tool you can use via the command line which will unpack .nupkg files to a specified file location?

答:
This worked for me:</p>
```<code>Rename-Item -Path A_Package.nupkg -NewName A_Package.zip

Expand-Archive -Path A_Package.zip -DestinationPath C:\Reference
</code>```

Body:
This worked for me:

Rename-Item -Path A_Package.nupkg -NewName A_Package.zip

Expand-Archive -Path A_Package.zip -DestinationPath C:\Reference


问:
TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable
I am trying to map from a service call but getting an error.
Looked at subscribe is not defined in angular 2? and it said that in order to subscribe we need to return from inside the operators. I have return statements as well.

Here's my code:

checkLogin(): Observable<boolean> {
  return this.service
    .getData()
    .map(
      (response) => {
        this.data = response;
        this.checkservice = true;
        return true;
      },
      (error) => {
        // debugger;
        this.router.navigate(["newpage"]);
        console.log(error);
        return false;
      }
    )
    .catch((e) => {
      return e;
    });
}
```

Error log:

TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable

答:
In regard to the "You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable" error.

This could happen if you import { Observable } from 'rxjs' after (below) some module/function/whatever, which actually uses it.

Solution: move this import above the import of that module.

Body:
I am trying to map from a service call but getting an error.
Looked at subscribe is not defined in angular 2? and it said that in order to subscribe we need to return from inside the operators. I have return statements as well.

Here's my code:

checkLogin(): Observable<boolean> {
  return this.service
    .getData()
    .map(
      (response) => {
        this.data = response;
        this.checkservice = true;
        return true;
      },
      (error) => {
        // debugger;
        this.router.navigate(["newpage"]);
        console.log(error);
        return false;
      }
    )
    .catch((e) => {
      return e;
    });
}

Error log:

TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable


问:
How can I add root certs into my existing truststore.jks file using kubectl?
I am new to kubernetes and trying to add root certs to my existing secrets truststore.jks file. Using get secret mysecret -o yaml. I am able to view the details of truststore file inside mysecret but not sure how to replace with new truststore file or to edit the existing one with latest root certs. Can anyone help me to get the correct command to do this using kubectl?

Thanks

答:
A Secret is an object that contains a small amount of sensitive data such as a password, a token, or a key. There is an official documentation about Kubernetes.io: Secrets.

Assuming that you created your secret by:

$ kubectl create secret generic NAME_OF_SECRET --from-file=keystore.jks

You can edit your secret by invoking command:

$ kubectl edit secret NAME_OF_SECRET

It will show you YAML definition similar to this:

```<code>apiVersion: v1
data:
  keystore.jks: HERE_IS_YOUR_JKS_FILE
kind: Secret
metadata:
  creationTimestamp: "2020-02-20T13:14:24Z"
  name: NAME_OF_SECRET
  namespace: default
  resourceVersion: "430816"
  selfLink: /api/v1/namespaces/default/secrets/jks-old
  uid: 0ce898af-8678-498e-963d-f1537a2ac0c6
type: Opaque
</code>```

To change it to new keystore.jks you would need to base64 encode it and paste in place of old one (HERE_IS_YOUR_JKS_FILE)

You can get a base64 encoded string by:
cat keystore.jks | base64

After successfully editing your secret it should give you a message:
secret/NAME_OF_SECRET edited

Also you can look on this StackOverflow answer

It shows a way to replace existing configmap but with a little of modification it can also replace a secret!

Example below:

Create a secret with keystore-old.jks:

$ kubectl create secret generic my-secret --from-file=keystore-old.jks

Update it with keystore-new.jks:

$ kubectl create secret generic my-secret --from-file=keystore-new.jks -o yaml --dry-run | kubectl replace -f -

Treating keystore.jks as a file allows you to use a volume mount to mount it to specific location inside a pod.

Example YAML below creates a pod with secret mounted as volume:

```<code>apiVersion: v1
kind: Pod
metadata:
  name: ubuntu
spec:
  containers:
  - name: ubuntu
    image: ubuntu
    command:
      - sleep
      - "360000"
    volumeMounts:
    - name: secret-volume
      mountPath: "/etc/secret"
  volumes:
  - name: secret-volume
    secret:
      secretName: NAME_OF_SECRET
</code>```

Take a specific look on:

```<code>    volumeMounts:
    - name: secret-volume
      mountPath: "/etc/secret"
  volumes:
  - name: secret-volume
    secret:
      secretName: NAME_OF_SECRET
</code>```

This part will mount your secret inside your /etc/secret/ directory. It will be available there with a name keystore.jks

A word about mounted secrets:

Mounted Secrets are updated automatically

When a secret currently consumed in a volume is updated, projected keys are eventually updated as well. The kubelet checks whether the mounted secret is fresh on every periodic sync.

--  Kubernetes.io: Secrets.

Please let me know if you have any questions regarding that.

Body:
A Secret is an object that contains a small amount of sensitive data such as a password, a token, or a key. There is an official documentation about Kubernetes.io: Secrets.

Assuming that you created your secret by:

$ kubectl create secret generic NAME_OF_SECRET --from-file=keystore.jks

You can edit your secret by invoking command:

$ kubectl edit secret NAME_OF_SECRET

It will show you YAML definition similar to this:

apiVersion: v1
data:
  keystore.jks: HERE_IS_YOUR_JKS_FILE
kind: Secret
metadata:
  creationTimestamp: "2020-02-20T13:14:24Z"
  name: NAME_OF_SECRET
  namespace: default
  resourceVersion: "430816"
  selfLink: /api/v1/namespaces/default/secrets/jks-old
  uid: 0ce898af-8678-498e-963d-f1537a2ac0c6
type: Opaque

To change it to new keystore.jks you would need to base64 encode it and paste in place of old one (HERE_IS_YOUR_JKS_FILE)

You can get a base64 encoded string by:
cat keystore.jks | base64

After successfully editing your secret it should give you a message:
secret/NAME_OF_SECRET edited

Also you can look on this StackOverflow answer

It shows a way to replace existing configmap but with a little of modification it can also replace a secret!

Example below:

Create a secret with keystore-old.jks:

$ kubectl create secret generic my-secret --from-file=keystore-old.jks

Update it with keystore-new.jks:

$ kubectl create secret generic my-secret --from-file=keystore-new.jks -o yaml --dry-run | kubectl replace -f -

Treating keystore.jks as a file allows you to use a volume mount to mount it to specific location inside a pod.

Example YAML below creates a pod with secret mounted as volume:

apiVersion: v1
kind: Pod
metadata:
  name: ubuntu
spec:
  containers:
  - name: ubuntu
    image: ubuntu
    command:
      - sleep
      - "360000"
    volumeMounts:
    - name: secret-volume
      mountPath: "/etc/secret"
  volumes:
  - name: secret-volume
    secret:
      secretName: NAME_OF_SECRET

Take a specific look on:

    volumeMounts:
    - name: secret-volume
      mountPath: "/etc/secret"
  volumes:
  - name: secret-volume
    secret:
      secretName: NAME_OF_SECRET

This part will mount your secret inside your /etc/secret/ directory. It will be available there with a name keystore.jks

A word about mounted secrets:

Mounted Secrets are updated automatically

When a secret currently consumed in a volume is updated, projected keys are eventually updated as well. The kubelet checks whether the mounted secret is fresh on every periodic sync.

--  Kubernetes.io: Secrets.

Please let me know if you have any questions regarding that.


答:
You can use a proper regex pattern to match your request:

```<code>def key_creator():
    log_data = read_log()

    keys = []
    for line in log_data:
        # print(line)
        search = re.search('/j_(DDD_\d{5})\n', line)
        if search is not None:
             keys.append(search.group(1))
             print(line)
    return keys
</code>```

The pattern requires the string DDD followed by an underscore and exactly 5 digits. The return value is non if the string is not found, and otherwise it returns two groups: one with the whole match (group(0)) and one with only the content of the parenthesis (group(1)), which is already what you are looking for.

Title: The most pythonic way to parse specific sub-string in a string?

Body:
I have the following log and want to extract the second "DDD-xxxxx" ID from each entry (if exist a second DDD id):

cs:444 - br:/main/j_DDD-50535/DDD-68009
cs:445 - br:/main/j_DDD-50535/j_DDD-70220
cs:446 - br:/main/j_DDD-50535/j_DDD-70117
cs:447-Merge from branch: /main/j_DDD-50544/j_DDD-61183
Requested by: Smith, John (UserID1)
cs:448-Merge from branch: /main/j_DDD-4822
Requested by: Grant, Huge (userID2)
cs:449-Daily automated release of 3.5.5.4

Using regex I found a workaround to get them but I think it should be possible to get much easier:

def read_log():
    log_file_name = "log"
    with open(log_file_name, "r") as file:
        log_file = file.read().split("cs:")
    return log_file

def key_creator():
    log_data = read_log()

    keys = []
    for line in log_data:
        # print(line)
        if line[:5].isdigit():
            search = re.search('/j_(.*)\n', line)
            if hasattr(search, "group"):
                search = search.group(1).split('/j_')

                if 1 < len(search) and search[1][:3] == "DDD":
                    keys.append(search[1])
                    print(line)
    return keys

key_creator()

Edit: Just to clarify:
 - the string DDD can be followed by indeterminate number of digits, (DDD-23, DDD-342, DDD-4842, DDD-44332... would be possibles entries as well)

Body:
You can use a proper regex pattern to match your request:

def key_creator():
    log_data = read_log()

    keys = []
    for line in log_data:
        # print(line)
        search = re.search('/j_(DDD_\d{5})\n', line)
        if search is not None:
             keys.append(search.group(1))
             print(line)
    return keys

The pattern requires the string DDD followed by an underscore and exactly 5 digits. The return value is non if the string is not found, and otherwise it returns two groups: one with the whole match (group(0)) and one with only the content of the parenthesis (group(1)), which is already what you are looking for.


问:
How do I get find my "CheckBox" item that is in the ItemTemplate?
I have the following (very simple) ItemsControl:

```<code><ItemsControl Name="BlahList" ItemsSource="{Binding Blah}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <CheckBox Name="MyCheckBox" Content="{Binding Text}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>
</code>```

In code, I would like to do the following:

```<code>foreach (var dahCurrentItem in BlahList.Items)
{
    var ItemCheckBox = BlahList.GimmeMyControl(dahCurrentItem, "MyCheckBox")

    // I'm going to do something with the check box here...
}
</code>```

How do I do that?

答:
Firstly, don't if there's any way you can avoid it. It's much cleaner to bind the various properties of the CheckBox to your view model rather than trying to pull them out manually.

That said, if you need to get to your CheckBox, you can should be able to use code like this:

```<code>var container = _itemsControl.ItemContainerGenerator.ContainerFromItem(dahCurrentItem) as FrameworkElement;
var checkBox = container.FindName("MyCheckBox") as CheckBox;
</code>```

OwnerDisplayName: Timothy Khouri

Body:
I have the following (very simple) ItemsControl:

<ItemsControl Name="BlahList" ItemsSource="{Binding Blah}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <CheckBox Name="MyCheckBox" Content="{Binding Text}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

In code, I would like to do the following:

foreach (var dahCurrentItem in BlahList.Items)
{
    var ItemCheckBox = BlahList.GimmeMyControl(dahCurrentItem, "MyCheckBox")

    // I'm going to do something with the check box here...
}

How do I do that?

Body:
Firstly, don't if there's any way you can avoid it. It's much cleaner to bind the various properties of the CheckBox to your view model rather than trying to pull them out manually.

That said, if you need to get to your CheckBox, you can should be able to use code like this:

var container = _itemsControl.ItemContainerGenerator.ContainerFromItem(dahCurrentItem) as FrameworkElement;
var checkBox = container.FindName("MyCheckBox") as CheckBox;

OwnerDisplayName: Kent Boogaart


问:
How can I get my inner div to center vertically and horizontally
I have the following code:

```<code><div id="footercenter">

    <div id="footer_copyright">abc</div><div id="footer_message">def</div>

</div>
</code>```

The inner two divs appear next to each other but at the top of the footercenter. Is there a way that I can make these appear centered vertically?

Hope for some help.

Mandy J

答:
Check out...

http://www.infinitywebdesign.com/research/cssverticalcentereddiv.htm

View the page source and CSS

Body:
I have the following code:

abc

def

The inner two divs appear next to each other but at the top of the footercenter. Is there a way that I can make these appear centered vertically?

Hope for some help.

Mandy J