答:
By your definition of the Particle class, my_first_particle (an instance of Particle) has no display attribute.

It looks like the definition of the display function should be part of the Particle class definition.

Check out the Python Classes tutorial.

Title: Python - AttributeError: 'Particle' object has no attribute 'display'

Body:
This question is asked a lot, but unfortunately I found no answer fitting my problem. If possible, I prefer a generic answer, since I'm a novice trying to learn Python. Thank you in advance.

This is the code I got by following a tutorial on the basics of python using the pygame library:

import pygame

background_colour = (255, 255, 255)
(width, height) = (300, 200)

class Particle:
    def __init__(self, x, y, size):
        self.x = x
        self.y = y
        self.size = size
        self.colour = (0, 0, 255)
        self.thickness = 1

screen = pygame.display.set_mode((width, height))

def display(self):
    pygame.draw.circle(screen, self.colour, (self.x, self.y), self.size,  self.thickness)

pygame.display.set_caption('Agar')
screen.fill(background_colour)
pygame.display.flip()

running = True
my_first_particle = Particle(150, 50, 15)
my_first_particle.display()
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

It is used to create a window for gaming, with a circle in it. The circle is defined as a class to be used multiple times in a similar way later on.

I got the following error:

Traceback (most recent call last):
  File "C:/Users/20172542/PycharmProjects/agarTryout/Agar.py", line 29, in <module>
    my_first_particle.display()
AttributeError: 'Particle' object has no attribute 'display'

What principle am I not understanding, and what is the specific solution for this error?

Thank you for your time and effort.


来源: stackexchange

问:
Hover effect on only one element and not affect the others
How to animate only one element (div) each time, having class .box and not affect the other elements with same class. Something like this :

```<code>$(.box).hover(function() {
        $(.box).animate({ fontSize : '2rem' });
        $(.box).removeClass("main");
        // other things...
</code>```

html:

```<code><div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</code>```

I tried with .next() and .find() but I did not succeed because of my basic level in jQuery.

答:
how to make a simple code for animate only one element and not affect the others divs with same class like this.

```<code>$(<selector>)
</code>```

Selects elements pseudo-based on CSS and some built in keywords by the jQuery team.

When you attach/bind an event to subscribe to on all of your selected elements

```<code>$('.box').hover(function() { /* do something */ })
</code>```

You basically saying when any of the .box class elements are hovered by a mouse execute a function.  jQuery will setup a context in which the event is binded with the value of this as the raw html element (not a jQuery object) as a feature.  (you can read more about this here). jQuery's selector engine also provides a way to convert raw html elements into jQuery object by simply passing them as a selector $(this). Thus some as simple as the following is possible:

$(document).ready(function(){
  $('.box').hover(
    function() { $(this).addClass('is-hover'); },
    function() { $(this).removeClass('is-hover'); });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box{border: 4px solid transparent}
.box.is-hover{border-color: red;}</code>```

Test

Test

Test

Test
```
</div>
</div>
</p>

<p>Replacing <code>$(this)</code> with <code>$('.box')</code> is executing a new query to find all elements with a box class, thus it will affect all the classes with a box class:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function(){
  $('.box').hover(
    function() { $('.box').addClass('is-hover'); },
    function() { $('.box').removeClass('is-hover'); });
});</code>```

.box{border: 4px solid transparent}
.box.is-hover{border-color: red;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">Test</div>
<div class="box">Test</div>
<div class="box">Test</div>
<div class="box">Test</div></code>```

Granted if you want to do this a way the more experienced developers would consider best practices, you wouldn't even use jQuery.

.box {
font-size:1rem;
transition: font-size .4s linear;
}
.box:hover {
color:red;
font-size: 2rem;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
<div class="box">5</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
How to animate only one element (div) each time, having class .box and not affect the other elements with same class. Something like this :

$(.box).hover(function() {
        $(.box).animate({ fontSize : '2rem' });
        $(.box).removeClass("main");
        // other things...

html:

I tried with .next() and .find() but I did not succeed because of my basic level in jQuery.

Body:
how to make a simple code for animate only one element and not affect the others divs with same class like this.

$(<selector>)

Selects elements pseudo-based on CSS and some built in keywords by the jQuery team.

When you attach/bind an event to subscribe to on all of your selected elements

$('.box').hover(function() { /* do something */ })

You basically saying when any of the .box class elements are hovered by a mouse execute a function.  jQuery will setup a context in which the event is binded with the value of this as the raw html element (not a jQuery object) as a feature.  (you can read more about this here). jQuery's selector engine also provides a way to convert raw html elements into jQuery object by simply passing them as a selector $(this). Thus some as simple as the following is possible:

$(document).ready(function(){
  $('.box').hover(
    function() { $(this).addClass('is-hover'); },
    function() { $(this).removeClass('is-hover'); });
});

.box{border: 4px solid transparent}
.box.is-hover{border-color: red;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">Test</div>
<div class="box">Test</div>
<div class="box">Test</div>
<div class="box">Test</div>

Replacing $(this) with $('.box') is executing a new query to find all elements with a box class, thus it will affect all the classes with a box class:

$(document).ready(function(){
  $('.box').hover(
    function() { $('.box').addClass('is-hover'); },
    function() { $('.box').removeClass('is-hover'); });
});

.box{border: 4px solid transparent}
.box.is-hover{border-color: red;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">Test</div>
<div class="box">Test</div>
<div class="box">Test</div>
<div class="box">Test</div>

Granted if you want to do this a way the more experienced developers would consider best practices, you wouldn't even use jQuery.

.box {
font-size:1rem;
transition: font-size .4s linear;
}
.box:hover {
color:red;
font-size: 2rem;
}

<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
<div class="box">5</div>


问:
How to receive SMS using Android service with BroadcastReceiver without GUI
I have been working on an application that use to receive SMS and show a Toast using Broadcast Receiver and i have an activity with no purpose, when i removed that activity and build the apk and run on my phone, application is not responding when SMS is received (no Toast showing), although remaining code is same as it was previously. Can anyone help please i am so stuck and couldn't help myself reading hundreds of answers. I studied i should create a service but still no Toast is appearing. below is my code. I can not have any GUI in my application even don't want to have auto kill activity.

BroadcastReceiver.java

```<code>package com.test.testservice;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;

public class SmsReceiver extends BroadcastReceiver {

    public static final String SMS_BUNDLE = "pdus";
    private static final String LOG = "SmsBroadcastReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {

        Bundle intentExtras = intent.getExtras();
        if (intentExtras != null) {
            Object[] sms = (Object[]) intentExtras.get(SMS_BUNDLE);

            if (sms != null)
            {
                String smsMessageStr = "";

                for (int i = 0; i < sms.length; ++i)
                {
                    SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);

                    String smsBody = smsMessage.getMessageBody().toString();
                    String address = smsMessage.getOriginatingAddress();

                    smsMessageStr += "SMS From: " + address + "\n";
                    smsMessageStr += smsBody + "\n";
                }
                Toast.makeText(context, smsMessageStr, Toast.LENGTH_LONG).show();
                //MyService objService=new MyService();
                //objService.startService(intent);
                //objService.stopService(intent);

                Intent myIntent = new Intent(context, MyService.class);
                //myIntent.putExtra("Sender", Sender);
                //myIntent.putExtra("Fullsms", Fullsms);
                context.startService(myIntent);

            }
        }
    }
}
</code>```

MyService.java

```<code>package com.test.testservice;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service {
    private static final String LOG = "MyService";
    @Override
    public boolean stopService(Intent name) {
        if (super.stopService(name))
        {
            Toast.makeText(this,"HELLO stopService",Toast.LENGTH_LONG).show();
            Log.i(LOG, "stopService");
            return true;
        }
        else return false;
    }

    @Override
    public ComponentName startService(Intent service) {
        return super.startService(service);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Toast.makeText(this,"HELLO onCreate",Toast.LENGTH_LONG).show();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Toast.makeText(this,"HELLO onStart",Toast.LENGTH_LONG).show();
    }
}
</code>```

AndroidManifest.xml

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.test.testservice">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <receiver android:name=".SmsReceiver" android:enabled="true" android:exported="true">
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
                <action android:name="android.intent.action.REBOOT"/>
            </intent-filter>
        </receiver>

    </application>

    <service android:name="com.test.testservice.service.MyService"/>

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.WRITE_SMS" />
    <uses-permission android:name="android.permission.READ_SMS" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
</manifest>
</code>```

答:
Unless you are creating your own phone, or your own custom ROM, you need the activity. Your BroadcastReceiver will not work when your app is first installed. It will only start to work once the user has launched your activity (or something else uses an explicit Intent to start one of your components).

I can not have any GUI in my application

Then your app will not work on Android 3.1+ devices, which make up the vast majority of the Android device ecosystem.

Body:
I have been working on an application that use to receive SMS and show a Toast using Broadcast Receiver and i have an activity with no purpose, when i removed that activity and build the apk and run on my phone, application is not responding when SMS is received (no Toast showing), although remaining code is same as it was previously. Can anyone help please i am so stuck and couldn't help myself reading hundreds of answers. I studied i should create a service but still no Toast is appearing. below is my code. I can not have any GUI in my application even don't want to have auto kill activity.

BroadcastReceiver.java

package com.test.testservice;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;

public class SmsReceiver extends BroadcastReceiver {

    public static final String SMS_BUNDLE = "pdus";
    private static final String LOG = "SmsBroadcastReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {

        Bundle intentExtras = intent.getExtras();
        if (intentExtras != null) {
            Object[] sms = (Object[]) intentExtras.get(SMS_BUNDLE);

            if (sms != null)
            {
                String smsMessageStr = "";

                for (int i = 0; i < sms.length; ++i)
                {
                    SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);

                    String smsBody = smsMessage.getMessageBody().toString();
                    String address = smsMessage.getOriginatingAddress();

                    smsMessageStr += "SMS From: " + address + "\n";
                    smsMessageStr += smsBody + "\n";
                }
                Toast.makeText(context, smsMessageStr, Toast.LENGTH_LONG).show();
                //MyService objService=new MyService();
                //objService.startService(intent);
                //objService.stopService(intent);

                Intent myIntent = new Intent(context, MyService.class);
                //myIntent.putExtra("Sender", Sender);
                //myIntent.putExtra("Fullsms", Fullsms);
                context.startService(myIntent);

            }
        }
    }
}

MyService.java

package com.test.testservice;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service {
    private static final String LOG = "MyService";
    @Override
    public boolean stopService(Intent name) {
        if (super.stopService(name))
        {
            Toast.makeText(this,"HELLO stopService",Toast.LENGTH_LONG).show();
            Log.i(LOG, "stopService");
            return true;
        }
        else return false;
    }

    @Override
    public ComponentName startService(Intent service) {
        return super.startService(service);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Toast.makeText(this,"HELLO onCreate",Toast.LENGTH_LONG).show();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Toast.makeText(this,"HELLO onStart",Toast.LENGTH_LONG).show();
    }
}

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.test.testservice">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <receiver android:name=".SmsReceiver" android:enabled="true" android:exported="true">
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
                <action android:name="android.intent.action.REBOOT"/>
            </intent-filter>
        </receiver>

    </application>

    <service android:name="com.test.testservice.service.MyService"/>

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.WRITE_SMS" />
    <uses-permission android:name="android.permission.READ_SMS" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
</manifest>


问:
numpy element-wise comparison in image
There are many answers related to avoid brute force RGB opencv image loop in python by using numpy. I checked many of them but none seems to answer completely my needs:

Given a image, I need to compare pixel-wise and create a mask based in the result. Is something like:

```<code># image contains a jpg regular image
data = np.asarray(image)

# Separate each channel
blue, green, red = data.T

print(blue.shape)
#(1024, 1024)
</code>```

So far so good.

I need a "white" mask of this image like the following:

->A pixel is white if its red_value > 80 AND red_value-green_value > 20 AND red_value-blue_value > 20

So after research I came to this:

```<code>white = ((red > 80).all and (red-green > 20).all and (red-blue > 20).all)
</code>```

But after this operation I can´t read white values.

I tried many things like:

```<code>print(white.shape)
</code>```

Gets: AttributeError: 'builtin_function_or_method' object has no attribute 'shape'

```<code>w = np.asarray(white)
</code>```

Gets: array ( "<" built-in method all of numpy.ndarray object at 0x0408ED68">", dtype=object)

Any suggestions?
Thanks.

答:
You have a couple of problem in your rgb expression which should be cleared up by this example:

```<code>import numpy as np
r, g, b = [np.random.rand(5,5) for i in range(3)]

w = (r>.5) & (b>.5) & (g>.5)  # change your "white = ..." to look similar to this
</code>```

To be more explicit: 1) don't use all when you want to do an element-wise comparison; 2) and doesn't usually do what you want with numpy arrays, instead use &; 3) you need to use the parens for this expression to work right.

Title: numpy element-wise comparison in image

Body:
There are many answers related to avoid brute force RGB opencv image loop in python by using numpy. I checked many of them but none seems to answer completely my needs:

Given a image, I need to compare pixel-wise and create a mask based in the result. Is something like:

# image contains a jpg regular image
data = np.asarray(image)

# Separate each channel
blue, green, red = data.T

print(blue.shape)
#(1024, 1024)

So far so good.

I need a "white" mask of this image like the following:

->A pixel is white if its red_value > 80 AND red_value-green_value > 20 AND red_value-blue_value > 20

So after research I came to this:

white = ((red > 80).all and (red-green > 20).all and (red-blue > 20).all)

But after this operation I can´t read white values.

I tried many things like:

print(white.shape)

Gets: AttributeError: 'builtin_function_or_method' object has no attribute 'shape'

w = np.asarray(white)

Gets: array ( "<" built-in method all of numpy.ndarray object at 0x0408ED68">", dtype=object)

Any suggestions?
Thanks.

Body:
You have a couple of problem in your rgb expression which should be cleared up by this example:

import numpy as np
r, g, b = [np.random.rand(5,5) for i in range(3)]

w = (r>.5) & (b>.5) & (g>.5)  # change your "white = ..." to look similar to this

To be more explicit: 1) don't use all when you want to do an element-wise comparison; 2) and doesn't usually do what you want with numpy arrays, instead use &; 3) you need to use the parens for this expression to work right.


问:
jQuery Mobile: How to correctly submit form data
This is a jQuery Mobile question, but it also relates to pure jQuery.

How can I post form data without page transition to the page set into form action attribute. I am building phonegap application and I don't want to directly access server side page.

I have tried few examples but each time form forwards me to the destination php file.

答:
Problem is that JQuery Mobile uses ajax to submit the form. The simple solution to this is to disable the ajax and submit form as a normal form.

Simple solution: form action="" method="post" data-ajax="false"


问:
How to connect buttons to texts that changes on vertical slide?
I don't know if it is a laborious question for whoever's going to answer this, and I'm sorry in this case, but I'm lost and here's the deal:

I have a vertical navigation bar at the left side of the page, and some text on the right side. Each button of the navigation has its own text, and I want it to be like: every time one of the buttons is clicked, the actual text slides (up or down), giving space to other text.

I need it to be in the same page, without link changing (in other words, without "a" tag). Do I need JavaScript to do this, or it can be done only by CSS?

In JavaScript case, I think it should be done with the onClick event, but I don't know how to proceed in this case. Can someone help me on this?
I hope I've made my problem clear, because I'm not fluent in English.

Here's a very simple demonstration, I hope it to be useful:
https://jsfiddle.net/4cgsn76t/3/

```<code><ul>

<li>Button 1</li>
<li>Button 2</li>
<li>Button 1</li>
<li>Button 2</li>
</ul>
<!-- Text below connected to Button 1 -->
<p>
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga."
</p>
<!-- Text below connected to Button 2 -->
<p>
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo."
</p>

ul {

  float:left;
}

ul li {
  list-style:none;
  width:100px;
  height: 30px;
  background:blue;
  margin-top:15px;
  margin-right:30px;
  color:white;
  border-radius:5px;
  cursor:pointer;
}

p {
  width:300px;
  float:left;
  font-size:12px;
}

p:nth-child(2) {
  display:none;
}
</code>```

答:
Get the lists of lis and ps using Document#querySelectorAll. Iterate the list items with .forEach(), and add an event listener to each item. When one is clicked hide all paragraphs, and show the relevant text:

var para = document.querySelectorAll('p');

document.querySelectorAll('li').forEach(function(el, i) {
  el.addEventListener('click', function() {
    para.forEach(function(p) {
      p.style.display = 'none';
    });

    para[i].style.display = 'block'
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul {
  float: left;
}

ul li {
  list-style: none;
  width: 100px;
  height: 30px;
  background: blue;
  margin-top: 15px;
  margin-right: 30px;
  color: white;
  border-radius: 5px;
  cursor: pointer;
}

p {
  width: 300px;
  float: left;
  font-size: 12px;
}

p:not(:first-child) {
  display: none;
}</code>```

Button 1

Button 2

    "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia
    animi, id est laborum et dolorum fuga."

    "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo."

```

ContentLicense: CC BY-SA 4.0

Body:
I don't know if it is a laborious question for whoever's going to answer this, and I'm sorry in this case, but I'm lost and here's the deal:

I have a vertical navigation bar at the left side of the page, and some text on the right side. Each button of the navigation has its own text, and I want it to be like: every time one of the buttons is clicked, the actual text slides (up or down), giving space to other text.

I need it to be in the same page, without link changing (in other words, without "a" tag). Do I need JavaScript to do this, or it can be done only by CSS?

In JavaScript case, I think it should be done with the onClick event, but I don't know how to proceed in this case. Can someone help me on this?
I hope I've made my problem clear, because I'm not fluent in English.

Here's a very simple demonstration, I hope it to be useful:
https://jsfiddle.net/4cgsn76t/3/

Button 1

Button 2

Button 1

Button 2

"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga."

"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo."

ul {

  float:left;
}

ul li {
  list-style:none;
  width:100px;
  height: 30px;
  background:blue;
  margin-top:15px;
  margin-right:30px;
  color:white;
  border-radius:5px;
  cursor:pointer;
}

p {
  width:300px;
  float:left;
  font-size:12px;
}

p:nth-child(2) {
  display:none;
}

Body:
Get the lists of lis and ps using Document#querySelectorAll. Iterate the list items with .forEach(), and add an event listener to each item. When one is clicked hide all paragraphs, and show the relevant text:

var para = document.querySelectorAll('p');

document.querySelectorAll('li').forEach(function(el, i) {
  el.addEventListener('click', function() {
    para.forEach(function(p) {
      p.style.display = 'none';
    });

    para[i].style.display = 'block'
  });
});

ul {
  float: left;
}

ul li {
  list-style: none;
  width: 100px;
  height: 30px;
  background: blue;
  margin-top: 15px;
  margin-right: 30px;
  color: white;
  border-radius: 5px;
  cursor: pointer;
}

p {
  width: 300px;
  float: left;
  font-size: 12px;
}

p:not(:first-child) {
  display: none;
}

<ul>
  <li>Button 1</li>
  <li>Button 2</li>
</ul>
<div>
  <!-- Text below connected to Button 1 -->
  <p>
    "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia
    animi, id est laborum et dolorum fuga."
  </p>
  <!-- Text below connected to Button 2 -->
  <p>
    "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo."
  </p>
</div>


问:
Should I go the widget way or HTML way?
Using UIBinder and Widgets is straightforward but the html it produces is quite bloted and difficult to style (uibinder generates a lot of inline styles that override external styling - even HTMLPanel has some).

Should I go with plain HTML where reasonable to get a clean makrup (with plain Element Objects - eg. ButtonElement) ?

How to process events then ?

Or is it a productivity overkill not worth doing ?

What are pro's and con's of widget vs html way ?

答:
My choice widget. I hate play with html and their id's and write javascript function for them and other reasons.

gwt has many reasonable widgets that really facilitate coding and thinking! just write any widget and many many handler to it instead of writing javascript functions of course if you like coding java.

you can say some widgets are slow in some browser but the speed is not important in all time performance and scalability is much more important that gwt structure and gwt-rpc mechanism guaranties it to you.

ContentLicense: CC BY-SA 2.5

Title: Should I go the widget way or HTML way?


问:
Lambda Function in VPC has no Internet Access
My Lambda function has access to other resources in the VPC, but once it attempts to make a request out to the Internet it will timeout. I have the following:

Two private subnets

A Route Table that routes 0.0.0.0/0 to the Internet Gateway.

A couple ACL Rules and a Lambda Security Group

Any help would be helpful. Here are my CF Templates:

```<code>AWSTemplateFormatVersion: 2010-09-09
Description: VPC Stack
Resources:
  VPC:
    Type: 'AWS::EC2::VPC'
    Properties:
      CidrBlock: 10.0.0.0/16
      EnableDnsHostnames: true
      Tags:
        - Key: Application
          Value: !Ref 'AWS::StackId'
  Subnet1:
    Type: 'AWS::EC2::Subnet'
    Properties:
      VpcId: !Ref VPC
      CidrBlock: 10.0.3.0/24
      AvailabilityZone: 'us-east-1b'
      Tags:
        - Key: Application
          Value: !Ref 'AWS::StackId'
  Subnet2:
    Type: 'AWS::EC2::Subnet'
    Properties:
      VpcId: !Ref VPC
      CidrBlock: 10.0.4.0/24
      AvailabilityZone: 'us-east-1e'
      Tags:
        - Key: Application
          Value: !Ref 'AWS::StackId'
  InternetGateway:
    Type: 'AWS::EC2::InternetGateway'
    Properties:
      Tags:
        - Key: Application
          Value: !Ref 'AWS::StackId'
  AttachGateway:
    Type: 'AWS::EC2::VPCGatewayAttachment'
    Properties:
      VpcId: !Ref VPC
      InternetGatewayId: !Ref InternetGateway
  RouteTable:
    Type: 'AWS::EC2::RouteTable'
    Properties:
      VpcId: !Ref VPC
      Tags:
        - Key: Application
          Value: !Ref 'AWS::StackId'
  Route:
    Type: 'AWS::EC2::Route'
    DependsOn: AttachGateway
    Properties:
      RouteTableId: !Ref RouteTable
      DestinationCidrBlock: 0.0.0.0/0
      GatewayId: !Ref InternetGateway
  SubnetRouteTableAssociation1:
    Type: 'AWS::EC2::SubnetRouteTableAssociation'
    Properties:
      SubnetId: !Ref Subnet1
      RouteTableId: !Ref RouteTable
  SubnetRouteTableAssociation2:
    Type: 'AWS::EC2::SubnetRouteTableAssociation'
    Properties:
      SubnetId: !Ref Subnet2
      RouteTableId: !Ref RouteTable
  NetworkAcl:
    Type: 'AWS::EC2::NetworkAcl'
    Properties:
      VpcId: !Ref VPC
      Tags:
        - Key: Application
          Value: !Ref 'AWS::StackId'
  InboundHTTPNetworkAclEntry:
    Type: 'AWS::EC2::NetworkAclEntry'
    Properties:
      NetworkAclId: !Ref NetworkAcl
      RuleNumber: '100'
      Protocol: '6'
      RuleAction: allowAWSTemplateFormatVersion: 2010-09-09
Description: VPC Stack
Resources:
  VPC:
    Type: 'AWS::EC2::VPC'
    Properties:
      CidrBlock: 10.0.0.0/16
      EnableDnsHostnames: true
      Tags:
        - Key: Application
          Value: !Ref 'AWS::StackId'
  Subnet1:
    Type: 'AWS::EC2::Subnet'
    Properties:
      VpcId: !Ref VPC
      CidrBlock: 10.0.3.0/24
      AvailabilityZone: 'us-east-1b'
      Tags:
        - Key: Application
          Value: !Ref 'AWS::StackId'
  Subnet2:
    Type: 'AWS::EC2::Subnet'
    Properties:
      VpcId: !Ref VPC
      CidrBlock: 10.0.4.0/24
      AvailabilityZone: 'us-east-1e'
      Tags:
        - Key: Application
          Value: !Ref 'AWS::StackId'
  InternetGateway:
    Type: 'AWS::EC2::InternetGateway'
    Properties:
      Tags:
        - Key: Application
          Value: !Ref 'AWS::StackId'
  AttachGateway:
    Type: 'AWS::EC2::VPCGatewayAttachment'
    Properties:
      VpcId: !Ref VPC
      InternetGatewayId: !Ref InternetGateway
  RouteTable:
    Type: 'AWS::EC2::RouteTable'
    Properties:
      VpcId: !Ref VPC
      Tags:
        - Key: Application
          Value: !Ref 'AWS::StackId'
  Route:
    Type: 'AWS::EC2::Route'
    DependsOn: AttachGateway
    Properties:
      RouteTableId: !Ref RouteTable
      DestinationCidrBlock: 0.0.0.0/0
      GatewayId: !Ref InternetGateway
  SubnetRouteTableAssociation1:
    Type: 'AWS::EC2::SubnetRouteTableAssociation'
    Properties:
      SubnetId: !Ref Subnet1
      RouteTableId: !Ref RouteTable
  SubnetRouteTableAssociation2:
    Type: 'AWS::EC2::SubnetRouteTableAssociation'
    Properties:
      SubnetId: !Ref Subnet2
      RouteTableId: !Ref RouteTable
  NetworkAcl:
    Type: 'AWS::EC2::NetworkAcl'
    Properties:
      VpcId: !Ref VPC
      Tags:
        - Key: Application
          Value: !Ref 'AWS::StackId'
  InboundHTTPNetworkAclEntry:
    Type: 'AWS::EC2::NetworkAclEntry'
    Properties:
      NetworkAclId: !Ref NetworkAcl
      RuleNumber: '100'
      Protocol: '6'
      RuleAction: allow
      Egress: 'false'
      CidrBlock: 0.0.0.0/0
      PortRange:
        From: '80'
        To: '80'
  InboundSSHNetworkAclEntry:
    Type: 'AWS::EC2::NetworkAclEntry'
    Properties:
      NetworkAclId: !Ref NetworkAcl
      RuleNumber: '101'
      Protocol: '6'
      RuleAction: allow
      Egress: 'false'
      CidrBlock: 0.0.0.0/0
      PortRange:
        From: '22'
        To: '22'
  InboundResponsePortsNetworkAclEntry:
    Type: 'AWS::EC2::NetworkAclEntry'
    Properties:
      NetworkAclId: !Ref NetworkAcl
      RuleNumber: '102'
      Protocol: '6'
      RuleAction: allow
      Egress: 'false'
      CidrBlock: 0.0.0.0/0
      PortRange:
        From: '1024'
        To: '65535'
  OutBoundNetworkAclEntry:
    Type: 'AWS::EC2::NetworkAclEntry'
    Properties:
      NetworkAclId: !Ref NetworkAcl
      RuleNumber: '103'
      Protocol: '6'
      RuleAction: allow
      Egress: 'true'
      CidrBlock: 0.0.0.0/0
      PortRange:
        From: '0'
        To: '65535'
  SubnetNetworkAclAssociation1:
    Type: 'AWS::EC2::SubnetNetworkAclAssociation'
    Properties:
      SubnetId: !Ref Subnet1
      NetworkAclId: !Ref NetworkAcl
  SubnetNetworkAclAssociation2:
    Type: 'AWS::EC2::SubnetNetworkAclAssociation'
    Properties:
      SubnetId: !Ref Subnet2
      NetworkAclId: !Ref NetworkAcl
  LambdaSecurityGroup:
      Type: AWS::EC2::SecurityGroup
      Properties:
          VpcId: !Ref VPC
          GroupDescription: Access to Lambda functions
          SecurityGroupIngress:
            - CidrIp: 0.0.0.0/0
              IpProtocol: -1
         SecurityGroupEgress:
            - CidrIp: 0.0.0.0/0
              IpProtocol: -1
Outputs:
  VpcId:
    Description: VPC ID
    Value: !Ref VPC
    Export:
      Name: !Sub "Portal-VpcId"
  Subnet1:
    Description: Subnet ID 1
    Value: !Ref Subnet1
    Export:
      Name: !Sub "Portal-SubnetID1"
  Subnet2:
    Description: Subnet ID 2
    Value: !Ref Subnet2
    Export:
      Name: !Sub "Portal-SubnetID2"
  LambdaSecurityGroup:
    Description: Access to Lambda functions
    Value: !Ref LambdaSecurityGroup
    Export:
      Name: !Sub "LambdaSecurityGroup"
      Egress: 'false'
      CidrBlock: 0.0.0.0/0
      PortRange:
        From: '80'
        To: '80'
  InboundResponsePortsNetworkAclEntry:
    Type: 'AWS::EC2::NetworkAclEntry'
    Properties:
      NetworkAclId: !Ref NetworkAcl
      RuleNumber: '102'
      Protocol: '6'
      RuleAction: allow
      Egress: 'false'
      CidrBlock: 0.0.0.0/0
      PortRange:
        From: '1024'
        To: '65535'
  OutBoundNetworkAclEntry:
    Type: 'AWS::EC2::NetworkAclEntry'
    Properties:
      NetworkAclId: !Ref NetworkAcl
      RuleNumber: '103'
      Protocol: '6'
      RuleAction: allow
      Egress: 'true'
      CidrBlock: 0.0.0.0/0
      PortRange:
        From: '0'
        To: '65535'
  SubnetNetworkAclAssociation1:
    Type: 'AWS::EC2::SubnetNetworkAclAssociation'
    Properties:
      SubnetId: !Ref Subnet1
      NetworkAclId: !Ref NetworkAcl
  SubnetNetworkAclAssociation2:
    Type: 'AWS::EC2::SubnetNetworkAclAssociation'
    Properties:
      SubnetId: !Ref Subnet2
      NetworkAclId: !Ref NetworkAcl
  LambdaSecurityGroup:
      Type: AWS::EC2::SecurityGroup
      Properties:
          VpcId: !Ref VPC
          GroupDescription: Access to Lambda functions
          SecurityGroupIngress:
            - CidrIp: 0.0.0.0/0
              IpProtocol: -1
          SecurityGroupEgress:
            - CidrIp: 0.0.0.0/0
              IpProtocol: -1
Outputs:
  VpcId:
    Description: VPC ID
    Value: !Ref VPC
    Export:
      Name: !Sub "Portal-VpcId"
  Subnet1:
    Description: Subnet ID 1
    Value: !Ref Subnet1
    Export:
      Name: !Sub "Portal-SubnetID1"
  Subnet2:
    Description: Subnet ID 2
    Value: !Ref Subnet2
    Export:
      Name: !Sub "Portal-SubnetID2"
  LambdaSecurityGroup:
    Description: Access to Lambda functions
    Value: !Ref LambdaSecurityGroup
    Export:
      Name: !Sub "LambdaSecurityGroup"
</code>```

CF Template 2:

```<code>Lambda:
    Type: "AWS::Lambda::Function"
    Properties:
      Handler: "index.handler"
      Environment:
        Variables:
          Environment: !Ref Environment
      Role: !GetAtt LambdaExecutionRole.Arn
      Runtime: "nodejs6.10"
      VpcConfig:
        SecurityGroupIds:
          - !ImportValue "LambdaSecurityGroup"
        SubnetIds:
          - !ImportValue "Portal-SubnetID1"
          - !ImportValue "Portal-SubnetID2"
      Code:
        S3Bucket: !Ref BaseS3Bucket
        S3Key:
          !Join
            - ''
            - - !Ref TemplatePath
              - '/'
              - !Ref Environment
              - '/Quick-Links/build-output.zip'
</code>```

答:
You need to route through a NAT instance if you want Lambda’s to communicate with the internet. </p>

<p>Add two more subnets and a NAT gateway to your existing VPC subnets. Then, set the route table in your new subnet to route the internet through the NAT. </p>

Body:
My Lambda function has access to other resources in the VPC, but once it attempts to make a request out to the Internet it will timeout. I have the following:

Two private subnets

A Route Table that routes 0.0.0.0/0 to the Internet Gateway.

A couple ACL Rules and a Lambda Security Group

Any help would be helpful. Here are my CF Templates:

AWSTemplateFormatVersion: 2010-09-09
Description: VPC Stack
Resources:
  VPC:
    Type: 'AWS::EC2::VPC'
    Properties:
      CidrBlock: 10.0.0.0/16
      EnableDnsHostnames: true
      Tags:
        - Key: Application
          Value: !Ref 'AWS::StackId'
  Subnet1:
    Type: 'AWS::EC2::Subnet'
    Properties:
      VpcId: !Ref VPC
      CidrBlock: 10.0.3.0/24
      AvailabilityZone: 'us-east-1b'
      Tags:
        - Key: Application
          Value: !Ref 'AWS::StackId'
  Subnet2:
    Type: 'AWS::EC2::Subnet'
    Properties:
      VpcId: !Ref VPC
      CidrBlock: 10.0.4.0/24
      AvailabilityZone: 'us-east-1e'
      Tags:
        - Key: Application
          Value: !Ref 'AWS::StackId'
  InternetGateway:
    Type: 'AWS::EC2::InternetGateway'
    Properties:
      Tags:
        - Key: Application
          Value: !Ref 'AWS::StackId'
  AttachGateway:
    Type: 'AWS::EC2::VPCGatewayAttachment'
    Properties:
      VpcId: !Ref VPC
      InternetGatewayId: !Ref InternetGateway
  RouteTable:
    Type: 'AWS::EC2::RouteTable'
    Properties:
      VpcId: !Ref VPC
      Tags:
        - Key: Application
          Value: !Ref 'AWS::StackId'
  Route:
    Type: 'AWS::EC2::Route'
    DependsOn: AttachGateway
    Properties:
      RouteTableId: !Ref RouteTable
      DestinationCidrBlock: 0.0.0.0/0
      GatewayId: !Ref InternetGateway
  SubnetRouteTableAssociation1:
    Type: 'AWS::EC2::SubnetRouteTableAssociation'
    Properties:
      SubnetId: !Ref Subnet1
      RouteTableId: !Ref RouteTable
  SubnetRouteTableAssociation2:
    Type: 'AWS::EC2::SubnetRouteTableAssociation'
    Properties:
      SubnetId: !Ref Subnet2
      RouteTableId: !Ref RouteTable
  NetworkAcl:
    Type: 'AWS::EC2::NetworkAcl'
    Properties:
      VpcId: !Ref VPC
      Tags:
        - Key: Application
          Value: !Ref 'AWS::StackId'
  InboundHTTPNetworkAclEntry:
    Type: 'AWS::EC2::NetworkAclEntry'
    Properties:
      NetworkAclId: !Ref NetworkAcl
      RuleNumber: '100'
      Protocol: '6'
      RuleAction: allowAWSTemplateFormatVersion: 2010-09-09
Description: VPC Stack
Resources:
  VPC:
    Type: 'AWS::EC2::VPC'
    Properties:
      CidrBlock: 10.0.0.0/16
      EnableDnsHostnames: true
      Tags:
        - Key: Application
          Value: !Ref 'AWS::StackId'
  Subnet1:
    Type: 'AWS::EC2::Subnet'
    Properties:
      VpcId: !Ref VPC
      CidrBlock: 10.0.3.0/24
      AvailabilityZone: 'us-east-1b'
      Tags:
        - Key: Application
          Value: !Ref 'AWS::StackId'
  Subnet2:
    Type: 'AWS::EC2::Subnet'
    Properties:
      VpcId: !Ref VPC
      CidrBlock: 10.0.4.0/24
      AvailabilityZone: 'us-east-1e'
      Tags:
        - Key: Application
          Value: !Ref 'AWS::StackId'
  InternetGateway:
    Type: 'AWS::EC2::InternetGateway'
    Properties:
      Tags:
        - Key: Application
          Value: !Ref 'AWS::StackId'
  AttachGateway:
    Type: 'AWS::EC2::VPCGatewayAttachment'
    Properties:
      VpcId: !Ref VPC
      InternetGatewayId: !Ref InternetGateway
  RouteTable:
    Type: 'AWS::EC2::RouteTable'
    Properties:
      VpcId: !Ref VPC
      Tags:
        - Key: Application
          Value: !Ref 'AWS::StackId'
  Route:
    Type: 'AWS::EC2::Route'
    DependsOn: AttachGateway
    Properties:
      RouteTableId: !Ref RouteTable
      DestinationCidrBlock: 0.0.0.0/0
      GatewayId: !Ref InternetGateway
  SubnetRouteTableAssociation1:
    Type: 'AWS::EC2::SubnetRouteTableAssociation'
    Properties:
      SubnetId: !Ref Subnet1
      RouteTableId: !Ref RouteTable
  SubnetRouteTableAssociation2:
    Type: 'AWS::EC2::SubnetRouteTableAssociation'
    Properties:
      SubnetId: !Ref Subnet2
      RouteTableId: !Ref RouteTable
  NetworkAcl:
    Type: 'AWS::EC2::NetworkAcl'
    Properties:
      VpcId: !Ref VPC
      Tags:
        - Key: Application
          Value: !Ref 'AWS::StackId'
  InboundHTTPNetworkAclEntry:
    Type: 'AWS::EC2::NetworkAclEntry'
    Properties:
      NetworkAclId: !Ref NetworkAcl
      RuleNumber: '100'
      Protocol: '6'
      RuleAction: allow
      Egress: 'false'
      CidrBlock: 0.0.0.0/0
      PortRange:
        From: '80'
        To: '80'
  InboundSSHNetworkAclEntry:
    Type: 'AWS::EC2::NetworkAclEntry'
    Properties:
      NetworkAclId: !Ref NetworkAcl
      RuleNumber: '101'
      Protocol: '6'
      RuleAction: allow
      Egress: 'false'
      CidrBlock: 0.0.0.0/0
      PortRange:
        From: '22'
        To: '22'
  InboundResponsePortsNetworkAclEntry:
    Type: 'AWS::EC2::NetworkAclEntry'
    Properties:
      NetworkAclId: !Ref NetworkAcl
      RuleNumber: '102'
      Protocol: '6'
      RuleAction: allow
      Egress: 'false'
      CidrBlock: 0.0.0.0/0
      PortRange:
        From: '1024'
        To: '65535'
  OutBoundNetworkAclEntry:
    Type: 'AWS::EC2::NetworkAclEntry'
    Properties:
      NetworkAclId: !Ref NetworkAcl
      RuleNumber: '103'
      Protocol: '6'
      RuleAction: allow
      Egress: 'true'
      CidrBlock: 0.0.0.0/0
      PortRange:
        From: '0'
        To: '65535'
  SubnetNetworkAclAssociation1:
    Type: 'AWS::EC2::SubnetNetworkAclAssociation'
    Properties:
      SubnetId: !Ref Subnet1
      NetworkAclId: !Ref NetworkAcl
  SubnetNetworkAclAssociation2:
    Type: 'AWS::EC2::SubnetNetworkAclAssociation'
    Properties:
      SubnetId: !Ref Subnet2
      NetworkAclId: !Ref NetworkAcl
  LambdaSecurityGroup:
      Type: AWS::EC2::SecurityGroup
      Properties:
          VpcId: !Ref VPC
          GroupDescription: Access to Lambda functions
          SecurityGroupIngress:
            - CidrIp: 0.0.0.0/0
              IpProtocol: -1
         SecurityGroupEgress:
            - CidrIp: 0.0.0.0/0
              IpProtocol: -1
Outputs:
  VpcId:
    Description: VPC ID
    Value: !Ref VPC
    Export:
      Name: !Sub "Portal-VpcId"
  Subnet1:
    Description: Subnet ID 1
    Value: !Ref Subnet1
    Export:
      Name: !Sub "Portal-SubnetID1"
  Subnet2:
    Description: Subnet ID 2
    Value: !Ref Subnet2
    Export:
      Name: !Sub "Portal-SubnetID2"
  LambdaSecurityGroup:
    Description: Access to Lambda functions
    Value: !Ref LambdaSecurityGroup
    Export:
      Name: !Sub "LambdaSecurityGroup"
      Egress: 'false'
      CidrBlock: 0.0.0.0/0
      PortRange:
        From: '80'
        To: '80'
  InboundResponsePortsNetworkAclEntry:
    Type: 'AWS::EC2::NetworkAclEntry'
    Properties:
      NetworkAclId: !Ref NetworkAcl
      RuleNumber: '102'
      Protocol: '6'
      RuleAction: allow
      Egress: 'false'
      CidrBlock: 0.0.0.0/0
      PortRange:
        From: '1024'
        To: '65535'
  OutBoundNetworkAclEntry:
    Type: 'AWS::EC2::NetworkAclEntry'
    Properties:
      NetworkAclId: !Ref NetworkAcl
      RuleNumber: '103'
      Protocol: '6'
      RuleAction: allow
      Egress: 'true'
      CidrBlock: 0.0.0.0/0
      PortRange:
        From: '0'
        To: '65535'
  SubnetNetworkAclAssociation1:
    Type: 'AWS::EC2::SubnetNetworkAclAssociation'
    Properties:
      SubnetId: !Ref Subnet1
      NetworkAclId: !Ref NetworkAcl
  SubnetNetworkAclAssociation2:
    Type: 'AWS::EC2::SubnetNetworkAclAssociation'
    Properties:
      SubnetId: !Ref Subnet2
      NetworkAclId: !Ref NetworkAcl
  LambdaSecurityGroup:
      Type: AWS::EC2::SecurityGroup
      Properties:
          VpcId: !Ref VPC
          GroupDescription: Access to Lambda functions
          SecurityGroupIngress:
            - CidrIp: 0.0.0.0/0
              IpProtocol: -1
          SecurityGroupEgress:
            - CidrIp: 0.0.0.0/0
              IpProtocol: -1
Outputs:
  VpcId:
    Description: VPC ID
    Value: !Ref VPC
    Export:
      Name: !Sub "Portal-VpcId"
  Subnet1:
    Description: Subnet ID 1
    Value: !Ref Subnet1
    Export:
      Name: !Sub "Portal-SubnetID1"
  Subnet2:
    Description: Subnet ID 2
    Value: !Ref Subnet2
    Export:
      Name: !Sub "Portal-SubnetID2"
  LambdaSecurityGroup:
    Description: Access to Lambda functions
    Value: !Ref LambdaSecurityGroup
    Export:
      Name: !Sub "LambdaSecurityGroup"

CF Template 2:

Lambda:
    Type: "AWS::Lambda::Function"
    Properties:
      Handler: "index.handler"
      Environment:
        Variables:
          Environment: !Ref Environment
      Role: !GetAtt LambdaExecutionRole.Arn
      Runtime: "nodejs6.10"
      VpcConfig:
        SecurityGroupIds:
          - !ImportValue "LambdaSecurityGroup"
        SubnetIds:
          - !ImportValue "Portal-SubnetID1"
          - !ImportValue "Portal-SubnetID2"
      Code:
        S3Bucket: !Ref BaseS3Bucket
        S3Key:
          !Join
            - ''
            - - !Ref TemplatePath
              - '/'
              - !Ref Environment
              - '/Quick-Links/build-output.zip'

Body:
You need to route through a NAT instance if you want Lambda’s to communicate with the internet.

Add two more subnets and a NAT gateway to your existing VPC subnets. Then, set the route table in your new subnet to route the internet through the NAT.


问:
Postgres incorrect update on join
I am trying to run some update queries on Postgres where tables are joined on common field. This is run with SQL Server and the update count is 1 which is expected whereas postgres the update count is 3. It seems that postgres does not perform implicit join when the destination table is the same name as the source table involved in the join. The script could be more descript than what is being said and here it is:

```<code>drop table test;
drop table test2;
create table test(col1 int, col2 varchar(10));
insert into test values(1, 'aaa');
insert into test values(2, 'bbb');
insert into test values(3, 'ccc');
create table test2(col1 int);
insert into test2 values(2);
select * from test;
select * from test2;

// Select join = rowcount 1
select count(*) from test t2, test2 t3
where t2.col1 = t3.col1;

// SQL Server update = 1; postgres =3
update test set col2 = 'changed'
from test t2, test2 t3
where t2.col1 = t3.col1;
</code>```

The above query can be simplified with:

```<code>update test set col2 = 'changed'
from test2 where test.col1 = test2.col1;
</code>```

but that is not my intention as the join clause might involve some more join statements.
The desired intention was to run a query like this:

```<code>UPDATE IDMAP_CHILD_JOBID SET RESTORESUCCESS = IDMAP_TABLE_JOBID.RESTORESUCCESS, RESTOREERRMSG = IDMAP_TABLE_JOBID.RESTOREERRMSG
FROM CHILD, IDMAP_TABLE_JOBID
WHERE CHILD.ID = IDMAP_CHILD_JOBID.OLDID AND CHILD.FK1 = IDMAP_TABLE_JOBID.OLDID
AND IDMAP_TABLE_JOBID.RESTORESUCCESS = $FALSE
</code>```

Postgres complains with table specified more than once if IDMAP_CHILD_JOBID is the same as IDMAP_TABLE_JOBID. How can this be rewritten?
My application is supposed to generate an update statement where this is unified query is supposed to be run whereas the behaviour is different. It is obvious that join is performed on select while it is not under update.

答:
For this SQL query:

```<code>update test
    set col2 = 'changed'
    from test t2, test2 t3
    where t2.col1 = t3.col1;
</code>```

The equivalent Postgres syntax is:

```<code>update test
    set col2 = 'changed'
    from test2 t3
    where test.col1 = t3.col1;
</code>```

The update/join syntax is different in the two databases (although I think the above will also work in SQL Server).

Title: Postgres incorrect update on join

Body:
I am trying to run some update queries on Postgres where tables are joined on common field. This is run with SQL Server and the update count is 1 which is expected whereas postgres the update count is 3. It seems that postgres does not perform implicit join when the destination table is the same name as the source table involved in the join. The script could be more descript than what is being said and here it is:

drop table test;
drop table test2;
create table test(col1 int, col2 varchar(10));
insert into test values(1, 'aaa');
insert into test values(2, 'bbb');
insert into test values(3, 'ccc');
create table test2(col1 int);
insert into test2 values(2);
select * from test;
select * from test2;

// Select join = rowcount 1
select count(*) from test t2, test2 t3
where t2.col1 = t3.col1;

// SQL Server update = 1; postgres =3
update test set col2 = 'changed'
from test t2, test2 t3
where t2.col1 = t3.col1;

The above query can be simplified with:

update test set col2 = 'changed'
from test2 where test.col1 = test2.col1;

but that is not my intention as the join clause might involve some more join statements.
The desired intention was to run a query like this:

UPDATE IDMAP_CHILD_JOBID SET RESTORESUCCESS = IDMAP_TABLE_JOBID.RESTORESUCCESS, RESTOREERRMSG = IDMAP_TABLE_JOBID.RESTOREERRMSG
FROM CHILD, IDMAP_TABLE_JOBID
WHERE CHILD.ID = IDMAP_CHILD_JOBID.OLDID AND CHILD.FK1 = IDMAP_TABLE_JOBID.OLDID
AND IDMAP_TABLE_JOBID.RESTORESUCCESS = $FALSE

Postgres complains with table specified more than once if IDMAP_CHILD_JOBID is the same as IDMAP_TABLE_JOBID. How can this be rewritten?
My application is supposed to generate an update statement where this is unified query is supposed to be run whereas the behaviour is different. It is obvious that join is performed on select while it is not under update.

Body:
For this SQL query:

update test
    set col2 = 'changed'
    from test t2, test2 t3
    where t2.col1 = t3.col1;

The equivalent Postgres syntax is:

update test
    set col2 = 'changed'
    from test2 t3
    where test.col1 = t3.col1;

The update/join syntax is different in the two databases (although I think the above will also work in SQL Server).


问:
Equivalent to AssemblyInfo in dotnet core/csproj
Since dotnet core moved back to the .csproj format, there is a new autogenerated MyProject.AssemblyInfo.cs which contains, among others:

[assembly: AssemblyCompany("MyProject")]
[assembly: AssemblyVersion("1.0.0.0")]
```

Note that this is automatically regenerated every build.
Previously, the file was found in the /obj/ directory, now it appears to be only in memory as the file can't be found on disk and clicking the error message does not open any file.

This is the error message:

Since they are defined there, I can't define them myself in the classical AssemblyInfo.cs.

Where/how can I define the Company and Version of a project?

答:
I want to extend this topic/answers with the following. As someone mentioned, this auto-generated AssemblyInfo can be an obstacle for the external tools. In my case, using FinalBuilder, I had an issue that AssemblyInfo wasn't getting updated by build action. Apparently, FinalBuilder relies on ~proj file to find location of the AssemblyInfo. I thought, it was looking anywhere under project folder. No. So, changing this

<PropertyGroup>
   <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup>
```

<p>did only half the job, it allowed custom assembly info if built by VS IDE/MS Build. But I needed <em>FinalBuilder</em> do it too without manual manipulations to assembly info file. I needed to satisfy all programs, MSBuild/VS and FinalBuilder.</p>

<p>I solved this by adding an entry to the existing <code>ItemGroup</code></p>

<pre class="lang-xml prettyprint-override"><code><ItemGroup>
   <Compile Remove="Common\**" />
   <Content Remove="Common\**" />
   <EmbeddedResource Remove="Common\**" />
   <None Remove="Common\**" />
   <!-- new added item -->
   <None Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
</code>```

Now, having this item, FinalBuilder finds location of AssemblyInfo and modifies the file. While action None allows MSBuild/DevEnv ignore this entry and no longer report an error based on Compile action that usually comes with Assembly Info entry in proj files.

C:\Program Files\dotnet\sdk\2.0.2\Sdks\Microsoft.NET.Sdk\build\Microsoft.NET.Sdk.DefaultItems.targets(263,5):
  error : Duplicate 'Compile' items were included. The .NET SDK includes 'Compile' items from your project directory by default.
  You can either remove these items from your project file, or set the 'EnableDefaultCompileItems' property to 'false' if you want to explicitly include them in your project file.
  For more information, see https://aka.ms/sdkimplicititems. The duplicate items were: 'AssemblyInfo.cs'

Body:
Since dotnet core moved back to the .csproj format, there is a new autogenerated MyProject.AssemblyInfo.cs which contains, among others:

[assembly: AssemblyCompany("MyProject")]
[assembly: AssemblyVersion("1.0.0.0")]

Note that this is automatically regenerated every build.
Previously, the file was found in the /obj/ directory, now it appears to be only in memory as the file can't be found on disk and clicking the error message does not open any file.

This is the error message:

Since they are defined there, I can't define them myself in the classical AssemblyInfo.cs.

Where/how can I define the Company and Version of a project?

Body:
I want to extend this topic/answers with the following. As someone mentioned, this auto-generated AssemblyInfo can be an obstacle for the external tools. In my case, using FinalBuilder, I had an issue that AssemblyInfo wasn't getting updated by build action. Apparently, FinalBuilder relies on ~proj file to find location of the AssemblyInfo. I thought, it was looking anywhere under project folder. No. So, changing this

<PropertyGroup>
   <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup>

did only half the job, it allowed custom assembly info if built by VS IDE/MS Build. But I needed FinalBuilder do it too without manual manipulations to assembly info file. I needed to satisfy all programs, MSBuild/VS and FinalBuilder.

I solved this by adding an entry to the existing ItemGroup

<ItemGroup>
   <Compile Remove="Common\**" />
   <Content Remove="Common\**" />
   <EmbeddedResource Remove="Common\**" />
   <None Remove="Common\**" />
   <!-- new added item -->
   <None Include="Properties\AssemblyInfo.cs" />
</ItemGroup>

Now, having this item, FinalBuilder finds location of AssemblyInfo and modifies the file. While action None allows MSBuild/DevEnv ignore this entry and no longer report an error based on Compile action that usually comes with Assembly Info entry in proj files.

C:\Program Files\dotnet\sdk\2.0.2\Sdks\Microsoft.NET.Sdk\build\Microsoft.NET.Sdk.DefaultItems.targets(263,5):
  error : Duplicate 'Compile' items were included. The .NET SDK includes 'Compile' items from your project directory by default.
  You can either remove these items from your project file, or set the 'EnableDefaultCompileItems' property to 'false' if you want to explicitly include them in your project file.
  For more information, see https://aka.ms/sdkimplicititems. The duplicate items were: 'AssemblyInfo.cs'


问:
Running javascript code in a console vs as a bookmarkl gives different results
I was very happy to see that I was able to solve my previous problem (with some much needed help). But soon after I had ran the new code:

javascript:var tt=document.createElement('div');
tt.setAttribute('id', 'CMenu');
var g=document.getElementById('adCost');
var RAW='<button id ="save1Button" onclick=\"save1()\">SAVE SLOT 1</button>' +
'<button id ="load1Button" onclick="load1()">LOAD SLOT 1</button>' +
'<button id ="save2Button" onclick="save2()">SAVE SLOT 2</button>' +
'<button id ="load2Button" onclick="load2()">LOAD SLOT 2</button>' +
'<button id ="resetButton" onclick="reset()">RESET ALL PROGRESS</button>' +
'<button id ="freeClipsButton" onclick="cheatClips()">Free Clips</button>' +
'<button id ="freeMoneyButton" onclick="cheatMoney()">Free Money</button>' +
'<button id ="freeTrustButton" onclick="cheatTrust()">Free Trust</button>' +
'<button id ="freeOpsButton" onclick="cheatOps()">Free Ops</button>' +
'<button id ="freeCreatButton" onclick="cheatCreat()">Free Creativity</button>' +
'<button id ="freeYomiButton" onclick="cheatYomi()">Free Yomi</button>' +
'<button id ="resetPrestige" onclick="resetPrestige()">Reset Prestige</button>' +
'<button id ="destroyAllHumansButton" onclick="cheatHypno()">Destroy all Humans</button>' +
'<button id ="freePrestigeU" onclick="cheatPrestigeU()">Free Prestige U</button>' +
'<button id ="freePrestigeS" onclick="cheatPrestigeS()">Free Prestige S</button>' +
'<button id ="debugBattleNumbers" onclick="setB()">Set Battle Number 1 to 7</button>' +
'<button id ="availMatterZero" onclick="zeroMatter()">Set Avail Matter to 0</button>';
g.appendChild(tt);
document.getElementById('CMenu').innerHTML= RAW```

as a bookmark instead of in the console (without javascript: of course), it gave different results. The console ran it as expected when tested line-by-line, and all at once. The bookmark however replaced all the content on the page with buttons!

答:
Add false to the end of the bookmarklet. Apparently the browser treats clicking on the bookmarklet as a navigation, so when it returns it only shows the new page. But if an inline Javascript returns false, that disables the default action of clicking on the link.

SAVE SLOT 1</button>' +
'<button id ="load1Button" onclick="load1()">LOAD SLOT 1</button>' +
'<button id ="save2Button" onclick="save2()">SAVE SLOT 2</button>' +
'<button id ="load2Button" onclick="load2()">LOAD SLOT 2</button>' +
'<button id ="resetButton" onclick="reset()">RESET ALL PROGRESS</button>' +
'<button id ="freeClipsButton" onclick="cheatClips()">Free Clips</button>' +
'<button id ="freeMoneyButton" onclick="cheatMoney()">Free Money</button>' +
'<button id ="freeTrustButton" onclick="cheatTrust()">Free Trust</button>' +
'<button id ="freeOpsButton" onclick="cheatOps()">Free Ops</button>' +
'<button id ="freeCreatButton" onclick="cheatCreat()">Free Creativity</button>' +
'<button id ="freeYomiButton" onclick="cheatYomi()">Free Yomi</button>' +
'<button id ="resetPrestige" onclick="resetPrestige()">Reset Prestige</button>' +
'<button id ="destroyAllHumansButton" onclick="cheatHypno()">Destroy all Humans</button>' +
'<button id ="freePrestigeU" onclick="cheatPrestigeU()">Free Prestige U</button>' +
'<button id ="freePrestigeS" onclick="cheatPrestigeS()">Free Prestige S</button>' +
'<button id ="debugBattleNumbers" onclick="setB()">Set Battle Number 1 to 7</button>' +
'<button id ="availMatterZero" onclick="zeroMatter()">Set Avail Matter to 0</button>';
g.appendChild(tt);
document.getElementById('CMenu').innerHTML= RAW;
false;">Click

This is some text at the beginning.

This is text at the end
```

Body:
I was very happy to see that I was able to solve my previous problem (with some much needed help). But soon after I had ran the new code:

javascript:var tt=document.createElement('div');
tt.setAttribute('id', 'CMenu');
var g=document.getElementById('adCost');
var RAW='<button id ="save1Button" onclick=\"save1()\">SAVE SLOT 1</button>' +
'<button id ="load1Button" onclick="load1()">LOAD SLOT 1</button>' +
'<button id ="save2Button" onclick="save2()">SAVE SLOT 2</button>' +
'<button id ="load2Button" onclick="load2()">LOAD SLOT 2</button>' +
'<button id ="resetButton" onclick="reset()">RESET ALL PROGRESS</button>' +
'<button id ="freeClipsButton" onclick="cheatClips()">Free Clips</button>' +
'<button id ="freeMoneyButton" onclick="cheatMoney()">Free Money</button>' +
'<button id ="freeTrustButton" onclick="cheatTrust()">Free Trust</button>' +
'<button id ="freeOpsButton" onclick="cheatOps()">Free Ops</button>' +
'<button id ="freeCreatButton" onclick="cheatCreat()">Free Creativity</button>' +
'<button id ="freeYomiButton" onclick="cheatYomi()">Free Yomi</button>' +
'<button id ="resetPrestige" onclick="resetPrestige()">Reset Prestige</button>' +
'<button id ="destroyAllHumansButton" onclick="cheatHypno()">Destroy all Humans</button>' +
'<button id ="freePrestigeU" onclick="cheatPrestigeU()">Free Prestige U</button>' +
'<button id ="freePrestigeS" onclick="cheatPrestigeS()">Free Prestige S</button>' +
'<button id ="debugBattleNumbers" onclick="setB()">Set Battle Number 1 to 7</button>' +
'<button id ="availMatterZero" onclick="zeroMatter()">Set Avail Matter to 0</button>';
g.appendChild(tt);
document.getElementById('CMenu').innerHTML= RAW

as a bookmark instead of in the console (without javascript: of course), it gave different results. The console ran it as expected when tested line-by-line, and all at once. The bookmark however replaced all the content on the page with buttons!

Body:
Add false to the end of the bookmarklet. Apparently the browser treats clicking on the bookmarklet as a navigation, so when it returns it only shows the new page. But if an inline Javascript returns false, that disables the default action of clicking on the link.

<a href="javascript:var tt=document.createElement('div');
tt.setAttribute('id', 'CMenu');
var g=document.getElementById('adCost');
var RAW='<button id =&quot;save1Button&quot; onclick=&quot;save1()&quot;>SAVE SLOT 1</button>' +
'<button id =&quot;load1Button&quot; onclick=&quot;load1()&quot;>LOAD SLOT 1</button>' +
'<button id =&quot;save2Button&quot; onclick=&quot;save2()&quot;>SAVE SLOT 2</button>' +
'<button id =&quot;load2Button&quot; onclick=&quot;load2()&quot;>LOAD SLOT 2</button>' +
'<button id =&quot;resetButton&quot; onclick=&quot;reset()&quot;>RESET ALL PROGRESS</button>' +
'<button id =&quot;freeClipsButton&quot; onclick=&quot;cheatClips()&quot;>Free Clips</button>' +
'<button id =&quot;freeMoneyButton&quot; onclick=&quot;cheatMoney()&quot;>Free Money</button>' +
'<button id =&quot;freeTrustButton&quot; onclick=&quot;cheatTrust()&quot;>Free Trust</button>' +
'<button id =&quot;freeOpsButton&quot; onclick=&quot;cheatOps()&quot;>Free Ops</button>' +
'<button id =&quot;freeCreatButton&quot; onclick=&quot;cheatCreat()&quot;>Free Creativity</button>' +
'<button id =&quot;freeYomiButton&quot; onclick=&quot;cheatYomi()&quot;>Free Yomi</button>' +
'<button id =&quot;resetPrestige&quot; onclick=&quot;resetPrestige()&quot;>Reset Prestige</button>' +
'<button id =&quot;destroyAllHumansButton&quot; onclick=&quot;cheatHypno()&quot;>Destroy all Humans</button>' +
'<button id =&quot;freePrestigeU&quot; onclick=&quot;cheatPrestigeU()&quot;>Free Prestige U</button>' +
'<button id =&quot;freePrestigeS&quot; onclick=&quot;cheatPrestigeS()&quot;>Free Prestige S</button>' +
'<button id =&quot;debugBattleNumbers&quot; onclick=&quot;setB()&quot;>Set Battle Number 1 to 7</button>' +
'<button id =&quot;availMatterZero&quot; onclick=&quot;zeroMatter()&quot;>Set Avail Matter to 0</button>';
g.appendChild(tt);
document.getElementById('CMenu').innerHTML= RAW;
false;">Click</a>
<div>This is some text at the beginning.</div>
<div id="adCost"></div>
<div>This is text at the end</div>


问:
Anti aliasing DrawLine on CE
I am drawing a line to a Graphics object in Windows CE using C#.NET 3.5.

The code I am using looks like this:

```<code>e.Graphics.DrawLine(new Pen(Color.FromArgb(11, 118, 200), 2), x1, y1, x2, y2);
</code>```

This works however looks terrible due to jaggies etc.  Is there anyway I can draw anti aliased lines?

From what I can tell the Graphics object doesn't support this natively but is there anyway to "cheat" this effect using some trickery?

答:
A fast trick if you're drawing on a solid color background, you can draw a line with a thicker pen and a color in between the background color and the line color prior to the actual line, for instance, when drawing on a black background:

```<code>e.Graphics.DrawLine(new Pen(Color.FromArgb(5, 59, 100), 3), x1, y1, x2, y2);
e.Graphics.DrawLine(new Pen(Color.FromArgb(11, 118, 200), 2), x1, y1, x2, y2);
</code>```

This adds a "glow" to the line (even on perfect horizontal / vertical lines though).

Title: Anti aliasing DrawLine on CE

Body:
I am drawing a line to a Graphics object in Windows CE using C#.NET 3.5.

The code I am using looks like this:

e.Graphics.DrawLine(new Pen(Color.FromArgb(11, 118, 200), 2), x1, y1, x2, y2);

This works however looks terrible due to jaggies etc.  Is there anyway I can draw anti aliased lines?

From what I can tell the Graphics object doesn't support this natively but is there anyway to "cheat" this effect using some trickery?

Body:
A fast trick if you're drawing on a solid color background, you can draw a line with a thicker pen and a color in between the background color and the line color prior to the actual line, for instance, when drawing on a black background:

e.Graphics.DrawLine(new Pen(Color.FromArgb(5, 59, 100), 3), x1, y1, x2, y2);
e.Graphics.DrawLine(new Pen(Color.FromArgb(11, 118, 200), 2), x1, y1, x2, y2);

This adds a "glow" to the line (even on perfect horizontal / vertical lines though).


问:
Changing table's cell background color using PHP while loop
I need to change the background color of cells with freezing temperature (32F, 0C) to #bff9ff but have some difficulties. I tried to print CSS class inside  but seems it just doesn't work properly inside the loop and being printed at the same time.

However, it's half a problem. How can I identify those cells with freezing temp and below not manually but using PHP?

```<code><html>
<head>
    <meta charset="UTF-8">
    <title>Unit 3 part 2</title>

        <style>
            table {
                font-family: arial, sans-serif;
                border-collapse: collapse;
                width: 100%;
            }

            tr:hover {
                background-color:#bff9ff;
                }

            td, th {
                border: 1px solid #dddddd;
                text-align: left;
                padding: 8px;``
            }
            .cell {
                background-color: #00bfff;
                }

        </style>

</head>
<body>

    <table border="1" cellpadding="3">

        <thead>
            <th>Fahrenheit</th>
            <th>Celsius</th>
        </thead>

        <?php
        $fahrenheit = 50;

        while ($fahrenheit >= -50) {

            $celsius = ($fahrenheit - 32) * 5 / 9;

            print "<tr><td>$fahrenheit</td><td>$celsius</td></tr>";

            $fahrenheit -= 5;
            $celsius -= 5;

        } ?>

    </table>

</body>
</html>
</code>```

答:
By adding an if statement to test the temperature, and then adding a class to the td tags, that should take care of it.</p>

```<code><html>
<head>
    <meta charset="UTF-8">
    <title>Unit 3 part 2</title>
    <style>
        table {
            font-family: arial, sans-serif;
            border-collapse: collapse;
            width: 100%;
        }
        tr:hover {
            background-color:#bff9ff;
            }
        td, th {
            border: 1px solid #dddddd;
            text-align: left;
            padding: 8px;``
        }
        .cell {
            background-color: #00bfff;
            }
        .cell.freezing {
            background-color: #bff9ff;
        }
    </style>
</head>
<body>
    <table border="1" cellpadding="3">
        <thead>
            <th>Fahrenheit</th>
            <th>Celsius</th>
        </thead>
        <?php
        $fahrenheit = 50;
        while ($fahrenheit >= -50) {
            $celsius = ($fahrenheit - 32) * 5 / 9;
            $class = '';
            if($fahrenheit <= 32) {
                $class = ' freezing';
            }
            print "<tr><td class='cell $class'>$fahrenheit</td><td class='cell $class'>$celsius</td></tr>";
            $fahrenheit -= 5;
            $celsius -= 5;
        } ?>
    </table>
</body>
</html>
</code>```

Body:
I need to change the background color of cells with freezing temperature (32F, 0C) to #bff9ff but have some difficulties. I tried to print CSS class inside  but seems it just doesn't work properly inside the loop and being printed at the same time.

However, it's half a problem. How can I identify those cells with freezing temp and below not manually but using PHP?

    <meta charset="UTF-8">
    <title>Unit 3 part 2</title>

            Fahrenheit
            Celsius

        <?php
        $fahrenheit = 50;

        while ($fahrenheit >= -50) {

            $celsius = ($fahrenheit - 32) * 5 / 9;

            print "
$fahrenheit	$celsius
";

            $fahrenheit -= 5;
            $celsius -= 5;

        } ?>

Body:
By adding an if statement to test the temperature, and then adding a class to the td tags, that should take care of it.

<html>
<head>
    <meta charset="UTF-8">
    <title>Unit 3 part 2</title>
    <style>
        table {
            font-family: arial, sans-serif;
            border-collapse: collapse;
            width: 100%;
        }
        tr:hover {
            background-color:#bff9ff;
            }
        td, th {
            border: 1px solid #dddddd;
            text-align: left;
            padding: 8px;``
        }
        .cell {
            background-color: #00bfff;
            }
        .cell.freezing {
            background-color: #bff9ff;
        }
    </style>
</head>
<body>
    <table border="1" cellpadding="3">
        <thead>
            <th>Fahrenheit</th>
            <th>Celsius</th>
        </thead>
        <?php
        $fahrenheit = 50;
        while ($fahrenheit >= -50) {
            $celsius = ($fahrenheit - 32) * 5 / 9;
            $class = '';
            if($fahrenheit <= 32) {
                $class = ' freezing';
            }
            print "<tr><td class='cell $class'>$fahrenheit</td><td class='cell $class'>$celsius</td></tr>";
            $fahrenheit -= 5;
            $celsius -= 5;
        } ?>
    </table>
</body>
</html>


问:
How do I mock a REST server with with multiple endpoints in the same test in Java?
I'm trying to test a Java method that makes a request to a remote REST server to retrieve some JSON data, extracts an ID from that JSON, then uses the ID to make another request to the same server at a different endpoint.

Using Mockito's MockRestServiceServer, I can successfully mock and test a server that expects a single request to one endpoint, but it seems that I cannot use it to create a server with a set of predefined endpoints with their own expectations and responses.

How do I mock a server with multiple endpoints for the purpose of testing a single function that makes multiple, distinct requests to the remote server?

答:
My answer assumes you are using SpringBoot but the idea can be applied generically.

Make your class depend on the RestOperations interface so that you can pass a stub when testing.

Class Under Test

```<code>public class Foo {
  private final RestOperations restOperations;

  public Foo(RestOperations restOperations) {
    this.restOperations = restOperations;
  }
}
</code>```

Test

```<code>  public void test() {
    Foo foo = new Foo(new MyStub());
  }
</code>```

Depend on abstractions, not concrete implementations.

Body:
My answer assumes you are using SpringBoot but the idea can be applied generically.

Make your class depend on the RestOperations interface so that you can pass a stub when testing.

Class Under Test

public class Foo {
  private final RestOperations restOperations;

  public Foo(RestOperations restOperations) {
    this.restOperations = restOperations;
  }
}

Test

  public void test() {
    Foo foo = new Foo(new MyStub());
  }

Depend on abstractions, not concrete implementations.


问:
SQL encoding problems (Â)
The website works and displayed correctly.
But in the database, there is a lot of symbols like 'Â', â€‹ and so.
Any new entry in SQL is created with such symbols - but displayed properly on the Website.

The database is in UTF encoding.
The majority of the files too. But there are some files in ANSI (Windows-1252). I changed files that I found, it didn't help, there are hundreds of files...

By default, the browser shows website at UTF encoding. If I manually change to Windows-1252 in the browser, the characters starting to appear.

If I exporting SQL DB as UTF - characters are present in the damp.
If I exporting SQL DB as Windows-1252 the characters are not there.

Why the website display content properly, but in the DB there is some problem?
How to solve this?

答:
You can use
mysqli_set_charset('utf8');

Object oriented style

bool mysqli::set_charset ( string $charset ) Procedural style

bool mysqli_set_charset ( mysqli $link , string $charset )

Sets the
  default character set to be used when sending data from and to the
  database server.

Title: SQL encoding problems (Â)


问:
Deployment package for a 64-bit windows service in VS2010
I'm trying to create a deployment package for a windows service targeting x64.

I've made the setup project itself target x64 but I need to add custom actions to actually register/unregister the service.

However, when I add custom actions and try to run the installer, I get a BadFormat exception which indicates that the executable for my service is corrupted.

I suspect I'm running into the issue mentioned here but am unable to prove it.

This windows service is being developed as part of a far larger application using TFS for automated builds and deployment, continuous integration, etc - So manually tweaking bits of a binary file using tools which require the use of a GUI is a definite no-no.

So... What I need to know is; Is it possible to automatically build a deployment package for a 64-bit windows service in VS2010? If so how?

答:
This will happen when either your service or one of the assemblies it uses was built with the Target Platform setting changed to x86.  In which case you have to use the right version of Installutil.exe to register the service.  There are two, in c:\windows\microsoft.net\framework and \framework64, respectively the 32-bit and the 64-bit version.  Odds are good that you need the former.  If you created a Setup project then you'd change the TargetPlatform property to x86.

Also check if you really need to have the target platform set, you only do if you have a dependency on unmanaged code like a COM server.  The C# setting is in Project + Properties, Compile tab.  The default for VS2010 is x86, just flip it to AnyCPU if you have no such dependency.


问:
Why does this output 10 for each loop? Isn't int a value type?
I was browsing through some C# examples and came upon this:

```<code>using System;
using System.Collections.Generic;

namespace ConsoleApp1
{
    class Program
    {
        delegate void Printer();

        static void Main()
        {
            List<Printer> printers = new List<Printer>();

            for (int i = 0; i < 10; i++)
            {
                printers.Add(delegate { var d = i; Console.WriteLine(d); });
            }

            foreach (var printer in printers)
            {
                printer();
            }
            Console.ReadLine();
        }
    }
}
</code>```

I expected this to output 0 through 9, since an int is a value type and d should be set to whatever i is at that time.

However, this outputs 10 ten times.

Why is this? Is the int not a reference instead inside the delegate?

Note: I am not trying to solve a problem here, just understand how this works, in a way that is re-applicable.

Edit: Example of my confusion

```<code>int i = 9;
int d = 8;
d = i;
i++;
Console.WriteLine(d);
</code>```

This would show that i is passed as a value, and not a reference. I expected the same inside the closure, but was surprised.

Thanks for the comments, I understand more now, the code in the delegate isn't executed till after and it uses i that exists outside of it in a generic class made by the compiler?

In javascript this same kind of code outputs 1-9, which is what I expected in C#. https://jsfiddle.net/L21xLaq0/2/.

答:
I think that most answers are good and comments are good but i would suggest looking into decompiled code transformed into C#:

private static void Main()
{
    List<Program.Printer> printers = new List<Program.Printer>();
    int i;
    int j;
    for (i = 0; i < 10; i = j + 1)
    {
        printers.Add(delegate
        {
            int d = i;
            Console.WriteLine(d);
        });
        j = i;
    }
    foreach (Program.Printer printer in printers)
    {
        printer();
    }
    Console.ReadLine();
}
```
<p>It's how dnSpy read my code from IL Instructions.  On the first glance there are 2 things that you must know about delegate that you added:</p>
<ol>
<li>When you add delegate there is no assignment inside Add because you do not execute code.</li>
<li>Your int is moved outside for loop. Because of that it is available for use for delegate.</li>
</ol>
<p>It's also worth looking at IL code of class that is auto generated to represent delegate. It will reveal completely what is being done under the hood:</p>
```.class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass1_0'
    extends [mscorlib]System.Object
{
    .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (
        01 00 00 00
    )
    // Fields
    // Token: 0x04000005 RID: 5
    .field public int32 i

    // Methods
    // Token: 0x06000007 RID: 7 RVA: 0x000020F4 File Offset: 0x000002F4
    .method public hidebysig specialname rtspecialname
        instance void .ctor () cil managed
    {
        // Header Size: 1 byte
        // Code Size: 8 (0x8) bytes
        .maxstack 8

          IL_0000: ldarg.0
          IL_0001: call      instance void [mscorlib]System.Object::.ctor()
          IL_0006: nop
          IL_0007: ret
    } // end of method '<>c__DisplayClass1_0'::.ctor

    // Token: 0x06000008 RID: 8 RVA: 0x00002100 File Offset: 0x00000300
    .method assembly hidebysig
        instance void 'b__0' () cil managed
    {
        // Header Size: 12 bytes
        // Code Size: 16 (0x10) bytes
        // LocalVarSig Token: 0x11000002 RID: 2
        .maxstack 1
        .locals init (
            [0] int32 d
        )

          IL_0000: nop
          IL_0001: ldarg.0
          IL_0002: ldfld     int32 ConsoleApp1.Program/'<>c__DisplayClass1_0'::i
          IL_0007: stloc.0
          IL_0008: ldloc.0
          IL_0009: call      void [mscorlib]System.Console::WriteLine(int32)
          IL_000E: nop
          IL_000F: ret
    } // end of method '<>c__DisplayClass1_0'::'b__0'

} // end of class <>c__DisplayClass1_0
```
<p>Code is very long but it is worth noting that this class has public int field inside.</p>
```.field public int32 i
```
<p>It's getting interesting at this point :P.</p>
<p>You can also see a constructor that does nothing. There is no assignment or whatever else when object is created. Nothing special excluding creating Object is done.</p>
<p>When you print your variable you are accessing public field inside your delegate which is i.</p>
```ldfld     int32 ConsoleApp1.Program/'<>c__DisplayClass1_0'::i
```
<p>Now you should scratch your head and do not know what is going on anymore because we did not assign i inside this private class. But this i field is public and it is being modified inside Program's main method.</p>
```.method private hidebysig static
    void Main () cil managed
{
    // Header Size: 12 bytes
    // Code Size: 136 (0x88) bytes
    // LocalVarSig Token: 0x11000001 RID: 1
    .maxstack 3
    .entrypoint
    .locals init (
        [0] class [mscorlib]System.Collections.Generic.List`1<class ConsoleApp1.Program/Printer> printers,
        [1] class ConsoleApp1.Program/'<>c__DisplayClass1_0' 'CS$<>8__locals0', //There is only one variable of your class that has method that is going to be invoked. You do not have 10 unique methods.
        [2] int32,
        [3] bool,
        [4] valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<class ConsoleApp1.Program/Printer>,
        [5] class ConsoleApp1.Program/Printer printer
    )

      IL_0007: newobj    instance void ConsoleApp1.Program/'<>c__DisplayClass1_0'::.ctor() //your class that is going to be used by delegate is created here
      IL_000C: stloc.1 //and stored in local variable at index 1
      /*(...)*/
      IL_000E: ldc.i4.0 //we are putting 0 on stack
      IL_000F: stfld     int32 ConsoleApp1.Program/'<>c__DisplayClass1_0'::i //and assign 0 to variable i which is inside this private class.
    // loop start (head: IL_003B)
          /*(...)*/
          IL_0019: ldftn     instance void ConsoleApp1.Program/'<>c__DisplayClass1_0'::'b__0'() //It push pointer to the main function of our private nested class on the stack.
          IL_001F: newobj    instance void ConsoleApp1.Program/Printer::.ctor(object, native int) //We create new delegate which will be pointing on our local DisplayClass_1_0
          IL_0024: callvirt  instance void class [mscorlib]System.Collections.Generic.List`1<class ConsoleApp1.Program/Printer>::Add(!0) //We are adding delegate
          /* (...) */
          IL_002C: ldfld     int32 ConsoleApp1.Program/'<>c__DisplayClass1_0'::i //loads i from our local private class into stack
          IL_0031: stloc.2 //and put it into local variable 2
          IL_0033: ldloc.2 //puts local variable at index 2 on the stack
          IL_0034: ldc.i4.1 // nputs 1 onto stack
          IL_0035: add //1 and local varaible 2 are being add and value is pushed on the evaluation stack
          IL_0036: stfld     int32 ConsoleApp1.Program/'<>c__DisplayClass1_0'::i //we are replacing i in our instance of our private class with value that is result of addition one line before.
          //This is very weird way of adding 1 to i... Very weird. Maybe there is a reason behind that
          /* (...) */
    // end loop

     /* (...) */
    .try
    {
          /* (...) */
        // loop start (head: IL_0067)
              /* (...) */
              IL_0056: call      instance !0 valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<class ConsoleApp1.Program/Printer>::get_Current() //gets element from list at current iterator position
              /* (...) */
              IL_0060: callvirt  instance void ConsoleApp1.Program/Printer::Invoke() //Invokes your delegate.
              /* (...) */
        // end loop

          IL_0070: leave.s   IL_0081
    } // end .try
    finally
    {
          /* (...) */
    } // end handler

      IL_0081: call      string [mscorlib]System.Console::ReadLine()
        /* (...) */
} // end of method Program::Main
```

Code is commented by me. But in short.

Your i is not an variable of Main method. It is public variable of a method that your delegate use.

Method that is being used by your delegate is inside private nested class in Main.

I do not know internals of C# compiler but this was pretty interesting to see. If you want to see it with your own eyes i recommend using dnSpy.

edit: @evk was faster :P.

Body:
I was browsing through some C# examples and came upon this:

using System;
using System.Collections.Generic;

namespace ConsoleApp1
{
    class Program
    {
        delegate void Printer();

        static void Main()
        {
            List<Printer> printers = new List<Printer>();

            for (int i = 0; i < 10; i++)
            {
                printers.Add(delegate { var d = i; Console.WriteLine(d); });
            }

            foreach (var printer in printers)
            {
                printer();
            }
            Console.ReadLine();
        }
    }
}

I expected this to output 0 through 9, since an int is a value type and d should be set to whatever i is at that time.

However, this outputs 10 ten times.

Why is this? Is the int not a reference instead inside the delegate?

Note: I am not trying to solve a problem here, just understand how this works, in a way that is re-applicable.

Edit: Example of my confusion

int i = 9;
int d = 8;
d = i;
i++;
Console.WriteLine(d);

This would show that i is passed as a value, and not a reference. I expected the same inside the closure, but was surprised.

Thanks for the comments, I understand more now, the code in the delegate isn't executed till after and it uses i that exists outside of it in a generic class made by the compiler?

In javascript this same kind of code outputs 1-9, which is what I expected in C#. https://jsfiddle.net/L21xLaq0/2/.

Body:
I think that most answers are good and comments are good but i would suggest looking into decompiled code transformed into C#:

private static void Main()
{
    List<Program.Printer> printers = new List<Program.Printer>();
    int i;
    int j;
    for (i = 0; i < 10; i = j + 1)
    {
        printers.Add(delegate
        {
            int d = i;
            Console.WriteLine(d);
        });
        j = i;
    }
    foreach (Program.Printer printer in printers)
    {
        printer();
    }
    Console.ReadLine();
}

It's how dnSpy read my code from IL Instructions.  On the first glance there are 2 things that you must know about delegate that you added:

When you add delegate there is no assignment inside Add because you do not execute code.

Your int is moved outside for loop. Because of that it is available for use for delegate.

It's also worth looking at IL code of class that is auto generated to represent delegate. It will reveal completely what is being done under the hood:

.class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass1_0'
    extends [mscorlib]System.Object
{
    .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (
        01 00 00 00
    )
    // Fields
    // Token: 0x04000005 RID: 5
    .field public int32 i

    // Methods
    // Token: 0x06000007 RID: 7 RVA: 0x000020F4 File Offset: 0x000002F4
    .method public hidebysig specialname rtspecialname
        instance void .ctor () cil managed
    {
        // Header Size: 1 byte
        // Code Size: 8 (0x8) bytes
        .maxstack 8

          IL_0000: ldarg.0
          IL_0001: call      instance void [mscorlib]System.Object::.ctor()
          IL_0006: nop
          IL_0007: ret
    } // end of method '<>c__DisplayClass1_0'::.ctor

    // Token: 0x06000008 RID: 8 RVA: 0x00002100 File Offset: 0x00000300
    .method assembly hidebysig
        instance void '<Main>b__0' () cil managed
    {
        // Header Size: 12 bytes
        // Code Size: 16 (0x10) bytes
        // LocalVarSig Token: 0x11000002 RID: 2
        .maxstack 1
        .locals init (
            [0] int32 d
        )

          IL_0000: nop
          IL_0001: ldarg.0
          IL_0002: ldfld     int32 ConsoleApp1.Program/'<>c__DisplayClass1_0'::i
          IL_0007: stloc.0
          IL_0008: ldloc.0
          IL_0009: call      void [mscorlib]System.Console::WriteLine(int32)
          IL_000E: nop
          IL_000F: ret
    } // end of method '<>c__DisplayClass1_0'::'<Main>b__0'

} // end of class <>c__DisplayClass1_0

Code is very long but it is worth noting that this class has public int field inside.

.field public int32 i

It's getting interesting at this point :P.

You can also see a constructor that does nothing. There is no assignment or whatever else when object is created. Nothing special excluding creating Object is done.

When you print your variable you are accessing public field inside your delegate which is i.

ldfld     int32 ConsoleApp1.Program/'<>c__DisplayClass1_0'::i

Now you should scratch your head and do not know what is going on anymore because we did not assign i inside this private class. But this i field is public and it is being modified inside Program's main method.

.method private hidebysig static
    void Main () cil managed
{
    // Header Size: 12 bytes
    // Code Size: 136 (0x88) bytes
    // LocalVarSig Token: 0x11000001 RID: 1
    .maxstack 3
    .entrypoint
    .locals init (
        [0] class [mscorlib]System.Collections.Generic.List`1<class ConsoleApp1.Program/Printer> printers,
        [1] class ConsoleApp1.Program/'<>c__DisplayClass1_0' 'CS$<>8__locals0', //There is only one variable of your class that has method that is going to be invoked. You do not have 10 unique methods.
        [2] int32,
        [3] bool,
        [4] valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<class ConsoleApp1.Program/Printer>,
        [5] class ConsoleApp1.Program/Printer printer
    )

      IL_0007: newobj    instance void ConsoleApp1.Program/'<>c__DisplayClass1_0'::.ctor() //your class that is going to be used by delegate is created here
      IL_000C: stloc.1 //and stored in local variable at index 1
      /*(...)*/
      IL_000E: ldc.i4.0 //we are putting 0 on stack
      IL_000F: stfld     int32 ConsoleApp1.Program/'<>c__DisplayClass1_0'::i //and assign 0 to variable i which is inside this private class.
    // loop start (head: IL_003B)
          /*(...)*/
          IL_0019: ldftn     instance void ConsoleApp1.Program/'<>c__DisplayClass1_0'::'<Main>b__0'() //It push pointer to the main function of our private nested class on the stack.
          IL_001F: newobj    instance void ConsoleApp1.Program/Printer::.ctor(object, native int) //We create new delegate which will be pointing on our local DisplayClass_1_0
          IL_0024: callvirt  instance void class [mscorlib]System.Collections.Generic.List`1<class ConsoleApp1.Program/Printer>::Add(!0) //We are adding delegate
          /* (...) */
          IL_002C: ldfld     int32 ConsoleApp1.Program/'<>c__DisplayClass1_0'::i //loads i from our local private class into stack
          IL_0031: stloc.2 //and put it into local variable 2
          IL_0033: ldloc.2 //puts local variable at index 2 on the stack
          IL_0034: ldc.i4.1 // nputs 1 onto stack
          IL_0035: add //1 and local varaible 2 are being add and value is pushed on the evaluation stack
          IL_0036: stfld     int32 ConsoleApp1.Program/'<>c__DisplayClass1_0'::i //we are replacing i in our instance of our private class with value that is result of addition one line before.
          //This is very weird way of adding 1 to i... Very weird. Maybe there is a reason behind that
          /* (...) */
    // end loop

     /* (...) */
    .try
    {
          /* (...) */
        // loop start (head: IL_0067)
              /* (...) */
              IL_0056: call      instance !0 valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<class ConsoleApp1.Program/Printer>::get_Current() //gets element from list at current iterator position
              /* (...) */
              IL_0060: callvirt  instance void ConsoleApp1.Program/Printer::Invoke() //Invokes your delegate.
              /* (...) */
        // end loop

          IL_0070: leave.s   IL_0081
    } // end .try
    finally
    {
          /* (...) */
    } // end handler

      IL_0081: call      string [mscorlib]System.Console::ReadLine()
        /* (...) */
} // end of method Program::Main

Code is commented by me. But in short.

Your i is not an variable of Main method. It is public variable of a method that your delegate use.

Method that is being used by your delegate is inside private nested class in Main.

I do not know internals of C# compiler but this was pretty interesting to see. If you want to see it with your own eyes i recommend using dnSpy.

edit: @evk was faster :P.