问:
How to display openweathermap weather icon
I am using openweathermap to display weather reports. Everything is working fine but there is a problem with the icon.
The JSON response code is:

```<code>Array
(
    [city] => Array
        (
            [id] => 1271476
            [name] => Guwahati
            [coord] => Array
                (
                    [lon] => 91.751
                    [lat] => 26.1862
                )

            [country] => IN
            [population] => 899094
        )

    [cod] => 200
    [message] => 0.0630711
    [cnt] => 1
    [list] => Array
        (
            [0] => Array
                (
                    [dt] => 1495688400
                    [temp] => Array
                        (
                            [day] => 33
                            [min] => 24.89
                            [max] => 33.82
                            [night] => 24.89
                            [eve] => 30.6
                            [morn] => 33
                        )

                    [pressure] => 1013.02
                    [humidity] => 90
                    [weather] => Array
                        (
                            [0] => Array
                                (
                                    [id] => 500
                                    [main] => Rain
                                    [description] => light rain
                                    [icon] => 10d
                                )

                        )

                    [speed] => 3.92
                    [deg] => 88
                    [clouds] => 24
                    [rain] => 2.73
                )

        )

)
</code>```

Now how can I display the icon: [weather][0][icon] => 10d?

What is 10d & how can I get the URL of the icon?

答:
Thank you all very much! I am a very beginning Flutter programmer and wanted to display the Icon in the Weatherapp, we made on course with Angela Yu.

I did this in Flutter:

```<code>String weerImageString;
weerImageString = weatherData['weather'][0]['icon'];
</code>```

and then were I wanted it to display, I did:

```<code>Image.network('http://openweathermap.org/img/w/$weerImageString.png',),
</code>```

I hope that I can someday helping someone with this. And... if there is an easier way, I would love to hear!

Body:
I am using openweathermap to display weather reports. Everything is working fine but there is a problem with the icon.
The JSON response code is:

Array
(
    [city] => Array
        (
            [id] => 1271476
            [name] => Guwahati
            [coord] => Array
                (
                    [lon] => 91.751
                    [lat] => 26.1862
                )

            [country] => IN
            [population] => 899094
        )

    [cod] => 200
    [message] => 0.0630711
    [cnt] => 1
    [list] => Array
        (
            [0] => Array
                (
                    [dt] => 1495688400
                    [temp] => Array
                        (
                            [day] => 33
                            [min] => 24.89
                            [max] => 33.82
                            [night] => 24.89
                            [eve] => 30.6
                            [morn] => 33
                        )

                    [pressure] => 1013.02
                    [humidity] => 90
                    [weather] => Array
                        (
                            [0] => Array
                                (
                                    [id] => 500
                                    [main] => Rain
                                    [description] => light rain
                                    [icon] => 10d
                                )

                        )

                    [speed] => 3.92
                    [deg] => 88
                    [clouds] => 24
                    [rain] => 2.73
                )

        )

)

Now how can I display the icon: [weather][0][icon] => 10d?

What is 10d & how can I get the URL of the icon?

Body:
Thank you all very much! I am a very beginning Flutter programmer and wanted to display the Icon in the Weatherapp, we made on course with Angela Yu.

I did this in Flutter:

String weerImageString;
weerImageString = weatherData['weather'][0]['icon'];

and then were I wanted it to display, I did:

Image.network('http://openweathermap.org/img/w/$weerImageString.png',),

I hope that I can someday helping someone with this. And... if there is an easier way, I would love to hear!


来源: stackexchange

问:
Config Transform, Unrecognized XML Namespace After Transformation
One of our config files is being transformed oddly.

Base Config

```<code><?xml version="1.0"?>
<configuration >

</configuration>
</code>```

Release Config (as it is in the project, truncated for brevity)

```<code><?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform" xmlns:role="http://www.sitecore.net/xmlconfig/role/" xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore xdt:Transform="Insert">
    <contentSearch>
      <configuration>
        <indexes>
          <index id="sitecore_web_index">
            <param desc="core" patch:instead="param[@desc='core']">#{IndexEnvironment}#_web_index</param>
          </index>
        </indexes>
        <indexes role:require="Standalone or ContentManagement">
          <index id="sitecore_master_index">
            <param desc="core" patch:instead="param[@desc='core']">#{IndexEnvironment}#_master_index</param>
          </index>
</code>```

After a build is run, the output of the final config looks very strange:

Post build

```<code><?xml version="1.0"?>
<configuration>
    <sitecore>
        <contentSearch>
            <configuration>
                <indexes>
                    <index id="sitecore_web_index">
                        <param desc="core" d7p1:instead="param[@desc='core']" xmlns:d7p1="http://www.sitecore.net/xmlconfig/">ASHQA_web_index</param>
                    </index>
                </indexes>
                <indexes d5p1:require="Standalone or ContentManagement" xmlns:d5p1="http://www.sitecore.net/xmlconfig/role/">
                    <index id="sitecore_master_index">
                        <param desc="core" d7p1:instead="param[@desc='core']" xmlns:d7p1="http://www.sitecore.net/xmlconfig/">ASHQA_master_index</param>
                    </index>
</code>```

Notice how the patch and role definitions are changed to d7p1 and d5p1 respectively.

While this is valid XML, it is causing issues in our application which parses the XML and looks for the proper terms of patch and role.

答:
TL;DR

Any namespaces required in a transformed config, need to be defined in the base config.

Base Config Updates

```<code><?xml version="1.0"?>
<configuration xmlns:role="http://www.sitecore.net/xmlconfig/role/" xmlns:patch="http://www.sitecore.net/xmlconfig/">

</configuration>
</code>```

Even though the base config does not rely on these namespaces, they do not carry over properly if they are not included. This also cleans up the output of the resulting config as expected:

```<code><?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform" xmlns:role="http://www.sitecore.net/xmlconfig/role/" xmlns:patch="http://www.sitecore.net/xmlconfig/">
    <sitecore>
        <contentSearch>
            <configuration>
                <indexes>
                    <index id="sitecore_web_index">
                        <param desc="core" patch:instead="param[@desc='core']">#{IndexEnvironment}#_web_index</param>
                    </index>
                </indexes>
                <indexes role:require="Standalone or ContentManagement">
                    <index id="sitecore_master_index">
                        <param desc="core" patch:instead="param[@desc='core']">#{IndexEnvironment}#_master_index</param>
                    </index>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
One of our config files is being transformed oddly.

Base Config

<?xml version="1.0"?>
<configuration >

</configuration>

Release Config (as it is in the project, truncated for brevity)

<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform" xmlns:role="http://www.sitecore.net/xmlconfig/role/" xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore xdt:Transform="Insert">
    <contentSearch>
      <configuration>
        <indexes>
          <index id="sitecore_web_index">
            <param desc="core" patch:instead="param[@desc='core']">#{IndexEnvironment}#_web_index</param>
          </index>
        </indexes>
        <indexes role:require="Standalone or ContentManagement">
          <index id="sitecore_master_index">
            <param desc="core" patch:instead="param[@desc='core']">#{IndexEnvironment}#_master_index</param>
          </index>

After a build is run, the output of the final config looks very strange:

Post build

<?xml version="1.0"?>
<configuration>
    <sitecore>
        <contentSearch>
            <configuration>
                <indexes>
                    <index id="sitecore_web_index">
                        <param desc="core" d7p1:instead="param[@desc='core']" xmlns:d7p1="http://www.sitecore.net/xmlconfig/">ASHQA_web_index</param>
                    </index>
                </indexes>
                <indexes d5p1:require="Standalone or ContentManagement" xmlns:d5p1="http://www.sitecore.net/xmlconfig/role/">
                    <index id="sitecore_master_index">
                        <param desc="core" d7p1:instead="param[@desc='core']" xmlns:d7p1="http://www.sitecore.net/xmlconfig/">ASHQA_master_index</param>
                    </index>

Notice how the patch and role definitions are changed to d7p1 and d5p1 respectively.

While this is valid XML, it is causing issues in our application which parses the XML and looks for the proper terms of patch and role.

Body:
TL;DR

Any namespaces required in a transformed config, need to be defined in the base config.

Base Config Updates

<?xml version="1.0"?>
<configuration xmlns:role="http://www.sitecore.net/xmlconfig/role/" xmlns:patch="http://www.sitecore.net/xmlconfig/">

</configuration>

Even though the base config does not rely on these namespaces, they do not carry over properly if they are not included. This also cleans up the output of the resulting config as expected:

<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform" xmlns:role="http://www.sitecore.net/xmlconfig/role/" xmlns:patch="http://www.sitecore.net/xmlconfig/">
    <sitecore>
        <contentSearch>
            <configuration>
                <indexes>
                    <index id="sitecore_web_index">
                        <param desc="core" patch:instead="param[@desc='core']">#{IndexEnvironment}#_web_index</param>
                    </index>
                </indexes>
                <indexes role:require="Standalone or ContentManagement">
                    <index id="sitecore_master_index">
                        <param desc="core" patch:instead="param[@desc='core']">#{IndexEnvironment}#_master_index</param>
                    </index>


问:
SqlAlchemy automap not generating Base.classes.[table_name]
I have an existing sqlite db file imported from csv. I tried to use sqlalchemy to automap the db file. But it always gives me...

Traceback (most recent call last):
  File "", line 1, in
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\sqlalchemy\util_colle
ctions.py", line 212, in getattr
    raise AttributeError(key)
AttributeError: destinationservices

Any help is appreciated.

```<code>from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine

Base = automap_base()

# engine, suppose it has two tables 'user' and 'address' set up
engine = create_engine("sqlite:///destServ.db")

# reflect the tables
Base.prepare(engine, reflect=True)

# mapped classes are now created with names by default
# matching that of the table name.
Service = Base.classes.destinationServices
</code>```

答:
Forgive me answering an old question, but the reason this happens is because of limitations in the reflection capabilities, and it rears its head more often with SQLite databases because they are often over-simplified.  To make automap_base work, you need to make sure your SQLite database tables have a primary key with a unique value (yes, this sounds redundant, but apparently they have different meanings in SQLite?).

If you are using DB Browser for SQLite (https://sqlitebrowser.org/ -- works on Mac and Windows), you can click on the "Database Structure" tab, click on a table name, then a "Modify Table" sub-tab should become visible in the secondary tabs just below the main tabs (the UI is a bit weird).

Once you're in the "Modify Table" popup window, find your table's primary key and make sure you check both the PK and U boxes (for Primary Key and Unique).  While you're in there, you can take the opportunity to make sure your columns have sensible types (e.g. make sure number columns use the proper numeric type).  Click Ok when you're done.

Once your database is properly defined, print(Base.classes.keys()) should reveal all the tables in your database.

ContentLicense: CC BY-SA 3.0

Body:
I have an existing sqlite db file imported from csv. I tried to use sqlalchemy to automap the db file. But it always gives me...

Traceback (most recent call last):
  File "", line 1, in
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\sqlalchemy\util_colle
ctions.py", line 212, in getattr
    raise AttributeError(key)
AttributeError: destinationservices

Any help is appreciated.

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine

Base = automap_base()

# engine, suppose it has two tables 'user' and 'address' set up
engine = create_engine("sqlite:///destServ.db")

# reflect the tables
Base.prepare(engine, reflect=True)

# mapped classes are now created with names by default
# matching that of the table name.
Service = Base.classes.destinationServices


问:
Button not being positioned in React Native
My button seems to be not positioned in my react native project. The code that I have looks like this:

```<code><Button style = "centered"
      onPress = {() => {Alert.alert('Button tapped!');} }
      title = "Confirm"
    />
</code>```

Then in my style sheet I did this :

```<code> centered:{
    position: 'absolute',
    top : 350,
}
</code>```

And it did not work. Some other things that I tried:

```<code>style = {centered}
</code>```

Gives a run-time error saying can not find variable centered

```<code>class = "centered"
</code>```

Does not do anything, either.

According to suggestion, I tried creating a separate View for my button alone, but it gave an error saying JSX expressions must have one parent element. The code I tried:

```<code><View style={styles.container}>
    <Text>Select a time to be notified : </Text>
    <Picker
      style={styles.picker} itemStyle={styles.pickerItem}
      selectedValue={this.state.time}
      onValueChange={(itemValue) => this.setState({time: itemValue})}
    >
    <Picker.Item label="Now" value="now" />
      <Picker.Item label="After 1 minute" value="1min" />
      <Picker.Item label="After 5 minutes" value="5min" />
      <Picker.Item label="Custom time" value="ctime" />
    </Picker>
  </View>
  <View>
    <Button style = {{marginTop:350}}
    onPress = {() => {Alert.alert('Button tapped!');} }
    title = "Confirm"
    />
  </View>
);
</code>```

Style sheet:

```<code>const styles = StyleSheet.create({

 container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },

  picker :{
    width: 200,
    height: 44,
    backgroundColor: '#CCE6FF',
    borderColor: 'white',
    borderWidth: 1,
  },

  pickerItem :{
    width: 200,
    height: 88,
    backgroundColor: '#CCE6FF',
    borderColor: 'black',
    borderWidth: 1,
  },

  notificationButton :{
    position: 'absolute',
    top : 50,
  },
});
</code>```

答:
You need change the properties:

```<code><Button style ={styles.centered}
      onPress = {() => {Alert.alert('Button tapped!');} }
      title = "Confirm"
    />
</code>```

and the style:

```<code>const styles = StyleSheet.create({
  centered:{
  position: 'absolute',
  top : 350,
  }
})
</code>```

Body:
My button seems to be not positioned in my react native project. The code that I have looks like this:

<Button style = "centered"
      onPress = {() => {Alert.alert('Button tapped!');} }
      title = "Confirm"
    />

Then in my style sheet I did this :

 centered:{
    position: 'absolute',
    top : 350,
}

And it did not work. Some other things that I tried:

style = {centered}

Gives a run-time error saying can not find variable centered

class = "centered"

Does not do anything, either.

According to suggestion, I tried creating a separate View for my button alone, but it gave an error saying JSX expressions must have one parent element. The code I tried:

<View style={styles.container}>
    <Text>Select a time to be notified : </Text>
    <Picker
      style={styles.picker} itemStyle={styles.pickerItem}
      selectedValue={this.state.time}
      onValueChange={(itemValue) => this.setState({time: itemValue})}
    >
    <Picker.Item label="Now" value="now" />
      <Picker.Item label="After 1 minute" value="1min" />
      <Picker.Item label="After 5 minutes" value="5min" />
      <Picker.Item label="Custom time" value="ctime" />
    </Picker>
  </View>
  <View>
    <Button style = {{marginTop:350}}
    onPress = {() => {Alert.alert('Button tapped!');} }
    title = "Confirm"
    />
  </View>
);

Style sheet:

const styles = StyleSheet.create({

 container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },

  picker :{
    width: 200,
    height: 44,
    backgroundColor: '#CCE6FF',
    borderColor: 'white',
    borderWidth: 1,
  },

  pickerItem :{
    width: 200,
    height: 88,
    backgroundColor: '#CCE6FF',
    borderColor: 'black',
    borderWidth: 1,
  },

  notificationButton :{
    position: 'absolute',
    top : 50,
  },
});

Body:
You need change the properties:

<Button style ={styles.centered}
      onPress = {() => {Alert.alert('Button tapped!');} }
      title = "Confirm"
    />

and the style:

const styles = StyleSheet.create({
  centered:{
  position: 'absolute',
  top : 350,
  }
})


问:
What's the best way to store the minimum differential data of a changed object?
I have an object which contains many properties, of many datatypes which is the settings for a search of a large cache. I would like to pass the values which have been changed on this object from the base settings and only the changes. I would also like to pass this information as a very short string.

So what I need is a technique for doing this in C# .NET 4 (pseudo code follows):

```<code>var changes = Diff(changedobject, baseobject);
return changes.ToShortString()
</code>```

and later on a remote machine which only knows the object

```<code>var changedobject = CreateObject(diffstring)
</code>```

Any ideas would be much appreciated.

Thanks

答:
The CSLA.NET framework uses reflection to walk the properties and fields of a type and write them to a hash table.  This hash table is then serialized and stored.

The type is called UndoableBase, in the CSLA.NET project.

I can't remember if it records diffs, but the premise is that you need a copy of the state before (in the CSLA case, this would be the previously serialized item).

Assuming you have a copy of an item (an actual copying, not a reference) as a source of originals, then you can use reflection to check each property and add it to the hash table if it has changed.

Send this hash table over the wire.

An alternative and one that I would look at more, is to prefix your serialized item with bit flags denoting what fields are provided in the forthcoming stream.  This will likely be more compact than a hash table of name values.  You can include this in your reflection solution by first sorting the fields / properties alphabetically (or by some other means).  This won't be version tolerant, however, if you store this serialized data across versions of the type.

Body:
I have an object which contains many properties, of many datatypes which is the settings for a search of a large cache. I would like to pass the values which have been changed on this object from the base settings and only the changes. I would also like to pass this information as a very short string.

So what I need is a technique for doing this in C# .NET 4 (pseudo code follows):

var changes = Diff(changedobject, baseobject);
return changes.ToShortString()

and later on a remote machine which only knows the object

var changedobject = CreateObject(diffstring)

Any ideas would be much appreciated.

Thanks


问:
JavaFX line chart change color shape
I have this window:

```<code>@Override
public void start(Stage primaryStage){

    NumberAxis xAxis = new NumberAxis(1960, 2020, 10);
    xAxis.setLabel("Years");

    NumberAxis yAxis = new NumberAxis(0, 350, 50);
    yAxis.setLabel("No.of schools");

    LineChart<Number, Number> lineChart = new LineChart<>(xAxis, yAxis);
    lineChart.setTitle("Chart");

    XYChart.Series<Number, Number> series = new XYChart.Series<>();
    series.setName("No of schools in an year");
    Platform.runLater(() ->
        series.getNode().lookup(".chart-series-line").setStyle("-fx-stroke: black;")
    );

    series.getData().add(new XYChart.Data<>(1970, 15));
    series.getData().add(new XYChart.Data<>(1980, 30));
    series.getData().add(new XYChart.Data<>(1990, 60));
    series.getData().add(new XYChart.Data<>(2000, 120));
    series.getData().add(new XYChart.Data<>(2013, 240));
    series.getData().add(new XYChart.Data<>(2014, 300));

    lineChart.getData().add(series);

    var scene = new Scene(lineChart);

    primaryStage.setScene(scene);
    primaryStage.show();

}
</code>```

This is how it looks:

I want to change the color of series, but what I can achieve is to change color of line, but shape not.

How I can change the color of shape?

答:
What about some css? These are list of css that can be used with line chart.You can combine lookup, setStyle and css property to change the style dynamically.

```<code>.chart {
    -fx-padding: 10px;
    -fx-background-image: url("icon.png");
}
.chart-content {
    -fx-padding: 30px;
}

.chart-title {
  -fx-text-fill: #4682b4;
  -fx-font-size: 1.6em;
}

.axis-label {
  -fx-text-fill: #4682b4;
}

.chart-legend {
   -fx-background-color:  transparent;
   -fx-padding: 20px;
}

.chart-legend-item-symbol{
   -fx-background-radius: 0;
}

.chart-legend-item{
    -fx-text-fill: #191970;
}

.chart-plot-background {
    -fx-background-color: #e2ecfe;
}
.chart-vertical-grid-lines {
    -fx-stroke: #3278fa;
}
.chart-horizontal-grid-lines {
    -fx-stroke: #3278fa;
}
.chart-alternative-row-fill {
    -fx-fill: #99bcfd;
    -fx-stroke: transparent;
    -fx-stroke-width: 0;
}
</code>```

More on https://docs.oracle.com/javafx/2/charts/css-styles.htm

Title: JavaFX line chart change color shape

Body:
I have this window:

@Override
public void start(Stage primaryStage){

    NumberAxis xAxis = new NumberAxis(1960, 2020, 10);
    xAxis.setLabel("Years");

    NumberAxis yAxis = new NumberAxis(0, 350, 50);
    yAxis.setLabel("No.of schools");

    LineChart<Number, Number> lineChart = new LineChart<>(xAxis, yAxis);
    lineChart.setTitle("Chart");

    XYChart.Series<Number, Number> series = new XYChart.Series<>();
    series.setName("No of schools in an year");
    Platform.runLater(() ->
        series.getNode().lookup(".chart-series-line").setStyle("-fx-stroke: black;")
    );

    series.getData().add(new XYChart.Data<>(1970, 15));
    series.getData().add(new XYChart.Data<>(1980, 30));
    series.getData().add(new XYChart.Data<>(1990, 60));
    series.getData().add(new XYChart.Data<>(2000, 120));
    series.getData().add(new XYChart.Data<>(2013, 240));
    series.getData().add(new XYChart.Data<>(2014, 300));

    lineChart.getData().add(series);

    var scene = new Scene(lineChart);

    primaryStage.setScene(scene);
    primaryStage.show();

}

This is how it looks:

I want to change the color of series, but what I can achieve is to change color of line, but shape not.

How I can change the color of shape?

Body:
What about some css? These are list of css that can be used with line chart.You can combine lookup, setStyle and css property to change the style dynamically.

.chart {
    -fx-padding: 10px;
    -fx-background-image: url("icon.png");
}
.chart-content {
    -fx-padding: 30px;
}

.chart-title {
  -fx-text-fill: #4682b4;
  -fx-font-size: 1.6em;
}

.axis-label {
  -fx-text-fill: #4682b4;
}

.chart-legend {
   -fx-background-color:  transparent;
   -fx-padding: 20px;
}

.chart-legend-item-symbol{
   -fx-background-radius: 0;
}

.chart-legend-item{
    -fx-text-fill: #191970;
}

.chart-plot-background {
    -fx-background-color: #e2ecfe;
}
.chart-vertical-grid-lines {
    -fx-stroke: #3278fa;
}
.chart-horizontal-grid-lines {
    -fx-stroke: #3278fa;
}
.chart-alternative-row-fill {
    -fx-fill: #99bcfd;
    -fx-stroke: transparent;
    -fx-stroke-width: 0;
}

More on https://docs.oracle.com/javafx/2/charts/css-styles.htm


问:
Selenium Button Selector and Click
I want to automate the restart of my router using Selenium on Python. Everything is working fine except for the last step, which is locating the restart button and click it!

I have tried to locate it by (id, css_selector, name, value, xpath), but nothing seemed to work.

Here is my code:

```<code>driver = webdriver.Firefox()
driver.get('http://192.168.100.1')

english = driver.find_element_by_id("English")
english.click()

usr = "username"
pwd = "password"

usrname_box = driver.find_element_by_id("txt_Username")
usrname_box.send_keys(usr)

pwd_box = driver.find_element_by_id("txt_Password")
pwd_box.send_keys(pwd)

submit_ = driver.find_element_by_id("button")
submit_.click()
sleep(1)

resetit = driver.find_element_by_name("maindiv_reset")
resetit.click()
sleep(1)

# This is the one I want to locate
reboot = driver.find_element_by_xpath("//input[@id='btnReboot']")
reboot.click()
</code>```

And this is the HTML code for the target button:

```<code><input class="ApplyButtoncss buttonwidth_150px" name="btnReboot" id="btnReboot" type="button" onclick="Reboot()" bindtext="s0603" value="Restart">
</code>```

When trying anything, I get the error:

```<code>NoSuchElementException: Message: Unable to locate element: (WHATEVER I TRY)
</code>```

A Screenshot of the HTML Page:

Thank you all for your help in advance.

答: As a last ditch solution you can tell Python to click the Restart button assuming you can find the pixel (X, Y) coordinates on the screen and assuming the Firefox browser does not shift when running the script. See here.</p>

Title: Selenium Button Selector and Click

Body:
I want to automate the restart of my router using Selenium on Python. Everything is working fine except for the last step, which is locating the restart button and click it!

I have tried to locate it by (id, css_selector, name, value, xpath), but nothing seemed to work.

Here is my code:

driver = webdriver.Firefox()
driver.get('http://192.168.100.1')

english = driver.find_element_by_id("English")
english.click()

usr = "username"
pwd = "password"

usrname_box = driver.find_element_by_id("txt_Username")
usrname_box.send_keys(usr)

pwd_box = driver.find_element_by_id("txt_Password")
pwd_box.send_keys(pwd)

submit_ = driver.find_element_by_id("button")
submit_.click()
sleep(1)

resetit = driver.find_element_by_name("maindiv_reset")
resetit.click()
sleep(1)

# This is the one I want to locate
reboot = driver.find_element_by_xpath("//input[@id='btnReboot']")
reboot.click()

And this is the HTML code for the target button:

<input class="ApplyButtoncss buttonwidth_150px" name="btnReboot" id="btnReboot" type="button" onclick="Reboot()" bindtext="s0603" value="Restart">

When trying anything, I get the error:

NoSuchElementException: Message: Unable to locate element: (WHATEVER I TRY)

A Screenshot of the HTML Page:

Thank you all for your help in advance.


问:
Unable to upload and download attachment in corda 4.0 ( java) showing null
uploading and downloading zip attachment containing a text file in corda not working

Tried  to attach and download a zip file manually and also tried to send the attachment using client RPC using proxy.

flow code:

```<code>public class IOUFlow extends FlowLogic<Void> {
    private final Integer iouValue;
    private final Party otherParty;
    private final SecureHash attachmentHash;

    public IOUFlow(Integer iouValue, Party otherParty,SecureHash attachmentHash) {
        this.iouValue = iouValue;
        this.otherParty = otherParty;
        this.attachmentHash=attachmentHash;
    }

    @Override
    public ProgressTracker getProgressTracker() {
        return progressTracker;
    }
    private static final Step ID_OTHER_NODES = new Step("Identifying other nodes on the network.");
    private static final Step SENDING_AND_RECEIVING_DATA = new Step("Sending data between parties.");
    private static final Step EXTRACTING_VAULT_STATES = new Step("Extracting states from the vault.");
    private static final Step OTHER_TX_COMPONENTS = new Step("Gathering a transaction's other components.");
    private static final Step TX_BUILDING = new Step("Building a transaction.");
    private static final Step TX_SIGNING = new Step("Signing a transaction.");
    private static final Step TX_VERIFICATION = new Step("Verifying a transaction.");
    private static final Step SIGS_GATHERING = new Step("Gathering a transaction's signatures.") {
        // Wiring up a child progress tracker allows us to see the
        // subflow's progress steps in our flow's progress tracker.
        @Override
        public ProgressTracker childProgressTracker() {
            return CollectSignaturesFlow.tracker();
        }
    };
    private static final Step VERIFYING_SIGS = new Step("Verifying a transaction's signatures.");
    private static final Step FINALISATION = new Step("Finalising a transaction.") {
        @Override
        public ProgressTracker childProgressTracker() {
            return FinalityFlow.tracker();
        }
    };

    private final ProgressTracker progressTracker = new ProgressTracker(
            ID_OTHER_NODES,
            SENDING_AND_RECEIVING_DATA,
            EXTRACTING_VAULT_STATES,
            OTHER_TX_COMPONENTS,
            TX_BUILDING,
            TX_SIGNING,
            TX_VERIFICATION,
            SIGS_GATHERING,
            FINALISATION
    );

    @Suspendable
    @Override
    public Void call() throws FlowException {
        progressTracker.setCurrentStep(ID_OTHER_NODES);
        // We retrieve the notary identity from the network map.
        Party notary = getServiceHub().getNetworkMapCache().getNotaryIdentities().get(0);

        progressTracker.setCurrentStep(SENDING_AND_RECEIVING_DATA);
        // We create the transaction components.
                IOUState outputState = new IOUState(iouValue, getOurIdentity(), otherParty);
                List<PublicKey> requiredSigners = Arrays.asList(getOurIdentity().getOwningKey(), otherParty.getOwningKey());
                Command command = new Command<>(new IOUContract.Create(), requiredSigners);

        TimeWindow ourAfter = TimeWindow.fromOnly(Instant.MIN);
        progressTracker.setCurrentStep(TX_BUILDING);
        // We create a transaction builder and add the components.
                TransactionBuilder txBuilder = new TransactionBuilder(notary)
                        .addOutputState(outputState, IOUContract.ID)
                        .addCommand(command)
                        .addAttachment(attachmentHash);

        // Verifying the transaction.
                txBuilder.verify(getServiceHub());

        progressTracker.setCurrentStep(TX_SIGNING);
        // Signing the transaction.
                SignedTransaction signedTx = getServiceHub().signInitialTransaction(txBuilder);

        // Creating a session with the other party.
                FlowSession otherPartySession = initiateFlow(otherParty);

        // Obtaining the counterparty's signature.
                SignedTransaction fullySignedTx = subFlow(new CollectSignaturesFlow(
                        signedTx, Arrays.asList(otherPartySession), CollectSignaturesFlow.tracker()));
        progressTracker.setCurrentStep(TX_VERIFICATION);

        // Finalising the transaction.
                subFlow(new FinalityFlow(fullySignedTx, otherPartySession));

                return null;
    }
}
</code>```

client code:

```<code>public class Client {
    private static final Logger logger = LoggerFactory.getLogger(Client.class);

    public static void main(String[] args) throws Exception {
        // Create an RPC connection to the node.
        if (args.length != 3) throw new IllegalArgumentException("Usage: Client <node address> <rpc username> <rpc password>");
        final NetworkHostAndPort nodeAddress = parse(args[0]);
        final String rpcUsername = args[1];
        final String rpcPassword = args[2];
        final CordaRPCClient client = new CordaRPCClient(nodeAddress);
        final CordaRPCOps proxy = client.start(rpcUsername, rpcPassword).getProxy();

        // Interact with the node.
        // For example, here we print the nodes on the network.
        final List<NodeInfo> nodes = proxy.networkMapSnapshot();
        logger.info("{}", nodes);
        InputStream inputstream = new FileInputStream("corda.zip");

        SecureHash hashId= proxy.uploadAttachment(inputstream);
        System.out.println(hashId);

        CordaX500Name x500Name = CordaX500Name.parse("O=ICICI,L=New York,C=US");
        final Party otherParty = proxy.wellKnownPartyFromX500Name(x500Name);

       /* proxy
                .startFlowDynamic(IOUFlow.class, "10", otherParty,hashId)
                .getReturnValue()
                .get();*/

        InputStream stream = proxy.openAttachment(hashId);

        JarInputStream in = new JarInputStream(stream);
        BufferedReader br =new BufferedReader(new InputStreamReader(in));
        System.out.println("Output from attachment :   "+br.readLine());

    }
}
</code>```

Output:

Task :clients:runTemplateClient
  I 16:36:28 1 RPCClient.logElapsedTime - Startup took 2066 msec
  I 16:36:28 1 Client.main - [NodeInfo(addresses=[localhost:10005], legalIdentitiesAndCerts=[O=PNB, L=London, C=GB], platformVersion=4, serial=1559037129874), NodeInfo(addresses=[localhost:10002], legalIdentitiesAndCerts=[O=Notary, L=London, C=GB], platformVersion=4, serial=1559037126875), NodeInfo(addresses=[localhost:10008], legalIdentitiesAndCerts=[O=ICICI, L=New York, C=US], platformVersion=4, serial=1559037128218)]

DF3C198E05092E52F47AE8EAA0D5D26721F344B3F5E0DF80B5A53CA2B7104C9C
Output from attachment :   null

Another output:when tried to send the attachment from client using RPC

Task :clients:runTemplateClient
  I 16:41:46 1 RPCClient.logElapsedTime - Startup took 2045 msec
  I 16:41:47 1 Client.main - [NodeInfo(addresses=[localhost:10005], legalIdentitiesAndCerts=[O=PNB, L=London, C=GB], platformVersion=4, serial=1559037129874), NodeInfo(addresses=[localhost:10002], legalIdentitiesAndCerts=[O=Notary, L=London, C=GB], platformVersion=4, serial=1559037126875), NodeInfo(addresses=[localhost:10008], legalIdentitiesAndCerts=[O=ICICI, L=New York, C=US], platformVersion=4, serial=1559037128218)]
  B7F5F70FC9086ED594883E6EB8B0B53B666B92CC4412E27FF3D6531446E9E40C
  Exception in thread "main" net.corda.core.CordaRuntimeException: net.corda.core.flows.IllegalFlowLogicException: A FlowLogicRef cannot be constructed for FlowLogic of type com.template.flows.IOUFlow: due to missing constructor for arguments: [class java.lang.String, class net.corda.core.identity.Party, class net.corda.core.crypto.SecureHash$SHA256]

答:
thanks for raising this question. This is definitely something we could improve in the developer experience.

Essentially there are two-steps to adding an attachment to a TX.

The first step is importing the attachment itself into the node (which it seems you've already done):

SecureHash attachmentHash = getServiceHub().getAttachments().importAttachment(INPUT-FILE, getOurIdentity().getName().toString(), INPUT-FILE.getName());

Replace INPUT-FILE with a java File instance.

The second is to add the attachment hash to the TX (which you have already done as well)

.addAttachment(attachmentHash);

You can facilitate the first step either explicitly via flow logic OR using the RPC proxy as you've done here.

For the second error you've listed:

The exception you've posted however is related to the way you're invoking your IOUFlow. The IOUFlow is expecting an Integer as the first argument but we are providing a String - this is causing the IllegalFlowLogicException. Try providing an Int OR changing the IOUFlow to expect a string input to be converted to an Int.

Body:
uploading and downloading zip attachment containing a text file in corda not working

Tried  to attach and download a zip file manually and also tried to send the attachment using client RPC using proxy.

flow code:

public class IOUFlow extends FlowLogic<Void> {
    private final Integer iouValue;
    private final Party otherParty;
    private final SecureHash attachmentHash;

    public IOUFlow(Integer iouValue, Party otherParty,SecureHash attachmentHash) {
        this.iouValue = iouValue;
        this.otherParty = otherParty;
        this.attachmentHash=attachmentHash;
    }

    @Override
    public ProgressTracker getProgressTracker() {
        return progressTracker;
    }
    private static final Step ID_OTHER_NODES = new Step("Identifying other nodes on the network.");
    private static final Step SENDING_AND_RECEIVING_DATA = new Step("Sending data between parties.");
    private static final Step EXTRACTING_VAULT_STATES = new Step("Extracting states from the vault.");
    private static final Step OTHER_TX_COMPONENTS = new Step("Gathering a transaction's other components.");
    private static final Step TX_BUILDING = new Step("Building a transaction.");
    private static final Step TX_SIGNING = new Step("Signing a transaction.");
    private static final Step TX_VERIFICATION = new Step("Verifying a transaction.");
    private static final Step SIGS_GATHERING = new Step("Gathering a transaction's signatures.") {
        // Wiring up a child progress tracker allows us to see the
        // subflow's progress steps in our flow's progress tracker.
        @Override
        public ProgressTracker childProgressTracker() {
            return CollectSignaturesFlow.tracker();
        }
    };
    private static final Step VERIFYING_SIGS = new Step("Verifying a transaction's signatures.");
    private static final Step FINALISATION = new Step("Finalising a transaction.") {
        @Override
        public ProgressTracker childProgressTracker() {
            return FinalityFlow.tracker();
        }
    };

    private final ProgressTracker progressTracker = new ProgressTracker(
            ID_OTHER_NODES,
            SENDING_AND_RECEIVING_DATA,
            EXTRACTING_VAULT_STATES,
            OTHER_TX_COMPONENTS,
            TX_BUILDING,
            TX_SIGNING,
            TX_VERIFICATION,
            SIGS_GATHERING,
            FINALISATION
    );

    @Suspendable
    @Override
    public Void call() throws FlowException {
        progressTracker.setCurrentStep(ID_OTHER_NODES);
        // We retrieve the notary identity from the network map.
        Party notary = getServiceHub().getNetworkMapCache().getNotaryIdentities().get(0);

        progressTracker.setCurrentStep(SENDING_AND_RECEIVING_DATA);
        // We create the transaction components.
                IOUState outputState = new IOUState(iouValue, getOurIdentity(), otherParty);
                List<PublicKey> requiredSigners = Arrays.asList(getOurIdentity().getOwningKey(), otherParty.getOwningKey());
                Command command = new Command<>(new IOUContract.Create(), requiredSigners);

        TimeWindow ourAfter = TimeWindow.fromOnly(Instant.MIN);
        progressTracker.setCurrentStep(TX_BUILDING);
        // We create a transaction builder and add the components.
                TransactionBuilder txBuilder = new TransactionBuilder(notary)
                        .addOutputState(outputState, IOUContract.ID)
                        .addCommand(command)
                        .addAttachment(attachmentHash);

        // Verifying the transaction.
                txBuilder.verify(getServiceHub());

        progressTracker.setCurrentStep(TX_SIGNING);
        // Signing the transaction.
                SignedTransaction signedTx = getServiceHub().signInitialTransaction(txBuilder);

        // Creating a session with the other party.
                FlowSession otherPartySession = initiateFlow(otherParty);

        // Obtaining the counterparty's signature.
                SignedTransaction fullySignedTx = subFlow(new CollectSignaturesFlow(
                        signedTx, Arrays.asList(otherPartySession), CollectSignaturesFlow.tracker()));
        progressTracker.setCurrentStep(TX_VERIFICATION);

        // Finalising the transaction.
                subFlow(new FinalityFlow(fullySignedTx, otherPartySession));

                return null;
    }
}

client code:

public class Client {
    private static final Logger logger = LoggerFactory.getLogger(Client.class);

    public static void main(String[] args) throws Exception {
        // Create an RPC connection to the node.
        if (args.length != 3) throw new IllegalArgumentException("Usage: Client <node address> <rpc username> <rpc password>");
        final NetworkHostAndPort nodeAddress = parse(args[0]);
        final String rpcUsername = args[1];
        final String rpcPassword = args[2];
        final CordaRPCClient client = new CordaRPCClient(nodeAddress);
        final CordaRPCOps proxy = client.start(rpcUsername, rpcPassword).getProxy();

        // Interact with the node.
        // For example, here we print the nodes on the network.
        final List<NodeInfo> nodes = proxy.networkMapSnapshot();
        logger.info("{}", nodes);
        InputStream inputstream = new FileInputStream("corda.zip");

        SecureHash hashId= proxy.uploadAttachment(inputstream);
        System.out.println(hashId);

        CordaX500Name x500Name = CordaX500Name.parse("O=ICICI,L=New York,C=US");
        final Party otherParty = proxy.wellKnownPartyFromX500Name(x500Name);

       /* proxy
                .startFlowDynamic(IOUFlow.class, "10", otherParty,hashId)
                .getReturnValue()
                .get();*/

        InputStream stream = proxy.openAttachment(hashId);

        JarInputStream in = new JarInputStream(stream);
        BufferedReader br =new BufferedReader(new InputStreamReader(in));
        System.out.println("Output from attachment :   "+br.readLine());

    }
}

Output:

Task :clients:runTemplateClient
  I 16:36:28 1 RPCClient.logElapsedTime - Startup took 2066 msec
  I 16:36:28 1 Client.main - [NodeInfo(addresses=[localhost:10005], legalIdentitiesAndCerts=[O=PNB, L=London, C=GB], platformVersion=4, serial=1559037129874), NodeInfo(addresses=[localhost:10002], legalIdentitiesAndCerts=[O=Notary, L=London, C=GB], platformVersion=4, serial=1559037126875), NodeInfo(addresses=[localhost:10008], legalIdentitiesAndCerts=[O=ICICI, L=New York, C=US], platformVersion=4, serial=1559037128218)]

DF3C198E05092E52F47AE8EAA0D5D26721F344B3F5E0DF80B5A53CA2B7104C9C
Output from attachment :   null

Another output:when tried to send the attachment from client using RPC

Task :clients:runTemplateClient
  I 16:41:46 1 RPCClient.logElapsedTime - Startup took 2045 msec
  I 16:41:47 1 Client.main - [NodeInfo(addresses=[localhost:10005], legalIdentitiesAndCerts=[O=PNB, L=London, C=GB], platformVersion=4, serial=1559037129874), NodeInfo(addresses=[localhost:10002], legalIdentitiesAndCerts=[O=Notary, L=London, C=GB], platformVersion=4, serial=1559037126875), NodeInfo(addresses=[localhost:10008], legalIdentitiesAndCerts=[O=ICICI, L=New York, C=US], platformVersion=4, serial=1559037128218)]
  B7F5F70FC9086ED594883E6EB8B0B53B666B92CC4412E27FF3D6531446E9E40C
  Exception in thread "main" net.corda.core.CordaRuntimeException: net.corda.core.flows.IllegalFlowLogicException: A FlowLogicRef cannot be constructed for FlowLogic of type com.template.flows.IOUFlow: due to missing constructor for arguments: [class java.lang.String, class net.corda.core.identity.Party, class net.corda.core.crypto.SecureHash$SHA256]


问:
multiple dev environments other than tenants
So lets say I want to stage my firmware to a select group of devices before I push my new firmware into production. I still want to push to stage via OTA. Something akin to the spheres dev and retail os feeds.  Can I set this up for my organization within the same tenant, or do I need to have each environment their own tenant to accomplish this?</p>

答:
Yes you can do that on the same Azure Sphere Tenant - if you use different device groups where each device group has feeds for production and dev accordingly.

For example you can create one device group for the devices in your test lab and another for devices in the retail channel. Devices in the test lab group receive the test application feed, and the devices in the retail group receive the production application feed.

Note: The feeds you create depend on one of the two different system software feeds Retail Azure Sphere OS or Retail Evaluation Azure Sphere OS.


问:
Building an AMP for Email with chilkat .net
I would like to build an Email with Chilkat in .NET which would have three body contents: a HTML one, a plain text one and an AMP for Email one (with Content Type: "text/x-amp-html")

Current version on Chilkat (9.5.0.78) or the one I am using (9.5.0.68) doesn't support AMP for Email so it is not possible to build an email with the methods they provided. As a workaround I am editing the email via GetMime() which already has a Plain Body and Html Body and I am pasting the AMP part there.

Will Chilkat support AMP for Email?

EDIT:

With some more experiments I managed to make three bodies of a message although it's kind of ridicules:

```<code>var email = new Email();
email.Body = PlainContent;
email.AddHtmlAlternativeBody(HtmlContent);
email.RemoveHtmlAlternative();
email.SetTextBody(AmpHtmlContent, "text/x-amp-html");
email.AddHtmlAlternativeBody(HtmlContent);
</code>```

The result is something like this:

```<code>    [...]

    X-Message-Type: test

    --------------090501080304020500060805
    Content-Type: text/plain; charset=utf-8
    Content-Transfer-Encoding: quoted-printable

    some text some text some text some text some text some text some text some =
    text some text some text some text=20
    --------------090501080304020500060805
    Content-Type: text/x-amp-html; charset=utf-8
    Content-Transfer-Encoding: quoted-printable

    <!doctype html>
    <html amp4email>
    <head>
      <meta charset=3D"utf-8">
      <script async src=3D"https://cdn.ampproject.org/v0.js"></script>
      <style amp4email-boilerplate>body{visibility:hidden}</style>
    </head>
    <body>
      Hello, AMP world.
      <amp-img src=3D"https://images-na.ssl-images-amazon.com/images/I/41zetwwV=
    h3L.jpg" alt=3D"Welcome" width=3D"382" height=3D"500">
      </amp-img>
    </body>
    </html>
    --------------090501080304020500060805
    Content-Type: text/html; charset=utf-8
    Content-Transfer-Encoding: quoted-printable

    <html><head><META http-equiv=3D"Content-Type" content=3D"text/html;charset=
    =3Dutf-8"></head><body><h1>test fallback to html</h1> <h1>test fallback t=
    o html</h1> <h1>test fallback to html</h1> </body></html>
    --------------090501080304020500060805--
</code>```

答:
Here is an example that works for me:

https://www.example-code.com/csharp/amp_for_email.asp

It calls AddPlainTextAlternativeBody instead of setting the email.Body property.

Body:
I would like to build an Email with Chilkat in .NET which would have three body contents: a HTML one, a plain text one and an AMP for Email one (with Content Type: "text/x-amp-html")

Current version on Chilkat (9.5.0.78) or the one I am using (9.5.0.68) doesn't support AMP for Email so it is not possible to build an email with the methods they provided. As a workaround I am editing the email via GetMime() which already has a Plain Body and Html Body and I am pasting the AMP part there.

Will Chilkat support AMP for Email?

EDIT:

With some more experiments I managed to make three bodies of a message although it's kind of ridicules:

var email = new Email();
email.Body = PlainContent;
email.AddHtmlAlternativeBody(HtmlContent);
email.RemoveHtmlAlternative();
email.SetTextBody(AmpHtmlContent, "text/x-amp-html");
email.AddHtmlAlternativeBody(HtmlContent);

The result is something like this:

    [...]

    X-Message-Type: test

    --------------090501080304020500060805
    Content-Type: text/plain; charset=utf-8
    Content-Transfer-Encoding: quoted-printable

    some text some text some text some text some text some text some text some =
    text some text some text some text=20
    --------------090501080304020500060805
    Content-Type: text/x-amp-html; charset=utf-8
    Content-Transfer-Encoding: quoted-printable

    <!doctype html>

      <meta charset=3D"utf-8">

      Hello, AMP world.
      <amp-img src=3D"https://images-na.ssl-images-amazon.com/images/I/41zetwwV=
    h3L.jpg" alt=3D"Welcome" width=3D"382" height=3D"500">
      </amp-img>

    --------------090501080304020500060805
    Content-Type: text/html; charset=utf-8
    Content-Transfer-Encoding: quoted-printable

    <META http-equiv=3D"Content-Type" content=3D"text/html;charset=
    =3Dutf-8">
test fallback to html

test fallback t=
    o html

test fallback to html

    --------------090501080304020500060805--


问:
Setting datasource to new MatTable Data Source Angular 7
When I set my data source to an array and try to set the dataSource to a new mat table dataSource to be able to use filtering it comes with I get the error:

Type 'MatTableDataSource' is missing the following properties from type 'TableRecord[]': length, pop, push, concat, and 24 more.

However, if I set the data source to any it works fine. Can someone please help me understand why:

service.ts

```<code>export interface PaginatedListResponse<TableRecord>{
  length: number,
  tableRows: Array<TableRecord>
}

export interface TableRecord{
  x: string,
  y: string,
  z: boolean,

}
</code>```

.ts

```<code>dataSource: TableRecord[] = [];
this.dataSource = new MatTableDataSource(response.tableRows);
//errror: Type 'MatTableDataSource<TableRecord>' is missing the following properties from type 'TableRecord[]': length, pop, push, concat, and 24 more.
</code>```

working example

```<code>    dataSource: any;
    this.dataSource = new MatTableDataSource(response.tableRows);
   //No error
</code>```

答:
The declaration for datasource is wrong. Do it like this:

```<code>dataSource: MatTableDataSource<TableRecord> = new MatTableDataSource([]) ;
</code>```

Then, when you receive data from backend:

```<code>   this.dataSource.data = response.tableRows;
</code>```

Body:
When I set my data source to an array and try to set the dataSource to a new mat table dataSource to be able to use filtering it comes with I get the error:

Type 'MatTableDataSource' is missing the following properties from type 'TableRecord[]': length, pop, push, concat, and 24 more.

However, if I set the data source to any it works fine. Can someone please help me understand why:

service.ts

export interface PaginatedListResponse<TableRecord>{
  length: number,
  tableRows: Array<TableRecord>
}

export interface TableRecord{
  x: string,
  y: string,
  z: boolean,

}

.ts

dataSource: TableRecord[] = [];
this.dataSource = new MatTableDataSource(response.tableRows);
//errror: Type 'MatTableDataSource<TableRecord>' is missing the following properties from type 'TableRecord[]': length, pop, push, concat, and 24 more.

working example

    dataSource: any;
    this.dataSource = new MatTableDataSource(response.tableRows);
   //No error

Body:
The declaration for datasource is wrong. Do it like this:

dataSource: MatTableDataSource<TableRecord> = new MatTableDataSource([]) ;

Then, when you receive data from backend:

   this.dataSource.data = response.tableRows;


问:
Why am I being displayed "TypeError: a float is required"?
My main issue is this error being displayed:

```<code>TypeError: a float is required
</code>```

I haven't tried much as I don't really know what I'm doing, being very new to coding and all, so I would appreciate some patient advice on the matter.

```<code>from math import sqrt

n = raw_input('Type number here: ')

def square_root(n):
  """Returns the square root of a number."""
  square_rooted = sqrt(n)
  print "%d square rooted is %d." % (n, square_rooted)
  return square_rooted

square_root(n)
</code>```

I want to be able to type in a number and it display the square root of it.

答:
Some issues/fixes for your code

You need to cast the string you got from raw_input

To display float, use %f string formatting

So the code will change to

```<code>from math import sqrt
#Convert string obtained from raw_input to float
n = float(raw_input('Type number here: '))
def square_root(n):
  """Returns the square root of a number."""
  square_rooted = sqrt(n)
  print "%f square rooted is %f." % (n, square_rooted)
  return square_rooted

square_root(n)
</code>```

And the output will look like

```<code>Type number here: 4.5
4.500000 square rooted is 2.121320.
</code>```

Body:
My main issue is this error being displayed:

TypeError: a float is required

I haven't tried much as I don't really know what I'm doing, being very new to coding and all, so I would appreciate some patient advice on the matter.

from math import sqrt

n = raw_input('Type number here: ')

def square_root(n):
  """Returns the square root of a number."""
  square_rooted = sqrt(n)
  print "%d square rooted is %d." % (n, square_rooted)
  return square_rooted

square_root(n)

I want to be able to type in a number and it display the square root of it.

Body:
Some issues/fixes for your code

You need to cast the string you got from raw_input

To display float, use %f string formatting

So the code will change to

from math import sqrt
#Convert string obtained from raw_input to float
n = float(raw_input('Type number here: '))
def square_root(n):
  """Returns the square root of a number."""
  square_rooted = sqrt(n)
  print "%f square rooted is %f." % (n, square_rooted)
  return square_rooted

square_root(n)

And the output will look like

Type number here: 4.5
4.500000 square rooted is 2.121320.


问:
How can I pass json variable to array of objects
im currently working on this project and im facing this error when I try to pass a variable (this.arrayObj) into the composals array.

```<code>ngOnInit() {
  this.apiService.getComposals().subscribe((res) => {
    console.log(res.tpoCampos);
    this.arrayObj = res.tpoCampos;
  });
}
</code>```

Im getting the Json content from a Web Service.

```<code>export class AppComponent {

title = 'Form';
arrayObj: any;

composals: Composal[] = [
  this.arrayObj,
];
}
</code>```

This is the content from the webservice

```<code>{
 "m_iPatientID":2,
 "tpoCampos":[
  {
     "m_cColor":"#000000",
     "m_cType":"combo",
     "m_cOptions":[
        "Sim",
        "N\u00e3o"
     ],
     "m_cQuestion":"",
     "m_cAnswer":"2",
     "m_eIdComposant":4443
  },
  {
     "m_cColor":"#000000",
     "m_cType":"combo",
     "m_cOptions":[
        "Sim",
        "N\u00e3o"
     ],
     "m_cQuestion":"",
     "m_cAnswer":"2",
     "m_eIdComposant":4448
  }
 ]
}
</code>```

How can I pass the json to the composal object inside the variable this.arrayObj?

答:
I think this.arrayObj is already an array of objects, so it could be written like this

composals: Composal[] = this.arrayObj;

```<code> export class AppComponent {

    title = 'Form';
    arrayObj: any;

    composals: Composal[] = this.arrayObj;
 }
</code>```

Body:
im currently working on this project and im facing this error when I try to pass a variable (this.arrayObj) into the composals array.

ngOnInit() {
  this.apiService.getComposals().subscribe((res) => {
    console.log(res.tpoCampos);
    this.arrayObj = res.tpoCampos;
  });
}

Im getting the Json content from a Web Service.

export class AppComponent {

title = 'Form';
arrayObj: any;

composals: Composal[] = [
  this.arrayObj,
];
}

This is the content from the webservice

{
 "m_iPatientID":2,
 "tpoCampos":[
  {
     "m_cColor":"#000000",
     "m_cType":"combo",
     "m_cOptions":[
        "Sim",
        "N\u00e3o"
     ],
     "m_cQuestion":"",
     "m_cAnswer":"2",
     "m_eIdComposant":4443
  },
  {
     "m_cColor":"#000000",
     "m_cType":"combo",
     "m_cOptions":[
        "Sim",
        "N\u00e3o"
     ],
     "m_cQuestion":"",
     "m_cAnswer":"2",
     "m_eIdComposant":4448
  }
 ]
}

How can I pass the json to the composal object inside the variable this.arrayObj?

Body:
I think this.arrayObj is already an array of objects, so it could be written like this

composals: Composal[] = this.arrayObj;

 export class AppComponent {

    title = 'Form';
    arrayObj: any;

    composals: Composal[] = this.arrayObj;
 }


问:
how can I disable everything inside a form using javascript/jquery?
I have a form that pop up inside a layer, and I need to make everything inside that form read only regarding what type of input it is. Anyway to do so?</p>

答:
Old question, but nobody mentioned using css:

pointer-events: none;

Whole form becomes immune from click but also hovers.

ContentLicense: CC BY-SA 2.5


问:
Prevent Visual Studio from breaking when throwing exceptions
I test the exceptions interception, so, I don't need that Visual Studio breaks on thinkgs like thrown new NullReferenceException("myVar").

I have the following under Debug=>Exceptions

however, VS breaks on the exceptions. What should I do?

PS.

for the application unhandled exception, I "catch" them using the Application.UnhandledException as in the the following:

```<code>''' <summary>Occurs when the application encounters an unhandled exception.</summary> '
Private Sub Application_UnhandledException(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException
  Dim message As String = String.Format("An application UnhandledException were thrown.{1}The application will now terminate.{1}'{0}'{1}{1}StackTrace:{1}{2}", e.Exception.Message, Environment.NewLine, e.Exception.StackTrace)
  MessageBox.Show(message)
End Sub
</code>```

答:
If you throw an exception that is not handled anywhere in your code, Visual Studio is going to break. It doesn't have any other choice: there was an unhandled exception. Outside of Visual Studio, the application would show an error message and inform the user that an unhandled exception occurred.

The options you see in the Debug -> Exceptions dialog only allow you to configure whether Visual Studio breaks on all exceptions, including those that are later handled in your code. These are often referred to as "first-chance" exceptions.

Beyond that, you should never throw a NullReferenceException yourself; this is a runtime exception that is reserved for the runtime framework. Instead, you should throw an ArgumentNullException.

Body:
I test the exceptions interception, so, I don't need that Visual Studio breaks on thinkgs like thrown new NullReferenceException("myVar").

I have the following under Debug=>Exceptions

however, VS breaks on the exceptions. What should I do?

PS.

for the application unhandled exception, I "catch" them using the Application.UnhandledException as in the the following:

''' Occurs when the application encounters an unhandled exception. '
Private Sub Application_UnhandledException(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException
  Dim message As String = String.Format("An application UnhandledException were thrown.{1}The application will now terminate.{1}'{0}'{1}{1}StackTrace:{1}{2}", e.Exception.Message, Environment.NewLine, e.Exception.StackTrace)
  MessageBox.Show(message)
End Sub


问:
Failed to serialize the response in Web API with Json
I am working with ASP.NET MVC 5 Web Api. I want consult all my users.

I wrote api/users and I receive this:

"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'"

In WebApiConfig, already I added these lines:

```<code>HttpConfiguration config = new HttpConfiguration();
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
</code>```

But it still doesn't work.

My function for return data is this:

```<code>public IEnumerable<User> GetAll()
{
    using (Database db = new Database())
    {
        return db.Users.ToList();
    }
}
</code>```

答:
In my case I solved recreating the database.
I made some changes in a model and launching Update-Database in Package Manager Console I got the following Error:

"The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.Activities_dbo.Projects_ProjectId". The conflict occurred in database "TrackEmAllContext-20190530144302", table "dbo.Projects", column 'Id'."

Body:
I am working with ASP.NET MVC 5 Web Api. I want consult all my users.

I wrote api/users and I receive this:

"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'"

In WebApiConfig, already I added these lines:

HttpConfiguration config = new HttpConfiguration();
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

But it still doesn't work.

My function for return data is this:

public IEnumerable<User> GetAll()
{
    using (Database db = new Database())
    {
        return db.Users.ToList();
    }
}


问:
MySQL: Count rows with similar not duplicated content as one
I am working with Codeigniter and its Query Builder class where I have a table with IDs and names.

Those names look like 1234_1a or 2345_2a where 1a can be 1b or 2a,2b,3a... and so on.

Now I want to count all these "1234" and "2345" but write them as one type.

So far I tried with:

```<code>$this->db->like('names', '1a', 'before');
$this->db->or_like('names', '1b', 'before');
return $this->db->count_all_results('table');
</code>```

But the problem:

What if there is 3456_2a but no 3456_1a, than it doesn't work anymore...

```<code>id  name
2   1212_1a
3   1243_1a
7   3142_1a
24  1243_2a
30  3142_2b
80  2315_2b
136 1243_3b
512 8562_1a
</code>```

This is how I would like it:

```<code>Result:
name    count
1212    1
1243    1
3142    1
2315    1
8562    1
</code>```

答:
If we always want to return a count value of 1, when the count of the number of rows in more than 1 ... then we aren't really returning a count.

And what is the pattern of the names... do they end with a digit and a letter, or is that underscore character important too?

What is to be done with name values such as 12345a or 5678_b2 or 11_22_3b? How are those to be handled?

Seems to me like we want to use a SQL query like this:

```<code>SELECT SUBSTRING_INDEX(t.name,'_',1)  AS `foo`
     , 1                              AS `count`
  FROM (
         SELECT 2 AS `id`, '1212_1a' AS `name`
         UNION ALL SELECT 3, '1243_1a'
         UNION ALL SELECT 7, '3142_1a'
         UNION ALL SELECT 24, '1243_2a'
         UNION ALL SELECT 30, '3142_2b'
         UNION ALL SELECT 80, '2315_2b'
         UNION ALL SELECT 136, '1243_3b'
         UNION ALL SELECT 512, '8562_1a'
       ) t
 GROUP BY `foo`
 ORDER BY `foo`
</code>```

The inline view (derived table) is in the query for testing. Replace that with the table reference:

```<code>SELECT SUBSTRING_INDEX(t.name,'_',1)  AS `foo`
     , 1                              AS `count`
  FROM mytable t
 GROUP BY `foo`
 ORDER BY `foo`
</code>```

The expression for foo may need to be adjusted, to get desirable behavior with values that don't follow the regular pattern. Consider name values with no underscore, with more than one underscore, with endings other than a digit.  We could also include a WHERE  clause to exclude rows that don't follow the pattern,

```<code>WHERE t.name REGEXP '_[0-9][a-z]$'
</code>```

(only name values that end with underscore, digit, lowercase letter).

Without a tested SQL query, I wouldn't know what to implement in CodeIgniter Query Builder.

Body:
I am working with Codeigniter and its Query Builder class where I have a table with IDs and names.

Those names look like 1234_1a or 2345_2a where 1a can be 1b or 2a,2b,3a... and so on.

Now I want to count all these "1234" and "2345" but write them as one type.

So far I tried with:

$this->db->like('names', '1a', 'before');
$this->db->or_like('names', '1b', 'before');
return $this->db->count_all_results('table');

But the problem:

What if there is 3456_2a but no 3456_1a, than it doesn't work anymore...

id  name
2   1212_1a
3   1243_1a
7   3142_1a
24  1243_2a
30  3142_2b
80  2315_2b
136 1243_3b
512 8562_1a

This is how I would like it:

Result:
name    count
1212    1
1243    1
3142    1
2315    1
8562    1

Body:
If we always want to return a count value of 1, when the count of the number of rows in more than 1 ... then we aren't really returning a count.

And what is the pattern of the names... do they end with a digit and a letter, or is that underscore character important too?

What is to be done with name values such as 12345a or 5678_b2 or 11_22_3b? How are those to be handled?

Seems to me like we want to use a SQL query like this:

SELECT SUBSTRING_INDEX(t.name,'_',1)  AS `foo`
     , 1                              AS `count`
  FROM (
         SELECT 2 AS `id`, '1212_1a' AS `name`
         UNION ALL SELECT 3, '1243_1a'
         UNION ALL SELECT 7, '3142_1a'
         UNION ALL SELECT 24, '1243_2a'
         UNION ALL SELECT 30, '3142_2b'
         UNION ALL SELECT 80, '2315_2b'
         UNION ALL SELECT 136, '1243_3b'
         UNION ALL SELECT 512, '8562_1a'
       ) t
 GROUP BY `foo`
 ORDER BY `foo`

The inline view (derived table) is in the query for testing. Replace that with the table reference:

SELECT SUBSTRING_INDEX(t.name,'_',1)  AS `foo`
     , 1                              AS `count`
  FROM mytable t
 GROUP BY `foo`
 ORDER BY `foo`

The expression for foo may need to be adjusted, to get desirable behavior with values that don't follow the regular pattern. Consider name values with no underscore, with more than one underscore, with endings other than a digit.  We could also include a WHERE  clause to exclude rows that don't follow the pattern,

WHERE t.name REGEXP '_[0-9][a-z]$'

(only name values that end with underscore, digit, lowercase letter).

Without a tested SQL query, I wouldn't know what to implement in CodeIgniter Query Builder.


问:
How to print $1, $2 and then all remaining parameters together in AWK
I'm making a script that generates aliases/abbreviations from a base file. The base file structure is something like this:

```<code>sctl   sudo         systemctl
pac    sudo         pacman
</code>```

This works fine with the following code that reads the base file, removes comments and awks the abbreviation line on the abbreviation file:

```<code>    sed "s/\s*#.*$//;/^\s*$/d" $command_file |
    awk -v c=$cmd -v o="$comp" '{ print c" "$1""o"\""$2" "$3"\"" }' >> $file
</code>```

And the end result would be something like this:

```<code>abbr sctl "sudo systemctl"
abbr pac "sudo pacman"
</code>```

But this code doesn't work when the line has many parts after the 3rd parameter:

```<code>svu    playerctl    -p spotify volume +0.05
</code>```

How can i go about printing in that format? $1 $2 ($3..$N)

答:
Here is  GNU sed version:

```<code>sed -r 's/(^[^ ]+)\s+([^ ]+)\s+(.*)/abbr \1 "\2 \3"/g' base_file
abbr sctl "sudo systemctl"
abbr pac "sudo pacman"
abbr svu "playerctl -p spotify volume +0.05"
</code>```

Explanation: Here back-referencing is used, each column is captured into respective groups and later used as \1, \2,\3. Note that -r flag is used in above sed command to enable extended regex. If this flag is not available in the target machine, then following command can be used:

```<code>sed  's/\(^[^ ]\+\)\s\+\([^ ]\+\)\s\+\(.*\)/abbr \1 "\2 \3"/g' base_file
abbr sctl "sudo systemctl"
abbr pac "sudo pacman"
abbr svu "playerctl -p spotify volume +0.05"
</code>```

Only difference in the two commands in that ( ,),+ are escaped in the later.

Body:
I'm making a script that generates aliases/abbreviations from a base file. The base file structure is something like this:

sctl   sudo         systemctl
pac    sudo         pacman

This works fine with the following code that reads the base file, removes comments and awks the abbreviation line on the abbreviation file:

    sed "s/\s*#.*$//;/^\s*$/d" $command_file |
    awk -v c=$cmd -v o="$comp" '{ print c" "$1""o"\""$2" "$3"\"" }' >> $file

And the end result would be something like this:

abbr sctl "sudo systemctl"
abbr pac "sudo pacman"

But this code doesn't work when the line has many parts after the 3rd parameter:

svu    playerctl    -p spotify volume +0.05

How can i go about printing in that format? $1 $2 ($3..$N)

Body:
Here is  GNU sed version:

sed -r 's/(^[^ ]+)\s+([^ ]+)\s+(.*)/abbr \1 "\2 \3"/g' base_file
abbr sctl "sudo systemctl"
abbr pac "sudo pacman"
abbr svu "playerctl -p spotify volume +0.05"

Explanation: Here back-referencing is used, each column is captured into respective groups and later used as \1, \2,\3. Note that -r flag is used in above sed command to enable extended regex. If this flag is not available in the target machine, then following command can be used:

sed  's/\(^[^ ]\+\)\s\+\([^ ]\+\)\s\+\(.*\)/abbr \1 "\2 \3"/g' base_file
abbr sctl "sudo systemctl"
abbr pac "sudo pacman"
abbr svu "playerctl -p spotify volume +0.05"

Only difference in the two commands in that ( ,),+ are escaped in the later.


问:
What is a measure?
I am reading this where I find this:

Measures -- In order to allow Haskell functions to appear in refinement
  types, we need to lift them to the refinement type level.

And there are other documents asserting that measures are needed to use such function in contract. But I tried this:

```<code>{-@ len :: List a -> Nat @-}
len :: List a -> Int
len Nil           = 0
len (x `Cons` xs) = 1 + len xs

{-@ mymap :: (a -> b) -> xs : List a -> { ys : List b | len xs == len ys } @-}
mymap :: (a -> b) -> List a -> List b
mymap _ Nil           = Nil
mymap f (x `Cons` xs) = f x `Cons` mymap f xs
</code>```

and this works but len is not measure. So what is measure exactly and when I need it?

Another example which does not work without measure:

```<code>{-@ measure ln @-}
ln :: [a] -> Int
ln [] = 0
ln (x:y) = 1 + ln y

{-@ conc :: xs : [a] -> ys : [a] -> {zs : [a] | ln zs == ln xs + ln ys} @-}
conc :: [a] -> [a] -> [a]
conc [] ys = ys
conc (x:xs) ys = x : (conc xs ys)
</code>```

Usage of {-@ measure length @-} like I found in many documents leads to error Cannot extract measure from haskell function (ie. from length).

答:
A measure is just a function that can be run by LiquidHaskell at verification time, to be used in refinements and termination checking. You likely already knew this.

The reason your first example "works" (I think it's incomplete as-is, but I can tell what you were going for) is that len is already defined as a measure in the LiquidHaskell prelude (technically it's a "class measure", which means it's polymorphic, and thus can be used both with [] lists and your custom List). Assuming you've added annotations for Nil and Cons as in this answer from your earlier question, the len used in the refinement for mymap is not your len, but the prelude len, which is already a measure.

In your second example, measure is required because ln is a new symbol in the measure namespace, and doesn't exist unless you make it.

Title: What is a measure?

Body:
I am reading this where I find this:

Measures -- In order to allow Haskell functions to appear in refinement
  types, we need to lift them to the refinement type level.

And there are other documents asserting that measures are needed to use such function in contract. But I tried this:

{-@ len :: List a -> Nat @-}
len :: List a -> Int
len Nil           = 0
len (x `Cons` xs) = 1 + len xs

{-@ mymap :: (a -> b) -> xs : List a -> { ys : List b | len xs == len ys } @-}
mymap :: (a -> b) -> List a -> List b
mymap _ Nil           = Nil
mymap f (x `Cons` xs) = f x `Cons` mymap f xs

and this works but len is not measure. So what is measure exactly and when I need it?

Another example which does not work without measure:

{-@ measure ln @-}
ln :: [a] -> Int
ln [] = 0
ln (x:y) = 1 + ln y

{-@ conc :: xs : [a] -> ys : [a] -> {zs : [a] | ln zs == ln xs + ln ys} @-}
conc :: [a] -> [a] -> [a]
conc [] ys = ys
conc (x:xs) ys = x : (conc xs ys)

Usage of {-@ measure length @-} like I found in many documents leads to error Cannot extract measure from haskell function (ie. from length).


问:
Redirect nohup to stdout on a script
I have a .sh script that via nohup runs a lot of Python scripts.

I use nohup to run them in the background and avoid neccesary enter pressing when the "nohup: ignoring input and appending output to 'nohup.out'" message appears.

```<code>nohup python script2.py 2> /dev/null &
nohup python script2.py 2> /dev/null &
[...]
</code>```

When I run this .sh, I get the two Python scripts running in the background, ok.

This Python scripts generate a log file, which I deriver to std.stdout:

```<code>stream_config = logging.StreamHandler(sys.stdout)  <-- here
stream_config.setFormatter(formatter)
importer_logger.addHandler(stream_config)
</code>```

Due to my implementation, I want to launch those nohup but sending the stdout to to PID 1

I can do this easily without using nohup as follows:

```<code>python tester.py > /proc/1/fd/1
</code>```

But how can I combine that "don't press enter to continue" and "deriver the file to stdout"?

I tried these with no luck:

```<code>nohup python tester.py > /proc/1/fd/1 2> /dev/null &
nohup python tester.py 2> /proc/1/fd/1 &
</code>```

Thanks in advance.

答:
You can fix your command by using the shell to indirectly start your program so that you can redirect its output rather than the output of nohup:

```<code>nohup bash -c "exec python tester.py > /proc/1/fd/1" 2> /dev/null &
</code>```

This isn't the best option but it at least corrects the issue that made your attempts fail.

Title: Redirect nohup to stdout on a script

Body:
I have a .sh script that via nohup runs a lot of Python scripts.

I use nohup to run them in the background and avoid neccesary enter pressing when the "nohup: ignoring input and appending output to 'nohup.out'" message appears.

nohup python script2.py 2> /dev/null &
nohup python script2.py 2> /dev/null &
[...]

When I run this .sh, I get the two Python scripts running in the background, ok.

This Python scripts generate a log file, which I deriver to std.stdout:

stream_config = logging.StreamHandler(sys.stdout)  <-- here
stream_config.setFormatter(formatter)
importer_logger.addHandler(stream_config)

Due to my implementation, I want to launch those nohup but sending the stdout to to PID 1

I can do this easily without using nohup as follows:

python tester.py > /proc/1/fd/1

But how can I combine that "don't press enter to continue" and "deriver the file to stdout"?

I tried these with no luck:

nohup python tester.py > /proc/1/fd/1 2> /dev/null &
nohup python tester.py 2> /proc/1/fd/1 &

Thanks in advance.

Body:
You can fix your command by using the shell to indirectly start your program so that you can redirect its output rather than the output of nohup:

nohup bash -c "exec python tester.py > /proc/1/fd/1" 2> /dev/null &

This isn't the best option but it at least corrects the issue that made your attempts fail.


问:
How can I delete multipe lines in a text by Python?
I have a similar question to delete multiple line

I want to delete the line and the next 4 lines. This is my code:

```<code>bind = open('/etc/bind/named.conf.local','r')
a = dict['name']
for line in bind:
        if a in line:
            print('line  exist')
            ''' and delete this line and 4 line after it'''
        else:
            print('line does not exist')
</code>```

I want to save modify text in /etc/bind/named.conf.local in place, without fileinput. I do not want skip 4 line I want to delete them from the file. I do not want to read it and write it again and skip 4 lines.

What should I do?

答:
If you don't want to use fileinput, you can also read all the lines of your file, write them (except for the lines you skip using next(f)) to a tempfile.NamedTemporaryFile and replace the original file with the temporary file.

```<code>from pathlib import Path
from tempfile import NamedTemporaryFile

named_conf = Path('/etc/bind/named.conf.local')

with open(named_conf) as infile:
    with NamedTemporaryFile("w", delete=False) as outfile:
        for line in infile:
            if line_should_be_deleted(line):
                # skip this line and the 4 lines after it
                for _ in range(4):
                    next(infile)
            else:
                outfile.write(line)

Path(outfile.name).replace(named_conf)
</code>```

But you should just use fileinput, like the answer to the question you linked to says, since it does the tempfile stuff for you.

Body:
I have a similar question to delete multiple line

I want to delete the line and the next 4 lines. This is my code:

bind = open('/etc/bind/named.conf.local','r')
a = dict['name']
for line in bind:
        if a in line:
            print('line  exist')
            ''' and delete this line and 4 line after it'''
        else:
            print('line does not exist')

I want to save modify text in /etc/bind/named.conf.local in place, without fileinput. I do not want skip 4 line I want to delete them from the file. I do not want to read it and write it again and skip 4 lines.

What should I do?

Body:
If you don't want to use fileinput, you can also read all the lines of your file, write them (except for the lines you skip using next(f)) to a tempfile.NamedTemporaryFile and replace the original file with the temporary file.

from pathlib import Path
from tempfile import NamedTemporaryFile

named_conf = Path('/etc/bind/named.conf.local')

with open(named_conf) as infile:
    with NamedTemporaryFile("w", delete=False) as outfile:
        for line in infile:
            if line_should_be_deleted(line):
                # skip this line and the 4 lines after it
                for _ in range(4):
                    next(infile)
            else:
                outfile.write(line)

Path(outfile.name).replace(named_conf)

But you should just use fileinput, like the answer to the question you linked to says, since it does the tempfile stuff for you.


问:
(Mathematica) RegionPlot3D + DiscretizeRegion + ImplicitRegion does not show any tick marks for axes
Running the following snippet

```<code>region = ImplicitRegion[x - y + z == 0, {{x, -1, 1}, {y, -1, 1}, {z, -1, 1}}];
RegionPlot3D[DiscretizeRegion[region]]
</code>```

Outputs

3D image of a plane

I want to have tick marks and to retain the functionality of RegionPlot3D (to be able to change the color, etc.). Any ideas?

答:
Nothing preventing you from using all of the available options to RegionPlot3D documented here.

```<code>RegionPlot3D[DiscretizeRegion[region], PlotTheme -> "Detailed", Mesh -> None,
  PlotStyle -> Directive[Red, Opacity[0.75]]]
</code>```

Body:
Running the following snippet

region = ImplicitRegion[x - y + z == 0, {{x, -1, 1}, {y, -1, 1}, {z, -1, 1}}];
RegionPlot3D[DiscretizeRegion[region]]

Outputs

3D image of a plane

I want to have tick marks and to retain the functionality of RegionPlot3D (to be able to change the color, etc.). Any ideas?

Body:
Nothing preventing you from using all of the available options to RegionPlot3D documented here.

RegionPlot3D[DiscretizeRegion[region], PlotTheme -> "Detailed", Mesh -> None,
  PlotStyle -> Directive[Red, Opacity[0.75]]]


问:
How to horizontally center a Text in flutter?
I’m trying to horizontally center a text. Please check the below code.

```<code>import 'package:flutter/material.dart';

class LoginPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
        color: Colors.black,
        child: Row(
          children: <Widget>[
            Column(
              children: <Widget>[_buildTitle()],
            ),
          ],
        ));
  }

  Widget _buildTitle() {
    return
    Center(child: Container(
      margin: EdgeInsets.only(top: 100),
      child: Column(

        children: <Widget>[
          Text(
            "something.xyz",
            style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 25,),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    ),);

  }
}
</code>```

This did not center horizontally, instead gave the following output. The margins etc is fine.

How can I fix this?

答:
more simple way:</p>

```<code>child: Center(
               child: Row(
                 mainAxisAlignment: MainAxisAlignment.center,
                 children: <Widget>[
                   Text('Sunday', style: TextStyle(fontSize: 20),),
                 ],
               ),
             ), //Center
</code>```

Body:
I’m trying to horizontally center a text. Please check the below code.

import 'package:flutter/material.dart';

class LoginPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
        color: Colors.black,
        child: Row(
          children: <Widget>[
            Column(
              children: <Widget>[_buildTitle()],
            ),
          ],
        ));
  }

  Widget _buildTitle() {
    return
    Center(child: Container(
      margin: EdgeInsets.only(top: 100),
      child: Column(

        children: <Widget>[
          Text(
            "something.xyz",
            style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 25,),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    ),);

  }
}

This did not center horizontally, instead gave the following output. The margins etc is fine.

How can I fix this?

Body:
more simple way:

child: Center(
               child: Row(
                 mainAxisAlignment: MainAxisAlignment.center,
                 children: <Widget>[
                   Text('Sunday', style: TextStyle(fontSize: 20),),
                 ],
               ),
             ), //Center


问:
How to define oneHotEncoder to the titanic dataset
I'm trying to work on the titanic dataset. The data has categorical values, so I used labelEncoder to change the data to numbers, instead of text. Before:

```<code>     PassengerId  Survived  Pclass     Sex    Age  SibSp  Parch      Fare Embarked
0              1         0       3    male  22.00      1      0    7.2500        S
1              2         1       1  female  38.00      1      0   71.2833        C
2              3         1       3  female  26.00      0      0    7.9250        S
</code>```

After:

```<code>     PassengerId  Survived  Pclass  Sex    Age  SibSp  Parch      Fare  Embarked
0              1         0       3    1  22.00      1      0    7.2500         2
1              2         1       1    0  38.00      1      0   71.2833         0
2              3         1       3    0  26.00      0      0    7.9250         2
</code>```

This is the code:

```<code>from sklearn.preprocessing import LabelEncoder

labelencoder_X = LabelEncoder()
data['Embarked'] = labelencoder_X.fit_transform(data['Embarked'])
data['Sex'] = labelencoder_X.fit_transform(data['Sex'])
</code>```

Now, because the gender of the passenger is with the same importancy, I want to use oneHotEncoder. As I understand, the data should look the following:

```<code>     PassengerId  Survived  Pclass  Male Female    Age  SibSp  Parch      Fare  Embarked
0              1         0       3    1     0     22.00  1      0    7.2500         2
1              2         1       1    0     1     38.00  1      0   71.2833         0
2              3         1       3    0     1     26.00  0      0    7.9250         2
</code>```

How can I write a code to do this? I have tried to work with similar method for oneHotEncoder:

```<code>from sklearn.preprocessing import LabelEncoder, OneHotEncoder

labelencoder_X = LabelEncoder()
data['Embarked'] = labelencoder_X.fit_transform(data['Embarked'])
data['Sex'] = labelencoder_X.fit_transform(data['Sex'])

onehotencoder = OneHotEncoder()
data['Embarked'] = onehotencoder.fit_transform(data['Embarked'].values.reshape(-1,1))
</code>```

But it just return the same result. How can I fix it? I'm new with Scikit and ML, I hope I'm doing things correctly.

答:
This is how you can do it.

import pandas as pd
from sklearn.preprocessing import OneHotEncoder

# Sample data
   Sex
0    1
1    0
2    0
3    1

# OneHotEncoder
result = OneHotEncoder().fit_transform(df['Sex'].reshape(-1, 1)).toarray()

# Appending columns
df[['Female', 'Male']] = pd.DataFrame(result, index = df.index)

# Resulting dataframe
df
   Sex  Female  Male
0    1     0.0   1.0
1    0     1.0   0.0
2    0     1.0   0.0
3    1     0.0   1.0
```

Body:
I'm trying to work on the titanic dataset. The data has categorical values, so I used labelEncoder to change the data to numbers, instead of text. Before:

     PassengerId  Survived  Pclass     Sex    Age  SibSp  Parch      Fare Embarked
0              1         0       3    male  22.00      1      0    7.2500        S
1              2         1       1  female  38.00      1      0   71.2833        C
2              3         1       3  female  26.00      0      0    7.9250        S

After:

     PassengerId  Survived  Pclass  Sex    Age  SibSp  Parch      Fare  Embarked
0              1         0       3    1  22.00      1      0    7.2500         2
1              2         1       1    0  38.00      1      0   71.2833         0
2              3         1       3    0  26.00      0      0    7.9250         2

This is the code:

from sklearn.preprocessing import LabelEncoder

labelencoder_X = LabelEncoder()
data['Embarked'] = labelencoder_X.fit_transform(data['Embarked'])
data['Sex'] = labelencoder_X.fit_transform(data['Sex'])

Now, because the gender of the passenger is with the same importancy, I want to use oneHotEncoder. As I understand, the data should look the following:

     PassengerId  Survived  Pclass  Male Female    Age  SibSp  Parch      Fare  Embarked
0              1         0       3    1     0     22.00  1      0    7.2500         2
1              2         1       1    0     1     38.00  1      0   71.2833         0
2              3         1       3    0     1     26.00  0      0    7.9250         2

How can I write a code to do this? I have tried to work with similar method for oneHotEncoder:

from sklearn.preprocessing import LabelEncoder, OneHotEncoder

labelencoder_X = LabelEncoder()
data['Embarked'] = labelencoder_X.fit_transform(data['Embarked'])
data['Sex'] = labelencoder_X.fit_transform(data['Sex'])

onehotencoder = OneHotEncoder()
data['Embarked'] = onehotencoder.fit_transform(data['Embarked'].values.reshape(-1,1))

But it just return the same result. How can I fix it? I'm new with Scikit and ML, I hope I'm doing things correctly.


问:
How can I count how many horizontal brush strokes are required to draw an array of buildings?
By given an array of integers, each element represents a building. For example: int buildings[] = {1, 4, 3, 2, 3, 1}.

If I drew the buildings horizontally with a brush, how many brush strike I would use?

I should write a function that returns the number of these brush strokes.  For example 5.

I can do it easily on run time O(n^2), by using 2 loops.

The external loop running on the levels of each building (according to the highest building).

The inner loop is running on the array from 0 to n, and compares the difference of the height (0 or 1) between two near elements.

How can I do this in the O(n) time and O(n) space?

答:
A little code golf :) (Based on samgak's excellent explanation.)

const f = A => A.reduce((a,b,i,A) => a + Math.max(0, b - A[i-1]));

console.log(f([1, 4, 3, 2, 3, 1]))
console.log(f([4, 1, 2, 1, 2, 2]))```


问:
Rename column name with hyphen (-) in laravel migration
I'm trying to run a laravel migration that renames a particular column in my database but I repeatedly get an error message.

```<code>class ModifyColumnName extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->renameColumn("content-description", "content_description");
        });
    }

}
</code>```

I keep on getting this error message.

```<code>Illuminate\Database\QueryException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax;
check the manual that corresponds to your MariaDB server version for the right syntax to use near '-description content_description VARCHAR(255) DEFAULT NULL' at line 1 (SQL: ALTER TABLE posts CHANGE content-description content_description VARCHAR(255) DEFAULT NULL)
</code>```

答:
Put your column name with hyphen in backticks</p>

```<code>Schema::table('posts', function (Blueprint $table) {
    $table->renameColumn("`content-description`", "content_description");
});
</code>```

Body:
I'm trying to run a laravel migration that renames a particular column in my database but I repeatedly get an error message.

class ModifyColumnName extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->renameColumn("content-description", "content_description");
        });
    }

}

I keep on getting this error message.

Illuminate\Database\QueryException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax;
check the manual that corresponds to your MariaDB server version for the right syntax to use near '-description content_description VARCHAR(255) DEFAULT NULL' at line 1 (SQL: ALTER TABLE posts CHANGE content-description content_description VARCHAR(255) DEFAULT NULL)

Body:
Put your column name with hyphen in backticks

Schema::table('posts', function (Blueprint $table) {
    $table->renameColumn("`content-description`", "content_description");
});


问:
Annoying wsgen tool pop up when publish server
When i start publish my application from WebSphere Application Server then it will always pop up a dialog box "Generation Result for Wsgen" which i need to click "okay" to close it, after that it will keep on pop up and i need to click okay until the server are successfully publish.

Do anyone know how to fix this ? I'm looking solution from online but there is no solution about this.

attached is the image
https://imgur.com/a/9FeQWeG

答:
If you are using the IBM Liberty Developer Tools for Eclipse, then use at least version 18.0.0.4.  You can get the latest release from here:

https://developer.ibm.com/wasdev/downloads/#asset/tools-IBM_Liberty_Developer_Tools_for_Eclipse_2019-03_4.11


问:
How to "close" database when the query happens?
```<code>$database->count = "SELECT * FROM table WHERE item_id = 1"

if($database->count == 1)
{
   $database->update = "UPDATE users SET money = money - 1000";
   $database->delete = "DELETE table WHERE item_id = 1";
}
</code>```

Let's say I have this code (I've just created it) in index.php page. Can at the same time "SELECT * FROM table WHERE item_id = 1" query happen so two people would get count 1 and -1000 money? If yes, how can I avoid that?

Thank you.

答:
Not all of the databases have transaction support so If you are using mysql as you are working with PHP so you will need table locking technique.
Your table will be locked unless all work will be done than you unlock it, you can specify row locking as well.

http://dev.mysql.com/doc/refman/5.0/en/lock-tables.html

Best :) Waqar Alamgir

Body:
$database->count = "SELECT * FROM table WHERE item_id = 1"

if($database->count == 1)
{
   $database->update = "UPDATE users SET money = money - 1000";
   $database->delete = "DELETE table WHERE item_id = 1";
}

Let's say I have this code (I've just created it) in index.php page. Can at the same time "SELECT * FROM table WHERE item_id = 1" query happen so two people would get count 1 and -1000 money? If yes, how can I avoid that?

Thank you.