问:
Count and remove similar elements in a list while iterating through it
I used many references in the site to build up my program but I'm kind of stuck right now. I think using iterator will do the job. Sadly even though I went through questions which had iterator, I couldn't get the way of using it properly to implement it on my code.

I want to,
      1. remove the similar elements found in the list fname
      2. count & add the that count of each element found in fname to
          counter.

Please help me do the above using iterator or with any other method. Following is my code,

```<code>List<String> fname = new ArrayList<>(Arrays.asList(fullname.split(""))); //Assigning the string to a list//

    int count = 1;
    ArrayList<Integer> counter = new ArrayList<>();
    List<String> holder = new ArrayList<>();

    for(int element=0; element<=fname.size; element++)
    {
        for(int run=(element+1); run<=fname.size; run++)
        {
            if((fname.get(element)).equals(fname.get(run)))
            {
                count++;
                holder.add(fname.get(run));
            }

            counter.add(count);
        }

        holder.add(fname.get(element));
        fname.removeAll(holder);
    }

    System.out.println(fname);
    System.out.println(counter);
</code>```

Thanks.

答:
I was using LinkedHashMap to preserve order of elements. Also for loop, which I am using,  implicitly uses Iterator. Code example is using Map.merge method, which is available since Java 8.

```<code>    List<String> fname = new ArrayList<>(Arrays.asList(fullname.split("")));
    /*
        Create Map which will contain pairs kay=values
        (in this case key is a name and value is the counter).
        Here we are using LinkedHashMap (instead of common HashMap)
        to preserve order in which name occurs first time in the list.
    */
    Map<String, Integer> countByName = new LinkedHashMap<>();
    for (String name : fname) {
        /*
             'merge' method put the key into the map (first parameter 'name').
             Second parameter is a value which we that to associate with the key
             Last (3rd) parameter is a function which will merge two values
             (new and ald) if map already contains this key
         */
        countByName.merge(name, 1, Integer::sum);
    }
    System.out.println(fname);                  // original list [a, d, e, a, a, f, t, d]
    System.out.println(countByName.values());   // counts [3, 2, 1, 1, 1]
    System.out.println(countByName.keySet());   // unique names [a, d, e, f, t]
</code>```

Also same might be done using Stream API but it would be probably hard for understanding if you are not familiar with Streams.

```<code>    Map<String, Long> countByName = fname.stream()
            .collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()));
</code>```

Body:
I used many references in the site to build up my program but I'm kind of stuck right now. I think using iterator will do the job. Sadly even though I went through questions which had iterator, I couldn't get the way of using it properly to implement it on my code.

I want to,
      1. remove the similar elements found in the list fname
      2. count & add the that count of each element found in fname to
          counter.

Please help me do the above using iterator or with any other method. Following is my code,

List<String> fname = new ArrayList<>(Arrays.asList(fullname.split(""))); //Assigning the string to a list//

    int count = 1;
    ArrayList<Integer> counter = new ArrayList<>();
    List<String> holder = new ArrayList<>();

    for(int element=0; element<=fname.size; element++)
    {
        for(int run=(element+1); run<=fname.size; run++)
        {
            if((fname.get(element)).equals(fname.get(run)))
            {
                count++;
                holder.add(fname.get(run));
            }

            counter.add(count);
        }

        holder.add(fname.get(element));
        fname.removeAll(holder);
    }

    System.out.println(fname);
    System.out.println(counter);

Thanks.

Body:
I was using LinkedHashMap to preserve order of elements. Also for loop, which I am using,  implicitly uses Iterator. Code example is using Map.merge method, which is available since Java 8.

    List<String> fname = new ArrayList<>(Arrays.asList(fullname.split("")));
    /*
        Create Map which will contain pairs kay=values
        (in this case key is a name and value is the counter).
        Here we are using LinkedHashMap (instead of common HashMap)
        to preserve order in which name occurs first time in the list.
    */
    Map<String, Integer> countByName = new LinkedHashMap<>();
    for (String name : fname) {
        /*
             'merge' method put the key into the map (first parameter 'name').
             Second parameter is a value which we that to associate with the key
             Last (3rd) parameter is a function which will merge two values
             (new and ald) if map already contains this key
         */
        countByName.merge(name, 1, Integer::sum);
    }
    System.out.println(fname);                  // original list [a, d, e, a, a, f, t, d]
    System.out.println(countByName.values());   // counts [3, 2, 1, 1, 1]
    System.out.println(countByName.keySet());   // unique names [a, d, e, f, t]

Also same might be done using Stream API but it would be probably hard for understanding if you are not familiar with Streams.

    Map<String, Long> countByName = fname.stream()
            .collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()));


来源: stackexchange

问:
Angularjs not binding data and html not printing scope variables
That's my complete code angular is not printing vars in the body tag of the html pice, console.log() everywhere is working. ng-click at submit button is also working.

```<code><html ng-app="fb">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap      /3.3.7/css/bootstrap.min.css"
 integrity="sha384-   BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5  /angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-cookie/4.1.0/angular-cookie.js"></script>

<script>
var app=angular.module('fb', []);

app.controller('home',function($scope){
    var hi;
    $scope.hi=5;
    //$rootScope.hola=9;
    console.log($scope.hi);
    //console.log($rootScope.hola);

    $scope.submitSignup=function()
    {
    var hi;
    $scope.hi=5;
    //$rootScope.hola=9;
    console.log($scope.hi);
    //console.log($rootScope.hola);
    console.log($scope.username);
        alert('button pressed');
    };
});

</script>
<head>
<title>Index</title
</head>

<body>
<div ng-controller='home'>
<input type="text" placeholder="Username" ng-model="username">
<br>
<input type="password" placeholder="Password" ng-model="password">
<br>

<button type="button" ng-click="submitSignup()">SignUp</button>

<br>

<p> {{username}} </p>

<p> {{hi}} </p>

{{hola}}

</div>

<p> index </p>
</body>
</html>
</code>```

Scratching my head for hours and hours at this, any help will be appreciated.

答:
You forgot to initiate your app with ng-app="fb"

```<code> <body ng-app="fb">
    <div ng-controller="home">
        <input type="text" placeholder="Username" ng-model="username">
        <br>
        <input type="password" placeholder="Password" ng-model="password">
        <br>
        <button type="button" ng-click="submitSignup()">SignUp</button>

        <p> {{username}} </p>

        <p> {{hi}} </p>

        {{hola}}

    </div>
    <p> index </p>
</body>

</html>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
That's my complete code angular is not printing vars in the body tag of the html pice, console.log() everywhere is working. ng-click at submit button is also working.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap      /3.3.7/css/bootstrap.min.css"
 integrity="sha384-   BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">

<title>Index</title

<input type="text" placeholder="Username" ng-model="username">

<input type="password" placeholder="Password" ng-model="password">

<button type="button" ng-click="submitSignup()">SignUp</button>

 {{username}}

 {{hi}}

{{hola}}

 index

Scratching my head for hours and hours at this, any help will be appreciated.

Body:
You forgot to initiate your app with ng-app="fb"

 <body ng-app="fb">
    <div ng-controller="home">
        <input type="text" placeholder="Username" ng-model="username">
        <br>
        <input type="password" placeholder="Password" ng-model="password">
        <br>
        <button type="button" ng-click="submitSignup()">SignUp</button>

        <p> {{username}} </p>

        <p> {{hi}} </p>

        {{hola}}

    </div>
    <p> index </p>
</body>

</html>


问:
Is there a Java equivalent for Python's map function?
I would like to easily transform a collection (list) of objects of class A to a collection of objects of class B, just as Python's map function does it. Is there any "well-known" implementation of this (some kind of library)? I've already searched for it in Apache's commons-lang but with no luck. </p>

答: Take a look at lambdaj and its convert method</p>

ContentLicense: CC BY-SA 2.5


问:
Asynchronous Flow Charts. How to visually represent asynchronous logic
Yes, it's a bit of an oxymoron.

Is there a visual language for representing asynchronous logic?  Something as simple as a flow chart?

I'd like to model UI "screens", and the logic behind them.

Thanks!

答:
I've used this library for a project, to visualize states of database-objects: https://www.npmjs.com/package/promise-state-machine-es6

While it does not really cover async stuff, it does help in reasoning about applicationlogic with non-technical people.


问:
IPv6 filter in Scapy
I am using scapy to sniff a IPv6 packet with a specific source ip /dest ip.

Example:

```<code>filter1 ="tcp port "+`port`+ " and ip6 host 2001::4 and tcp[tcpflags] & tcp-syn !=0 and !icmp and !arp and not host "+host_ip

            a= sniff(count =1,filter=filter1,iface=eth)
</code>```

This throws an exception as shown below:
scapy.error.Scapy_Exception: Filter parse error

答:
For complex filters, scapy allows you the use of a python function as a filter:

```<code>desiredip = "2001::4"
undesiredip = host_ip

def isMyPacket (pkt):
    if IPv6 in pkt:
        pktip6 = pkt[IPv6]
        if pktip6.src == desiredip or pktip6.dst == desiredip:
            if pktip6.src != undesiredip and pktip6.dst != undesiredip:
                if TCP in pktip6:
                    if pktip6[TCP].flags & 0x02: #Check if it is a SYN
                        return True #If all conditions are met
    return False

a= sniff(count =1,lfilter=isMyPacket,iface=eth)
</code>```

Anyway, you don't need to check whether it is arp or icmp: If it is TCP you know for sure that it is not arp nor icmp.

More about TCP flags in scapy: Get TCP Flags with Scapy

Title: IPv6 filter in Scapy

Body:
I am using scapy to sniff a IPv6 packet with a specific source ip /dest ip.

Example:

filter1 ="tcp port "+`port`+ " and ip6 host 2001::4 and tcp[tcpflags] & tcp-syn !=0 and !icmp and !arp and not host "+host_ip

            a= sniff(count =1,filter=filter1,iface=eth)

This throws an exception as shown below:
scapy.error.Scapy_Exception: Filter parse error

Body:
For complex filters, scapy allows you the use of a python function as a filter:

desiredip = "2001::4"
undesiredip = host_ip

def isMyPacket (pkt):
    if IPv6 in pkt:
        pktip6 = pkt[IPv6]
        if pktip6.src == desiredip or pktip6.dst == desiredip:
            if pktip6.src != undesiredip and pktip6.dst != undesiredip:
                if TCP in pktip6:
                    if pktip6[TCP].flags & 0x02: #Check if it is a SYN
                        return True #If all conditions are met
    return False

a= sniff(count =1,lfilter=isMyPacket,iface=eth)

Anyway, you don't need to check whether it is arp or icmp: If it is TCP you know for sure that it is not arp nor icmp.

More about TCP flags in scapy: Get TCP Flags with Scapy


问:
Hide/Blur Activity on opening another Activity over as pop-up Window(Not a Dialog Box) In Android
I am finding the solution from last few days, a solution will appreciate.
The scenario is:
There are two activities in my application 1. mainActivity 2.newActivity. On button click on mainActivity newActivity will be open as a pop-up window(not a dialog box). I want to hide/blur mainActivity when pop-up window(newActivity) is active and display mainActivity when pop-up(newActivity) activity close. how can I achieve this?

答:
I would suggest putting an opaque Drawable or background (either black for darkening or white for fading) behind your popup.

This is not blurring the main activity but it highlits the foreground popup.

Just use a color like:

```<code><color name="Translucent">#80000000</color>
</code>```

Body:
I would suggest putting an opaque Drawable or background (either black for darkening or white for fading) behind your popup.

This is not blurring the main activity but it highlits the foreground popup.

Just use a color like:

<color name="Translucent">#80000000</color>


问:
How to update DjangoItem in Scrapy
I've been working with Scrapy but run into a bit of a problem.

DjangoItem has a save method to persist items using the Django ORM. This is great, except that if I run a scraper multiple times, new items will be created in the database even though I may just want to update a previous value.

After looking at the documentation and source code, I don't see any means to update existing items.

I know that I could call out to the ORM to see if an item exists and update it, but it would mean calling out to the database for every single object and then again to save the item.

How can I update items if they already exist?

答:
for related models with foreignkeys</p>

```<code>def update_model(destination, source, commit=True):
    pk = destination.pk

    source_fields = fields_for_model(source)
    for key in source_fields.keys():
        setattr(destination, key, getattr(source, key))

    setattr(destination, 'pk', pk)

    if commit:
        destination.save()

    return destination
</code>```

Title: How to update DjangoItem in Scrapy

Body:
for related models with foreignkeys

def update_model(destination, source, commit=True):
    pk = destination.pk

    source_fields = fields_for_model(source)
    for key in source_fields.keys():
        setattr(destination, key, getattr(source, key))

    setattr(destination, 'pk', pk)

    if commit:
        destination.save()

    return destination


答:
add ng-app  in your template with ng-app="fb"

DEMO

 ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html ng-app="fb">
<head>
<title>Index</title>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.min.js"></script>
<script>
var app=angular.module('fb', []);
app.controller('home',function($scope){
    var hi;
    $scope.hi=5;
    //$rootScope.hola=9;
    console.log($scope.hi);
    //console.log($rootScope.hola);

    $scope.submitSignup=function()
    {
    var hi;
    $scope.hi=5;
    //$rootScope.hola=9;
    console.log($scope.hi);
    //console.log($rootScope.hola);
    console.log($scope.username);
        alert('button pressed');
    };
});
</script>
<body>
<div ng-controller='home'>
<input type="text" placeholder="Username" ng-model="username">
<br>
<input type="password" placeholder="Password" ng-model="password">
<br>
<button type="button" ng-click="submitSignup()">SignUp</button>
<br>
<p> {{username}} </p>
<p> {{hi}} </p>
{{hola}}
</div>
<p> index </p>
</body>
</html></code>```

Title: Angularjs not binding data and html not printing scope variables

Body:
add ng-app  in your template with ng-app="fb"

DEMO

<html ng-app="fb">
<head>
<title>Index</title>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.min.js"></script>
<script>
var app=angular.module('fb', []);
app.controller('home',function($scope){
    var hi;
    $scope.hi=5;
    //$rootScope.hola=9;
    console.log($scope.hi);
    //console.log($rootScope.hola);

    $scope.submitSignup=function()
    {
    var hi;
    $scope.hi=5;
    //$rootScope.hola=9;
    console.log($scope.hi);
    //console.log($rootScope.hola);
    console.log($scope.username);
        alert('button pressed');
    };
});
</script>
<body>
<div ng-controller='home'>
<input type="text" placeholder="Username" ng-model="username">
<br>
<input type="password" placeholder="Password" ng-model="password">
<br>
<button type="button" ng-click="submitSignup()">SignUp</button>
<br>
<p> {{username}} </p>
<p> {{hi}} </p>
{{hola}}
</div>
<p> index </p>
</body>
</html>


问:
Why would one omit the close tag?
I keep reading it is poor practice to use the PHP close tag ?> at the end of the file. The header problem seems irrelevant in the following context (and this is the only good argument so far):

Modern versions of PHP set the output_buffering flag in php.ini
  If output buffering is enabled, you can set HTTP headers and cookies after outputting HTML because the returned code is not sent to the browser immediately.

Every good practice book and wiki starts with this 'rule' but nobody offers good reasons.
Is there another good reason to skip the ending PHP tag?

答:
Sending headers earlier than the normal course may have far reaching consequences. Below are just a few of them that happened to come to my mind at the moment:

While current PHP releases may have output buffering on, the actual production servers you will be deploying your code on are far more important than any development or testing machines. And they do not always tend to follow latest PHP trends immediately.

You may have headaches over inexplicable functionality loss. Say, you are implementing some kind payment gateway, and redirect user to a specific URL after successful confirmation by the payment processor. If some kind of PHP error, even a warning, or an excess line ending happens, the payment may remain unprocessed and the user may still seem unbilled. This is also one of the reasons why needless redirection is evil and if redirection is to be used, it must be used with caution.

You may get "Page loading canceled" type of errors in Internet Explorer, even in the most recent versions. This is because an AJAX response/json include contains something that it shouldn't contain, because of the excess line endings in some PHP files, just as I've encountered a few days ago.

If you have some file downloads in your app, they can break too, because of this. And you may not notice it, even after years, since the specific breaking habit of a download depends on the server, the browser, the type and content of the file (and possibly some other factors I don't want to bore you with).

Finally, many PHP frameworks including Symfony, Zend and Laravel (there is no mention of this in the coding guidelines but it follows the suit) and the PSR-2 standard (item 2.2) require omission of the closing tag. PHP manual itself (1,2), Wordpress, Drupal and many other PHP software I guess, advise to do so. If you simply make a habit of following the standard (and setup PHP-CS-Fixer for your code) you can forget the issue. Otherwise you will always need to keep the issue in your mind.

Bonus: a few gotchas (actually currently one) related to these 2 characters:

Even some well-known libraries may contain excess line endings after ?>. An example is Smarty, even the most recent versions of both 2.* and 3.* branch have this. So, as always, watch for third party code. Bonus in bonus: A regex for deleting needless PHP endings: replace (\s*\?>\s*)$ with empty text in all files that contain PHP code.

ContentLicense: CC BY-SA 4.0

Title: Why would one omit the close tag?


问:
Fatal error: Call to a member function find() on boolean in /home/admin/web//public_html/index.php on line 14
PHP Simple HTML DOM Parser

Fatal error: Call to a member function find() on boolean in /home/admin/web//public_html/index.php on line 14

Why does it fail?

```<code>include("simple_html_dom.php");

$html = file_get_html('http://en.wikipedia.org/wiki/facebook');

$title = $html->find('h1[id=firstHeading]',0)->innertext;

echo $title;
</code>```

答:
I am not familiar with file_get_html but it probably returns false on errors, so you should check the returned value:</p>

```<code>if ($html === false) {
   // check what the error is (look for file_get_html documentation to understand how to get more info on the error
} else {
   // file is ok, process it
}
</code>```

Body:
PHP Simple HTML DOM Parser

Fatal error: Call to a member function find() on boolean in /home/admin/web//public_html/index.php on line 14

Why does it fail?

include("simple_html_dom.php");

$html = file_get_html('http://en.wikipedia.org/wiki/facebook');

$title = $html->find('h1[id=firstHeading]',0)->innertext;

echo $title;

Body:
I am not familiar with file_get_html but it probably returns false on errors, so you should check the returned value:

if ($html === false) {
   // check what the error is (look for file_get_html documentation to understand how to get more info on the error
} else {
   // file is ok, process it
}


问:
Searching unsorted array in perl?
I have an array with... lets say 100 elements. I want to check to see if any of the elements matches a particular string. For example:

@array = ('red','white','blue');

I also want to know if the array contains the string 'white' as one of the elements.
I know how to do this with a foreach loop and comparing each element, but... is there an easier (faster) way than looping through the whole array?

-Thanks

答:
It won't be any faster than looping, but you can use grep within Perl.</p>

```<code>$ perl -e "@array = ('red','white','blue'); print grep(/^white$/, @array);"
white
</code>```

Title: Searching unsorted array in perl?

Body:
It won't be any faster than looping, but you can use grep within Perl.

$ perl -e "@array = ('red','white','blue'); print grep(/^white$/, @array);"
white


问:
Relational Learning: What does this Prolog Output say?
I need to find relations in a prolog dataset. I have different kinds of trains with different features, for example Train1:

```<code>has_car(rel_east1,car_11).
has_car(rel_east1,car_12).
has_car(rel_east1,car_13).

infront(car_11,car_12).
infront(car_12,car_13).

size(car_11,long).
size(car_12,long).
size(car_13,short).

shape(car_11,hexagon).
shape(car_12,rectangle).
shape(car_13,hexagon).

load(car_11,rectangle).
load(car_12,circle).
load(car_13,triangle).
</code>```

I have ten different trains. Now I used the Metagol algorithm which shall learn the different relations within the different trains. As a result I get a list with different clauses. And here is my problem: I don't understand the inductive steps in between the clauses. For example:

```<code>relational(A):-has_car(A,B),relational_1(B).
relational_1(A):-relational_2(A,rectangle).
relational_2(A,B):-relational_3(A),shape(A,B).
relational_3(A):-infront(A,B),relational_4(B).
relational_4(A):-load(A,triangle).
</code>```

The only thing I know is, that the whole clause says: "There is a Train which contains a car which is in the shape rectangle. This car is in front of another car which contains a triangle."
But can anybody explain the code to me? Line for line?
For example, I don't understand how to read the 2nd line: "If there is a relation 1 with A, then there is also a relation 2 between A and rectangle"?

答:
I am not 100% sure, but I think the relational_x predicates, are relations (predicates) that are 'invented' by metagol for your learning task.
As naming invented predicates is a hard task (for which there is not a good solution for ) you get these type of names.

For instance if you used the example `kinship1' here : https://github.com/metagol/metagol

```<code>?- [kinship1].
Warning: /media/sam/9bb6ab40-5f17-481e-aba8-7bd9e4e05d66/home/sam/Documents/Prolog_practise/metagol/metagol.pl:250:
    Local definition of metagol:list_to_set/2 overrides weak import from lists
true.

    ?- a.
    % learning grandparent/2
    % clauses: 1
    % clauses: 2
    % clauses: 3
    grandparent_1(A,B):-father(A,B).
    grandparent_1(A,B):-mother(A,B).
    grandparent(A,B):-grandparent_1(A,C),grandparent_1(C,B).
    true .
</code>```

It learns the grandparent/2 relation by also learning grandparent_1/2. Which we as humans would call parent/2.

So relational_4(A):-load(A,triangle). you might call 'car carrying a load which is triangle shaped' . and relational_3(A):-infront(A,B),relational_4(B). would then be 'car in front of a car carrying a load which is triangle shaped' etc

```<code>relational_4(A):-load(A,triangle).
</code>```

If an object A is loaded with a triangle then A is relational_4
or
There is a car which has a load which is a triangle.

```<code>relational_3(A):-infront(A,B),relational_4(B).
</code>```

If an object A is infront of object B and B is relational_4 then A is relational_3
or
Car A is infront of a car B which has a load which is a triangle

```<code>relational_2(A,B):-relational_3(A),shape(A,B).
</code>```

If A is relational_3 and has shape B then A relational_2 B.
or
Car A is a car infront of another car which is loaded with a triangle, car A has an unspecified shape.

```<code>relational_1(A):-relational_2(A,rectangle).
</code>```

If an object A is relational_2 rectangle then A is relational_1
or
There is a car which has a rectangle shape, it is infront of a car which caries a triangle load.

```<code>relational(A):-has_car(A,B),relational_1(B).
</code>```

If an object A has a car B and B is relational_1 then relational A.

There is a train which has a car, that car is a rectangle in shape and it is infront of a car that has a triangle load

Body:
I need to find relations in a prolog dataset. I have different kinds of trains with different features, for example Train1:

has_car(rel_east1,car_11).
has_car(rel_east1,car_12).
has_car(rel_east1,car_13).

infront(car_11,car_12).
infront(car_12,car_13).

size(car_11,long).
size(car_12,long).
size(car_13,short).

shape(car_11,hexagon).
shape(car_12,rectangle).
shape(car_13,hexagon).

load(car_11,rectangle).
load(car_12,circle).
load(car_13,triangle).

I have ten different trains. Now I used the Metagol algorithm which shall learn the different relations within the different trains. As a result I get a list with different clauses. And here is my problem: I don't understand the inductive steps in between the clauses. For example:

relational(A):-has_car(A,B),relational_1(B).
relational_1(A):-relational_2(A,rectangle).
relational_2(A,B):-relational_3(A),shape(A,B).
relational_3(A):-infront(A,B),relational_4(B).
relational_4(A):-load(A,triangle).

The only thing I know is, that the whole clause says: "There is a Train which contains a car which is in the shape rectangle. This car is in front of another car which contains a triangle."
But can anybody explain the code to me? Line for line?
For example, I don't understand how to read the 2nd line: "If there is a relation 1 with A, then there is also a relation 2 between A and rectangle"?

Body:
I am not 100% sure, but I think the relational_x predicates, are relations (predicates) that are 'invented' by metagol for your learning task.
As naming invented predicates is a hard task (for which there is not a good solution for ) you get these type of names.

For instance if you used the example `kinship1' here : https://github.com/metagol/metagol

?- [kinship1].
Warning: /media/sam/9bb6ab40-5f17-481e-aba8-7bd9e4e05d66/home/sam/Documents/Prolog_practise/metagol/metagol.pl:250:
    Local definition of metagol:list_to_set/2 overrides weak import from lists
true.

    ?- a.
    % learning grandparent/2
    % clauses: 1
    % clauses: 2
    % clauses: 3
    grandparent_1(A,B):-father(A,B).
    grandparent_1(A,B):-mother(A,B).
    grandparent(A,B):-grandparent_1(A,C),grandparent_1(C,B).
    true .

It learns the grandparent/2 relation by also learning grandparent_1/2. Which we as humans would call parent/2.

So relational_4(A):-load(A,triangle). you might call 'car carrying a load which is triangle shaped' . and relational_3(A):-infront(A,B),relational_4(B). would then be 'car in front of a car carrying a load which is triangle shaped' etc

relational_4(A):-load(A,triangle).

If an object A is loaded with a triangle then A is relational_4
or
There is a car which has a load which is a triangle.

relational_3(A):-infront(A,B),relational_4(B).

If an object A is infront of object B and B is relational_4 then A is relational_3
or
Car A is infront of a car B which has a load which is a triangle

relational_2(A,B):-relational_3(A),shape(A,B).

If A is relational_3 and has shape B then A relational_2 B.
or
Car A is a car infront of another car which is loaded with a triangle, car A has an unspecified shape.

relational_1(A):-relational_2(A,rectangle).

If an object A is relational_2 rectangle then A is relational_1
or
There is a car which has a rectangle shape, it is infront of a car which caries a triangle load.

relational(A):-has_car(A,B),relational_1(B).

If an object A has a car B and B is relational_1 then relational A.

There is a train which has a car, that car is a rectangle in shape and it is infront of a car that has a triangle load


问:
Starting previous activity with Intent, without creating a new one
I want to have my MainActivity which shows a list of different TextViews.
The second Activity contains an EditText field. When I hit 'Submit' in the second Activity, I want to add the String from EditText to the list of TextViews in MainActivity.

The problem I have is that there is a new MainActivity started each time, so that only the latest Text is shown. I want to go back to my MainActivity and kind of "collect" the texts in there. Here is some code:

The MainActivity:

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

    private LinearLayout linLayout;
    private FloatingActionButton addEntry;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_full_timeline);
        linLayout = (LinearLayout) findViewById(R.id.entriesLinear);
        addEntry = (FloatingActionButton) findViewById(R.id.floatingActionButton); //starts the second Activity with the EditText

        //Here I want to get the text from my second Activity
        Intent intent = getIntent();
        String entry = intent.getStringExtra(EntryTextActivity.EXTRA_ENTRY);
        linLayout.addView(createNewTextView(entry), 0);
    }

    public void openEntryActivity(View view){
        Intent intent = new Intent(this, EntryTextActivity.class);
        startActivity(intent);

    }

    private TextView createNewTextView(String text) {
        final LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        final TextView textView = new TextView(this);
        textView.setLayoutParams(lparams);
        textView.setText(text);
        return textView;
    }
}
</code>```

This is the second Activity with the EditText:

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

public static final String EXTRA_ENTRY = "com.xyz.ENTRY";
    private Button submitButton;
    private EditText editTextEntry;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_entry_text);
        submitButton = (Button) findViewById(R.id.submitButton);
        submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(EntryTextActivity.this, FullTimeline.class);
                editTextEntry = (EditText) findViewById(R.id.editTextEntry);
                String entryText = editTextEntry.getText().toString();
                intent.putExtra(EXTRA_ENTRY, entryText);
                startActivity(intent);//this starts a new instance of the MainActivity ?
            }
        });
    }
}
</code>```

I hope that helps understanding my problem. I could not find any working solutions on here.

答:
I haven't tested it but i think that in the case you don't want to use a database, you can set your MainActivity as "singleInstance" in your manifest :

```<code><activity android:name="{your }" android:launchMode= "singleInstance" />
</code>```

Then you can add the new text in an your MainActivity's onResume

```<code> @Override
  public void onResume() {
    super.onResume();
    Intent intent = getIntent();
    String entry = intent.getStringExtra(EntryTextActivity.EXTRA_ENTRY);
    linLayout.addView(createNewTextView(entry), 0);
  }
</code>```

Body:
I want to have my MainActivity which shows a list of different TextViews.
The second Activity contains an EditText field. When I hit 'Submit' in the second Activity, I want to add the String from EditText to the list of TextViews in MainActivity.

The problem I have is that there is a new MainActivity started each time, so that only the latest Text is shown. I want to go back to my MainActivity and kind of "collect" the texts in there. Here is some code:

The MainActivity:

public class FullTimeline extends AppCompatActivity {

    private LinearLayout linLayout;
    private FloatingActionButton addEntry;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_full_timeline);
        linLayout = (LinearLayout) findViewById(R.id.entriesLinear);
        addEntry = (FloatingActionButton) findViewById(R.id.floatingActionButton); //starts the second Activity with the EditText

        //Here I want to get the text from my second Activity
        Intent intent = getIntent();
        String entry = intent.getStringExtra(EntryTextActivity.EXTRA_ENTRY);
        linLayout.addView(createNewTextView(entry), 0);
    }

    public void openEntryActivity(View view){
        Intent intent = new Intent(this, EntryTextActivity.class);
        startActivity(intent);

    }

    private TextView createNewTextView(String text) {
        final LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        final TextView textView = new TextView(this);
        textView.setLayoutParams(lparams);
        textView.setText(text);
        return textView;
    }
}

This is the second Activity with the EditText:

public class EntryTextActivity extends AppCompatActivity {

public static final String EXTRA_ENTRY = "com.xyz.ENTRY";
    private Button submitButton;
    private EditText editTextEntry;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_entry_text);
        submitButton = (Button) findViewById(R.id.submitButton);
        submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(EntryTextActivity.this, FullTimeline.class);
                editTextEntry = (EditText) findViewById(R.id.editTextEntry);
                String entryText = editTextEntry.getText().toString();
                intent.putExtra(EXTRA_ENTRY, entryText);
                startActivity(intent);//this starts a new instance of the MainActivity ?
            }
        });
    }
}

I hope that helps understanding my problem. I could not find any working solutions on here.

Body:
I haven't tested it but i think that in the case you don't want to use a database, you can set your MainActivity as "singleInstance" in your manifest :

<activity android:name="{your }" android:launchMode= "singleInstance" />

Then you can add the new text in an your MainActivity's onResume

 @Override
  public void onResume() {
    super.onResume();
    Intent intent = getIntent();
    String entry = intent.getStringExtra(EntryTextActivity.EXTRA_ENTRY);
    linLayout.addView(createNewTextView(entry), 0);
  }


问:
TypeError when using iloc to create dummy variables
Source data is from the book  Python_for_Data_Analysis, chp 2.
The data for movies is as follows and can also be found here:

```<code>movies.head(n=10)
Out[3]:
   movie_id                               title                        genres
0         1                    Toy Story (1995)   Animation|Children's|Comedy
1         2                      Jumanji (1995)  Adventure|Children's|Fantasy
2         3             Grumpier Old Men (1995)                Comedy|Romance
3         4            Waiting to Exhale (1995)                  Comedy|Drama
4         5  Father of the Bride Part II (1995)                        Comedy
5         6                         Heat (1995)         Action|Crime|Thriller
6         7                      Sabrina (1995)                Comedy|Romance
7         8                 Tom and Huck (1995)          Adventure|Children's
8         9                 Sudden Death (1995)                        Action
9        10                    GoldenEye (1995)     Action|Adventure|Thriller
</code>```

The following code has trouble when I use iloc:

```<code>import pandas as pd
import numpy as np
from pandas import Series,DataFrame

mnames = ['movie_id', 'title', 'genres']
movies = pd.read_table( 'movies.dat', sep='::',
                       engine='python', header=None, names=mnames)
movies.head(n=10)
genre_iter = (set(x.split('|')) for x in movies['genres'])
genres = sorted(set.union(*genre_iter))
dummies = DataFrame(np.zeros((len(movies), len(genres))), columns=genres)

for i, gen in enumerate(movies['genres']):
# the following code report error
# TypeError: '['Animation', "Children's", 'Comedy']' is an invalid key
    dummies.iloc[i,dummies.columns.get_loc(gen.split('|'))] = 1
# while loc can run successfully
    dummies.loc[dummies.index[[i]],gen.split('|')] = 1
movies_windic = movies.join(dummies.add_prefix('Genre_'))
movies_windic.iloc[0]
</code>```

I have some understanding of why Children's is error, but why Animation,Comedy are error? I have tried:

```<code>dummies.columns.get_loc('Animation')
</code>```

and the result is 2.

答:
This is a pretty simple (and fast) answer using string matching that should work fine here and in any case where the genres names don't overlap.  E.g. if you had categories "crime" and "crime thriller" then a crime thriller would be categorized under both crime AND crime thriller rather than just crime thriller.  (But see note below for how you could generalize this.)

```<code>for g in genres:
    movies[g] = movies.genres.str.contains(g).astype(np.int8)
</code>```

(Note using np.int8 rather than int will save a lot of memory as int defaults to 64 bits rather than 8)

Results for movies.head(2):

```<code>   movie_id             title                        genres  Action  \
0         1  Toy Story (1995)   Animation|Children's|Comedy       0
1         2    Jumanji (1995)  Adventure|Children's|Fantasy       0

   Adventure  Animation  Children's  Comedy  Crime  Documentary   ...     \
0          0          1           1       1      0            0   ...
1          1          0           1       0      0            0   ...

   Fantasy  Film-Noir  Horror  Musical  Mystery  Romance  Sci-Fi  Thriller  \
0        0          0       0        0        0        0       0         0
1        1          0       0        0        0        0       0         0

   War  Western
0    0        0
1    0        0
</code>```

The following generalizaion of the above code may be overkill but gives you a more general approach that should avoid potential double counting of genre categories (e.g. equating Crime and Crime Thriller):

```<code># add '|' delimiter to beginning and end of the genres column
movies['genres2'] = '|' + movies['genres'] + '|'

# search for '|Crime|' rather than 'Crime' which is much safer b/c
# we don't match a category which merely contains 'Crime', we
# only match 'Crime' exactly
for g in genres:
    movies[g+'2'] movies.genres2.str.contains('\|'+g+'\|').astype(np.int8)
</code>```

(If you're better with regular expressions than me you wouldn't need to add the '|' at the beginning and end ;-)

Body:
Source data is from the book  Python_for_Data_Analysis, chp 2.
The data for movies is as follows and can also be found here:

movies.head(n=10)
Out[3]:
   movie_id                               title                        genres
0         1                    Toy Story (1995)   Animation|Children's|Comedy
1         2                      Jumanji (1995)  Adventure|Children's|Fantasy
2         3             Grumpier Old Men (1995)                Comedy|Romance
3         4            Waiting to Exhale (1995)                  Comedy|Drama
4         5  Father of the Bride Part II (1995)                        Comedy
5         6                         Heat (1995)         Action|Crime|Thriller
6         7                      Sabrina (1995)                Comedy|Romance
7         8                 Tom and Huck (1995)          Adventure|Children's
8         9                 Sudden Death (1995)                        Action
9        10                    GoldenEye (1995)     Action|Adventure|Thriller

The following code has trouble when I use iloc:

import pandas as pd
import numpy as np
from pandas import Series,DataFrame

mnames = ['movie_id', 'title', 'genres']
movies = pd.read_table( 'movies.dat', sep='::',
                       engine='python', header=None, names=mnames)
movies.head(n=10)
genre_iter = (set(x.split('|')) for x in movies['genres'])
genres = sorted(set.union(*genre_iter))
dummies = DataFrame(np.zeros((len(movies), len(genres))), columns=genres)

for i, gen in enumerate(movies['genres']):
# the following code report error
# TypeError: '['Animation', "Children's", 'Comedy']' is an invalid key
    dummies.iloc[i,dummies.columns.get_loc(gen.split('|'))] = 1
# while loc can run successfully
    dummies.loc[dummies.index[[i]],gen.split('|')] = 1
movies_windic = movies.join(dummies.add_prefix('Genre_'))
movies_windic.iloc[0]

I have some understanding of why Children's is error, but why Animation,Comedy are error? I have tried:

dummies.columns.get_loc('Animation')

and the result is 2.

Body:
This is a pretty simple (and fast) answer using string matching that should work fine here and in any case where the genres names don't overlap.  E.g. if you had categories "crime" and "crime thriller" then a crime thriller would be categorized under both crime AND crime thriller rather than just crime thriller.  (But see note below for how you could generalize this.)

for g in genres:
    movies[g] = movies.genres.str.contains(g).astype(np.int8)

(Note using np.int8 rather than int will save a lot of memory as int defaults to 64 bits rather than 8)

Results for movies.head(2):

   movie_id             title                        genres  Action  \
0         1  Toy Story (1995)   Animation|Children's|Comedy       0
1         2    Jumanji (1995)  Adventure|Children's|Fantasy       0

   Adventure  Animation  Children's  Comedy  Crime  Documentary   ...     \
0          0          1           1       1      0            0   ...
1          1          0           1       0      0            0   ...

   Fantasy  Film-Noir  Horror  Musical  Mystery  Romance  Sci-Fi  Thriller  \
0        0          0       0        0        0        0       0         0
1        1          0       0        0        0        0       0         0

   War  Western
0    0        0
1    0        0

The following generalizaion of the above code may be overkill but gives you a more general approach that should avoid potential double counting of genre categories (e.g. equating Crime and Crime Thriller):

# add '|' delimiter to beginning and end of the genres column
movies['genres2'] = '|' + movies['genres'] + '|'

# search for '|Crime|' rather than 'Crime' which is much safer b/c
# we don't match a category which merely contains 'Crime', we
# only match 'Crime' exactly
for g in genres:
    movies[g+'2'] movies.genres2.str.contains('\|'+g+'\|').astype(np.int8)

(If you're better with regular expressions than me you wouldn't need to add the '|' at the beginning and end ;-)


问:
Custom data annotation validation attribute with client side validation
I have made a custom data annotation attribute which verifies whether an email already exists in my database like this:

```<code>   public class ValidateEmail : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            using (var ctx = new myCtx())
            {
                if (value != null)
                {
                    var valueAsString = value.ToString().ToLower();
                    IEnumerable<string> email = ctx.Users.Where(x => x.Email != null).Select(x => x.Email);
                    if (email.Contains(valueAsString))
                    {
                        var errorMessage = FormatErrorMessage(validationContext.DisplayName);
                        return new ValidationResult(errorMessage);
                    }
                }
                return ValidationResult.Success;
            }
        }
    }
</code>```

And in my view model I set it like this:

```<code>   [ValidateEmail(ErrorMessage = "Email exists")]
        [Required(ErrorMessage = "Required")]
        [RegularExpression(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$", ErrorMessage = "Invalid Email")]
        public string Email { get; set; }
</code>```

This works perfectly when the page reloads...But I would like now to change this so that I enable client side validation and message displaying without reloading the page itself...

How can I modify this validation attribute to make it compliable with jquery's unobstrusive validation in .NET MVC?

Based on @Sayan's link, I've implemented something like this:

```<code>   public class ValidateEmail : ValidationAttribute, IClientValidatable
    {
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule();
            rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
            rule.ValidationType = "emailvalidate";

            yield return rule;

        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            using (var ctx = new myContext())
            {
                if (value != null)
                {
                    var valueAsString = value.ToString().ToLower();
                    IEnumerable<string> email = ctx.Users.Where(x => x.Email != null).Select(x => x.Email);
                    if (email.Contains(valueAsString))
                    {
                        var errorMessage = FormatErrorMessage(validationContext.DisplayName);
                        return new ValidationResult(errorMessage);
                    }
                }
                return ValidationResult.Success;
            }
        }
    }
</code>```

and client side:

```<code>$.validator.addMethod("emailvalidate", function (value, element) {
{
    console.log("value: " + value + " " + element);
}});
$.validator.unobtrusive.adapters.add("emailvalidate", function (options) {

      //adding rules for validator
    options.rules["emailvalidate"] = true;
    if (options.message) {
        options.messages["emailvalidate"] = options.message;
    }

});
</code>```

But whatever I insert now in the email field as email like:

```<code>myemail@ymail.xyz
</code>```

I get the error that email exists ?

答:
You can implement IClientValidatable in your ValidateEmail validation attribute to supply the data-val-xxx attributes to the client side.

Then you can write the jQuery unobtrusive validator and adapter to validate the field value on client side using the data-val-xxx rendered in HTML.

Make sure to return true (truthy value) or false (falsy value) from the jQuery validator based on whether the field value is valid or not respectively.

Lastly, include this custom jQuery validator script to your view.

You can find more details here. Though this blog post presents a slightly complicated scenario, but seeing how to use IClientValidatable and how to write jQuery unobtrusive validator is enough.

Hope this is helpful.

Body:
I have made a custom data annotation attribute which verifies whether an email already exists in my database like this:

   public class ValidateEmail : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            using (var ctx = new myCtx())
            {
                if (value != null)
                {
                    var valueAsString = value.ToString().ToLower();
                    IEnumerable<string> email = ctx.Users.Where(x => x.Email != null).Select(x => x.Email);
                    if (email.Contains(valueAsString))
                    {
                        var errorMessage = FormatErrorMessage(validationContext.DisplayName);
                        return new ValidationResult(errorMessage);
                    }
                }
                return ValidationResult.Success;
            }
        }
    }

And in my view model I set it like this:

   [ValidateEmail(ErrorMessage = "Email exists")]
        [Required(ErrorMessage = "Required")]
        [RegularExpression(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$", ErrorMessage = "Invalid Email")]
        public string Email { get; set; }

This works perfectly when the page reloads...But I would like now to change this so that I enable client side validation and message displaying without reloading the page itself...

How can I modify this validation attribute to make it compliable with jquery's unobstrusive validation in .NET MVC?

Based on @Sayan's link, I've implemented something like this:

   public class ValidateEmail : ValidationAttribute, IClientValidatable
    {
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule();
            rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
            rule.ValidationType = "emailvalidate";

            yield return rule;

        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            using (var ctx = new myContext())
            {
                if (value != null)
                {
                    var valueAsString = value.ToString().ToLower();
                    IEnumerable<string> email = ctx.Users.Where(x => x.Email != null).Select(x => x.Email);
                    if (email.Contains(valueAsString))
                    {
                        var errorMessage = FormatErrorMessage(validationContext.DisplayName);
                        return new ValidationResult(errorMessage);
                    }
                }
                return ValidationResult.Success;
            }
        }
    }

and client side:

$.validator.addMethod("emailvalidate", function (value, element) {
{
    console.log("value: " + value + " " + element);
}});
$.validator.unobtrusive.adapters.add("emailvalidate", function (options) {

      //adding rules for validator
    options.rules["emailvalidate"] = true;
    if (options.message) {
        options.messages["emailvalidate"] = options.message;
    }

});

But whatever I insert now in the email field as email like:

myemail@ymail.xyz

I get the error that email exists ?


问:
Android: AndroidManifest.xml with errors after doing checkout from respository
After doing the checkout of repository (Bitbucket) I can't run my project in Android Studio (version 2.3.3) because I have errors(in red) in AndroidManifest.xml as you can see in the screenshot below:

AndroidManifest.xml

strings.xml

The errors are "Cannot resolve symbol @string/app_name" and "Unresolved class MainActivity". I've already do the Invalidate/Caches Restart but it didn't resolve it. Can anyone help me please?

答:
Try this:

Build -> Rebuild Project

Body:
Try this:

Build -> Rebuild Project


问:
what is the best way to transform a java Class into a php class?
I'd like to transform my java Class file intp a php class file. Do you know a good open source tool to do this?

Thanks you very much,

Bat

答:
I don't know any tool able to convert Java to PHP, but you may want to seize the opportunity of having a well structured source program in Java and keep a similar structure in PHP - as much as possible (by using classes, keeping the files segmentation, it'll help the conversion anyway)

Unless you have a pretty complex Java code (synchronized methods, Spring transactions, multi threaded access, data isolation...), or with heavy subclassing, or using an exotic framework, the logic itself should translate well from Java to PHP.

The templates should not be a real pain.

Regarding data structure, PHP usually makes the programmer life rather easy - basically you can make an array() from a Set, a Map, a List/Array[].

Regarding data types, you have to be careful when PHP (not typed) automatically converts a fraction to a double if necessary (in Java (int)4/3 is 1, and 1.333... in PHP).

Strings should be ok (implement mbstring in PHP - Java is utf8 by default)

And PHP offers so many functions that you should be able to find most of the necessary Java equivalent features.

Interesting project - I would be glad if you could edit your question and post the progress and how you finally could deal with the challenge.


问:
React function with multiple params
I'm having issues trying to use my delete function that calls an API method for removing that selected item from the database.

The API just accepts the page ID, so I've been trying to send the ID to the api.

This is the function that lives in the main container of the app.

```<code>  deletePage(id) {
    instance.put(`/admin/deletePage/${id}`).then((response) => {
      this.getPages();
      window.location.replace('/')
    }).catch((error) => {
      console.log(error)
    })
  }
</code>```

I then pass this function down as a prop to the Dashboard component, where I create another function to handle the delete:

```<code>  handleDelete(e, id) {
    e.preventDefault()
    this.props.deletePage(id)
  }
</code>```

and finally, my render function:

```<code>render() {
    const pages = this.props.pages.map((page, i) => {
        return (
        <div key={i}>
        <h2>{page.title}</h2>
        <a href={`/admin/edit-page/${i}`}>Edit</a>
        <button onClick={this.handleDelete(i)}>Delete</button>
        </div>
        )
    });

    return (
      <div>
        <h2>Dashboard</h2>
        {pages}
      </div>
    );
  }
</code>```

Currently I get this error in console: e.preventDefault is not a function

And if I remove the preventDefault line it just causes a constant reload.

Please help. Just trying to delete stuff mwhaha

答:
I think there's two problems here.

First, the order of this.handleDelete params should be reversed: this.handleDelete(id, e). The event object is always supplied last.

Second, onClick={this.handleDelete(i)} should be onClick={this.handleDelete.bind(this, i)}. onClick={this.handleDelete(i)} assigns the result of calling this.handleDelete to onClick. You're accidentally calling this.handleClick during the render phase when you mean for that function to be called when the user clicks the button.

Title: React function with multiple params

Body:
I'm having issues trying to use my delete function that calls an API method for removing that selected item from the database.

The API just accepts the page ID, so I've been trying to send the ID to the api.

This is the function that lives in the main container of the app.

  deletePage(id) {
    instance.put(`/admin/deletePage/${id}`).then((response) => {
      this.getPages();
      window.location.replace('/')
    }).catch((error) => {
      console.log(error)
    })
  }

I then pass this function down as a prop to the Dashboard component, where I create another function to handle the delete:

  handleDelete(e, id) {
    e.preventDefault()
    this.props.deletePage(id)
  }

and finally, my render function:

render() {
    const pages = this.props.pages.map((page, i) => {
        return (

{page.title}

        <a href={`/admin/edit-page/${i}`}>Edit
        <button onClick={this.handleDelete(i)}>Delete</button>

        )
    });

    return (

Dashboard

        {pages}

    );
  }

Currently I get this error in console: e.preventDefault is not a function

And if I remove the preventDefault line it just causes a constant reload.

Please help. Just trying to delete stuff mwhaha


问:
using nodejs cluster in production?
i was reading nodejs cluster to run multiple instances of node appication

```<code>    const cluster = require('cluster');
    const http = require('http');
    const numCPUs = require('os').cpus().length;

    if (cluster.isMaster) {
    console.log(`Master ${process.pid} is running`);
    for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
     }
     cluster.on('exit', (worker, code, signal) => {
     console.log(`worker ${worker.process.pid} died`);
      });
     }
    else {

     http.createServer((req, res) => {
     res.writeHead(200);
     res.end('hello world\n');
      }).listen(8000);

     console.log(`Worker ${process.pid} started`);
     }
</code>```

is using this approach good in a production environment.
where the number of requests is more

答:
You can rather use pm2/strongloop for managing this.Because all these modules are production ready and really easy to manage.

I personally feel pm2 is awesome to manage node processes.

Use following link to know more about pm2
http://pm2.keymetrics.io/

Title: using nodejs cluster in production?

Body:
i was reading nodejs cluster to run multiple instances of node appication

    const cluster = require('cluster');
    const http = require('http');
    const numCPUs = require('os').cpus().length;

    if (cluster.isMaster) {
    console.log(`Master ${process.pid} is running`);
    for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
     }
     cluster.on('exit', (worker, code, signal) => {
     console.log(`worker ${worker.process.pid} died`);
      });
     }
    else {

     http.createServer((req, res) => {
     res.writeHead(200);
     res.end('hello world\n');
      }).listen(8000);

     console.log(`Worker ${process.pid} started`);
     }

is using this approach good in a production environment.
where the number of requests is more


问:
How to format the text below
I am displaying a text from database. Earlier we are displaying this from an html file means just we are accessing that html file so we are able to see that text format what we have placed in that HTML file. Now we stored it in the database and displaying it in UI. But the thing is we are not able to display it in the required format can any one help me to do this.

The below text we displaying in UI is

User-agent:

```<code> * Disallow:/national/ Disallow: /ax/en/ Disallow: /ki/fi/ Disallow: /es/en/
Disallow: /cbc/ Disallow: /xsd/en/ Disallow: /lg/ Disallow: /re/ like this.
</code>```

But we need to display it in the below format

```<code>    User-agent *
    Disallow:/national/
    Disallow: /ax/en/
    Disallow: /ki/fi/
    Disallow: /es/en/
    Disallow: /cbc/
    Disallow: /xsd/en/
    Disallow: /lg/
    Disallow: /re/
</code>```

Like this.

答:
I don't know what jcr and cq5 are but,

Your problem seems to be the String delimiter.

if I understand, in HTML it was ok, from DB it is not.

(there are alot of GUIs that supports html subset of tags)
I would try to replace the delimiters (probably \n) with the HTML br tag.

br is the HTML way of saying break row (new line)

```<code>this is a line of text <br>
this is the next line
</code>```

Title: How to format the text below

Body:
I am displaying a text from database. Earlier we are displaying this from an html file means just we are accessing that html file so we are able to see that text format what we have placed in that HTML file. Now we stored it in the database and displaying it in UI. But the thing is we are not able to display it in the required format can any one help me to do this.

The below text we displaying in UI is

User-agent:

 * Disallow:/national/ Disallow: /ax/en/ Disallow: /ki/fi/ Disallow: /es/en/
Disallow: /cbc/ Disallow: /xsd/en/ Disallow: /lg/ Disallow: /re/ like this.

But we need to display it in the below format

    User-agent *
    Disallow:/national/
    Disallow: /ax/en/
    Disallow: /ki/fi/
    Disallow: /es/en/
    Disallow: /cbc/
    Disallow: /xsd/en/
    Disallow: /lg/
    Disallow: /re/

Like this.

Body:
I don't know what jcr and cq5 are but,

Your problem seems to be the String delimiter.

if I understand, in HTML it was ok, from DB it is not.

(there are alot of GUIs that supports html subset of tags)
I would try to replace the delimiters (probably \n) with the HTML br tag.

br is the HTML way of saying break row (new line)

this is a line of text <br>
this is the next line


问:
How to create a user defined function in PHP exactly the same as str_replace(), without using any other built-in functions except for strlen()
```<code><?php
echo my_string_replace("world","jonathan","hello world helloworld");

function my_string_replace($find, $replace, $string)
{
//Block of codes here...
}
?>
</code>```

I can only use loops, if else statements, and other commands such as break and continue. I want to create my own algorithm. Please help me. This should output : hello jonathan hellojonathan"

答:
That was a fun brain teaser. Here you go:</p>

```<code>echo my_string_replace("world", "jonathan", "hello world helloworld");

function my_string_replace($find, $replace, $string)
{
    $characterCount = strlen($string);
    $findCount      = strlen($find);
    $replaceCount   = strlen($replace);

    for ($i = 0; $i < $characterCount - $findCount +1; $i++) {
        if ($string[$i] == $find[0]) {
            $j     = 1;
            $found = true;
            while ($j < $findCount) {
                if ($string[$i + $j] != $find[$j]) {
                    $found = false;
                    break;
                }
                $j++;
            }
            if ($found) {
                // copy string until current position
                $replaced = '';
                for ($x = 0; $x < $i; $x++) {
                    $replaced .= $string[$x];
                }
                // append replacement
                $replaced .= $replace;
                // copy after match till end
                for ($x = $i + $findCount; $x < $characterCount; $x++) {
                    $replaced .= $string[$x];
                }
                // continue with replaced string, after replacement
                $string         = $replaced;
                $characterCount = strlen($string);
                $i              = $i + $replaceCount;
            }
        }
    }

    return $string;
}
</code>```

Body:
<?php
echo my_string_replace("world","jonathan","hello world helloworld");

function my_string_replace($find, $replace, $string)
{
//Block of codes here...
}
?>

I can only use loops, if else statements, and other commands such as break and continue. I want to create my own algorithm. Please help me. This should output : hello jonathan hellojonathan"

Body:
That was a fun brain teaser. Here you go:

echo my_string_replace("world", "jonathan", "hello world helloworld");

function my_string_replace($find, $replace, $string)
{
    $characterCount = strlen($string);
    $findCount      = strlen($find);
    $replaceCount   = strlen($replace);

    for ($i = 0; $i < $characterCount - $findCount +1; $i++) {
        if ($string[$i] == $find[0]) {
            $j     = 1;
            $found = true;
            while ($j < $findCount) {
                if ($string[$i + $j] != $find[$j]) {
                    $found = false;
                    break;
                }
                $j++;
            }
            if ($found) {
                // copy string until current position
                $replaced = '';
                for ($x = 0; $x < $i; $x++) {
                    $replaced .= $string[$x];
                }
                // append replacement
                $replaced .= $replace;
                // copy after match till end
                for ($x = $i + $findCount; $x < $characterCount; $x++) {
                    $replaced .= $string[$x];
                }
                // continue with replaced string, after replacement
                $string         = $replaced;
                $characterCount = strlen($string);
                $i              = $i + $replaceCount;
            }
        }
    }

    return $string;
}


问:
CSS - Background images
Probably very silly question, but since I am trying to put my website online using my domaine which I have recently purchased, the background image doesn't seem to load at all.

Any idea?

body {
  margin: 0;
  background-image: url("homepage1.jpg");
  background-size: cover;
  font-family: 'Parisienne', cursive;
  background-repeat: no-repeat;
}

.navbar {
  background-color: none;
  width: 100%;
  height: 30px;
  padding-top: 0;
  text-align: center;
}

.navbar a {
  padding: 20px;
  font-size: 2.0em;
  color: black;
  text-decoration: none;
}

.navbar a:hover:not(.active) {
  color: #B22222;
}

.homepage {
  padding-top: 15px;
}

#welcome {
  color: black;
  font-size: 30px;
  text-align: center;
}

#welcome h1 {
  font-size: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="homepage">
  <div class="navbar">
    Home
    Schedule
    Accommodations
    Travel
    Activities
    Contact
  </div>
  <div id="welcome">
    <h1>Tracey & Jonathan's Wedding</h1>
    <p>16 / 08 / 2018</p>
  </div>
</div></code>```

答:
Folder Structure 1

index.html

homepage1.jpg

style.css

Then background-image url will be

```<code>background-image: url("homepage1.jpg");
</code>```

Folder Structure

index.html

images (folder)

homepage1.jpg

style.css

Then background-image url will be

```<code>background-image: url("images/homepage1.jpg");
</code>```

Folder Structure 2

index.html

images (folder)

homepage1.jpg

style (folder)

style.css

Then the background-image url will be

```<code>background-image: url(../images/homepage1.jpg");
</code>```

Also compare the actual image name along with background-image url.

Title: CSS - Background images

Body:
Probably very silly question, but since I am trying to put my website online using my domaine which I have recently purchased, the background image doesn't seem to load at all.

Any idea?

body {
  margin: 0;
  background-image: url("homepage1.jpg");
  background-size: cover;
  font-family: 'Parisienne', cursive;
  background-repeat: no-repeat;
}

.navbar {
  background-color: none;
  width: 100%;
  height: 30px;
  padding-top: 0;
  text-align: center;
}

.navbar a {
  padding: 20px;
  font-size: 2.0em;
  color: black;
  text-decoration: none;
}

.navbar a:hover:not(.active) {
  color: #B22222;
}

.homepage {
  padding-top: 15px;
}

#welcome {
  color: black;
  font-size: 30px;
  text-align: center;
}

#welcome h1 {
  font-size: 50px;
}

    Home
    Schedule
    Accommodations
    Travel
    Activities
    Contact

Tracey & Jonathan's Wedding

16 / 08 / 2018

Body:
Folder Structure 1

index.html

homepage1.jpg

style.css

Then background-image url will be

background-image: url("homepage1.jpg");

Folder Structure

index.html

images (folder)

homepage1.jpg

style.css

Then background-image url will be

background-image: url("images/homepage1.jpg");

Folder Structure 2

index.html

images (folder)

homepage1.jpg

style (folder)

style.css

Then the background-image url will be

background-image: url(../images/homepage1.jpg");

Also compare the actual image name along with background-image url.


问:
Explanation of the Function that Defines strlen
I'm learning about pointers in c++.

I have researched and found the manual function that defines strlen to be something like this.

```<code>int strlen(const char *a){
    const char *b;
    for (b=a;*b;++b);
    return b-a;
}
</code>```

Would anyone be able to explain this block of code in plain english? In particular, why is *b set as the terminating condition in the for loop?

This is not an answer to homework. It's just a question that arose while I was researching. Thanks.

答:
In both C and C++ strings are really called null terminated byte strings. That null terminator is equal to zero. And in both C and C++ the value zero is equivalent to false.

What the loop does is to iterate until the "current character" (pointed to by b) becomes equal to the terminator.

Body:
I'm learning about pointers in c++.

I have researched and found the manual function that defines strlen to be something like this.

int strlen(const char *a){
    const char *b;
    for (b=a;*b;++b);
    return b-a;
}

Would anyone be able to explain this block of code in plain english? In particular, why is *b set as the terminating condition in the for loop?

This is not an answer to homework. It's just a question that arose while I was researching. Thanks.


问:
Should defined numbers be stored in a table within the database?
Imagine you have a table - lets contrive an example where this is Orders - which has a field named type, which may be only one of a few fixed values (lets say 0 or 1, for Quotation and Order).

Should all the possible values of type be represented by another table in the database (with just typeID and typeName columns?), and Orders made to reference the new table?

Or is it normal to leave these numbers as-is and have them documented outside the database?

If this is a "it depends" situation: What are the important implications of both options?

I have used the first option in a recent University assignement, but without really thinking about why - and looking back at the design now I'm wondering whether this is important.

I never once queried the reference table as part of my application - because I didn't "need" to - does this indicate the reference table is unneeded, or is this a flaw in my application because it should be checking the ref table (what for?)?

答:
If its a value that only has meaning for that table, then it suggests an enum type for that field.  </p>

<p>If the value has meaning in multiple tables, I would use a reference table like you did.  </p>

Body:
If its a value that only has meaning for that table, then it suggests an enum type for that field.

If the value has meaning in multiple tables, I would use a reference table like you did.


答:
try clean and rebuild the project again
also check is gradle build succesfully ?</p>

Title: Android: AndroidManifest.xml with errors after doing checkout from respository

Body:
After doing the checkout of repository (Bitbucket) I can't run my project in Android Studio (version 2.3.3) because I have errors(in red) in AndroidManifest.xml as you can see in the screenshot below:

AndroidManifest.xml

strings.xml

The errors are "Cannot resolve symbol @string/app_name" and "Unresolved class MainActivity". I've already do the Invalidate/Caches Restart but it didn't resolve it. Can anyone help me please?


问:
Get an outlet variable by name
Looking for a way to access an outlet programmatically in swift:

```<code>@IBOutlet var label1: UILabel?
var outletName = "label1"
view[outletName].text = "hello, world!"
</code>```

Is the only way to do this to create my own custom mapping, like so?

```<code>@IBOutlet var label1: UILabel?
let outlets = ["label1": label1]
let outletName = "label1"
outlets[outletName].text = "hello, world!"
</code>```

EDIT: Seems my original question was poorly worded, lets try again:

I'm looking to access a variable through some string identifier. In my original question I was trying to ask if a variable can be accessed by the name of the variable itself somehow. IE accessing variable label1 with a string of the variable's name "label1".

答:
Turning a string into a property access is actually kind of difficult in pure Swift.

You can use some objective-c APIs to help you out.

```<code>// Mark your outlet variable as dynamic
@IBOutlet dynamic var label1: UILabel?

var outletName = "label1"
// Then you can access it via a key path (aka string)
if let myProperty = value(forKey: outletName) as? UILabel {
    myProperty.text = "Hello, world!"
}
</code>```

Title: Get an outlet variable by name

Body:
Looking for a way to access an outlet programmatically in swift:

@IBOutlet var label1: UILabel?
var outletName = "label1"
view[outletName].text = "hello, world!"

Is the only way to do this to create my own custom mapping, like so?

@IBOutlet var label1: UILabel?
let outlets = ["label1": label1]
let outletName = "label1"
outlets[outletName].text = "hello, world!"

EDIT: Seems my original question was poorly worded, lets try again:

I'm looking to access a variable through some string identifier. In my original question I was trying to ask if a variable can be accessed by the name of the variable itself somehow. IE accessing variable label1 with a string of the variable's name "label1".

Body:
Turning a string into a property access is actually kind of difficult in pure Swift.

You can use some objective-c APIs to help you out.

// Mark your outlet variable as dynamic
@IBOutlet dynamic var label1: UILabel?

var outletName = "label1"
// Then you can access it via a key path (aka string)
if let myProperty = value(forKey: outletName) as? UILabel {
    myProperty.text = "Hello, world!"
}


问:
I have a text file encoded in several different formats, I need to force that file text to be UTF-8 on Javascript
I have a web application where I need to read from the hard disk a text file, the problem is that I don't know in which format is saved.  Could be in the 4 formats that window's notepad let you save the txt file like ANSI, UNICODE, UNICODE Big ENDIAN and UTF-8.

My web application already reads UTF-8, but if for example the user saves the file on ANSI, my web app will display some weird characteres.

I'm using this function in JAVASCRIPT to read the file text from the hard drive

```<code> $.get('./file.txt', function (data) {
        document.getElementById('file').value = data;
 }, 'text');
</code>```

Is there any way to get this fixed?

Thank you in advance

答:
You can try the following code:

```<code>var newString = decodeURIComponent(escape(oldstring));
</code>```

The escape function will encode the characters as two-digit or four digit hex strings, while the encodeURIComponent function will encode them as UTF-8.

Body:
I have a web application where I need to read from the hard disk a text file, the problem is that I don't know in which format is saved.  Could be in the 4 formats that window's notepad let you save the txt file like ANSI, UNICODE, UNICODE Big ENDIAN and UTF-8.

My web application already reads UTF-8, but if for example the user saves the file on ANSI, my web app will display some weird characteres.

I'm using this function in JAVASCRIPT to read the file text from the hard drive

 $.get('./file.txt', function (data) {
        document.getElementById('file').value = data;
 }, 'text');

Is there any way to get this fixed?

Thank you in advance

Body:
You can try the following code:

var newString = decodeURIComponent(escape(oldstring));

The escape function will encode the characters as two-digit or four digit hex strings, while the encodeURIComponent function will encode them as UTF-8.


问:
Bash - How to get multi line text between XML tags
I have a text file...

```<code># <?xml version="1.0" encoding="UTF-8"?>
<response>
<content>Pulsa:Rp200,Bonus:0 s/d 12-JUL-17. 1GB Rp10rb.Mau?
1. Mau
2. Info
3. Internet
4. RAMADHAN HOTSALE
5. Nelpon
6. SMS
7. BB
8. NEW:UNLIMITED INTERNET
9. Roaming
10. 100MB2K</content>
</response>
</code>```

and I want to extract the text between <content> up to </content>. I have tried:

```<code>grep -oP '(?<=<content> ).*?(?= </content>)' file
</code>```

But it doesn't output anything, I want the end result to be like this:

```<code>Pulsa:Rp200,Bonus:0 s/d 12-JUL-17. 1GB Rp10rb.Mau?
1. Mau
2. Info
3. Internet
4. RAMADHAN HOTSALE
5. Nelpon
6. SMS
7. BB
8. NEW:UNLIMITED INTERNET
9. Roaming
10. 100MB2K
</code>```

How can I do this?

答:
Alternate approach:</p>

```<code>tr \\n \\r < test.xml | sed 's:.*<content>\([^<]*\)<.*:\1:' | tr \\r \\n
</code>```

Body:
I have a text file...

# <?xml version="1.0" encoding="UTF-8"?>
<response>
<content>Pulsa:Rp200,Bonus:0 s/d 12-JUL-17. 1GB Rp10rb.Mau?
1. Mau
2. Info
3. Internet
4. RAMADHAN HOTSALE
5. Nelpon
6. SMS
7. BB
8. NEW:UNLIMITED INTERNET
9. Roaming
10. 100MB2K</content>
</response>

and I want to extract the text between <content> up to </content>. I have tried:

grep -oP '(?<=<content> ).*?(?= </content>)' file

But it doesn't output anything, I want the end result to be like this:

Pulsa:Rp200,Bonus:0 s/d 12-JUL-17. 1GB Rp10rb.Mau?
1. Mau
2. Info
3. Internet
4. RAMADHAN HOTSALE
5. Nelpon
6. SMS
7. BB
8. NEW:UNLIMITED INTERNET
9. Roaming
10. 100MB2K

How can I do this?

Body:
Alternate approach:

tr \\n \\r < test.xml | sed 's:.*<content>\([^<]*\)<.*:\1:' | tr \\r \\n


问:
Failed to Autowire beans in a Java thread in Spring Boot
I successfully autowired beans and sent emails in my previous code. The code is as follow:

```<code>public class HomeController{
    @Autowired
    private MailConstructor mailConstructor;

    @Autowired
    private JavaMailSender mailSender;

    ...
    String token = UUID.randomUUID().toString();
    String appUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
    SimpleMailMessage newEmail = mailConstructor.constructResetTokenEmail(appUrl, request.getLocale(), token, user);

    mailSender.send(newEmail);
    ...
}
</code>```

Now I want to send the email in a new thread and I wrote my code referring to this link:Why does Autowiring not function in a thread?
My new code is as follow:

```<code>public class EmailUtility {
@Autowired
private JavaMailSender mailSender;

public static SimpleMailMessage constructNormalEmail(String text, String subject, String toAddress, String fromAddr) {
    SimpleMailMessage email = new SimpleMailMessage();
    email.setTo(toAddress);
    email.setSubject(subject);
    email.setText(text);
    email.setFrom(fromAddr);
    return email;
}

public class SendEmail implements Runnable{
    private String subject;
    private String text;
    private String toAddr;
    private String fromAddr;

    public SendEmail(String subject, String text, String toAddr, String fromAddr){
        this.subject = subject;
        this.text = text;
        this.toAddr = toAddr;
        this.fromAddr = fromAddr;
    }

    @Override
    public void run() {
        SimpleMailMessage email = constructNormalEmail(text, subject, toAddr, fromAddr);
        mailSender.send(email);
    }
}
}
</code>```

But I got the following error:

```<code>exception in thread "Thread-5" java.lang.NullPointerException
</code>```

Both this error and the message presented by IntelliJ Could not autowire. No beans of 'JavaMailSender' type found indicates that the autowire fails.

What may be the cause of this error and how can I autowire a bean in a thread? Any suggestion will be appreciated.

=============================UPDATE=====================================
Solved this problem with the help of these guys. The problem is that I create the EmailUtility myself.
MY previous code is as follow:

```<code>//Wrong Version
Thread sendEmailThread = new Thread(new EmailUtility().new SendEmail(subject, text, toAddress, fromAddress));
</code>```

If I let Spring autowires the EmailUtility, then the code works:

```<code>//Correct Version
@Component
public class EmailUtility {
......
}

public class HomeController{

     @Autowired
     private EmailUtility emailUtility;
     ...
     Thread sendEmailThread = new Thread(emailUtility.new SendEmail(subject, text, toAddress));
     ...
}
</code>```

答: Most likely your EmailUtility is not a spring managed bean. Consider adding annotation @Component to EmailUtility or declare a corresponding bean in your configuration class.

Body:
I successfully autowired beans and sent emails in my previous code. The code is as follow:

public class HomeController{
    @Autowired
    private MailConstructor mailConstructor;

    @Autowired
    private JavaMailSender mailSender;

    ...
    String token = UUID.randomUUID().toString();
    String appUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
    SimpleMailMessage newEmail = mailConstructor.constructResetTokenEmail(appUrl, request.getLocale(), token, user);

    mailSender.send(newEmail);
    ...
}

Now I want to send the email in a new thread and I wrote my code referring to this link:Why does Autowiring not function in a thread?
My new code is as follow:

public class EmailUtility {
@Autowired
private JavaMailSender mailSender;

public static SimpleMailMessage constructNormalEmail(String text, String subject, String toAddress, String fromAddr) {
    SimpleMailMessage email = new SimpleMailMessage();
    email.setTo(toAddress);
    email.setSubject(subject);
    email.setText(text);
    email.setFrom(fromAddr);
    return email;
}

public class SendEmail implements Runnable{
    private String subject;
    private String text;
    private String toAddr;
    private String fromAddr;

    public SendEmail(String subject, String text, String toAddr, String fromAddr){
        this.subject = subject;
        this.text = text;
        this.toAddr = toAddr;
        this.fromAddr = fromAddr;
    }

    @Override
    public void run() {
        SimpleMailMessage email = constructNormalEmail(text, subject, toAddr, fromAddr);
        mailSender.send(email);
    }
}
}

But I got the following error:

exception in thread "Thread-5" java.lang.NullPointerException

Both this error and the message presented by IntelliJ Could not autowire. No beans of 'JavaMailSender' type found indicates that the autowire fails.

What may be the cause of this error and how can I autowire a bean in a thread? Any suggestion will be appreciated.

=============================UPDATE=====================================
Solved this problem with the help of these guys. The problem is that I create the EmailUtility myself.
MY previous code is as follow:

//Wrong Version
Thread sendEmailThread = new Thread(new EmailUtility().new SendEmail(subject, text, toAddress, fromAddress));

If I let Spring autowires the EmailUtility, then the code works:

//Correct Version
@Component
public class EmailUtility {
......
}

public class HomeController{

     @Autowired
     private EmailUtility emailUtility;
     ...
     Thread sendEmailThread = new Thread(emailUtility.new SendEmail(subject, text, toAddress));
     ...
}


问:
Catching thread exceptions from Java ExecutorService
I'm working on a software development framework for parallel computing JavaSeis.org. I need a robust mechanism for reporting thread exceptions. During development, knowing where exceptions came from has high value, so I would like to err on the side of over-reporting. I would also like to be able to handle Junit4 testing in threads as well. Is the approach below reasonable or is there a better way ?</p>

```<code>import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class TestThreadFailure {

  public static void main(String[] args) {
    int size = 1;
    ExecutorService exec = Executors.newFixedThreadPool(size);
    ThreadFailTask worker = new ThreadFailTask();
    Future<Integer> result = exec.submit(worker);
    try {
      Integer value = result.get();
      System.out.println("Result: " + value);
    } catch (Throwable t) {
      System.out.println("Caught failure: " + t.toString());
      exec.shutdownNow();
      System.out.println("Stack Trace:");
      t.printStackTrace();
      return;
    }
    throw new RuntimeException("Did not catch failure !!");
  }

  public static class ThreadFailTask implements Callable<Integer> {
    @Override
    public Integer call() {
      int nbuf = 65536;
      double[][] buf = new double[nbuf][nbuf];
      return new Integer((int) buf[0][0]);
    }
  }
}
</code>```

答:
My original question asked how to implement "robust" thread exception handling with Java ExecutorService. Thanks to Angelo and Greg for pointers on how exception handling works with ExecutorService.submit() and Future.get(). My revised code fragment is shown below. The key point I learned here is that Future.get() catches all exceptions. If the the thread was interrupted or cancelled, you get the appropriate exception, otherwise, the exception is wrapped and re-thrown as an ExecutionException.</p>

```
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class TestThreadFailure {

  public static void main(String[] args) {
    int size = 1;
    ExecutorService exec = Executors.newFixedThreadPool(size);
    ThreadFailTask worker = new ThreadFailTask();
    Future result = exec.submit(worker);
    try {
      Integer value = result.get();
      System.out.println("Result: " + value);
    } catch (ExecutionException ex) {
      System.out.println("Caught failure: " + ex.toString());
      exec.shutdownNow();
      return;
    } catch (InterruptedException iex) {
      System.out.println("Thread interrupted: " + iex.toString());
    } catch (CancellationException cex) {
      System.out.println("Thread cancelled: " + cex.toString());
    }
    exec.shutdownNow();
    throw new RuntimeException("Did not catch failure !!");
  }

  public static class ThreadFailTask implements Callable {
    @Override
    public Integer call() {
      int nbuf = 65536;
      double[][] buf = new double[nbuf][nbuf];
      return new Integer((int) buf[0][0]);
    }
  }
}
```

Body:
I'm working on a software development framework for parallel computing JavaSeis.org. I need a robust mechanism for reporting thread exceptions. During development, knowing where exceptions came from has high value, so I would like to err on the side of over-reporting. I would also like to be able to handle Junit4 testing in threads as well. Is the approach below reasonable or is there a better way ?

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class TestThreadFailure {

  public static void main(String[] args) {
    int size = 1;
    ExecutorService exec = Executors.newFixedThreadPool(size);
    ThreadFailTask worker = new ThreadFailTask();
    Future<Integer> result = exec.submit(worker);
    try {
      Integer value = result.get();
      System.out.println("Result: " + value);
    } catch (Throwable t) {
      System.out.println("Caught failure: " + t.toString());
      exec.shutdownNow();
      System.out.println("Stack Trace:");
      t.printStackTrace();
      return;
    }
    throw new RuntimeException("Did not catch failure !!");
  }

  public static class ThreadFailTask implements Callable<Integer> {
    @Override
    public Integer call() {
      int nbuf = 65536;
      double[][] buf = new double[nbuf][nbuf];
      return new Integer((int) buf[0][0]);
    }
  }
}

Body:
My original question asked how to implement "robust" thread exception handling with Java ExecutorService. Thanks to Angelo and Greg for pointers on how exception handling works with ExecutorService.submit() and Future.get(). My revised code fragment is shown below. The key point I learned here is that Future.get() catches all exceptions. If the the thread was interrupted or cancelled, you get the appropriate exception, otherwise, the exception is wrapped and re-thrown as an ExecutionException.

import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class TestThreadFailure {

  public static void main(String[] args) {
    int size = 1;
    ExecutorService exec = Executors.newFixedThreadPool(size);
    ThreadFailTask worker = new ThreadFailTask();
    Future result = exec.submit(worker);
    try {
      Integer value = result.get();
      System.out.println("Result: " + value);
    } catch (ExecutionException ex) {
      System.out.println("Caught failure: " + ex.toString());
      exec.shutdownNow();
      return;
    } catch (InterruptedException iex) {
      System.out.println("Thread interrupted: " + iex.toString());
    } catch (CancellationException cex) {
      System.out.println("Thread cancelled: " + cex.toString());
    }
    exec.shutdownNow();
    throw new RuntimeException("Did not catch failure !!");
  }

  public static class ThreadFailTask implements Callable {
    @Override
    public Integer call() {
      int nbuf = 65536;
      double[][] buf = new double[nbuf][nbuf];
      return new Integer((int) buf[0][0]);
    }
  }
}


问:
Laravel Seed: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails
I building Twitter clone app use Laravel5.4 and While referring to this

now i want seeding database with test data

in my terminal input php artisan db:seed --class=TweetsTableSeeder
 got error

```<code>Integrity constraint violation: 1452 Cannot add
  or update a child row: a foreign key constraint fails (`twitter`.
  `tweets`, CONSTRAINT `tweets_user_id_foreign` FOREIGN KEY (`user_
  id`) REFERENCES `users` (`id`) ON DELETE CASCADE)
</code>```

I read the error and tried to understand, but I had no good results.
I'm looking at the official document but I can not understand much because  beginner.

so please help me

2017_07_09_create_tweets_table

```<code><?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTweetsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tweets', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned()->index();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->string('body', 140);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('tweets');
    }
}
</code>```

Tweet.php

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Tweet extends Model
{
    protected $fillable = [
        'user_id', 'body',
    ];
}
</code>```

TweetsTableSeeder

```<code><?php

use App\Tweet;
use Illuminate\Database\Seeder;

class TweetsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(Tweet::class, 10)->create([
        'user_id' => 2
        ]);
    }
}
</code>```

ModelFactory.php

```<code><?php

/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/

/** @var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(App\User::class, function (Faker\Generator $faker) {
    static $password;

    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => $password ?: $password = bcrypt('secret'),
        'remember_token' => str_random(10),
    ];
});

$factory->define(App\Tweet::class, function (Faker\Generator $faker) {
    return [
        'body' => $faker->realText(140),
    ];
});
</code>```

答:
Integrity constraint violation: 1452 Cannot add   or update a child
  row: a foreign key constraint fails (twitter.   tweets, CONSTRAINT
  tweets_user_id_foreign FOREIGN KEY (user_   id) REFERENCES users
  (id) ON DELETE CASCADE)

The above error simply means that you are trying to seed (insert) a value in tweets table and that value is not available in the parent users table.

In layman terms, when two tables are sharing foreign key relationship, then only those values can be inserted into child table that are already present in parent table, and in your case you are violating the above stated rule.

Body:
I building Twitter clone app use Laravel5.4 and While referring to this

now i want seeding database with test data

in my terminal input php artisan db:seed --class=TweetsTableSeeder
 got error

Integrity constraint violation: 1452 Cannot add
  or update a child row: a foreign key constraint fails (`twitter`.
  `tweets`, CONSTRAINT `tweets_user_id_foreign` FOREIGN KEY (`user_
  id`) REFERENCES `users` (`id`) ON DELETE CASCADE)

I read the error and tried to understand, but I had no good results.
I'm looking at the official document but I can not understand much because  beginner.

so please help me

2017_07_09_create_tweets_table

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTweetsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tweets', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned()->index();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->string('body', 140);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('tweets');
    }
}

Tweet.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Tweet extends Model
{
    protected $fillable = [
        'user_id', 'body',
    ];
}

TweetsTableSeeder

<?php

use App\Tweet;
use Illuminate\Database\Seeder;

class TweetsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(Tweet::class, 10)->create([
        'user_id' => 2
        ]);
    }
}

ModelFactory.php

<?php

/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/

/** @var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(App\User::class, function (Faker\Generator $faker) {
    static $password;

    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => $password ?: $password = bcrypt('secret'),
        'remember_token' => str_random(10),
    ];
});

$factory->define(App\Tweet::class, function (Faker\Generator $faker) {
    return [
        'body' => $faker->realText(140),
    ];
});


问:
Please explain the code snippet that tells whether the given word is unique?
Could someone please explain the working of this code snippet which tells if the given word is unique or not?

```<code>public static boolean isUniqueChars(String str) {
    if (str.length() > 128) {
        return false;
    }
    int checker = 0;
    for (int i = 0; i < str.length(); i++) {
        int val = str.charAt(i) - 'a';
        if ((checker & (1 << val)) > 0) return false;
        checker |= (1 << val);
    }
    return true;
}
</code>```

I don't understand what is happening in the following two lines:

```<code>if ((checker & (1 << val)) > 0) return false;
checker |= (1 << val);
</code>```

Thank you!

答:
Checker behaves like a Boolean array. Each element of this array stores whether a character is used or not.
So, checker|= (1 << Val)  stores a character into array.and  if statement checks whether this char is used or not.

But it seems strange  : < 128 comparison. because of the length of int is 32 bit.

Body:
Could someone please explain the working of this code snippet which tells if the given word is unique or not?

public static boolean isUniqueChars(String str) {
    if (str.length() > 128) {
        return false;
    }
    int checker = 0;
    for (int i = 0; i < str.length(); i++) {
        int val = str.charAt(i) - 'a';
        if ((checker & (1 << val)) > 0) return false;
        checker |= (1 << val);
    }
    return true;
}

I don't understand what is happening in the following two lines:

if ((checker & (1 << val)) > 0) return false;
checker |= (1 << val);

Thank you!