问:
How to maintain transaction handling executing two stored procedure from C# code
I one method in my class Which executing two stored procedure and insert data into three tables. How to handle transaction in that case?

For Example:

```<code>public class InsertClass
{
   public void AddData()
   {
       try
       {
           Execute Sp1;
           Execute Sp2;
       }
       catch (Exception ex)
       {
           throw ex;
       }
   }
}
</code>```

Both SP are for insert.

答:
Try this code:</p>

```<code>connection.Open();
SqlTransaction transaction = connection.BeginTransaction();

try
       {
           Execute Sp1;
           Execute Sp2;
       }
       catch (Exception)
       {
           transaction.Rollback();
           connection.Close();
       }

       transaction.Commit();
</code>```

Body:
I one method in my class Which executing two stored procedure and insert data into three tables. How to handle transaction in that case?

For Example:

public class InsertClass
{
   public void AddData()
   {
       try
       {
           Execute Sp1;
           Execute Sp2;
       }
       catch (Exception ex)
       {
           throw ex;
       }
   }
}

Both SP are for insert.

Body:
Try this code:

connection.Open();
SqlTransaction transaction = connection.BeginTransaction();

try
       {
           Execute Sp1;
           Execute Sp2;
       }
       catch (Exception)
       {
           transaction.Rollback();
           connection.Close();
       }

       transaction.Commit();


来源: stackexchange

问:
Set unchangeable some part of editText android
I have some EditText for mobile number input. App must add unique text for every country. For example for Armenia is must add +374 , and user must fill other numbers. Also +374 must be unchangeable, user can't change or remove it. So is there some kind of ways for doing this?

EDIT:

I don't want to use textView or another view with this text and put it left of the ediText. I want to find some way with less operations. I need text to be frozen not to check every text changes or add missing text when user will delete some part of it.

答:
you can create class extend AppCompatEditText or EditText.

```<code>public class CEditTextMaster extends AppCompatEditText {

        private boolean isNeedNoChangeSomeCharacters;
        private String charactersNoChange;

        public CEditTextMaster(Context context) {
            super(context);
            init(context, null);
        }

        public CEditTextMaster(Context context, AttributeSet attrs) {
            super(context, attrs);
            init(context, attrs);
        }

        public CEditTextMaster(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            init(context, attrs);
        }

        public void init(Context context, @Nullable AttributeSet attrs) {

            if (isInEditMode())
                return;

            addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    if (isNeedNoChangeSomeCharacters && charactersNoChange != null) {
                        if (!getText().toString().startsWith(charactersNoChange)) {
                            removeTextChangedListener(this);
                            if (charactersNoChange.length() > s.length()) {
                                setText(charactersNoChange);
                            } else {
                                setText(charactersNoChange + getText());
                            }
                            setSelection(getText().toString().length());
                            addTextChangedListener(this);
                        }
                    }
                }
            });

        }

        @Override
        protected void onSelectionChanged(int selStart, int selEnd) {
            if (isNeedNoChangeSomeCharacters && charactersNoChange != null) {
                if (length() > charactersNoChange.length() && selStart < charactersNoChange.length()) {
                    setSelection(charactersNoChange.length(),selEnd);
                }
            }
        }

        @Override
        public void setText(CharSequence text, BufferType type) {
            super.setText(text, type);
            if (isNeedNoChangeSomeCharacters && charactersNoChange != null) {
                if (!getText().toString().trim().startsWith(charactersNoChange)) {
                    setText(charactersNoChange + getText());
                }
            }
        }

        public void setCharactersNoChangeInitial(String charactersNoChange) {
            isNeedNoChangeSomeCharacters = true;
            this.charactersNoChange = charactersNoChange;
            if (!getText().toString().trim().startsWith(charactersNoChange)) {
                setText(getText());
            }
        }

}
</code>```

for use:

```<code>edt.setCharactersNoChangeInitial("+734 ");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
you can create class extend AppCompatEditText or EditText.

public class CEditTextMaster extends AppCompatEditText {

        private boolean isNeedNoChangeSomeCharacters;
        private String charactersNoChange;

        public CEditTextMaster(Context context) {
            super(context);
            init(context, null);
        }

        public CEditTextMaster(Context context, AttributeSet attrs) {
            super(context, attrs);
            init(context, attrs);
        }

        public CEditTextMaster(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            init(context, attrs);
        }

        public void init(Context context, @Nullable AttributeSet attrs) {

            if (isInEditMode())
                return;

            addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    if (isNeedNoChangeSomeCharacters && charactersNoChange != null) {
                        if (!getText().toString().startsWith(charactersNoChange)) {
                            removeTextChangedListener(this);
                            if (charactersNoChange.length() > s.length()) {
                                setText(charactersNoChange);
                            } else {
                                setText(charactersNoChange + getText());
                            }
                            setSelection(getText().toString().length());
                            addTextChangedListener(this);
                        }
                    }
                }
            });

        }

        @Override
        protected void onSelectionChanged(int selStart, int selEnd) {
            if (isNeedNoChangeSomeCharacters && charactersNoChange != null) {
                if (length() > charactersNoChange.length() && selStart < charactersNoChange.length()) {
                    setSelection(charactersNoChange.length(),selEnd);
                }
            }
        }

        @Override
        public void setText(CharSequence text, BufferType type) {
            super.setText(text, type);
            if (isNeedNoChangeSomeCharacters && charactersNoChange != null) {
                if (!getText().toString().trim().startsWith(charactersNoChange)) {
                    setText(charactersNoChange + getText());
                }
            }
        }

        public void setCharactersNoChangeInitial(String charactersNoChange) {
            isNeedNoChangeSomeCharacters = true;
            this.charactersNoChange = charactersNoChange;
            if (!getText().toString().trim().startsWith(charactersNoChange)) {
                setText(getText());
            }
        }

}

for use:

edt.setCharactersNoChangeInitial("+734 ");

ContentLicense: CC BY-SA 4.0


问:
Css Table-cell and relative width
I'm struggling with a CSS issue and I was hoping for some help.

Here's the story:

I'm designing a header. It's split in two divs. First one must be 70% wide and second one 30% wide. I used the css-property "Display: table-cell" in order to place them side by side.

```<code>div.chapo {
width: 70%;
display: table-cell;
}

div.img_header {
width: 30%;
display: table-cell;
background-position: center center;
background-repeat: no-repeat;
background-size: cover;
-webkit-background-size: cover;
background-image: url(...);
}
</code>```

It's working fine when the text placed in the first div is long enough:

Buuuut... when text is short, it's all messy:

I can't figure out why my widths values aren't kept in this specific case.

Thanks in advance for all who would be kind enough to help me...

Here's the fiddle link: https://jsfiddle.net/vinny38/verucw8p/3/

答:
This CSS it's ok... the 'float:left' option and relative width are different.
 Here, I disccount the paddings left and right of total width. The float is necessary to horizontal align.</p>

```<code>body,
div {
  margin: 0;
  padding: 0;
  font-family: 'Roboto condensed', sans-serif;

}

div.inside {
  position: relative;
}

div.chapo {
      background-image: none;
    width: 50%;
    height: 255px;
    vertical-align: top;
    background-color: #aaa;
    color: #fff;
    padding: 20px 10%;
    position: relative;
    float: left;

}

h1 {
  margin-top: 0;
  font: 1.4em 'Oswald', Helvetica, sans-serif;
  font-weight: bold;
  text-transform: uppercase;
}

div.chapo p {
  width: 100%;
  position: relative;
  padding: 0;
  font-size: 1em;
  font-weight: 300;
}

div.img_header {
     width: 30%;
    position: relative;
    height: 295px;
    vertical-align: top;
    background-position: center center;
    background-repeat: no-repeat;
    background-size: cover;
    float: left;
    -webkit-background-size: cover;
    background-image: url(https://image.freepik.com/free-psd/abstract-background-design_1297-73.jpg);
}

div.mod_breadcrumb {
  height: 40px;
  margin: 0;
  padding-top: 5px;
  padding-right: 2%;
  padding-bottom: 5px;
  background-color: #e3e3e3;
  padding-left: 8%;
  float:left;
  width:90%;
}

.mod_breadcrumb ul li {
  height: 30px;
  display: inline-block;
  padding: 3px 0;
  color: #828282;

}
</code>```

Title: Css Table-cell and relative width

Body:
I'm struggling with a CSS issue and I was hoping for some help.

Here's the story:

I'm designing a header. It's split in two divs. First one must be 70% wide and second one 30% wide. I used the css-property "Display: table-cell" in order to place them side by side.

div.chapo {
width: 70%;
display: table-cell;
}

div.img_header {
width: 30%;
display: table-cell;
background-position: center center;
background-repeat: no-repeat;
background-size: cover;
-webkit-background-size: cover;
background-image: url(...);
}

It's working fine when the text placed in the first div is long enough:

Buuuut... when text is short, it's all messy:

I can't figure out why my widths values aren't kept in this specific case.

Thanks in advance for all who would be kind enough to help me...

Here's the fiddle link: https://jsfiddle.net/vinny38/verucw8p/3/

Body:
This CSS it's ok... the 'float:left' option and relative width are different.
 Here, I disccount the paddings left and right of total width. The float is necessary to horizontal align.

body,
div {
  margin: 0;
  padding: 0;
  font-family: 'Roboto condensed', sans-serif;

}

div.inside {
  position: relative;
}

div.chapo {
      background-image: none;
    width: 50%;
    height: 255px;
    vertical-align: top;
    background-color: #aaa;
    color: #fff;
    padding: 20px 10%;
    position: relative;
    float: left;

}

h1 {
  margin-top: 0;
  font: 1.4em 'Oswald', Helvetica, sans-serif;
  font-weight: bold;
  text-transform: uppercase;
}

div.chapo p {
  width: 100%;
  position: relative;
  padding: 0;
  font-size: 1em;
  font-weight: 300;
}

div.img_header {
     width: 30%;
    position: relative;
    height: 295px;
    vertical-align: top;
    background-position: center center;
    background-repeat: no-repeat;
    background-size: cover;
    float: left;
    -webkit-background-size: cover;
    background-image: url(https://image.freepik.com/free-psd/abstract-background-design_1297-73.jpg);
}

div.mod_breadcrumb {
  height: 40px;
  margin: 0;
  padding-top: 5px;
  padding-right: 2%;
  padding-bottom: 5px;
  background-color: #e3e3e3;
  padding-left: 8%;
  float:left;
  width:90%;
}

.mod_breadcrumb ul li {
  height: 30px;
  display: inline-block;
  padding: 3px 0;
  color: #828282;

}


问:
Download the place's website and priceLevel (Google places, Swift)
I created this class

```<code>import UIKit
import CoreLocation

private let geometryKey = "geometry"
private let locationKey = "location"
private let latitudeKey = "lat"
private let longitudeKey = "lng"
private let nameKey = "name"
private let openingHoursKey = "opening_hours"
private let openNowKey = "open_now"
private let vicinityKey = "vicinity"
private let typesKey = "types"
private let photosKey = "photos"
private let phoneNumberKey = "phoneNumber"
private let ratingKey = "rating"
private let priceLevelKey = "priceLevel"
private let websiteKey = "website"

class QPlace: NSObject  {

    var location: CLLocationCoordinate2D?
    var name: String?
    var photos: [QPhoto]?
    var vicinity: String?
    var isOpen: Bool?
    var types: [String]?
    var rating: Float?
    var priceLevel: Int?
    var website: String?

    init(placeInfo:[String: Any]) {
        // coordinates
        if let g = placeInfo[geometryKey] as? [String:Any] {
            if let l = g[locationKey] as? [String:Double] {
                if let lat = l[latitudeKey], let lng = l[longitudeKey] {
                    location = CLLocationCoordinate2D.init(latitude: lat, longitude: lng)
                }
            }
        }

        // name
        name = placeInfo[nameKey] as? String

        // opening hours
        if let oh = placeInfo[openingHoursKey] as? [String:Any] {
            if let on = oh[openNowKey] as? Bool {
                isOpen = on
            }
        }

        // vicinity
        vicinity = placeInfo[vicinityKey] as? String

        // types
        types = placeInfo[typesKey] as? [String]

        // rating
        rating = placeInfo[ratingKey] as? Float

        //priceLevel
        priceLevel = placeInfo[priceLevelKey] as? Int

        website = placeInfo[websiteKey] as? String

        // photos
        photos = [QPhoto]()
        if let ps = placeInfo[photosKey] as? [[String:Any]] {
            for p in ps {
                photos?.append(QPhoto.init(photoInfo: p))
            }
        }
    }

    func getDescription() -> String {

        var s : [String] = []

        if let types = types {
            s.append("\(types.joined(separator: ", "))")
        }

        if let rating = rating {
            s.append("Rating: \(rating)")
        }

        if let priceLevel = priceLevel {
            s.append("PriceLevel: \(priceLevel)")
        }

        if let website = website {
            s.append("\(website)")
        }

         if let isOpen = isOpen {
            s.append(isOpen ? "OPEN NOW" : "CLOSED NOW")
        }

        if let vicinity = vicinity {
            s.append("\(vicinity)")
        }
        return s.joined(separator: "\n")
    }

 func heightForComment(_ font: UIFont, width: CGFloat) -> CGFloat {
        let desc = getDescription()
        let rect = NSString(string: desc).boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
        return ceil(rect.height)
    }

}
</code>```

to get the place's details that i'll show in a VC of my application by calling this function   func getDescription() -> String { } but my problem and i don't know why (because i follow the documentation of google places API) is that the website and also the price level not working, so when in the viewController i call the function getDescription() it load all place's details which i added in that function, but not the website and the price level. What i did wrong? How can i adjust it?

UPDATE

https://developers.google.com/places/ios-api/place-details

```<code>static func getNearbyPlaces(by category:String, coordinates:CLLocationCoordinate2D, radius:Int, token: String?, completion: @escaping (QNearbyPlacesResponse?, Error?) -> Void) {

        var params : [String : Any]

        if let t = token {
            params = [
                "key" : AppDelegate.googlePlacesAPIKey,
                "pagetoken" : t,
            ]
        } else {
            params = [
                "key" : AppDelegate.googlePlacesAPIKey,
                "radius" : radius,
                "location" : "\(coordinates.latitude),\(coordinates.longitude)",
                "type" : category.lowercased()
            ]
        }
</code>```

答:
As per the Google Places API:

The key for price level is price_level but you have used priceLevel which might be why you are not seeing the prices

As for website I think it could be case that there is no data available for the property you have selected.

Body:
I created this class

import UIKit
import CoreLocation

private let geometryKey = "geometry"
private let locationKey = "location"
private let latitudeKey = "lat"
private let longitudeKey = "lng"
private let nameKey = "name"
private let openingHoursKey = "opening_hours"
private let openNowKey = "open_now"
private let vicinityKey = "vicinity"
private let typesKey = "types"
private let photosKey = "photos"
private let phoneNumberKey = "phoneNumber"
private let ratingKey = "rating"
private let priceLevelKey = "priceLevel"
private let websiteKey = "website"

class QPlace: NSObject  {

    var location: CLLocationCoordinate2D?
    var name: String?
    var photos: [QPhoto]?
    var vicinity: String?
    var isOpen: Bool?
    var types: [String]?
    var rating: Float?
    var priceLevel: Int?
    var website: String?

    init(placeInfo:[String: Any]) {
        // coordinates
        if let g = placeInfo[geometryKey] as? [String:Any] {
            if let l = g[locationKey] as? [String:Double] {
                if let lat = l[latitudeKey], let lng = l[longitudeKey] {
                    location = CLLocationCoordinate2D.init(latitude: lat, longitude: lng)
                }
            }
        }

        // name
        name = placeInfo[nameKey] as? String

        // opening hours
        if let oh = placeInfo[openingHoursKey] as? [String:Any] {
            if let on = oh[openNowKey] as? Bool {
                isOpen = on
            }
        }

        // vicinity
        vicinity = placeInfo[vicinityKey] as? String

        // types
        types = placeInfo[typesKey] as? [String]

        // rating
        rating = placeInfo[ratingKey] as? Float

        //priceLevel
        priceLevel = placeInfo[priceLevelKey] as? Int

        website = placeInfo[websiteKey] as? String

        // photos
        photos = [QPhoto]()
        if let ps = placeInfo[photosKey] as? [[String:Any]] {
            for p in ps {
                photos?.append(QPhoto.init(photoInfo: p))
            }
        }
    }

    func getDescription() -> String {

        var s : [String] = []

        if let types = types {
            s.append("\(types.joined(separator: ", "))")
        }

        if let rating = rating {
            s.append("Rating: \(rating)")
        }

        if let priceLevel = priceLevel {
            s.append("PriceLevel: \(priceLevel)")
        }

        if let website = website {
            s.append("\(website)")
        }

         if let isOpen = isOpen {
            s.append(isOpen ? "OPEN NOW" : "CLOSED NOW")
        }

        if let vicinity = vicinity {
            s.append("\(vicinity)")
        }
        return s.joined(separator: "\n")
    }

 func heightForComment(_ font: UIFont, width: CGFloat) -> CGFloat {
        let desc = getDescription()
        let rect = NSString(string: desc).boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
        return ceil(rect.height)
    }

}

to get the place's details that i'll show in a VC of my application by calling this function   func getDescription() -> String { } but my problem and i don't know why (because i follow the documentation of google places API) is that the website and also the price level not working, so when in the viewController i call the function getDescription() it load all place's details which i added in that function, but not the website and the price level. What i did wrong? How can i adjust it?

UPDATE

https://developers.google.com/places/ios-api/place-details

static func getNearbyPlaces(by category:String, coordinates:CLLocationCoordinate2D, radius:Int, token: String?, completion: @escaping (QNearbyPlacesResponse?, Error?) -> Void) {

        var params : [String : Any]

        if let t = token {
            params = [
                "key" : AppDelegate.googlePlacesAPIKey,
                "pagetoken" : t,
            ]
        } else {
            params = [
                "key" : AppDelegate.googlePlacesAPIKey,
                "radius" : radius,
                "location" : "\(coordinates.latitude),\(coordinates.longitude)",
                "type" : category.lowercased()
            ]
        }


问:
React Native: can't call a parent method from child
I have this function in parent component, and I am trying to call this method/function in child , like so:

```<code>buttonPressed = () => {
  console.log('button pressed')
}

<childComp ref={ref => this.feedback = ref}
           onPress={this.buttonPressed}
/>
</code>```

in child:

```<code><Animated.View>
  ...   // other views
  <View>
    <TouchableOpacity onPress={this.props.buttonPressed}> // calling here
     ...
    </TouchableOpacity>

  </View>
</Animated.View>
</code>```

No matter what I tried , it didn't work.

答:
I think that in child component you should call to this.props.onPress(), because the name of the property thar you are passing is onPress. Also, don't forget to put () when you want to call the function. So it should be:

```<code><Animated.View>
  ...   // other views
  <View>
    <TouchableOpacity onPress={this.props.onPress()}> // calling here
     ...
    </TouchableOpacity>

  </View>
</Animated.View>
</code>```

Body:
I have this function in parent component, and I am trying to call this method/function in child , like so:

buttonPressed = () => {
  console.log('button pressed')
}

<childComp ref={ref => this.feedback = ref}
           onPress={this.buttonPressed}
/>

in child:

<Animated.View>
  ...   // other views
  <View>
    <TouchableOpacity onPress={this.props.buttonPressed}> // calling here
     ...
    </TouchableOpacity>

  </View>
</Animated.View>

No matter what I tried , it didn't work.

Body:
I think that in child component you should call to this.props.onPress(), because the name of the property thar you are passing is onPress. Also, don't forget to put () when you want to call the function. So it should be:

<Animated.View>
  ...   // other views
  <View>
    <TouchableOpacity onPress={this.props.onPress()}> // calling here
     ...
    </TouchableOpacity>

  </View>
</Animated.View>


问:
How to run a single specflow scenario outline using nunit3 console tool
Using VS2015 the Test Explorer allows you to run a single scenario outline.

Now I need to do the same using NUnit3 console tool (I'm using NUnit as Unit Test Provider).

Currently I'm using the following command in order to run a test using console tool.

```<code>"C:\NUnit-3.0.1\bin\nunit3-console.exe" Path.Scripts.dll --test:Fully.Qualified.Name.TestAAAFeature.TestAAA --x86
</code>```

答:
First and foresmost, I think you should rename your test cases to be more informative as a best practice.

Coming to your question, you should use filters which can be specified by using a where clause. For running a specific test case, you can use either method or name to filter down to one or more target test case(s).

Just append the following to your command and you should be good to go.

```<code>--where "name == 'TestCase11257'"
</code>```

OR

```<code>--where "method == 'TestCase11257'"
</code>```

or you can even combine multiple filters like

```<code>--where "name == 'TestCase11257' || method == 'TestCase11257'"
</code>```

You can read more about filters here

Body:
Using VS2015 the Test Explorer allows you to run a single scenario outline.

Now I need to do the same using NUnit3 console tool (I'm using NUnit as Unit Test Provider).

Currently I'm using the following command in order to run a test using console tool.

"C:\NUnit-3.0.1\bin\nunit3-console.exe" Path.Scripts.dll --test:Fully.Qualified.Name.TestAAAFeature.TestAAA --x86

Body:
First and foresmost, I think you should rename your test cases to be more informative as a best practice.

Coming to your question, you should use filters which can be specified by using a where clause. For running a specific test case, you can use either method or name to filter down to one or more target test case(s).

Just append the following to your command and you should be good to go.

--where "name == 'TestCase11257'"

OR

--where "method == 'TestCase11257'"

or you can even combine multiple filters like

--where "name == 'TestCase11257' || method == 'TestCase11257'"

You can read more about filters here


问:
Adding multi-language option to a Qt app with hard-coded text
I'm a beginner in Qt. I have an app designed using Qt which has multiple windows with each consisting of several labels with hard coded text. What would be the easiest way to add multi language support for this app? Which built in Qt objects/functions I should use?

My current idea is to maybe create a separate xml file including the text for all labels for a language. Then once the user selects a language icon from the menu, load the relevant xml file. But I have no idea how to do this. Any help would be highly appreciated!

UPDATE:
I have tried to implement the example given here. But it throws the following error and I can't fix it. 'class Ui::MainWindow' has no member named 'menuLanguage'

QActionGroup* langGroup = new QActionGroup(ui->menuLanguage);

答:
Try  Qt Linguist:

I made you a simple example:

.pro

```<code>TRANSLATIONS += translation_fa.ts
</code>```

.h

```<code>#include <QTranslator>
QTranslator translator;
</code>```

.cpp

```<code>if(translator.load("E:/Qt/Linguist/linguist/translation_fa.qm"))
    qDebug()<<"successfully load qm file.";
else
    qDebug()<<"problem in load qm file.";

// change language to second language
qApp->installTranslator(&translator);

// change language to default language
qApp->removeTranslator(&translator);
</code>```

Don't forget to use Qt Linguist Tools.

This is a sample project for your question on github download here.

Body:
Try  Qt Linguist:

I made you a simple example:

.pro

TRANSLATIONS += translation_fa.ts

.h

#include <QTranslator>
QTranslator translator;

.cpp

if(translator.load("E:/Qt/Linguist/linguist/translation_fa.qm"))
    qDebug()<<"successfully load qm file.";
else
    qDebug()<<"problem in load qm file.";

// change language to second language
qApp->installTranslator(&translator);

// change language to default language
qApp->removeTranslator(&translator);

Don't forget to use Qt Linguist Tools.

This is a sample project for your question on github download here.


问:
UI-codemirror Addons
I am using UI-codemirror in angularjs application for java code editing with mode set to 'text/x-java'. Now I want to use addons like autocomplete and lint.

for autocomplete I set options as below with keyup and also with onKeyUp, both the events are not triggered.

configure options in controller:

```<code>_this.editorOptions = {
        lineWrapping: true,
        lineNumbers: true,
        mode: 'text/x-java',
        smartIndent: true,
        tabSize: 4,
        indentWithTabs: true,
        tabindex: 4,
        autofocus: true,
        addModeClass: true,
        keyup: function (e, s) {
            console.log("Event Keyup");

        },
        onKeyUp: function (e, s) {
            console.log("Event Keyup");

        }
    }
</code>```

Directive in the template:

```<code><ui-codemirror ui-codemirror-opts="vm.editorOptions" ng-model="vm.activeQuestion.candidateAnswer"></ui-codemirror>
</code>```

What are the addon js scripts to include and what configuration options to set for these to workout?

答:
Get access to the editor; after that you can register a listener on it :</p>

```<code>var myCodeMirror = CodeMirror.fromTextArea(myTextArea);
myCodeMirror.on('change', function(codemirrorinstance)
{
    console.log(key pressed);
})
</code>```

Title: UI-codemirror Addons

Body:
I am using UI-codemirror in angularjs application for java code editing with mode set to 'text/x-java'. Now I want to use addons like autocomplete and lint.

for autocomplete I set options as below with keyup and also with onKeyUp, both the events are not triggered.

configure options in controller:

_this.editorOptions = {
        lineWrapping: true,
        lineNumbers: true,
        mode: 'text/x-java',
        smartIndent: true,
        tabSize: 4,
        indentWithTabs: true,
        tabindex: 4,
        autofocus: true,
        addModeClass: true,
        keyup: function (e, s) {
            console.log("Event Keyup");

        },
        onKeyUp: function (e, s) {
            console.log("Event Keyup");

        }
    }

Directive in the template:

<ui-codemirror ui-codemirror-opts="vm.editorOptions" ng-model="vm.activeQuestion.candidateAnswer"></ui-codemirror>

What are the addon js scripts to include and what configuration options to set for these to workout?

Body:
Get access to the editor; after that you can register a listener on it :

var myCodeMirror = CodeMirror.fromTextArea(myTextArea);
myCodeMirror.on('change', function(codemirrorinstance)
{
    console.log(key pressed);
})


问:
How to set a background image for a card in CardView?
I have a card and want to add content to it. How should I add images and also Text to the card? Here is my xml code:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="ml.vedantk.app.god.MainActivity">

    <android.support.v7.widget.CardView
        android:id="@+id/card1"
        android:layout_width="364dp"
        android:layout_height="389dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="64dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>
</code>```

Here is the java file:

```<code>package ml.vedantk.app.god;

import android.support.annotation.ColorInt;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        CardView card1 = (CardView)findViewById(R.id.card1);
        card1.setCardBackgroundColor(100);

    }
}
</code>```

The card1.setCardBackgroundColor(100); also did not change the background color. So can anybody help me add an image?

答:
Did you try this?</p>

```<code>card1.setBackgroundResource(R.drawable.yourimage);
</code>```

Body:
I have a card and want to add content to it. How should I add images and also Text to the card? Here is my xml code:

    <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="ml.vedantk.app.god.MainActivity">

    <android.support.v7.widget.CardView
        android:id="@+id/card1"
        android:layout_width="364dp"
        android:layout_height="389dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="64dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

Here is the java file:

package ml.vedantk.app.god;

import android.support.annotation.ColorInt;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        CardView card1 = (CardView)findViewById(R.id.card1);
        card1.setCardBackgroundColor(100);

    }
}

The card1.setCardBackgroundColor(100); also did not change the background color. So can anybody help me add an image?

Body:
Did you try this?

card1.setBackgroundResource(R.drawable.yourimage);


问:
How make modeling from train and test data?
I have data in the order file,

```<code>#split into train and test sets
X = DataFrame.values
train_size = int(len(X)*0.66)
train, test = X[1:train_size], X[train_size:]
train_X, train_y = train[:,0], train[:,1]
test_X, test_y = test[:,0], test[:,1]
</code>```

I want train_data to test data in different files by calling.

```<code>def test(learning_rate=0.1, k=1, training_epochs=15):
    print ('... loading data')
    datasets = ('book-sales.csv')
    train_X, train_y = datasets[0]
    test_X, test_y = datasets[0]
    print ('... modeling')
    rbm = RBM(input=train_X, n_visible=28 * 28, n_hidden=500)
</code>```

I tried but I found this message.

train_X, train_y = datasets[0]

ValueError: not enough values to unpack (expected 2, got 1)

How should I write it?

答:
You would be able to split the dataframe into two random samples (80% and 20%) for training and testing in Python by using : </p>

```<code>import pandas as pd
data_path = "./book-sales.csv"
df = pd.read_csv(data_path)
msk = np.random.rand(len(df)) < 0.8
train_X, train_y= df[msk]
test_X, test_y= df[~msk]
</code>```

Body:
I have data in the order file,

#split into train and test sets
X = DataFrame.values
train_size = int(len(X)*0.66)
train, test = X[1:train_size], X[train_size:]
train_X, train_y = train[:,0], train[:,1]
test_X, test_y = test[:,0], test[:,1]

I want train_data to test data in different files by calling.

def test(learning_rate=0.1, k=1, training_epochs=15):
    print ('... loading data')
    datasets = ('book-sales.csv')
    train_X, train_y = datasets[0]
    test_X, test_y = datasets[0]
    print ('... modeling')
    rbm = RBM(input=train_X, n_visible=28 * 28, n_hidden=500)

I tried but I found this message.

train_X, train_y = datasets[0]

ValueError: not enough values to unpack (expected 2, got 1)

How should I write it?

Body:
You would be able to split the dataframe into two random samples (80% and 20%) for training and testing in Python by using :

import pandas as pd
data_path = "./book-sales.csv"
df = pd.read_csv(data_path)
msk = np.random.rand(len(df)) < 0.8
train_X, train_y= df[msk]
test_X, test_y= df[~msk]


问:
Unable to extend AppCompatActivity as i'm already extending ListActivity
I'm using TwitterKit to load a list of tweets in an activity. I would like to add a custom ActionBar to my activity. I'm unable to find a way to extend both AppCompatActivity and ListActivity at the same time...  Are there any workarounds or solutions for this?  Please see code below</p>

```<code>public class travel_info extends ListActivity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_travel_info);

        getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        getSupportActionBar().setDisplayShowCustomEnabled(true);
        getSupportActionBar().setCustomView(R.layout.custom_line_info);
        View view = getSupportActionBar().getCustomView();

        Twitter.initialize(this);
        final UserTimeline userTimeline = new UserTimeline.Builder()
                .screenName("TfLTravelAlerts")
                .build();
        final TweetTimelineListAdapter adapter = new TweetTimelineListAdapter.Builder(this)
                .setTimeline(userTimeline)
                .build();
        setListAdapter(adapter);
    }
}
</code>```

答:
You can only Extend a single class. And implement Interfaces from many sources.

Extending multiple classes is not available.

you could use ListActivity or ListView inside regular Activity. In the newest versions of Android, preferred way of displaying items on a list is using so called RecyclerView.

Please, see linked documentation. It's quite good and helpful. Besides naming convetion, RecyclerView gives you more flexibility and has ViewHolder pattern implemented out-of-the-box for re-using views during the scrolling what increases application's performance. Before introducing RecyclerView, you had to implement ViewHolder pattern on your own.

Instead of Activity or ListActivity, you should use AppCompatActivity and place RecyclerView inside it to keep backward compatibility with older systems and devices.

Body:
I'm using TwitterKit to load a list of tweets in an activity. I would like to add a custom ActionBar to my activity. I'm unable to find a way to extend both AppCompatActivity and ListActivity at the same time...  Are there any workarounds or solutions for this?  Please see code below

public class travel_info extends ListActivity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_travel_info);

        getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        getSupportActionBar().setDisplayShowCustomEnabled(true);
        getSupportActionBar().setCustomView(R.layout.custom_line_info);
        View view = getSupportActionBar().getCustomView();

        Twitter.initialize(this);
        final UserTimeline userTimeline = new UserTimeline.Builder()
                .screenName("TfLTravelAlerts")
                .build();
        final TweetTimelineListAdapter adapter = new TweetTimelineListAdapter.Builder(this)
                .setTimeline(userTimeline)
                .build();
        setListAdapter(adapter);
    }
}


答:
I wrapped both div ce_text chapo and img_header to .test-wrap class and give it to below css:

```<code>.test-wrap {
 display: table;
 width: 100%;
}
</code>```

body,
div {
  margin: 0;
  padding: 0;
  font-family: 'Roboto condensed', sans-serif;
}

div.inside {
  position: relative;
}

div.chapo {
  background-color: #ef4056;
  background-image: none;
  width: 70%;
  height: 255px;
  display: table-cell;
  vertical-align: top;
  background-color: #aaa;
  color: #fff;
  padding: 20px 8%;
  position: relative;
}

h1 {
  margin-top: 0;
  font: 1.4em 'Oswald', Helvetica, sans-serif;
  font-weight: bold;
  text-transform: uppercase;
}

div.chapo p {
  width: 100%;
  min-width: 100%;
  position: relative;
  padding: 0;
  font-size: 1em;
  font-weight: 300;
}

div.img_header {
  width: 30%;
  position: relative;
  display: table-cell;
  vertical-align: top;
  background-position: center center;
  background-repeat: no-repeat;
  background-size: cover;
  -webkit-background-size: cover;
  background-image: url(https://image.freepik.com/free-psd/abstract-background-design_1297-73.jpg);
}

div.mod_breadcrumb {
  height: 40px;
  margin: 0;
  padding-top: 5px;
  padding-right: 30px;
  padding-bottom: 5px;
  background-color: #e3e3e3;
  padding-left: 8%;
}

.mod_breadcrumb ul li {
  height: 30px;
  display: inline-block;
  padding: 3px 0;
  color: #828282;
}
.test-wrap {
  display: table;
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="inside">
  <div class="test-wrap">
    <div class="ce_text chapo">
      <h1>My header</h1>
      <div class='text-chapo'>
        <p>Lorem ipsum dolor sit Lorem ipsum dolor sit amet, consectetur adipiscing </p>
      </div>
    </div>
    <div class="img_header"></div>
  </div>
  <div class="mod_breadcrumb block">
    <ul>
      <li></li>
      <li></li>
      <li></li>
    </ul>
  </div>
</div></code>```

Title: Css Table-cell and relative width

Body:
I wrapped both div ce_text chapo and img_header to .test-wrap class and give it to below css:

.test-wrap {
 display: table;
 width: 100%;
}

body,
div {
  margin: 0;
  padding: 0;
  font-family: 'Roboto condensed', sans-serif;
}

div.inside {
  position: relative;
}

div.chapo {
  background-color: #ef4056;
  background-image: none;
  width: 70%;
  height: 255px;
  display: table-cell;
  vertical-align: top;
  background-color: #aaa;
  color: #fff;
  padding: 20px 8%;
  position: relative;
}

h1 {
  margin-top: 0;
  font: 1.4em 'Oswald', Helvetica, sans-serif;
  font-weight: bold;
  text-transform: uppercase;
}

div.chapo p {
  width: 100%;
  min-width: 100%;
  position: relative;
  padding: 0;
  font-size: 1em;
  font-weight: 300;
}

div.img_header {
  width: 30%;
  position: relative;
  display: table-cell;
  vertical-align: top;
  background-position: center center;
  background-repeat: no-repeat;
  background-size: cover;
  -webkit-background-size: cover;
  background-image: url(https://image.freepik.com/free-psd/abstract-background-design_1297-73.jpg);
}

div.mod_breadcrumb {
  height: 40px;
  margin: 0;
  padding-top: 5px;
  padding-right: 30px;
  padding-bottom: 5px;
  background-color: #e3e3e3;
  padding-left: 8%;
}

.mod_breadcrumb ul li {
  height: 30px;
  display: inline-block;
  padding: 3px 0;
  color: #828282;
}
.test-wrap {
  display: table;
  width: 100%;
}

<div class="inside">
  <div class="test-wrap">
    <div class="ce_text chapo">
      <h1>My header</h1>
      <div class='text-chapo'>
        <p>Lorem ipsum dolor sit Lorem ipsum dolor sit amet, consectetur adipiscing </p>
      </div>
    </div>
    <div class="img_header"></div>
  </div>
  <div class="mod_breadcrumb block">
    <ul>
      <li></li>
      <li></li>
      <li></li>
    </ul>
  </div>
</div>


问:
Trying to connect to a database created in a spring boot package with intelij Datagrip
I have created a spring boot project in eclipse with a H2 embedded database and JPA. Inside my resource folder I'm using import.sql to populate the tables created in my entity package.The spring web application and database runs fine as I can check it but I want to know if it is possible to check this database in Intelij DataGrip like I can when I do this:

```<code>localhost:8080/h2-console
</code>```

In my application.properties in my spring project I have this:

```<code>spring.datasource.url=jdbc:h2:file:./database/suppliersDB;
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
spring.jpa.hibernate.naming.strategy=org.hibernate.cfg.DefaultNamingStrategy
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create
</code>```

In my Intelij Datagrip I add a data source H2 and give it the url and test connection and it says ok but doesn't show any of the tables and when I run a query in the DLL it says table doesn't exist

And I know I should probably shouldn't be using Intelij IDE since my project is in eclipse but it is just an experiment and it is frustrating me I can't get it working in Datagrip.

Also the embedded database file stored by eclipse is an .mv.db file which maybe the problem i'm not sure!

Any help would be much appreciated!

答: You cannot do it because the database you created is in-memory.</p>

Body:
I have created a spring boot project in eclipse with a H2 embedded database and JPA. Inside my resource folder I'm using import.sql to populate the tables created in my entity package.The spring web application and database runs fine as I can check it but I want to know if it is possible to check this database in Intelij DataGrip like I can when I do this:

localhost:8080/h2-console

In my application.properties in my spring project I have this:

spring.datasource.url=jdbc:h2:file:./database/suppliersDB;
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
spring.jpa.hibernate.naming.strategy=org.hibernate.cfg.DefaultNamingStrategy
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create

In my Intelij Datagrip I add a data source H2 and give it the url and test connection and it says ok but doesn't show any of the tables and when I run a query in the DLL it says table doesn't exist

And I know I should probably shouldn't be using Intelij IDE since my project is in eclipse but it is just an experiment and it is frustrating me I can't get it working in Datagrip.

Also the embedded database file stored by eclipse is an .mv.db file which maybe the problem i'm not sure!

Any help would be much appreciated!


答:
Image can't be set as Background Image For a Card View.But You can Use Background Color using setCardBackgroundColor(ContextCompat.getColor(this, R.color.colorPrimary))

If you want to set a background Image Inside Cardview Use Another Layout such as LinearLayout, RelativeLayout or any other Inside The CardView. And Add Background for that Layout. This is one of the easy way to set BackgroundImage for CardView

Title: How to set a background image for a card in CardView?


答:
I'm unable to find a way to extend both AppCompatActivity and ListActivity at the same time

If you want to use ListView in your app then directly use it without extending ListActivity See here

Title: Unable to extend AppCompatActivity as i'm already extending ListActivity


问:
Should I use in or not in to optimise my Redshift SQL
I've a list of 85 values, and I want to limit my query to only use 10 of them.

Is it more efficient to use NOT IN or IN  in the where clause. The exclusion list will not change, but the list of values to include will change, so I would prefer to use NOT IN, but want to ensure I don't make the query very slow if I do that.

Thanks

答:
Firstly for the sake of code maintainability it's better to use Not IN or you will have to keep updating code every time you update the inclusion list if you use the IN method.

The actual performance depends on the query, the data being queried and other parameters and a generally acceptable answer to performance questions is to profile your query by running it multiple times and timing them to check performance.


问:
Enterprise Architect - Transfering project from file to PostgreSQL repository
I am trying to transfer project file to DB repository (PostgreSQL). During project transfer (copying project information to t_object) error is displayed:

Error during project transfer

I've repeated it 3 times, every time with the same result. Logfile looks like below:

```<code>2017-11-13 16:30:20  Copying project information for: t_glossary
2017-11-13 16:30:20  Copying project information for: t_implement
2017-11-13 16:30:20  Copying project information for: t_object
  ERROR: *** t_object - record no: 1345 Key: object_id=3390
</code>```

Any ideas how to solve it?

答: Try to run a Project Consistency Check beforehand. If that does not help you might be forced to use XMI for the model and separately ex-/import for the Reference Data.</p>

Body:
I am trying to transfer project file to DB repository (PostgreSQL). During project transfer (copying project information to t_object) error is displayed:

Error during project transfer

I've repeated it 3 times, every time with the same result. Logfile looks like below:

2017-11-13 16:30:20  Copying project information for: t_glossary
2017-11-13 16:30:20  Copying project information for: t_implement
2017-11-13 16:30:20  Copying project information for: t_object
  ERROR: *** t_object - record no: 1345 Key: object_id=3390

Any ideas how to solve it?


问:
Scraping a website with requests (post, js?)
I tried to scrape this site:

http://www.finanzen.net/historische-kurse/Daimler

and used the following source code:

```<code>from cookies import cookies
import datetime
import requests
import time
import webbrowser

def download(number,
             isin,
             start=datetime.date(1998,1,1),
             end=datetime.date.today(),
             dst="raw"):
    """
    """
    # ToDo -- I want to give a tag and not an url!
    url = "http://www.finanzen.net/historische-kurse/daimler"

    # ToDo -- should be dynamic
    today = datetime.date.today()
    inTag1    = str(1)
    inMonat1  = str(1)
    inJahr1   = str(1998)
    inTag2    = str(today.day)
    inMonat2  = str(today.month)
    inJahr2   = str(today.year)
    strBoerse = "XETRA"
    pkBHTs    = int(time.time())

    payload = {"inTag1"    : inTag1,
               "inMonat1"  : inMonat1,
               "inJahr1"   : inJahr1,
               "inTag2"    : inTag2,
               "inMonat2"  : inMonat2,
               "inJahr2"   : inJahr2,
               "strBoerse" : strBoerse,
               "pkBHTs"    : pkBHTs}

    r = requests.get(url, params=payload, cookies=cookies)

    if "08.11.2017" in r.text:
        print("OK")
    else:
        print("FAIL!")

    with open("output.html", "w") as f:
        f.write(r.text)

if __name__ == "__main__":

    print("Test: download()")

    download(1510210323,
             "DE0007100000",
             start=datetime.date(1998,1,1),
             end=datetime.date.today(),
             dst="raw")
    print("Done.")

    webbrowser.open("output.html")
</code>```

I have a second script which provides the cookie data from my browser:

```<code>cookies = {'CAP' : 'data=44a1e1f46fef0411bf06d9bfc501913f',
           'CUID' : 'N,1510569302850:ALHGLuQAAAAPTiwxNTEwNTY5MzAyODUwVdj35/i8kfuLw5RmnsCECh6uWduJEJHPHe44+gmS5k1OeVohiY2UE0s8Toc6Z1KsPkSIOyvb0rHFvfBB5GtZD0BeUVeUq8xKkDIkDqq2RsE7AvdO9c+GoqElRytvxjPuoExKFUZ7sMl3+ugTDvQsjM0q6iEkcfYTCjZcqRhGJ2JicnT0yZI8NIINqvt1OUufo4jtHTgznYHCgSG8lxydqzv+Cax90XRsvKoUEzTfJCxzqryt3rkXiy4IMEOrTMxZOZCoT0HO3hgghkd3XyzOhhr70tLnPbY4GxPkWrcXy4y+7xHwwoX+jmJGiNvEJod8mQF3QkkDSN+uwmTlAgy7Yg==',
           'MI' : '1',
           'OPTOUTMULTI' : '0:0%7Cc2:0',
           '__utma' : '99761801.1635127051.1447939999.1510562258.1510569245.10',
           '__utmb' : '99761801.1.10.1510569245',
           '__utmc' : '99761801',
           '__utmt_UA-1858090-1' : '1',
           '__utmz' : '99761801.1503872185.2.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided)',
           '_ga' : 'GA1.2.1635127051.1447939999',
           '_gid' : 'GA1.2.216894857.1510518215',
           'finpopup2' : 'n=3&d=08%2E09%2E2017',
           'fintargeting' : 'v=1&h=0x000000&hd=131117091117091117091117091117091117',
           'finvisit' : 'v=5&p=16&d=13%2E11%2E2017',
           'mjdkyj' : 'AKsRol8bjClrOgYBI9F53uwo0572ZvzG_ifsQhL0W6CGIPDli067aLH682nhCzAvZJLwgmI_hfnp1G_cO6_R7La4pHyjXqGz7w',
           'utag_main' : 'v_id:015e25c45b49001bad6f158e01b004066002a05e00838$_sn:10$_ss:0$_st:1510571043449$dc_visit:10$dc_visit_dip-main:10$dip_times_empty_enrichment:26$ses_id:1510569240676%3Bexp-session$_pn:1%3Bexp-session$collectCookieMode:3rdParty%3Bexp-session$dc_event:1%3Bexp-session$dip_events_this_session:1%3Bexp-session$dc_event_dip-main:1%3Bexp-session$dc_region_dip-main:eu-central-1%3Bexp-session$dc_region:eu-central-1%3Bexp-session',
           'xdefcc' : 'G18e8ffb3a46fc000807955c49556bf4cc',
           '1P_JAR' : '2017-11-13-10',
           'AID' : 'AJHaeXJrF9XjJOxZm8l4doMQZS4yMOPes3h5NKKcWJZxIyGSOAjtzw',
           'APISID' : 'VILFXotMggFxtb9h/AcPvkxMR5pWR0AzUo',
           'ASPSESSIONIDQSRTTSCC' : 'GLLJJMHAIDCBGEEODOLMADEN',
           'ASPSESSIONIDSSRSRSBD' : 'PGHHNMHANNCJJKIPNALFCCMO',
           'CAP' : 'data=44a1e1f46fef0411bf06d9bfc501913f',
           'CONSENT' : 'YES+DE.de+20150726-13-0',
           'CUID' : 'N,1510569302850:ALHGLuQAAAAPTiwxNTEwNTY5MzAyODUwVdj35/i8kfuLw5RmnsCECh6uWduJEJHPHe44+gmS5k1OeVohiY2UE0s8Toc6Z1KsPkSIOyvb0rHFvfBB5GtZD0BeUVeUq8xKkDIkDqq2RsE7AvdO9c+GoqElRytvxjPuoExKFUZ7sMl3+ugTDvQsjM0q6iEkcfYTCjZcqRhGJ2JicnT0yZI8NIINqvt1OUufo4jtHTgznYHCgSG8lxydqzv+Cax90XRsvKoUEzTfJCxzqryt3rkXiy4IMEOrTMxZOZCoT0HO3hgghkd3XyzOhhr70tLnPbY4GxPkWrcXy4y+7xHwwoX+jmJGiNvEJod8mQF3QkkDSN+uwmTlAgy7Yg==',
           'HSID' : 'AkD2AyVb5Z9wR9QT-',
           'MI' : '1',
           'NID' : '117=IbpFdbi-srSVK7HAD-b_ENXheFKQqlI0MtwsBKkQ5kMzKE_YMKHN7THu3mgYrYZZ45mSgYb1r67FfyX30QDu3pT22YEzK4Ylj_DbQ0BwbLx36NJV68KmDoivU9zD38hSPe9oPS89Z8spzbp9mPSEuYOhhznowFxCS0ZnZDhYIKsnwdMEYWqDVhQ0fUqnpnTQFV1VWb1-7dZJ5LvnKKWf5xHi5wNhL5YQtaFdYEb2rY0L3HTR0IeZMu3ZIR-2pOYQYspwyg',
           'NID' : '110=Chz_C4sXWBfkLwySlpc-od0DauOGbWPjjZ_UYJgVYSeOXLWaQayrm_PHSMfnI4bkHwFQjWq0atuDmXEGq39-uJHLpanLu7kQDs9WTm004KBx7nWacN1-_x_p05gbw8wx',
           'OPTOUTMULTI' : '0:0%7Cc2:0',
           'POPUPCHECK' : '1510604610799',
           'SAPISID' : 'e-07IvwMgsqnc1KL/AWrA0YaffjZEXetqg',
           'SID' : 'FwUbfPob8j7z4QAbMUsPD7HI4FwPoOM7wPo9cyTwyAveBe0fy86idhBKLMz8mn93l-pyPA.',
           'SIDCC' : 'AE4kn7_ynLaaOiVILBfgv5-_j3I-18GWRw0_rgIiJGSRP0YLV8zwv3Me80u9dqJI_a58y8xXxMCyLlu7qBw2rQ',
           'SSID' : 'ADQhejhWBta7RIl3q',
           '__utma' : '99761801.1635127051.1447939999.1510562258.1510569245.10',
           '__utmb' : '99761801.1.10.1510569245',
           '__utmc' : '99761801',
           '__utmt_UA-1858090-1' : '1',
           '__utmz' : '99761801.1503872185.2.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided)',
           '_ga' : 'GA1.2.1635127051.1447939999',
           '_gid' : 'GA1.2.216894857.1510518215',
           'anj' : """dTM7k!M4/C@-S3@:5]qk`_#I2PQ7s]@!7PT-Q!$Rkf%Tam0H]QFpc6s(!H!k>jP5fr<Pn!Sse@DnFc!m#J[!_?'td[$Y+EO30JW48u`al*p]+pQ%.IaIz(eLt1a=RpN+IIuSI6>2pVG*(l/YR]55R_8*)f_>Bgu2u'nh]2pe>#n88><bUjXaW]vuR5bchvb:ei<F/=Ow02i-18D:GO_nsX`cEj282$Vr6Zz2%R'kHi(@n0veK7e2'oM:Nd`*Ju!l/-nAbGM6F3YP-^KnNXwhV1.yggNVGk!<5]]1?:av7hOQ/L#d9Q``r=MjWhED9SGjg%*!X1%w5kp?T<s?7j=KIM8Y$p1^aigtynxfq/5MBw3X2Bc8E5EILM(^k=p=B+%ra1D^CUB]=ExTXvZx7go4f/B(8iGBZRtY(q7_H=>?rY$IpGd).%<kME<mKK:vp7SPIctG0J8vv3y6MW*)3'5N9/Ju_Oiw98wU4016EdBD9et%n*bF_uZv<jF>'E9@VDsp3i^mu'h2R4Y8:2]ko2YdA.(6d3^+<+4Dyo=Z-Mi./o1lsVmD61*JVd'oKHFeNRD*7d:wbm(7!4vs*Ahw+.XI2d?c4#.oV1%5pnBbLG^!1N1qfcZMzhBp?xs_#Ch3o$L$hlWShx4HF@u5e9Agc*S[s.gz6MTIX6:[Rm`v-pH_<(#8YlG`P_(PHOI*v*N^mA!>5Nmh8U?<WbeUp48=ux1N@quBj7U2(Kz1W7/>7`Q2A-`C7X6N_.bl/V/43$YC8N6zsH:M$KCuLYMOsnBP<3v3h)rg2aA2V?PAMJ71Lc*oW?!I^KQ<CPZ#RByeri1*v-M93nj?6#tLa?5o-[E*.ys9IO/2KA)?C^vETDT%wlq#n=7kK9_U`Q=HTXf]UwV(h8H2]_x^UElV<-Jd.hF$pC#O#+2f1I6i44C<NiDE$C2Lhv=z#pWxmO?o4I*aMM2t])V=p>>i[n-caqAWXA`#7(h2Ka8_dV7bgcPn_h./y#T[!AyHDHC-4!t3+wnhevgtid(Y=^JnIDS6@J$jP$wO`bUt5^neF+TZMJNpbwFfE=<dL.627>80_)>!ViHO9vIz7]ebKf-WPz3-%7p]w_1nPBQvyJ_r*^cg['SV3T/t<?UK_ZqgOio<1W])V^'PW^Ev7^_`McptJ3`gig?Hh$DFMgh[yImN`wByK71`iKGSxl_8Fq!?p7WW)]R:8XVy+fJZ6zYJc@ro-!w@'_WN`A7'O]Slqu3gh/RPX!Ps[gJp9IA439Ki3Ak!II7Lgy997x07G][')<2wjcG9H3f'SwP/wKC>o=F7#3mMF9R#1U[5^SQCb:VD*7$G9pj9i7hJq:DMe)rg`lO-kf#2>mv3gzo_Jf?`*]*afAw3#21o/#YC<A9@/!41/zOjJ'<W2Z@?6EN2's]ZiejVf$y!mpqR7b2[ulW:gR.5Bcv[6>C9'Gl7uJHY1%@j!sP>>!bCYTvKIL>wV*`Hq.2q/FBSY?F%_iT7I%AZ<.`7@*)oo+DWqHvHvnK?4OQEzdX+4g.Mrhj(H<WjfG<4gIa([228)?u)*nhKni6oaXD!1YJEEVg07mn1_Ad:6cO37jyJ3?2L?+)$PaLfTKocjN55L@E+cMm4)k3jv.$z_rTgYiga4/""",
           'finpopup2' : 'n=3&d=08%2E09%2E2017',
           'fintargeting' : 'v=1&h=0x000000&hd=131117091117091117091117091117091117',
           'finvisit' : 'v=5&p=16&d=13%2E11%2E2017',
           'i00' : '002963d5e4108c32058a5679f0001%3B5a097588%3B5a3b7d3c',
           'icu' : 'ChgI95w7EAoYAiACKAIwuPaX0AU4AkACSAIQuPaX0AUYAQ..',
           'mjdkyj' : 'AKsRol8bjClrOgYBI9F53uwo0572ZvzG_ifsQhL0W6CGIPDli067aLH682nhCzAvZJLwgmI_hfnp1G_cO6_R7La4pHyjXqGz7w',
           'sess' : '1',
           'utag_main' : 'v_id:015e25c45b49001bad6f158e01b004066002a05e00838$_sn:10$_ss:0$_st:1510571043449$dc_visit:10$dc_visit_dip-main:10$dip_times_empty_enrichment:26$ses_id:1510569240676%3Bexp-session$_pn:1%3Bexp-session$collectCookieMode:3rdParty%3Bexp-session$dc_event:1%3Bexp-session$dip_events_this_session:1%3Bexp-session$dc_event_dip-main:1%3Bexp-session$dc_region_dip-main:eu-central-1%3Bexp-session$dc_region:eu-central-1%3Bexp-session',
           'uuid2' : '869611879133359501',
           'xdefcc' : 'G18e8ffb3a46fc000807955c49556bf4cc'}
</code>```

Please inform me if I provide in the cookie any personal information. Thanks.

I run my script and expect to get the same data like processing the form manually in my browser, but this didn't worked.

In my console I get:

```<code>Test: download()
FAIL!
Done.
</code>```

The output.html file - generated by my script - contains "Bitte wählen Sie das Start- und Enddatum des Zeitraumes, für den Sie historische Kursdaten anzeigen möchten." (= "Please choose a start and end date for which you want to show historical prices") instead of the data. This messaage is the error message and tolds me to send data to the form - but I had send the data to the website as you can see!

At the moment I don't understand what I can change to get the data instead of this message. Can you give me a tipp, please. Thank you for your efforts and excuse my English!

答:
You may choose selenium to get the same result. So I modified your code to achieve the values you tried to get.</p>

```<code># -*- coding: utf-8 -*-
import datetime
import requests
import time
import webbrowser
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import io

def getBoersenIndex(boerse):
    """Get index of given boerse.
       To set the value of the boersen dropdown, you have to know the index of the chosen boerse.

        Keyword arguments:
        boerse -- name of boerse as you see in dropdown at the website
    """

    boersen = [
        'Budapest',
        'Berlin',
        'Baader Bank',
        'BX Swiss',
        'Bats',
        'Chi-X',
        'Düsseldorf',
        'Frankfurt',
        'Hamburg',
        'Hannover',
        'Lang und Schwarz',
        'München',
        'Mexiko',
        'Nasdaq OTC',
        'XETRA',
        'Prag',
        'Stuttgart',
        'Swiss Exchange',
        'Tradegate',
        'Wien',
        'Quotrix'
    ]

    for index, boerseName in enumerate(boersen):
        if boerseName == boerse:
            return index+1

def download(startDay, startMonth, startYear, boerse, url):

    today = datetime.date.today()
    inTag1    = str(startDay)
    inMonat1  = str(startMonth)
    inJahr1   = str(startYear + 1 - 1998) # because the dropdown uses the index as a value starting with 1998 = 1
    inTag2    = str(today.day)
    inMonat2  = str(today.month)
    inJahr2   = str(today.year + 1 - 1998) # same as starting year
    strBoerse = str(getBoersenIndex(boerse))

    # this is my webdriver implementation, you may use another one
    options = webdriver.ChromeOptions()
    options.add_argument('headless')
    browser = webdriver.Chrome(<path_to_your_chrome_driver>, chrome_options=options)

    browser.get(url)
    time.sleep(1)

    browser.find_element_by_xpath("//select[@name='inTag1']/option[" +inTag1+ "]").click()
    browser.find_element_by_xpath("//select[@name='inMonat1']/option[" +inMonat1+ "]").click()
    browser.find_element_by_xpath("//select[@name='inJahr1']/option[" +inJahr1+ "]").click()
    browser.find_element_by_xpath("//select[@name='inTag2']/option[" +inTag2+ "]").click()
    browser.find_element_by_xpath("//select[@name='inMonat2']/option[" +inMonat2+ "]").click()
    browser.find_element_by_xpath("//select[@name='inJahr2']/option[" +inJahr2+ "]").click()
    browser.find_element_by_xpath("//select[@name='strBoerse']/option[" +strBoerse+ "]").click()
    browser.find_element_by_css_selector("span.button").click()

    if "08.11.2017" in browser.page_source:
        print("OK")
    else:
        print("FAIL!")

    with io.open("output.html", "w", encoding='utf8') as f:
        f.write(browser.page_source)

if __name__ == "__main__":
    print("Test: download()")
    download(1,1,1998,'XETRA', 'http://www.finanzen.net/historische-kurse/daimler')
    print("Done.")

    webbrowser.open("output.html")
</code>```

Body:
I tried to scrape this site:

http://www.finanzen.net/historische-kurse/Daimler

and used the following source code:

from cookies import cookies
import datetime
import requests
import time
import webbrowser

def download(number,
             isin,
             start=datetime.date(1998,1,1),
             end=datetime.date.today(),
             dst="raw"):
    """
    """
    # ToDo -- I want to give a tag and not an url!
    url = "http://www.finanzen.net/historische-kurse/daimler"

    # ToDo -- should be dynamic
    today = datetime.date.today()
    inTag1    = str(1)
    inMonat1  = str(1)
    inJahr1   = str(1998)
    inTag2    = str(today.day)
    inMonat2  = str(today.month)
    inJahr2   = str(today.year)
    strBoerse = "XETRA"
    pkBHTs    = int(time.time())

    payload = {"inTag1"    : inTag1,
               "inMonat1"  : inMonat1,
               "inJahr1"   : inJahr1,
               "inTag2"    : inTag2,
               "inMonat2"  : inMonat2,
               "inJahr2"   : inJahr2,
               "strBoerse" : strBoerse,
               "pkBHTs"    : pkBHTs}

    r = requests.get(url, params=payload, cookies=cookies)

    if "08.11.2017" in r.text:
        print("OK")
    else:
        print("FAIL!")

    with open("output.html", "w") as f:
        f.write(r.text)

if __name__ == "__main__":

    print("Test: download()")

    download(1510210323,
             "DE0007100000",
             start=datetime.date(1998,1,1),
             end=datetime.date.today(),
             dst="raw")
    print("Done.")

    webbrowser.open("output.html")

I have a second script which provides the cookie data from my browser:

cookies = {'CAP' : 'data=44a1e1f46fef0411bf06d9bfc501913f',
           'CUID' : 'N,1510569302850:ALHGLuQAAAAPTiwxNTEwNTY5MzAyODUwVdj35/i8kfuLw5RmnsCECh6uWduJEJHPHe44+gmS5k1OeVohiY2UE0s8Toc6Z1KsPkSIOyvb0rHFvfBB5GtZD0BeUVeUq8xKkDIkDqq2RsE7AvdO9c+GoqElRytvxjPuoExKFUZ7sMl3+ugTDvQsjM0q6iEkcfYTCjZcqRhGJ2JicnT0yZI8NIINqvt1OUufo4jtHTgznYHCgSG8lxydqzv+Cax90XRsvKoUEzTfJCxzqryt3rkXiy4IMEOrTMxZOZCoT0HO3hgghkd3XyzOhhr70tLnPbY4GxPkWrcXy4y+7xHwwoX+jmJGiNvEJod8mQF3QkkDSN+uwmTlAgy7Yg==',
           'MI' : '1',
           'OPTOUTMULTI' : '0:0%7Cc2:0',
           '__utma' : '99761801.1635127051.1447939999.1510562258.1510569245.10',
           '__utmb' : '99761801.1.10.1510569245',
           '__utmc' : '99761801',
           '__utmt_UA-1858090-1' : '1',
           '__utmz' : '99761801.1503872185.2.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided)',
           '_ga' : 'GA1.2.1635127051.1447939999',
           '_gid' : 'GA1.2.216894857.1510518215',
           'finpopup2' : 'n=3&d=08%2E09%2E2017',
           'fintargeting' : 'v=1&h=0x000000&hd=131117091117091117091117091117091117',
           'finvisit' : 'v=5&p=16&d=13%2E11%2E2017',
           'mjdkyj' : 'AKsRol8bjClrOgYBI9F53uwo0572ZvzG_ifsQhL0W6CGIPDli067aLH682nhCzAvZJLwgmI_hfnp1G_cO6_R7La4pHyjXqGz7w',
           'utag_main' : 'v_id:015e25c45b49001bad6f158e01b004066002a05e00838$_sn:10$_ss:0$_st:1510571043449$dc_visit:10$dc_visit_dip-main:10$dip_times_empty_enrichment:26$ses_id:1510569240676%3Bexp-session$_pn:1%3Bexp-session$collectCookieMode:3rdParty%3Bexp-session$dc_event:1%3Bexp-session$dip_events_this_session:1%3Bexp-session$dc_event_dip-main:1%3Bexp-session$dc_region_dip-main:eu-central-1%3Bexp-session$dc_region:eu-central-1%3Bexp-session',
           'xdefcc' : 'G18e8ffb3a46fc000807955c49556bf4cc',
           '1P_JAR' : '2017-11-13-10',
           'AID' : 'AJHaeXJrF9XjJOxZm8l4doMQZS4yMOPes3h5NKKcWJZxIyGSOAjtzw',
           'APISID' : 'VILFXotMggFxtb9h/AcPvkxMR5pWR0AzUo',
           'ASPSESSIONIDQSRTTSCC' : 'GLLJJMHAIDCBGEEODOLMADEN',
           'ASPSESSIONIDSSRSRSBD' : 'PGHHNMHANNCJJKIPNALFCCMO',
           'CAP' : 'data=44a1e1f46fef0411bf06d9bfc501913f',
           'CONSENT' : 'YES+DE.de+20150726-13-0',
           'CUID' : 'N,1510569302850:ALHGLuQAAAAPTiwxNTEwNTY5MzAyODUwVdj35/i8kfuLw5RmnsCECh6uWduJEJHPHe44+gmS5k1OeVohiY2UE0s8Toc6Z1KsPkSIOyvb0rHFvfBB5GtZD0BeUVeUq8xKkDIkDqq2RsE7AvdO9c+GoqElRytvxjPuoExKFUZ7sMl3+ugTDvQsjM0q6iEkcfYTCjZcqRhGJ2JicnT0yZI8NIINqvt1OUufo4jtHTgznYHCgSG8lxydqzv+Cax90XRsvKoUEzTfJCxzqryt3rkXiy4IMEOrTMxZOZCoT0HO3hgghkd3XyzOhhr70tLnPbY4GxPkWrcXy4y+7xHwwoX+jmJGiNvEJod8mQF3QkkDSN+uwmTlAgy7Yg==',
           'HSID' : 'AkD2AyVb5Z9wR9QT-',
           'MI' : '1',
           'NID' : '117=IbpFdbi-srSVK7HAD-b_ENXheFKQqlI0MtwsBKkQ5kMzKE_YMKHN7THu3mgYrYZZ45mSgYb1r67FfyX30QDu3pT22YEzK4Ylj_DbQ0BwbLx36NJV68KmDoivU9zD38hSPe9oPS89Z8spzbp9mPSEuYOhhznowFxCS0ZnZDhYIKsnwdMEYWqDVhQ0fUqnpnTQFV1VWb1-7dZJ5LvnKKWf5xHi5wNhL5YQtaFdYEb2rY0L3HTR0IeZMu3ZIR-2pOYQYspwyg',
           'NID' : '110=Chz_C4sXWBfkLwySlpc-od0DauOGbWPjjZ_UYJgVYSeOXLWaQayrm_PHSMfnI4bkHwFQjWq0atuDmXEGq39-uJHLpanLu7kQDs9WTm004KBx7nWacN1-_x_p05gbw8wx',
           'OPTOUTMULTI' : '0:0%7Cc2:0',
           'POPUPCHECK' : '1510604610799',
           'SAPISID' : 'e-07IvwMgsqnc1KL/AWrA0YaffjZEXetqg',
           'SID' : 'FwUbfPob8j7z4QAbMUsPD7HI4FwPoOM7wPo9cyTwyAveBe0fy86idhBKLMz8mn93l-pyPA.',
           'SIDCC' : 'AE4kn7_ynLaaOiVILBfgv5-_j3I-18GWRw0_rgIiJGSRP0YLV8zwv3Me80u9dqJI_a58y8xXxMCyLlu7qBw2rQ',
           'SSID' : 'ADQhejhWBta7RIl3q',
           '__utma' : '99761801.1635127051.1447939999.1510562258.1510569245.10',
           '__utmb' : '99761801.1.10.1510569245',
           '__utmc' : '99761801',
           '__utmt_UA-1858090-1' : '1',
           '__utmz' : '99761801.1503872185.2.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided)',
           '_ga' : 'GA1.2.1635127051.1447939999',
           '_gid' : 'GA1.2.216894857.1510518215',
           'anj' : """dTM7k!M4/C@-S3@:5]qk`_#I2PQ7s]@!7PT-Q!$Rkf%Tam0H]QFpc6s(!H!k>jP5fr<Pn!Sse@DnFc!m#J[!_?'td[$Y+EO30JW48u`al*p]+pQ%.IaIz(eLt1a=RpN+IIuSI6>2pVG*(l/YR]55R_8*)f_>Bgu2u'nh]2pe>#n88><bUjXaW]vuR5bchvb:ei<F/=Ow02i-18D:GO_nsX`cEj282$Vr6Zz2%R'kHi(@n0veK7e2'oM:Nd`*Ju!l/-nAbGM6F3YP-^KnNXwhV1.yggNVGk!<5]]1?:av7hOQ/L#d9Q``r=MjWhED9SGjg%*!X1%w5kp?T<s?7j=KIM8Y$p1^aigtynxfq/5MBw3X2Bc8E5EILM(^k=p=B+%ra1D^CUB]=ExTXvZx7go4f/B(8iGBZRtY(q7_H=>?rY$IpGd).%<kME<mKK:vp7SPIctG0J8vv3y6MW*)3'5N9/Ju_Oiw98wU4016EdBD9et%n*bF_uZv<jF>'E9@VDsp3i^mu'h2R4Y8:2]ko2YdA.(6d3^+<+4Dyo=Z-Mi./o1lsVmD61*JVd'oKHFeNRD*7d:wbm(7!4vs*Ahw+.XI2d?c4#.oV1%5pnBbLG^!1N1qfcZMzhBp?xs_#Ch3o$L$hlWShx4HF@u5e9Agc*S[s.gz6MTIX6:[Rm`v-pH_<(#8YlG`P_(PHOI*v*N^mA!>5Nmh8U?<WbeUp48=ux1N@quBj7U2(Kz1W7/>7`Q2A-`C7X6N_.bl/V/43$YC8N6zsH:M$KCuLYMOsnBP<3v3h)rg2aA2V?PAMJ71Lc*oW?!I^KQ<CPZ#RByeri1*v-M93nj?6#tLa?5o-[E*.ys9IO/2KA)?C^vETDT%wlq#n=7kK9_U`Q=HTXf]UwV(h8H2]_x^UElV<-Jd.hF$pC#O#+2f1I6i44C<NiDE$C2Lhv=z#pWxmO?o4I*aMM2t])V=p>>i[n-caqAWXA`#7(h2Ka8_dV7bgcPn_h./y#T[!AyHDHC-4!t3+wnhevgtid(Y=^JnIDS6@J$jP$wO`bUt5^neF+TZMJNpbwFfE=<dL.627>80_)>!ViHO9vIz7]ebKf-WPz3-%7p]w_1nPBQvyJ_r*^cg['SV3T/t<?UK_ZqgOio<1W])V^'PW^Ev7^_`McptJ3`gig?Hh$DFMgh[yImN`wByK71`iKGSxl_8Fq!?p7WW)]R:8XVy+fJZ6zYJc@ro-!w@'_WN`A7'O]Slqu3gh/RPX!Ps[gJp9IA439Ki3Ak!II7Lgy997x07G][')<2wjcG9H3f'SwP/wKC>o=F7#3mMF9R#1U[5^SQCb:VD*7$G9pj9i7hJq:DMe)rg`lO-kf#2>mv3gzo_Jf?`*]*afAw3#21o/#YC<A9@/!41/zOjJ'<W2Z@?6EN2's]ZiejVf$y!mpqR7b2[ulW:gR.5Bcv[6>C9'Gl7uJHY1%@j!sP>>!bCYTvKIL>wV*`Hq.2q/FBSY?F%_iT7I%AZ<.`7@*)oo+DWqHvHvnK?4OQEzdX+4g.Mrhj(H<WjfG<4gIa([228)?u)*nhKni6oaXD!1YJEEVg07mn1_Ad:6cO37jyJ3?2L?+)$PaLfTKocjN55L@E+cMm4)k3jv.$z_rTgYiga4/""",
           'finpopup2' : 'n=3&d=08%2E09%2E2017',
           'fintargeting' : 'v=1&h=0x000000&hd=131117091117091117091117091117091117',
           'finvisit' : 'v=5&p=16&d=13%2E11%2E2017',
           'i00' : '002963d5e4108c32058a5679f0001%3B5a097588%3B5a3b7d3c',
           'icu' : 'ChgI95w7EAoYAiACKAIwuPaX0AU4AkACSAIQuPaX0AUYAQ..',
           'mjdkyj' : 'AKsRol8bjClrOgYBI9F53uwo0572ZvzG_ifsQhL0W6CGIPDli067aLH682nhCzAvZJLwgmI_hfnp1G_cO6_R7La4pHyjXqGz7w',
           'sess' : '1',
           'utag_main' : 'v_id:015e25c45b49001bad6f158e01b004066002a05e00838$_sn:10$_ss:0$_st:1510571043449$dc_visit:10$dc_visit_dip-main:10$dip_times_empty_enrichment:26$ses_id:1510569240676%3Bexp-session$_pn:1%3Bexp-session$collectCookieMode:3rdParty%3Bexp-session$dc_event:1%3Bexp-session$dip_events_this_session:1%3Bexp-session$dc_event_dip-main:1%3Bexp-session$dc_region_dip-main:eu-central-1%3Bexp-session$dc_region:eu-central-1%3Bexp-session',
           'uuid2' : '869611879133359501',
           'xdefcc' : 'G18e8ffb3a46fc000807955c49556bf4cc'}

Please inform me if I provide in the cookie any personal information. Thanks.

I run my script and expect to get the same data like processing the form manually in my browser, but this didn't worked.

In my console I get:

Test: download()
FAIL!
Done.

The output.html file - generated by my script - contains "Bitte wählen Sie das Start- und Enddatum des Zeitraumes, für den Sie historische Kursdaten anzeigen möchten." (= "Please choose a start and end date for which you want to show historical prices") instead of the data. This messaage is the error message and tolds me to send data to the form - but I had send the data to the website as you can see!

At the moment I don't understand what I can change to get the data instead of this message. Can you give me a tipp, please. Thank you for your efforts and excuse my English!

Body:
You may choose selenium to get the same result. So I modified your code to achieve the values you tried to get.

# -*- coding: utf-8 -*-
import datetime
import requests
import time
import webbrowser
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import io

def getBoersenIndex(boerse):
    """Get index of given boerse.
       To set the value of the boersen dropdown, you have to know the index of the chosen boerse.

        Keyword arguments:
        boerse -- name of boerse as you see in dropdown at the website
    """

    boersen = [
        'Budapest',
        'Berlin',
        'Baader Bank',
        'BX Swiss',
        'Bats',
        'Chi-X',
        'Düsseldorf',
        'Frankfurt',
        'Hamburg',
        'Hannover',
        'Lang und Schwarz',
        'München',
        'Mexiko',
        'Nasdaq OTC',
        'XETRA',
        'Prag',
        'Stuttgart',
        'Swiss Exchange',
        'Tradegate',
        'Wien',
        'Quotrix'
    ]

    for index, boerseName in enumerate(boersen):
        if boerseName == boerse:
            return index+1

def download(startDay, startMonth, startYear, boerse, url):

    today = datetime.date.today()
    inTag1    = str(startDay)
    inMonat1  = str(startMonth)
    inJahr1   = str(startYear + 1 - 1998) # because the dropdown uses the index as a value starting with 1998 = 1
    inTag2    = str(today.day)
    inMonat2  = str(today.month)
    inJahr2   = str(today.year + 1 - 1998) # same as starting year
    strBoerse = str(getBoersenIndex(boerse))

    # this is my webdriver implementation, you may use another one
    options = webdriver.ChromeOptions()
    options.add_argument('headless')
    browser = webdriver.Chrome(<path_to_your_chrome_driver>, chrome_options=options)

    browser.get(url)
    time.sleep(1)

    browser.find_element_by_xpath("//select[@name='inTag1']/option[" +inTag1+ "]").click()
    browser.find_element_by_xpath("//select[@name='inMonat1']/option[" +inMonat1+ "]").click()
    browser.find_element_by_xpath("//select[@name='inJahr1']/option[" +inJahr1+ "]").click()
    browser.find_element_by_xpath("//select[@name='inTag2']/option[" +inTag2+ "]").click()
    browser.find_element_by_xpath("//select[@name='inMonat2']/option[" +inMonat2+ "]").click()
    browser.find_element_by_xpath("//select[@name='inJahr2']/option[" +inJahr2+ "]").click()
    browser.find_element_by_xpath("//select[@name='strBoerse']/option[" +strBoerse+ "]").click()
    browser.find_element_by_css_selector("span.button").click()

    if "08.11.2017" in browser.page_source:
        print("OK")
    else:
        print("FAIL!")

    with io.open("output.html", "w", encoding='utf8') as f:
        f.write(browser.page_source)

if __name__ == "__main__":
    print("Test: download()")
    download(1,1,1998,'XETRA', 'http://www.finanzen.net/historische-kurse/daimler')
    print("Done.")

    webbrowser.open("output.html")


问:
array of DBObject with same keys each element
I am trying to create an array of DBObject, all of the elements have the same key with different values.
what is the problem with this implementation ? </p>

```<code> DBObject[] Out = new BasicDBObject[2];

 out[0].put("VALUE","1");
 out[0].put("PROPERTY","1");

 out[1].put("VALUE","2");
 out[1].put("PROPERTY","2");
</code>```

答:
First, Out and out are mixed up (use upper/lower case consistently)

Second, you need to initialize the objects in the array before you can use them:

```<code>DBObject[] out = new BasicDBObject[2];

out[0] = new BasicDBObject();
out[0].put("VALUE","1");
out[0].put("PROPERTY","1");

out[1] = new BasicDBObject();
out[1].put("VALUE","2");
out[1].put("PROPERTY","2");
</code>```

Body:
I am trying to create an array of DBObject, all of the elements have the same key with different values.
what is the problem with this implementation ?

 DBObject[] Out = new BasicDBObject[2];

 out[0].put("VALUE","1");
 out[0].put("PROPERTY","1");

 out[1].put("VALUE","2");
 out[1].put("PROPERTY","2");

Body:
First, Out and out are mixed up (use upper/lower case consistently)

Second, you need to initialize the objects in the array before you can use them:

DBObject[] out = new BasicDBObject[2];

out[0] = new BasicDBObject();
out[0].put("VALUE","1");
out[0].put("PROPERTY","1");

out[1] = new BasicDBObject();
out[1].put("VALUE","2");
out[1].put("PROPERTY","2");


问:
DRY Then and Always in jQuery Promise
I have the following example JS code:

```<code>function loadData(url, data) {
    return $.get(url, data ? data : {});
}

function example1() {

    showSpinner();

    $.when(loadData('/example1', { hello: 'world' }))
        .then(function (resp) {
            // do something with the data
        })
        .always(function(){
            hideSpinner();
        })
        .fail(function (jqXHR, textStatus, errorThrown) {
            handleError(jqXHR);
        });
}

function example2() {

    showSpinner();

    $.when(loadData('/example2', { hello: 'world' }))
        .then(function (resp) {
            // do something with the data
        })
        .then(function () {
            // do something else
        })
        .always(function(){
            hideSpinner();
        })
        .fail(function (jqXHR, textStatus, errorThrown) {
            handleError(jqXHR);
        });
}
</code>```

Both example1() and example2() use the same promise logic and will do something different with the returned data and then always hide the spinner and handle the failures the same (if any). The issue is that I may want to do different things after the data is loaded in each example and have multiple then's follow.

However I am having to repeat the always and fail code. How can I make them more DRY so they are only written once but used in both scenarios (and other examples if need be). So I can't just move the when into a method and pass a callback as there maybe more than one and in different then`s. So this wouldn't work:

```<code>function customPromise(load, callback) {

    showSpinner();

    $.when(load)
    .then(function (resp) {
        callback(resp);
    })
    .always(function(){
        hideSpinner();
    })
    .fail(function (jqXHR, textStatus, errorThrown) {
        handleError(jqXHR);
    });

}

function example3() {
    customPromise(loadData('/example2', { hello: 'world' }));
}
</code>```

答:
Perhaps you can factor the .when() out into a function returning a promise itself, then call that and chain onto the returned promise with .then(), so something like foobar().then().then(). There's no law stating that always or fail must come last in the chain.

This is a rough sketch for a solution, I have not tested this.

```<code>function loadData(url, data) {
    return $.get(url, data ? data : {});
}

function wrapWhen(endpoint, data) {

    // return a promise
    return $.when(loadData(endpoint, data))
        .always(function(){
            hideSpinner();
        })
        .fail(function (jqXHR, textStatus, errorThrown) {
            handleError(jqXHR);
        });
}

function example1() {

    showSpinner();

    wrapWhen('/example1', {hello: 'world'})
        .then(function (resp) {
            // do something with the data
        });
}

function example2() {

    showSpinner();

    wrapWhen('/example2', {hello: 'world'})
        .then(function (resp) {
            // do something with the data
        })
        .then(function () {
            // do something else
        });
}
</code>```

Title: DRY Then and Always in jQuery Promise

Body:
I have the following example JS code:

function loadData(url, data) {
    return $.get(url, data ? data : {});
}

function example1() {

    showSpinner();

    $.when(loadData('/example1', { hello: 'world' }))
        .then(function (resp) {
            // do something with the data
        })
        .always(function(){
            hideSpinner();
        })
        .fail(function (jqXHR, textStatus, errorThrown) {
            handleError(jqXHR);
        });
}

function example2() {

    showSpinner();

    $.when(loadData('/example2', { hello: 'world' }))
        .then(function (resp) {
            // do something with the data
        })
        .then(function () {
            // do something else
        })
        .always(function(){
            hideSpinner();
        })
        .fail(function (jqXHR, textStatus, errorThrown) {
            handleError(jqXHR);
        });
}

Both example1() and example2() use the same promise logic and will do something different with the returned data and then always hide the spinner and handle the failures the same (if any). The issue is that I may want to do different things after the data is loaded in each example and have multiple then's follow.

However I am having to repeat the always and fail code. How can I make them more DRY so they are only written once but used in both scenarios (and other examples if need be). So I can't just move the when into a method and pass a callback as there maybe more than one and in different then`s. So this wouldn't work:

function customPromise(load, callback) {

    showSpinner();

    $.when(load)
    .then(function (resp) {
        callback(resp);
    })
    .always(function(){
        hideSpinner();
    })
    .fail(function (jqXHR, textStatus, errorThrown) {
        handleError(jqXHR);
    });

}

function example3() {
    customPromise(loadData('/example2', { hello: 'world' }));
}

Body:
Perhaps you can factor the .when() out into a function returning a promise itself, then call that and chain onto the returned promise with .then(), so something like foobar().then().then(). There's no law stating that always or fail must come last in the chain.

This is a rough sketch for a solution, I have not tested this.

function loadData(url, data) {
    return $.get(url, data ? data : {});
}

function wrapWhen(endpoint, data) {

    // return a promise
    return $.when(loadData(endpoint, data))
        .always(function(){
            hideSpinner();
        })
        .fail(function (jqXHR, textStatus, errorThrown) {
            handleError(jqXHR);
        });
}

function example1() {

    showSpinner();

    wrapWhen('/example1', {hello: 'world'})
        .then(function (resp) {
            // do something with the data
        });
}

function example2() {

    showSpinner();

    wrapWhen('/example2', {hello: 'world'})
        .then(function (resp) {
            // do something with the data
        })
        .then(function () {
            // do something else
        });
}


问:
Manage different versions of a Web application
How to implement a concept in Web Application where in i have the flow from one of my version say classic to a newer version we have hosted.
For example in gmail(Regular to Html version) or SharePoint(between different versions)
And also what key points to take care while doing the same.</p>

答:
To implement different web application version, same as having multiple application.
Now, in this case three major factors works.

Source Control and its versioning

Sharing session between two applications

Either share same database or make a copy of another database

Lets focus more on Session sharing.One way is to implement Single Sign On method.
Second one is to having a session manager at single point (SQL- memcached - redis).


问:
Partial template specialization of non type argument not allowed
The following code does not work, it gives an error saying "Too few template arguments for struct foo" and I do not understand why. To me it seems like the code should be valid. I found a snippet from CPP reference here in the section "The argument list", paragraph 4 which might explain why it does not work but I don't understand it.</p>

```<code>template<int a, int b, int c> struct foo { };
template<int a> struct foo<a, 0, 0> { };

int main()
{
    foo<1> f;
}
</code>```

答:
It's allowed. But your template takes 3 parameters. Specializing it doesn't magically turn it into a 1 parameter template.

You can make the other parameter have default arguments, however:

```<code>template<int a, int b = 0, int c = 0> struct foo { char _[1] ; };
template<int a> struct foo<a, 0, 0> { char _[10] ;};

int main() {
    static_assert(sizeof(foo<1>) > sizeof(foo<1, 1, 1>), "");
    return 0;
}
</code>```

Body:
The following code does not work, it gives an error saying "Too few template arguments for struct foo" and I do not understand why. To me it seems like the code should be valid. I found a snippet from CPP reference here in the section "The argument list", paragraph 4 which might explain why it does not work but I don't understand it.

template<int a, int b, int c> struct foo { };
template<int a> struct foo { };

int main()
{
    foo<1> f;
}

Body:
It's allowed. But your template takes 3 parameters. Specializing it doesn't magically turn it into a 1 parameter template.

You can make the other parameter have default arguments, however:

template<int a, int b = 0, int c = 0> struct foo { char _[1] ; };
template<int a> struct foo<a, 0, 0> { char _[10] ;};

int main() {
    static_assert(sizeof(foo<1>) > sizeof(foo<1, 1, 1>), "");
    return 0;
}


问:
Invalid x509 certificate for kubernetes master
I am trying reach my k8s master from my workstation. I can access the master from the LAN fine but not from my workstation. The error message is:

```<code>% kubectl --context=employee-context get pods
Unable to connect to the server: x509: certificate is valid for 10.96.0.1, 10.161.233.80, not 114.215.201.87
</code>```

How can I do to add 114.215.201.87 to the certificate? Do I need to remove my old cluster ca.crt, recreate it, restart whole cluster and then resign client certificate? I have deployed my cluster with kubeadm and I am not sure how to do these steps manually.

答:
This command for new kubernetes >=1.8:

```<code>rm /etc/kubernetes/pki/apiserver.*
kubeadm alpha phase certs all --apiserver-advertise-address=0.0.0.0 --apiserver-cert-extra-sans=10.161.233.80,114.215.201.87
docker rm -f `docker ps -q -f 'name=k8s_kube-apiserver*'`
systemctl restart kubelet
</code>```

Also whould be better to add dns name into --apiserver-cert-extra-sans for avoid issues like this in next time.

Body:
I am trying reach my k8s master from my workstation. I can access the master from the LAN fine but not from my workstation. The error message is:

% kubectl --context=employee-context get pods
Unable to connect to the server: x509: certificate is valid for 10.96.0.1, 10.161.233.80, not 114.215.201.87

How can I do to add 114.215.201.87 to the certificate? Do I need to remove my old cluster ca.crt, recreate it, restart whole cluster and then resign client certificate? I have deployed my cluster with kubeadm and I am not sure how to do these steps manually.

Body:
This command for new kubernetes >=1.8:

rm /etc/kubernetes/pki/apiserver.*
kubeadm alpha phase certs all --apiserver-advertise-address=0.0.0.0 --apiserver-cert-extra-sans=10.161.233.80,114.215.201.87
docker rm -f `docker ps -q -f 'name=k8s_kube-apiserver*'`
systemctl restart kubelet

Also whould be better to add dns name into --apiserver-cert-extra-sans for avoid issues like this in next time.


问:
Make div overlap horizontally the other 4 divs and stretch across the page(height 100%?)
So i have 4 different divs with buttons in them and I'm trying to set up so whenever one of those buttons are being clicked, it will overlap the other divs on the page.

I know it has something to do with z-index and positioning of the divs but I guess it needs to be added to the Jquery rather than the CSS?

I have checked out a previous code, where the divs overlap eachother vertically. Here's that code:

$('#divleft, #divmid, #divright').toggle(function () {
  var cfg = {height:'200', width:'100%'};
  $(this).css({'z-index':100});
  var pct = $(this).css('left').split('p')[0]/$(document).width();

  if(pct <= .33 && pct > 0){
    cfg.left = '0';
    $(this).data('oldLeft', "33%");
  } else if(pct <= .66 && pct > .33) {
    cfg.left = '0';
    $(this).data('oldLeft', "66%");
  }
  $(this).animate(cfg)
}, function () {
  var cfg= {height:'200', width:'33%', 'z-index':1};

  if ($(this).data('oldLeft')) {
    console.log($(this).data('oldLeft'));
    cfg.left = $(this).data('oldLeft');
  }
  $(this).animate(cfg)
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#divleft {
  width:33.3%;
  height:200px;
  background:#ccc;
  z-index: 1;
  margin-top: 10px;
  position: absolute;
  left:0;
}

#divmid {
  width:33.3%;
  height: 200px;
  background: #696;
  margin-top: 10px;
  z-index: 1;
  position:absolute;
  left:33%;
}

#divright {
  width:33.3%;
  height:200px;
  background:#000;
  margin-top: 10px;
  z-index: 1;
  position:absolute;
  left:66%;
}</code>```

Click Me!

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

<p>What this code does is that it overlaps the divs using width 100%, vertically. I was just wondering how you would go about if you were to overlap the divs horizontally. </p>

<p>My code so far is this: </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>html, body {
  width: 80%;
  margin: 0 auto;
}

head {
  text-align:left;
}

head, img {
  width: 350px;
  height: 100px;
  float: left;
  margin-bottom: 1%;
}

.container {
  width: 100%;
  height: 100%;
  margin: 0 auto;
}

button {
  background-color: #cccccc;
  color: #000000;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  border: none;
  text-align: left;
  padding-left: 15%;
  outline: none;
  font-size: 17px;
  transition: 0.4s;
  margin-top: 2%;
}

.icon {
  width: 25px;
  height: 25px;
  padding-right: 15%;
  float: right;
}

button.accordion.active, button.accordion:hover {
  background-color: #ddd;
}</code>```

    <button>
Random
</button>

    <button>
Random
</button>

    <button>
Random
</button>

    <button>
Random
</button>

    <button>
Random
</button>

```

Thanks!

答:
I think what you are trying to get it has more to do with relative height and absolute positioning than with the z-index property only.

Once the element div is clicked it has to cover the parent element. To do that you should put the container the position: relative property and the growing element as position: absolute and the height and width to 100% and positioning top and leftcoinciding with the parent (to 0). The button is inside that div (#first, #second, #third, #last) so it has to be also height: 100%

And finally you just set the z-index to ensure that the current button overlaps and cover the other buttons displayed.

$('.container div').click(function(event){
  $(this).toggleClass('active');

})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html, body{
    width: 80%;
    margin: 0 auto;
}

head{
    text-align:left;
}

head, img{
    width: 350px;
    height: 100px;
    float: left;
    margin-bottom: 1%;
}

.container{
    width: 100%;
    height: 100%;
    margin: 0 auto;
    position: relative;
}

button{
    background-color: #cccccc;
    color: #000000;
    cursor: pointer;
    padding: 18px;
    width: 100%;
    border: none;
    text-align: left;
    padding-left: 15%;
    outline: none;
    font-size: 17px;

    margin-top: 2%;
    position: relative;
}

button h3{
    display: flex;
    justify-content: space-around;
    align-items: center;
}
.icon {
    height: 2.5em;
    width: 1.7em;
    float: right;
}

.icon {
    background-image: url(https://cdn.sstatic.net/Sites/stackoverflow/img/sprites.svg?v=1b3cdae197be);
}

.container div.active{
 height: 100%;
 background-color: white;
 position:absolute;
 top:0;
 left:0;
 width: 100%;
 z-index: 2;
}
.container div.active button{
   height: 100%;
}
#first,#second,#third,#fourth,#last{
}</code>```

        <button>
Random

</button>

        <button>
Random

</button>

        <button>
Random

</button>

        <button>
Random

</button>

        <button>
Random

</button>

```

Body:
So i have 4 different divs with buttons in them and I'm trying to set up so whenever one of those buttons are being clicked, it will overlap the other divs on the page.

I know it has something to do with z-index and positioning of the divs but I guess it needs to be added to the Jquery rather than the CSS?

I have checked out a previous code, where the divs overlap eachother vertically. Here's that code:

$('#divleft, #divmid, #divright').toggle(function () {
  var cfg = {height:'200', width:'100%'};
  $(this).css({'z-index':100});
  var pct = $(this).css('left').split('p')[0]/$(document).width();

  if(pct <= .33 && pct > 0){
    cfg.left = '0';
    $(this).data('oldLeft', "33%");
  } else if(pct <= .66 && pct > .33) {
    cfg.left = '0';
    $(this).data('oldLeft', "66%");
  }
  $(this).animate(cfg)
}, function () {
  var cfg= {height:'200', width:'33%', 'z-index':1};

  if ($(this).data('oldLeft')) {
    console.log($(this).data('oldLeft'));
    cfg.left = $(this).data('oldLeft');
  }
  $(this).animate(cfg)
})

#divleft {
  width:33.3%;
  height:200px;
  background:#ccc;
  z-index: 1;
  margin-top: 10px;
  position: absolute;
  left:0;
}

#divmid {
  width:33.3%;
  height: 200px;
  background: #696;
  margin-top: 10px;
  z-index: 1;
  position:absolute;
  left:33%;
}

#divright {
  width:33.3%;
  height:200px;
  background:#000;
  margin-top: 10px;
  z-index: 1;
  position:absolute;
  left:66%;
}

Click Me!

What this code does is that it overlaps the divs using width 100%, vertically. I was just wondering how you would go about if you were to overlap the divs horizontally.

My code so far is this:

html, body {
  width: 80%;
  margin: 0 auto;
}

head {
  text-align:left;
}

head, img {
  width: 350px;
  height: 100px;
  float: left;
  margin-bottom: 1%;
}

.container {
  width: 100%;
  height: 100%;
  margin: 0 auto;
}

button {
  background-color: #cccccc;
  color: #000000;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  border: none;
  text-align: left;
  padding-left: 15%;
  outline: none;
  font-size: 17px;
  transition: 0.4s;
  margin-top: 2%;
}

.icon {
  width: 25px;
  height: 25px;
  padding-right: 15%;
  float: right;
}

button.accordion.active, button.accordion:hover {
  background-color: #ddd;
}

    <button>
Random
</button>

    <button>
Random
</button>

    <button>
Random
</button>

    <button>
Random
</button>

    <button>
Random
</button>

Thanks!

Body:
I think what you are trying to get it has more to do with relative height and absolute positioning than with the z-index property only.

Once the element div is clicked it has to cover the parent element. To do that you should put the container the position: relative property and the growing element as position: absolute and the height and width to 100% and positioning top and leftcoinciding with the parent (to 0). The button is inside that div (#first, #second, #third, #last) so it has to be also height: 100%

And finally you just set the z-index to ensure that the current button overlaps and cover the other buttons displayed.

$('.container div').click(function(event){
  $(this).toggleClass('active');

})

html, body{
    width: 80%;
    margin: 0 auto;
}

head{
    text-align:left;
}

head, img{
    width: 350px;
    height: 100px;
    float: left;
    margin-bottom: 1%;
}

.container{
    width: 100%;
    height: 100%;
    margin: 0 auto;
    position: relative;
}

button{
    background-color: #cccccc;
    color: #000000;
    cursor: pointer;
    padding: 18px;
    width: 100%;
    border: none;
    text-align: left;
    padding-left: 15%;
    outline: none;
    font-size: 17px;

    margin-top: 2%;
    position: relative;
}

button h3{
    display: flex;
    justify-content: space-around;
    align-items: center;
}
.icon {
    height: 2.5em;
    width: 1.7em;
    float: right;
}

.icon {
    background-image: url(https://cdn.sstatic.net/Sites/stackoverflow/img/sprites.svg?v=1b3cdae197be);
}

.container div.active{
 height: 100%;
 background-color: white;
 position:absolute;
 top:0;
 left:0;
 width: 100%;
 z-index: 2;
}
.container div.active button{
   height: 100%;
}
#first,#second,#third,#fourth,#last{
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
    <div id="first">
        <button><h3>Random <div class ="icon" /></h3></button>
    </div>

    <div id="second">
        <button><h3>Random <div class ="icon" /></h3></button>
    </div>

    <div id="third">
        <button><h3>Random <div class ="icon" /></h3></button>
    </div>

    <div id="fourth">
        <button><h3>Random <div class ="icon" /></h3></button>
    </div>

    <div id="last">
        <button><h3>Random <div class ="icon" /></h3></button>
    </div>

</div>