问:
Parsing numbers from standard input stream using sscanf in C
Parsing numbers from standard input stream using sscanf in C

I have a text file which contains rows that start with a letter and then are followed by unsigned integers (some times a pair and other times just one).  At the begging of each row is a letter to categorize the row.  (see below) I’m able to get the content of the file and read it to screen. However, I am struggling with using sscanf to extract the letter and each integer from each row. So the results would be char, int and int all in separate variables - just using the ‘a’ row as an example.  I’ve been using the below code. The best I’ve gotten is that sscanf causes the strange behavior of giving all zeros. Again, I’m trying to get the char and each int into separate variables.

Sample of rows from text file

```<code>a -1109180 699692587
a 1213834231 -226769626
c 994957275 2082945813
e 1213834231

//The Code Used//////////////

char *line = NULL;
size_t size;
int results;

int val1;
int val2;

while (getline(&line, &size, stdin) != -1){

    if(strstr(line,"a") != NULL){

        sscanf(line,"Val1 and Val2: %d %d", val1,val2);
        printf("Value1 %d\n",val1);
        printf("Value2 %d\n",val2);

    }

//This prints each line in file
printf("%s\n", line);

}
</code>```

Kinda clueless on what’s missing here. Is sscanf the best method to achieve this in C or is there a simpler alternative?  Thanks in advance.

答:
Ethan, some times you just need to slow down to help C fall into place. I your case you have data that evidently will contain a classification character in the beginning row of each line. That can be following by one or two number you need to read and handle accordingly. Your problem is defined by your dataset.

Thankfully, you can utilize line-oriented input functions fgets or getline and then a single call to sscanf for each like to handle all cases. After reading your line, you pass it to a sscanf call similar to the following:

```<code>rtn = sscanf (buf, "%c %d %d", &c, &v1, &v2);  /* always check return */
</code>```

Preserving the return (i.e. the number of successful conversions that took place based upon your format string), you can began answering logical questions about the data you can expect. However before blindly comparing whether there are three, or two, or less conversions, you can answer simple questions just by looking at the first char in your buffer. If you require a lowercase letter to begin a valid line, then all you need to do is dereference your buffer to get the first char and then check if it is between 'a' - 'z'. If not, it's not a valid line. Similarly, if you check the first char and find it 0 (the terminating char) or '\n', then you know the line is empty and you need not bother with it any more. Those two test will filter out all the crud leaving you with at least lines that may match your criteria. For instance simply checking:

```<code>    if (rtn == 0) { /* no successful conversions took place */
        fprintf (stderr, "error: no values parsed from line.\n");
        continue;
    }

    if (!*buf || *buf == '\n') {    /* check if buf was empty line */
        fprintf (stderr, "error: line is empty or contians only newline.\n");
        continue;
    }

    if (*buf < 'a' || 'z' < *buf) {  /* check first char not a-z */
        fprintf (stderr, "error: no lowercase char beginning line.\n");
        continue;
    }
</code>```

gives you confidence that at least the line you operated on had a reasonable chance of matching what you are looking for.

Now you can either do and if ... else if .... else if .... (which is perfectly fine), or since you know you are primarily concerned with checking values 1-3, a switch statement makes sense for handling the remaining lines. For example, you could do something like the following to parse the value from those line that warrant a look:

```<code>    switch (rtn) {  /* switch on number of successful conversions */

        case 3:     /* three successful conversions */
            printf ("all values: '%c'  %d  %d\n", c, v1, v2);
            break;

        case 2:     /* two successful conversions */
            printf ("two values: '%c'  %d\n", c, v1);
            break;

        default:    /* one or less (need at least two */
            fprintf (stderr, "error: no character and value on line.\n");
    }
</code>```

Putting all those pieces together, you could do something similar to:

```<code>#include <stdio.h>

#define MAXC 256

int main (void) {

    char buf[MAXC] = "";

    while (fgets (buf, MAXC, stdin))    /* read each line into buf */
    {
        char c;
        int v1, v2, rtn;     /* vars for values and sscanf return */

        rtn = sscanf (buf, "%c %d %d", &c, &v1, &v2);

        if (rtn == 0) { /* no successful conversions took place */
            fprintf (stderr, "error: no values parsed from line.\n");
            continue;
        }

        if (!*buf || *buf == '\n') {    /* check if buf was empty line */
            fprintf (stderr, "error: line is empty or contians only newline.\n");
            continue;
        }

        if (*buf < 'a' || 'z' < *buf) {  /* check first char not a-z */
            fprintf (stderr, "error: no lowercase char beginning line.\n");
            continue;
        }

        switch (rtn) {  /* switch on number of successful conversions */

            case 3:     /* three successful conversions */
                printf ("all values: '%c'  %d  %d\n", c, v1, v2);
                break;

            case 2:     /* two successful conversions */
                printf ("two values: '%c'  %d\n", c, v1);
                break;

            default:    /* one or less (need at least two */
                fprintf (stderr, "error: no character and value on line.\n");
        }
    }

    return 0;
}
</code>```

Example Input Files

```<code>$ cat dat/input.txt
a -1109180 699692587
a 1213834231 -226769626
c 994957275 2082945813
e 1213834231
</code>```

And a little messier file:

```<code>$ cat dat/rows.txt
a -1109180 699692587
a quick brown fox jumps over the lazy dog
a 1213834231 -226769626

c 994957275 2082945813
227 isn't good
e 1213834231
</code>```

Should provide a good test to see if the code does what you need it to do. Running your data through the code provides:

Example Use/Output

```<code>$ /bin/sscanf_mixed <dat/input.txt
all values: 'a'  -1109180  699692587
all values: 'a'  1213834231  -226769626
all values: 'c'  994957275  2082945813
two values: 'e'  1213834231
</code>```

The messier file output:

```<code>$ ./bin/sscanf_mixed <dat/rows.txt
all values: 'a'  -1109180  699692587
error: no character and value on line.
all values: 'a'  1213834231  -226769626
error: line is empty or contians only newline.
all values: 'c'  994957275  2082945813
error: no lowercase char beginning line.
two values: 'e'  1213834231
</code>```

As you can see, both input files provided the same number of conversions, the second simply noting the error or problem that took place when non-conforming line are encountered.

Look things over and let me know if you have any questions. There are many ways to approach the logic of the problem, but which ever way you choose, you want to make sure you build all input routines flexible enough to handle those conditions (empty line, etc...) that you should reasonably expect to encounter in real world use.

Body:
Parsing numbers from standard input stream using sscanf in C

I have a text file which contains rows that start with a letter and then are followed by unsigned integers (some times a pair and other times just one).  At the begging of each row is a letter to categorize the row.  (see below) I’m able to get the content of the file and read it to screen. However, I am struggling with using sscanf to extract the letter and each integer from each row. So the results would be char, int and int all in separate variables - just using the ‘a’ row as an example.  I’ve been using the below code. The best I’ve gotten is that sscanf causes the strange behavior of giving all zeros. Again, I’m trying to get the char and each int into separate variables.

Sample of rows from text file

a -1109180 699692587
a 1213834231 -226769626
c 994957275 2082945813
e 1213834231

//The Code Used//////////////

char *line = NULL;
size_t size;
int results;

int val1;
int val2;

while (getline(&line, &size, stdin) != -1){

    if(strstr(line,"a") != NULL){

        sscanf(line,"Val1 and Val2: %d %d", val1,val2);
        printf("Value1 %d\n",val1);
        printf("Value2 %d\n",val2);

    }

//This prints each line in file
printf("%s\n", line);

}

Kinda clueless on what’s missing here. Is sscanf the best method to achieve this in C or is there a simpler alternative?  Thanks in advance.

Body:
Ethan, some times you just need to slow down to help C fall into place. I your case you have data that evidently will contain a classification character in the beginning row of each line. That can be following by one or two number you need to read and handle accordingly. Your problem is defined by your dataset.

Thankfully, you can utilize line-oriented input functions fgets or getline and then a single call to sscanf for each like to handle all cases. After reading your line, you pass it to a sscanf call similar to the following:

rtn = sscanf (buf, "%c %d %d", &c, &v1, &v2);  /* always check return */

Preserving the return (i.e. the number of successful conversions that took place based upon your format string), you can began answering logical questions about the data you can expect. However before blindly comparing whether there are three, or two, or less conversions, you can answer simple questions just by looking at the first char in your buffer. If you require a lowercase letter to begin a valid line, then all you need to do is dereference your buffer to get the first char and then check if it is between 'a' - 'z'. If not, it's not a valid line. Similarly, if you check the first char and find it 0 (the terminating char) or '\n', then you know the line is empty and you need not bother with it any more. Those two test will filter out all the crud leaving you with at least lines that may match your criteria. For instance simply checking:

    if (rtn == 0) { /* no successful conversions took place */
        fprintf (stderr, "error: no values parsed from line.\n");
        continue;
    }

    if (!*buf || *buf == '\n') {    /* check if buf was empty line */
        fprintf (stderr, "error: line is empty or contians only newline.\n");
        continue;
    }

    if (*buf < 'a' || 'z' < *buf) {  /* check first char not a-z */
        fprintf (stderr, "error: no lowercase char beginning line.\n");
        continue;
    }

gives you confidence that at least the line you operated on had a reasonable chance of matching what you are looking for.

Now you can either do and if ... else if .... else if .... (which is perfectly fine), or since you know you are primarily concerned with checking values 1-3, a switch statement makes sense for handling the remaining lines. For example, you could do something like the following to parse the value from those line that warrant a look:

    switch (rtn) {  /* switch on number of successful conversions */

        case 3:     /* three successful conversions */
            printf ("all values: '%c'  %d  %d\n", c, v1, v2);
            break;

        case 2:     /* two successful conversions */
            printf ("two values: '%c'  %d\n", c, v1);
            break;

        default:    /* one or less (need at least two */
            fprintf (stderr, "error: no character and value on line.\n");
    }

Putting all those pieces together, you could do something similar to:

#include <stdio.h>

#define MAXC 256

int main (void) {

    char buf[MAXC] = "";

    while (fgets (buf, MAXC, stdin))    /* read each line into buf */
    {
        char c;
        int v1, v2, rtn;     /* vars for values and sscanf return */

        rtn = sscanf (buf, "%c %d %d", &c, &v1, &v2);

        if (rtn == 0) { /* no successful conversions took place */
            fprintf (stderr, "error: no values parsed from line.\n");
            continue;
        }

        if (!*buf || *buf == '\n') {    /* check if buf was empty line */
            fprintf (stderr, "error: line is empty or contians only newline.\n");
            continue;
        }

        if (*buf < 'a' || 'z' < *buf) {  /* check first char not a-z */
            fprintf (stderr, "error: no lowercase char beginning line.\n");
            continue;
        }

        switch (rtn) {  /* switch on number of successful conversions */

            case 3:     /* three successful conversions */
                printf ("all values: '%c'  %d  %d\n", c, v1, v2);
                break;

            case 2:     /* two successful conversions */
                printf ("two values: '%c'  %d\n", c, v1);
                break;

            default:    /* one or less (need at least two */
                fprintf (stderr, "error: no character and value on line.\n");
        }
    }

    return 0;
}

Example Input Files

$ cat dat/input.txt
a -1109180 699692587
a 1213834231 -226769626
c 994957275 2082945813
e 1213834231

And a little messier file:

$ cat dat/rows.txt
a -1109180 699692587
a quick brown fox jumps over the lazy dog
a 1213834231 -226769626

c 994957275 2082945813
227 isn't good
e 1213834231

Should provide a good test to see if the code does what you need it to do. Running your data through the code provides:

Example Use/Output

$ /bin/sscanf_mixed <dat/input.txt
all values: 'a'  -1109180  699692587
all values: 'a'  1213834231  -226769626
all values: 'c'  994957275  2082945813
two values: 'e'  1213834231

The messier file output:

$ ./bin/sscanf_mixed <dat/rows.txt
all values: 'a'  -1109180  699692587
error: no character and value on line.
all values: 'a'  1213834231  -226769626
error: line is empty or contians only newline.
all values: 'c'  994957275  2082945813
error: no lowercase char beginning line.
two values: 'e'  1213834231

As you can see, both input files provided the same number of conversions, the second simply noting the error or problem that took place when non-conforming line are encountered.

Look things over and let me know if you have any questions. There are many ways to approach the logic of the problem, but which ever way you choose, you want to make sure you build all input routines flexible enough to handle those conditions (empty line, etc...) that you should reasonably expect to encounter in real world use.


来源: stackexchange

问:
how to change ouput format of mapreduce in hadoop?
I'm now practicing MapReduce in Hadoop,
and I got this code of matrix multiplication,
there isn't any question running it, but the output format is not what I want. I currently have:

```<code>00    66
01    78
02    90
</code>```

The format I want is like

```<code>0,0,66
0,1,78
0,2,90
</code>```

How do I change the code?

答:
You can change the format of the key in the Mapper. There are two places where it creates sKey. At the moment both lines (56 & 68) that look like:

```<code>sKey = row+i; (taking line 56 as an example)
</code>```

So you can just change it too:

```<code>sKey = row+","+i;
</code>```

Which will give you the format you're after.

ContentLicense: CC BY-SA 3.0

Body:
I'm now practicing MapReduce in Hadoop,
and I got this code of matrix multiplication,
there isn't any question running it, but the output format is not what I want. I currently have:

00    66
01    78
02    90

The format I want is like

0,0,66
0,1,78
0,2,90

How do I change the code?

Body:
You can change the format of the key in the Mapper. There are two places where it creates sKey. At the moment both lines (56 & 68) that look like:

sKey = row+i; (taking line 56 as an example)

So you can just change it too:

sKey = row+","+i;

Which will give you the format you're after.


问:
How to have code in the constructor that will NOT be executed at design time by Visual Studio?
I have a method call in the constructor of my user control that does something that won't work at design time (connecting to a database), and Visual Studio just bailed out when I tried to add that control to the GUI designer.

Sure, I can factor out that code to a separate method, but I don't like the idea that every time I use that object I need to remember to execute a certain method which is essential to that object's function (that's what the constructor is for!).

Is there something like a preprocessor symbol that I can mark my code with so that Visual Studio won't try to execute that code at design time?

答:
```<code>public SomeViewModel()
{
    if (!IsInDesignMode)
    {
        DoWork();
    }
}
</code>```

This code above if you are working on the actual UI that you are trying to work on. In a situation that you have something like this on a control, when you switch back to the designer for that control it's ok and no design time error. Now if you added that control that contains the code above to some other Form or another control via dragging it from the toolbox, it will show some design time errors.

Body:
public SomeViewModel()
{
    if (!IsInDesignMode)
    {
        DoWork();
    }
}

This code above if you are working on the actual UI that you are trying to work on. In a situation that you have something like this on a control, when you switch back to the designer for that control it's ok and no design time error. Now if you added that control that contains the code above to some other Form or another control via dragging it from the toolbox, it will show some design time errors.


问:
R- list of combination of 3 item sets from n items
I am getting a tough time in selecting the combinations of factors.

I have a vector as ("Ryan", "Leo", "Jack","Harry","Edd").

I want to get the list of of all combinations taken  3 of the names once.

I want to do it in R. Probably a resultant matrix will help me.

答:
We can use combn

```<code>t(combn(vec1, 3))
</code>```

Body:
We can use combn

t(combn(vec1, 3))


问:
Can't telnet to mysql on 3306 from other vps
My vps system verion is Ubuntu 16.04.1 x64.
Mysql version is 5.5.48

I have tried various methods to support 3306.

I have updated "etc/my.cnf" file to commented "'skip-networking" and have the "bind-address" to be 0.0.0.0;

and I use "netstat -an | grep 3306" to check the port status, I got the result:

```<code>tcp 0 0 0.0.0.0:3306 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.1:35498 127.0.0.1:3306 TIME_WAIT
</code>```

I had shut down my firewall, when I type "ufw status", I got:

```<code>Status: Inactive
</code>```

But after all the step and reboot my vps, I type "telnet 128.XXX.XXX.27 3306" on other vps, I got:

```<code>telnet: connect to address 128.XXX.XXX.27: Operation timed out
</code>```

But the strange thing is when I type "telnet localhost 3306" on the local vps, it works fine.

So What could be possible problems? I could provide more details you want.
Thanks a lot!

答:
I solved it.

It was a problem with the firewall.

Although I turned off the firewall, but the rule of the iptables are still affect all network requests, and use "iptables -L", I found that:

DROP     tcp  --  anywhere             anywhere             tcp dpt:mysql

The beginning is "DROP", and the end is "mysql".

After I removed this line, everything is fine.

Body:
My vps system verion is Ubuntu 16.04.1 x64.
Mysql version is 5.5.48

I have tried various methods to support 3306.

I have updated "etc/my.cnf" file to commented "'skip-networking" and have the "bind-address" to be 0.0.0.0;

and I use "netstat -an | grep 3306" to check the port status, I got the result:

tcp 0 0 0.0.0.0:3306 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.1:35498 127.0.0.1:3306 TIME_WAIT

I had shut down my firewall, when I type "ufw status", I got:

Status: Inactive

But after all the step and reboot my vps, I type "telnet 128.XXX.XXX.27 3306" on other vps, I got:

telnet: connect to address 128.XXX.XXX.27: Operation timed out

But the strange thing is when I type "telnet localhost 3306" on the local vps, it works fine.

So What could be possible problems? I could provide more details you want.
Thanks a lot!


问:
Python iterate nested dictionary to remove keys
I want to remove nested keys in a dictionary whose values are empty.

Example:

```<code>d = {'A': {'a': {1: [('string1', 'string2')]}},
     'B': {'b': {}},
     'C': {}
    }
</code>```

For each of the main keys, there is a sub key and a sub sub key.
If any of the key's values are empty, i want to remove the entire key.

However, i get the error :RuntimeError: dictionary changed size during iteration
when i loop through the dictionary to delete empty values.

```<code>for k,v in d.iteritems():
    if not v:
        del d[k]
    else:
        for a,b in v.iteritems():
        if not b:
            del d[k][a]
</code>```

desired output:

```<code>d = {'A': {'a': {1: [('string1', 'string2')]}}}
</code>```

答:
As others have pointed out, you're modifying the iterable as you iterate over it. Instead, you could make a deep copy of your dictionary to iterate over, which will allow you to edit the contents of the original datastructure.

```<code>import copy
d = {'A': {'a': {1: [('string1', 'string2')]}},
     'B': {'b': {}},
     'C': {}
    }

for k,v in copy.deepcopy(d).items():
    if not v:
        del d[k]
    else:
        for a,b in v.items():
            if not b:
                del d[k]
</code>```

out:

```<code>{'A': {'a': {1: [('string1', 'string2')]}}}
</code>```

Body:
I want to remove nested keys in a dictionary whose values are empty.

Example:

d = {'A': {'a': {1: [('string1', 'string2')]}},
     'B': {'b': {}},
     'C': {}
    }

For each of the main keys, there is a sub key and a sub sub key.
If any of the key's values are empty, i want to remove the entire key.

However, i get the error :RuntimeError: dictionary changed size during iteration
when i loop through the dictionary to delete empty values.

for k,v in d.iteritems():
    if not v:
        del d[k]
    else:
        for a,b in v.iteritems():
        if not b:
            del d[k][a]

desired output:

d = {'A': {'a': {1: [('string1', 'string2')]}}}

Body:
As others have pointed out, you're modifying the iterable as you iterate over it. Instead, you could make a deep copy of your dictionary to iterate over, which will allow you to edit the contents of the original datastructure.

import copy
d = {'A': {'a': {1: [('string1', 'string2')]}},
     'B': {'b': {}},
     'C': {}
    }

for k,v in copy.deepcopy(d).items():
    if not v:
        del d[k]
    else:
        for a,b in v.items():
            if not b:
                del d[k]

out:

{'A': {'a': {1: [('string1', 'string2')]}}}


问:
Swift - Fetch photos from album in CollectionView and keep resolution
I have a UICollectionView in which I load all of the user's photos from the photo album. All of the photos are fetched and stored in an array when the user opens the controller. Tapping a photo will create a subview with a black background and a bigger version of that photo. Tapping it again will remove it from the superView with a zoom-out transition.

My problem is that I don't know how to keep the original size of the photo as well as maintain a low execution time. Having 100+ photos load into a collection really hurts my load time.

I don't think it's necessary to fetch the pictures at a higher CGSize, because I actually want it to be the bounds of the cell (I have three cells per row).

Fetching images at 250 by 250 returns a 0.20 second execution time

Fetching images at 300 by 300 returns a 3.0 seconds execution time

What I want to achieve is to keep a very low execution time, have crisp thumbnails and a high resolution version of that photo when tapped. Do I have to create a second thread to load everything in the background or is it better to not call my function in my viewDidLoad?

```<code>var imageArray = [UIImage]()

func getPhotosFromAlbum() {

    let imageManager = PHImageManager.default()

    let requestOptions = PHImageRequestOptions()
    requestOptions.isSynchronous = true
    requestOptions.deliveryMode = .highQualityFormat

    let fetchOptions = PHFetchOptions()
    fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]

    let fetchResult: PHFetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions)

        if fetchResult.count > 0 {

            for i in 0..<fetchResult.count {

                imageManager.requestImage(for: fetchResult.object(at: i), targetSize: CGSize(width: 300, height: 300), contentMode: .aspectFill, options: requestOptions, resultHandler: { image, error in

                    self.imageArray.append(image!)
                })
            }
        } else {
                self.collectionView?.reloadData()
    }
}
</code>```

答: Generally, if you are doing some heavy processing, it is better to do it in a background thread so that you don't lock up your main thread or make UI interaction sluggish. Of course, in that case, do remember to do any UI updates on the main thread.</p>

Body:
I have a UICollectionView in which I load all of the user's photos from the photo album. All of the photos are fetched and stored in an array when the user opens the controller. Tapping a photo will create a subview with a black background and a bigger version of that photo. Tapping it again will remove it from the superView with a zoom-out transition.

My problem is that I don't know how to keep the original size of the photo as well as maintain a low execution time. Having 100+ photos load into a collection really hurts my load time.

I don't think it's necessary to fetch the pictures at a higher CGSize, because I actually want it to be the bounds of the cell (I have three cells per row).

Fetching images at 250 by 250 returns a 0.20 second execution time

Fetching images at 300 by 300 returns a 3.0 seconds execution time

What I want to achieve is to keep a very low execution time, have crisp thumbnails and a high resolution version of that photo when tapped. Do I have to create a second thread to load everything in the background or is it better to not call my function in my viewDidLoad?

var imageArray = [UIImage]()

func getPhotosFromAlbum() {

    let imageManager = PHImageManager.default()

    let requestOptions = PHImageRequestOptions()
    requestOptions.isSynchronous = true
    requestOptions.deliveryMode = .highQualityFormat

    let fetchOptions = PHFetchOptions()
    fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]

    let fetchResult: PHFetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions)

        if fetchResult.count > 0 {

            for i in 0..<fetchResult.count {

                imageManager.requestImage(for: fetchResult.object(at: i), targetSize: CGSize(width: 300, height: 300), contentMode: .aspectFill, options: requestOptions, resultHandler: { image, error in

                    self.imageArray.append(image!)
                })
            }
        } else {
                self.collectionView?.reloadData()
    }
}


问:
Simplest way to read JSON from a URL in Java
This might be a dumb question but what is the simplest way to read and parse JSON from URL in Java?

In Groovy, it's a matter of few lines of code. Java examples that I find are ridiculously long (and have huge exception handling block).

All I want to do is to read the content of this link.

答:
I am not sure if this is efficient, but this is one of the possible ways:

Read json from url use url.openStream() and read contents into a string.

construct a JSON object with this string (more at json.org)

```<code>JSONObject(java.lang.String source)
      Construct a JSONObject from a source JSON text string.
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am not sure if this is efficient, but this is one of the possible ways:

Read json from url use url.openStream() and read contents into a string.

construct a JSON object with this string (more at json.org)

JSONObject(java.lang.String source)
      Construct a JSONObject from a source JSON text string.

ContentLicense: CC BY-SA 2.5


问:
Show and hide loading at the beginning and end of the observable subscription
I want to show and hide the loading at the beginning and end of the observable subscription, but not succeeding. I think it's something related to forkJoin or switchMap. Below is what I've tried:

```<code>this.query
  .debounceTime(400)
  .distinctUntilChanged()
  .switchMap((query) => {
    // code...
    return Observable.forkJoin(sources);
  })
  .finally(() => console.log('completed')) // never called
  .subscribe((hashtags) => {
    // code...
  }, (error) => {
    console.log(error);
  }, () => {
    console.log('completed'); // never called
  });
</code>```

答:
A very common problem with forkJoin is that all its source Observables need to emit at least one value and complete before the forkJoin emits anything.

It's hard to say what you're doing inside switchMap() and what this.query is but both the complete signals and the finally() operator are called only when the Observable chain completes. So if you're receiving items in the next callback (that's the (hashtags) => { // code... } function) and you know the completed string is never printed that it seems like the source never completes and thus either finally() nor the complete callbacks are called.

Body:
I want to show and hide the loading at the beginning and end of the observable subscription, but not succeeding. I think it's something related to forkJoin or switchMap. Below is what I've tried:

this.query
  .debounceTime(400)
  .distinctUntilChanged()
  .switchMap((query) => {
    // code...
    return Observable.forkJoin(sources);
  })
  .finally(() => console.log('completed')) // never called
  .subscribe((hashtags) => {
    // code...
  }, (error) => {
    console.log(error);
  }, () => {
    console.log('completed'); // never called
  });


问:
lists with parenthesis using only javascript or jquery?
I need a list (
 and
) with parenthesis like this.

```<code>(1) List1
(2) List2
(3) List3
(4) List4
</code>```

The important thing is that I need this using only javascript or jQuery without using external, internal css.

This is my code

```<code>$("ol").css("counter-reset", "list");
$("ol li").css("list-style", "none");
$("ol li:before").css({"content": "counter(list, lower-alpha) ') '", "counter-increment": "list"});
</code>```

答:
You Can acheive this with the help of a line css and js code as given below :</p>

```<code><script>
$(document).ready(function(){
    var length = $('ol li').length;
    for(i=1;i<=length;i++){
        $('ol li:nth-child('+i+')').children('span').html('('+i+') ');
    }
});
</script>

And HTML:

<body>

<ol>
    <li><span class="list_number"></span>Stone</li>
    <li><span class="list_number"></span>Paper</li>
    <li><span class="list_number"></span>Scissor</li>
</ol>

</body>

My CSS:

<style>
ol { list-style-type:none; }
</style>

Hope This is Helpful
</code>```

Body:
I need a list (
 and
) with parenthesis like this.

(1) List1
(2) List2
(3) List3
(4) List4

The important thing is that I need this using only javascript or jQuery without using external, internal css.

This is my code

$("ol").css("counter-reset", "list");
$("ol li").css("list-style", "none");
$("ol li:before").css({"content": "counter(list, lower-alpha) ') '", "counter-increment": "list"});

Body:
You Can acheive this with the help of a line css and js code as given below :

<script>
$(document).ready(function(){
    var length = $('ol li').length;
    for(i=1;i<=length;i++){
        $('ol li:nth-child('+i+')').children('span').html('('+i+') ');
    }
});
</script>

And HTML:

<body>

<ol>
    <li><span class="list_number"></span>Stone</li>
    <li><span class="list_number"></span>Paper</li>
    <li><span class="list_number"></span>Scissor</li>
</ol>

</body>

My CSS:

<style>
ol { list-style-type:none; }
</style>

Hope This is Helpful


问:
Icinga2 -- host's display_name is ignored by icingaweb2
I setup an icinga2 installation to monitor a set of servers. On the client node(ubuntu 16.04, icinga2 installed via apt from the Ubuntu repository) I set in hosts.conf:

```<code>object Host NodeName {
  /* Import the default host template defined in `templates.conf`. */
  display_name = "Gitlab-CI"
  import "generic-host"

  /* Specify the address attributes for checks e.g. `ssh` or `http`. */
  address = "127.0.0.1"
  address6 = "::1"

  /* Set custom attribute `os` for hostgroup assignment in `groups.conf`. */
  vars.os = "Linux"
  }
</code>```

But in the web interface I only see its FQDN gitlabci.example.com.

Who can I changed the displayed name without removing the NodeName directive because this is a nice feature with the standard Ubuntu (and I think all standard Icinga2 setups) configuration?

答: I moved from the bottom up to the top down configuration mode and updated Icinga2 to version 2.6.0 and then it works as described in the above question. </p>

Body:
I setup an icinga2 installation to monitor a set of servers. On the client node(ubuntu 16.04, icinga2 installed via apt from the Ubuntu repository) I set in hosts.conf:

object Host NodeName {
  /* Import the default host template defined in `templates.conf`. */
  display_name = "Gitlab-CI"
  import "generic-host"

  /* Specify the address attributes for checks e.g. `ssh` or `http`. */
  address = "127.0.0.1"
  address6 = "::1"

  /* Set custom attribute `os` for hostgroup assignment in `groups.conf`. */
  vars.os = "Linux"
  }

But in the web interface I only see its FQDN gitlabci.example.com.

Who can I changed the displayed name without removing the NodeName directive because this is a nice feature with the standard Ubuntu (and I think all standard Icinga2 setups) configuration?


答:
You can create the identical deep copy of your dictionary. Below is the solution for the same.

```<code>import copy
d = {'A': {'a': {1: [('string1', 'string2')]}},
     'B': {'b': {}},
     'C': {}
    }

d2 = copy.deepcopy(d)

for k,v in d.items():
    if not v:
        del d2[k]
    else:
        for a,b in v.items():
            if not b:
                del d2[k][a]
        if not d2[k]:
            del d2[k]
print(d2)
</code>```

So, d2 gives you require dict.

Title: Python iterate nested dictionary to remove keys

Body:
You can create the identical deep copy of your dictionary. Below is the solution for the same.

import copy
d = {'A': {'a': {1: [('string1', 'string2')]}},
     'B': {'b': {}},
     'C': {}
    }

d2 = copy.deepcopy(d)

for k,v in d.items():
    if not v:
        del d2[k]
    else:
        for a,b in v.items():
            if not b:
                del d2[k][a]
        if not d2[k]:
            del d2[k]
print(d2)

So, d2 gives you require dict.


问:
I want a command to apt-get Tensorflow on robot Nao
I want to install TensorFlow framework in robot NAO , if i do :

```<code>ssh nao@192.168.1.3
sudo apt-get install python-pip python-dev
</code>```

he print an error :

```<code>-bash: apt-get: command not found
</code>```

so How can i install tensorflow framework on robot NAO?

答:
Apparently there is no apt-get tool on your NAO, because NAO has different portage method, although its os is Linux. Generally two approaches you can go with:

if you have NAO simulator, first install the Tensorflow on it, and then copy all files to you NAO robot, so you have apt-get tool on your simulator and no mess on robot.

or you can install packages per pip tool, but NAO's os is Gentoo, so it could be a little twisted.

First search pip

```<code>emerge -s pip
</code>```

Find the name of tools you need, such as dev-python/pip and others python packages, to install it superuser is required.

```<code>emerge dev-python/pip
</code>```

Then you can begin other tasks.

I am not familiar with Tensorflow, however if you can not install it, you can built it from source code.
BTY, you might wanna check emerge command.

Body:
I want to install TensorFlow framework in robot NAO , if i do :

ssh nao@192.168.1.3
sudo apt-get install python-pip python-dev

he print an error :

-bash: apt-get: command not found

so How can i install tensorflow framework on robot NAO?

Body:
Apparently there is no apt-get tool on your NAO, because NAO has different portage method, although its os is Linux. Generally two approaches you can go with:

if you have NAO simulator, first install the Tensorflow on it, and then copy all files to you NAO robot, so you have apt-get tool on your simulator and no mess on robot.

or you can install packages per pip tool, but NAO's os is Gentoo, so it could be a little twisted.

First search pip

emerge -s pip

Find the name of tools you need, such as dev-python/pip and others python packages, to install it superuser is required.

emerge dev-python/pip

Then you can begin other tasks.

I am not familiar with Tensorflow, however if you can not install it, you can built it from source code.
BTY, you might wanna check emerge command.


问:
Zoom to show all locations in bing maps
Say I have 3 pushpins: (1) California, (2) Florida, (3) New York. In order for all the 3 of them to be visible, I'd have to zoom out far enough to pretty much see the whole country. But say instead of that I had (1) California, (2) Nevada, (3) Texas. I'd have to zoom out only to cover the south west corner of the US. Is there any function in the bing maps for Windows Phone 7 API that helps me with this. Basically, I want to zoom out just enough to see a set of locations.

Thanks!

答:
I don't know about a function that will do what you want directly, but you can find the bounding box that just surrounds all of your locations and you should be able to set the viewport to that extent.

If you start with an inverted box where the bottom left corner is (maxVal, maxVal) and the top right is (-maxVal, -maxval). you can loop over all your points and reset the bottom left if the point is less than its current value or the top right if it's greater than its current value.

The end result will be the smallest box that everything fits into. Add a little to the size to cope with rounding error and to make sure your pins are actually on the map and then set the extent of the viewport.

Title: Zoom to show all locations in bing maps


问:
Need pcre for pattern like "xxyy.zz"
I need pcre for pattern like "xxyy.zz", where x,y and z can be any alphabet.

Language: Python

What I have tried:

For 's = "xx"', 're.match(r"([a-z])\1{1}",s)' works but for my full string it does not work. For example for 's = "xxyy"', 're.match(r"([a-z])\1{1}([a-z])\1{1}",s)' does not work...

Please guide me how to fix this pcre.

答:
Each alpha group needs to be in parens and followed by a \1 style group reference.  I don't think you can use a {2} quantifier here, so the pairs needs need to be written serially:

```<code>>>> re.search(r'([a-z])\1([a-z])\2\.([a-z])\3', 'abccdd.eef').group(0)
'ccdd.ee'
</code>```

Title: Need pcre for pattern like "xxyy.zz"

Body:
Each alpha group needs to be in parens and followed by a \1 style group reference.  I don't think you can use a {2} quantifier here, so the pairs needs need to be written serially:

>>> re.search(r'([a-z])\1([a-z])\2\.([a-z])\3', 'abccdd.eef').group(0)
'ccdd.ee'


问:
XPath of text from child element
I'm trying to get an XPath to select text from a web page. Upon inspecting element, I see this. I'm trying to get Florida State University. When I right-click to copy XPath, I get this:

```<code>//*[@id="clue_J_3_2"]/em
</code>```

However, when I run the python code:

```<code>from lxml import html
import requests
game_url = 'http://www.j-archive.com/showgame.php?game_id=5566'
page = requests.get(game_url)
tree = html.fromstring(page.content)
path = '//*[@id="clue_J_3_2"]/em'
print tree.xpath(path)
</code>```

the output I get is []. I have tried many variations including:

//*[@id="clue_J_3_2"]/em/text()

/*/[@id="clue_J_3_2"]/em

//*[@id="clue_J_3_2"]//em[@class="correct_response"]/text()

Please let me know how to fix my XPath to get the text I want!

答:
Your xpath is correct, but you need to click the element to be able to get to your desired xpath in the DOM. When I inspected the page in question, I got this.

```<code><div onmouseover="toggle('clue_J_3_2', 'clue_J_3_2_stuck', '(Grant: What is Florida?)<br /><br /><em class="correct_response">Florida State University</em><br /><br /><table width="100%"><tr><td class="wrong">Grant</td><td class="right">Holly</td></tr></table>')" onmouseout="toggle('clue_J_3_2', 'clue_J_3_2_stuck', 'In 1858 this university went co-ed when it took on the Tallahassee Female Academy')" onclick="togglestick('clue_J_3_2_stuck')">
</code>```

So, looks like you'll have to parse the div's onmouseover all by yourself. Or perhaps use selenium, but I wouldn't go that far.

```<code>toggle_js = tree.xpath('//div[@onclick="togglestick(\'clue_J_3_2_stuck\')"]/@onmouseover')[0]
# 'toggle(\'clue_J_3_2\', \'clue_J_3_2_stuck\', \'(Grant: What is Florida?)<br /><br /><em class="correct_response">Florida State University</em><br /><br /><table width="100%"><tr><td class="wrong">Grant</td><td class="right">Holly</td></tr></table>\')'
answer = re.findall(r'correct_response">(.*)</em>', str(toggle_js))
answer[0].strip() if answer else None
# 'Florida State University'
</code>```

Title: XPath of text from child element

Body:
I'm trying to get an XPath to select text from a web page. Upon inspecting element, I see this. I'm trying to get Florida State University. When I right-click to copy XPath, I get this:

//*[@id="clue_J_3_2"]/em

However, when I run the python code:

from lxml import html
import requests
game_url = 'http://www.j-archive.com/showgame.php?game_id=5566'
page = requests.get(game_url)
tree = html.fromstring(page.content)
path = '//*[@id="clue_J_3_2"]/em'
print tree.xpath(path)

the output I get is []. I have tried many variations including:

//*[@id="clue_J_3_2"]/em/text()

/*/[@id="clue_J_3_2"]/em

//*[@id="clue_J_3_2"]//em[@class="correct_response"]/text()

Please let me know how to fix my XPath to get the text I want!

Body:
Your xpath is correct, but you need to click the element to be able to get to your desired xpath in the DOM. When I inspected the page in question, I got this.

<div onmouseover="toggle('clue_J_3_2', 'clue_J_3_2_stuck', '(Grant: What is Florida?)<br /><br /><em class=&quot;correct_response&quot;>Florida State University</em><br /><br /><table width=&quot;100%&quot;><tr><td class=&quot;wrong&quot;>Grant</td><td class=&quot;right&quot;>Holly</td></tr></table>')" onmouseout="toggle('clue_J_3_2', 'clue_J_3_2_stuck', 'In 1858 this university went co-ed when it took on the Tallahassee Female Academy')" onclick="togglestick('clue_J_3_2_stuck')">

So, looks like you'll have to parse the div's onmouseover all by yourself. Or perhaps use selenium, but I wouldn't go that far.

toggle_js = tree.xpath('//div[@onclick="togglestick(\'clue_J_3_2_stuck\')"]/@onmouseover')[0]
# 'toggle(\'clue_J_3_2\', \'clue_J_3_2_stuck\', \'(Grant: What is Florida?)<br /><br /><em class="correct_response">Florida State University</em><br /><br /><table width="100%"><tr><td class="wrong">Grant</td><td class="right">Holly</td></tr></table>\')'
answer = re.findall(r'correct_response">(.*)</em>', str(toggle_js))
answer[0].strip() if answer else None
# 'Florida State University'


问:
Proper use of thread and display.asyncexe in java swt
I'm doing a program which needed a thread because It's not responding when the GUI start its work. I'd used thread but i don't know if the use of it is correct, also I'd used the display.asyncExeceach of this gives me error

here is the code

```<code>btnCopyFolder.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent arg0) {

                    display.asyncExec(
                    new Runnable()
                    {
                    public void run(){

                        File srcFolder = new File(txtSource.getText());
                        File destFolder = new File(txtDestination.getText());

                        if(!srcFolder.exists()){
                            MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
                            msgBox.setText("Information");
                            msgBox.setMessage("Directory does not exist.");
                            msgBox.open();
                            txtSource.setText("");
                            txtSource.setEnabled(false);
                            txtDestination.setText("");

                        }else{
                            if(txtDestination.getText().isEmpty())
                            {
                                MessageBox msgBox = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
                                msgBox.setText("WARNING");
                                msgBox.setMessage("Invalid Path...");
                                msgBox.open();
                                txtSource.setText("");
                                txtSource.setEditable(false);
                                txtDestination.setText("");
                                btnCopyFolder.setEnabled(true);
                                btnCopyFile.setEnabled(true);
                            }
                            else
                            {
                                try {
                                    tc.copyFolder(srcFolder,destFolder);
                                } catch (IOException e1) {
                                    // TODO Auto-generated catch block
                                    e1.printStackTrace();
                                }
                                txtDetails.append("Finished Copying.....\n");
                                MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
                                msgBox.setText("Information");
                                msgBox.setMessage("Done Copying...");
                                msgBox.open();
                                txtSource.setText("");
                                txtSource.setEditable(false);
                                txtDestination.setText("");
                                btnCopyFolder.setEnabled(true);
                                btnCopyFile.setEnabled(true);

                                tc1 = new threadclass();
                                tc = new threadclass();
                                tc1.start();
                                tc.start();
                            }
                        }
                    }
                });
            }

    });
</code>```

Error

```<code>java.lang.NullPointerException
    at org.eclipse.wb.swt.FortryApplication$5.widgetSelected(FortryApplication.java:303)
    at org.eclipse.swt.widgets.TypedListener.handleEvent(Unknown Source)
    at org.eclipse.swt.widgets.EventTable.sendEvent(Unknown Source)
    at org.eclipse.swt.widgets.Widget.sendEvent(Unknown Source)
    at org.eclipse.swt.widgets.Display.runDeferredEvents(Unknown Source)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Unknown Source)
    at org.eclipse.wb.swt.FortryApplication.open(FortryApplication.java:63)
    at org.eclipse.wb.swt.FortryApplication.main(FortryApplication.java:486)
</code>```

for Thread i tried these

```<code>btnCopyFile.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent arg0)
            {
                new Thread(){
                    public void run()
                    {

                        File srcFolder = new File(txtSource.getText());
                        File destFolder = new File(txtDestination.getText());
                        if(!srcFolder.exists()){
                            MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
                            msgBox.setText("Information");
                            msgBox.setMessage("Directory does not exist.");
                            msgBox.open();
                            txtSource.setText("");
                            txtSource.setEditable(false);
                            txtDestination.setText("");

                        }else{

                            if(txtDestination.getText().isEmpty())
                            {
                                MessageBox msgBox = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
                                msgBox.setText("Warning");
                                msgBox.setMessage("Invalid Path..");
                                msgBox.open();
                                txtSource.setText("");
                                txtSource.setEditable(false);
                                txtDestination.setText("");
                                btnCopyFolder.setEnabled(true);
                                btnCopyFile.setEnabled(true);

                            }
                            else
                            {
                                try {
                                    tc.copyFolder1(srcFolder,destFolder);
                                } catch (IOException e1) {
                                    // TODO Auto-generated catch block
                                    e1.printStackTrace();
                                }
                                txtDetails.append("Finished Copying.....\n");
                                MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
                                msgBox.setText("Information");
                                msgBox.setMessage("Done Copying...");
                                msgBox.open();
                                txtSource.setText("");
                                txtSource.setEditable(false);
                                txtDestination.setText("");
                                btnCopyFolder.setEnabled(true);
                                btnCopyFile.setEnabled(true);

                                //                      tc1 = new threadclass();
                                //                      tc = new threadclass();
                                //                      tc1.start();
                                //                      tc.start();
                            }
                        }
                    }
                }.start();
            }
        });
</code>```

Error shows:

```<code>Exception in thread "Thread-2" org.eclipse.swt.SWTException: Invalid thread access
    at org.eclipse.swt.SWT.error(Unknown Source)
    at org.eclipse.swt.SWT.error(Unknown Source)
    at org.eclipse.swt.SWT.error(Unknown Source)
    at org.eclipse.swt.widgets.Widget.error(Unknown Source)
    at org.eclipse.swt.widgets.Widget.checkWidget(Unknown Source)
    at org.eclipse.swt.widgets.Text.getText(Unknown Source)
    at org.eclipse.wb.swt.FortryApplication$4$1.run(FortryApplication.java:239)
</code>```

EDIT

Full Code:

```<code>ublic class FortryApplication implements Runnable {
    static Display display;
    static Shell shell;
    static Color color;
    private static Text txtSource;
    private static Text txtDestination;
    private static Text txtDetails;
    static DateTime dateFrom;
    static DateTime dateTo;
    Button btnSourceFile, btnSelectFolder;
    Button btnBrowseFile;
    Button btnCopyFolder;
    Button btnCopyFile;
    Button btnCancel;
    static String text = "" ;
    static String text2 = "" ;
    threadclass tc = new threadclass();
    threadclass tc1 = new threadclass();

    // pos x, pos y, width, height
    public void open() {

        Display display = Display.getDefault();
        createContents();
        shell.open();
        shell.layout();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
    }
    protected void createContents()
    {
        shell = new Shell();
        shell.setSize(600,530);
        shell.setText("SWT Shell Demonstration");
        shell.setLayout(new GridLayout());

        final Group grpInput = new Group(shell, SWT.NONE);
        grpInput.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL));
        grpInput.setText("Input File");
        GridLayout gl_grpInput = new GridLayout();
        gl_grpInput.numColumns = 3;
        grpInput.setLayout(gl_grpInput);
        GridData gd_grpInput = new GridData(GridData.FILL_HORIZONTAL);
        gd_grpInput.widthHint = 419;
        gd_grpInput.verticalAlignment = SWT.CENTER;
        gd_grpInput.heightHint = 57;
        grpInput.setLayoutData(gd_grpInput);

        btnSourceFile = new Button(grpInput, SWT.PUSH);
        btnSourceFile.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent arg0) {
                FileDialog fd = new FileDialog(shell, SWT.MULTI);
                //              Collection files = new ArrayList();
                String firstFile = fd.open();
                if (firstFile != null) {
                    txtSource.setText("");
                    String[] selectedFiles = fd.getFileNames();
                    File file = new File(firstFile);
                    for (int ii = 0; ii < selectedFiles.length; ii++ )
                    {
                        if (file.isFile())
                        {
                            tc.displayFiles(new String[] { file.toString()});
                        }
                        else
                            tc.displayFiles(file.list());
                    }
                }
                btnCopyFolder.setEnabled(false);
                btnCopyFile.setEnabled(true);
                btnCancel.setEnabled(true);
            }
        });
        btnSourceFile.setText("Select File");

        btnSelectFolder = new Button(grpInput, SWT.NONE);
        btnSelectFolder.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent arg0) {

                DirectoryDialog dlg = new DirectoryDialog(shell);
                dlg.setFilterPath(txtSource.getText());
                dlg.setMessage("Select a source file to transfer");
                String dir = dlg.open();
                if (dir != null) {
                    txtSource.setText(dir);
                    btnCopyFile.setEnabled(false);
                    btnCopyFolder.setEnabled(true);
                    btnCancel.setEnabled(true);
                    //                  txtDetails.setText("Progress " + "\n");
                }

            }

        });
        btnSelectFolder.setText("Select Folder");
        new Label(grpInput, SWT.NONE);

        txtSource = new Text(grpInput, SWT.BORDER);
        txtSource.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
        new Label(grpInput, SWT.NONE);

        Group grpDestnationFile = new Group(shell, SWT.NONE);
        grpDestnationFile.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
        grpDestnationFile.setText("Destnation File");
        grpDestnationFile.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL));
        GridLayout gl_grpDestnationFile = new GridLayout();
        gl_grpDestnationFile.numColumns = 2;
        grpDestnationFile.setLayout(gl_grpDestnationFile);

        btnBrowseFile = new Button(grpDestnationFile, SWT.NONE);
        btnBrowseFile.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent arg0) {
                DirectoryDialog dialog = new DirectoryDialog(shell, SWT.SAVE);
                dialog.setFilterPath(txtDestination.getText());
                String dir = dialog.open();
                if(dir != null){
                    txtDestination.setText(dir);
                }
            }
        });
        btnBrowseFile.setText("Browse File");
        new Label(grpDestnationFile, SWT.NONE);

        txtDestination = new Text(grpDestnationFile, SWT.BORDER);
        GridData gd_txtDestination = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
        gd_txtDestination.widthHint = 429;
        txtDestination.setLayoutData(gd_txtDestination);
        new Label(grpDestnationFile, SWT.NONE);
        Label label = new Label(grpDestnationFile, SWT.NONE);
        GridData gd_label = new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1);
        gd_label.heightHint = -5;
        label.setLayoutData(gd_label);

        Group grpDateRange = new Group(shell, SWT.NONE);
        grpDateRange.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL));
        GridData gd_grpDateRange = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
        gd_grpDateRange.heightHint = 63;
        gd_grpDateRange.widthHint = 78;
        grpDateRange.setLayoutData(gd_grpDateRange);
        grpDateRange.setText("Date Range");

        DateTime dateFrom = new DateTime(grpDateRange, SWT.BORDER);
        dateFrom.setBounds(111, 40, 122, 24);

        Label lblFrom = new Label(grpDateRange, SWT.NONE);
        lblFrom.setBounds(153, 19, 55, 15);
        lblFrom.setText("From");

        DateTime dateTo = new DateTime(grpDateRange, SWT.BORDER);
        dateTo.setBounds(352, 40, 122, 24);

        Label lblTo = new Label(grpDateRange, SWT.NONE);
        lblTo.setText("To");
        lblTo.setBounds(397, 19, 55, 15);

        Label label_1 = new Label(grpDateRange, SWT.NONE);
        label_1.setFont(SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
        label_1.setBounds(293, 40, 20, 24);
        label_1.setText(":");

        Group grpDetails = new Group(shell, SWT.NONE);
        grpDetails.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
        grpDetails.setText("Details");
        grpDetails.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL));
        GridLayout gl_grpDetails = new GridLayout();
        gl_grpDetails.numColumns = 2;
        grpDetails.setLayout(gl_grpDetails);

        txtDetails = new Text(grpDetails, SWT.BORDER | SWT.READ_ONLY | SWT.WRAP | SWT.H_SCROLL | SWT.V_SCROLL | SWT.CANCEL | SWT.MULTI);
        GridData gd_txtDetails = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
        gd_txtDetails.widthHint = 460;
        gd_txtDetails.heightHint = 66;
        txtDetails.setLayoutData(gd_txtDetails);

        new Label(grpDetails, SWT.NONE);
        Label label_2 = new Label(grpDetails, SWT.NONE);
        GridData gd_label_2 = new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1);
        gd_label_2.heightHint = -3;
        label_2.setLayoutData(gd_label_2);

        Group grpCopyOptions = new Group(shell, SWT.NONE);
        grpCopyOptions.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL));
        GridData gd_grpCopyOptions = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
        gd_grpCopyOptions.heightHint = 70;
        gd_grpCopyOptions.widthHint = 492;
        grpCopyOptions.setLayoutData(gd_grpCopyOptions);
        grpCopyOptions.setText("Copy Options");

        btnCopyFile = new Button(grpCopyOptions, SWT.NONE);
        btnCopyFile.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent arg0)
            {
                Display.getDefault().asyncExec(
                        new Runnable()
                        {
                    public void run()
                    {

                        File srcFolder = new File(txtSource.getText());
                        File destFolder = new File(txtDestination.getText());
                        if(!srcFolder.exists()){
                            MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
                            msgBox.setText("Information");
                            msgBox.setMessage("Directory does not exist.");
                            msgBox.open();
                            txtSource.setText("");
                            txtSource.setEditable(false);
                            txtDestination.setText("");

                        }else{

                            if(txtDestination.getText().isEmpty())
                            {
                                MessageBox msgBox = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
                                msgBox.setText("Warning");
                                msgBox.setMessage("Invalid Path..");
                                msgBox.open();
                                txtSource.setText("");
                                txtSource.setEditable(false);
                                txtDestination.setText("");
                                btnCopyFolder.setEnabled(true);
                                btnCopyFile.setEnabled(true);

                            }
                            else
                            {
                                try {
                                    tc.copyFolder1(srcFolder,destFolder);
                                } catch (IOException e1) {
                                    // TODO Auto-generated catch block
                                    e1.printStackTrace();
                                }
                                txtDetails.append("Finished Copying.....\n");
                                MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
                                msgBox.setText("Information");
                                msgBox.setMessage("Done Copying...");
                                msgBox.open();
                                txtSource.setText("");
                                txtSource.setEditable(false);
                                txtDestination.setText("");
                                btnCopyFolder.setEnabled(true);
                                btnCopyFile.setEnabled(true);

                                                        tc1 = new threadclass();
                                                        tc = new threadclass();
                                                        tc1.start();
                                                        tc.start();
                            }
                        }
                    }
                });
            }
        });
        btnCopyFile.setBounds(128, 23, 166, 25);
        btnCopyFile.setText("Copy File");

        btnCopyFolder = new Button(grpCopyOptions, SWT.NONE);
        btnCopyFolder.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent arg0) {

                    Display.getDefault().asyncExec(
                    new Runnable()
                    {
                    public void run(){

                        File srcFolder = new File(txtSource.getText());
                        File destFolder = new File(txtDestination.getText());

                        if(!srcFolder.exists()){
                            MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
                            msgBox.setText("Information");
                            msgBox.setMessage("Directory does not exist.");
                            msgBox.open();
                            txtSource.setText("");
                            txtSource.setEnabled(false);
                            txtDestination.setText("");

                        }else{
                            if(txtDestination.getText().isEmpty())
                            {
                                MessageBox msgBox = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
                                msgBox.setText("WARNING");
                                msgBox.setMessage("Invalid Path...");
                                msgBox.open();
                                txtSource.setText("");
                                txtSource.setEditable(false);
                                txtDestination.setText("");
                                btnCopyFolder.setEnabled(true);
                                btnCopyFile.setEnabled(true);
                            }
                            else
                            {
                                try {
                                    tc.copyFolder(srcFolder,destFolder);
                                } catch (IOException e1) {
                                    // TODO Auto-generated catch block
                                    e1.printStackTrace();
                                }
                                txtDetails.append("Finished Copying.....\n");
                                MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
                                msgBox.setText("Information");
                                msgBox.setMessage("Done Copying...");
                                msgBox.open();
                                txtSource.setText("");
                                txtSource.setEditable(false);
                                txtDestination.setText("");
                                btnCopyFolder.setEnabled(true);
                                btnCopyFile.setEnabled(true);

                                tc1 = new threadclass();
                                tc = new threadclass();
                                tc1.start();
                                tc.start();
                            }
                        }
                    }
                });
            }
        });
        btnCopyFolder.setText("Copy Folder");
        btnCopyFolder.setBounds(300, 23, 166, 25);

        btnCancel = new Button(grpCopyOptions, SWT.NONE);
        btnCancel.setBounds(247, 54, 96, 25);
        btnCancel.setText("Cancel");
    }

    class threadclass extends Thread
    {
        public void cancel(boolean b) {

            tc.interrupt();

        }
        public void displayFiles(String[] files) {
            for (int i = 0; files != null && i < files.length; i++) {
                txtSource.append(files[i]);
                txtSource.setEditable(false);

            }
        }

        public void copyFolder(File src, File dest)
                throws IOException{
            if(src.isDirectory()){
                if (!dest.exists())
                {
                    dest.mkdir();
                    txtDetails.append("Directory created : " + dest + "\n");
                }
                final String files[] = src.list();
                for (String file : files)
                {
                    File srcFile = new File(src, file);
                    File destFile = new File(dest, file);

                    //Recursive function call
                    copyFolder(srcFile, destFile);
                }
            }
            else{
                //              btnCancel.setEnabled(true);
                txtDetails.append("");
                Files.copy(src.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
                txtDetails.append(text + "Copying " + src.getAbsolutePath() + "\n");
                //
            }
        }
        public void copyFolder1(File src, File dest)
                throws IOException{
            //      String fileName = new SimpleDateFormat("yyyyMMddHHmm'.txt'").format(new DateTime(ddFrom, 0));
            if(src.isDirectory()){
                if (!dest.exists())
                {
                    dest.mkdir();
                    txtDetails.append("Directory created : " + dest + "\n");
                }
                String files[] = src.list();
                for (String file : files)
                {
                    File srcFile = new File(src, file);
                    File destFile = new File(dest, file);

                    //Recursive function call
                    copyFolder1(srcFile, destFile);
                }
            }
            else{
                if(dest.isDirectory())
                {
                    //                  btnCancel.setEnabled(true);
                    copyFile(src, new File (dest, src.getName()));
                    txtDetails.append(text + "Copying " + src.getAbsolutePath() + "\n");
                }
                else
                {
                    copyFile(src, dest);
                }
                //          }
            }
        }
        public void copyFile(File src, File dest) throws IOException
        {
            InputStream oInStream = new FileInputStream(src);
            OutputStream oOutStream = new FileOutputStream(dest);

            // Transfer bytes from in to out
            byte[] oBytes = new byte[1024];
            int nLength;
            BufferedInputStream oBuffInputStream = new BufferedInputStream( oInStream );
            while ((nLength = oBuffInputStream.read(oBytes)) > 0)
            {
                oOutStream.write(oBytes, 0, nLength);
            }
            oInStream.close();
            oOutStream.close();
        }
        public  void fileCopy(File sourceDir , File destDir) throws IOException{
            //    File sDir = new File(sourceDir);
            if (!sourceDir.isDirectory()){
                // throw error
            }
            //    File dDir = new File(destDir);
            if (!destDir.exists()){
                destDir.mkdir();
            }
            File[] files = sourceDir.listFiles();
            for (int i = 0; i < files.length; i++) {
                File destFile = new File(destDir.getAbsolutePath()+File.separator+files[i].getName().replace(",", "")  //remove the commas
                        .replace("[", "")   //remove the right bracket
                        .replace("]", "")
                        .replace(" ", ""));
                //  destFile.createNewFile();
                Files.copy(files[i].toPath(), destFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
                txtDetails.append(text + " Copying " + files[i].getAbsolutePath() + "\n");
            }

        }
    }

    public static void main(String[] args) {
        try {
            FortryApplication window = new FortryApplication();
            window.open();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub

    }

}
</code>```

答:
You do not use asyncExec to run a background task, asyncExec always runs code in the UI thread.

You use asyncExec inside a background Thread every time you want to do a UI operation. You must use a background Thread to do long running tasks.

So when you want to run a long running task you do something like:

```<code>Thread background = new Thread() {
  @Override
  public void run() {

     ... long running background code

     Display.getDefault().asyncExec(new Runnable() {
        @Override
        public void run() {
           .. code accessing user interface objects
        }
     });

     .... more code
  }
};

background.start();
</code>```

Body:
I'm doing a program which needed a thread because It's not responding when the GUI start its work. I'd used thread but i don't know if the use of it is correct, also I'd used the display.asyncExeceach of this gives me error

here is the code

btnCopyFolder.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent arg0) {

                    display.asyncExec(
                    new Runnable()
                    {
                    public void run(){

                        File srcFolder = new File(txtSource.getText());
                        File destFolder = new File(txtDestination.getText());

                        if(!srcFolder.exists()){
                            MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
                            msgBox.setText("Information");
                            msgBox.setMessage("Directory does not exist.");
                            msgBox.open();
                            txtSource.setText("");
                            txtSource.setEnabled(false);
                            txtDestination.setText("");

                        }else{
                            if(txtDestination.getText().isEmpty())
                            {
                                MessageBox msgBox = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
                                msgBox.setText("WARNING");
                                msgBox.setMessage("Invalid Path...");
                                msgBox.open();
                                txtSource.setText("");
                                txtSource.setEditable(false);
                                txtDestination.setText("");
                                btnCopyFolder.setEnabled(true);
                                btnCopyFile.setEnabled(true);
                            }
                            else
                            {
                                try {
                                    tc.copyFolder(srcFolder,destFolder);
                                } catch (IOException e1) {
                                    // TODO Auto-generated catch block
                                    e1.printStackTrace();
                                }
                                txtDetails.append("Finished Copying.....\n");
                                MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
                                msgBox.setText("Information");
                                msgBox.setMessage("Done Copying...");
                                msgBox.open();
                                txtSource.setText("");
                                txtSource.setEditable(false);
                                txtDestination.setText("");
                                btnCopyFolder.setEnabled(true);
                                btnCopyFile.setEnabled(true);

                                tc1 = new threadclass();
                                tc = new threadclass();
                                tc1.start();
                                tc.start();
                            }
                        }
                    }
                });
            }

    });

Error

java.lang.NullPointerException
    at org.eclipse.wb.swt.FortryApplication$5.widgetSelected(FortryApplication.java:303)
    at org.eclipse.swt.widgets.TypedListener.handleEvent(Unknown Source)
    at org.eclipse.swt.widgets.EventTable.sendEvent(Unknown Source)
    at org.eclipse.swt.widgets.Widget.sendEvent(Unknown Source)
    at org.eclipse.swt.widgets.Display.runDeferredEvents(Unknown Source)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Unknown Source)
    at org.eclipse.wb.swt.FortryApplication.open(FortryApplication.java:63)
    at org.eclipse.wb.swt.FortryApplication.main(FortryApplication.java:486)

for Thread i tried these

btnCopyFile.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent arg0)
            {
                new Thread(){
                    public void run()
                    {

                        File srcFolder = new File(txtSource.getText());
                        File destFolder = new File(txtDestination.getText());
                        if(!srcFolder.exists()){
                            MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
                            msgBox.setText("Information");
                            msgBox.setMessage("Directory does not exist.");
                            msgBox.open();
                            txtSource.setText("");
                            txtSource.setEditable(false);
                            txtDestination.setText("");

                        }else{

                            if(txtDestination.getText().isEmpty())
                            {
                                MessageBox msgBox = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
                                msgBox.setText("Warning");
                                msgBox.setMessage("Invalid Path..");
                                msgBox.open();
                                txtSource.setText("");
                                txtSource.setEditable(false);
                                txtDestination.setText("");
                                btnCopyFolder.setEnabled(true);
                                btnCopyFile.setEnabled(true);

                            }
                            else
                            {
                                try {
                                    tc.copyFolder1(srcFolder,destFolder);
                                } catch (IOException e1) {
                                    // TODO Auto-generated catch block
                                    e1.printStackTrace();
                                }
                                txtDetails.append("Finished Copying.....\n");
                                MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
                                msgBox.setText("Information");
                                msgBox.setMessage("Done Copying...");
                                msgBox.open();
                                txtSource.setText("");
                                txtSource.setEditable(false);
                                txtDestination.setText("");
                                btnCopyFolder.setEnabled(true);
                                btnCopyFile.setEnabled(true);

                                //                      tc1 = new threadclass();
                                //                      tc = new threadclass();
                                //                      tc1.start();
                                //                      tc.start();
                            }
                        }
                    }
                }.start();
            }
        });

Error shows:

Exception in thread "Thread-2" org.eclipse.swt.SWTException: Invalid thread access
    at org.eclipse.swt.SWT.error(Unknown Source)
    at org.eclipse.swt.SWT.error(Unknown Source)
    at org.eclipse.swt.SWT.error(Unknown Source)
    at org.eclipse.swt.widgets.Widget.error(Unknown Source)
    at org.eclipse.swt.widgets.Widget.checkWidget(Unknown Source)
    at org.eclipse.swt.widgets.Text.getText(Unknown Source)
    at org.eclipse.wb.swt.FortryApplication$4$1.run(FortryApplication.java:239)

EDIT

Full Code:

ublic class FortryApplication implements Runnable {
    static Display display;
    static Shell shell;
    static Color color;
    private static Text txtSource;
    private static Text txtDestination;
    private static Text txtDetails;
    static DateTime dateFrom;
    static DateTime dateTo;
    Button btnSourceFile, btnSelectFolder;
    Button btnBrowseFile;
    Button btnCopyFolder;
    Button btnCopyFile;
    Button btnCancel;
    static String text = "" ;
    static String text2 = "" ;
    threadclass tc = new threadclass();
    threadclass tc1 = new threadclass();

    // pos x, pos y, width, height
    public void open() {

        Display display = Display.getDefault();
        createContents();
        shell.open();
        shell.layout();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
    }
    protected void createContents()
    {
        shell = new Shell();
        shell.setSize(600,530);
        shell.setText("SWT Shell Demonstration");
        shell.setLayout(new GridLayout());

        final Group grpInput = new Group(shell, SWT.NONE);
        grpInput.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL));
        grpInput.setText("Input File");
        GridLayout gl_grpInput = new GridLayout();
        gl_grpInput.numColumns = 3;
        grpInput.setLayout(gl_grpInput);
        GridData gd_grpInput = new GridData(GridData.FILL_HORIZONTAL);
        gd_grpInput.widthHint = 419;
        gd_grpInput.verticalAlignment = SWT.CENTER;
        gd_grpInput.heightHint = 57;
        grpInput.setLayoutData(gd_grpInput);

        btnSourceFile = new Button(grpInput, SWT.PUSH);
        btnSourceFile.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent arg0) {
                FileDialog fd = new FileDialog(shell, SWT.MULTI);
                //              Collection files = new ArrayList();
                String firstFile = fd.open();
                if (firstFile != null) {
                    txtSource.setText("");
                    String[] selectedFiles = fd.getFileNames();
                    File file = new File(firstFile);
                    for (int ii = 0; ii < selectedFiles.length; ii++ )
                    {
                        if (file.isFile())
                        {
                            tc.displayFiles(new String[] { file.toString()});
                        }
                        else
                            tc.displayFiles(file.list());
                    }
                }
                btnCopyFolder.setEnabled(false);
                btnCopyFile.setEnabled(true);
                btnCancel.setEnabled(true);
            }
        });
        btnSourceFile.setText("Select File");

        btnSelectFolder = new Button(grpInput, SWT.NONE);
        btnSelectFolder.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent arg0) {

                DirectoryDialog dlg = new DirectoryDialog(shell);
                dlg.setFilterPath(txtSource.getText());
                dlg.setMessage("Select a source file to transfer");
                String dir = dlg.open();
                if (dir != null) {
                    txtSource.setText(dir);
                    btnCopyFile.setEnabled(false);
                    btnCopyFolder.setEnabled(true);
                    btnCancel.setEnabled(true);
                    //                  txtDetails.setText("Progress " + "\n");
                }

            }

        });
        btnSelectFolder.setText("Select Folder");
        new Label(grpInput, SWT.NONE);

        txtSource = new Text(grpInput, SWT.BORDER);
        txtSource.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
        new Label(grpInput, SWT.NONE);

        Group grpDestnationFile = new Group(shell, SWT.NONE);
        grpDestnationFile.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
        grpDestnationFile.setText("Destnation File");
        grpDestnationFile.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL));
        GridLayout gl_grpDestnationFile = new GridLayout();
        gl_grpDestnationFile.numColumns = 2;
        grpDestnationFile.setLayout(gl_grpDestnationFile);

        btnBrowseFile = new Button(grpDestnationFile, SWT.NONE);
        btnBrowseFile.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent arg0) {
                DirectoryDialog dialog = new DirectoryDialog(shell, SWT.SAVE);
                dialog.setFilterPath(txtDestination.getText());
                String dir = dialog.open();
                if(dir != null){
                    txtDestination.setText(dir);
                }
            }
        });
        btnBrowseFile.setText("Browse File");
        new Label(grpDestnationFile, SWT.NONE);

        txtDestination = new Text(grpDestnationFile, SWT.BORDER);
        GridData gd_txtDestination = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
        gd_txtDestination.widthHint = 429;
        txtDestination.setLayoutData(gd_txtDestination);
        new Label(grpDestnationFile, SWT.NONE);
        Label label = new Label(grpDestnationFile, SWT.NONE);
        GridData gd_label = new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1);
        gd_label.heightHint = -5;
        label.setLayoutData(gd_label);

        Group grpDateRange = new Group(shell, SWT.NONE);
        grpDateRange.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL));
        GridData gd_grpDateRange = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
        gd_grpDateRange.heightHint = 63;
        gd_grpDateRange.widthHint = 78;
        grpDateRange.setLayoutData(gd_grpDateRange);
        grpDateRange.setText("Date Range");

        DateTime dateFrom = new DateTime(grpDateRange, SWT.BORDER);
        dateFrom.setBounds(111, 40, 122, 24);

        Label lblFrom = new Label(grpDateRange, SWT.NONE);
        lblFrom.setBounds(153, 19, 55, 15);
        lblFrom.setText("From");

        DateTime dateTo = new DateTime(grpDateRange, SWT.BORDER);
        dateTo.setBounds(352, 40, 122, 24);

        Label lblTo = new Label(grpDateRange, SWT.NONE);
        lblTo.setText("To");
        lblTo.setBounds(397, 19, 55, 15);

        Label label_1 = new Label(grpDateRange, SWT.NONE);
        label_1.setFont(SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
        label_1.setBounds(293, 40, 20, 24);
        label_1.setText(":");

        Group grpDetails = new Group(shell, SWT.NONE);
        grpDetails.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
        grpDetails.setText("Details");
        grpDetails.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL));
        GridLayout gl_grpDetails = new GridLayout();
        gl_grpDetails.numColumns = 2;
        grpDetails.setLayout(gl_grpDetails);

        txtDetails = new Text(grpDetails, SWT.BORDER | SWT.READ_ONLY | SWT.WRAP | SWT.H_SCROLL | SWT.V_SCROLL | SWT.CANCEL | SWT.MULTI);
        GridData gd_txtDetails = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
        gd_txtDetails.widthHint = 460;
        gd_txtDetails.heightHint = 66;
        txtDetails.setLayoutData(gd_txtDetails);

        new Label(grpDetails, SWT.NONE);
        Label label_2 = new Label(grpDetails, SWT.NONE);
        GridData gd_label_2 = new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1);
        gd_label_2.heightHint = -3;
        label_2.setLayoutData(gd_label_2);

        Group grpCopyOptions = new Group(shell, SWT.NONE);
        grpCopyOptions.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL));
        GridData gd_grpCopyOptions = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
        gd_grpCopyOptions.heightHint = 70;
        gd_grpCopyOptions.widthHint = 492;
        grpCopyOptions.setLayoutData(gd_grpCopyOptions);
        grpCopyOptions.setText("Copy Options");

        btnCopyFile = new Button(grpCopyOptions, SWT.NONE);
        btnCopyFile.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent arg0)
            {
                Display.getDefault().asyncExec(
                        new Runnable()
                        {
                    public void run()
                    {

                        File srcFolder = new File(txtSource.getText());
                        File destFolder = new File(txtDestination.getText());
                        if(!srcFolder.exists()){
                            MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
                            msgBox.setText("Information");
                            msgBox.setMessage("Directory does not exist.");
                            msgBox.open();
                            txtSource.setText("");
                            txtSource.setEditable(false);
                            txtDestination.setText("");

                        }else{

                            if(txtDestination.getText().isEmpty())
                            {
                                MessageBox msgBox = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
                                msgBox.setText("Warning");
                                msgBox.setMessage("Invalid Path..");
                                msgBox.open();
                                txtSource.setText("");
                                txtSource.setEditable(false);
                                txtDestination.setText("");
                                btnCopyFolder.setEnabled(true);
                                btnCopyFile.setEnabled(true);

                            }
                            else
                            {
                                try {
                                    tc.copyFolder1(srcFolder,destFolder);
                                } catch (IOException e1) {
                                    // TODO Auto-generated catch block
                                    e1.printStackTrace();
                                }
                                txtDetails.append("Finished Copying.....\n");
                                MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
                                msgBox.setText("Information");
                                msgBox.setMessage("Done Copying...");
                                msgBox.open();
                                txtSource.setText("");
                                txtSource.setEditable(false);
                                txtDestination.setText("");
                                btnCopyFolder.setEnabled(true);
                                btnCopyFile.setEnabled(true);

                                                        tc1 = new threadclass();
                                                        tc = new threadclass();
                                                        tc1.start();
                                                        tc.start();
                            }
                        }
                    }
                });
            }
        });
        btnCopyFile.setBounds(128, 23, 166, 25);
        btnCopyFile.setText("Copy File");

        btnCopyFolder = new Button(grpCopyOptions, SWT.NONE);
        btnCopyFolder.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent arg0) {

                    Display.getDefault().asyncExec(
                    new Runnable()
                    {
                    public void run(){

                        File srcFolder = new File(txtSource.getText());
                        File destFolder = new File(txtDestination.getText());

                        if(!srcFolder.exists()){
                            MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
                            msgBox.setText("Information");
                            msgBox.setMessage("Directory does not exist.");
                            msgBox.open();
                            txtSource.setText("");
                            txtSource.setEnabled(false);
                            txtDestination.setText("");

                        }else{
                            if(txtDestination.getText().isEmpty())
                            {
                                MessageBox msgBox = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
                                msgBox.setText("WARNING");
                                msgBox.setMessage("Invalid Path...");
                                msgBox.open();
                                txtSource.setText("");
                                txtSource.setEditable(false);
                                txtDestination.setText("");
                                btnCopyFolder.setEnabled(true);
                                btnCopyFile.setEnabled(true);
                            }
                            else
                            {
                                try {
                                    tc.copyFolder(srcFolder,destFolder);
                                } catch (IOException e1) {
                                    // TODO Auto-generated catch block
                                    e1.printStackTrace();
                                }
                                txtDetails.append("Finished Copying.....\n");
                                MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
                                msgBox.setText("Information");
                                msgBox.setMessage("Done Copying...");
                                msgBox.open();
                                txtSource.setText("");
                                txtSource.setEditable(false);
                                txtDestination.setText("");
                                btnCopyFolder.setEnabled(true);
                                btnCopyFile.setEnabled(true);

                                tc1 = new threadclass();
                                tc = new threadclass();
                                tc1.start();
                                tc.start();
                            }
                        }
                    }
                });
            }
        });
        btnCopyFolder.setText("Copy Folder");
        btnCopyFolder.setBounds(300, 23, 166, 25);

        btnCancel = new Button(grpCopyOptions, SWT.NONE);
        btnCancel.setBounds(247, 54, 96, 25);
        btnCancel.setText("Cancel");
    }

    class threadclass extends Thread
    {
        public void cancel(boolean b) {

            tc.interrupt();

        }
        public void displayFiles(String[] files) {
            for (int i = 0; files != null && i < files.length; i++) {
                txtSource.append(files[i]);
                txtSource.setEditable(false);

            }
        }

        public void copyFolder(File src, File dest)
                throws IOException{
            if(src.isDirectory()){
                if (!dest.exists())
                {
                    dest.mkdir();
                    txtDetails.append("Directory created : " + dest + "\n");
                }
                final String files[] = src.list();
                for (String file : files)
                {
                    File srcFile = new File(src, file);
                    File destFile = new File(dest, file);

                    //Recursive function call
                    copyFolder(srcFile, destFile);
                }
            }
            else{
                //              btnCancel.setEnabled(true);
                txtDetails.append("");
                Files.copy(src.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
                txtDetails.append(text + "Copying " + src.getAbsolutePath() + "\n");
                //
            }
        }
        public void copyFolder1(File src, File dest)
                throws IOException{
            //      String fileName = new SimpleDateFormat("yyyyMMddHHmm'.txt'").format(new DateTime(ddFrom, 0));
            if(src.isDirectory()){
                if (!dest.exists())
                {
                    dest.mkdir();
                    txtDetails.append("Directory created : " + dest + "\n");
                }
                String files[] = src.list();
                for (String file : files)
                {
                    File srcFile = new File(src, file);
                    File destFile = new File(dest, file);

                    //Recursive function call
                    copyFolder1(srcFile, destFile);
                }
            }
            else{
                if(dest.isDirectory())
                {
                    //                  btnCancel.setEnabled(true);
                    copyFile(src, new File (dest, src.getName()));
                    txtDetails.append(text + "Copying " + src.getAbsolutePath() + "\n");
                }
                else
                {
                    copyFile(src, dest);
                }
                //          }
            }
        }
        public void copyFile(File src, File dest) throws IOException
        {
            InputStream oInStream = new FileInputStream(src);
            OutputStream oOutStream = new FileOutputStream(dest);

            // Transfer bytes from in to out
            byte[] oBytes = new byte[1024];
            int nLength;
            BufferedInputStream oBuffInputStream = new BufferedInputStream( oInStream );
            while ((nLength = oBuffInputStream.read(oBytes)) > 0)
            {
                oOutStream.write(oBytes, 0, nLength);
            }
            oInStream.close();
            oOutStream.close();
        }
        public  void fileCopy(File sourceDir , File destDir) throws IOException{
            //    File sDir = new File(sourceDir);
            if (!sourceDir.isDirectory()){
                // throw error
            }
            //    File dDir = new File(destDir);
            if (!destDir.exists()){
                destDir.mkdir();
            }
            File[] files = sourceDir.listFiles();
            for (int i = 0; i < files.length; i++) {
                File destFile = new File(destDir.getAbsolutePath()+File.separator+files[i].getName().replace(",", "")  //remove the commas
                        .replace("[", "")   //remove the right bracket
                        .replace("]", "")
                        .replace(" ", ""));
                //  destFile.createNewFile();
                Files.copy(files[i].toPath(), destFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
                txtDetails.append(text + " Copying " + files[i].getAbsolutePath() + "\n");
            }

        }
    }

    public static void main(String[] args) {
        try {
            FortryApplication window = new FortryApplication();
            window.open();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub

    }

}

Body:
You do not use asyncExec to run a background task, asyncExec always runs code in the UI thread.

You use asyncExec inside a background Thread every time you want to do a UI operation. You must use a background Thread to do long running tasks.

So when you want to run a long running task you do something like:

Thread background = new Thread() {
  @Override
  public void run() {

     ... long running background code

     Display.getDefault().asyncExec(new Runnable() {
        @Override
        public void run() {
           .. code accessing user interface objects
        }
     });

     .... more code
  }
};

background.start();