问:
Use python to replace values with a variable?
With the following json:

```<code>{
    "operationalLayers": [
        {
            "id": "GRSM_STORM_TOTAL_PRECIP_8083",
            "layerType": "ArcGISFeatureLayer",
            "url": "https://services1.arcgis.com/fBc8EJBxQRMcHlei/arcgis/rest/services/GRSM_STORM_TOTAL_PRECIP/FeatureServer/0",
            "visibility": true,
            "opacity": 0.8,
            "title": "GRSM_STORM_TOTAL_PRECIP",
            "itemId": "20370bddfa7948bb98cf5f9e143b44b2",
            "layerDefinition": {
                "drawingInfo": {
                    "renderer": {
                        "visualVariables": [
                            {
                                "type": "colorInfo",
                                "field": "INCHES",
                                "valueExpression": null,
                                "stops": [
                                    {
                                        "value": 0.753,
                                        "color": [
                                            255,
                                            252,
                                            212,
                                            255
                                        ],
                                        "label": "< 0.7"
                                    },
                                    {
                                        "value": 2.91475,
                                        "color": [
                                            238,
                                            190,
                                            139,
                                            255
                                        ],
                                        "label": null
                                    },
                                    {
                                        "value": 5.0765,
                                        "color": [
                                            221,
                                            128,
                                            66,
                                            255
                                        ],
                                        "label": "5.07"
                                    },
                                    {
                                        "value": 7.238250000000001,
                                        "color": [
                                            162,
                                            64,
                                            33,
                                            255
                                        ],
                                        "label": null
                                    },
                                    {
                                        "value": 9.4,
                                        "color": [
                                            102,
                                            0,
                                            0,
                                            255
                                        ],
                                        "label": "> 9.3"
                                    }
                                ]
                            },
                            {
                                "type": "sizeInfo",
                                "target": "outline",
                                "expression": "view.scale",
                                "valueExpression": "$view.scale",
                                "stops": [
                                    {
                                        "size": 1.5,
                                        "value": 13459
                                    },
                                    {
                                        "size": 0.75,
                                        "value": 42058
                                    },
                                    {
                                        "size": 0.375,
                                        "value": 168232
                                    },
                                    {
                                        "size": 0,
                                        "value": 336463
                                    }
                                ]
                            }
                        ],
                        "authoringInfo": {
                            "visualVariables": [
                                {
                                    "type": "colorInfo",
                                    "minSliderValue": 0.753,
                                    "maxSliderValue": 9.4,
                                    "theme": "high-to-low"
                                }
                            ]
                        },
                        "type": "classBreaks",
                        "field": "INCHES",
                        "minValue": -9007199254740991,
                        "classBreakInfos": [
                            {
                                "symbol": {
                                    "color": [
                                        170,
                                        170,
                                        170,
                                        255
                                    ],
                                    "outline": {
                                        "color": null,
                                        "width": 0.75,
                                        "type": "esriSLS",
                                        "style": "esriSLSNull"
                                    },
                                    "type": "esriSFS",
                                    "style": "esriSFSSolid"
                                },
                                "classMaxValue": 9007199254740991
                            }
                        ]
                    }
                }
            },
            "popupInfo": {
                "title": "GRSM_STORM_TOTAL_PRECIP: {Id}",
                "fieldInfos": [
                    {
                        "fieldName": "OBJECTID",
                        "label": "OBJECTID",
                        "isEditable": false,
                        "tooltip": "",
                        "visible": false,
                        "stringFieldOption": "textbox"
                    },
                    {
                        "fieldName": "Id",
                        "label": "Id",
                        "isEditable": true,
                        "tooltip": "",
                        "visible": true,
                        "stringFieldOption": "textbox",
                        "format": {
                            "places": 0,
                            "digitSeparator": true
                        }
                    },
                    {
                        "fieldName": "gridcode",
                        "label": "gridcode",
                        "isEditable": true,
                        "tooltip": "",
                        "visible": true,
                        "stringFieldOption": "textbox",
                        "format": {
                            "places": 0,
                            "digitSeparator": true
                        }
                    },
                    {
                        "fieldName": "INCHES",
                        "label": "INCHES",
                        "isEditable": true,
                        "tooltip": "",
                        "visible": true,
                        "stringFieldOption": "textbox",
                        "format": {
                            "places": 2,
                            "digitSeparator": true
                        }
                    },
                    {
                        "fieldName": "TIMESTAMP",
                        "label": "TIMESTAMP",
                        "isEditable": true,
                        "tooltip": "",
                        "visible": true,
                        "stringFieldOption": "textbox",
                        "format": {
                            "dateFormat": "shortDateShortTime"
                        }
                    },
                    {
                        "fieldName": "Shape__Area",
                        "label": "Shape__Area",
                        "isEditable": false,
                        "tooltip": "",
                        "visible": false,
                        "stringFieldOption": "textbox",
                        "format": {
                            "places": 2,
                            "digitSeparator": true
                        }
                    },
                    {
                        "fieldName": "Shape__Length",
                        "label": "Shape__Length",
                        "isEditable": false,
                        "tooltip": "",
                        "visible": false,
                        "stringFieldOption": "textbox",
                        "format": {
                            "places": 2,
                            "digitSeparator": true
                        }
                    }
                ],
                "description": null,
                "showAttachments": true,
                "mediaInfos": []
            }
        }
    ],
    "baseMap": {
        "baseMapLayers": [
            {
                "id": "World_Hillshade_3689",
                "layerType": "ArcGISTiledMapServiceLayer",
                "url": "https://services.arcgisonline.com/arcgis/rest/services/Elevation/World_Hillshade/MapServer",
                "visibility": true,
                "opacity": 1,
                "title": "World Hillshade"
            },
            {
                "id": "VectorTile_6451",
                "type": "VectorTileLayer",
                "layerType": "VectorTileLayer",
                "title": "World Topographic Map",
                "styleUrl": "https://www.arcgis.com/sharing/rest/content/items/7dc6cea0b1764a1f9af2e679f642f0f5/resources/styles/root.json",
                "itemId": "7dc6cea0b1764a1f9af2e679f642f0f5",
                "visibility": true,
                "opacity": 1
            }
        ],
        "title": "Topographic"
    },
    "spatialReference": {
        "wkid": 102100,
        "latestWkid": 3857
    },
    "authoringApp": "WebMapViewer",
    "authoringAppVersion": "7.4",
    "version": "2.16"
}
</code>```

I need to replace some values in

```<code>                "visualVariables": [
                    {
                        "type": "colorInfo",
                        "field": "INCHES",
                        "valueExpression": null,
                        "stops": [
                            {
                                "value": 0.753,
                                "color": [
                                    255,
                                    252,
                                    212,
                                    255
                                ],
                                "label": "< 0.7"
                            },
                            {
                                "value": 2.91475,
                                "color": [
                                    238,
                                    190,
                                    139,
                                    255
                                ],
                                "label": null
                            },
                            {
                                "value": 5.0765,
                                "color": [
                                    221,
                                    128,
                                    66,
                                    255
                                ],
                                "label": "5.07"
                            },
                            {
                                "value": 7.238250000000001,
                                "color": [
                                    162,
                                    64,
                                    33,
                                    255
                                ],
                                "label": null
                            },
                            {
                                "value": 9.4,
                                "color": [
                                    102,
                                    0,
                                    0,
                                    255
                                ],
                                "label": "> 9.3"
                            }
                        ]
                    }
</code>```

so that for example the output is

```<code>                "visualVariables": [
                    {
                        "type": "colorInfo",
                        "field": "INCHES",
                        "valueExpression": null,
                        "stops": [
                            {
                                "value": 0.5,
                                "color": [
                                    255,
                                    252,
                                    212,
                                    255
                                ],
                                "label": "< 0.5"
                            },
                            {
                                "value": 5,
                                "color": [
                                    238,
                                    190,
                                    139,
                                    255
                                ],
                                "label": 5
                            },
                            {
                                "value": 15,
                                "color": [
                                    221,
                                    128,
                                    66,
                                    255
                                ],
                                "label": "15"
                            },
                            {
                                "value": 10,
                                "color": [
                                    162,
                                    64,
                                    33,
                                    255
                                ],
                                "label": 10
                            },
                            {
                                "value": 20,
                                "color": [
                                    102,
                                    0,
                                    0,
                                    255
                                ],
                                "label": "> 20"
                            }
                        ]
                    }
</code>```

So far all I've managed to do is read the value one by one for example

```<code>import json
from pprint import pprint
with open('C:/Temp/NEXRAD_PYTHON/new 1.json') as f:
    data = json.load(f)
data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["visualVariables"][0]["stops"][2]["value"]
5.0765
data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["visualVariables"][0]["stops"][2]["label"]
'5.07'
</code>```

but what I'm looking to do is have a separate (list?dictionary), for example

```<code>['.5', '5', '10', '15', '20']
</code>```

which is updated outside of this workflow (every 10 minutes the number will be changed as the result of another program) that will replace "value" and "label".

I've looked at
Change json.dumps dictionary values in python,
Replace multiple keys and values of JSON file in Python,
Python - change JSON values and pretty print, and
https://www.geeksforgeeks.org/python-ways-to-change-keys-in-dictionary/

Which either don't match my situation or I'm missing something obvious.

答:
...and just like that. Added a random # generator to test actual values.</p>

```<code>import json
from pprint import pprint
import numpy as np
import random
min = random.uniform(.01,1)
max = random.uniform(5,15)
a = np.array([min,max])
x = np.percentile(a, 25)
y = np.percentile(a, 50)
z = np.percentile(a, 75)
print (x,y,z)
with open('C:/Temp/NEXRAD_PYTHON/new 1.json','r') as f:
    data = json.load(f)

with open('C:/Temp/NEXRAD_PYTHON/new 1.json','w') as f:

    data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["visualVariables"][0]["stops"][0]["value"] = min
    data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["visualVariables"][0]["stops"][1]["value"] = x
    data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["visualVariables"][0]["stops"][2]["value"] = y
    data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["visualVariables"][0]["stops"][3]["value"] = z
    data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["visualVariables"][0]["stops"][4]["value"] = max
    data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["visualVariables"][0]["stops"][0]["label"] = "<"+str(round(min,2))
    data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["visualVariables"][0]["stops"][1]["label"] = str(round(x,2))
    data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["visualVariables"][0]["stops"][2]["label"] = str(round(y,2))
    data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["visualVariables"][0]["stops"][3]["label"] = str(round(z,2))
    data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["visualVariables"][0]["stops"][4]["label"] = ">"+str(round(max,2))
    data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["authoringInfo"]["visualVariables"][0]["minSliderValue"] = round(min,3)
    data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["authoringInfo"]["visualVariables"][0]["maxSliderValue"] = round(max,3)
    f.write(json.dumps(data))

f.close()
</code>```

Body:
With the following json:

{
    "operationalLayers": [
        {
            "id": "GRSM_STORM_TOTAL_PRECIP_8083",
            "layerType": "ArcGISFeatureLayer",
            "url": "https://services1.arcgis.com/fBc8EJBxQRMcHlei/arcgis/rest/services/GRSM_STORM_TOTAL_PRECIP/FeatureServer/0",
            "visibility": true,
            "opacity": 0.8,
            "title": "GRSM_STORM_TOTAL_PRECIP",
            "itemId": "20370bddfa7948bb98cf5f9e143b44b2",
            "layerDefinition": {
                "drawingInfo": {
                    "renderer": {
                        "visualVariables": [
                            {
                                "type": "colorInfo",
                                "field": "INCHES",
                                "valueExpression": null,
                                "stops": [
                                    {
                                        "value": 0.753,
                                        "color": [
                                            255,
                                            252,
                                            212,
                                            255
                                        ],
                                        "label": "< 0.7"
                                    },
                                    {
                                        "value": 2.91475,
                                        "color": [
                                            238,
                                            190,
                                            139,
                                            255
                                        ],
                                        "label": null
                                    },
                                    {
                                        "value": 5.0765,
                                        "color": [
                                            221,
                                            128,
                                            66,
                                            255
                                        ],
                                        "label": "5.07"
                                    },
                                    {
                                        "value": 7.238250000000001,
                                        "color": [
                                            162,
                                            64,
                                            33,
                                            255
                                        ],
                                        "label": null
                                    },
                                    {
                                        "value": 9.4,
                                        "color": [
                                            102,
                                            0,
                                            0,
                                            255
                                        ],
                                        "label": "> 9.3"
                                    }
                                ]
                            },
                            {
                                "type": "sizeInfo",
                                "target": "outline",
                                "expression": "view.scale",
                                "valueExpression": "$view.scale",
                                "stops": [
                                    {
                                        "size": 1.5,
                                        "value": 13459
                                    },
                                    {
                                        "size": 0.75,
                                        "value": 42058
                                    },
                                    {
                                        "size": 0.375,
                                        "value": 168232
                                    },
                                    {
                                        "size": 0,
                                        "value": 336463
                                    }
                                ]
                            }
                        ],
                        "authoringInfo": {
                            "visualVariables": [
                                {
                                    "type": "colorInfo",
                                    "minSliderValue": 0.753,
                                    "maxSliderValue": 9.4,
                                    "theme": "high-to-low"
                                }
                            ]
                        },
                        "type": "classBreaks",
                        "field": "INCHES",
                        "minValue": -9007199254740991,
                        "classBreakInfos": [
                            {
                                "symbol": {
                                    "color": [
                                        170,
                                        170,
                                        170,
                                        255
                                    ],
                                    "outline": {
                                        "color": null,
                                        "width": 0.75,
                                        "type": "esriSLS",
                                        "style": "esriSLSNull"
                                    },
                                    "type": "esriSFS",
                                    "style": "esriSFSSolid"
                                },
                                "classMaxValue": 9007199254740991
                            }
                        ]
                    }
                }
            },
            "popupInfo": {
                "title": "GRSM_STORM_TOTAL_PRECIP: {Id}",
                "fieldInfos": [
                    {
                        "fieldName": "OBJECTID",
                        "label": "OBJECTID",
                        "isEditable": false,
                        "tooltip": "",
                        "visible": false,
                        "stringFieldOption": "textbox"
                    },
                    {
                        "fieldName": "Id",
                        "label": "Id",
                        "isEditable": true,
                        "tooltip": "",
                        "visible": true,
                        "stringFieldOption": "textbox",
                        "format": {
                            "places": 0,
                            "digitSeparator": true
                        }
                    },
                    {
                        "fieldName": "gridcode",
                        "label": "gridcode",
                        "isEditable": true,
                        "tooltip": "",
                        "visible": true,
                        "stringFieldOption": "textbox",
                        "format": {
                            "places": 0,
                            "digitSeparator": true
                        }
                    },
                    {
                        "fieldName": "INCHES",
                        "label": "INCHES",
                        "isEditable": true,
                        "tooltip": "",
                        "visible": true,
                        "stringFieldOption": "textbox",
                        "format": {
                            "places": 2,
                            "digitSeparator": true
                        }
                    },
                    {
                        "fieldName": "TIMESTAMP",
                        "label": "TIMESTAMP",
                        "isEditable": true,
                        "tooltip": "",
                        "visible": true,
                        "stringFieldOption": "textbox",
                        "format": {
                            "dateFormat": "shortDateShortTime"
                        }
                    },
                    {
                        "fieldName": "Shape__Area",
                        "label": "Shape__Area",
                        "isEditable": false,
                        "tooltip": "",
                        "visible": false,
                        "stringFieldOption": "textbox",
                        "format": {
                            "places": 2,
                            "digitSeparator": true
                        }
                    },
                    {
                        "fieldName": "Shape__Length",
                        "label": "Shape__Length",
                        "isEditable": false,
                        "tooltip": "",
                        "visible": false,
                        "stringFieldOption": "textbox",
                        "format": {
                            "places": 2,
                            "digitSeparator": true
                        }
                    }
                ],
                "description": null,
                "showAttachments": true,
                "mediaInfos": []
            }
        }
    ],
    "baseMap": {
        "baseMapLayers": [
            {
                "id": "World_Hillshade_3689",
                "layerType": "ArcGISTiledMapServiceLayer",
                "url": "https://services.arcgisonline.com/arcgis/rest/services/Elevation/World_Hillshade/MapServer",
                "visibility": true,
                "opacity": 1,
                "title": "World Hillshade"
            },
            {
                "id": "VectorTile_6451",
                "type": "VectorTileLayer",
                "layerType": "VectorTileLayer",
                "title": "World Topographic Map",
                "styleUrl": "https://www.arcgis.com/sharing/rest/content/items/7dc6cea0b1764a1f9af2e679f642f0f5/resources/styles/root.json",
                "itemId": "7dc6cea0b1764a1f9af2e679f642f0f5",
                "visibility": true,
                "opacity": 1
            }
        ],
        "title": "Topographic"
    },
    "spatialReference": {
        "wkid": 102100,
        "latestWkid": 3857
    },
    "authoringApp": "WebMapViewer",
    "authoringAppVersion": "7.4",
    "version": "2.16"
}

I need to replace some values in

                "visualVariables": [
                    {
                        "type": "colorInfo",
                        "field": "INCHES",
                        "valueExpression": null,
                        "stops": [
                            {
                                "value": 0.753,
                                "color": [
                                    255,
                                    252,
                                    212,
                                    255
                                ],
                                "label": "< 0.7"
                            },
                            {
                                "value": 2.91475,
                                "color": [
                                    238,
                                    190,
                                    139,
                                    255
                                ],
                                "label": null
                            },
                            {
                                "value": 5.0765,
                                "color": [
                                    221,
                                    128,
                                    66,
                                    255
                                ],
                                "label": "5.07"
                            },
                            {
                                "value": 7.238250000000001,
                                "color": [
                                    162,
                                    64,
                                    33,
                                    255
                                ],
                                "label": null
                            },
                            {
                                "value": 9.4,
                                "color": [
                                    102,
                                    0,
                                    0,
                                    255
                                ],
                                "label": "> 9.3"
                            }
                        ]
                    }

so that for example the output is

                "visualVariables": [
                    {
                        "type": "colorInfo",
                        "field": "INCHES",
                        "valueExpression": null,
                        "stops": [
                            {
                                "value": 0.5,
                                "color": [
                                    255,
                                    252,
                                    212,
                                    255
                                ],
                                "label": "< 0.5"
                            },
                            {
                                "value": 5,
                                "color": [
                                    238,
                                    190,
                                    139,
                                    255
                                ],
                                "label": 5
                            },
                            {
                                "value": 15,
                                "color": [
                                    221,
                                    128,
                                    66,
                                    255
                                ],
                                "label": "15"
                            },
                            {
                                "value": 10,
                                "color": [
                                    162,
                                    64,
                                    33,
                                    255
                                ],
                                "label": 10
                            },
                            {
                                "value": 20,
                                "color": [
                                    102,
                                    0,
                                    0,
                                    255
                                ],
                                "label": "> 20"
                            }
                        ]
                    }

So far all I've managed to do is read the value one by one for example

import json
from pprint import pprint
with open('C:/Temp/NEXRAD_PYTHON/new 1.json') as f:
    data = json.load(f)
data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["visualVariables"][0]["stops"][2]["value"]
5.0765
data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["visualVariables"][0]["stops"][2]["label"]
'5.07'

but what I'm looking to do is have a separate (list?dictionary), for example

['.5', '5', '10', '15', '20']

which is updated outside of this workflow (every 10 minutes the number will be changed as the result of another program) that will replace "value" and "label".

I've looked at
Change json.dumps dictionary values in python,
Replace multiple keys and values of JSON file in Python,
Python - change JSON values and pretty print, and
https://www.geeksforgeeks.org/python-ways-to-change-keys-in-dictionary/

Which either don't match my situation or I'm missing something obvious.

Body:
...and just like that. Added a random # generator to test actual values.

import json
from pprint import pprint
import numpy as np
import random
min = random.uniform(.01,1)
max = random.uniform(5,15)
a = np.array([min,max])
x = np.percentile(a, 25)
y = np.percentile(a, 50)
z = np.percentile(a, 75)
print (x,y,z)
with open('C:/Temp/NEXRAD_PYTHON/new 1.json','r') as f:
    data = json.load(f)

with open('C:/Temp/NEXRAD_PYTHON/new 1.json','w') as f:

    data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["visualVariables"][0]["stops"][0]["value"] = min
    data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["visualVariables"][0]["stops"][1]["value"] = x
    data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["visualVariables"][0]["stops"][2]["value"] = y
    data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["visualVariables"][0]["stops"][3]["value"] = z
    data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["visualVariables"][0]["stops"][4]["value"] = max
    data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["visualVariables"][0]["stops"][0]["label"] = "<"+str(round(min,2))
    data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["visualVariables"][0]["stops"][1]["label"] = str(round(x,2))
    data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["visualVariables"][0]["stops"][2]["label"] = str(round(y,2))
    data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["visualVariables"][0]["stops"][3]["label"] = str(round(z,2))
    data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["visualVariables"][0]["stops"][4]["label"] = ">"+str(round(max,2))
    data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["authoringInfo"]["visualVariables"][0]["minSliderValue"] = round(min,3)
    data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["authoringInfo"]["visualVariables"][0]["maxSliderValue"] = round(max,3)
    f.write(json.dumps(data))

f.close()


来源: stackexchange

问:
Getting this error when I try to execute this program (python file management)
Python file management error could not execute this program</p>

答:
In this case it's better to use a context manager (with . as .:). And to write the path of your file try to put single back slash instead of two.</p>

```<code>with open('Users\you\Documents\a_text_file.txt', 'r') as jabber:
    for line in jabber:
        print(line)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In this case it's better to use a context manager (with . as .:). And to write the path of your file try to put single back slash instead of two.

with open('Users\you\Documents\a_text_file.txt', 'r') as jabber:
    for line in jabber:
        print(line)


问:
Normalisation--2NF vs 3NF
We say 2NF is "the whole key" and 3NF "nothing but the key".

Referencing this answer by Smashery:

What are database normal forms and can you give examples?

The example used for 3NF is exactly the same as 2NF--it's a field which is dependent on only one key attribute. How is the example for 3NF different from the one for 2NF?

答:
You have achieved the 3rd NF when there are no relations between the key and other columns that don't depend on it.

Not sure my professor would have said that like this but this is what it is.

If you're "in the field". Forget about the definitions. Look for "best practices". One is DRY : Don't Repeat Yourself.

If you follow that principle, you already master everything you need for NF.

Here is an example.
Your table has the following schema:

```<code>PERSONS : id, name, age, car make, car model
</code>```

Age and name are related to the person entry (=> id) but the model depends to the car and not the person.

Then, you would split it in two tables:

```<code>PERSONS : id, name, age, car_models_id (references CAR_MODELS.id)
CAR_MODELS : id, name, car_makes_id (references CAR_MAKES.id)
CAR_MAKES : id, name
</code>```

You can have replication in 2FN but not in 3FN anymore.

Normalization is all about non-replication, consistency, and from another point of view foreign keys and JOINs.

The more normalized the better for data but not for performance nor understanding if it gets really too complicated.

Title: Normalisation--2NF vs 3NF

Body:
You have achieved the 3rd NF when there are no relations between the key and other columns that don't depend on it.

Not sure my professor would have said that like this but this is what it is.

If you're "in the field". Forget about the definitions. Look for "best practices". One is DRY : Don't Repeat Yourself.

If you follow that principle, you already master everything you need for NF.

Here is an example.
Your table has the following schema:

PERSONS : id, name, age, car make, car model

Age and name are related to the person entry (=> id) but the model depends to the car and not the person.

Then, you would split it in two tables:

PERSONS : id, name, age, car_models_id (references CAR_MODELS.id)
CAR_MODELS : id, name, car_makes_id (references CAR_MAKES.id)
CAR_MAKES : id, name

You can have replication in 2FN but not in 3FN anymore.

Normalization is all about non-replication, consistency, and from another point of view foreign keys and JOINs.

The more normalized the better for data but not for performance nor understanding if it gets really too complicated.

ContentLicense: CC BY-SA 3.0


问:
How is Forth LEAVE ... LOOP implemented, since number of LEAVEs is not known beforehand?
The word LOOP is described as "Resolve the destination of all unresolved occurrences of LEAVE". (emphasis mine)

Unlike IF ... ELSE ... THEN, where the number of forward references is always one, LOOP has no constraints on the quantity of LEAVE. How to implement it then?

One approach I thought of is to always keep the number of LEAVEs on top of the stack. Each LEAVE increments this counter and puts itself under it. LOOP reads the counter from the top and resolves that many references. But it seems like a cheap trick.

How do real Forth systems implement this kind of loop? I don't need teh codez (been implementing Forth as a learning experience), just the concepts.

答:
As another approach, you can thread a singly-linked list through the unresolved address "holes". I used this when I implemented counted loops in my FORTH:</p>

```<code>( We can now define DO, ?DO, LOOP, +LOOP and LEAVE. It would be much easier
  if LEAVE didn't exist, but oh well. Because storing LEAVE's data on the stack
  would interfere with other control flow inside the loop, let's store it in a variable. )

VARIABLE LEAVE-PTR

( Let's consider the base case: only one LEAVE in the loop. This can be trivially
  handled by storing the address we need to patch in the variable.

  This would also work quite well with nested loops. All we need to do is store
  the old value of the variable on the stack when opening a loop.

  Finally, we can extend this to an arbitrary number of LEAVEs by threading
  a singly-linked list through the branch target address holes. )

\ ...

: LEAVE, ( -- )
  HERE
  LEAVE-PTR @ ,
  LEAVE-PTR !
;

: LEAVE POSTPONE BRANCH LEAVE, ; IMMEDIATE

: DO ( -- old-leave-ptr loop-beginning )
  LEAVE-PTR @
  0 LEAVE-PTR !
  POSTPONE 2>R
  HERE
; IMMEDIATE

\ SOME-LOOP is the common code between LOOP and +LOOP
: SOME-LOOP ( old-leave-ptr loop-beginning -- )
  POSTPONE 0BRANCH ,
  LEAVE-PTR @
  BEGIN
    ?DUP
  WHILE
    DUP @ >R
    HERE SWAP !
    R>
  REPEAT
  POSTPONE UNLOOP
  LEAVE-PTR !
;
</code>```

Body:
As another approach, you can thread a singly-linked list through the unresolved address "holes". I used this when I implemented counted loops in my FORTH:

( We can now define DO, ?DO, LOOP, +LOOP and LEAVE. It would be much easier
  if LEAVE didn't exist, but oh well. Because storing LEAVE's data on the stack
  would interfere with other control flow inside the loop, let's store it in a variable. )

VARIABLE LEAVE-PTR

( Let's consider the base case: only one LEAVE in the loop. This can be trivially
  handled by storing the address we need to patch in the variable.

  This would also work quite well with nested loops. All we need to do is store
  the old value of the variable on the stack when opening a loop.

  Finally, we can extend this to an arbitrary number of LEAVEs by threading
  a singly-linked list through the branch target address holes. )

\ ...

: LEAVE, ( -- )
  HERE
  LEAVE-PTR @ ,
  LEAVE-PTR !
;

: LEAVE POSTPONE BRANCH LEAVE, ; IMMEDIATE

: DO ( -- old-leave-ptr loop-beginning )
  LEAVE-PTR @
  0 LEAVE-PTR !
  POSTPONE 2>R
  HERE
; IMMEDIATE

\ SOME-LOOP is the common code between LOOP and +LOOP
: SOME-LOOP ( old-leave-ptr loop-beginning -- )
  POSTPONE 0BRANCH ,
  LEAVE-PTR @
  BEGIN
    ?DUP
  WHILE
    DUP @ >R
    HERE SWAP !
    R>
  REPEAT
  POSTPONE UNLOOP
  LEAVE-PTR !
;


问:
WebSphere 9 upgrade with RAD 8.5
Our developers currently use the IBM RAD 8.5 to develop web applications (No enterprise Java beans (No J2EE), use Spring framework). The server team is planning to upgrade WebSphere from version 8 to version 9.  Last I checked in the servers tab, RAD 8.5 supports WAS version 8, 8.5, and 8.5 Liberty profile. See screenshot.

Is it possible to continue to develop in RAD 8.5, and deploy to WebSphere 9 in the server environment?  What kind of snag would I expect to run into?  e.g. Assemble the WAR file in RAD 8.5, and deploy the WAR file in WAS 9.

Would there be any problem I should anticipate in the deployment descriptor?  e.g. files like web.xml and application.xml?

Moving forward, is it better to use other IDE to do software development if we are not planning to upgrade RAD 8.5 to a newer version?  Would MyEclipse(variant of Eclipse with better server support) or Eclipse IDE for Java EE Developers  (oxygen) suffice? Do I also need the liberty profile?
https://developer.ibm.com/wasdev/downloads/liberty-profile-using-eclipse/

What kind of issues should I be expecting?  Or continue using RAD 8.5 would be a better option?

Here are some of the stackoverflow links I had checked already.  There are pretty high level.

what-are-the-differences-when-deploying-on-tomcat-vs-websphere

can-a-war-file-be-deployed-on-any-server

Thanks.

答:
Adding to the information provided by Bruce, IBM had introduced OpenLiberty where one can deploy the war file built with RAD. Deploying to other application server (e.g. tomcatEE
) is possible, but it would require some work.  OpenLiberty should be closest to the IBM Websphere in terms of setup and architecture.

Here are some links that provide more information.

OpenLiberty

IBM announces Open Liberty, an open source runtime for Java microservices

Difference between OpenLiberty and Websphere Liberty

Title: WebSphere 9 upgrade with RAD 8.5


问:
Python configparser read config from S3 without downloading
is there a way to read a .ini configuration file from s3 without downloading it?

What I have tried:

config.ini:

```<code>[DEFAULT]
test = test1
test1 = test2

[ME]
me = you
you = he
</code>```

code:

```<code>import boto3
import io
import configparser

s3_boto = boto3.client('s3')
configuration_file_bucket = "mybucket"
configuration_file_key = "config.ini"
obj = s3_boto.get_object(Bucket=configuration_file_bucket, Key=configuration_file_key)

config = configparser.ConfigParser()
config.read(io.BytesIO(obj['Body'].read()))
</code>```

It returns [].

I have tried to make sure that

```<code>obj['Body'].read()
</code>```

is returning well a binary with content of config.ini. This is working. It breaks somewhere further.

答:
The read method of ConfigParser takes a file name, and yet you're passing it a file object.

You can instead use the read_string method so that you can pass to it the content returned by the read method of the StreamingBody object:

```<code>config.read_string(obj['Body'].read().decode())
</code>```

Body:
is there a way to read a .ini configuration file from s3 without downloading it?

What I have tried:

config.ini:

[DEFAULT]
test = test1
test1 = test2

[ME]
me = you
you = he

code:

import boto3
import io
import configparser

s3_boto = boto3.client('s3')
configuration_file_bucket = "mybucket"
configuration_file_key = "config.ini"
obj = s3_boto.get_object(Bucket=configuration_file_bucket, Key=configuration_file_key)

config = configparser.ConfigParser()
config.read(io.BytesIO(obj['Body'].read()))

It returns [].

I have tried to make sure that

obj['Body'].read()

is returning well a binary with content of config.ini. This is working. It breaks somewhere further.

Body:
The read method of ConfigParser takes a file name, and yet you're passing it a file object.

You can instead use the read_string method so that you can pass to it the content returned by the read method of the StreamingBody object:

config.read_string(obj['Body'].read().decode())


问:
Javascript 'undefined' error, when trying to get values from database
I'm trying to get values from an array on my database, however everytime I run the code it says that the value is 'undefined'. But it return the right values when I use document.write, why is that? Here is the code that returns 'undefined':

```<code> $.get("/api/IgnicoesAPI", function (data) {

        console.log(data);

        $.each(data, function (i, item) {
            //janela de informação de cada marcador

            //console.log(item);
            var infowindow = '<div id="content" style="hight:700px; width:500px">' +
                '<div id="siteNotice">' +
                '</div>' +
                '<div id="bodyContent">' +
                '<p><b>Avaliação da Ocorrência:</b></p>' +
                // iterar todas as ocorrencias para tirar delas as imagens
                item.listaOcorrencias.forEach(function (ocorrencia, o) {
                    ocorrencias.azimute
                });

                +'<p> Latitude: </p>'

            var marker = new L.marker([item.latitude, item.longitude], { icon: ignicao })
                .bindPopup(infowindow)
                .on('click', onClick)
                .addTo(map);

            $('#json map').append(marker);

        });
    });
</code>```

The model that I refer to (Ignicoes) has a property that is a list:

```<code>  public class Ignicoes
{

    public Ignicoes()
    {
        ListaOcorrencias = new HashSet<Ocorrencias>();

    }

    public virtual ICollection<Ocorrencias> ListaOcorrencias { get; set; }

}
</code>```

listaOcorrencias is what I'm trying to access on my Index.

When I use document.write the map doesn't appear, but the right value is returned

答:
 var something;
 item.listaOcorrencias.forEach(function (ocorrencia, o) {
                something = ocorrencias.azimute;
                });
var infowindow = '
' +
                '
' +
                '
' +
                '
' +
                '
Avaliação da Ocorrência:
' +
                // iterar todas as ocorrencias para tirar delas as imagens
               something

                +'
 Latitude:
'```

Body:
I'm trying to get values from an array on my database, however everytime I run the code it says that the value is 'undefined'. But it return the right values when I use document.write, why is that? Here is the code that returns 'undefined':

 $.get("/api/IgnicoesAPI", function (data) {

        console.log(data);

        $.each(data, function (i, item) {
            //janela de informação de cada marcador

            //console.log(item);
            var infowindow = '
' +
                '
' +
                '
' +
                '
' +
                '
Avaliação da Ocorrência:
' +
                // iterar todas as ocorrencias para tirar delas as imagens
                item.listaOcorrencias.forEach(function (ocorrencia, o) {
                    ocorrencias.azimute
                });

                +'
 Latitude:
'

            var marker = new L.marker([item.latitude, item.longitude], { icon: ignicao })
                .bindPopup(infowindow)
                .on('click', onClick)
                .addTo(map);

            $('#json map').append(marker);

        });
    });

The model that I refer to (Ignicoes) has a property that is a list:

  public class Ignicoes
{

    public Ignicoes()
    {
        ListaOcorrencias = new HashSet<Ocorrencias>();

    }

    public virtual ICollection<Ocorrencias> ListaOcorrencias { get; set; }

}

listaOcorrencias is what I'm trying to access on my Index.

When I use document.write the map doesn't appear, but the right value is returned

Body:
 var something;
 item.listaOcorrencias.forEach(function (ocorrencia, o) {
                something = ocorrencias.azimute;
                });
var infowindow = '<div id="content" style="hight:700px; width:500px">' +
                '<div id="siteNotice">' +
                '</div>' +
                '<div id="bodyContent">' +
                '<p><b>Avaliação da Ocorrência:</b></p>' +
                // iterar todas as ocorrencias para tirar delas as imagens
               something

                +'<p> Latitude: </p>'


问:
Properly handling initialization in generic methods
Suppose I have an object of some type A and want to transform it into type B. Let's say multiple implementations of this interface will exist as we will have many children of A, and B. So, I create an interface like:

```<code>interface IAToB {
    B Transform<A, B>(A a);
}
</code>```

The problem with this interface that I see is I need to initialize an object of type B in Transform, which means if I change the initialization logic of B, I need to appropriately change all implementations of IAToB. So, consider the following:

```<code>interface IAToB {
    void Transform<A, B>(A a, out B b);
}
</code>```

The implementer of IAToB is now required to pass in an initialized B.

So, is the latter interface more compliant with SOLID principles in comparison to the former? Or am I just moving the coupling around without actually reducing it, so to speak? Further, would it make sense to place the generics in the definition of the interface too, to have interface IAToB { ... }?

答:
"The implementer of IAToB is now required to pass in an initialized B. So, is the latter interface more compliant with SOLID principles in comparison to the former"

The first statement here isn't true. An out parameter is guaranteed to be initialized by the called method, and it is not required that it's pre-initialized to anything (doing so, in fact, is redundant and should be avoided). It's only a reference that the caller can access after the method completes. Therefore the answer is, "No, it's not any more SOLID than the first example."

From the documentation:

Variables passed as out arguments do not have to be initialized before being passed in a method call. However, the called method is required to assign a value before the method returns.

Typically an out parameter is used so that a method can return more than one result. TryParse is a typical example, in that it returns a bool indicating success, and sets an out parameter to the parsed value (or the default for the type if it's not successful).

Furthermore, no matter how you implement this conversion method, if you change the initiliaztion logic in a way that impacts how a B can be created from an A, then you're going to have to update the conversion code somewhere.

Body:
Suppose I have an object of some type A and want to transform it into type B. Let's say multiple implementations of this interface will exist as we will have many children of A, and B. So, I create an interface like:

interface IAToB {
    B Transform(A a);
}

The problem with this interface that I see is I need to initialize an object of type B in Transform, which means if I change the initialization logic of B, I need to appropriately change all implementations of IAToB. So, consider the following:

interface IAToB {
    void Transform(A a, out B b);
}

The implementer of IAToB is now required to pass in an initialized B.

So, is the latter interface more compliant with SOLID principles in comparison to the former? Or am I just moving the coupling around without actually reducing it, so to speak? Further, would it make sense to place the generics in the definition of the interface too, to have interface IAToB { ... }?


问:
How change range slider to show money?
I found this slider on codepen .

How do I get it to show me a minimum of € 500 and a maximum of € 6000 but to preserve the red background?

I have tried everything eg.

```<code><input id = "range" type = "range" class = "range-slider" min = "500" max = "6000" step = "100">
</code>```

But the range slider stretches to 6000% and I'm not good at JS.

const rangeSlider = document.querySelector('.range-slider');
const rangeValueBar = document.querySelector('#range-value-bar');
const rangeValue = document.querySelector('#range-value');

let isDown = false;

function dragHandler() {
  isDown = !isDown;
  if (!isDown) {
    rangeValue.style.setProperty('opacity', '1');
  } else {
    rangeValue.style.setProperty('opacity', '1');
  }
}

function dragOn(e) {
  if (!isDown) return;
  rangeValueHandler();
}

function rangeValueHandler() {
  rangeValueBar.style.setProperty('width', `${rangeSlider.value}%`);
  rangeValue.innerHTML = `${rangeSlider.value}€`;
}

rangeValueHandler();
rangeSlider.addEventListener('mousedown', dragHandler);
rangeSlider.addEventListener('mousemove', dragOn);
rangeSlider.addEventListener('mouseup', dragHandler);
rangeSlider.addEventListener('click', rangeValueHandler);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  padding: 100px;
}
.range-slider-container {
  position: relative;
}

input[type=range] {
  -webkit-appearance: none;
  margin: 10px 0;
  width: 100%;
  position: absolute;
  top: 0;
  margin: 0;
}
#range-value-bar {
  width: 100%;
  content: "0";
  background-color: #FC6E50;
  position: absolute;
  z-index: 10000;
  height: 25px;
  top: 0;
  margin: 0;
  border-radius: 5px;
}
/**/
#range-value {
  width: 25px;
  content:"0";
  background: rgba(233, 239, 244, 0.1);;
  position: absolute;
  z-index: 10000;
  height: 25px;
  top: -65px;
  margin: 0;
  border-radius: 5px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 20px;
  padding: 12px;
  color: #41576B;
  box-shadow: 0 2px 10px 0 rgba(0,0,0,0.08);
  text-align: center;
  opacity: 0;
}

input[type=range]:focus {
  outline: none;
}
input[type=range]::-webkit-slider-runnable-track {
  width: 100%;
  height: 25px;
  cursor: pointer;
  animate: 0.2s;
  box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
  background: #E9EFF4;
  border-radius: 5px;
  border: 0px solid #000101;
}
input[type=range]::-webkit-slider-thumb {
  box-shadow: 0 2px 10px 0 rgba(0,0,0,0.08);
  border: 14px solid #FFF;
  height: 53px;
  width: 53px;
  border-radius: 30px;
  background: #FC6E50;
  cursor: pointer;
  -webkit-appearance: none;
  margin-top: -13.5px;
  position: relative;
  z-index: 1000000000;
}
input[type=range]::-moz-range-track {
  width: 100%;
  height: 12.8px;
  cursor: pointer;
  animate: 0.2s;
  box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
  background: #000;
  border-radius: 25px;
  border: 0px solid #000101;
}
input[type=range]::-moz-range-thumb {
  box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
  border: 0px solid #000000;
  height: 20px;
  width: 39px;
  border-radius: 7px;
  background: #000000;
  cursor: pointer;
}
input[type=range]::-ms-track {
  width: 100%;
  height: 12.8px;
  cursor: pointer;
  animate: 0.2s;
  background: transparent;
  border-color: transparent;
  border-width: 39px 0;
  color: transparent;
}
input[type=range]::-ms-fill-lower {
  background: #000;
  border: 0px solid #000101;
  border-radius: 50px;
  box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
}
input[type=range]::-ms-fill-upper {
  background: #000;
  border: 0px solid #000101;
  border-radius: 50px;
  box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
}
input[type=range]::-ms-thumb {
  box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
  border: 0px solid #000000;
  height: 20px;
  width: 39px;
  border-radius: 7px;
  background: #000;
  cursor: pointer;
}</code>```

  <input id="range" type="range" class="range-slider">

  0

```

答:
Simply adapt the javascript that display the value:</p>

```<code>function rangeValueHandler() {
  rangeValueBar.style.setProperty('width', `${rangeSlider.value}%`);
  const moneyValue = Math.round(500 + 5500 * rangeSlider.value * 0.01);
  rangeValue.innerHTML = `\$ ${moneyValue}`;
}
</code>```

Title: How change range slider to show money?

Body:
I found this slider on codepen .

How do I get it to show me a minimum of € 500 and a maximum of € 6000 but to preserve the red background?

I have tried everything eg.

<input id = "range" type = "range" class = "range-slider" min = "500" max = "6000" step = "100">

But the range slider stretches to 6000% and I'm not good at JS.

const rangeSlider = document.querySelector('.range-slider');
const rangeValueBar = document.querySelector('#range-value-bar');
const rangeValue = document.querySelector('#range-value');

let isDown = false;

function dragHandler() {
  isDown = !isDown;
  if (!isDown) {
    rangeValue.style.setProperty('opacity', '1');
  } else {
    rangeValue.style.setProperty('opacity', '1');
  }
}

function dragOn(e) {
  if (!isDown) return;
  rangeValueHandler();
}

function rangeValueHandler() {
  rangeValueBar.style.setProperty('width', `${rangeSlider.value}%`);
  rangeValue.innerHTML = `${rangeSlider.value}€`;
}

rangeValueHandler();
rangeSlider.addEventListener('mousedown', dragHandler);
rangeSlider.addEventListener('mousemove', dragOn);
rangeSlider.addEventListener('mouseup', dragHandler);
rangeSlider.addEventListener('click', rangeValueHandler);

body {
  padding: 100px;
}
.range-slider-container {
  position: relative;
}

input[type=range] {
  -webkit-appearance: none;
  margin: 10px 0;
  width: 100%;
  position: absolute;
  top: 0;
  margin: 0;
}
#range-value-bar {
  width: 100%;
  content: "0";
  background-color: #FC6E50;
  position: absolute;
  z-index: 10000;
  height: 25px;
  top: 0;
  margin: 0;
  border-radius: 5px;
}
/**/
#range-value {
  width: 25px;
  content:"0";
  background: rgba(233, 239, 244, 0.1);;
  position: absolute;
  z-index: 10000;
  height: 25px;
  top: -65px;
  margin: 0;
  border-radius: 5px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 20px;
  padding: 12px;
  color: #41576B;
  box-shadow: 0 2px 10px 0 rgba(0,0,0,0.08);
  text-align: center;
  opacity: 0;
}

input[type=range]:focus {
  outline: none;
}
input[type=range]::-webkit-slider-runnable-track {
  width: 100%;
  height: 25px;
  cursor: pointer;
  animate: 0.2s;
  box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
  background: #E9EFF4;
  border-radius: 5px;
  border: 0px solid #000101;
}
input[type=range]::-webkit-slider-thumb {
  box-shadow: 0 2px 10px 0 rgba(0,0,0,0.08);
  border: 14px solid #FFF;
  height: 53px;
  width: 53px;
  border-radius: 30px;
  background: #FC6E50;
  cursor: pointer;
  -webkit-appearance: none;
  margin-top: -13.5px;
  position: relative;
  z-index: 1000000000;
}
input[type=range]::-moz-range-track {
  width: 100%;
  height: 12.8px;
  cursor: pointer;
  animate: 0.2s;
  box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
  background: #000;
  border-radius: 25px;
  border: 0px solid #000101;
}
input[type=range]::-moz-range-thumb {
  box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
  border: 0px solid #000000;
  height: 20px;
  width: 39px;
  border-radius: 7px;
  background: #000000;
  cursor: pointer;
}
input[type=range]::-ms-track {
  width: 100%;
  height: 12.8px;
  cursor: pointer;
  animate: 0.2s;
  background: transparent;
  border-color: transparent;
  border-width: 39px 0;
  color: transparent;
}
input[type=range]::-ms-fill-lower {
  background: #000;
  border: 0px solid #000101;
  border-radius: 50px;
  box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
}
input[type=range]::-ms-fill-upper {
  background: #000;
  border: 0px solid #000101;
  border-radius: 50px;
  box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
}
input[type=range]::-ms-thumb {
  box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
  border: 0px solid #000000;
  height: 20px;
  width: 39px;
  border-radius: 7px;
  background: #000;
  cursor: pointer;
}

  <input id="range" type="range" class="range-slider">

  0

Body:
Simply adapt the javascript that display the value:

function rangeValueHandler() {
  rangeValueBar.style.setProperty('width', `${rangeSlider.value}%`);
  const moneyValue = Math.round(500 + 5500 * rangeSlider.value * 0.01);
  rangeValue.innerHTML = `\$ ${moneyValue}`;
}


问:
Generate XML in specific format from struct
I Need to generate this xml from a structure:

```<code><doc>
    <item name='documentCommand' value='i' />
    <item name='documentType' value='1' />
    <item name='offset' value='0' />
    <item name='bytesRead' value='63636' />
    <item name='bDoneUpload' value='false' />
    <item name='documentVar' value='' />
    <item name='vendorFileName' value='/example.pdf' />
</doc>
</code>```

I have the following structure:

```<code>type XMLDoc struct {
    XMLName         xml.Name `xml:"doc"`
    DocumentCommand string   `xml:"documentCommand"`
    DocumentType    string   `xml:"documentType"`
    Offset          string   `xml:"offset"`
    BytesRead       string   `xml:"bytesRead"`
    DoneUpload      string   `xml:"bDoneUpload"`
    DocumentVar     string   `xml:"documentVar"`
    FileName        string   `xml:"vendorFileName"`
}
</code>```

Using xml.Marshal gives me this and it is not acceptable to the endpoint:

```<code><doc>
    <documentCommand>i</documentCommand>
    <documentType>27</documentType>
    <offset>27181</offset>
    <bytesRead>0</bytesRead>
    <bDoneUpload>true</bDoneUpload>
    <documentVar></documentVar>
    <vendorFileName>testdoc.pdf</vendorFileName>
</doc>
</code>```

Then endpoint tells me the bDoneUpload string boolean is not valid.

What is the proper way to create the desired XML?

答:
If you want that specific order for your XML item's then you could use a slice like so:

```<code>type XMLDoc struct {
    XMLName xml.Name `xml:"doc"`
    Items   []Item   `xml:"item"`
}

type Item struct {
    Name  string `xml:"name,attr"`
    Value string `xml:"value,attr"`
}
</code>```

and to use:

```<code>v := XMLDoc{
    Items: []Item{
        Item{"documentCommand", "i"},
        Item{"documentType", "1"},
        /* ... */
    },
}
</code>```

Playground working example.

You could also create a custom XML Marshaler to render the XML exactly how you would like e.g.

```<code>type XMLDoc struct {
    Comment    string
    Type       string
    Offset     int
    Read       int
    DoneUpload bool
    Var        string
    VenderPath string
}

func (x XMLDoc) MarshalXML(e *xml.Encoder, start xml.StartElement) (err error) { /* ... */ }
</code>```

Pro: one can use native go-types like int, bool etc. for fields

Con: Marshaler can be tedious to write: https://play.golang.org/p/KZ-HKgNHmbE

Body:
I Need to generate this xml from a structure:

<doc>
    <item name='documentCommand' value='i' />
    <item name='documentType' value='1' />
    <item name='offset' value='0' />
    <item name='bytesRead' value='63636' />
    <item name='bDoneUpload' value='false' />
    <item name='documentVar' value='' />
    <item name='vendorFileName' value='/example.pdf' />
</doc>

I have the following structure:

type XMLDoc struct {
    XMLName         xml.Name `xml:"doc"`
    DocumentCommand string   `xml:"documentCommand"`
    DocumentType    string   `xml:"documentType"`
    Offset          string   `xml:"offset"`
    BytesRead       string   `xml:"bytesRead"`
    DoneUpload      string   `xml:"bDoneUpload"`
    DocumentVar     string   `xml:"documentVar"`
    FileName        string   `xml:"vendorFileName"`
}

Using xml.Marshal gives me this and it is not acceptable to the endpoint:

<doc>
    <documentCommand>i</documentCommand>
    <documentType>27</documentType>
    <offset>27181</offset>
    <bytesRead>0</bytesRead>
    <bDoneUpload>true</bDoneUpload>
    <documentVar></documentVar>
    <vendorFileName>testdoc.pdf</vendorFileName>
</doc>

Then endpoint tells me the bDoneUpload string boolean is not valid.

What is the proper way to create the desired XML?

Body:
If you want that specific order for your XML item's then you could use a slice like so:

type XMLDoc struct {
    XMLName xml.Name `xml:"doc"`
    Items   []Item   `xml:"item"`
}

type Item struct {
    Name  string `xml:"name,attr"`
    Value string `xml:"value,attr"`
}

and to use:

v := XMLDoc{
    Items: []Item{
        Item{"documentCommand", "i"},
        Item{"documentType", "1"},
        /* ... */
    },
}

Playground working example.

You could also create a custom XML Marshaler to render the XML exactly how you would like e.g.

type XMLDoc struct {
    Comment    string
    Type       string
    Offset     int
    Read       int
    DoneUpload bool
    Var        string
    VenderPath string
}

func (x XMLDoc) MarshalXML(e *xml.Encoder, start xml.StartElement) (err error) { /* ... */ }

Pro: one can use native go-types like int, bool etc. for fields

Con: Marshaler can be tedious to write: https://play.golang.org/p/KZ-HKgNHmbE


问:
How to get value of element using text in BeautifulSoup
I've got a problem using BeautifulSoup. I need to get the value of the element using only some text inside but I've got no idea how to do that. There's some HTML code:

<option class="" value="9_72"> 42,5 EUR · 9 US </option>
<option class="" value="9_73"> 43 EUR · 9,5 US </option>
<option class="" value="9_74"> 44 EUR · 10 US </option>
```

<p>Is there any posibility to get it?</p>

<p>I tried this code:</p>

<pre class="lang-py prettyprint-override"><code>scraper = cfscrape.create_scraper()
content_rdy = scraper.get(link, headers=headers).text
soup = bs4.BeautifulSoup(content_rdy, 'lxml')

input_id = soup.find_all('option', text='44 EUR')
print(input_id)
</code>```

but it gives me empty [].  If I use:

input_id = soup.find_all('option')
```

I can't get exact the value of the option. And the problem is that the only thing how I can get this value is the size inside this element.

I want to get this -> value="9_72"

答:
Add this after the line:

```<code>input_id = soup.find_all('option')
for options in input_id:
    option_text = options.text
    if '44 EUR' in options_text:
       final_options_text = options_text

print(final_options_text)
</code>```

Essentially you can iterate over the result set and do a wild card match to see which of the tags has the text you need.

Body:
I've got a problem using BeautifulSoup. I need to get the value of the element using only some text inside but I've got no idea how to do that. There's some HTML code:

<option class="" value="9_72"> 42,5 EUR · 9 US </option>
<option class="" value="9_73"> 43 EUR · 9,5 US </option>
<option class="" value="9_74"> 44 EUR · 10 US </option>

Is there any posibility to get it?

I tried this code:

scraper = cfscrape.create_scraper()
content_rdy = scraper.get(link, headers=headers).text
soup = bs4.BeautifulSoup(content_rdy, 'lxml')

input_id = soup.find_all('option', text='44 EUR')
print(input_id)

but it gives me empty [].  If I use:

input_id = soup.find_all('option')

I can't get exact the value of the option. And the problem is that the only thing how I can get this value is the size inside this element.

I want to get this -> value="9_72"

Body:
Add this after the line:

input_id = soup.find_all('option')
for options in input_id:
    option_text = options.text
    if '44 EUR' in options_text:
       final_options_text = options_text

print(final_options_text)

Essentially you can iterate over the result set and do a wild card match to see which of the tags has the text you need.


问:
Avoiding asynchonous code from beign run after the test was finished
Our Jasmine test suite is becoming flakier everyday because of asynchronous code running after the test finished.

Example:

code:

@Component
export class MyComponent {

  doSomething() {
    setTimeout(() => {
      somethingThatThrowsOnTest();
    }, 5000);
  }
}
```

<p>test:</p>

<pre class="lang-js prettyprint-override"><code>it('should do something', () => {
  component.doSomething(); <-- Doesnt fail because the exception isn't thrown during the test.
});
</code>```

How do I avoid this kind of problems ?

I made a stackblitz with this issue: https://stackblitz.com/edit/jasmine-fail-afterall?file=app%2Fapp.component.spec.ts

It will pass all tests and then throw a error.

答:
I like using async(done) and waiting for promises to resolve before asserting for them.

```<code>  it('should do something', async(done) => {
    // given
    const { comp, el, fixture } = setup();

    // when
    fixture.detectChanges();
    comp.doSomethingAsync(); // Trigger asynchronous code
    await fixture.whenStable();
    // your assertions
    done();
  });
</code>```

However, in your case, since you're using a setTimeout of 5s, you can save yourself 5s by using fakeAsync and tick. Tick does the fake passing of time.

```<code>  it('should do something', fakeAsync(() => {
    // given
    const { comp, el, fixture } = setup();

    // when
    fixture.detectChanges();
    comp.doSomethingAsync(); // Trigger asynchronous code
    tick(5000);              // Make 5 seconds pass instantaneously
    // your assertions
  }));
</code>```

=============================================
Now you're saying to avoid asynchronous code from running after the test has completed. Maybe you can do:

```<code>  // wait for the promises to resolve before going to the next it test
  afterEach(async(done) => { await fixture.whenStable(); done(); });
</code>```

If they are setTimeout, I would clear the timeouts in the ngOnDestroy so they don't haunt you in the future.

Body:
Our Jasmine test suite is becoming flakier everyday because of asynchronous code running after the test finished.

Example:

code:

@Component
export class MyComponent {

  doSomething() {
    setTimeout(() => {
      somethingThatThrowsOnTest();
    }, 5000);
  }
}

test:

it('should do something', () => {
  component.doSomething(); <-- Doesnt fail because the exception isn't thrown during the test.
});

How do I avoid this kind of problems ?

I made a stackblitz with this issue: https://stackblitz.com/edit/jasmine-fail-afterall?file=app%2Fapp.component.spec.ts

It will pass all tests and then throw a error.

Body:
I like using async(done) and waiting for promises to resolve before asserting for them.

  it('should do something', async(done) => {
    // given
    const { comp, el, fixture } = setup();

    // when
    fixture.detectChanges();
    comp.doSomethingAsync(); // Trigger asynchronous code
    await fixture.whenStable();
    // your assertions
    done();
  });

However, in your case, since you're using a setTimeout of 5s, you can save yourself 5s by using fakeAsync and tick. Tick does the fake passing of time.

  it('should do something', fakeAsync(() => {
    // given
    const { comp, el, fixture } = setup();

    // when
    fixture.detectChanges();
    comp.doSomethingAsync(); // Trigger asynchronous code
    tick(5000);              // Make 5 seconds pass instantaneously
    // your assertions
  }));

=============================================
Now you're saying to avoid asynchronous code from running after the test has completed. Maybe you can do:

  // wait for the promises to resolve before going to the next it test
  afterEach(async(done) => { await fixture.whenStable(); done(); });

If they are setTimeout, I would clear the timeouts in the ngOnDestroy so they don't haunt you in the future.


答:
So, I reworked the entire answer. Please, review the code. I am pretty sure this is what you want.

Short summary

The problem is that you need to split rows which start and end on different dates. And you need to do this recursively. So, I split the dataframe into a list of 1-row dataframes. For each I check whether start and end is on the same day. If not, I make it a 2-row dataframe with the adjusted start and end times. This is then split up again into a list of 1-row dataframes and so on so forth.
In the end there is a nested list of 1-row dataframes where start and end is on the same day. And this list is then recursively bound together again.

```<code># Load Packages ---------------------------------------------------------------------------------------------------

library(tidyverse)
library(lubridate)

df <- tribble(
    ~ID,         ~WearStart,              ~WearEnd
    , 01, "2018-05-14 09:00:00", "2018-05-14 20:00:00"
    , 01, "2018-05-14 21:30:00", "2018-05-15 02:00:00"
    , 01, "2018-05-15 07:00:00", "2018-05-16 22:30:00"
    , 01, "2018-05-16 23:00:00", "2018-05-16 23:40:00"
    , 01, "2018-05-17 01:00:00", "2018-05-19 15:00:00"
)
df <- df %>% mutate_at(vars(starts_with("Wear")), ymd_hms)

# Helper Functions ------------------------------------------------------------------------------------------------

endsOnOtherDay <- function(df){
    as_date(df$WearStart) != as_date(df$WearEnd)
}

split1rowInto2Days <- function(df){
    df1 <- df
    df2 <- df
    df1$WearEnd <- as_date(df1$WearStart) + days(1) - milliseconds(1)
    df2$WearStart <- as_date(df2$WearStart) + days(1)
    rbind(df1, df2)
}

splitDates <- function(df){
    if (nrow(df) > 1){
        return(df %>%
                   split(f = 1:nrow(df)) %>%
                   lapply(splitDates) %>%
                   reduce(rbind))
    }

    if (df %>% endsOnOtherDay()){
        return(df %>%
                   split1rowInto2Days() %>%
                   splitDates())
    }

    df
}

# The actual Calculation ------------------------------------------------------------------------------------------

df %>%
    splitDates() %>%
    mutate(wearDuration = difftime(WearEnd, WearStart, units = "hours")
           , wearDay = as_date(WearStart)) %>%
    group_by(ID, wearDay) %>%
    summarise(wearDuration_perDay = sum(wearDuration))

     ID wearDay    wearDuration_perDay
  <dbl> <date>     <drtn>
1     1 2018-05-14 13.50000 hours
2     1 2018-05-15 19.00000 hours
3     1 2018-05-16 23.16667 hours
4     1 2018-05-17 23.00000 hours
5     1 2018-05-18 24.00000 hours
6     1 2018-05-19 15.00000 hours
</code>```

Title: R: how can I split one row of a time period into multiple rows based on day and time

Body:
I am trying to split rows in an excel file based on day and time. The data is from a study which participants will need to wear a tracking watch. Each row of the data set is started with participants put on the watch (Variable: 'Wear Time Start ') and ended with them taking off the device (Variable: 'Wear Time End').

I need to calculate how many hours of each participant wearing the device on each day (NOT each time period in one row).

Data set before split:

   ID          WearStart                WearEnd
1  01           2018-05-14 09:00:00      2018-05-14 20:00:00
2  01           2018-05-14 21:30:00      2018-05-15 02:00:00
3  01           2018-05-15 07:00:00      2018-05-16 22:30:00
4  01           2018-05-16 23:00:00      2018-05-16 23:40:00
5  01           2018-05-17 01:00:00      2018-05-19 15:00:00
6  02           ...

Some explanation about the data set before split:  the data type of 'WearStart' and 'WearEnd' are POSIXlt.

Desired output after split:

  ID         WearStart                WearEnd                Interval
1 01         2018-05-14 09:00:00      2018-05-14 20:00:00    11
2 01         2018-05-14 21:30:00      2018-05-15 00:00:00    2.5
3 01         2018-05-15 00:00:00      2018-05-15 02:00:00    2
4 01         2018-05-15 07:00:00      2018-05-16 00:00:00    17
5 01         2018-05-16 00:00:00      2018-05-16 22:30:00    22.5
4 01         2018-05-16 23:00:00      2018-05-16 23:40:00    0.4
5 01         2018-05-17 01:00:00      2018-05-18 00:00:00    23
6 01         2018-05-18 00:00:00      2018-05-19 00:00:00    24
7 01         2018-05-19 00:00:00      2018-05-19 15:00:00    15

Then I need to accumulate hours based on day:

  ID         Wear_Day        Total_Hours
1 01         2018-05-14      13.5
2 01         2018-05-15      19
3 01         2018-05-16      22.9
4 01         2018-05-17      23
5 01         2018-05-18      24
4 01         2018-05-19      15

Body:
So, I reworked the entire answer. Please, review the code. I am pretty sure this is what you want.

Short summary

The problem is that you need to split rows which start and end on different dates. And you need to do this recursively. So, I split the dataframe into a list of 1-row dataframes. For each I check whether start and end is on the same day. If not, I make it a 2-row dataframe with the adjusted start and end times. This is then split up again into a list of 1-row dataframes and so on so forth.
In the end there is a nested list of 1-row dataframes where start and end is on the same day. And this list is then recursively bound together again.

# Load Packages ---------------------------------------------------------------------------------------------------

library(tidyverse)
library(lubridate)

df <- tribble(
    ~ID,         ~WearStart,              ~WearEnd
    , 01, "2018-05-14 09:00:00", "2018-05-14 20:00:00"
    , 01, "2018-05-14 21:30:00", "2018-05-15 02:00:00"
    , 01, "2018-05-15 07:00:00", "2018-05-16 22:30:00"
    , 01, "2018-05-16 23:00:00", "2018-05-16 23:40:00"
    , 01, "2018-05-17 01:00:00", "2018-05-19 15:00:00"
)
df <- df %>% mutate_at(vars(starts_with("Wear")), ymd_hms)

# Helper Functions ------------------------------------------------------------------------------------------------

endsOnOtherDay <- function(df){
    as_date(df$WearStart) != as_date(df$WearEnd)
}

split1rowInto2Days <- function(df){
    df1 <- df
    df2 <- df
    df1$WearEnd <- as_date(df1$WearStart) + days(1) - milliseconds(1)
    df2$WearStart <- as_date(df2$WearStart) + days(1)
    rbind(df1, df2)
}

splitDates <- function(df){
    if (nrow(df) > 1){
        return(df %>%
                   split(f = 1:nrow(df)) %>%
                   lapply(splitDates) %>%
                   reduce(rbind))
    }

    if (df %>% endsOnOtherDay()){
        return(df %>%
                   split1rowInto2Days() %>%
                   splitDates())
    }

    df
}

# The actual Calculation ------------------------------------------------------------------------------------------

df %>%
    splitDates() %>%
    mutate(wearDuration = difftime(WearEnd, WearStart, units = "hours")
           , wearDay = as_date(WearStart)) %>%
    group_by(ID, wearDay) %>%
    summarise(wearDuration_perDay = sum(wearDuration))

     ID wearDay    wearDuration_perDay
  <dbl> <date>     <drtn>
1     1 2018-05-14 13.50000 hours
2     1 2018-05-15 19.00000 hours
3     1 2018-05-16 23.16667 hours
4     1 2018-05-17 23.00000 hours
5     1 2018-05-18 24.00000 hours
6     1 2018-05-19 15.00000 hours


问:
LiveDataScope vs ViewModelScope in Android
I was reading how to use coroutines here https://developer.android.com/topic/libraries/architecture/coroutines. What makes me confused about is the difference between LiveDataScope and ViewModelScope. It sounds like ViewModelScope takes care of lifecycle automatically and you can do network request in the block. When data received from server, post the value to livedata. but then when I continued to read, there's another topic about LiveDataScope which seems redundant to me since you can already accomplish the same result by using ViewModelScope with livedata. What is the main difference between those two? and when should I choose to use one over the other?

答:
Note: This might be late answer for this topic if Author of OP already has understanding about this, But providing some pointers for the referencing comment of @IgorGanapolsky.

Let's see what is the main difference between viewModelScope & LiveDataScope

1. viewModelScope:

Official doc says that, CoroutineScope tied to this ViewModel. This
  scope will be canceled when ViewModel will be cleared, i.e
  ViewModel.onCleared is called

Meaning that coroutine scope is tied to ViewModel, and once ViewModel gets cleared this scope gets destroyed by cancelling all child coroutine jobs.

Basically, in MVVM pattern we use ViewModel tied to a particular Activity/Fragment.  So once that Activity/Fragment gets destroyed, its ViewModel reaches a cleared state. Thus, it cancels all incomplete jobs started by viewModelScope, throwing CancellationException.

So a usecase of viewModelScope is: inside ViewModel when you've got any suspended function to be called and need a CoroutineScope, inspite of making new one you can directly use this one out of the box from viewodel-ktx library.

```<code>class SomeViewModel: ViewModel() {

    fun someFunction() {
        viewModelScope.launch {
            callingSomeSuspendedFun()
            callingAnotherSuspendedFun()
        }
    }
}
</code>```

Note that you don't need to explicitly override onCleared() method of ViewModel to cancel the scope, it does automatically for you, cheers!

2. LiveDataScope:

Now speaking of LiveDataScope, it's actually an interface provided to build better support for LiveData/CoroutineLiveData that can have CoroutineScope out of the box! use livedata-ktx version

Now imagine a situation that you're having a MVVM pattern and wanted to return LiveData from repository to view model. your repository also contains some suspended functions and some coroutine scope.

In that situation when you do some suspended method calls & return the result as live data, there would be some extra work. you'll need transform your data to particular live data after getting it as result. see the example below:

```<code>class SomeRepository {

    suspended fun someApiCall() : LiveData<Result> {
        val result = MutableLiveData<Result>()
        someCoroutineScope.launch {
            val someData = someOtherCallToGetResult()
            result.postValue(someData)
        }
        return result
    }
}
</code>```

Imagine you had to write above code block due to LiveData didn't had any support for Coroutines ... but until now!

Now you can directly use liveData { } function that returns you LiveData object giving you scope of LiveDataScope in such a way that you can continue your suspended work and emit the result at the same level rather than getting it messy way like above. So above code block can now optimized by following code or better:

```<code>class SomeRepository {

    suspended fun someApiCall() : LiveData<Result> {
        return liveData<Result> {
            val someData = someOtherCallToGetResult()
            emit(someData)
        }
    }
}
</code>```

So use case of liveData would be at repository level when using MVVM pattern if you expose LiveData to viewmodel from respository rather than creating new inside viewmodel. Please note that there's no thumb rule about liveData method shouldn't be used at viewmodel directly. You can if you want to avoid viewModelScope completely.

TL;DR

Check out the liveData method,

Doc states that, The liveData building block serves as a
  structured concurrency primitive between coroutines and LiveData. The code block starts executing when LiveData becomes
  active and is automatically canceled after a configurable timeout when
  the LiveData becomes inactive. If it is canceled before completion,
  it is restarted if the LiveData becomes active again. If it
  completed successfully in a previous run, it doesn't restart. Note
  that it is restarted only if canceled automatically. If the block is
  canceled for any other reason (e.g. throwing a
  CancelationException), it is not restarted.

I hope that make sense!

Body:
Note: This might be late answer for this topic if Author of OP already has understanding about this, But providing some pointers for the referencing comment of @IgorGanapolsky.

Let's see what is the main difference between viewModelScope & LiveDataScope

1. viewModelScope:

Official doc says that, CoroutineScope tied to this ViewModel. This
  scope will be canceled when ViewModel will be cleared, i.e
  ViewModel.onCleared is called

Meaning that coroutine scope is tied to ViewModel, and once ViewModel gets cleared this scope gets destroyed by cancelling all child coroutine jobs.

Basically, in MVVM pattern we use ViewModel tied to a particular Activity/Fragment.  So once that Activity/Fragment gets destroyed, its ViewModel reaches a cleared state. Thus, it cancels all incomplete jobs started by viewModelScope, throwing CancellationException.

So a usecase of viewModelScope is: inside ViewModel when you've got any suspended function to be called and need a CoroutineScope, inspite of making new one you can directly use this one out of the box from viewodel-ktx library.

class SomeViewModel: ViewModel() {

    fun someFunction() {
        viewModelScope.launch {
            callingSomeSuspendedFun()
            callingAnotherSuspendedFun()
        }
    }
}

Note that you don't need to explicitly override onCleared() method of ViewModel to cancel the scope, it does automatically for you, cheers!

2. LiveDataScope:

Now speaking of LiveDataScope, it's actually an interface provided to build better support for LiveData/CoroutineLiveData that can have CoroutineScope out of the box! use livedata-ktx version

Now imagine a situation that you're having a MVVM pattern and wanted to return LiveData from repository to view model. your repository also contains some suspended functions and some coroutine scope.

In that situation when you do some suspended method calls & return the result as live data, there would be some extra work. you'll need transform your data to particular live data after getting it as result. see the example below:

class SomeRepository {

    suspended fun someApiCall() : LiveData<Result> {
        val result = MutableLiveData<Result>()
        someCoroutineScope.launch {
            val someData = someOtherCallToGetResult()
            result.postValue(someData)
        }
        return result
    }
}

Imagine you had to write above code block due to LiveData didn't had any support for Coroutines ... but until now!

Now you can directly use liveData { } function that returns you LiveData object giving you scope of LiveDataScope in such a way that you can continue your suspended work and emit the result at the same level rather than getting it messy way like above. So above code block can now optimized by following code or better:

class SomeRepository {

    suspended fun someApiCall() : LiveData<Result> {
        return liveData<Result> {
            val someData = someOtherCallToGetResult()
            emit(someData)
        }
    }
}

So use case of liveData would be at repository level when using MVVM pattern if you expose LiveData to viewmodel from respository rather than creating new inside viewmodel. Please note that there's no thumb rule about liveData method shouldn't be used at viewmodel directly. You can if you want to avoid viewModelScope completely.

TL;DR

Check out the liveData method,

Doc states that, The liveData building block serves as a
  structured concurrency primitive between coroutines and LiveData. The code block starts executing when LiveData becomes
  active and is automatically canceled after a configurable timeout when
  the LiveData becomes inactive. If it is canceled before completion,
  it is restarted if the LiveData becomes active again. If it
  completed successfully in a previous run, it doesn't restart. Note
  that it is restarted only if canceled automatically. If the block is
  canceled for any other reason (e.g. throwing a
  CancelationException), it is not restarted.

I hope that make sense!


问:
SSRS Report XML export
When we export an SSRS report as an XML, the generated XML report has fully qualified internal domain name of the reporting server.
need to come up with a solution , wherein the generated XML should contain only the report data without the details of the reporting server.</p>

答:
There's not a way to remove the domain from the XML. This is the default and there aren't any properties to control it.

Attaching the name prefix is a normal behavior when you export the
  report to XML file, as name conflicts in XML can easily be avoided
  using a name prefix

[MSFT] MSDN Community Support

The suggestion is to create a custom rendering extension.

Unfortunately, MS Docs notes that:

Writing a custom rendering extension is difficult. A rendering
  extension must typically support all possible combinations of report
  elements and requires that you implement hundreds of classes,
  interfaces, methods, and properties.

MS Docs - Rendering Extensions Overview

Title: SSRS Report XML export