问:
When I start running my java application through Tomcat server, I encountered this kind of error. What should I do?
Tomcat authentication filter error.

```<code>Dec 07, 2017 11:15:51 AM org.apache.catalina.core.StandardContext filterStart
SEVERE: Exception starting filter AuthenticationFilter
java.lang.ClassNotFoundException: gov.da.jmrs.webapp.filters.AuthenticationFilter
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1339)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1167)
    at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:509)
    at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:490)
    at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:118)
    at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:258)
    at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:105)
    at
</code>```

org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4700)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5340)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

答:
Check your classpath, missing class to the classptah.
Read this topic to know more
How do I resolve ClassNotFoundException?</p>

Body:
Tomcat authentication filter error.

Dec 07, 2017 11:15:51 AM org.apache.catalina.core.StandardContext filterStart
SEVERE: Exception starting filter AuthenticationFilter
java.lang.ClassNotFoundException: gov.da.jmrs.webapp.filters.AuthenticationFilter
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1339)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1167)
    at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:509)
    at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:490)
    at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:118)
    at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:258)
    at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:105)
    at

org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4700)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5340)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)


来源: stackexchange

问:
I can't run Alamofire in Xcode 8
I have a project created in Xcode 7 some time ago. Now I have to make some changes in it. It was created in Swift 2.3 and I am used in it Alamofire. Now I have Xcode updated at Xcode 8.2.1 and the Swift Version is 3.

I meet a lot of errors now and I don't know how to make it work again.

I found same possible solutions but not works for me.

I updated my Cocoa Pods at 1.2.0. Not enough.
I updated Alamofire version to last. Same result.
I tried to convert to the current Swift Version. Still not good.

I found that code to put in the end of Podfile.

```<code>post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['SWIFT_VERSION'] = '3.0'
    end
  end
end
</code>```

Here is my Podfile. Maybe helps...

```<code>    # platform :ios, '9.0'

target 'LeTrans Swift' do

   pod 'Alamofire', :git => 'https://github.com/Alamofire/Alamofire.git', :tag => '3.5.0'

   pod 'KRProgressHUD'

   pod 'SwiftyJSON'

   pod 'GoogleMaps'
   pod 'GooglePlaces'
   pod 'GooglePlacePicker'

end
</code>```

答:
```<code>  pod 'Alamofire', '~> 4.6'
</code>```

latest Alamofire pod version in swift 3.0 and Xcode 8 or later all version supported.

ContentLicense: CC BY-SA 4.0

Title: I can't run Alamofire in Xcode 8

Body:
I have a project created in Xcode 7 some time ago. Now I have to make some changes in it. It was created in Swift 2.3 and I am used in it Alamofire. Now I have Xcode updated at Xcode 8.2.1 and the Swift Version is 3.

I meet a lot of errors now and I don't know how to make it work again.

I found same possible solutions but not works for me.

I updated my Cocoa Pods at 1.2.0. Not enough.
I updated Alamofire version to last. Same result.
I tried to convert to the current Swift Version. Still not good.

I found that code to put in the end of Podfile.

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['SWIFT_VERSION'] = '3.0'
    end
  end
end

Here is my Podfile. Maybe helps...

    # platform :ios, '9.0'

target 'LeTrans Swift' do

   pod 'Alamofire', :git => 'https://github.com/Alamofire/Alamofire.git', :tag => '3.5.0'

   pod 'KRProgressHUD'

   pod 'SwiftyJSON'

   pod 'GoogleMaps'
   pod 'GooglePlaces'
   pod 'GooglePlacePicker'

end

Body:
  pod 'Alamofire', '~> 4.6'

latest Alamofire pod version in swift 3.0 and Xcode 8 or later all version supported.

ContentLicense: CC BY-SA 3.0


问:
How to create operation loop for two 1 to 1 lists
Say I have 2 lists:

```<code>A = [a1,a2,a3,...,an]
B = [b1,b2,b3,...,bn]
</code>```

The lists are one-to-one.

So how do I create a loop that operates (any operation):

```<code>a1 with b1
a2 with b2
...
an with bn
</code>```

答:
Since your lists are one-to-one, then they must both be the same size. In this case zip() is the best option here. This function makes an iterator and aggregates elements into tuple pairs from each of the iterables:

```<code>>>> a = [1, 2, 3, 4]
>>> b = [5, 6, 7, 8]
>>> zipped = zip(a, b)
>>> print(list(zipped))
[(1, 5), (2, 6), (3, 7), (4, 8)]
>>> print(tuple(zipped))
((1, 5), (2, 6), (3, 7), (4, 8))
</code>```

This means that you can apply a function on each of the tuples within the zipped iterable:

```<code>>>> print([sum(x) for x in zipped])
[6, 8, 10, 12]
>>> print([max(x) for x in zipped])
[5, 6, 7, 8]
</code>```

You can also achieve similar behavior with map():

```<code>>>> a = [1, 2, 3, 4]
>>> b = [5, 6, 7, 8]
>>> print(list(map(lambda x, y : x + y, a, b)))
[6, 8, 10, 12]
>>> print(list(map(lambda x, y : x * y, a, b)))
[5, 12, 21, 32]
</code>```

I'd also suggest writing a zip() function with iterators to see how it works:

```<code>def my_zip(seq1, seq2):
    i1 = iter(seq1)
    i2 = iter(seq2)
    while True:
        yield next(i1), next(i2)
</code>```

Additionally, another less preferred way would be to loop over the first list, and use the indices to also access the elements in the second list:

```<code>>>> a = [1, 2, 3, 4]
>>> b = [5, 6, 7, 8]
>>> for i in range(len(a)):
        print(a[i], b[i])
1 5
2 6
3 7
4 8
>>> print([a[i] + b[i] for i in range(len(a))])
[6, 8, 10, 12]
</code>```

This is not very pythonic, but it also works. I recommend using zip() over this.

Body:
Say I have 2 lists:

A = [a1,a2,a3,...,an]
B = [b1,b2,b3,...,bn]

The lists are one-to-one.

So how do I create a loop that operates (any operation):

a1 with b1
a2 with b2
...
an with bn

Body:
Since your lists are one-to-one, then they must both be the same size. In this case zip() is the best option here. This function makes an iterator and aggregates elements into tuple pairs from each of the iterables:

>>> a = [1, 2, 3, 4]
>>> b = [5, 6, 7, 8]
>>> zipped = zip(a, b)
>>> print(list(zipped))
[(1, 5), (2, 6), (3, 7), (4, 8)]
>>> print(tuple(zipped))
((1, 5), (2, 6), (3, 7), (4, 8))

This means that you can apply a function on each of the tuples within the zipped iterable:

>>> print([sum(x) for x in zipped])
[6, 8, 10, 12]
>>> print([max(x) for x in zipped])
[5, 6, 7, 8]

You can also achieve similar behavior with map():

>>> a = [1, 2, 3, 4]
>>> b = [5, 6, 7, 8]
>>> print(list(map(lambda x, y : x + y, a, b)))
[6, 8, 10, 12]
>>> print(list(map(lambda x, y : x * y, a, b)))
[5, 12, 21, 32]

I'd also suggest writing a zip() function with iterators to see how it works:

def my_zip(seq1, seq2):
    i1 = iter(seq1)
    i2 = iter(seq2)
    while True:
        yield next(i1), next(i2)

Additionally, another less preferred way would be to loop over the first list, and use the indices to also access the elements in the second list:

>>> a = [1, 2, 3, 4]
>>> b = [5, 6, 7, 8]
>>> for i in range(len(a)):
        print(a[i], b[i])
1 5
2 6
3 7
4 8
>>> print([a[i] + b[i] for i in range(len(a))])
[6, 8, 10, 12]

This is not very pythonic, but it also works. I recommend using zip() over this.


问:
Adding to integers in a list which is inside a dictionary
I have a dictionary which houses some integer values in a list:

```<code>d = {"Numbers": [5, 10, 15, 20]}
</code>```

How do I access the integers within the list and add to them all at once? So if I wanted to add 10 on, it would look like this:

```<code>d = {"Numbers": [15, 20, 25, 30]}
</code>```

Thanks for the help!

答:
You have:

```<code>d = {"Numbers": [5, 10, 15, 20]}
add = 10 # Amount you want to increase.
</code>```

You can make a list comprehension:

```<code>d['Numbers'] = [v + add for v in d['Numbers']]
</code>```

That is the same as:

```<code>tmp_list = []
for v in d['Numbers']:
    tmp_list.append(v + add)
d['Numbers'] = tmp_list
</code>```

But in one line.

And if you want to increase all the items of every keys in the dictionary:

```<code>d = {k:[n + add for n in v] for k, v in d.items()}
</code>```

That was a dictionary comprehension and it's equal to:

```<code>tmp_dict = {}
for k,v in d.items():
    tmp_dict[k] = []
    for n in v:
        tmp_dict[k].append(n + add)
d = tmp_dict
</code>```

Body:
I have a dictionary which houses some integer values in a list:

d = {"Numbers": [5, 10, 15, 20]}

How do I access the integers within the list and add to them all at once? So if I wanted to add 10 on, it would look like this:

d = {"Numbers": [15, 20, 25, 30]}

Thanks for the help!

Body:
You have:

d = {"Numbers": [5, 10, 15, 20]}
add = 10 # Amount you want to increase.

You can make a list comprehension:

d['Numbers'] = [v + add for v in d['Numbers']]

That is the same as:

tmp_list = []
for v in d['Numbers']:
    tmp_list.append(v + add)
d['Numbers'] = tmp_list

But in one line.

And if you want to increase all the items of every keys in the dictionary:

d = {k:[n + add for n in v] for k, v in d.items()}

That was a dictionary comprehension and it's equal to:

tmp_dict = {}
for k,v in d.items():
    tmp_dict[k] = []
    for n in v:
        tmp_dict[k].append(n + add)
d = tmp_dict


问:
how to show one value if there have same value
I want to show just 1 value if there is have same value,
forexample

in my record like this..

```<code>Jumlah
5
5
5
5
6
6
6
7
7
</code>```

nad I want to show for my view is

```<code>5
6
7
</code>```

for my SQL Code is select year(tgl_moc) as tahun from rol_tb_form1 group by tahun order by tahun desc

how to make that in C# ASP.NET MVC

sorry for my bad englis

答:
If it is already in list then use below code

```<code>listOfYears.GroupBy(s => s).Select(g => g);
</code>```

and if you are fetching from database then

```<code>from y in listOfYears
          group y by y into g
          select g.Key;
</code>```

Body:
I want to show just 1 value if there is have same value,
forexample

in my record like this..

Jumlah
5
5
5
5
6
6
6
7
7

nad I want to show for my view is

5
6
7

for my SQL Code is select year(tgl_moc) as tahun from rol_tb_form1 group by tahun order by tahun desc

how to make that in C# ASP.NET MVC

sorry for my bad englis

Body:
If it is already in list then use below code

listOfYears.GroupBy(s => s).Select(g => g);

and if you are fetching from database then

from y in listOfYears
          group y by y into g
          select g.Key;


问:
Fetch api preflight request failing
I'm trying to make a GET request from a public API but cant seem to figure out why the cors preflight request keeps failing.

```<code>Response for preflight has invalid HTTP status code 404
</code>```

I've done some searching around and it seems like this is something that needs to be changed server side, but I just want to make sure theres nothing I might be doing wrong. I'm using the following code:

```<code>try {
  let guideData = await fetch(guideUrl, {
    method: 'GET',
    headers: {
      Authorization: `Bearer ${json.access_token}`,
    }
  });
} catch(err) {
  console.log("Failed to fetch data", err);
}
</code>```

I've tested using Postman and Hurl, both seem to work fine, I just can't get it to work on my client.

答:
When you are sending http request from Postman and Curl the two don't behave like a web browser would. In your case you are using a web browser running js. The code itself looks fine minus the fact that you need to encode your token to make the Authorization work when sent.

The issue definitely seems to be server side, the gist is when you send OPTIONS it will tell you whether or not it's a problem with you or server. Most likely than not from the response you posted, it is definitely CORS.

Title: Fetch api preflight request failing

Body:
I'm trying to make a GET request from a public API but cant seem to figure out why the cors preflight request keeps failing.

Response for preflight has invalid HTTP status code 404

I've done some searching around and it seems like this is something that needs to be changed server side, but I just want to make sure theres nothing I might be doing wrong. I'm using the following code:

try {
  let guideData = await fetch(guideUrl, {
    method: 'GET',
    headers: {
      Authorization: `Bearer ${json.access_token}`,
    }
  });
} catch(err) {
  console.log("Failed to fetch data", err);
}

I've tested using Postman and Hurl, both seem to work fine, I just can't get it to work on my client.


问:
How to set the .Text property of a label from a "string" + stringVariable
I am working on the last form in a multi-formed Winforms application in C#. On the last form, I display schedule information of the user (what the user enters in the forms between the first and last one). Some of the information I am trying to display is a display Label that says something like "Student Schedule for " + firstName. I retrieve the first name from the first user form and save it locally in the method. I have verified that the string variable isn't empty; it actually contains the first name. However, when I try to set the text of a label to "Student Schedule for " + firstName, I get just "Schedule" as the label text.

```<code>firstName = "Tango"; //passed in from first user form, verified correct
sampleLbl.Text = "Student Schedule for " + firstName;
</code>```

I expect the label text to read "Student Schedule for Tango", but it only shows "Student".

I have also tried

```<code>sampleLbl.Text = new string("Student Schedule for " + firstName);
</code>```

This gives me an error that I 'cannot convert from string to char'.

Also, a side note.. The Label that doesn't display the right text is one that I added programmatically using

```<code>Label sampleLbl = new Label();
sampleLbl.Text = "Student Schedule for " + firstName;
</code>```

When I added a label in the designer and change the text, it displays the  correct text (ie. Student Schedule for Tango).

I realize this is probably a simple error and would appreciate help anyway. Thank you in advance.

答:
Set AutoSize to true for the label, it may be displaying correct text, but since it's not AutoSize, it hidden on the form and you can't see.

```<code>Label sampleLbl = new Label();
sampleLbl.AutoSize = true;
</code>```

Body:
I am working on the last form in a multi-formed Winforms application in C#. On the last form, I display schedule information of the user (what the user enters in the forms between the first and last one). Some of the information I am trying to display is a display Label that says something like "Student Schedule for " + firstName. I retrieve the first name from the first user form and save it locally in the method. I have verified that the string variable isn't empty; it actually contains the first name. However, when I try to set the text of a label to "Student Schedule for " + firstName, I get just "Schedule" as the label text.

firstName = "Tango"; //passed in from first user form, verified correct
sampleLbl.Text = "Student Schedule for " + firstName;

I expect the label text to read "Student Schedule for Tango", but it only shows "Student".

I have also tried

sampleLbl.Text = new string("Student Schedule for " + firstName);

This gives me an error that I 'cannot convert from string to char'.

Also, a side note.. The Label that doesn't display the right text is one that I added programmatically using

Label sampleLbl = new Label();
sampleLbl.Text = "Student Schedule for " + firstName;

When I added a label in the designer and change the text, it displays the  correct text (ie. Student Schedule for Tango).

I realize this is probably a simple error and would appreciate help anyway. Thank you in advance.

Body:
Set AutoSize to true for the label, it may be displaying correct text, but since it's not AutoSize, it hidden on the form and you can't see.

Label sampleLbl = new Label();
sampleLbl.AutoSize = true;


问:
Model Derivative API responses not mapping through Jackson
Have there been updates made to the response objects from the Model Derivative API as we are having issues mapping the responses from requests for 3D models back into the Manifest and Metadata objects.

Both are throwing Jackson errors.

GetManifest is returning an unhandled role enum

GetMetadataForGuid is throwing - Illegal character ((CTRL-CHAR, code 31))

Thanks

答:
This is to answer the second question as references for all.

The problem is due to the header is set to "gzip" format when calling GET :urn/metadata/:guid. If it is not "gzip", all work well. While with other ways such as Postman, the header with gzip can also work.

In the past, when clients used gzip header, actually it doesn't trigger a gzip encoding. So everything is fine. After the release recently, the content returns the content in gzip if gzip is specified, while the SDK doesn't handle it correctly. Postman unzips the gzip to json automatically, so it looks working.

So, the fix could be adding one line in the ApiClient.java at line 115: client.addFilter(new GZIPContentEncodingFilter(false));

I also forked the source github repository in my space with the fixes on the two problems. a pull request is commit to the main repo. that is to allow the response of API call can handle gzip content and unzip it.
https://github.com/xiaodongliang/forge-api-java-client

We apologize for the two issues that have affected some projects using SDK.


问:
Check my UML Class Diagram

Can someone check my class diagram because I am not too good at drawing this type of uml diagram

A User can be a PersonalUser or a BusinessUser

An Administrator is a special type of PersonalUser

A PersonalUser or BusinessUser can create many Auction

But an Auction can be created by only one PersonalUser or only one BusinessUser

There an Auction cannot exist without an PersonalUser or a BusinessUser

An Auction can contain only one Item

An Item can be in only one Auction

An Item cannot exist without an Auction

An Auction cannot exist without an Item

An Item has one Category

Category can has many item

An Item  cannot exist without a category

A Category can has a Parent Category but this is not mandatory

A Category can has many Attributes

But an Attribute is for only one Category

An Attribute cannot exist a Category

An Attribute can has many AttributeOption

But an AttributeOption is linked to only one Attribute

An AttributeOption cannot exist without an Attribute

An Auction can has many bids

A bid is only for one auction

A Bid cannot exist without an Auction and a Personal User or a BusinessUser

An Item can has many picture

A picture is only for once item and a picture cannot exist without an Item

A User can create many ForumTopics but a ForumTopic can be created only by one User

A ForumTopics can contain one or more ForumMessage

A ForumTopic cannot exist without a User and a ForumMessage cannot exist without a ForumTopic

A BusinessUser can has many BusinessContactNumber but a BusinessContactNumber is only for one BusinessUser

A BusinessContactNumber cannot exist without a Business

答:
At first glance, you used a lot of aggregations. This is quite uncommon. I have never seen a good example of when an aggregation is justified. It's usually either a plain association (no whole-part relationship) or a composition (the part is deleted when the whole is deleted).

Cannot exists without does not imply aggregation. A proper multiplicity is sufficient. Can create does not imply aggregation. Creation is usually modeled with an appropriately stereotyped use-relation (i.e. dashed arrow), unless an association between the creator and the creation exists (in which case creation need not be mentioned explicitly).

4 But an Auction can be created by only one PersonalUser or only one BusinessUser.

Then the multiplicity of the Auction-PersonalUser association cannot be 1 at the PersonalUser end (because the Auction might have been created by a BusinessUser) and the multiplicity of the Auction-BusinessUser association cannot be 1 at the BusinessUser end (for much the same reason). Use 0..1 as multiplicity, but beware of what I will write about 3.

3 A PersonalUser or BusinessUser can create many Auction

This is equivalent to a User can create many Auction.

6 An Auction can contain only one Item

7 An Item can be in only one Auction

8 An Item cannot exist without an Auction

9 An Auction cannot exist without an Item

Then there is a single association between Item and Auction with multiplicity of 1 at both ends. Don't make aggregations out of it and don't use two associations for it.

13 A Category can has a Parent Category but this is not mandatory

That would be made clear if you label the association ends.

25 A User can create many ForumTopics but a ForumTopic can be created only by one User

This is only vaguely related to Auctions and might as well exists independent of them. Put the Forum stuff into a separate package. Then maybe the auction stuff and the user stuff also deserve a separate packages.

BTW: You did not mention the Bidding Service. It seems solely to model the concept of theses objects do not exist in thin air, they are actually used by some software. In that case, leave it out.

ContentLicense: CC BY-SA 2.5

Title: Check my UML Class Diagram


问:
the main method overlap in the java program
This is the full coding. Once we compile it |it throwing error that main method already defined before.How to settle this error. Guidance needed. Thank you.</p>

```<code>import java.util.Scanner;
import java.lang.*;
import java.math.*;

public class AdditiveCipher {
    public static void main(String[] args){
        String message, encryptedMessage = "", decryptedMessage = "", decryptMessage = "", encryptMessage = "";
        String text;
        int key;
        String keyy = "15";
        char ch;
        char cha;

        System.out.println("");
        System.out.println("-------------------Additive Cipher----------------------");
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a message: ");
        message = sc.nextLine();

        System.out.println("Enter key: ");
        key = sc.nextInt();

        for(int i = 0; i < message.length(); ++i){
            ch = message.charAt(i);

            if(ch >= 'a' && ch <= 'z'){
                ch = (char)(ch + key);

                if(ch > 'z'){
                    ch = (char)(ch - 'z' + 'a' - 1);
                }

                encryptedMessage += ch;
            }
            else if(ch >= 'A' && ch <= 'Z'){
                ch = (char)(ch + key);

                if(ch > 'Z'){
                    ch = (char)(ch - 'Z' + 'A' - 1);
                }

                encryptedMessage += ch;
            }
            else {
                encryptedMessage += ch;
            }
        }

        System.out.println("Encrypted Message using additive cipher = " + encryptedMessage);

//Additive decrypted codes

            Scanner sca = new Scanner(System.in);

            System.out.println("Enter a encryted message: ");
            text = sca.nextLine();

            for(int i = 0; i < text.length(); ++i){
                ch = text.charAt(i);

                if(ch >= 'a' && ch <= 'z'){
                    ch = (char)(ch - key);

                    if(ch < 'a'){
                        ch = (char)(ch + 'z' - 'a' + 1);
                    }

                    decryptedMessage += ch;
                }
                else if(ch >= 'A' && ch <= 'Z'){
                    ch = (char)(ch - key);

                    if(ch < 'A'){
                        ch = (char)(ch + 'Z' - 'A' + 1);
                    }

                    decryptedMessage += ch;
                }
                else {
                    decryptedMessage += ch;
                }
            }

            System.out.println("Decrypted Message using additive cipher = " + decryptedMessage);

    }

//Autokey encrypted codes

    private static String alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    public static void main(String[] args){
        String keyy = "15";  //15 - P
        String textt = "HELLO";

    if(keyy.matches("[-+]?\\d*\\.?\\d+"))
         keyy = ""+alpha.charAt(Integer.parseInt(keyy));

        System.out.println("");
                System.out.println("-------------------Autokey Cipher----------------------");
                System.out.println("");

                String enc = AutoEncryption(textt,keyy);
                System.out.println("Enter a encryted message: " +textt);
                System.out.println("Encrypted Message using additive cipher = " + enc);

    }
        public static String AutoEncryption(String textt,String keyy){
        int len = textt.length();

             String subkey = keyy + textt;
             subkey = subkey.substring(0,subkey.length()-keyy.length());

                String sb = "";
                 for(int x=0;x<len;x++){
                         int get1 = alpha.indexOf(textt.charAt(x));
                         int get2 = alpha.indexOf(subkey.charAt(x));

                         int total = (get1 + get2)%26;

                         sb += alpha.charAt(total);
                }
            return sb;

        }

         public static String AutoDecryption(String text,String key){
              int len = text.length();

              String current = key;
              String sb ="";

              for(int x=0;x<len;x++){
                 int get1 = alpha.indexOf(text.charAt(x));
                 int get2 = alpha.indexOf(current.charAt(x));

                 int total = (get1 - get2)%26;
                 total = (total<0)? total + 26 : total;
                 sb += alpha.charAt(total);

                 current += alpha.charAt(total);
              }
              return sb;
           }

}
</code>```

答:
You can put the second main into another class if you really want everything in one file or have one of them have different arguments.

```<code>public class Sample2 {

    public static void main(String[] args){
        // do some stuff........
    }

}

class SampleClass{
    public static void main(String[] args){
        // do some stuff........
    }
}
</code>```

you could also do this:

```<code>public class Sample2{
    public static void main(String[] args){
         // do some stuff........
    }

    public static void main(byte b){    // whatever datatype you want
         // do some stuff........
    }

}
</code>```

Body:
This is the full coding. Once we compile it |it throwing error that main method already defined before.How to settle this error. Guidance needed. Thank you.

import java.util.Scanner;
import java.lang.*;
import java.math.*;

public class AdditiveCipher {
    public static void main(String[] args){
        String message, encryptedMessage = "", decryptedMessage = "", decryptMessage = "", encryptMessage = "";
        String text;
        int key;
        String keyy = "15";
        char ch;
        char cha;

        System.out.println("");
        System.out.println("-------------------Additive Cipher----------------------");
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a message: ");
        message = sc.nextLine();

        System.out.println("Enter key: ");
        key = sc.nextInt();

        for(int i = 0; i < message.length(); ++i){
            ch = message.charAt(i);

            if(ch >= 'a' && ch <= 'z'){
                ch = (char)(ch + key);

                if(ch > 'z'){
                    ch = (char)(ch - 'z' + 'a' - 1);
                }

                encryptedMessage += ch;
            }
            else if(ch >= 'A' && ch <= 'Z'){
                ch = (char)(ch + key);

                if(ch > 'Z'){
                    ch = (char)(ch - 'Z' + 'A' - 1);
                }

                encryptedMessage += ch;
            }
            else {
                encryptedMessage += ch;
            }
        }

        System.out.println("Encrypted Message using additive cipher = " + encryptedMessage);

//Additive decrypted codes

            Scanner sca = new Scanner(System.in);

            System.out.println("Enter a encryted message: ");
            text = sca.nextLine();

            for(int i = 0; i < text.length(); ++i){
                ch = text.charAt(i);

                if(ch >= 'a' && ch <= 'z'){
                    ch = (char)(ch - key);

                    if(ch < 'a'){
                        ch = (char)(ch + 'z' - 'a' + 1);
                    }

                    decryptedMessage += ch;
                }
                else if(ch >= 'A' && ch <= 'Z'){
                    ch = (char)(ch - key);

                    if(ch < 'A'){
                        ch = (char)(ch + 'Z' - 'A' + 1);
                    }

                    decryptedMessage += ch;
                }
                else {
                    decryptedMessage += ch;
                }
            }

            System.out.println("Decrypted Message using additive cipher = " + decryptedMessage);

    }

//Autokey encrypted codes

    private static String alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    public static void main(String[] args){
        String keyy = "15";  //15 - P
        String textt = "HELLO";

    if(keyy.matches("[-+]?\\d*\\.?\\d+"))
         keyy = ""+alpha.charAt(Integer.parseInt(keyy));

        System.out.println("");
                System.out.println("-------------------Autokey Cipher----------------------");
                System.out.println("");

                String enc = AutoEncryption(textt,keyy);
                System.out.println("Enter a encryted message: " +textt);
                System.out.println("Encrypted Message using additive cipher = " + enc);

    }
        public static String AutoEncryption(String textt,String keyy){
        int len = textt.length();

             String subkey = keyy + textt;
             subkey = subkey.substring(0,subkey.length()-keyy.length());

                String sb = "";
                 for(int x=0;x<len;x++){
                         int get1 = alpha.indexOf(textt.charAt(x));
                         int get2 = alpha.indexOf(subkey.charAt(x));

                         int total = (get1 + get2)%26;

                         sb += alpha.charAt(total);
                }
            return sb;

        }

         public static String AutoDecryption(String text,String key){
              int len = text.length();

              String current = key;
              String sb ="";

              for(int x=0;x<len;x++){
                 int get1 = alpha.indexOf(text.charAt(x));
                 int get2 = alpha.indexOf(current.charAt(x));

                 int total = (get1 - get2)%26;
                 total = (total<0)? total + 26 : total;
                 sb += alpha.charAt(total);

                 current += alpha.charAt(total);
              }
              return sb;
           }

}

Body:
You can put the second main into another class if you really want everything in one file or have one of them have different arguments.

public class Sample2 {

    public static void main(String[] args){
        // do some stuff........
    }

}

class SampleClass{
    public static void main(String[] args){
        // do some stuff........
    }
}

you could also do this:

public class Sample2{
    public static void main(String[] args){
         // do some stuff........
    }

    public static void main(byte b){    // whatever datatype you want
         // do some stuff........
    }

}


问:
an efficient way to loop an slice/array in go
basically I have this:

```<code>package main

import "fmt"

type Struct1 struct {
    id   int
    name string
}

type Struct2 struct {
    id       int
    lastname string
}

type Struct3 struct {
    id   int
    real bool
}

func main() {
    var (
     s1 []Struct1
     s2 []Struct2
     s3 []Struct3
    )
    s1 = append(s1, Struct1{id: 1, name: "Eliot"}, Struct1{id: 2, name: "Tyrell"}, Struct1{id: 3, name: "Mr Robot"})
    s2 = append(s2, Struct2{id: 1, lastname: "Anderson"}, Struct2{id: 2, lastname: "Wellick"})
    s3 = append(s3, Struct3{id: 1, real: true}, Struct3{id: 2, real: true}, Struct3{id: 3, real: false})
}
</code>```

I want to show something like this:

Eliot Anderson real(true)

Tyrell Wellick real(true)

But I don't want to loop the s1 inside the s2 and then inside the s3

Example:

```<code>for i := 0; i < len(s1); i++ {
        for j := 0; j < len(s2); j++ {
            if s1[i].id == s2[j].id {
                for k := 0; k < len(s3); k++ {
                    if s2[j].id == s3[k].id {
                        // some code ...
                    }
                }
            }
        }
    }
</code>```

So, what other ways are there to doing that?

答:
In fact to join all first elements, then all second etc, you don’t need to make a cycle in a cycle:

Prepare every slice as a map:

```<code>m1 := make(map[int]string)
for i:=0; i < len(s1); i ++ {
    m1[s1[i].id] = s1[i].Name
}
</code>```

The same for 2 other slices.
Finally iterate once:

```<code>for i:=0; i < len(s1); i ++ {
    fmt.Println(m1[i], m2[i], m3[i])
}
</code>```

This solution supposes all slices have corresponding items. If not, you should decide what to do with an element without its fragment: ignore, replace blank with some placeholders, break whole cycle etc. For example, you decided firstName is mandatory (we will iterate by it), secondName is optional and should be replaced with ? in case of absence, and real is absolutely obligatory for the whole cycle - if it's absent we break further work and return empty slice:

```<code>type Person struct { // corrected struct from the neighbour recipe
     firstName: string
     lastName: string
     real: bool
}

var persons []Person // slice for result

for i, firstName := range m1 { // iterate by keys and values of m1
    secondName, ok := m2[i]
    if !ok {
       secondName = "?"
    }
    real, ok := m3[i]
    if !ok {
       persons = []Person
       break
    }
    person := Person{firstName, secondName, real}
    persons = append(persons, person)
}
</code>```

Body:
basically I have this:

package main

import "fmt"

type Struct1 struct {
    id   int
    name string
}

type Struct2 struct {
    id       int
    lastname string
}

type Struct3 struct {
    id   int
    real bool
}

func main() {
    var (
     s1 []Struct1
     s2 []Struct2
     s3 []Struct3
    )
    s1 = append(s1, Struct1{id: 1, name: "Eliot"}, Struct1{id: 2, name: "Tyrell"}, Struct1{id: 3, name: "Mr Robot"})
    s2 = append(s2, Struct2{id: 1, lastname: "Anderson"}, Struct2{id: 2, lastname: "Wellick"})
    s3 = append(s3, Struct3{id: 1, real: true}, Struct3{id: 2, real: true}, Struct3{id: 3, real: false})
}

I want to show something like this:

Eliot Anderson real(true)

Tyrell Wellick real(true)

But I don't want to loop the s1 inside the s2 and then inside the s3

Example:

for i := 0; i < len(s1); i++ {
        for j := 0; j < len(s2); j++ {
            if s1[i].id == s2[j].id {
                for k := 0; k < len(s3); k++ {
                    if s2[j].id == s3[k].id {
                        // some code ...
                    }
                }
            }
        }
    }

So, what other ways are there to doing that?

Body:
In fact to join all first elements, then all second etc, you don’t need to make a cycle in a cycle:

Prepare every slice as a map:

m1 := make(map[int]string)
for i:=0; i < len(s1); i ++ {
    m1[s1[i].id] = s1[i].Name
}

The same for 2 other slices.
Finally iterate once:

for i:=0; i < len(s1); i ++ {
    fmt.Println(m1[i], m2[i], m3[i])
}

This solution supposes all slices have corresponding items. If not, you should decide what to do with an element without its fragment: ignore, replace blank with some placeholders, break whole cycle etc. For example, you decided firstName is mandatory (we will iterate by it), secondName is optional and should be replaced with ? in case of absence, and real is absolutely obligatory for the whole cycle - if it's absent we break further work and return empty slice:

type Person struct { // corrected struct from the neighbour recipe
     firstName: string
     lastName: string
     real: bool
}

var persons []Person // slice for result

for i, firstName := range m1 { // iterate by keys and values of m1
    secondName, ok := m2[i]
    if !ok {
       secondName = "?"
    }
    real, ok := m3[i]
    if !ok {
       persons = []Person
       break
    }
    person := Person{firstName, secondName, real}
    persons = append(persons, person)
}


问:
How to send an array with objects to next screen in react-native?
I want to sent atn array to next screen, this atn array is fine and all the item are easily accesible...I am new to react-native, okay this atn array is on ListM.js and I want to take this array to VenueD.js.... help thanks in advance.</p>

答:
As you're using react-navigation, you can bypass your data to next screen with:

from_screen.js

navigateTo() {
    this.props.navigation.navigate('ToScreen', {
        data: this.YOUR_ARRAY,
    });
}
```

<h2>to_screen.js</h2>

<p>then you can get back your data right in next screen.</p>

<pre class="lang-js prettyprint-override"><code>const { state, setParams, navigate } = this.props.navigation;
const params = state.params || {};

console.log(params.data);
</code>```

Body:
As you're using react-navigation, you can bypass your data to next screen with:

from_screen.js

navigateTo() {
    this.props.navigation.navigate('ToScreen', {
        data: this.YOUR_ARRAY,
    });
}

to_screen.js

then you can get back your data right in next screen.

const { state, setParams, navigate } = this.props.navigation;
const params = state.params || {};

console.log(params.data);


问:
How to check if record is updated?
I'm trying to get updated records count from previous week. But I'm having trouble approaching the problem.

For Eg: I have a table 'Org'

week1 :

```<code>              id     name          age       address   date
  record1 :  123     Joe           35        xyz       12/01/2017
</code>```

week2 :

```<code>              id     name          age       address     date
  record1 :  123     Joe           35        abc        12/03/2017
</code>```

I'm trying to get the record which has been updated. In the above example, the address for record1 with id 123 has been updated. Currently I'm checking in an in-efficient way.

Query:

```<code>select * from Org where date='12/01/2017'
</code>```

and

```<code>select * from Org where date='12/03/2017'
</code>```

Query:

```<code>select distinct on (id) count(*) from Org group by Org.id
</code>```

A file is being pushed to the db every day. So, the updated record will have a new timestamp and the records are getting aggregated overtime which made my job a little harder. I tried joining the table to itself but it didn't make any sense to me. I'm not sure how to approach this problem. I was trying and almost reaching the solution but I don't understand why I'm getting count two times. Example Fiddle

答:
Try this Query:

```<code>select col1
from(
  select distinct col1,col2,col3,col4
  from table_not
    )D
group by col1
having count(1)>1
</code>```

SQL Fiddle link: SQL Fiddle

Title: How to check if record is updated?

Body:
I'm trying to get updated records count from previous week. But I'm having trouble approaching the problem.

For Eg: I have a table 'Org'

week1 :

              id     name          age       address   date
  record1 :  123     Joe           35        xyz       12/01/2017

week2 :

              id     name          age       address     date
  record1 :  123     Joe           35        abc        12/03/2017

I'm trying to get the record which has been updated. In the above example, the address for record1 with id 123 has been updated. Currently I'm checking in an in-efficient way.

Query:

select * from Org where date='12/01/2017'

and

select * from Org where date='12/03/2017'

Query:

select distinct on (id) count(*) from Org group by Org.id

A file is being pushed to the db every day. So, the updated record will have a new timestamp and the records are getting aggregated overtime which made my job a little harder. I tried joining the table to itself but it didn't make any sense to me. I'm not sure how to approach this problem. I was trying and almost reaching the solution but I don't understand why I'm getting count two times. Example Fiddle

Body:
Try this Query:

select col1
from(
  select distinct col1,col2,col3,col4
  from table_not
    )D
group by col1
having count(1)>1

SQL Fiddle link: SQL Fiddle


问:
Resetting MySQL Root Password with XAMPP on Localhost
So for the past hour I've been trying to figure out how to reset my 'root' password for MySQL as I cannot log into PHPMyAdmin. I've tried changing the password in the config.inc.php file and searching through other methods. I cannot find a successful way. A few months ago I changed it as a test password but now I forget what it was. If anyone can help, that would be great. (I'm running on a Windows computer).</p>

答:
Open the file C:\xampp\phpMyAdmin\config.inc.php in your text editor. Search for the tags below and edit accordingly

```<code>$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'password';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = true;
</code>```

Where 'password' is your new password. In-between quotes.

GO to your browser and visit link http://localhost/phpmyadmin/. Click on 'GO' without your new password. It would log you in and you would be able to see the "CHANGE PASSWORD". Proceed to change your password and you are done.

Body:
Open the file C:\xampp\phpMyAdmin\config.inc.php in your text editor. Search for the tags below and edit accordingly

$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'password';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = true;

Where 'password' is your new password. In-between quotes.

GO to your browser and visit link http://localhost/phpmyadmin/. Click on 'GO' without your new password. It would log you in and you would be able to see the "CHANGE PASSWORD". Proceed to change your password and you are done.


问:
pg_config, ruby pg, postgresql 9.0 problem after upgrade, centos 5
After upgrade postgresql 8.1 to 9.0 ive noticed issues with libraries dependency. Postgresql works fine (connection, queries).

```<code>yum list postgresql*
Installed Packages
postgresql.i386 9.0.0-1PGDG.el5 installed
postgresql-debuginfo.i386 9.0.0-1PGDG.el5 installed
postgresql-devel.i386 9.0.0-1PGDG.el5 installed
postgresql-libs.i386 9.0.0-1PGDG.el5 installed
postgresql-odbcng.i386 0.90.101-2.el5 installed
postgresql-plruby.i386 0.5.1-5.el5 installed
postgresql-server.i386 9.0.0-1PGDG.el5 install
</code>```

but when im trying to install 'pg' for ruby, ive received

```<code>gem install pg
Building native extensions.  This could take a while...
ERROR:  Error installing pg:
        ERROR: Failed to build gem native extension.

/usr/local/bin/ruby extconf.rb
checking for pg_config... no
checking for libpq-fe.h... no
Can't find the 'libpq-fe.h header
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.
</code>```

When trying with another ruby-postgres driver, ive got

```<code>yum install ruby-postgres
ruby-postgres-0.7.1-5.el5.i386 from epel has depsolving problems
  --> Missing Dependency: libpq.so.4 is needed by package ruby-postgres-0.7.1-5.el5.i386 (epel)
</code>```

and

```<code>locate libpq.so.4
/usr/lib/libpq.so.4
/usr/lib/libpq.so.4.1
</code>```

also exported path

```<code>LD_LIBRARY_PATH=/usr/pgsql-9.0/lib
export LD_LIBRARY_PATH
</code>```

after running ruby script with "require pg" (works on 8.1), ive got:

```<code>/usr/local/lib/ruby/site_ruby/1.8/i686-linux/pg_ext.so: libpq.so.4: cannot open shared object file: No such file or directory - /usr/local/lib/ruby/site_ruby/1.8/i686-linux/pg_ext.so (LoadError)
        from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:29:in `require'
        from /usr/local/lib/ruby/site_ruby/1.8/pg.rb:12
        from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:29:in `gem_original_require'
        from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:29:in `require'
</code>```

Any suggestions what to do more?

答:
libpq.so.4 is from an older version of PostgreSQL; 9.0 ships with /usr/pgsql-9.0/lib/libpq.so.5

If you have a program that was built against libpq.so.4, that file is provided by the compat-postgresql-libs packages, which you may not have installed.  A lot of people remove it using "--force" because it can be hard to get the newer RPMs installed otherwise; that's a bad idea, but the alternative is complicated.  If you've installed that package, you should find a /usr/lib/libpq.so.4 available that makes your existing program, compiled originally for the older PostgreSQL, happy.

Body:
After upgrade postgresql 8.1 to 9.0 ive noticed issues with libraries dependency. Postgresql works fine (connection, queries).

yum list postgresql*
Installed Packages
postgresql.i386 9.0.0-1PGDG.el5 installed
postgresql-debuginfo.i386 9.0.0-1PGDG.el5 installed
postgresql-devel.i386 9.0.0-1PGDG.el5 installed
postgresql-libs.i386 9.0.0-1PGDG.el5 installed
postgresql-odbcng.i386 0.90.101-2.el5 installed
postgresql-plruby.i386 0.5.1-5.el5 installed
postgresql-server.i386 9.0.0-1PGDG.el5 install

but when im trying to install 'pg' for ruby, ive received

gem install pg
Building native extensions.  This could take a while...
ERROR:  Error installing pg:
        ERROR: Failed to build gem native extension.

/usr/local/bin/ruby extconf.rb
checking for pg_config... no
checking for libpq-fe.h... no
Can't find the 'libpq-fe.h header
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

When trying with another ruby-postgres driver, ive got

yum install ruby-postgres
ruby-postgres-0.7.1-5.el5.i386 from epel has depsolving problems
  --> Missing Dependency: libpq.so.4 is needed by package ruby-postgres-0.7.1-5.el5.i386 (epel)

and

locate libpq.so.4
/usr/lib/libpq.so.4
/usr/lib/libpq.so.4.1

also exported path

LD_LIBRARY_PATH=/usr/pgsql-9.0/lib
export LD_LIBRARY_PATH

after running ruby script with "require pg" (works on 8.1), ive got:

/usr/local/lib/ruby/site_ruby/1.8/i686-linux/pg_ext.so: libpq.so.4: cannot open shared object file: No such file or directory - /usr/local/lib/ruby/site_ruby/1.8/i686-linux/pg_ext.so (LoadError)
        from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:29:in `require'
        from /usr/local/lib/ruby/site_ruby/1.8/pg.rb:12
        from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:29:in `gem_original_require'
        from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:29:in `require'

Any suggestions what to do more?


问:
How to protect AWS API gateway URL from unauthorized access?
I want to host my static website in AWS  S3. But it contains "contact us" page which is for sending emails. When the user clicks the submit button it sends the request to AWS API gateway, API gateway triggers the lambda function; the lambda function sends the mail to Admin.

But it has some problem . when we host the website at server we can use captcha to prevent the submit request automation and fraudulent activities . in this case the anybody can misuse (sending more request by passing a query string in the URL ) my API gateway URL who know it.

So my question is how to know that the submit request is requested from my website only and is there any way to use instead of Captcha?.

答:
Validate reCAPTCHA using API Gateway and Lambda

For Contact Forms on serverless SPA sites on S3 static sites, I use AngularJS with the "angular-recaptcha" service (https://github.com/VividCortex/angular-recaptcha), though you can use any way of getting and POSTing the recaptcha value.

On the Backend you can use API Gateway which calls a Lambda function to validate the recaptcha value and do something. Using NodeJS and Recaptcha2 (https://www.npmjs.com/package/recaptcha2) to validate the token.

```<code>var reCAPTCHA = require('recaptcha2')

module.exports.sendemail = (event, context, callback) => {

    // parse the data that was sent from API Gateway
    var eventData = JSON.parse(event.body);

    // Prepare the recaptcha connection to Google
    var recaptcha = new reCAPTCHA({
      siteKey: process.env.RECAPTCHA_KEY,
      secretKey: process.env.RECAPTCHA_SECRET
    })

    // Validate the recaptcha value
    recaptcha.validate(eventData.recaptcha)
        .then(function(){
            // validated ok
            console.log("ReCaptcha Valid")

            ... DO STUFF HERE ...

        })
        .catch(function(errorCodes){

            // invalid recaptcha
            console.log("ReCaptcha Not Valid")

            // translate error codes to human readable text
            console.log(recaptcha.translateErrors(errorCodes));

            // send a fail message with cors headers back to the UI
            var response = {
                statusCode: 500,
                headers: {
                    "Access-Control-Allow-Origin" : "*",
                    "Access-Control-Allow-Credentials" : true
                },
                body: JSON.stringify({"message":"Error: Invalid Recaptcha"})
            }
            callback(null, response);
        });
};
</code>```

Example Templated Emails using Handlebars and SES

As a bonus, here is some code I reuse for sending emails using html/text templates:

Handlebars to inject values to the template SES to send the email.

Make sure that you have set up SES with your domain name, and permissioned the Lambda to "ses:SendEmail" and "ses:SendEmailRaw".

Add the environment variables when deploying the function, this makes the code reusable and keeps the secrets out of the source code.

I highly recommend using the Serverless Framework to deploy your serverless applications. https://serverless.com

Works a treat for me :)

```<code>'use strict';

var AWS = require('aws-sdk');
var ses = new AWS.SES();
var reCAPTCHA = require('recaptcha2')
var fs = require('fs');
var Handlebars = require('handlebars');

module.exports.sendemail = (event, context, callback) => {

    // parse the data that was sent from API Gateway
    var eventData = JSON.parse(event.body);

    // Prepare the recaptcha connection to Google
    var recaptcha = new reCAPTCHA({
      siteKey: process.env.RECAPTCHA_KEY,
      secretKey: process.env.RECAPTCHA_SECRET
    })

    // Validate the recaptcha value
    recaptcha.validate(eventData.recaptcha)
        .then(function(){
            // validated ok
            console.log("reCAPTCHA Valid")

            // Read the HTML template from the package root
            fs.readFile('./contact/email_template.html', function (err, emailHtmlTemplate) {
                if (err) {
                    console.log("Unable to load HTML Template");
                    throw err;
                }
                // Read the TEXT template from the package root
                fs.readFile('./contact/email_template.txt', function (err, emailTextTemplate) {
                    if (err) {
                        console.log("Unable to load TEXT Template");
                        throw err;
                    }

                    // Gather data to be injected to the templates
                    var emailData = {
                        "websiteaddress": process.env.WEBSITEADDRESS,
                        "websitename": process.env.WEBSITENAME,
                        "content": null,
                        "email": process.env.EMAIL_TO,
                        "event": eventData
                    };

                    // Use Handlebars to compile the template and inject values into the title (used in subject and body of email)
                    var templateTitle = Handlebars.compile(process.env.EMAIL_TITLE);
                    var titleText = templateTitle(emailData);
                    console.log(titleText);

                    // Add title to the values object
                    emailData.title = titleText;

                    // Use Handlebars to compile email plaintext body
                    var templateText = Handlebars.compile(emailTextTemplate.toString());
                    var bodyText = templateText(emailData);
                    console.log(bodyText);

                    // Use Handlebars to compile email html body
                    var templateHtml = Handlebars.compile(emailHtmlTemplate.toString());
                    var bodyHtml = templateHtml(emailData);
                    console.log(bodyHtml);

                    // Prepare the SES payload
                    var params = {
                        Destination: {
                            ToAddresses: [
                                process.env.EMAIL_TO
                            ]
                        },
                        Message: {
                            Body: {
                                Text: {
                                    Data: bodyText,
                                    Charset: 'UTF-8'
                                },
                                Html: {
                                    Data: bodyHtml
                                },
                            },
                            Subject: {
                                Data: titleText,
                                Charset: 'UTF-8'
                            }
                        },
                        Source: process.env.EMAIL_FROM
                    }
                    console.log(JSON.stringify(params,null,4));

                    // Send SES Email
                    ses.sendEmail(params, function(err,data){
                        if(err) {
                            console.log(err,err.stack); // error

                            // Handle SES send errors
                            var response = {
                                statusCode: 500,
                                headers: {
                                    "Access-Control-Allow-Origin" : "*",
                                    "Access-Control-Allow-Credentials" : true
                                },
                                body: JSON.stringify({"message":"Error: Unable to Send Message"})
                            }
                            callback(null, response);
                        }
                        else {
                            console.log(data); // success

                            // SES send was successful
                            var response = {
                                statusCode: 200,
                                headers: {
                                    "Access-Control-Allow-Origin" : "*",
                                    "Access-Control-Allow-Credentials" : true
                                },
                                body: JSON.stringify({"message":"Message Sent"})
                            }
                            callback(null, response);
                        }
                  });

              }); //end of load text template
          }); //end of load html template

      })
      .catch(function(errorCodes){

          // invalid recaptcha
          console.log("reCAPTCHA Not Valid")

          // translate error codes to human readable text
          console.log(recaptcha.translateErrors(errorCodes));

          // send a fail message with cors headers back to the UI
          var response = {
              statusCode: 500,
              headers: {
                  "Access-Control-Allow-Origin" : "*",
                  "Access-Control-Allow-Credentials" : true
              },
              body: JSON.stringify({"message":"Error: Invalid Recaptcha"})
          }
          callback(null, response);
     });
 };
</code>```

Edit: fixed syntax error

Body:
Validate reCAPTCHA using API Gateway and Lambda

For Contact Forms on serverless SPA sites on S3 static sites, I use AngularJS with the "angular-recaptcha" service (https://github.com/VividCortex/angular-recaptcha), though you can use any way of getting and POSTing the recaptcha value.

On the Backend you can use API Gateway which calls a Lambda function to validate the recaptcha value and do something. Using NodeJS and Recaptcha2 (https://www.npmjs.com/package/recaptcha2) to validate the token.

var reCAPTCHA = require('recaptcha2')

module.exports.sendemail = (event, context, callback) => {

    // parse the data that was sent from API Gateway
    var eventData = JSON.parse(event.body);

    // Prepare the recaptcha connection to Google
    var recaptcha = new reCAPTCHA({
      siteKey: process.env.RECAPTCHA_KEY,
      secretKey: process.env.RECAPTCHA_SECRET
    })

    // Validate the recaptcha value
    recaptcha.validate(eventData.recaptcha)
        .then(function(){
            // validated ok
            console.log("ReCaptcha Valid")

            ... DO STUFF HERE ...

        })
        .catch(function(errorCodes){

            // invalid recaptcha
            console.log("ReCaptcha Not Valid")

            // translate error codes to human readable text
            console.log(recaptcha.translateErrors(errorCodes));

            // send a fail message with cors headers back to the UI
            var response = {
                statusCode: 500,
                headers: {
                    "Access-Control-Allow-Origin" : "*",
                    "Access-Control-Allow-Credentials" : true
                },
                body: JSON.stringify({"message":"Error: Invalid Recaptcha"})
            }
            callback(null, response);
        });
};

Example Templated Emails using Handlebars and SES

As a bonus, here is some code I reuse for sending emails using html/text templates:

Handlebars to inject values to the template SES to send the email.

Make sure that you have set up SES with your domain name, and permissioned the Lambda to "ses:SendEmail" and "ses:SendEmailRaw".

Add the environment variables when deploying the function, this makes the code reusable and keeps the secrets out of the source code.

I highly recommend using the Serverless Framework to deploy your serverless applications. https://serverless.com

Works a treat for me :)

'use strict';

var AWS = require('aws-sdk');
var ses = new AWS.SES();
var reCAPTCHA = require('recaptcha2')
var fs = require('fs');
var Handlebars = require('handlebars');

module.exports.sendemail = (event, context, callback) => {

    // parse the data that was sent from API Gateway
    var eventData = JSON.parse(event.body);

    // Prepare the recaptcha connection to Google
    var recaptcha = new reCAPTCHA({
      siteKey: process.env.RECAPTCHA_KEY,
      secretKey: process.env.RECAPTCHA_SECRET
    })

    // Validate the recaptcha value
    recaptcha.validate(eventData.recaptcha)
        .then(function(){
            // validated ok
            console.log("reCAPTCHA Valid")

            // Read the HTML template from the package root
            fs.readFile('./contact/email_template.html', function (err, emailHtmlTemplate) {
                if (err) {
                    console.log("Unable to load HTML Template");
                    throw err;
                }
                // Read the TEXT template from the package root
                fs.readFile('./contact/email_template.txt', function (err, emailTextTemplate) {
                    if (err) {
                        console.log("Unable to load TEXT Template");
                        throw err;
                    }

                    // Gather data to be injected to the templates
                    var emailData = {
                        "websiteaddress": process.env.WEBSITEADDRESS,
                        "websitename": process.env.WEBSITENAME,
                        "content": null,
                        "email": process.env.EMAIL_TO,
                        "event": eventData
                    };

                    // Use Handlebars to compile the template and inject values into the title (used in subject and body of email)
                    var templateTitle = Handlebars.compile(process.env.EMAIL_TITLE);
                    var titleText = templateTitle(emailData);
                    console.log(titleText);

                    // Add title to the values object
                    emailData.title = titleText;

                    // Use Handlebars to compile email plaintext body
                    var templateText = Handlebars.compile(emailTextTemplate.toString());
                    var bodyText = templateText(emailData);
                    console.log(bodyText);

                    // Use Handlebars to compile email html body
                    var templateHtml = Handlebars.compile(emailHtmlTemplate.toString());
                    var bodyHtml = templateHtml(emailData);
                    console.log(bodyHtml);

                    // Prepare the SES payload
                    var params = {
                        Destination: {
                            ToAddresses: [
                                process.env.EMAIL_TO
                            ]
                        },
                        Message: {
                            Body: {
                                Text: {
                                    Data: bodyText,
                                    Charset: 'UTF-8'
                                },
                                Html: {
                                    Data: bodyHtml
                                },
                            },
                            Subject: {
                                Data: titleText,
                                Charset: 'UTF-8'
                            }
                        },
                        Source: process.env.EMAIL_FROM
                    }
                    console.log(JSON.stringify(params,null,4));

                    // Send SES Email
                    ses.sendEmail(params, function(err,data){
                        if(err) {
                            console.log(err,err.stack); // error

                            // Handle SES send errors
                            var response = {
                                statusCode: 500,
                                headers: {
                                    "Access-Control-Allow-Origin" : "*",
                                    "Access-Control-Allow-Credentials" : true
                                },
                                body: JSON.stringify({"message":"Error: Unable to Send Message"})
                            }
                            callback(null, response);
                        }
                        else {
                            console.log(data); // success

                            // SES send was successful
                            var response = {
                                statusCode: 200,
                                headers: {
                                    "Access-Control-Allow-Origin" : "*",
                                    "Access-Control-Allow-Credentials" : true
                                },
                                body: JSON.stringify({"message":"Message Sent"})
                            }
                            callback(null, response);
                        }
                  });

              }); //end of load text template
          }); //end of load html template

      })
      .catch(function(errorCodes){

          // invalid recaptcha
          console.log("reCAPTCHA Not Valid")

          // translate error codes to human readable text
          console.log(recaptcha.translateErrors(errorCodes));

          // send a fail message with cors headers back to the UI
          var response = {
              statusCode: 500,
              headers: {
                  "Access-Control-Allow-Origin" : "*",
                  "Access-Control-Allow-Credentials" : true
              },
              body: JSON.stringify({"message":"Error: Invalid Recaptcha"})
          }
          callback(null, response);
     });
 };

Edit: fixed syntax error


问:
Is it possible to add border to image in GitHub markdown?
I need to add border to the image in GitHub README.md file. This is how image should be embeded:

```<code>![GitHub Logo](/images/logo.png)
</code>```

I have tried to wrap image with the table:

```<code>|--------------------------------|
|![GitHub Logo](/images/logo.png)|
</code>```

but it is not possible to create table without header.

I have also tried to include image as html tag:

```<code><img src="/images/logo.png" style="border: 1px solid black" />
</code>```

but without success. Is there any way how to do this?

答:
You can use
 tag to create tables without header.

```<code><table><tr><td>
    <img src="/images/logo.png" />
</td></tr></table>
</code>```

Body:
I need to add border to the image in GitHub README.md file. This is how image should be embeded:

![GitHub Logo](/images/logo.png)

I have tried to wrap image with the table:

|--------------------------------|
|![GitHub Logo](/images/logo.png)|

but it is not possible to create table without header.

I have also tried to include image as html tag:

but without success. Is there any way how to do this?

Body:
You can use <table> tag to create tables without header.

<table><tr><td>
    <img src="/images/logo.png" />
</td></tr></table>


问:
Not reading lesser or greater than input properly
So this is the problem section in a simple "Is your amount greater than or less than 50?" program. This section is entirely independent, but it doesn't work. If my input is 50 or anything less, it says "Sorry, not enough money." But strangely, from 100 and on, it also registers those amounts as "Sorry, that is not enough money." I've tried a bunch of things with it and I can't get it to work! What am I missing? Thank you!</p>

```<code>money_amount = input("Type your amount with no quotations.")

if money_amount <= "50":
    print ("Sorry, that is not enough money.")
    quit()

else:
    print ("Yay!")
</code>```

答:
Or you can try this one:</p>

```<code>money_amount = int(raw_input("Type your amount with no quotations."))
if money_amount <= 50:
     print ("Sorry, that is not enough money.")
     quit()
else:
     print ("Yay!")
</code>```

Body:
So this is the problem section in a simple "Is your amount greater than or less than 50?" program. This section is entirely independent, but it doesn't work. If my input is 50 or anything less, it says "Sorry, not enough money." But strangely, from 100 and on, it also registers those amounts as "Sorry, that is not enough money." I've tried a bunch of things with it and I can't get it to work! What am I missing? Thank you!

money_amount = input("Type your amount with no quotations.")

if money_amount <= "50":
    print ("Sorry, that is not enough money.")
    quit()

else:
    print ("Yay!")

Body:
Or you can try this one:

money_amount = int(raw_input("Type your amount with no quotations."))
if money_amount <= 50:
     print ("Sorry, that is not enough money.")
     quit()
else:
     print ("Yay!")


问:
sql: ERROR 1062 (23000): Duplicate entry '0' for key 'PRIMARY'
I am running and keep getting this error. Any help would be appreciated.
ERROR 1062 (23000): Duplicate entry '0' for key 'PRIMARY'

I have  had other errors with senmcolons, commas and other small mistakes, but this one is eating me alive

```<code>-- 1 - Create Faculty Table
create table Faculty (
FacultyID int not null primary key,
FirstName varchar(50) not null,
LastName varchar(50) not null,
Email varchar(50) not null,
Date_of_birth date,
Number_of_courses smallint not null
);
</code>```

答:
It looks like you don't have auto-increment for FacultyID and it is inserting 0 for each record and you are getting

Duplicate entry '0' for key 'PRIMARY'

Insert value for FacultyID or use Auto increment (AUTO_INCREMENT) for FacultyID.

```<code>create table Faculty (
    FacultyID int not null AUTO_INCREMENT  primary key,
    FirstName varchar(50) not null,
    LastName varchar(50) not null,
    Email varchar(50) not null,
    Date_of_birth date,
    Number_of_courses smallint not null
);
</code>```

Body:
I am running and keep getting this error. Any help would be appreciated.
ERROR 1062 (23000): Duplicate entry '0' for key 'PRIMARY'

I have  had other errors with senmcolons, commas and other small mistakes, but this one is eating me alive

-- 1 - Create Faculty Table
create table Faculty (
FacultyID int not null primary key,
FirstName varchar(50) not null,
LastName varchar(50) not null,
Email varchar(50) not null,
Date_of_birth date,
Number_of_courses smallint not null
);

Body:
It looks like you don't have auto-increment for FacultyID and it is inserting 0 for each record and you are getting

Duplicate entry '0' for key 'PRIMARY'

Insert value for FacultyID or use Auto increment (AUTO_INCREMENT) for FacultyID.

create table Faculty (
    FacultyID int not null AUTO_INCREMENT  primary key,
    FirstName varchar(50) not null,
    LastName varchar(50) not null,
    Email varchar(50) not null,
    Date_of_birth date,
    Number_of_courses smallint not null
);


问:
Using angular 2 material icons
I'm trying to use angular material 2 to display icons on my website, but I'm a little confused.

This is how it's supposed to work, from the demo in github repo of material 2:

https://github.com/angular/material2/blob/master/src/demo-app/icon/icon-demo.ts

I've been trying to use it but no icons are shown at all.

This is how I set it up:

app.component.ts

```<code>import {MdIcon, MdIconRegistry} from '@angular2-material/icon/icon';

@Component({
  ...
  encapsulation: ViewEncapsulation.None,
  viewProviders: [MdIconRegistry],
  directives: [MdIcon],
})
export class MyComponent{
  constructor(private router: Router,
              private JwtService:JwtService,
              mdIconRegistry: MdIconRegistry){
    mdIconRegistry.addSvgIconSetInNamespace('core', 'fonts/core-icon-set.svg')
  }
}
</code>```

and the template..

```<code><md-icon>home</md-icon>
</code>```

The page loads with no errors, but no icon is shown. What could have gone wrong?

答:
This is the way, I tried and it works.

```<code>mdIconRegistry.addSvgIcon('slider', sanitizer.bypassSecurityTrustResourceUrl('./assets/controls/slider.svg'));
</code>```

The instance mdIconRegistry will be available via DI and add custom svg using addSvgIcon method. Then use <md-icon svgIcon="slider"> in your template.

Title: Using angular 2 material icons

Body:
I'm trying to use angular material 2 to display icons on my website, but I'm a little confused.

This is how it's supposed to work, from the demo in github repo of material 2:

https://github.com/angular/material2/blob/master/src/demo-app/icon/icon-demo.ts

I've been trying to use it but no icons are shown at all.

This is how I set it up:

app.component.ts

import {MdIcon, MdIconRegistry} from '@angular2-material/icon/icon';

@Component({
  ...
  encapsulation: ViewEncapsulation.None,
  viewProviders: [MdIconRegistry],
  directives: [MdIcon],
})
export class MyComponent{
  constructor(private router: Router,
              private JwtService:JwtService,
              mdIconRegistry: MdIconRegistry){
    mdIconRegistry.addSvgIconSetInNamespace('core', 'fonts/core-icon-set.svg')
  }
}

and the template..

<md-icon>home</md-icon>

The page loads with no errors, but no icon is shown. What could have gone wrong?

Body:
This is the way, I tried and it works.

mdIconRegistry.addSvgIcon('slider', sanitizer.bypassSecurityTrustResourceUrl('./assets/controls/slider.svg'));

The instance mdIconRegistry will be available via DI and add custom svg using addSvgIcon method. Then use <md-icon svgIcon="slider"> in your template.


问:
Reactjs onClick not rerendering data when sent to child component to get info from api

I am new to react, trying to call api to render data on specific user onClick, data changes on different clicks but only after the user presses a clear button, tried everything i can think of, componentWillUpdate, forceUpdate, but nothing works, i have link to codepen below, any advice is appreciated

https://codepen.io/dau328/pen/ZaVwaQ?editors=0110

```<code>    class Person extends React.Component{
  constructor(props){
    super(props);
    this.props.test = "https://swapi.co/api/people/unknown/";
    this.state = {
      "characters": [
        {
          "name": "Luke Skywalker",
          "url": "https://swapi.co/api/people/1/"
        },
        {
          "name": "Darth Vader",
          "url": "https://swapi.co/api/people/4/"
        },
        {
          "name": "Obi-wan Kenobi",
          "url": "https://swapi.co/api/people/unknown/"
        },
        {
          "name": "R2-D2",
          "url": "https://swapi.co/api/people/3/"
        }
      ],

      url: "",
      person: ""

    };

  }

    handleClick(cName, person, e) {
   // console.log(person);

        this.setState({person: person});
        this.setState({url: cName});
        this.props.test = cName;
     // console.log(this.props.test);
     // console.log(`cName ${cName}`);

  }

   _renderSubComp(link) {
    var url = <FilmDemo subreddit={this.state.url} />;
   if(link === 'https://swapi.co/api/people/1/'){
     return url;
   }

   if(link === 'https://swapi.co/api/people/4/'){
     return url;
   }

     if(link === 'https://swapi.co/api/people/unknown/'){
     return url;
   }

     if(link === 'https://swapi.co/api/people/3/'){
     return url;
   }

   }

    render(){
      var people = this.state.characters.map(function(p) {
      return  <p>{p.name}</p> ;

    });

      return (
        <div>
         <p className="clearButton" onClick={this.handleClick.bind(this, 'null', '' )}><button>Clear</button></p>
        <div className="people">
          <p className="peopleName" onClick={this.handleClick.bind(this, this.state.characters[0].url, people[0] )}>{people[0]} </p>
           <p className="peopleName" onClick={this.handleClick.bind(this, this.state.characters[1].url, people[1] )}>{people[1]} </p>
           <p className="peopleName" onClick={this.handleClick.bind(this, this.state.characters[2].url, people[2] )}>{people[2]}</p>
           <p className="peopleName" onClick={this.handleClick.bind(this, this.state.characters[3].url, people[3] )}>{people[3]}</p>
          </div>

          <span className="info-films example"><h3>{this.state.person}</h3>

            {this._renderSubComp(this.state.url)} </span>

          </div>
        );
    }

}

class Films extends React.Component {
constructor(props){
  super(props);

     this.state = {
      films: [],
       director: [],
       date: []

    };

 }

   componentDidMount() {
      axios.get(`${this.props.name}`)
      .then(res => {
        var filmTitle = res.data.title;
        var director = res.data.director;
        var date = new Date(res.data.release_date);
        var dateFormat = date.toDateString();
        this.setState({films: filmTitle});
        this.setState({director: director});
        this.setState({date: dateFormat});
       // console.log(filmTitle);

      });

   }

    render(){

          return (
      <div>
              <h3 className="filmInfo"> Movie Title: {this.state.films} <div className="info"> director: {this.state.director} </div> release date: {this.state.date} </h3>
      </div>
           );

    }

            }

class FilmDemo extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      posts: [],
      error: null,

    };
  }

  componentDidMount() {
      axios.get(`${this.props.subreddit}`)
      .then(res => {
       // console.log(res);
       // var data = res.data.films;
        const posts = res.data.films.map(obj => obj);
        this.setState({ posts: posts });
       // console.log(this.state);
      //  console.log(posts[0]);
      })
    .catch(err => {
        // Something went wrong. Save the error in state and re-render.
        this.setState({
          error: err
        });
      });

   }

  renderError() {
    return (
      <div className="error">
        Something went wrong: {this.state.error.message}
      </div>
    );
  }

  render() {

     if(this.state.error){
       return this.renderError();
     }

    return (

      <div>

          {this.state.posts.map(post =>
            <Films key={post.id} name={post} />
                              )}
       </div>
    );
  }

}

ReactDOM.render(<div>
  <Person />   </div>,
  document.getElementById('root')
);
</code>```

    I expect to just click on next character and data gets replaced
    The data will not rerender when i click on new character unless i clcik clear button. I tried ComponentWillUpdate on FilmDemo class also forceUpdate, do not know what else to try.

答:
The problem is the placement of the axios.get call in the FilmDemo component. You're fetching data from your API in componentDidMount, which only fires once (after the component has been mounted). Since the component is mounted when you click on the first character, you never fetch data for any subsequent clicks, so the data don't change after the first click.

To fix this, you'll need to move the axios.get call somewhere that will get called on subsequent clicks. You have a couple options here, like componentWillReceiveProps or extracting the call to the parent.

I'd recommend extracting the API call to the parent as follows. Note that the code doesn't have any loading indicators, so you have to remember to wait a second for the API calls to complete and the newest information to become available.

class Person extends React.Component {
  constructor(props) {
    super(props);
    this.props.test = "https://swapi.co/api/people/unknown/";
    this.state = {
      characters: [
        {
          name: "Luke Skywalker",
          url: "https://swapi.co/api/people/1/"
        },
        {
          name: "Darth Vader",
          url: "https://swapi.co/api/people/4/"
        },
        {
          name: "Obi-wan Kenobi",
          url: "https://swapi.co/api/people/unknown/"
        },
        {
          name: "R2-D2",
          url: "https://swapi.co/api/people/3/"
        }
      ],

      url: "",
      person: "",

      // Pulled posts and errors into parent instead of storing
      // them in FilmDemo
      posts: [],
      error: null
    };
  }

  handleClick(cName, person, e) {
    this.setState({ person: person });
    this.setState({ url: cName });
    this.props.test = cName;

    // On each click, call the API and then call this.setState
    // this.setState triggers a re-render which garauntees
    // the newest information will show up
    axios
      .get(`${cName}`)
      .then(res => {
        const posts = res.data.films.map(obj => obj);
        this.setState({ posts: posts, error: null });
      })
      .catch(err => {
        this.setState({
          error: err
        });
      });
  }

  _renderSubComp(link) {
    // Now, pass the fetched posts and possible errors down as props
    var url = <FilmDemo posts={this.state.posts} error={this.state.error} />;

    if (link === "https://swapi.co/api/people/1/") {
      return url;
    }

    if (link === "https://swapi.co/api/people/4/") {
      return url;
    }

    if (link === "https://swapi.co/api/people/unknown/") {
      return url;
    }

    if (link === "https://swapi.co/api/people/3/") {
      return url;
    }
  }

  render() {
    var people = this.state.characters.map(function(p) {
      return
{p.name}
;
    });

    return (

          <button>Clear</button>

            {people[0]}{" "}

            {people[1]}{" "}

            {people[2]}

            {people[3]}

{this.state.person}

          {this._renderSubComp(this.state.url)}

    );
  }
}

class Films extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      films: [],
      director: [],
      date: []
    };
  }

  componentDidMount() {
    axios.get(`${this.props.name}`).then(res => {
      var filmTitle = res.data.title;
      var director = res.data.director;
      var date = new Date(res.data.release_date);
      var dateFormat = date.toDateString();

      // Each call to setState triggers a (potentially expensive)
      // re-render, so make sure to group these as follows:
      this.setState({ films: filmTitle, director: director, date: dateFormat });
    });
  }

  render() {
    return (

          {" "}
          Movie Title: {this.state.films}{" "}

 director: {this.state.director}
 release
          date: {this.state.date}{" "}

    );
  }
}

class FilmDemo extends React.Component {
  renderError() {
    return (

        Something went wrong: {this.props.error.message}

    );
  }

  render() {
    // Now, the appropriate information is passed down as props on each new click
    if (this.props.error) {
      return this.renderError();
    }

    return (

        {this.props.posts.map(post => <Films key={post.id} name={post} />)}

    );
  }
}

ReactDOM.render(

    <Person />{" "}

,
  document.getElementById("root")
);
```

I left some comments to explain the things I changed.

There are also some other issues you might be concerned with going forward. For example, the _renderSubComp does not return a value in all code paths.

Happy coding!

Body:
I am new to react, trying to call api to render data on specific user onClick, data changes on different clicks but only after the user presses a clear button, tried everything i can think of, componentWillUpdate, forceUpdate, but nothing works, i have link to codepen below, any advice is appreciated

https://codepen.io/dau328/pen/ZaVwaQ?editors=0110

    class Person extends React.Component{
  constructor(props){
    super(props);
    this.props.test = "https://swapi.co/api/people/unknown/";
    this.state = {
      "characters": [
        {
          "name": "Luke Skywalker",
          "url": "https://swapi.co/api/people/1/"
        },
        {
          "name": "Darth Vader",
          "url": "https://swapi.co/api/people/4/"
        },
        {
          "name": "Obi-wan Kenobi",
          "url": "https://swapi.co/api/people/unknown/"
        },
        {
          "name": "R2-D2",
          "url": "https://swapi.co/api/people/3/"
        }
      ],

      url: "",
      person: ""

    };

  }

    handleClick(cName, person, e) {
   // console.log(person);

        this.setState({person: person});
        this.setState({url: cName});
        this.props.test = cName;
     // console.log(this.props.test);
     // console.log(`cName ${cName}`);

  }

   _renderSubComp(link) {
    var url = <FilmDemo subreddit={this.state.url} />;
   if(link === 'https://swapi.co/api/people/1/'){
     return url;
   }

   if(link === 'https://swapi.co/api/people/4/'){
     return url;
   }

     if(link === 'https://swapi.co/api/people/unknown/'){
     return url;
   }

     if(link === 'https://swapi.co/api/people/3/'){
     return url;
   }

   }

    render(){
      var people = this.state.characters.map(function(p) {
      return
{p.name}
 ;

    });

      return (

<button>Clear</button>

{people[0]}

{people[1]}

{people[2]}

{people[3]}

{this.state.person}

            {this._renderSubComp(this.state.url)}

        );
    }

}

class Films extends React.Component {
constructor(props){
  super(props);

     this.state = {
      films: [],
       director: [],
       date: []

    };

 }

   componentDidMount() {
      axios.get(`${this.props.name}`)
      .then(res => {
        var filmTitle = res.data.title;
        var director = res.data.director;
        var date = new Date(res.data.release_date);
        var dateFormat = date.toDateString();
        this.setState({films: filmTitle});
        this.setState({director: director});
        this.setState({date: dateFormat});
       // console.log(filmTitle);

      });

   }

    render(){

          return (

 Movie Title: {this.state.films}
 director: {this.state.director}
 release date: {this.state.date}

           );

    }

            }

class FilmDemo extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      posts: [],
      error: null,

    };
  }

  componentDidMount() {
      axios.get(`${this.props.subreddit}`)
      .then(res => {
       // console.log(res);
       // var data = res.data.films;
        const posts = res.data.films.map(obj => obj);
        this.setState({ posts: posts });
       // console.log(this.state);
      //  console.log(posts[0]);
      })
    .catch(err => {
        // Something went wrong. Save the error in state and re-render.
        this.setState({
          error: err
        });
      });

   }

  renderError() {
    return (

        Something went wrong: {this.state.error.message}

    );
  }

  render() {

     if(this.state.error){
       return this.renderError();
     }

    return (

          {this.state.posts.map(post =>
            <Films key={post.id} name={post} />
                              )}

    );
  }

}

ReactDOM.render(

  <Person />
,
  document.getElementById('root')
);

    I expect to just click on next character and data gets replaced
    The data will not rerender when i click on new character unless i clcik clear button. I tried ComponentWillUpdate on FilmDemo class also forceUpdate, do not know what else to try.

Body:
The problem is the placement of the axios.get call in the FilmDemo component. You're fetching data from your API in componentDidMount, which only fires once (after the component has been mounted). Since the component is mounted when you click on the first character, you never fetch data for any subsequent clicks, so the data don't change after the first click.

To fix this, you'll need to move the axios.get call somewhere that will get called on subsequent clicks. You have a couple options here, like componentWillReceiveProps or extracting the call to the parent.

I'd recommend extracting the API call to the parent as follows. Note that the code doesn't have any loading indicators, so you have to remember to wait a second for the API calls to complete and the newest information to become available.

class Person extends React.Component {
  constructor(props) {
    super(props);
    this.props.test = "https://swapi.co/api/people/unknown/";
    this.state = {
      characters: [
        {
          name: "Luke Skywalker",
          url: "https://swapi.co/api/people/1/"
        },
        {
          name: "Darth Vader",
          url: "https://swapi.co/api/people/4/"
        },
        {
          name: "Obi-wan Kenobi",
          url: "https://swapi.co/api/people/unknown/"
        },
        {
          name: "R2-D2",
          url: "https://swapi.co/api/people/3/"
        }
      ],

      url: "",
      person: "",

      // Pulled posts and errors into parent instead of storing
      // them in FilmDemo
      posts: [],
      error: null
    };
  }

  handleClick(cName, person, e) {
    this.setState({ person: person });
    this.setState({ url: cName });
    this.props.test = cName;

    // On each click, call the API and then call this.setState
    // this.setState triggers a re-render which garauntees
    // the newest information will show up
    axios
      .get(`${cName}`)
      .then(res => {
        const posts = res.data.films.map(obj => obj);
        this.setState({ posts: posts, error: null });
      })
      .catch(err => {
        this.setState({
          error: err
        });
      });
  }

  _renderSubComp(link) {
    // Now, pass the fetched posts and possible errors down as props
    var url = <FilmDemo posts={this.state.posts} error={this.state.error} />;

    if (link === "https://swapi.co/api/people/1/") {
      return url;
    }

    if (link === "https://swapi.co/api/people/4/") {
      return url;
    }

    if (link === "https://swapi.co/api/people/unknown/") {
      return url;
    }

    if (link === "https://swapi.co/api/people/3/") {
      return url;
    }
  }

  render() {
    var people = this.state.characters.map(function(p) {
      return <p>{p.name}</p>;
    });

    return (
      <div>
        <p
          className="clearButton"
          onClick={this.handleClick.bind(this, "null", "")}
        >
          <button>Clear</button>
        </p>
        <div className="people">
          <p
            className="peopleName"
            onClick={this.handleClick.bind(
              this,
              this.state.characters[0].url,
              people[0]
            )}
          >
            {people[0]}{" "}
          </p>
          <p
            className="peopleName"
            onClick={this.handleClick.bind(
              this,
              this.state.characters[1].url,
              people[1]
            )}
          >
            {people[1]}{" "}
          </p>
          <p
            className="peopleName"
            onClick={this.handleClick.bind(
              this,
              this.state.characters[2].url,
              people[2]
            )}
          >
            {people[2]}
          </p>
          <p
            className="peopleName"
            onClick={this.handleClick.bind(
              this,
              this.state.characters[3].url,
              people[3]
            )}
          >
            {people[3]}
          </p>
        </div>

        <span className="info-films example">
          <h3>{this.state.person}</h3>
          {this._renderSubComp(this.state.url)}
        </span>
      </div>
    );
  }
}

class Films extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      films: [],
      director: [],
      date: []
    };
  }

  componentDidMount() {
    axios.get(`${this.props.name}`).then(res => {
      var filmTitle = res.data.title;
      var director = res.data.director;
      var date = new Date(res.data.release_date);
      var dateFormat = date.toDateString();

      // Each call to setState triggers a (potentially expensive)
      // re-render, so make sure to group these as follows:
      this.setState({ films: filmTitle, director: director, date: dateFormat });
    });
  }

  render() {
    return (
      <div>
        <h3 className="filmInfo">
          {" "}
          Movie Title: {this.state.films}{" "}
          <div className="info"> director: {this.state.director} </div> release
          date: {this.state.date}{" "}
        </h3>
      </div>
    );
  }
}

class FilmDemo extends React.Component {
  renderError() {
    return (
      <div className="error">
        Something went wrong: {this.props.error.message}
      </div>
    );
  }

  render() {
    // Now, the appropriate information is passed down as props on each new click
    if (this.props.error) {
      return this.renderError();
    }

    return (
      <div>
        {this.props.posts.map(post => <Films key={post.id} name={post} />)}
      </div>
    );
  }
}

ReactDOM.render(
  <div>
    <Person />{" "}
  </div>,
  document.getElementById("root")
);

I left some comments to explain the things I changed.

There are also some other issues you might be concerned with going forward. For example, the _renderSubComp does not return a value in all code paths.

Happy coding!


问:
Ejb application server in Eclipse development
I want to develop an EJB project using Eclipse. In the Eclipse development environment, which application server is lightest, easiest and fastest ?

Thanks.

答: I'm using JBoss 4 and Eclipse for a project at work. The workflow is OK but I'm stuck with it because of the code. Arun Gupta just released a 5-part screen cast using GlassFish and Eclipse for Java EE development, probably worth checking out.  http://blogs.oracle.com/arungupta/entry/screencast_31_java_ee_6</p>


问:
How do you specify permissionID in Google Drive API v3?
I understand that v3 narrows the data returned from the API, which makes sense. I’m using v2 and a fileId and get a large amount of data.

I believe you have to specify permissionId in v3 to get anything beyond a basic return.

But I don’t understand what permissionId really is - I initially thought it would just be a key/value sort of thing. Specify “owner.emailAddress” in your call and get that value back for a specific fileId. But I don’t think that is the case...but I haven’t found a decent, entry-level description, perhaps because it is assumed knowledge.

If I wanted to get a document owner’s email with v3, what URL would I use in my Get?

答:
In order to retrieve the e-mail of document owner using Drive API v3, you can use the following request.

```<code>GET https://www.googleapis.com/drive/v3/files/### file ID ###?fields=owners%2FemailAddress
</code>```

owners%2FemailAddress was URL encoded from owners/emailAddress.

If I misunderstand your question, I'm sorry.

Body:
In order to retrieve the e-mail of document owner using Drive API v3, you can use the following request.

GET https://www.googleapis.com/drive/v3/files/### file ID ###?fields=owners%2FemailAddress

owners%2FemailAddress was URL encoded from owners/emailAddress.

If I misunderstand your question, I'm sorry.