问:
Download encrypted webpage
Hi I have researched this but I can not find any answers this question. I need to download a sub directory of a web page to a string for a search, I know have to do this but the only problem is the site is encrypted and requires a login to acces the directory. I know I need to send the cookies to request the download but I am unsure how to do this. I am coding python. feel free to ask for more info.</p>

答:
```<code>import urllib
import urllib2
import cookielib
import time

# All your cookie related things are done by this.
cookie_jar = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie_jar))
urllib2.install_opener(opener)

#POST Parameters for login page.
request_body_params = {'your_parameter_name': 'its_value', 'another_parameter_name': 'its_value'}

data_encoding = urllib.urlencode(request_body_params)
url_main = 'https://your_site.com/login'

main_request = urllib2.Request(url_main, data_encoding)

#Any headers required goes here.
main_request.add_header('Accept-encoding', 'gzip')

# This is the response of login. You don't want to read this.
main_response = urllib2.urlopen(main_request)

# You want data from this link.
url_results = 'https://your_site.com/sub_directory'
results_response = urllib2.urlopen(url_results)

print results_response.read()
</code>```

To check the POST Parameters, go to the site from a browser, click on 'View Source', go to 'Network' in view source. Then as you login in the browser, there will be network logs generated, click on the link and check out it's POST Parameters and headers.

Title: Download encrypted webpage

Body:
import urllib
import urllib2
import cookielib
import time

# All your cookie related things are done by this.
cookie_jar = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie_jar))
urllib2.install_opener(opener)

#POST Parameters for login page.
request_body_params = {'your_parameter_name': 'its_value', 'another_parameter_name': 'its_value'}

data_encoding = urllib.urlencode(request_body_params)
url_main = 'https://your_site.com/login'

main_request = urllib2.Request(url_main, data_encoding)

#Any headers required goes here.
main_request.add_header('Accept-encoding', 'gzip')

# This is the response of login. You don't want to read this.
main_response = urllib2.urlopen(main_request)

# You want data from this link.
url_results = 'https://your_site.com/sub_directory'
results_response = urllib2.urlopen(url_results)

print results_response.read()

To check the POST Parameters, go to the site from a browser, click on 'View Source', go to 'Network' in view source. Then as you login in the browser, there will be network logs generated, click on the link and check out it's POST Parameters and headers.


来源: stackexchange

问:
How to adjust the items in a recyclerview so that they fill exactly one page
I have a RecyclerView with 3 different item types (I am required to use a RecyclerView, instead of different views because of the course exercise requirements). The result is a layout with an ExoplayerView (item_player.xml) at Top, the item_step_description.xml in the middle and after that an item_navigation.xml as code and picture showing below.

I want a layout the RecyclerView that the item_player continues to occupy the top 200dp, the item_navigation align the bottom of the page and that all the remaining space between these two views be occupied by the item_step_description.

If I use three set of views in the same layout it would be easy to achieve what by using a LinearLayout as the parent and adjusting the children with layout_weight. But I'm not able to achieve this result inside a RecyclerView.

```<code>: recycler_view_layout

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:tools="http://schemas.android.com/tools"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             tools:context="com.github.alexpfx.udacity.nanodegree.android.baking_app.step.detail.StepViewFragment">

    <!-- TODO: Update blank fragment layout -->
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_step_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >

    </android.support.v7.widget.RecyclerView>

</FrameLayout>
</code>```

```<code>: item_player.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="200dp"
              android:orientation="vertical"

    >

    <com.google.android.exoplayer2.ui.SimpleExoPlayerView
        android:id="@+id/video_player_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>
</code>```

```<code>: item_step_description.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:background="#1ab"
              android:orientation="vertical"
    >

    <TextView
        android:id="@+id/text_step_description"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="detail step"/>
</LinearLayout>
</code>```

```<code>: item_navigation.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                xmlns:tools="http://schemas.android.com/tools"
    >

    <ImageButton
        android:id="@+id/btn_previous"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_gravity="left"
        android:padding="@dimen/fab_margin"
        android:src="@drawable/ic_navigate_before_black_24dp"
        android:background="@null"
        />

    <TextView
        android:id="@+id/text_short_description"
        android:layout_toRightOf="@+id/btn_previous"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@+id/btn_next"
        android:layout_alignBottom="@+id/btn_previous"
        android:layout_alignTop="@+id/btn_previous"
        tools:text="descrição da receita"
        android:gravity="center"
        android:textAppearance="@style/TextAppearance.AppCompat.Subhead"

        />

    <ImageButton
        android:id="@+id/btn_next"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_gravity="right"
        android:src="@drawable/ic_navigate_next_black_24dp"
        android:background="@null"
        android:padding="@dimen/fab_margin"
        />

</RelativeLayout>
</code>```

答:
you can archive it by setting the height of each view type in your ViewHolder constructor as below:

```<code> //your player height
 public ViewHolderPlayer(View itemView) {
        super(itemView);
        itemView.getLayoutParams().height = your200dpHeight;
    }
// your instruction
 public ViewHolderPlayerInstruction(View itemView) {
        super(itemView);
        itemView.getLayoutParams().height = (screenHeight - your200dpHeight)*3f/4f;
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a RecyclerView with 3 different item types (I am required to use a RecyclerView, instead of different views because of the course exercise requirements). The result is a layout with an ExoplayerView (item_player.xml) at Top, the item_step_description.xml in the middle and after that an item_navigation.xml as code and picture showing below.

I want a layout the RecyclerView that the item_player continues to occupy the top 200dp, the item_navigation align the bottom of the page and that all the remaining space between these two views be occupied by the item_step_description.

If I use three set of views in the same layout it would be easy to achieve what by using a LinearLayout as the parent and adjusting the children with layout_weight. But I'm not able to achieve this result inside a RecyclerView.

: recycler_view_layout

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:tools="http://schemas.android.com/tools"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             tools:context="com.github.alexpfx.udacity.nanodegree.android.baking_app.step.detail.StepViewFragment">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_step_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >

    </android.support.v7.widget.RecyclerView>

</FrameLayout>

: item_player.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="200dp"
              android:orientation="vertical"

    >

    <com.google.android.exoplayer2.ui.SimpleExoPlayerView
        android:id="@+id/video_player_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>

: item_step_description.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:background="#1ab"
              android:orientation="vertical"
    >

    <TextView
        android:id="@+id/text_step_description"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="detail step"/>
</LinearLayout>

: item_navigation.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                xmlns:tools="http://schemas.android.com/tools"
    >

    <ImageButton
        android:id="@+id/btn_previous"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_gravity="left"
        android:padding="@dimen/fab_margin"
        android:src="@drawable/ic_navigate_before_black_24dp"
        android:background="@null"
        />

    <TextView
        android:id="@+id/text_short_description"
        android:layout_toRightOf="@+id/btn_previous"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@+id/btn_next"
        android:layout_alignBottom="@+id/btn_previous"
        android:layout_alignTop="@+id/btn_previous"
        tools:text="descrição da receita"
        android:gravity="center"
        android:textAppearance="@style/TextAppearance.AppCompat.Subhead"

        />

    <ImageButton
        android:id="@+id/btn_next"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_gravity="right"
        android:src="@drawable/ic_navigate_next_black_24dp"
        android:background="@null"
        android:padding="@dimen/fab_margin"
        />

</RelativeLayout>

Body:
you can archive it by setting the height of each view type in your ViewHolder constructor as below:

 //your player height
 public ViewHolderPlayer(View itemView) {
        super(itemView);
        itemView.getLayoutParams().height = your200dpHeight;
    }
// your instruction
 public ViewHolderPlayerInstruction(View itemView) {
        super(itemView);
        itemView.getLayoutParams().height = (screenHeight - your200dpHeight)*3f/4f;
    }


问:
Android smooth transition on list items removed
This gif illustrates what I'm trying to accomplish:

All of the ListView's items are removed except for the one that was clicked, and it smoothly transitions to the center of the ListView, now with a size of 1.

The problem is that whenever items at the front of the Adapter's ArrayList are removed, in other words when any other item besides the first is clicked, I get this discontinuous transition where the clicked item and its text jump to the position of the previously first item before transitioning:

```<code>final String[] items = {"foo", "bar", "The Quick Brown Fox", "qwerty"};
    final ArrayList<String> alItems = new ArrayList<>(Arrays.asList(items));

    final ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.tv1, alItems);
    final ViewGroup main = (ViewGroup) findViewById(R.id.main);
    final ListView lv = (ListView)findViewById(R.id.theListView);
    lv.setAdapter(adapter);
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // Remove all items except for the chosen one

            TransitionManager.beginDelayedTransition(main);
            alItems.subList(0, position).clear();  // Remove items before clicked item
            alItems.subList(1, alItems.size()).clear();  // Remove items after clicked item
            adapter.notifyDataSetChanged();

        }
    });
</code>```

I suspect it has to do with the ArrayList getting set to a new ArrayList behind the scenes. What's a good way to accomplish the desired effect without jumps?

答:
Hack alert!!!

```<code>    TransitionManager.beginDelayedTransition(main);
    // set all but selected to empty string
    //   this leaves the list intact but only displaying selected item
    for (int i=0; i<alItems.size(); i++) {
        if(i != position) {
            alItems.set(i, "");
        }
    }
    adapter.notifyDataSetChanged();

    // now wait a while & clear the list
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            alItems.subList(0, position).clear();  // Remove items before clicked item
            alItems.subList(1, alItems.size()).clear();  // Remove items after clicked item
            adapter.notifyDataSetChanged();
        }
    };
    Handler handler = new Handler();
    handler.postDelayed(runnable, 200);     // 200ms or whatever delay looks good
</code>```

If you're desperate enough, this might give you what you want.

Body:
This gif illustrates what I'm trying to accomplish:

All of the ListView's items are removed except for the one that was clicked, and it smoothly transitions to the center of the ListView, now with a size of 1.

The problem is that whenever items at the front of the Adapter's ArrayList are removed, in other words when any other item besides the first is clicked, I get this discontinuous transition where the clicked item and its text jump to the position of the previously first item before transitioning:

final String[] items = {"foo", "bar", "The Quick Brown Fox", "qwerty"};
    final ArrayList<String> alItems = new ArrayList<>(Arrays.asList(items));

    final ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.tv1, alItems);
    final ViewGroup main = (ViewGroup) findViewById(R.id.main);
    final ListView lv = (ListView)findViewById(R.id.theListView);
    lv.setAdapter(adapter);
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // Remove all items except for the chosen one

            TransitionManager.beginDelayedTransition(main);
            alItems.subList(0, position).clear();  // Remove items before clicked item
            alItems.subList(1, alItems.size()).clear();  // Remove items after clicked item
            adapter.notifyDataSetChanged();

        }
    });

I suspect it has to do with the ArrayList getting set to a new ArrayList behind the scenes. What's a good way to accomplish the desired effect without jumps?

Body:
Hack alert!!!

    TransitionManager.beginDelayedTransition(main);
    // set all but selected to empty string
    //   this leaves the list intact but only displaying selected item
    for (int i=0; i<alItems.size(); i++) {
        if(i != position) {
            alItems.set(i, "");
        }
    }
    adapter.notifyDataSetChanged();

    // now wait a while & clear the list
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            alItems.subList(0, position).clear();  // Remove items before clicked item
            alItems.subList(1, alItems.size()).clear();  // Remove items after clicked item
            adapter.notifyDataSetChanged();
        }
    };
    Handler handler = new Handler();
    handler.postDelayed(runnable, 200);     // 200ms or whatever delay looks good

If you're desperate enough, this might give you what you want.


问:
MVVM RxSwift way to send data from main view to detail view controller?
I have a view model that has an element that returns an observable array after calling an API.

I then find that result to a table view to display it. The problem I am having is how to call the detail view controller on the specific cell that is clicked. I bound the results with:

```<code> let queryResults = eventsViewModel.mainTableItems

       queryResults
            .bind(to: collectionView.rx.items) { collectionView, row, item in

                let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: IndexPath(row: row, section: 0)) as! EventCell
                cell.heroID = "heroCellID"
                cell.restaurantNameLabel.text = item.name
                cell.restaurantDetailLabel.text = item.location
                cell.timeLabel.text = item.date
                cell.restaurantImageView.kf.setImage(with: URL(string: item.image))

                return cell
        }
        .addDisposableTo(disposeBag)
</code>```

I have no way to access the specific element in this observable array that was clicked. It says an Observable array cannot have subscript.

This is the code that says that:

```<code> vc.festival = queryResults.value[indexPath.row]
</code>```

I am still new to RxSwift and I am struggling to understand this.

答:
This really is the million dollar question, and something that has a lot of different answers and none are really simple, even without using RxSwift. The short answer is, it depends on how your app is architected.

First thing, if you haven't already realized, is that you find out which item was selected with tableView.rx.itemSelected.

IMHO, view controllers should be independent of each other so the one thing you don't want to do is create or segue to the detail view controller from this one. There should be some sort of coordinator object that subscribes to itemSelected and is in charge of deciding where to go from there.

Here are some good articles to get you on the right track:

http://rasic.info/a-different-take-on-mvvm-with-swift/

In this article, Mr. Rasic talks about a class that he calls the Scene which is in charge of creating the view controller and its view mode, attaching them and then deciding where to go from there.

http://khanlou.com/2015/01/the-coordinator/

In this article, Mr. Khanlou talks about a class that he calls the Coordinator. He doesn't use Rx, instead he uses delegates, but it's pretty easy to see how it would relate.

https://talk.objc.io/episodes/S01E05-connecting-view-controllers

This is a video where the objc.io team creates an App class that takes care of view controller navigation. They use closures here instead of Rx, but again the correspondence should be obvious.

Body:
I have a view model that has an element that returns an observable array after calling an API.

I then find that result to a table view to display it. The problem I am having is how to call the detail view controller on the specific cell that is clicked. I bound the results with:

 let queryResults = eventsViewModel.mainTableItems

       queryResults
            .bind(to: collectionView.rx.items) { collectionView, row, item in

                let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: IndexPath(row: row, section: 0)) as! EventCell
                cell.heroID = "heroCellID"
                cell.restaurantNameLabel.text = item.name
                cell.restaurantDetailLabel.text = item.location
                cell.timeLabel.text = item.date
                cell.restaurantImageView.kf.setImage(with: URL(string: item.image))

                return cell
        }
        .addDisposableTo(disposeBag)

I have no way to access the specific element in this observable array that was clicked. It says an Observable array cannot have subscript.

This is the code that says that:

 vc.festival = queryResults.value[indexPath.row]

I am still new to RxSwift and I am struggling to understand this.


问:
Find all instances of every file name in a directory tree
This Perl script has a search function that searches for files in subdirectories that have the same filename.

The output generated must be something like this:

```<code>file_name1: ~/X/file_name1 ~/?/??/file_name1
file_name2: ~/X/XYZ/file_name2 ~/?/?????/ ??/file_name2
</code>```

I have tried the way using below:

```<code>find . -type f | perl -e'

while ( <> ) {
    chomp;
    push @{ $h{ substr($_, rindex($_, "/") + 1) } }, $_;
}

for $k (keys %h) {
    next if @{ $h{$k} } < 2;
    print "$k: @{ $h{$k} }\n"
}'
</code>```

Does anyone have another solution to this?

答:
It seems that you are looking for duplicate files, simply put.

A couple of approaches

There is a module File::Find::Duplicates, what may just solve your problem directly.

Use a module to find all files, say File::Find::Rule. Then use one of many ways to find duplicates in list(s), or use a hash (see this post). Use MD5 to confirm that the files are the same.

There are posts on SO on details mentioned above, and in fact on the whole topic, please search.

Body:
This Perl script has a search function that searches for files in subdirectories that have the same filename.

The output generated must be something like this:

file_name1: ~/X/file_name1 ~/?/??/file_name1
file_name2: ~/X/XYZ/file_name2 ~/?/?????/ ??/file_name2

I have tried the way using below:

find . -type f | perl -e'

while ( <> ) {
    chomp;
    push @{ $h{ substr($_, rindex($_, "/") + 1) } }, $_;
}

for $k (keys %h) {
    next if @{ $h{$k} } < 2;
    print "$k: @{ $h{$k} }\n"
}'

Does anyone have another solution to this?


问:
Differences in print output/format
New to python and trying to figure out why the following 2 lists generate different output formats

```<code>n=5
mylist = "*" * n
print(mylist)
mylist = ["\*", "\*", "\*", "\*", "\*"]
print(mylist)
</code>```

Output:

*****
['\*', '\*', '\*', '\*', '\*']
```

答:
In Python when using a multiplication operator (*) with a string this string is repeated according to the number, for example

str = "-" * 6 # output : ------```

NOTE : This operation returns a string and not a list

The second output is simply a list with elements and its output is as expected

I hope I have helped

Title: Differences in print output/format

Body:
New to python and trying to figure out why the following 2 lists generate different output formats

n=5
mylist = "*" * n
print(mylist)
mylist = ["\*", "\*", "\*", "\*", "\*"]
print(mylist)

Output:

*****
['\*', '\*', '\*', '\*', '\*']

Body:
In Python when using a multiplication operator (*) with a string this string is repeated according to the number, for example

str = "-" * 6 # output : ------

NOTE : This operation returns a string and not a list

The second output is simply a list with elements and its output is as expected

I hope I have helped


问:
Perimeter Calculator Java
I'm trying to write a program that would be able to calculate the perimeter of either a circle, triangle, or rectangle. However the program doesn't run correctly, it just show the menu but I can't input anything.

```<code>public class GeometryDriver
{

public static void main(String[] args)
{

  double radius;
  double side1 = 0;
  double side2 = 0;
  double side3 = 0;
  double length =0;
  double width =0;
  double perimeter = 0;
  String userChoice;

    Scanner keyboard = new Scanner(System.in);
    int option;

    System.out.println("Welcome to the Geometry Calculator!\n"
            + "In this program we will use a menu to decide what kind of shape we will create.\n"
            + "\n1.Create and Calculate Perimeter of a Circle"
            + "\n2. Create and Calculate Perimeter of a Rectangle"
            + "\n3. Create and Calculate Perimeter of a Triangle");

    String input;
    GeometricShape aShape = null;

    option = keyboard.nextInt();

    switch (option)
    {
        case 1:

            input = JOptionPane. showInputDialog(null, "Enter the radius: ");
            radius = Double.parseDouble(input);
            aShape = new GeometricShape(radius);
            perimeter = aShape.getPerimeter();

            aShape = new GeometricShape(radius);
            break;

        case 2:

            input = JOptionPane.showInputDialog(null, "Enter the length: ");

            length = Double.parseDouble(input);

            perimeter = aShape.getPerimeter();
            input = JOptionPane.showInputDialog(null, "Enter the width: ");
            width = Double.parseDouble(input);

            aShape = new GeometricShape (length, width);

            break;
        case 3:

            perimeter = aShape.getPerimeter();

            input = JOptionPane.showInputDialog(null, "Enter side 1: ");
            input = JOptionPane.showInputDialog(null, "Enter side 2: ");
            input = JOptionPane.showInputDialog(null, "Enter side 3: ");
            side1 = Double.parseDouble(input);
            side2 = Double.parseDouble(input);
            side3 = Double.parseDouble(input);

            aShape = new GeometricShape (side1, side2, side3);

            break;
        default:

                    }

      System.out.println(aShape + " has perimeter" + perimeter);
}

}
</code>```

and...

```<code>public class GeometricShape
{
    private double side1, side2, side3;
    private double radius;
    private double length, width;
    private boolean triangle = false;
    private boolean rectangle = false;
    private boolean circle = false;`

    public GeometricShape(double aSide1, double aSide2, double aSide3)
    {
        side1 = aSide1;
        side2 = aSide2;
        side3 = aSide3;
        triangle = true;
    }

    public GeometricShape(double aLength, double aWidth)
    {
        length = aLength;
        width = aWidth;
        rectangle = true;
    }

    public GeometricShape(double aRadius)
    {
        radius = aRadius;
        circle = true;
    }

    public double getRadius()
    {
        return radius;
    }

    public double getSide1()
    {
        return side1;
    }

    public double getSide2()
    {
        return side2;
    }

    public double getSide3()
    {
        return side3;
    }

    public double getLength()
    {
        return length;
    }

    public double getWidth()
    {
    return width;
    }

    public void setRadius(double aRadius)
    {
        radius = aRadius;
    }

    public void setSide1(double aSide1)
    {
        side1 = aSide1;
    }

    public void setSide2(double aSide2)
    {
        side2 = aSide2;
    }

    public void setSide3(double aSide3)
    {
        side3 = aSide3;
    }

    public void setLength(double aLength)
    {
        length = aLength;
    }

    public void setWidth(double aWidth)
    {
        width = aWidth;
    }

    public double getPerimeter()
    {

        double perimeter = 0;

        if (triangle == true)
        {
            perimeter = side1 + side2 + side3;
        }

        else if (rectangle == true)
        {
            perimeter = (2* length) + (2*width);
        }

        else if (circle == true)
        {
            perimeter = 2* Math.PI * radius;
        }

    }

    public String toString()
    {
        return "The perimeter is: " + this.getPerimeter();
    }
}
</code>```

答:
With some slight modifications to your code, I can enter a radius. It's now all in one file named Main.java and still a nullpointer for a rectangle because the width is null.

```<code>import javax.swing.*;
import java.util.Scanner;

class GeometricShape {
    private double side1, side2, side3;
    private double radius;
    private double length, width;
    private boolean triangle = false;
    private boolean rectangle = false;
    private boolean circle = false;

    GeometricShape(double aSide1, double aSide2, double aSide3) {
        side1 = aSide1;
        side2 = aSide2;
        side3 = aSide3;
        triangle = true;
    }

    GeometricShape(double aLength, double aWidth) {
        length = aLength;
        width = aWidth;
        rectangle = true;
    }

    GeometricShape(double aRadius) {
        radius = aRadius;
        circle = true;
    }

    public double getRadius() {
        return radius;
    }

    public double getSide1() {
        return side1;
    }

    public double getSide2() {
        return side2;
    }

    public double getSide3() {
        return side3;
    }

    public double getLength() {
        return length;
    }

    public double getWidth() {
        return width;
    }

    public void setRadius(double aRadius) {
        radius = aRadius;
    }

    public void setSide1(double aSide1) {
        side1 = aSide1;
    }

    public void setSide2(double aSide2) {
        side2 = aSide2;
    }

    public void setSide3(double aSide3) {
        side3 = aSide3;
    }

    public void setLength(double aLength) {
        length = aLength;
    }

    public void setWidth(double aWidth) {
        width = aWidth;
    }

    public double getPerimeter() {

        double perimeter = 0;

        if (triangle == true) {
            perimeter = side1 + side2 + side3;
        } else if (rectangle == true) {
            perimeter = (2 * length) + (2 * width);
        } else if (circle == true) {
            perimeter = 2 * Math.PI * radius;
        }
        return perimeter;

    }

    public String toString() {

        return "The perimeter is: " + this.getPerimeter()
                ;
    }

}

public class Main {

    public static void main(String[] args) {
        {

            double radius;
            double side1 = 0;
            double side2 = 0;
            double side3 = 0;
            double length = 0;
            double width = 0;
            double perimeter = 0;
            String userChoice;

            Scanner keyboard = new Scanner(System.in);
            int option;

            System.out.println("Welcome to the Geometry Calculator!\n"
                    + "In this program we will use a menu to decide what kind of shape we will create.\n"
                    + "\n1.Create and Calculate Perimeter of a Circle"
                    + "\n2. Create and Calculate Perimeter of a Rectangle"
                    + "\n3. Create and Calculate Perimeter of a Triangle");

            String input;
            GeometricShape aShape = null;

            option = keyboard.nextInt();

            switch (option) {
                case 1:

                    input = JOptionPane.showInputDialog(null, "Enter the radius: ");
                    radius = Double.parseDouble(input);
                    aShape = new GeometricShape(radius);
                    perimeter = aShape.getPerimeter();

                    aShape = new GeometricShape(radius);
                    break;

                case 2:

                    input = JOptionPane.showInputDialog(null, "Enter the length: ");

                    length = Double.parseDouble(input);

                    perimeter = aShape.getPerimeter();
                    input = JOptionPane.showInputDialog(null, "Enter the width: ");
                    width = Double.parseDouble(input);

                    aShape = new GeometricShape(length, width);

                    break;
                case 3:

                    perimeter = aShape.getPerimeter();

                    input = JOptionPane.showInputDialog(null, "Enter side 1: ");
                    input = JOptionPane.showInputDialog(null, "Enter side 2: ");
                    input = JOptionPane.showInputDialog(null, "Enter side 3: ");
                    side1 = Double.parseDouble(input);
                    side2 = Double.parseDouble(input);
                    side3 = Double.parseDouble(input);

                    aShape = new GeometricShape(side1, side2, side3);

                    break;
                default:

            }

            System.out.println(aShape + " has perimeter" + perimeter);
            ;

        }
    }
}
</code>```

Test

```<code>Welcome to the Geometry Calculator!
In this program we will use a menu to decide what kind of shape we will create.

1.Create and Calculate Perimeter of a Circle
2. Create and Calculate Perimeter of a Rectangle
3. Create and Calculate Perimeter of a Triangle
1
The perimeter is: 12.566370614359172 has perimeter12.566370614359172
</code>```

Title: Perimeter Calculator Java

Body:
I'm trying to write a program that would be able to calculate the perimeter of either a circle, triangle, or rectangle. However the program doesn't run correctly, it just show the menu but I can't input anything.

public class GeometryDriver
{

public static void main(String[] args)
{

  double radius;
  double side1 = 0;
  double side2 = 0;
  double side3 = 0;
  double length =0;
  double width =0;
  double perimeter = 0;
  String userChoice;

    Scanner keyboard = new Scanner(System.in);
    int option;

    System.out.println("Welcome to the Geometry Calculator!\n"
            + "In this program we will use a menu to decide what kind of shape we will create.\n"
            + "\n1.Create and Calculate Perimeter of a Circle"
            + "\n2. Create and Calculate Perimeter of a Rectangle"
            + "\n3. Create and Calculate Perimeter of a Triangle");

    String input;
    GeometricShape aShape = null;

    option = keyboard.nextInt();

    switch (option)
    {
        case 1:

            input = JOptionPane. showInputDialog(null, "Enter the radius: ");
            radius = Double.parseDouble(input);
            aShape = new GeometricShape(radius);
            perimeter = aShape.getPerimeter();

            aShape = new GeometricShape(radius);
            break;

        case 2:

            input = JOptionPane.showInputDialog(null, "Enter the length: ");

            length = Double.parseDouble(input);

            perimeter = aShape.getPerimeter();
            input = JOptionPane.showInputDialog(null, "Enter the width: ");
            width = Double.parseDouble(input);

            aShape = new GeometricShape (length, width);

            break;
        case 3:

            perimeter = aShape.getPerimeter();

            input = JOptionPane.showInputDialog(null, "Enter side 1: ");
            input = JOptionPane.showInputDialog(null, "Enter side 2: ");
            input = JOptionPane.showInputDialog(null, "Enter side 3: ");
            side1 = Double.parseDouble(input);
            side2 = Double.parseDouble(input);
            side3 = Double.parseDouble(input);

            aShape = new GeometricShape (side1, side2, side3);

            break;
        default:

                    }

      System.out.println(aShape + " has perimeter" + perimeter);
}

}

and...

public class GeometricShape
{
    private double side1, side2, side3;
    private double radius;
    private double length, width;
    private boolean triangle = false;
    private boolean rectangle = false;
    private boolean circle = false;`

    public GeometricShape(double aSide1, double aSide2, double aSide3)
    {
        side1 = aSide1;
        side2 = aSide2;
        side3 = aSide3;
        triangle = true;
    }

    public GeometricShape(double aLength, double aWidth)
    {
        length = aLength;
        width = aWidth;
        rectangle = true;
    }

    public GeometricShape(double aRadius)
    {
        radius = aRadius;
        circle = true;
    }

    public double getRadius()
    {
        return radius;
    }

    public double getSide1()
    {
        return side1;
    }

    public double getSide2()
    {
        return side2;
    }

    public double getSide3()
    {
        return side3;
    }

    public double getLength()
    {
        return length;
    }

    public double getWidth()
    {
    return width;
    }

    public void setRadius(double aRadius)
    {
        radius = aRadius;
    }

    public void setSide1(double aSide1)
    {
        side1 = aSide1;
    }

    public void setSide2(double aSide2)
    {
        side2 = aSide2;
    }

    public void setSide3(double aSide3)
    {
        side3 = aSide3;
    }

    public void setLength(double aLength)
    {
        length = aLength;
    }

    public void setWidth(double aWidth)
    {
        width = aWidth;
    }

    public double getPerimeter()
    {

        double perimeter = 0;

        if (triangle == true)
        {
            perimeter = side1 + side2 + side3;
        }

        else if (rectangle == true)
        {
            perimeter = (2* length) + (2*width);
        }

        else if (circle == true)
        {
            perimeter = 2* Math.PI * radius;
        }

    }

    public String toString()
    {
        return "The perimeter is: " + this.getPerimeter();
    }
}

Body:
With some slight modifications to your code, I can enter a radius. It's now all in one file named Main.java and still a nullpointer for a rectangle because the width is null.

import javax.swing.*;
import java.util.Scanner;

class GeometricShape {
    private double side1, side2, side3;
    private double radius;
    private double length, width;
    private boolean triangle = false;
    private boolean rectangle = false;
    private boolean circle = false;

    GeometricShape(double aSide1, double aSide2, double aSide3) {
        side1 = aSide1;
        side2 = aSide2;
        side3 = aSide3;
        triangle = true;
    }

    GeometricShape(double aLength, double aWidth) {
        length = aLength;
        width = aWidth;
        rectangle = true;
    }

    GeometricShape(double aRadius) {
        radius = aRadius;
        circle = true;
    }

    public double getRadius() {
        return radius;
    }

    public double getSide1() {
        return side1;
    }

    public double getSide2() {
        return side2;
    }

    public double getSide3() {
        return side3;
    }

    public double getLength() {
        return length;
    }

    public double getWidth() {
        return width;
    }

    public void setRadius(double aRadius) {
        radius = aRadius;
    }

    public void setSide1(double aSide1) {
        side1 = aSide1;
    }

    public void setSide2(double aSide2) {
        side2 = aSide2;
    }

    public void setSide3(double aSide3) {
        side3 = aSide3;
    }

    public void setLength(double aLength) {
        length = aLength;
    }

    public void setWidth(double aWidth) {
        width = aWidth;
    }

    public double getPerimeter() {

        double perimeter = 0;

        if (triangle == true) {
            perimeter = side1 + side2 + side3;
        } else if (rectangle == true) {
            perimeter = (2 * length) + (2 * width);
        } else if (circle == true) {
            perimeter = 2 * Math.PI * radius;
        }
        return perimeter;

    }

    public String toString() {

        return "The perimeter is: " + this.getPerimeter()
                ;
    }

}

public class Main {

    public static void main(String[] args) {
        {

            double radius;
            double side1 = 0;
            double side2 = 0;
            double side3 = 0;
            double length = 0;
            double width = 0;
            double perimeter = 0;
            String userChoice;

            Scanner keyboard = new Scanner(System.in);
            int option;

            System.out.println("Welcome to the Geometry Calculator!\n"
                    + "In this program we will use a menu to decide what kind of shape we will create.\n"
                    + "\n1.Create and Calculate Perimeter of a Circle"
                    + "\n2. Create and Calculate Perimeter of a Rectangle"
                    + "\n3. Create and Calculate Perimeter of a Triangle");

            String input;
            GeometricShape aShape = null;

            option = keyboard.nextInt();

            switch (option) {
                case 1:

                    input = JOptionPane.showInputDialog(null, "Enter the radius: ");
                    radius = Double.parseDouble(input);
                    aShape = new GeometricShape(radius);
                    perimeter = aShape.getPerimeter();

                    aShape = new GeometricShape(radius);
                    break;

                case 2:

                    input = JOptionPane.showInputDialog(null, "Enter the length: ");

                    length = Double.parseDouble(input);

                    perimeter = aShape.getPerimeter();
                    input = JOptionPane.showInputDialog(null, "Enter the width: ");
                    width = Double.parseDouble(input);

                    aShape = new GeometricShape(length, width);

                    break;
                case 3:

                    perimeter = aShape.getPerimeter();

                    input = JOptionPane.showInputDialog(null, "Enter side 1: ");
                    input = JOptionPane.showInputDialog(null, "Enter side 2: ");
                    input = JOptionPane.showInputDialog(null, "Enter side 3: ");
                    side1 = Double.parseDouble(input);
                    side2 = Double.parseDouble(input);
                    side3 = Double.parseDouble(input);

                    aShape = new GeometricShape(side1, side2, side3);

                    break;
                default:

            }

            System.out.println(aShape + " has perimeter" + perimeter);
            ;

        }
    }
}

Test

Welcome to the Geometry Calculator!
In this program we will use a menu to decide what kind of shape we will create.

1.Create and Calculate Perimeter of a Circle
2. Create and Calculate Perimeter of a Rectangle
3. Create and Calculate Perimeter of a Triangle
1
The perimeter is: 12.566370614359172 has perimeter12.566370614359172


问:
regex for php to find all self-closing tags
I've got a system that uses a DomDocumentFragment which is created based on markup from a database or another area of the system (i.e. other XHTML code).

One such tag that may be included is:

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

Before the string is added to the DomDocumentFragment, the content is correct - the  class is closing correctly.

However, the DomDocumentFragment transforms this into:

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

This does not display correctly in browsers due to the incorrect closing of the  tag.

So my thought is to post-process the XML string that the DomDocument returns me (that includes the incorrect div structure, as shown above), and transform self-closing tags back to their correct structure... i.e. turn  back to .

But I'm having trouble with the pattern for preg_match to find these tags - I've seen some patterns that return all tags (i.e. find all  tags), but not just those that are self closing.

I've tried something along the lines of this, but my head gets a little confused with regex (and I start over-complicating things)

```<code>/<div(["\d\w\s])\/>/
</code>```

The aim is for a pattern to match , where the "...." could be any valid XHTML attributes.

Any suggestions or pointers to put me back on track?

答:
Putting

```<code><div></div>
</code>```

into a DomDocumentFragment doesn't actually change it into

```<code><div/>
</code>```

it changes it into

```<code>A-DOM-Element-Node-with-name-"div"-and-no-content.
</code>```

It's only when the DomDocumentFragment is serialized that either

 or
 is created. In other words, the problem lies not with the DomDocumentFragment, but with the serialization process that you are using.

PHP is not my language, so I can't be much more help, but I would be looking for an HTML-compatible serializer for your DomDocumentFragment, rather than try to patch the output after serialization.

ContentLicense: CC BY-SA 2.5

Body:
I've got a system that uses a DomDocumentFragment which is created based on markup from a database or another area of the system (i.e. other XHTML code).

One such tag that may be included is:

Before the string is added to the DomDocumentFragment, the content is correct - the  class is closing correctly.

However, the DomDocumentFragment transforms this into:

This does not display correctly in browsers due to the incorrect closing of the  tag.

So my thought is to post-process the XML string that the DomDocument returns me (that includes the incorrect div structure, as shown above), and transform self-closing tags back to their correct structure... i.e. turn  back to .

But I'm having trouble with the pattern for preg_match to find these tags - I've seen some patterns that return all tags (i.e. find all  tags), but not just those that are self closing.

I've tried something along the lines of this, but my head gets a little confused with regex (and I start over-complicating things)

/
/

The aim is for a pattern to match , where the "...." could be any valid XHTML attributes.

Any suggestions or pointers to put me back on track?

Body:
Putting

<div></div>

into a DomDocumentFragment doesn't actually change it into

<div/>

it changes it into

A-DOM-Element-Node-with-name-"div"-and-no-content.

It's only when the DomDocumentFragment is serialized that either <div></div> or <div/> is created. In other words, the problem lies not with the DomDocumentFragment, but with the serialization process that you are using.

PHP is not my language, so I can't be much more help, but I would be looking for an HTML-compatible serializer for your DomDocumentFragment, rather than try to patch the output after serialization.


问:
Compiling `core` from a specific source using Xargo
Based on this comment, it should be possible to use Xargo to manage the installation of a custom core crate for a particular target. I've tried the following to get it working with a crate that has no other dependency except core:

Cargo.toml: no dependencies listed

```<code>[package]
name = "chip8-engine"
version = "0.1.0"
authors = ["Dr. ERDI Gergo <gergo@erdi.hu>"]

[dependencies]
</code>```

Xargo.toml: my specific source listed for core

```<code>[target.avr-atmel-none.dependencies]
core = { git = "https://github.com/gergoerdi/rust-avr-libcore-mini", rev = "adda44aa91ac517aab6915447592ee4cad26564c" }
</code>```

However, building via xargo build fails as if I was just using cargo:

```<code>$ ~/.cargo/bin/xargo build --release -v --target avr-atmel-none
+ "rustc" "--print" "sysroot"
+ "cargo" "build" "--release" "-v" "--target" "avr-atmel-none"
   Compiling chip8-engine v0.1.0 (file:///home/cactus/prog/rust/avr/chip8-engine-avr)
     Running `stage1/bin/rustc --crate-name chip8_engine src/lib.rs --crate-type lib -C opt-level=3 -C metadata=231962fc6e1bee04 -C extra-filename=-231962fc6e1bee04 --out-dir /home/cactus/prog/rust/avr/chip8-engine-avr/target/avr-atmel-none/release/deps --emit=dep-info,link --target avr-atmel-none -L dependency=/home/cactus/prog/rust/avr/chip8-engine-avr/target/avr-atmel-none/release/deps -L dependency=/home/cactus/prog/rust/avr/chip8-engine-avr/target/release/deps`
error[E0463]: can't find crate for `core`
  |
  = note: the `avr-atmel-none` target may not be installed

error: aborting due to previous error

error: Could not compile `chip8-engine`.

Caused by:
  process didn't exit successfully: `stage1/bin/rustc --crate-name chip8_engine src/lib.rs --crate-type lib -C opt-level=3 -C metadata=231962fc6e1bee04 -C extra-filename=-231962fc6e1bee04 --out-dir /home/cactus/prog/rust/avr/chip8-engine-avr/target/avr-atmel-none/release/deps --emit=dep-info,link --target avr-atmel-none -L dependency=/home/cactus/prog/rust/avr/chip8-engine-avr/target/avr-atmel-none/release/deps -L dependency=/home/cactus/prog/rust/avr/chip8-engine-avr/target/release/deps` (exit code: 101)
</code>```

Note that there's nothing indicating even attempted Git traffic.

In contrast, here's the output of vanilla cargo if I put my core = { git = ...} line in Cargo.toml instead of Xargo.toml, which works as expected:

```<code>$ cargo build -v --target=avr-atmel-none --release
   Compiling core v0.1.0 (https://github.com/gergoerdi/rust-avr-libcore-mini?rev=adda44aa91ac517aab6915447592ee4cad26564c#adda44aa)
     Running `stage1/bin/rustc --crate-name core /home/cactus/.cargo/git/checkouts/rust-avr-libcore-mini-37e279d93a70b45a/adda44a/src/lib.rs --crate-type lib -C opt-level=3 -C metadata=47f38a1987c5b284 -C extra-filename=-47f38a1987c5b284 --out-dir /home/cactus/prog/rust/avr/chip8-engine-avr/target/avr-atmel-none/release/deps --emit=dep-info,link --target avr-atmel-none -L dependency=/home/cactus/prog/rust/avr/chip8-engine-avr/target/avr-atmel-none/release/deps -L dependency=/home/cactus/prog/rust/avr/chip8-engine-avr/target/release/deps --cap-lints allow`
   Compiling chip8-engine v0.1.0 (file:///home/cactus/prog/rust/avr/chip8-engine-avr)
     Running `stage1/bin/rustc --crate-name chip8_engine src/lib.rs --crate-type lib -C opt-level=3 -C metadata=231962fc6e1bee04 -C extra-filename=-231962fc6e1bee04 --out-dir /home/cactus/prog/rust/avr/chip8-engine-avr/target/avr-atmel-none/release/deps --emit=dep-info,link --target avr-atmel-none -L dependency=/home/cactus/prog/rust/avr/chip8-engine-avr/target/avr-atmel-none/release/deps -L dependency=/home/cactus/prog/rust/avr/chip8-engine-avr/target/release/deps --extern core=/home/cactus/prog/rust/avr/chip8-engine-avr/target/avr-atmel-none/release/deps/libcore-47f38a1987c5b284.rlib`
    Finished release [optimized] target(s) in 15.21 secs
</code>```

答:
You may need to install the nightly Rust toolchain to allow xargo to buildup some support code for your target. I had to do something similar to get an embedded ARM setup working with xargo. Do this in the directory of your embedded target:

$ rustup install nightly
$ rustup component add rust-src  # needed for xargo buildup of the target
$ rustup override set nightly    # sets the rustc version to run for this dir
$ xargo build
```

Body:
Based on this comment, it should be possible to use Xargo to manage the installation of a custom core crate for a particular target. I've tried the following to get it working with a crate that has no other dependency except core:

Cargo.toml: no dependencies listed

[package]
name = "chip8-engine"
version = "0.1.0"
authors = ["Dr. ERDI Gergo <gergo@erdi.hu>"]

[dependencies]

Xargo.toml: my specific source listed for core

[target.avr-atmel-none.dependencies]
core = { git = "https://github.com/gergoerdi/rust-avr-libcore-mini", rev = "adda44aa91ac517aab6915447592ee4cad26564c" }

However, building via xargo build fails as if I was just using cargo:

$ ~/.cargo/bin/xargo build --release -v --target avr-atmel-none
+ "rustc" "--print" "sysroot"
+ "cargo" "build" "--release" "-v" "--target" "avr-atmel-none"
   Compiling chip8-engine v0.1.0 (file:///home/cactus/prog/rust/avr/chip8-engine-avr)
     Running `stage1/bin/rustc --crate-name chip8_engine src/lib.rs --crate-type lib -C opt-level=3 -C metadata=231962fc6e1bee04 -C extra-filename=-231962fc6e1bee04 --out-dir /home/cactus/prog/rust/avr/chip8-engine-avr/target/avr-atmel-none/release/deps --emit=dep-info,link --target avr-atmel-none -L dependency=/home/cactus/prog/rust/avr/chip8-engine-avr/target/avr-atmel-none/release/deps -L dependency=/home/cactus/prog/rust/avr/chip8-engine-avr/target/release/deps`
error[E0463]: can't find crate for `core`
  |
  = note: the `avr-atmel-none` target may not be installed

error: aborting due to previous error

error: Could not compile `chip8-engine`.

Caused by:
  process didn't exit successfully: `stage1/bin/rustc --crate-name chip8_engine src/lib.rs --crate-type lib -C opt-level=3 -C metadata=231962fc6e1bee04 -C extra-filename=-231962fc6e1bee04 --out-dir /home/cactus/prog/rust/avr/chip8-engine-avr/target/avr-atmel-none/release/deps --emit=dep-info,link --target avr-atmel-none -L dependency=/home/cactus/prog/rust/avr/chip8-engine-avr/target/avr-atmel-none/release/deps -L dependency=/home/cactus/prog/rust/avr/chip8-engine-avr/target/release/deps` (exit code: 101)

Note that there's nothing indicating even attempted Git traffic.

In contrast, here's the output of vanilla cargo if I put my core = { git = ...} line in Cargo.toml instead of Xargo.toml, which works as expected:

$ cargo build -v --target=avr-atmel-none --release
   Compiling core v0.1.0 (https://github.com/gergoerdi/rust-avr-libcore-mini?rev=adda44aa91ac517aab6915447592ee4cad26564c#adda44aa)
     Running `stage1/bin/rustc --crate-name core /home/cactus/.cargo/git/checkouts/rust-avr-libcore-mini-37e279d93a70b45a/adda44a/src/lib.rs --crate-type lib -C opt-level=3 -C metadata=47f38a1987c5b284 -C extra-filename=-47f38a1987c5b284 --out-dir /home/cactus/prog/rust/avr/chip8-engine-avr/target/avr-atmel-none/release/deps --emit=dep-info,link --target avr-atmel-none -L dependency=/home/cactus/prog/rust/avr/chip8-engine-avr/target/avr-atmel-none/release/deps -L dependency=/home/cactus/prog/rust/avr/chip8-engine-avr/target/release/deps --cap-lints allow`
   Compiling chip8-engine v0.1.0 (file:///home/cactus/prog/rust/avr/chip8-engine-avr)
     Running `stage1/bin/rustc --crate-name chip8_engine src/lib.rs --crate-type lib -C opt-level=3 -C metadata=231962fc6e1bee04 -C extra-filename=-231962fc6e1bee04 --out-dir /home/cactus/prog/rust/avr/chip8-engine-avr/target/avr-atmel-none/release/deps --emit=dep-info,link --target avr-atmel-none -L dependency=/home/cactus/prog/rust/avr/chip8-engine-avr/target/avr-atmel-none/release/deps -L dependency=/home/cactus/prog/rust/avr/chip8-engine-avr/target/release/deps --extern core=/home/cactus/prog/rust/avr/chip8-engine-avr/target/avr-atmel-none/release/deps/libcore-47f38a1987c5b284.rlib`
    Finished release [optimized] target(s) in 15.21 secs


问:
Issue when joining serf nodes located in different Docker containers
Context: Host is AWS-EC2 / Ubuntu 14.04.5 with Docker version 17.05.0-ce. Containers are built from publicly available repo image cbhihe/serf-alpine-bash. All containers are located on the same EC2 instance and share the same default bridge network with net-interface "docker0".

Trying to join nodes serfDC1 (id d4fd90692e18) and serfDC2 (id 6353e7f6134d), by passing cmds from the host's shell:

```<code>$ docker exec serfDC1 serf agent -node=Node1 -bind=0.0.0.0:7946
==> Starting Serf agent…
==> Starting Serf agent RPC...
==> Serf agent running!
         Node name: 'd4fd90692e18'
         Bind addr: '0.0.0.0:7946'
          RPC addr: '127.0.0.1:7373'
         Encrypted: false
          Snapshot: false
           Profile: lan
==> Log data will now stream in as it occurs:
    2017/06/04 00:01:10 [INFO] agent: Serf agent starting
    2017/06/04 00:01:10 [INFO] serf: EventMemberJoin: d4fd90692e18 127.0.0.1
    2017/06/04 00:01:11 [INFO] agent: Received event: member-join
    ^C
</code>```

After discovering Node1's container's IP=172.17.0.4, I can issue the serf agent -join cmd to Node2:

```<code>$ docker exec serfDC2 serf agent -node=Node2 -join=172.17.0.4
==> Starting Serf agent...
==> Starting Serf agent RPC...
==> Serf agent running!
         Node name: '6353e7f6134d'
         Bind addr: '0.0.0.0:7946'
          RPC addr: '127.0.0.1:7373'
         Encrypted: false
          Snapshot: false
           Profile: lan
==> Joining cluster...(replay: false)
    Join completed. Synced with 1 initial agents
==> Log data will now stream in as it occurs:
    2017/06/04 00:18:35 [INFO] agent: Serf agent starting
    2017/06/04 00:18:35 [INFO] serf: EventMemberJoin: 6353e7f6134d 127.0.0.1
    2017/06/04 00:18:35 [INFO] agent: joining: [172.17.0.4] replay: false
    2017/06/04 00:18:35 [INFO] serf: EventMemberJoin: d4fd90692e18 127.0.0.1
    2017/06/04 00:18:35 [INFO] agent: joined: 1 nodes
    2017/06/04 00:18:36 [WARN] memberlist: Got ping for unexpected node 'd4fd90692e18' from=127.0.0.1:7946
    2017/06/04 00:18:36 [INFO] agent: Received event: member-join
    2017/06/04 00:18:37 [WARN] memberlist: Got ping for unexpected node d4fd90692e18 from=127.0.0.1:34876
    2017/06/04 00:18:37 [ERR] memberlist: Failed TCP fallback ping: EOF
    2017/06/04 00:18:37 [INFO] memberlist: Suspect d4fd90692e18 has failed, no acks received
    2017/06/04 00:18:38 [WARN] memberlist: Got ping for unexpected node 'd4fd90692e18' from=127.0.0.1:7946
    2017/06/04 00:18:39 [WARN] memberlist: Got ping for unexpected node d4fd90692e18 from=127.0.0.1:34879
    2017/06/04 00:18:39 [ERR] memberlist: Failed TCP fallback ping: EOF
    2017/06/04 00:18:40 [INFO] memberlist: Suspect d4fd90692e18 has failed, no acks received
    2017/06/04 00:18:41 [WARN] memberlist: Got ping for unexpected node 'd4fd90692e18' from=127.0.0.1:7946
    2017/06/04 00:18:42 [WARN] memberlist: Got ping for unexpected node d4fd90692e18 from=127.0.0.1:34881
    2017/06/04 00:18:42 [ERR] memberlist: Failed TCP fallback ping: EOF
    2017/06/04 00:18:42 [INFO] memberlist: Marking d4fd90692e18 as failed, suspect timeout reached (0 peer confirmations)
    2017/06/04 00:18:42 [INFO] serf: EventMemberFailed: d4fd90692e18 127.0.0.1
    2017/06/04 00:18:43 [INFO] agent: Received event: member-failed
    2017/06/04 00:18:44 [INFO] memberlist: Suspect d4fd90692e18 has failed, no acks received
    2017/06/04 00:19:05 [INFO] serf: attempting reconnect to d4fd90692e18 127.0.0.1:7946
   ^C
</code>```

Resulted in failure to join as shown by:

```<code>$ docker exec serfDC2 serf members
6353e7f6134d  127.0.0.1:7946  alive
d4fd90692e18  127.0.0.1:7946  failed
$ docker exec serfDC1 serf members
d4fd90692e18  127.0.0.1:7946  alive
6353e7f6134d  127.0.0.1:7946  failed
</code>```

I have been at this for quite some time now and am at my wit's end as to where I should turn. Hashicorp's and Docker's documentation do not seem to cover this aspect of the initial handshake between two serf agents in different containers.

Could somebody show me where I took a wrong turn ? Any answer would be great, really. Tx.

答:
Serf nodes need to 'announce' themselves with a routable address. In your case they are telling to each other: 'hi, I'm localhost:...', so each one tries to answer to localhost, which is something wrong because each container has its own localhost.

There is an option to configure the agent to use the eth0 ip to advertise to the others nodes in the network: -iface. Then you need to discard the -bind option. Those ports are default so there is no need to customize.

So, for the node1:

```<code>serf agent -node=Node1 -iface=eth0
</code>```

And for the node2:

```<code>serf agent -node=Node2 -join=172.17.0.2 -iface=eth0
</code>```

From docs:

-iface - This flag can be used to provide a binding interface. It can be used instead of -bind if the interface is known but not the address.

It's working properly for me:

Node1:

```<code>==> Log data will now stream in as it occurs:

    2017/06/04 01:56:40 [INFO] agent: Serf agent starting
    2017/06/04 01:56:40 [INFO] serf: EventMemberJoin: Node1 172.17.0.2
    2017/06/04 01:56:41 [INFO] agent: Received event: member-join
    2017/06/04 01:57:02 [INFO] serf: EventMemberJoin: Node2 172.17.0.3
    2017/06/04 01:57:03 [INFO] agent: Received event: member-join
</code>```

Node2:

```<code>==> Log data will now stream in as it occurs:

    2017/06/04 01:57:02 [INFO] agent: Serf agent starting
    2017/06/04 01:57:02 [INFO] serf: EventMemberJoin: Node2 172.17.0.3
    2017/06/04 01:57:02 [INFO] agent: joining: [172.17.0.2] replay: false
    2017/06/04 01:57:02 [INFO] serf: EventMemberJoin: Node1 172.17.0.2
    2017/06/04 01:57:02 [INFO] agent: joined: 1 nodes
    2017/06/04 01:57:03 [INFO] agent: Received event: member-join
</code>```

Edit:

In the case that each container is in its own VM (EC2 instance), as each instance has its own docker network and not interconnected, you have to provide the EC2 instance IP and expose the corresponding ports. Use -advertise

-advertise - The advertise flag is used to change the address that we advertise to other nodes in the cluster.

Node1:

```<code>serf agent -node=Node1 -iface=eth0 -advertise=INSTANCE_IP
</code>```

Node2:

```<code>serf agent -node=Node2 -join=NODE1_INSTANCE_IP -iface=eth0
</code>```

And remember to expose the serf port in docker run

```<code>docker run -p 7946:7946 (...rest of the command...)
</code>```

Body:
Context: Host is AWS-EC2 / Ubuntu 14.04.5 with Docker version 17.05.0-ce. Containers are built from publicly available repo image cbhihe/serf-alpine-bash. All containers are located on the same EC2 instance and share the same default bridge network with net-interface "docker0".

Trying to join nodes serfDC1 (id d4fd90692e18) and serfDC2 (id 6353e7f6134d), by passing cmds from the host's shell:

$ docker exec serfDC1 serf agent -node=Node1 -bind=0.0.0.0:7946
==> Starting Serf agent…
==> Starting Serf agent RPC...
==> Serf agent running!
         Node name: 'd4fd90692e18'
         Bind addr: '0.0.0.0:7946'
          RPC addr: '127.0.0.1:7373'
         Encrypted: false
          Snapshot: false
           Profile: lan
==> Log data will now stream in as it occurs:
    2017/06/04 00:01:10 [INFO] agent: Serf agent starting
    2017/06/04 00:01:10 [INFO] serf: EventMemberJoin: d4fd90692e18 127.0.0.1
    2017/06/04 00:01:11 [INFO] agent: Received event: member-join
    ^C

After discovering Node1's container's IP=172.17.0.4, I can issue the serf agent -join cmd to Node2:

$ docker exec serfDC2 serf agent -node=Node2 -join=172.17.0.4
==> Starting Serf agent...
==> Starting Serf agent RPC...
==> Serf agent running!
         Node name: '6353e7f6134d'
         Bind addr: '0.0.0.0:7946'
          RPC addr: '127.0.0.1:7373'
         Encrypted: false
          Snapshot: false
           Profile: lan
==> Joining cluster...(replay: false)
    Join completed. Synced with 1 initial agents
==> Log data will now stream in as it occurs:
    2017/06/04 00:18:35 [INFO] agent: Serf agent starting
    2017/06/04 00:18:35 [INFO] serf: EventMemberJoin: 6353e7f6134d 127.0.0.1
    2017/06/04 00:18:35 [INFO] agent: joining: [172.17.0.4] replay: false
    2017/06/04 00:18:35 [INFO] serf: EventMemberJoin: d4fd90692e18 127.0.0.1
    2017/06/04 00:18:35 [INFO] agent: joined: 1 nodes
    2017/06/04 00:18:36 [WARN] memberlist: Got ping for unexpected node 'd4fd90692e18' from=127.0.0.1:7946
    2017/06/04 00:18:36 [INFO] agent: Received event: member-join
    2017/06/04 00:18:37 [WARN] memberlist: Got ping for unexpected node d4fd90692e18 from=127.0.0.1:34876
    2017/06/04 00:18:37 [ERR] memberlist: Failed TCP fallback ping: EOF
    2017/06/04 00:18:37 [INFO] memberlist: Suspect d4fd90692e18 has failed, no acks received
    2017/06/04 00:18:38 [WARN] memberlist: Got ping for unexpected node 'd4fd90692e18' from=127.0.0.1:7946
    2017/06/04 00:18:39 [WARN] memberlist: Got ping for unexpected node d4fd90692e18 from=127.0.0.1:34879
    2017/06/04 00:18:39 [ERR] memberlist: Failed TCP fallback ping: EOF
    2017/06/04 00:18:40 [INFO] memberlist: Suspect d4fd90692e18 has failed, no acks received
    2017/06/04 00:18:41 [WARN] memberlist: Got ping for unexpected node 'd4fd90692e18' from=127.0.0.1:7946
    2017/06/04 00:18:42 [WARN] memberlist: Got ping for unexpected node d4fd90692e18 from=127.0.0.1:34881
    2017/06/04 00:18:42 [ERR] memberlist: Failed TCP fallback ping: EOF
    2017/06/04 00:18:42 [INFO] memberlist: Marking d4fd90692e18 as failed, suspect timeout reached (0 peer confirmations)
    2017/06/04 00:18:42 [INFO] serf: EventMemberFailed: d4fd90692e18 127.0.0.1
    2017/06/04 00:18:43 [INFO] agent: Received event: member-failed
    2017/06/04 00:18:44 [INFO] memberlist: Suspect d4fd90692e18 has failed, no acks received
    2017/06/04 00:19:05 [INFO] serf: attempting reconnect to d4fd90692e18 127.0.0.1:7946
   ^C

Resulted in failure to join as shown by:

$ docker exec serfDC2 serf members
6353e7f6134d  127.0.0.1:7946  alive
d4fd90692e18  127.0.0.1:7946  failed
$ docker exec serfDC1 serf members
d4fd90692e18  127.0.0.1:7946  alive
6353e7f6134d  127.0.0.1:7946  failed

I have been at this for quite some time now and am at my wit's end as to where I should turn. Hashicorp's and Docker's documentation do not seem to cover this aspect of the initial handshake between two serf agents in different containers.

Could somebody show me where I took a wrong turn ? Any answer would be great, really. Tx.

Body:
Serf nodes need to 'announce' themselves with a routable address. In your case they are telling to each other: 'hi, I'm localhost:...', so each one tries to answer to localhost, which is something wrong because each container has its own localhost.

There is an option to configure the agent to use the eth0 ip to advertise to the others nodes in the network: -iface. Then you need to discard the -bind option. Those ports are default so there is no need to customize.

So, for the node1:

serf agent -node=Node1 -iface=eth0

And for the node2:

serf agent -node=Node2 -join=172.17.0.2 -iface=eth0

From docs:

-iface - This flag can be used to provide a binding interface. It can be used instead of -bind if the interface is known but not the address.

It's working properly for me:

Node1:

==> Log data will now stream in as it occurs:

    2017/06/04 01:56:40 [INFO] agent: Serf agent starting
    2017/06/04 01:56:40 [INFO] serf: EventMemberJoin: Node1 172.17.0.2
    2017/06/04 01:56:41 [INFO] agent: Received event: member-join
    2017/06/04 01:57:02 [INFO] serf: EventMemberJoin: Node2 172.17.0.3
    2017/06/04 01:57:03 [INFO] agent: Received event: member-join

Node2:

==> Log data will now stream in as it occurs:

    2017/06/04 01:57:02 [INFO] agent: Serf agent starting
    2017/06/04 01:57:02 [INFO] serf: EventMemberJoin: Node2 172.17.0.3
    2017/06/04 01:57:02 [INFO] agent: joining: [172.17.0.2] replay: false
    2017/06/04 01:57:02 [INFO] serf: EventMemberJoin: Node1 172.17.0.2
    2017/06/04 01:57:02 [INFO] agent: joined: 1 nodes
    2017/06/04 01:57:03 [INFO] agent: Received event: member-join

Edit:

In the case that each container is in its own VM (EC2 instance), as each instance has its own docker network and not interconnected, you have to provide the EC2 instance IP and expose the corresponding ports. Use -advertise

-advertise - The advertise flag is used to change the address that we advertise to other nodes in the cluster.

Node1:

serf agent -node=Node1 -iface=eth0 -advertise=INSTANCE_IP

Node2:

serf agent -node=Node2 -join=NODE1_INSTANCE_IP -iface=eth0

And remember to expose the serf port in docker run

docker run -p 7946:7946 (...rest of the command...)


问:
Flask minimalist API + XHR Ajax slow for no apparent reason
I really can't understand this situation. I tried as many web server as possible, from embedded one to tornado web server + nginx.

I've monitored my requests and here is the log:

WARNING:tornado.access:409 PUT /afficheur/article (127.0.0.1) 8.81ms

WARNING:tornado.access:409 GET /imprimante/tiroir (127.0.0.1) 1.38ms

Response time is pretty good so far. Troubles begin on my browser. Same result with Safari, Chrome and Firefox.

I use a web profiler bar to monitor XHR requests. Here are the results:

PUT  xhr 409 http://127.0.0.1:5000/afficheur/article 7ms n/a

GET  xhr 409 http://127.0.0.1:5000/imprimante/tiroir 162ms   n/a

Weird thing is that when using Chrome embedded developer tool for XHR req monitoring, response time is close to server answer time.

Can someone explain to me why imprimante/tiroir took 162ms with simple Ajax request when the server responded 1.38ms after hit.

I'm really confused with this. Something is most definitely happening on browser side, but I don't known what.

Note#1: I even tried to remove all treatment from server, nothing changed.

Note#2: HTTP 409 code is normal here. Same occurs with HTTP 200.

Note#3: .ajax request is asynchronous and does not have success handler nor error.

Thank!

EDIT:

ouvrir_tiroir = function () {
        $.ajax({
            url: 'http://127.0.0.1:5000/imprimante/tiroir',
            type: 'GET'
        });
    };```
<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></code>```

答:
WebProfiler bar does not display the XHR time but the surrounding function delay. (Could be multiple XHR requests, the profiler will sum up everything and assign it to the first XHR call). Be careful then.

Problem solved.


问:
Centered
 box colliding with left and right aligned
 boxes above
I've been making a project after learning HTML and CSS (haven't learned JavaScript yet, but I'm getting to it soon), and I've run into a slight problem.

I'm trying to have two div boxes (left and right aligned respectively, both 45% width), and then have a 45% width centered div box below it. It technically works, but the problem is while the centered div box is below the left and right boxes, only half of it is. The other half pours into the edges of the left and right boxes above.

This is what my HTML code looks like for these 3 boxes:

```<code>    <div class="left-align">
        <p class="medium-font">
            This box is <b>left-aligned</b>, so it'll be much less wide than other boxes.
        </p>
    </div>

    <div class="right-align">
        <p class="medium-font">
            This is box <b>right-aligned</b>, so it'll also be much less wide, however it's on the right now.
        </p>
    </div>

    <div class="center-align medium-font dotted-border bg-dkred">
        <form>
            <span>Form test thing i dunno</span>
            <p>Favorite gemstone:</p>
            <input type="text" name="fav-gem" value=""><br/>
        </form>
    </div>
</code>```

And my CSS code for the alignments:

```<code>div.right-align
{
    width:45%;
    float:right;
}

div.left-align
{
    width:45%;
    float:left;
}

div.center-align
{
    width:45%;
    margin:0 auto;
}
</code>```

I tried putting the two left and right boxes in their own  element, however that didn't make any difference.

Any help is appreciated, I can provide more info if you need it.

答:
Because you have float element, therefore it is ignored by 3rd div (the one below), just add clear: both to 3rd div to not allowed float element at both side of this element.

The clear CSS property specifies whether an element can be next to floating elements that precede it or must be moved down (cleared) below them. The clear property applies to both floating and non-floating elements.
  Example:

REF: https://developer.mozilla.org/en/docs/Web/CSS/clear

div.right-align {
  width: 45%;
  float: right;
  background: red;
}

div.left-align {
  width: 45%;
  float: left;
  background: aqua;
}

div.center-align {
  width: 45%;
  margin: 0 auto;
  background: green;
  clear: both;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="left-align">
  <p class="medium-font">
    This box is <b>left-aligned</b>, so it'll also be much less wide, however it's on the left now.
  </p>
</div>

<div class="right-align">
  <p class="medium-font">
    This is box <b>right-aligned</b>, so it'll also be much less wide, however it's on the right now.
  </p>
</div>

<div class="center-align medium-font dotted-border bg-dkred">
  <form>
    <span>Form test thing i dunno</span>
    <p>Favorite gemstone:</p>
    <input type="text" name="fav-gem" value=""><br/>
  </form>
</div></code>```

Title: Centered <div> box colliding with left and right aligned <div> boxes above

Body:
I've been making a project after learning HTML and CSS (haven't learned JavaScript yet, but I'm getting to it soon), and I've run into a slight problem.

I'm trying to have two div boxes (left and right aligned respectively, both 45% width), and then have a 45% width centered div box below it. It technically works, but the problem is while the centered div box is below the left and right boxes, only half of it is. The other half pours into the edges of the left and right boxes above.

This is what my HTML code looks like for these 3 boxes:

            This box is left-aligned, so it'll be much less wide than other boxes.

            This is box right-aligned, so it'll also be much less wide, however it's on the right now.

        <form>
            Form test thing i dunno

Favorite gemstone:

            <input type="text" name="fav-gem" value="">

        </form>

And my CSS code for the alignments:

div.right-align
{
    width:45%;
    float:right;
}

div.left-align
{
    width:45%;
    float:left;
}

div.center-align
{
    width:45%;
    margin:0 auto;
}

I tried putting the two left and right boxes in their own  element, however that didn't make any difference.

Any help is appreciated, I can provide more info if you need it.

Body:
Because you have float element, therefore it is ignored by 3rd div (the one below), just add clear: both to 3rd div to not allowed float element at both side of this element.

The clear CSS property specifies whether an element can be next to floating elements that precede it or must be moved down (cleared) below them. The clear property applies to both floating and non-floating elements.
  Example:

REF: https://developer.mozilla.org/en/docs/Web/CSS/clear

div.right-align {
  width: 45%;
  float: right;
  background: red;
}

div.left-align {
  width: 45%;
  float: left;
  background: aqua;
}

div.center-align {
  width: 45%;
  margin: 0 auto;
  background: green;
  clear: both;
}

<div class="left-align">
  <p class="medium-font">
    This box is <b>left-aligned</b>, so it'll also be much less wide, however it's on the left now.
  </p>
</div>

<div class="right-align">
  <p class="medium-font">
    This is box <b>right-aligned</b>, so it'll also be much less wide, however it's on the right now.
  </p>
</div>

<div class="center-align medium-font dotted-border bg-dkred">
  <form>
    <span>Form test thing i dunno</span>
    <p>Favorite gemstone:</p>
    <input type="text" name="fav-gem" value=""><br/>
  </form>
</div>


问:
Using a database to store configuration rather than a configuration file
Unfortunately searching for this kind of material produces a lot of noise for me so I was wondering if anyone here knew of a good resource for anyone wishing to learn how to use a database to store site configuration info rather than a file.

I guess some points I'm interested in are:
1) How to store the data. One array like e107? Separate row for each configurable?
2) How to get the configuration data. Global array?

答:
Your approach is very common for settings that users change through a web interface.

You might look at the way WordPress stores configuration in the database.


问:
How to open a file in a specified program using window comand prompt
How can I open a file from the command prompt in a specified program rather than the default program for opening the file.

like in MAC terminal

```<code>open main.js -a "Sublime Text"
</code>```

currently I only do

```<code>start filename.extension
</code>```

which opens the file in the default program.
please what command can I use to achieve this?

答:
With Windows, you type application first.

So with Notepad, which is on the Windows path, you can type

notepad filename.extension

By 'Windows Path' I mean a list of directories that Windows looks in for your application.  If your app is in one of those folders, then you only have to type the application name.  If your app isn't, then you need the full path to the application.

Most of the Windows native apps (like Notepad, MSPaint, etc) are automatically on the path.  However apps that are installed afterwards sometimes don't update the path and you need the full path.  You can usually get this by right-clicking on the application and getting properties.  Often you'll need quote marks - specifically if there are spaces in the path, which there usually are because "Program Files", so:

```<code>"C:\Program Files (x86)\Notepad++\notepad++.exe" filename.extension
</code>```

Note the quote marks go around the path to the application file itself - not all the way to the end of the line.  An easy way to check that you've got the full path to the file is with the dir command:

```<code>dir "C:\Program Files (x86)\Notepad++\notepad++.exe"
</code>```

Some applications expect instructions about what to do with the file, and you may need to figure out what else to put on the command line.  Usually google will tell you this.

For example, to execute an SQL script, with one tool I use, just putting the filename on the command line won't work, you do something like:

```<code>"C:\Program Files\PostgreSQL\9.4\bin\psql.exe" -U user -d dbName -f filename.extension
</code>```

Body:
How can I open a file from the command prompt in a specified program rather than the default program for opening the file.

like in MAC terminal

open main.js -a "Sublime Text"

currently I only do

start filename.extension

which opens the file in the default program.
please what command can I use to achieve this?

Body:
With Windows, you type application first.

So with Notepad, which is on the Windows path, you can type

notepad filename.extension

By 'Windows Path' I mean a list of directories that Windows looks in for your application.  If your app is in one of those folders, then you only have to type the application name.  If your app isn't, then you need the full path to the application.

Most of the Windows native apps (like Notepad, MSPaint, etc) are automatically on the path.  However apps that are installed afterwards sometimes don't update the path and you need the full path.  You can usually get this by right-clicking on the application and getting properties.  Often you'll need quote marks - specifically if there are spaces in the path, which there usually are because "Program Files", so:

"C:\Program Files (x86)\Notepad++\notepad++.exe" filename.extension

Note the quote marks go around the path to the application file itself - not all the way to the end of the line.  An easy way to check that you've got the full path to the file is with the dir command:

dir "C:\Program Files (x86)\Notepad++\notepad++.exe"

Some applications expect instructions about what to do with the file, and you may need to figure out what else to put on the command line.  Usually google will tell you this.

For example, to execute an SQL script, with one tool I use, just putting the filename on the command line won't work, you do something like:

"C:\Program Files\PostgreSQL\9.4\bin\psql.exe" -U user -d dbName -f filename.extension


问:
SQL count query - how to get desired results?
I have a factory that contains 4 production lines, work in a year which is devised into periods of year. I also have a working days and holidays table that contains these columns:

```<code>factory_id, mainline_id, year_id, period_id, holiday check
</code>```

Holiday check is a boolean column; it's true when the day is holiday, false when it's working day

I want to count all working days in a period of the year that belongs to specific mainline which is belong to specific factory

I tried

```<code>select count(holiday_check)
from myTable
where holiday_check = false
</code>```

but it returns all working days in all periods and all years for all factories

答:
Use the GROUP BY clause:

```<code>SELECT COUNT(*) FROM your_table
WHERE  holiday_check = false
GROUP BY period_id, factory_id, mainline_id
</code>```

Body:
I have a factory that contains 4 production lines, work in a year which is devised into periods of year. I also have a working days and holidays table that contains these columns:

factory_id, mainline_id, year_id, period_id, holiday check

Holiday check is a boolean column; it's true when the day is holiday, false when it's working day

I want to count all working days in a period of the year that belongs to specific mainline which is belong to specific factory

I tried

select count(holiday_check)
from myTable
where holiday_check = false

but it returns all working days in all periods and all years for all factories

Body:
Use the GROUP BY clause:

SELECT COUNT(*) FROM your_table
WHERE  holiday_check = false
GROUP BY period_id, factory_id, mainline_id


问:
How can I make sure the frame buffer has already been written before I fetch the FBO texture?
In Three.js RTT sample, the code is like this:

```<code>renderer.render( sceneRTT, cameraRTT, rtTexture, true );

// Render full screen quad with generated texture
renderer.render( sceneScreen, cameraRTT );
</code>```

How to make sure the rtTexture has been written before actually fetching the rtTexture data in renderer.render( sceneScreen, cameraRTT );?

答:
You don't need to check. It will be rendered to before you fetch it. WebGL like all OpenGL happens sequentially. From the spec

Chapter 2

OpenGL ES Operation

2.1 OpenGL ES Fundamentals

...

Commands are always processed in the order in which they are received, although there may be an indeterminate delay before the effects of a command are
realized. This means, for example, that one primitive must be drawn completely before any subsequent one can affect the framebuffer. It also means that queries and pixel read operations return state consistent with complete execution of all previously invoked GL commands. In general, the effects of a GL command on either GL modes or the framebuffer must be complete before any subsequent command
can have any such effects.

This same paragraph is also in the OpenGL spec

Body:
In Three.js RTT sample, the code is like this:

renderer.render( sceneRTT, cameraRTT, rtTexture, true );

// Render full screen quad with generated texture
renderer.render( sceneScreen, cameraRTT );

How to make sure the rtTexture has been written before actually fetching the rtTexture data in renderer.render( sceneScreen, cameraRTT );?


问:
MariaDB Galera Cluster set up problems
I am trying to get a mariadb cluster up and running but it is not working out for me. Right now I am using MariaDB Galera 5.5.36 on a 64 bit red hat ES6 machine. I installed mariadb through this repo here:

```<code>[mariadb]
name = MariaDB
baseurl = http://yum.mariadb.org/5.5-galera/rhel6-amd64/
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=1
</code>```

In the server.conf I have the following in server 1:

```<code>[mariadb]
log_error=/var/log/mariadb.log
query_cache_size=0
query_cache_type=0
binlog_format=ROW
default_storage_engine=innodb
innodb_autoinc_lock_mode=2
wsrep_provider=/usr/lib64/galera/libgalera_smm.so
wsrep_cluster_address=gcomm://192.168.211.133
wsrep_cluster_name='cluster'
wsrep_node_address='192.168.211.132'
wsrep_node_name='cluster1'
wsrep_sst_method=rsync
</code>```

and on server 2 I have

```<code>[mariadb]
log_error=/var/log/mariadb.log
query_cache_size=0
query_cache_type=0
binlog_format=ROW
default_storage_engine=innodb
innodb_autoinc_lock_mode=2
wsrep_provider=/usr/lib64/galera/libgalera_smm.so
wsrep_cluster_address=gcomm://192.168.211.132
wsrep_cluster_name='cluster'
wsrep_node_address='192.168.211.133'
wsrep_node_name='cluster2'
wsrep_sst_method=rsync
</code>```

When I start server 1 with the following command: sudo service mysql start --wsrep-new-cluster it starts up just fine, if I open up mysql and check the status of wsrep it says everything is up and running which is good but when I try to do sudo service mysql start on the second server I get the following in the error logs:

```<code>140609 14:47:55 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
140609 14:47:56 mysqld_safe WSREP: Running position recovery with --log_error='/var/lib/mysql/wsrep_recovery.i5qfm2' --pid-file='/var/lib/mysql/localhost.localdomain-recover.pid'
140609 14:47:57 mysqld_safe WSREP: Recovered position 85448d73-ebe8-11e3-9c20-fbc1995fee11:0
140609 14:47:57 [Note] WSREP: wsrep_start_position var submitted: '85448d73-ebe8-11e3-9c20-fbc1995fee11:0'
140609 14:47:57 [Note] WSREP: Read nil XID from storage engines, skipping position init
140609 14:47:57 [Note] WSREP: wsrep_load(): loading provider library '/usr/lib64/galera/libgalera_smm.so'
140609 14:47:57 [Note] WSREP: wsrep_load(): Galera 25.3.2(r170) by Codership Oy <info@codership.com> loaded successfully.
140609 14:47:57 [Note] WSREP: CRC-32C: using hardware acceleration.
140609 14:47:57 [Note] WSREP: Found saved state: 85448d73-ebe8-11e3-9c20-fbc1995fee11:-1
140609 14:47:57 [Note] WSREP: Passing config to GCS: base_host = 192.168.211.133; base_port = 4567; cert.log_conflicts = no; gcache.dir = /var/lib/mysql/; gcache.keep_pages_size = 0; gcache.mem_size = 0; gcache.name = /var/lib/mysql//galera.cache; gcache.page_size = 128M; gcache.size = 128M; gcs.fc_debug = 0; gcs.fc_factor = 1; gcs.fc_limit = 16; gcs.fc_master_slave = NO; gcs.max_packet_size = 64500; gcs.max_throttle = 0.25; gcs.recv_q_hard_limit = 9223372036854775807; gcs.recv_q_soft_limit = 0.25; gcs.sync_donor = NO; repl.causal_read_timeout = PT30S; repl.commit_order = 3; repl.key_format = FLAT8; repl.proto_max = 5
140609 14:47:57 [Note] WSREP: Assign initial position for certification: 0, protocol version: -1
140609 14:47:57 [Note] WSREP: wsrep_sst_grab()
140609 14:47:57 [Note] WSREP: Start replication
140609 14:47:57 [Note] WSREP: Setting initial position to 85448d73-ebe8-11e3-9c20-fbc1995fee11:0
140609 14:47:57 [Note] WSREP: protonet asio version 0
140609 14:47:57 [Note] WSREP: Using CRC-32C (optimized) for message checksums.
140609 14:47:57 [Note] WSREP: backend: asio
140609 14:47:57 [Note] WSREP: GMCast version 0
140609 14:47:57 [Note] WSREP: (0c085f34-efe5-11e3-9f6b-8bfd1706e2a4, 'tcp://0.0.0.0:4567') listening at tcp://0.0.0.0:4567
140609 14:47:57 [Note] WSREP: (0c085f34-efe5-11e3-9f6b-8bfd1706e2a4, 'tcp://0.0.0.0:4567') multicast: , ttl: 1
140609 14:47:57 [Note] WSREP: EVS version 0
140609 14:47:57 [Note] WSREP: PC version 0
140609 14:47:57 [Note] WSREP: gcomm: connecting to group 'cluster', peer '192.168.211.132:,192.168.211.134:'
140609 14:48:00 [Warning] WSREP: no nodes coming from prim view, prim not possible
140609 14:48:00 [Note] WSREP: view(view_id(NON_PRIM,0c085f34-efe5-11e3-9f6b-8bfd1706e2a4,1) memb {
        0c085f34-efe5-11e3-9f6b-8bfd1706e2a4,0
} joined {
} left {
} partitioned {
})
140609 14:48:01 [Warning] WSREP: last inactive check more than PT1.5S ago (PT3.50775S), skipping check
140609 14:48:31 [Note] WSREP: view((empty))
140609 14:48:31 [ERROR] WSREP: failed to open gcomm backend connection: 110: failed to reach primary view: 110 (Connection timed out)
         at gcomm/src/pc.cpp:connect():141
140609 14:48:31 [ERROR] WSREP: gcs/src/gcs_core.c:gcs_core_open():196: Failed to open backend connection: -110 (Connection timed out)
140609 14:48:31 [ERROR] WSREP: gcs/src/gcs.c:gcs_open():1291: Failed to open channel 'cluster' at 'gcomm://192.168.211.132,192.168.211.134': -110 (Connection timed out)
140609 14:48:31 [ERROR] WSREP: gcs connect failed: Connection timed out
140609 14:48:31 [ERROR] WSREP: wsrep::connect() failed: 7
140609 14:48:31 [ERROR] Aborting

140609 14:48:31 [Note] WSREP: Service disconnected.
140609 14:48:32 [Note] WSREP: Some threads may fail to exit.
140609 14:48:32 [Note] /usr/sbin/mysqld: Shutdown complete

140609 14:48:32 mysqld_safe mysqld from pid file /var/lib/mysql/localhost.localdomain.pid ended
</code>```

I am at a loss as to why the second server cannot detect that a cluster is up and running. These machines can communicate with each other just fine, I can SSH from one to the other and they can ping each other. I tried deleted the galera cache, tried downgrading my version of mariadb galera, tried disabling SELinux, tried running the mysql service as a different user, verified that the correct ports are open, tried running them on 2 VMs on separate computers with different IP addresses, etc. Does anyone have any idea what is going on here because I have been searching for 3 days trying to fix this but no solution seems to work with me.

答:
The cluster must start with this command on primary node:

```<code>galera_new_cluster
</code>```

after starting first node, you can start other nodes in the cluster successfully.

Title: MariaDB Galera Cluster set up problems

Body:
I am trying to get a mariadb cluster up and running but it is not working out for me. Right now I am using MariaDB Galera 5.5.36 on a 64 bit red hat ES6 machine. I installed mariadb through this repo here:

[mariadb]
name = MariaDB
baseurl = http://yum.mariadb.org/5.5-galera/rhel6-amd64/
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=1

In the server.conf I have the following in server 1:

[mariadb]
log_error=/var/log/mariadb.log
query_cache_size=0
query_cache_type=0
binlog_format=ROW
default_storage_engine=innodb
innodb_autoinc_lock_mode=2
wsrep_provider=/usr/lib64/galera/libgalera_smm.so
wsrep_cluster_address=gcomm://192.168.211.133
wsrep_cluster_name='cluster'
wsrep_node_address='192.168.211.132'
wsrep_node_name='cluster1'
wsrep_sst_method=rsync

and on server 2 I have

[mariadb]
log_error=/var/log/mariadb.log
query_cache_size=0
query_cache_type=0
binlog_format=ROW
default_storage_engine=innodb
innodb_autoinc_lock_mode=2
wsrep_provider=/usr/lib64/galera/libgalera_smm.so
wsrep_cluster_address=gcomm://192.168.211.132
wsrep_cluster_name='cluster'
wsrep_node_address='192.168.211.133'
wsrep_node_name='cluster2'
wsrep_sst_method=rsync

When I start server 1 with the following command: sudo service mysql start --wsrep-new-cluster it starts up just fine, if I open up mysql and check the status of wsrep it says everything is up and running which is good but when I try to do sudo service mysql start on the second server I get the following in the error logs:

140609 14:47:55 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
140609 14:47:56 mysqld_safe WSREP: Running position recovery with --log_error='/var/lib/mysql/wsrep_recovery.i5qfm2' --pid-file='/var/lib/mysql/localhost.localdomain-recover.pid'
140609 14:47:57 mysqld_safe WSREP: Recovered position 85448d73-ebe8-11e3-9c20-fbc1995fee11:0
140609 14:47:57 [Note] WSREP: wsrep_start_position var submitted: '85448d73-ebe8-11e3-9c20-fbc1995fee11:0'
140609 14:47:57 [Note] WSREP: Read nil XID from storage engines, skipping position init
140609 14:47:57 [Note] WSREP: wsrep_load(): loading provider library '/usr/lib64/galera/libgalera_smm.so'
140609 14:47:57 [Note] WSREP: wsrep_load(): Galera 25.3.2(r170) by Codership Oy <info@codership.com> loaded successfully.
140609 14:47:57 [Note] WSREP: CRC-32C: using hardware acceleration.
140609 14:47:57 [Note] WSREP: Found saved state: 85448d73-ebe8-11e3-9c20-fbc1995fee11:-1
140609 14:47:57 [Note] WSREP: Passing config to GCS: base_host = 192.168.211.133; base_port = 4567; cert.log_conflicts = no; gcache.dir = /var/lib/mysql/; gcache.keep_pages_size = 0; gcache.mem_size = 0; gcache.name = /var/lib/mysql//galera.cache; gcache.page_size = 128M; gcache.size = 128M; gcs.fc_debug = 0; gcs.fc_factor = 1; gcs.fc_limit = 16; gcs.fc_master_slave = NO; gcs.max_packet_size = 64500; gcs.max_throttle = 0.25; gcs.recv_q_hard_limit = 9223372036854775807; gcs.recv_q_soft_limit = 0.25; gcs.sync_donor = NO; repl.causal_read_timeout = PT30S; repl.commit_order = 3; repl.key_format = FLAT8; repl.proto_max = 5
140609 14:47:57 [Note] WSREP: Assign initial position for certification: 0, protocol version: -1
140609 14:47:57 [Note] WSREP: wsrep_sst_grab()
140609 14:47:57 [Note] WSREP: Start replication
140609 14:47:57 [Note] WSREP: Setting initial position to 85448d73-ebe8-11e3-9c20-fbc1995fee11:0
140609 14:47:57 [Note] WSREP: protonet asio version 0
140609 14:47:57 [Note] WSREP: Using CRC-32C (optimized) for message checksums.
140609 14:47:57 [Note] WSREP: backend: asio
140609 14:47:57 [Note] WSREP: GMCast version 0
140609 14:47:57 [Note] WSREP: (0c085f34-efe5-11e3-9f6b-8bfd1706e2a4, 'tcp://0.0.0.0:4567') listening at tcp://0.0.0.0:4567
140609 14:47:57 [Note] WSREP: (0c085f34-efe5-11e3-9f6b-8bfd1706e2a4, 'tcp://0.0.0.0:4567') multicast: , ttl: 1
140609 14:47:57 [Note] WSREP: EVS version 0
140609 14:47:57 [Note] WSREP: PC version 0
140609 14:47:57 [Note] WSREP: gcomm: connecting to group 'cluster', peer '192.168.211.132:,192.168.211.134:'
140609 14:48:00 [Warning] WSREP: no nodes coming from prim view, prim not possible
140609 14:48:00 [Note] WSREP: view(view_id(NON_PRIM,0c085f34-efe5-11e3-9f6b-8bfd1706e2a4,1) memb {
        0c085f34-efe5-11e3-9f6b-8bfd1706e2a4,0
} joined {
} left {
} partitioned {
})
140609 14:48:01 [Warning] WSREP: last inactive check more than PT1.5S ago (PT3.50775S), skipping check
140609 14:48:31 [Note] WSREP: view((empty))
140609 14:48:31 [ERROR] WSREP: failed to open gcomm backend connection: 110: failed to reach primary view: 110 (Connection timed out)
         at gcomm/src/pc.cpp:connect():141
140609 14:48:31 [ERROR] WSREP: gcs/src/gcs_core.c:gcs_core_open():196: Failed to open backend connection: -110 (Connection timed out)
140609 14:48:31 [ERROR] WSREP: gcs/src/gcs.c:gcs_open():1291: Failed to open channel 'cluster' at 'gcomm://192.168.211.132,192.168.211.134': -110 (Connection timed out)
140609 14:48:31 [ERROR] WSREP: gcs connect failed: Connection timed out
140609 14:48:31 [ERROR] WSREP: wsrep::connect() failed: 7
140609 14:48:31 [ERROR] Aborting

140609 14:48:31 [Note] WSREP: Service disconnected.
140609 14:48:32 [Note] WSREP: Some threads may fail to exit.
140609 14:48:32 [Note] /usr/sbin/mysqld: Shutdown complete

140609 14:48:32 mysqld_safe mysqld from pid file /var/lib/mysql/localhost.localdomain.pid ended

I am at a loss as to why the second server cannot detect that a cluster is up and running. These machines can communicate with each other just fine, I can SSH from one to the other and they can ping each other. I tried deleted the galera cache, tried downgrading my version of mariadb galera, tried disabling SELinux, tried running the mysql service as a different user, verified that the correct ports are open, tried running them on 2 VMs on separate computers with different IP addresses, etc. Does anyone have any idea what is going on here because I have been searching for 3 days trying to fix this but no solution seems to work with me.

Body:
The cluster must start with this command on primary node:

galera_new_cluster

after starting first node, you can start other nodes in the cluster successfully.

ContentLicense: CC BY-SA 4.0


问:
Is it possible to grant permission for groups (in SharePoint) to a site programmatically?
I am using the SharePoint Object Model to create new sites programmatically (with a custom web part). It works fine but I am wondering if it is possible to grant permission for groups as well?

When I create the site I have set it to not inherit permission

```<code>newWeb = SPContext.GetContext(HttpContext.Current).Web.Webs.Add(siteUrl, siteName, siteDescription, (uint)1033, siteTemplate, true, false);
</code>```

In the GUI I can then go to Site Actions (on the newly created site) -> Grant Permission -> search for groups in the parent site and then grant permission for this group. So, in the parent site myGroup can have Full Access permissions but in this site I can set it to Contribution or whatever. Is it possible to do this when I create the site or just after (programmatically)?

Thanks in advance.

答:
You must assign a role definition to your group.

Here's a code snippet I wrote to assign a group one of the predefined sharepoint role definitions.

```<code>public bool AssignExistingGroupToWeb(SPWeb siteWeb, string GroupName, SPRoleDefinition roleDefinition)
{
//retrieve a group
SPGroup siteGroup = siteWeb.SiteGroups.FindGroupByName(GroupName);

//create a role assignment for the group using the specified SPRoleDefinition
//examples of roles as "Full Control", "Design", etc...
SPRoleAssignment roleAssignment = new SPRoleAssignment(siteGroup);
roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
siteWeb.RoleAssignments.Add(roleAssignment);
siteWeb.Update();
}
</code>```

You can retrieve a SPRoleDefinition by accessing the RoleDefinitions collection, like so...

```<code>siteWeb.RoleDefinitions["Contribute"]
</code>```

Body:
I am using the SharePoint Object Model to create new sites programmatically (with a custom web part). It works fine but I am wondering if it is possible to grant permission for groups as well?

When I create the site I have set it to not inherit permission

newWeb = SPContext.GetContext(HttpContext.Current).Web.Webs.Add(siteUrl, siteName, siteDescription, (uint)1033, siteTemplate, true, false);

In the GUI I can then go to Site Actions (on the newly created site) -> Grant Permission -> search for groups in the parent site and then grant permission for this group. So, in the parent site myGroup can have Full Access permissions but in this site I can set it to Contribution or whatever. Is it possible to do this when I create the site or just after (programmatically)?

Thanks in advance.

Body:
You must assign a role definition to your group.

Here's a code snippet I wrote to assign a group one of the predefined sharepoint role definitions.

public bool AssignExistingGroupToWeb(SPWeb siteWeb, string GroupName, SPRoleDefinition roleDefinition)
{
//retrieve a group
SPGroup siteGroup = siteWeb.SiteGroups.FindGroupByName(GroupName);

//create a role assignment for the group using the specified SPRoleDefinition
//examples of roles as "Full Control", "Design", etc...
SPRoleAssignment roleAssignment = new SPRoleAssignment(siteGroup);
roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
siteWeb.RoleAssignments.Add(roleAssignment);
siteWeb.Update();
}

You can retrieve a SPRoleDefinition by accessing the RoleDefinitions collection, like so...

siteWeb.RoleDefinitions["Contribute"]


问:
Android studio path error
I'm getting this error:

```<code>Config path'C:\Program Files(x86)\Android\android-studio\config' is invalid.
If you have modified the 'idea.config.path' property please make sure it is correct,
otherwise please re-install the IDE.
</code>```

I even re-installed the IDE, however, it doesn't work!

How to resolve this error?

答: I had this issue and the reason for my issue was my hard disk has run out of free space (installing new android versions had filled up my hard disk without me knowing :) ) . cleaning up the hard and getting some free space fixed my issue</p>

Title: Android studio path error

Body:
I'm getting this error:

Config path'C:\Program Files(x86)\Android\android-studio\config' is invalid.
If you have modified the 'idea.config.path' property please make sure it is correct,
otherwise please re-install the IDE.

I even re-installed the IDE, however, it doesn't work!

How to resolve this error?