问:
Wfs layer registration failed
I can't solve this problem:

We have developed a webmapping application.

We use OpenLayers version 6 and Geoserver 2.18, and PostGis 3.0.2

Loading a WFS layer on openlayers is no problem.

On Openlayers, I tried to edit (add new vector) this layer (wfs-t) but save failed.

Editing this layer (wfs-t) on Qgis is going well.

here are the code blocks:

```<code>//variables
var its_typeName ='reception:fak_test';
var url_NS = 'http://localhost:8080/geoserver';
var url_wfs ='http://localhost:8080/geoserver/reception/ows?service=WFS&version=1.0.0';
var fak_draw;
var formatWFS = new ol.format.WFS();
var formatGML = new ol.format.GML3({
    featureNS: url_NS,
    featureType: its_typeName,
    srsName: 'EPSG:4326'
    //srsName: "EPSG:3857"
});
var transactWFS = function(p,f) {
    f.unset('bbox', true);
    switch(p) {
    case 'insert':
        node = formatWFS.writeTransaction([f],null,null,formatGML);
        break;
    case 'update':
        node = formatWFS.writeTransaction(null,[f],null,formatGML);
        break;
    case 'delete':
        node = formatWFS.writeTransaction(null,null,[f],formatGML);
        break;
    }
    s = new XMLSerializer();
    str = s.serializeToString(node);
    console.log(str);

    // send data
    var request = new XMLHttpRequest();
    request.onreadystatechange = function() {
        if (request.readyState == 4 && request.status == 200) {
            alert(request.responseText);
        }
    }
    request.open("POST", url_wfs, true);
    request.send(str);

}

// parameter of layer
var PolygonStyle = [
    new ol.style.Style({
        stroke: new ol.style.Stroke({ color: '#EC1B0C', width: 3,}),
        fill: new ol.style.Fill({ color: 'rgba(0, 0, 255, 0.1)',}),
    })
];

// to load wfs on OpenLayers
function test_wfs_t(){
    var url = url_wfs
        + '&request=GetFeature'
        + '&typeName=' + its_typeName
        + '&outputFormat=application/json';
    fetch(url)
    .then((response) => response.text())
    .then((data) => {
        //console.log(data);
        getItsAttributs_db(data);
    });

}

function getItsAttributs_db(xData)
{
    //get its infos to post in the new feature
    var JSON_received = JSON.parse(xData);
    var len_draw = JSON_received.features.length;
    var xid = len_draw + 1;
    var nom = "xxx";
    var custom_lab = "next";
    var descriptio = "bla bla";
    var xcouleur= "#FF0000";

    // convert to GeoJSON
    const vectorSource = new ol.source.Vector({
        features: new ol.format.GeoJSON().readFeatures(xData, {
            dataProjection: 'EPSG:4326',
            featureProjection: 'EPSG:3857'
        }),
    });

    // init vector to load on map
    var fak_Vector = new ol.layer.Vector({
        source: vectorSource,
        style: PolygonStyle
    });
    var its_source = fak_Vector.getSource();

    // load on map
    map.addLayer(fak_Vector);

    //remove old draw
    map.removeInteraction(fak_draw);

    //add new draw
    draw_boo_wfst = true;
    fak_draw = new ol.interaction.Draw({
        type: 'MultiPolygon',
        source: its_source
    });
    map.addInteraction(fak_draw);

    // on end of draw
    fak_draw.on('drawend', function(e) {
        //add its properties
        var draw_wfst = e.feature;
        draw_wfst.setProperties(create_gfc_Attributs_view(xid, nom, descriptio, custom_lab, xcouleur));
        // try to send to database
        transactWFS('insert', draw_wfst);
    });

}

// to create attributs of the new feature
function create_gfc_Attributs_view(xid, nom, descriptio, custom_lab, xcouleur){
    var xTable = {};
    xTable.id = xid;
    xTable.name = nom;
    xTable.descriptio = descriptio;
    xTable.custom_lab = custom_lab;
    xTable.color = xcouleur;
    // callback
    return xTable;
}

</code>```

PostgreSQL syntax :

```<code>-- Structure of postgis
CREATE TABLE public.fak_test
(
    id integer NOT NULL DEFAULT nextval('track_store.fak_test_id_seq'::regclass),
    geom geometry(MultiPolygon,4326),
    name character varying(254) COLLATE pg_catalog."default",
    descriptio character varying(254) COLLATE pg_catalog."default",
    custom_lab character varying(254) COLLATE pg_catalog."default",
    color character varying(254) COLLATE pg_catalog."default",
    CONSTRAINT fak_test_pkey PRIMARY KEY (id)
)

GRANT ALL ON TABLE public.fak_test TO myuser;

CREATE INDEX sidx_fak_test_geom
    ON public.fak_test USING gist
    (geom)
    TABLESPACE pg_default;

</code>```

Output of GML

```<code><Transaction xmlns="http://www.opengis.net/wfs" service="WFS" version="1.1.0"
    xsi:schemaLocation="http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.1.0/wfs.xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Insert>
        <reception:fak_test xmlns:reception="http://localhost:8080/geoserver">
            <reception:geometry>
                <MultiPolygon xmlns="http://www.opengis.net/gml" srsName="EPSG:4326">
                    <polygonMember>
                        <Polygon srsName="EPSG:4326">
                        <exterior>
                            <LinearRing srsName="EPSG:4326">
                                <posList srsDimension="2">
                                    -2144007.8418341065 5288167.744512376 -2144040.7892421824 5289040.850826394 -2145259.8433409994 5288645.48192948 -2144007.8418341065 5288167.744512376
                                </posList>
                            </LinearRing>
                        </exterior>
                        </Polygon>
                    </polygonMember>
                </MultiPolygon>
            </reception:geometry>
            <reception:id>5</reception:id>
            <reception:name>xxx</reception:name>
            <reception:descriptio>bla blax</reception:descriptio>
            <reception:custom_lab>suite</reception:custom_lab>
            <reception:color>#FF0000</reception:color>
        </reception:fak_test>
    </Insert>
</Transaction>
</code>```

Response from server:

```<code><?xml version="1.0" encoding="UTF-8"?>
<ows:ExceptionReport xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:ows="http://www.opengis.net/ows"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0.0"
xsi:schemaLocation="http://www.opengis.net/ows http://localhost:8080/geoserver/schemas/ows/1.0.0/owsExceptionReport.xsd">
<ows:Exception exceptionCode="InvalidParameterValue">
<ows:ExceptionText>org.geotools.referencing.operation.projection.PointOutsideEnvelopeException: -2144007.8418341065 outside of (-180.0,180.0)
Parsing failed for LinearRing: org.geoserver.wfs.WFSException: org.geotools.referencing.operation.projection.PointOutsideEnvelopeException: -2144007.8418341065 outside of (-180.0,180.0)
org.geotools.referencing.operation.projection.PointOutsideEnvelopeException: -2144007.8418341065 outside of (-180.0,180.0)
-2144007.8418341065 outside of (-180.0,180.0)</ows:ExceptionText>
</ows:Exception>
</ows:ExceptionReport>
</code>```

Where is the problem?
Thank you

答:
You are lying to GeoServer and it doesn't like it. You are sending coordinates that are not in lat/lon but claiming that they are.

```<code>                <Polygon srsName="EPSG:4326">
                    <exterior>
                        <LinearRing srsName="EPSG:4326">
                            <posList srsDimension="2">
                                -2144007.8418341065 5288167.744512376 -2144040.7892421824 5289040.850826394 -2145259.8433409994 5288645.48192948 -2144007.8418341065 5288167.744512376
                            </posList>
                        </LinearRing>
                    </exterior>
                   </Polygon>
</code>```

I don't know what projection your map is in, but I'd guess it is Web Mercator (EPSG:3857) so you should either set that in the data you send or reproject the polygon to ESPG:4326 before you send it.

Title: Wfs layer registration failed

Body:
I can't solve this problem:

We have developed a webmapping application.

We use OpenLayers version 6 and Geoserver 2.18, and PostGis 3.0.2

Loading a WFS layer on openlayers is no problem.

On Openlayers, I tried to edit (add new vector) this layer (wfs-t) but save failed.

Editing this layer (wfs-t) on Qgis is going well.

here are the code blocks:

//variables
var its_typeName ='reception:fak_test';
var url_NS = 'http://localhost:8080/geoserver';
var url_wfs ='http://localhost:8080/geoserver/reception/ows?service=WFS&version=1.0.0';
var fak_draw;
var formatWFS = new ol.format.WFS();
var formatGML = new ol.format.GML3({
    featureNS: url_NS,
    featureType: its_typeName,
    srsName: 'EPSG:4326'
    //srsName: "EPSG:3857"
});
var transactWFS = function(p,f) {
    f.unset('bbox', true);
    switch(p) {
    case 'insert':
        node = formatWFS.writeTransaction([f],null,null,formatGML);
        break;
    case 'update':
        node = formatWFS.writeTransaction(null,[f],null,formatGML);
        break;
    case 'delete':
        node = formatWFS.writeTransaction(null,null,[f],formatGML);
        break;
    }
    s = new XMLSerializer();
    str = s.serializeToString(node);
    console.log(str);

    // send data
    var request = new XMLHttpRequest();
    request.onreadystatechange = function() {
        if (request.readyState == 4 && request.status == 200) {
            alert(request.responseText);
        }
    }
    request.open("POST", url_wfs, true);
    request.send(str);

}

// parameter of layer
var PolygonStyle = [
    new ol.style.Style({
        stroke: new ol.style.Stroke({ color: '#EC1B0C', width: 3,}),
        fill: new ol.style.Fill({ color: 'rgba(0, 0, 255, 0.1)',}),
    })
];

// to load wfs on OpenLayers
function test_wfs_t(){
    var url = url_wfs
        + '&request=GetFeature'
        + '&typeName=' + its_typeName
        + '&outputFormat=application/json';
    fetch(url)
    .then((response) => response.text())
    .then((data) => {
        //console.log(data);
        getItsAttributs_db(data);
    });

}

function getItsAttributs_db(xData)
{
    //get its infos to post in the new feature
    var JSON_received = JSON.parse(xData);
    var len_draw = JSON_received.features.length;
    var xid = len_draw + 1;
    var nom = "xxx";
    var custom_lab = "next";
    var descriptio = "bla bla";
    var xcouleur= "#FF0000";

    // convert to GeoJSON
    const vectorSource = new ol.source.Vector({
        features: new ol.format.GeoJSON().readFeatures(xData, {
            dataProjection: 'EPSG:4326',
            featureProjection: 'EPSG:3857'
        }),
    });

    // init vector to load on map
    var fak_Vector = new ol.layer.Vector({
        source: vectorSource,
        style: PolygonStyle
    });
    var its_source = fak_Vector.getSource();

    // load on map
    map.addLayer(fak_Vector);

    //remove old draw
    map.removeInteraction(fak_draw);

    //add new draw
    draw_boo_wfst = true;
    fak_draw = new ol.interaction.Draw({
        type: 'MultiPolygon',
        source: its_source
    });
    map.addInteraction(fak_draw);

    // on end of draw
    fak_draw.on('drawend', function(e) {
        //add its properties
        var draw_wfst = e.feature;
        draw_wfst.setProperties(create_gfc_Attributs_view(xid, nom, descriptio, custom_lab, xcouleur));
        // try to send to database
        transactWFS('insert', draw_wfst);
    });

}

// to create attributs of the new feature
function create_gfc_Attributs_view(xid, nom, descriptio, custom_lab, xcouleur){
    var xTable = {};
    xTable.id = xid;
    xTable.name = nom;
    xTable.descriptio = descriptio;
    xTable.custom_lab = custom_lab;
    xTable.color = xcouleur;
    // callback
    return xTable;
}

PostgreSQL syntax :

-- Structure of postgis
CREATE TABLE public.fak_test
(
    id integer NOT NULL DEFAULT nextval('track_store.fak_test_id_seq'::regclass),
    geom geometry(MultiPolygon,4326),
    name character varying(254) COLLATE pg_catalog."default",
    descriptio character varying(254) COLLATE pg_catalog."default",
    custom_lab character varying(254) COLLATE pg_catalog."default",
    color character varying(254) COLLATE pg_catalog."default",
    CONSTRAINT fak_test_pkey PRIMARY KEY (id)
)

GRANT ALL ON TABLE public.fak_test TO myuser;

CREATE INDEX sidx_fak_test_geom
    ON public.fak_test USING gist
    (geom)
    TABLESPACE pg_default;

Output of GML

<Transaction xmlns="http://www.opengis.net/wfs" service="WFS" version="1.1.0"
    xsi:schemaLocation="http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.1.0/wfs.xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Insert>
        <reception:fak_test xmlns:reception="http://localhost:8080/geoserver">
            <reception:geometry>
                <MultiPolygon xmlns="http://www.opengis.net/gml" srsName="EPSG:4326">
                    <polygonMember>
                        <Polygon srsName="EPSG:4326">
                        <exterior>
                            <LinearRing srsName="EPSG:4326">
                                <posList srsDimension="2">
                                    -2144007.8418341065 5288167.744512376 -2144040.7892421824 5289040.850826394 -2145259.8433409994 5288645.48192948 -2144007.8418341065 5288167.744512376
                                </posList>
                            </LinearRing>
                        </exterior>
                        </Polygon>
                    </polygonMember>
                </MultiPolygon>
            </reception:geometry>
            <reception:id>5</reception:id>
            <reception:name>xxx</reception:name>
            <reception:descriptio>bla blax</reception:descriptio>
            <reception:custom_lab>suite</reception:custom_lab>
            <reception:color>#FF0000</reception:color>
        </reception:fak_test>
    </Insert>
</Transaction>

Response from server:

<?xml version="1.0" encoding="UTF-8"?>
<ows:ExceptionReport xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:ows="http://www.opengis.net/ows"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0.0"
xsi:schemaLocation="http://www.opengis.net/ows http://localhost:8080/geoserver/schemas/ows/1.0.0/owsExceptionReport.xsd">
<ows:Exception exceptionCode="InvalidParameterValue">
<ows:ExceptionText>org.geotools.referencing.operation.projection.PointOutsideEnvelopeException: -2144007.8418341065 outside of (-180.0,180.0)
Parsing failed for LinearRing: org.geoserver.wfs.WFSException: org.geotools.referencing.operation.projection.PointOutsideEnvelopeException: -2144007.8418341065 outside of (-180.0,180.0)
org.geotools.referencing.operation.projection.PointOutsideEnvelopeException: -2144007.8418341065 outside of (-180.0,180.0)
-2144007.8418341065 outside of (-180.0,180.0)</ows:ExceptionText>
</ows:Exception>
</ows:ExceptionReport>

Where is the problem?
Thank you

Body:
You are lying to GeoServer and it doesn't like it. You are sending coordinates that are not in lat/lon but claiming that they are.

                <Polygon srsName="EPSG:4326">
                    <exterior>
                        <LinearRing srsName="EPSG:4326">
                            <posList srsDimension="2">
                                -2144007.8418341065 5288167.744512376 -2144040.7892421824 5289040.850826394 -2145259.8433409994 5288645.48192948 -2144007.8418341065 5288167.744512376
                            </posList>
                        </LinearRing>
                    </exterior>
                   </Polygon>

I don't know what projection your map is in, but I'd guess it is Web Mercator (EPSG:3857) so you should either set that in the data you send or reproject the polygon to ESPG:4326 before you send it.


来源: stackexchange

问:
Get variable name from object array
Can't find out how to get element variable name from array.

Need something like that:

var test = 1;
var test2 = "2";

var array = new object[]{test, test2};
foreach (var v in array)
{
 Debug.Log($"{v.ToString()} {v}")
}

// test 1
// test2 2
```

I need that in one method, lets call it "void CombineWithName(params object[] msg){}

答:
The nameof operator allows you to get the name of a variable, type or member in string form without hard-coding it as a literal.

```<code> var myVar = "ABC";
 Console.WriteLine(nameof(myVar));

</code>```

Source: https://riptutorial.com/csharp/example/363/basic-usage--printing-a-variable-name

Edited:

In your above approach, since you are directly mapping variables to an object, There is no way to figure out the variable that was used to set a element, unless you save that information in a separate array or collection (For debug purpose)

```<code>var test = 1;
var test2 = "2";

var array = new object[]{test, test2};

var arrayOfArrays = {
    new {Name = nameof(test), Array=test}
,   new {Name = nameof(test2), Array=test2}
};
foreach (var p in arrayOfArrays) {
    Console.WriteLine(p.Name);
    ...
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Get variable name from object array

Body:
Can't find out how to get element variable name from array.

Need something like that:

var test = 1;
var test2 = "2";

var array = new object[]{test, test2};
foreach (var v in array)
{
 Debug.Log($"{v.ToString()} {v}")
}

// test 1
// test2 2

I need that in one method, lets call it "void CombineWithName(params object[] msg){}

Body:
The nameof operator allows you to get the name of a variable, type or member in string form without hard-coding it as a literal.

 var myVar = "ABC";
 Console.WriteLine(nameof(myVar));

Source: https://riptutorial.com/csharp/example/363/basic-usage--printing-a-variable-name

Edited:

In your above approach, since you are directly mapping variables to an object, There is no way to figure out the variable that was used to set a element, unless you save that information in a separate array or collection (For debug purpose)

var test = 1;
var test2 = "2";

var array = new object[]{test, test2};

var arrayOfArrays = {
    new {Name = nameof(test), Array=test}
,   new {Name = nameof(test2), Array=test2}
};
foreach (var p in arrayOfArrays) {
    Console.WriteLine(p.Name);
    ...
}


问:
Why does @cacheEvict not work when called from the same class?
I am trying to clear my cache after every 30 mins using a scheduler in SpringBoot.

```<code>@Scheduled(cron = "0 0/30 * * * ?)
@CacheEvict(value = { "cache1", "cache2" }, allEntries = true)
public void clear() {
      //clears caches
}
</code>```

This wasn't working initially. I referred to this post : @CacheEvict is not working in SpringBoot and started calling it from a different class and it worked.

My question is why does this happen? I couldn't find any answer over the internet.

答:
This is not only for @cacheEvict but for all annotations on methods. Spring uses so called proxies to intercept the call and see which annotations are on a method to execute the logic for these annotations. But this can only be achieved when it's not an inner call.

See this https://spring.io/blog/2012/05/23/transactions-caching-and-aop-understanding-proxy-usage-in-spring

In proxy mode (which is the default), only external method calls
coming in through the proxy are intercepted. This means that
self-invocation, in effect, a method within the target object calling
another method of the target object, will not lead to an actual
transaction at runtime even if the invoked method is marked with
@Transactional. Also, the proxy must be fully initialized to provide
the expected behaviour so you should not rely on this feature in your
initialization code, i.e. @PostConstruct.

Body:
I am trying to clear my cache after every 30 mins using a scheduler in SpringBoot.

@Scheduled(cron = "0 0/30 * * * ?)
@CacheEvict(value = { "cache1", "cache2" }, allEntries = true)
public void clear() {
      //clears caches
}

This wasn't working initially. I referred to this post : @CacheEvict is not working in SpringBoot and started calling it from a different class and it worked.

My question is why does this happen? I couldn't find any answer over the internet.


问:
Returning cells as a Matrix VBA
I have a bunch of cells in a sheet that look like this:

Each rows has a gap of 3, and columns a gap of 5.

Id like to extract these values and copy it to some area:

How would I grab each cell and create a matrix like so. Im trying to use a VBA sub() for this, as the initial table size can vary but Im not sure how to do it. Any thoughts appreciated.

答:
For your data...</p>
```<code>Sub DeleteEmptyCells()
  Dim rngArea As Range
  Dim rngAreaErg As Range

  'determine usedrange of worksheet
  Set rngArea = Sheet1.UsedRange

 'identify all empty cells in area
  Set rngAreaErg = rngArea.SpecialCells(xlCellTypeBlanks)

  'delete empty cells by killig empty columns
  rngAreaErg.Delete xlShiftToLeft

  'determine alle empty cells, again
  Set rngAreaErg = rngArea.SpecialCells(xlCellTypeBlanks)

  'delete empty cells by killing empty rows
  rngAreaErg.Delete xlShiftUp

End Sub
</code>```

Title: Returning cells as a Matrix VBA

Body:
For your data...

Sub DeleteEmptyCells()
  Dim rngArea As Range
  Dim rngAreaErg As Range

  'determine usedrange of worksheet
  Set rngArea = Sheet1.UsedRange

 'identify all empty cells in area
  Set rngAreaErg = rngArea.SpecialCells(xlCellTypeBlanks)

  'delete empty cells by killig empty columns
  rngAreaErg.Delete xlShiftToLeft

  'determine alle empty cells, again
  Set rngAreaErg = rngArea.SpecialCells(xlCellTypeBlanks)

  'delete empty cells by killing empty rows
  rngAreaErg.Delete xlShiftUp

End Sub


问:
SwiftUI ForEach statement iterate the list twice
I've got ForEach loop inside a picker widget, that suppose to iterate a list of items (handler.items).

However, in reality, I get that the tags where not properly set and $arg = $0 instead of $arg = $0.components(separatedBy: " ")[0]

after debugging the problem, it seems that although i see the right number of items according to the list size ... the ForEach iterate all the items twice, thus causing duplicated tags where they suppose to be unique.

here's the code, any idea how come the iteration repeat itself ?

```<code>VStack {
    Picker("items", selection: $arg) {
        ForEach(handler.items , id: \.self, content: {
            Text($0).tag($0.components(separatedBy: " ")[0])
        })
    }
}
</code>```

and here's how handler.items are defined. it's actually a separated object that is visible from the view, and can be changed from swift native methods.

```<code>class myHandler: ObservableObject {
  @Published var items = [String]()
}
</code>```

when setting a breakpoint in the ForEach statement, i could print this object

```<code>(lldb) p handler.items
([String]) $R1 = 2 values {
  [0] = "aaa bbb cc 1.1.1.1"
  [1] = "ddd eee ff 2.2.2.2"
}
</code>```

When i put breakpoint inside the ForEach body, I could see that the breakpoint caught there 4 times, and printing the iterator value i Got this printouts:

```<code>aaa bbb cc 1.1.1.1
ddd eee ff 2.2.2.2
aaa bbb cc 1.1.1.1
ddd eee ff 2.2.2.2
</code>```

EDIT : here's a minimal reproducible example. notice the circled text that clearly shows that the arg didn't get the tag expression but the whole item :

答:
You need to have .pickerStyle(.wheel) to make it work on ios devices. Here is the code I used for testing:

(on macos 12.3-beta, using xcode 13.3-beta, targets ios 15 and macCatalyst 12)

```<code>class MyHandler: ObservableObject {
    @Published var items: [String] = ["aaa bbb cc 1.1.1.1", "ddd eee ff 2.2.2.2"]
}

struct ContentView: View {
    @State var handler = MyHandler()
    @State var arg = ""

    var body: some View {
        VStack {
            Text(arg) // <-- to display arg
            Picker("items", selection: $arg) {
                ForEach(handler.items , id: \.self) { str in
                    let _ = print(str.components(separatedBy: " ")[0]) // <-- to print tag values
                    Text(str).tag(str.components(separatedBy: " ")[0])
                }
            }.pickerStyle(.wheel)  // <--- here
        }
    }
}
</code>```

EDIT-1:
Note, on macos (Monterey) only app,  pickerStyle with radioGroup, segmented and inline, will work (i.e, no repeat of tags),
however,  menu, and automatic do not.

On ios/mac Catalyst, wheel, inline, segmented and automatic work, but menu does not.

Body:
I've got ForEach loop inside a picker widget, that suppose to iterate a list of items (handler.items).

However, in reality, I get that the tags where not properly set and $arg = $0 instead of $arg = $0.components(separatedBy: " ")[0]

after debugging the problem, it seems that although i see the right number of items according to the list size ... the ForEach iterate all the items twice, thus causing duplicated tags where they suppose to be unique.

here's the code, any idea how come the iteration repeat itself ?

VStack {
    Picker("items", selection: $arg) {
        ForEach(handler.items , id: \.self, content: {
            Text($0).tag($0.components(separatedBy: " ")[0])
        })
    }
}

and here's how handler.items are defined. it's actually a separated object that is visible from the view, and can be changed from swift native methods.

class myHandler: ObservableObject {
  @Published var items = [String]()
}

when setting a breakpoint in the ForEach statement, i could print this object

(lldb) p handler.items
([String]) $R1 = 2 values {
  [0] = "aaa bbb cc 1.1.1.1"
  [1] = "ddd eee ff 2.2.2.2"
}

When i put breakpoint inside the ForEach body, I could see that the breakpoint caught there 4 times, and printing the iterator value i Got this printouts:

aaa bbb cc 1.1.1.1
ddd eee ff 2.2.2.2
aaa bbb cc 1.1.1.1
ddd eee ff 2.2.2.2

EDIT : here's a minimal reproducible example. notice the circled text that clearly shows that the arg didn't get the tag expression but the whole item :

Body:
You need to have .pickerStyle(.wheel) to make it work on ios devices. Here is the code I used for testing:

(on macos 12.3-beta, using xcode 13.3-beta, targets ios 15 and macCatalyst 12)

class MyHandler: ObservableObject {
    @Published var items: [String] = ["aaa bbb cc 1.1.1.1", "ddd eee ff 2.2.2.2"]
}

struct ContentView: View {
    @State var handler = MyHandler()
    @State var arg = ""

    var body: some View {
        VStack {
            Text(arg) // <-- to display arg
            Picker("items", selection: $arg) {
                ForEach(handler.items , id: \.self) { str in
                    let _ = print(str.components(separatedBy: " ")[0]) // <-- to print tag values
                    Text(str).tag(str.components(separatedBy: " ")[0])
                }
            }.pickerStyle(.wheel)  // <--- here
        }
    }
}

EDIT-1:
Note, on macos (Monterey) only app,  pickerStyle with radioGroup, segmented and inline, will work (i.e, no repeat of tags),
however,  menu, and automatic do not.

On ios/mac Catalyst, wheel, inline, segmented and automatic work, but menu does not.


问:
Webbrowser support after 2022 - Internet Explorer
I have an application in which System.Forms.WebBrowser is being used.
Since Internet Explorer will be retired and go out of support on June 2022, Will System.Forms.WebBrowser will be supported after 2022 or in the newer versions of windows ?</p>

答:
Microsoft encourages customers to migrate to Microsoft Edge, because it provides support for legacy and modern websites and apps with Edge IE mode.

Internet Explorer mode in Microsoft Edge enables backward compatibility and will be supported through at least 2029. Additionally, Microsoft will provide notice one year prior to the retirement of IE mode.

So I think what we discussed after that is mainly about the issues in Edge IE mode rather than a specific control.

For more related Q & A, please refer to this official blog: Internet Explorer 11 desktop app retirement FAQ.


问:
Remove whole parent div if contained child div is empty
I'm trying to achieve the following:

I have multiple divs with the class "et_pb_row_inner" that contain two columns each. Each of the columns contain a text container with the class "et_pb_text".

Here's the basic html:

```<code><div class="et_pb_row_inner">
   <div class="et_pb_column"><div class="et_pb_text"></div></div>
   <div class="et_pb_column"><div class="et_pb_text"></div></div>
</div>

<div class="et_pb_row_inner">
   <div class="et_pb_column"><div class="et_pb_text"></div></div>
   <div class="et_pb_column"><div class="et_pb_text"></div></div>
</div>

<div class="et_pb_row_inner">
   <div class="et_pb_column"><div class="et_pb_text"></div></div>
   <div class="et_pb_column"><div class="et_pb_text"></div></div>
</div>

</code>```

I need a way to check if the text in the second column of each row is empty and if so remove the whole row. Like so:

```<code><div class="et_pb_row_inner">
   <div class="et_pb_column"><div class="et_pb_text">HAS TEXT</div></div>
   <div class="et_pb_column"><div class="et_pb_text">HAS TEXT</div></div>
</div>

<div class="et_pb_row_inner"> <!-- second column text empty, remove whole row -->
   <div class="et_pb_column"><div class="et_pb_text">HAS TEXT</div></div>
   <div class="et_pb_column"><div class="et_pb_text">EMPTY</div></div>
</div>

<div class=".et_pb_row_inner"> <!-- second column text empty, remove whole row -->
   <div class="et_pb_column"><div class="et_pb_text">HAS TEXT</div></div>
   <div class="et_pb_column"><div class="et_pb_text">EMPTY</div></div>
</div>

</code>```

I found a code snippet and tried the following:

```<code>$(function() {
    $('.et_pb_row_inner').each(function() {
        if ($('.et_pb_text', this).text() == "" ) {
            $('.et_pb_row_inner').hide();
        }
    });
});
</code>```

It kind of works, but it removes ALL divs with the class "et_pb_row_inner", not just the ones that contain the empty text div.

I guess it's just tweaking the code a little, but I can't get it working.

Any ideas?

Body:
I'm trying to achieve the following:

I have multiple divs with the class "et_pb_row_inner" that contain two columns each. Each of the columns contain a text container with the class "et_pb_text".

Here's the basic html:

I need a way to check if the text in the second column of each row is empty and if so remove the whole row. Like so:

HAS TEXT

HAS TEXT

HAS TEXT

EMPTY

HAS TEXT

EMPTY

I found a code snippet and tried the following:

$(function() {
    $('.et_pb_row_inner').each(function() {
        if ($('.et_pb_text', this).text() == "" ) {
            $('.et_pb_row_inner').hide();
        }
    });
});

It kind of works, but it removes ALL divs with the class "et_pb_row_inner", not just the ones that contain the empty text div.

I guess it's just tweaking the code a little, but I can't get it working.

Any ideas?

Body:
Try this:

$('.et_pb_row_inner').each((idx, ele) => {
    if($($(ele).children()[1]).text() === ''){
        $(ele).hide();
    }
})


问:
JIB with GitHub Actions

Introduction

I am currently create a GitHub Actions with that build a container automatically.

And I'm wondering if it's possible to create a GitHub action that automatically builds the container without adding JIB in the project's pom.xml ?

If we can t do this, can you show me how?

答:
Yes you can, whit this code on your GitHub workflows:

name: JIB container publish

on:
  release:
    types: [created]

jobs:
  publish:
    runs-on: ubuntu-latest
    steps:
      - name: JIB container build and publish
        uses: MathieuSoysal/jib-container-publish.yml@v2.0.7
        with:
          PASSWORD: ${{ secrets.GITHUB_TOKEN }}
```

For more details you can go in: https://github.com/MathieuSoysal/jib-container-publish.yml

Title: JIB with GitHub Actions

Body:
Yes you can, whit this code on your GitHub workflows:

name: JIB container publish

on:
  release:
    types: [created]

jobs:
  publish:
    runs-on: ubuntu-latest
    steps:
      - name: JIB container build and publish
        uses: MathieuSoysal/jib-container-publish.yml@v2.0.7
        with:
          PASSWORD: ${{ secrets.GITHUB_TOKEN }}

For more details you can go in: https://github.com/MathieuSoysal/jib-container-publish.yml


问:
Presenting a a ViewController on a xib file in SWIFT
I have a xib file which I have created a pop up controller on a UIView. This pop up controller animates up when a button is pressed on a View Controller 1. I then have a button on the UIView which when pressed I want to present another View Controller (View Controller 2). code looks like:

```<code>class PopUpViewControllerSwift : UIViewController {

  @IBAction func goToVC2(sender: UIButton) {

        self.removeAnimate()

        let VC2: VC2 = self.storyboard?.instantiateViewControllerWithIdentifier("VC2") as VC2
        var modalStyle: UIModalTransitionStyle = UIModalTransitionStyle.CoverVertical
        VC2.modalTransitionStyle = modalStyle
        presentViewController(VC2, animated: true, completion: nil)

    }
}
</code>```

Although thou when the button is pressed it crashes, no error or callbacks or anything. Obviously this would normally work if it was just a regular View Controller but because I am doing it inside a pop Up View which has been animated on top of another View I think that is the problem?

Can anybody help?

thanks

答:
It should be like this:</p>
```<code>let vc = MyViewController(nibName: "MyViewController", bundle: nil)
present(vc, animated: true, completion: nil)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a xib file which I have created a pop up controller on a UIView. This pop up controller animates up when a button is pressed on a View Controller 1. I then have a button on the UIView which when pressed I want to present another View Controller (View Controller 2). code looks like:

class PopUpViewControllerSwift : UIViewController {

  @IBAction func goToVC2(sender: UIButton) {

        self.removeAnimate()

        let VC2: VC2 = self.storyboard?.instantiateViewControllerWithIdentifier("VC2") as VC2
        var modalStyle: UIModalTransitionStyle = UIModalTransitionStyle.CoverVertical
        VC2.modalTransitionStyle = modalStyle
        presentViewController(VC2, animated: true, completion: nil)

    }
}

Although thou when the button is pressed it crashes, no error or callbacks or anything. Obviously this would normally work if it was just a regular View Controller but because I am doing it inside a pop Up View which has been animated on top of another View I think that is the problem?

Can anybody help?

thanks

Body:
It should be like this:

let vc = MyViewController(nibName: "MyViewController", bundle: nil)
present(vc, animated: true, completion: nil)


问:
TestNG: alternate between test cases with dataProvider
I've implemented dataProvider and it works for each class, but it doesn't alternate between test cases.

What it currently does is: start with test case 1 and go through all the dataset in the dataProvider, then move to Test Case 2 and do the same with all the data set.

I would like instead to alternate between test cases:

Start with line 1 of dataProvider: Test case 1 with line 1 of dataset, then move to Test Case 2 with line 1 of dataProvider, then Test case 3 with line 1 of dataProvider ... Once all test cases done, then

Move to the line 2 of dataProvider and start again: Test Case 1 with line 2 of dataProvider, then Test Case 2 with line 2 of dataProvider.... Is this possible ?

答:
Are you looking for class-level DataProvider?

In order to parametrize the test class, use @Factory + @DataProvider in the next way:

```<code>import org.testng.annotations.DataProvider
import org.testng.annotations.Factory
import org.testng.annotations.Test

class MyTestClass {

    String arg1;
    String arg2;

    @Factory(dataProvider = "provideClassArgs")
    public MyTestClass(String arg1, String arg2) {
        this.arg1 = arg1;
        this.arg2 = arg2;
    }

    @DataProvider
    public static Object[][] provideClassArgs() {
        return new Object[]{
                {"arg1-value1", "arg2-value1"},
                {"arg1-value2", "arg2-value2"}

        };
    }

    @Test
    public void test1() {
        System.out.println("Do test1 with: " + arg1 + ", " + arg2);
    }

    @Test
    public void test2() {
        System.out.println("Do test2 with: " + arg1 + ", " + arg2);
    }

    @Test
    public void test3() {
        System.out.println("Do test3 with: " + arg1 + ", " + arg2);
    }
}
</code>```

with the next textng.xml

NOTE: group-by-instances="true" should be defined

```<code><!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Test Suite" group-by-instances="true">
    <test name="Test">
        <classes>
            <class name="samples.MyTestClass"/>
        </classes>
    </test>
</suite>
</code>```

you will get:

```<code>Do test1 with: arg1-value2, arg2-value2
Do test2 with: arg1-value2, arg2-value2
Do test3 with: arg1-value2, arg2-value2
Do test1 with: arg1-value1, arg2-value1
Do test2 with: arg1-value1, arg2-value1
Do test3 with: arg1-value1, arg2-value1
</code>```

Class Execution Order

By default, DataProvider items will launch classes in random order.

The easiest way to make the order fixed: is override toString() method for test-class.

For this example:

```<code>@Override
public String toString() {
    return "MyTestClass";
}
</code>```

tests will be sorted alphabetically based on DataProvider args, converted to a string. This won't be the natural order like in DataProvider, but at least not random.

See more:

Factory annotation does not execute in the same order we configure the instances

Only the last @Test is being executed when using IMethodInterceptor as Listener in TestNG

Use Factory with DataProvider for multiple classes

NOTE: the request is to run all the classes per args line, and then the same classes per next arg line, etc.

Create the parent class for all test classes.

It should define all the required arguments

It should have a constructor for all the arguments

It should override toString() method, the result to be reflected by all the args. This is valuable for the execution order.

```<code>public class MyClassParent {

  String arg1;
  String arg2;

  public MyClassParent(String arg1, String arg2) {
      this.arg1 = arg1;
      this.arg2 = arg2;
  }

  @Override
  public String toString() {
      arg1.toString() + arg2.toString();
  }
}
</code>```

Implement test classes, like:

Extend from MyClassParent

Create the same constructor

```<code>public class MyTestClass1 extends MyClassParent {

    public MyTestClass1(String arg1, String arg2) {
        super(arg1, arg2);
    }

    @Test
    public void test1() {
        System.out.println("MyTestClass1: Do test1 with: " + arg1 + ", " + arg2);
    }

}
</code>```

Implement Factory with DataProvider.

Factory with DataProvider moved to separate class and produces test class objects array.

For applying the correct ordering IMethodInterceptor TestNG Listener interface was implemented.

And applied for the class with @Listeners(MyFactory).

intercept method overridden and sorting applied here.

Custom Comparator implemented for sorting, which compare 2 MyClassParent based on it's toString() results.

So while toString() depends on the MyClassParent args, all the classes for the same args will be in the same group.

```<code>import org.testng.IMethodInstance
import org.testng.IMethodInterceptor
import org.testng.ITestContext
import org.testng.annotations.DataProvider
import org.testng.annotations.Factory
import org.testng.annotations.Listeners

@Listeners(MyFactory)
public class MyFactory implements IMethodInterceptor {

    @Factory(dataProvider = "provideClassArgs")
    public Object[] generateTests(String arg1, String arg2) {
        return new Object[] {
                new MyTestClass1(arg1, arg2),
                new MyTestClass2(arg1, arg2),
                new MyTestClass3(arg1, arg2),
                new MyTestClass4(arg1, arg2),
                new MyTestClass5(arg1, arg2)
        };
    }

    @DataProvider
    public static Object[][] provideClassArgs() {
        return new Object[]{
                {"arg1-value1", "arg2-value1"},
                {"arg1-value2", "arg2-value2"},
                {"arg1-value3", "arg2-value2"}

        };
    }

    @Override
    List<IMethodInstance> intercept(List<IMethodInstance> methods, ITestContext context) {
        // applying sorting is essential to change the tests order
        methods.sort(new MyTestClassComparator());
        return methods;
    }

    // internal class added, assumed it should compare only methods from MainImpClass
    // here compareTo delegated to getA() results
    class MyTestClassComparator implements Comparator<IMethodInstance> {

        @Override
        int compare(IMethodInstance o1, IMethodInstance o2) {
            return ((MyClassParent)o1.getInstance()).toString().compareTo(((MyClassParent)o2.getInstance()).toString());
        }
    }
}
</code>```

4 TestNG xml:

```<code><!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Test Suite" group-by-instances="true">
    <test name="Test">
        <classes>
            <class name="samples.MyFactory"/>
        </classes>
    </test>
</suite>
</code>```

The final output:

```<code>MyTestClass1: Do test1 with: arg1-value1, arg2-value1
MyTestClass2: Do test2 with: arg1-value1, arg2-value1
MyTestClass3: Do test3 with: arg1-value1, arg2-value1
MyTestClass4: Do test4 with: arg1-value1, arg2-value1
MyTestClass5: Do test5 with: arg1-value1, arg2-value1
MyTestClass1: Do test1 with: arg1-value2, arg2-value2
MyTestClass2: Do test2 with: arg1-value2, arg2-value2
MyTestClass3: Do test3 with: arg1-value2, arg2-value2
MyTestClass4: Do test4 with: arg1-value2, arg2-value2
MyTestClass5: Do test5 with: arg1-value2, arg2-value2
MyTestClass1: Do test1 with: arg1-value3, arg2-value2
MyTestClass2: Do test2 with: arg1-value3, arg2-value2
MyTestClass3: Do test3 with: arg1-value3, arg2-value2
MyTestClass4: Do test4 with: arg1-value3, arg2-value2
MyTestClass5: Do test5 with: arg1-value3, arg2-value2
</code>```

Body:
Are you looking for class-level DataProvider?

In order to parametrize the test class, use @Factory + @DataProvider in the next way:

import org.testng.annotations.DataProvider
import org.testng.annotations.Factory
import org.testng.annotations.Test

class MyTestClass {

    String arg1;
    String arg2;

    @Factory(dataProvider = "provideClassArgs")
    public MyTestClass(String arg1, String arg2) {
        this.arg1 = arg1;
        this.arg2 = arg2;
    }

    @DataProvider
    public static Object[][] provideClassArgs() {
        return new Object[]{
                {"arg1-value1", "arg2-value1"},
                {"arg1-value2", "arg2-value2"}

        };
    }

    @Test
    public void test1() {
        System.out.println("Do test1 with: " + arg1 + ", " + arg2);
    }

    @Test
    public void test2() {
        System.out.println("Do test2 with: " + arg1 + ", " + arg2);
    }

    @Test
    public void test3() {
        System.out.println("Do test3 with: " + arg1 + ", " + arg2);
    }
}

with the next textng.xml

NOTE: group-by-instances="true" should be defined

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Test Suite" group-by-instances="true">
    <test name="Test">
        <classes>
            <class name="samples.MyTestClass"/>
        </classes>
    </test>
</suite>

you will get:

Do test1 with: arg1-value2, arg2-value2
Do test2 with: arg1-value2, arg2-value2
Do test3 with: arg1-value2, arg2-value2
Do test1 with: arg1-value1, arg2-value1
Do test2 with: arg1-value1, arg2-value1
Do test3 with: arg1-value1, arg2-value1

Class Execution Order

By default, DataProvider items will launch classes in random order.

The easiest way to make the order fixed: is override toString() method for test-class.

For this example:

@Override
public String toString() {
    return "MyTestClass";
}

tests will be sorted alphabetically based on DataProvider args, converted to a string. This won't be the natural order like in DataProvider, but at least not random.

See more:

Factory annotation does not execute in the same order we configure the instances

Only the last @Test is being executed when using IMethodInterceptor as Listener in TestNG

Use Factory with DataProvider for multiple classes

NOTE: the request is to run all the classes per args line, and then the same classes per next arg line, etc.

Create the parent class for all test classes.

It should define all the required arguments

It should have a constructor for all the arguments

It should override toString() method, the result to be reflected by all the args. This is valuable for the execution order.

public class MyClassParent {

  String arg1;
  String arg2;

  public MyClassParent(String arg1, String arg2) {
      this.arg1 = arg1;
      this.arg2 = arg2;
  }

  @Override
  public String toString() {
      arg1.toString() + arg2.toString();
  }
}

Implement test classes, like:

Extend from MyClassParent

Create the same constructor

public class MyTestClass1 extends MyClassParent {

    public MyTestClass1(String arg1, String arg2) {
        super(arg1, arg2);
    }

    @Test
    public void test1() {
        System.out.println("MyTestClass1: Do test1 with: " + arg1 + ", " + arg2);
    }

}

Implement Factory with DataProvider.

Factory with DataProvider moved to separate class and produces test class objects array.

For applying the correct ordering IMethodInterceptor TestNG Listener interface was implemented.

And applied for the class with @Listeners(MyFactory).

intercept method overridden and sorting applied here.

Custom Comparator implemented for sorting, which compare 2 MyClassParent based on it's toString() results.

So while toString() depends on the MyClassParent args, all the classes for the same args will be in the same group.

import org.testng.IMethodInstance
import org.testng.IMethodInterceptor
import org.testng.ITestContext
import org.testng.annotations.DataProvider
import org.testng.annotations.Factory
import org.testng.annotations.Listeners

@Listeners(MyFactory)
public class MyFactory implements IMethodInterceptor {

    @Factory(dataProvider = "provideClassArgs")
    public Object[] generateTests(String arg1, String arg2) {
        return new Object[] {
                new MyTestClass1(arg1, arg2),
                new MyTestClass2(arg1, arg2),
                new MyTestClass3(arg1, arg2),
                new MyTestClass4(arg1, arg2),
                new MyTestClass5(arg1, arg2)
        };
    }

    @DataProvider
    public static Object[][] provideClassArgs() {
        return new Object[]{
                {"arg1-value1", "arg2-value1"},
                {"arg1-value2", "arg2-value2"},
                {"arg1-value3", "arg2-value2"}

        };
    }

    @Override
    List<IMethodInstance> intercept(List<IMethodInstance> methods, ITestContext context) {
        // applying sorting is essential to change the tests order
        methods.sort(new MyTestClassComparator());
        return methods;
    }

    // internal class added, assumed it should compare only methods from MainImpClass
    // here compareTo delegated to getA() results
    class MyTestClassComparator implements Comparator<IMethodInstance> {

        @Override
        int compare(IMethodInstance o1, IMethodInstance o2) {
            return ((MyClassParent)o1.getInstance()).toString().compareTo(((MyClassParent)o2.getInstance()).toString());
        }
    }
}

4 TestNG xml:

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Test Suite" group-by-instances="true">
    <test name="Test">
        <classes>
            <class name="samples.MyFactory"/>
        </classes>
    </test>
</suite>

The final output:

MyTestClass1: Do test1 with: arg1-value1, arg2-value1
MyTestClass2: Do test2 with: arg1-value1, arg2-value1
MyTestClass3: Do test3 with: arg1-value1, arg2-value1
MyTestClass4: Do test4 with: arg1-value1, arg2-value1
MyTestClass5: Do test5 with: arg1-value1, arg2-value1
MyTestClass1: Do test1 with: arg1-value2, arg2-value2
MyTestClass2: Do test2 with: arg1-value2, arg2-value2
MyTestClass3: Do test3 with: arg1-value2, arg2-value2
MyTestClass4: Do test4 with: arg1-value2, arg2-value2
MyTestClass5: Do test5 with: arg1-value2, arg2-value2
MyTestClass1: Do test1 with: arg1-value3, arg2-value2
MyTestClass2: Do test2 with: arg1-value3, arg2-value2
MyTestClass3: Do test3 with: arg1-value3, arg2-value2
MyTestClass4: Do test4 with: arg1-value3, arg2-value2
MyTestClass5: Do test5 with: arg1-value3, arg2-value2


问:
How to clear props.location.state on refresh?
I am navigating to another page where in am passing some data like so:

```<code>this.props.history.push({
  pathname: "/someotherpage",
  state: { somedata: somedata }
});
</code>```

Now on /someotherpage, I have a condition in my render() method to show a component depending on whether this.props.location.state is not null.

```<code>{this.props.location.state && (
    <SomeComponent>
        {this.props.location.state.somedata}
    </SomeComponent>
)}
</code>```

It's working. However, when I refresh the page, <SomeComponent> still shows up as it still has the this.props.location.state.somedata stored even if I refresh. How do I clear this.props.location.state back to null when refreshing the page? (It seems to clear though when navigating away, only on refresh it gets retained.)

答:
You can do this by setting the current history entry's state to null like this:

```<code>const { state, pathname } = useLocation();

history.replace(pathname, null);
</code>```

Body:
I am navigating to another page where in am passing some data like so:

this.props.history.push({
  pathname: "/someotherpage",
  state: { somedata: somedata }
});

Now on /someotherpage, I have a condition in my render() method to show a component depending on whether this.props.location.state is not null.

{this.props.location.state && (
    <SomeComponent>
        {this.props.location.state.somedata}
    </SomeComponent>
)}

It's working. However, when I refresh the page, <SomeComponent> still shows up as it still has the this.props.location.state.somedata stored even if I refresh. How do I clear this.props.location.state back to null when refreshing the page? (It seems to clear though when navigating away, only on refresh it gets retained.)

Body:
You can do this by setting the current history entry's state to null like this:

const { state, pathname } = useLocation();

history.replace(pathname, null);


问:
VBA Loop through Sheets where sheetnames are made up of two variables
Caveat: my VBA knowledge is self-taught via Googling so please be patient with me!
I have a set of worksheets and am trying to perform the same set of actions through each sheet. Having problem with my codes:
E.g. worksheets are "Staging AA 101", "Staging AA 102", "Staging AA 201", "Staging BB 101", "Staging BB 102", "Staging BB 201", "Staging CC 101", "Staging CC 102", "Staging CC 201"

My codes are:

```<code>Dim ExpSub(1 To 3) As String
Dim Post(1 To 3) As String
Dim i As Integer 'ExpSub
Dim j As Integer 'Post

ExpSub(1) = "101"
ExpSub(2) = "102"
ExpSub(3) = "201"
Post(1) = "AA"
Post(2) = "BB"
Post(3) = "CC"

For j = 1 To 3 'j for Post
For i = 1 To 3 'i for ExpSub
    Sheets("Staging " & Post(j) & " " & ExpSub(i)).Select
    Range("AK4").Select
    Range(Selection, Selection.Offset(100, 1)).Select
    Selection.ClearContents
Next i
Next j
</code>```

Errored out at this line
Sheets("Staging " & Post(j) & " " & ExpSub(i)).Select

How do i loop through all the sheets with such variables please? Thanks in advance!

答:
Your loops work as expected. You should write the result of your string concatenation into an intermediate variable and check with the debugger.

I can think of two reasons why your code fails:

a) One of your sheets is missing or has a typo in its name (maybe an extra space character). Check with the debugger for which sheet your code fails.

b) You don't specify the Workbook you want to work with, so VBA will look for the sheets in the Active Workbook - maybe this is a different workbook.

Beside this: You don't need to Select a sheet or a range to work with them, and it fact this should be avoided because it makes your code slow and is an open gate for bugs. You should take the time and read How to avoid using Select in Excel VBA.

Your code could look like

```<code>Dim ExpSub() As Variant, Post As Variant
ExpSub = Array("101", "102", "201")
Post = Array("AA", "BB", "CC")

Dim i As Integer 'ExpSub
Dim j As Integer 'Post
For j = LBound(Post) To UBound(Post) 'j for Post
    For i = LBound(ExpSub) To UBound(ExpSub)  'i for ExpSub
        Dim sheetname As String
        sheetname = "Staging " & Post(j) & " " & ExpSub(i)
        Debug.Print sheetname

        With ThisWorkbook.Sheets(sheetname)
            Dim r As Range
            Set r = .Range("A4").Resize(100, 1)
            r.ClearContents
        End With
    Next i
Next j
</code>```

The code assumes that the sheets are in the same Workbook as your code (ThisWorkbook), else you need to change that.

If you like loooong statements, instead of the With-Block you can write a single line. Personally, I hate such long statements as they are hard to read and if they fail, you don't know which part caused the fail.

```<code>ThisWorkbook.Sheets(sheetname).Range("A4").Resize(100, 1).ClearContents
</code>```

Body:
Caveat: my VBA knowledge is self-taught via Googling so please be patient with me!
I have a set of worksheets and am trying to perform the same set of actions through each sheet. Having problem with my codes:
E.g. worksheets are "Staging AA 101", "Staging AA 102", "Staging AA 201", "Staging BB 101", "Staging BB 102", "Staging BB 201", "Staging CC 101", "Staging CC 102", "Staging CC 201"

My codes are:

Dim ExpSub(1 To 3) As String
Dim Post(1 To 3) As String
Dim i As Integer 'ExpSub
Dim j As Integer 'Post

ExpSub(1) = "101"
ExpSub(2) = "102"
ExpSub(3) = "201"
Post(1) = "AA"
Post(2) = "BB"
Post(3) = "CC"

For j = 1 To 3 'j for Post
For i = 1 To 3 'i for ExpSub
    Sheets("Staging " & Post(j) & " " & ExpSub(i)).Select
    Range("AK4").Select
    Range(Selection, Selection.Offset(100, 1)).Select
    Selection.ClearContents
Next i
Next j

Errored out at this line
Sheets("Staging " & Post(j) & " " & ExpSub(i)).Select

How do i loop through all the sheets with such variables please? Thanks in advance!

Body:
Your loops work as expected. You should write the result of your string concatenation into an intermediate variable and check with the debugger.

I can think of two reasons why your code fails:

a) One of your sheets is missing or has a typo in its name (maybe an extra space character). Check with the debugger for which sheet your code fails.

b) You don't specify the Workbook you want to work with, so VBA will look for the sheets in the Active Workbook - maybe this is a different workbook.

Beside this: You don't need to Select a sheet or a range to work with them, and it fact this should be avoided because it makes your code slow and is an open gate for bugs. You should take the time and read How to avoid using Select in Excel VBA.

Your code could look like

Dim ExpSub() As Variant, Post As Variant
ExpSub = Array("101", "102", "201")
Post = Array("AA", "BB", "CC")

Dim i As Integer 'ExpSub
Dim j As Integer 'Post
For j = LBound(Post) To UBound(Post) 'j for Post
    For i = LBound(ExpSub) To UBound(ExpSub)  'i for ExpSub
        Dim sheetname As String
        sheetname = "Staging " & Post(j) & " " & ExpSub(i)
        Debug.Print sheetname

        With ThisWorkbook.Sheets(sheetname)
            Dim r As Range
            Set r = .Range("A4").Resize(100, 1)
            r.ClearContents
        End With
    Next i
Next j

The code assumes that the sheets are in the same Workbook as your code (ThisWorkbook), else you need to change that.

If you like loooong statements, instead of the With-Block you can write a single line. Personally, I hate such long statements as they are hard to read and if they fail, you don't know which part caused the fail.

ThisWorkbook.Sheets(sheetname).Range("A4").Resize(100, 1).ClearContents


问:
Support for password authentication was removed on August 13, 2021. Please use a personal access token instead
Even though I create a PET in GitHub, and I set it in Sourcetree, it does get user, or updated.

Cloning a repo will result the same issue. Why? Should I remove the cache, or what?

答:
Found here answer:

https://community.atlassian.com/t5/Sourcetree-questions/Sourcetree-ignores-github-token-and-throws-403-error/qaq-p/1778978

pen sourcetree, in the right click icon Settings (Repository settings) ->Remotes -> Select Origin and Edit:
Set URL/Path in the following format:  https://<token>@<git_url>.git


问:
Count occurrences of list of values in column using PySpark DataFrame
I have a PySpark DataFrame with a string column text and a separate list word_list and I need to count how many of the word_list values appear in each text row (can be counted more than once).

```<code>df = spark.createDataFrame(
  [(1,'Hello my name is John'),
   (2,'Yo go Bengals'),
   (3,'this is a text')
  ]
  , ['id','text']
)

word_list = ['is', 'm', 'o', 'my']
</code>```

The result would be:

| text                  | list_count   |
| Hello my name is John |       6      |
| Yo go Bengals         |       2      |
| this is a text        |       2      |
```

For text's first value, "is" occurs once, "m" occurs twice, "o" occurs twice, and "my" occurs once. In the second row, the only value from word_list that appears is "o" and it appears twice. In the third value for text, the only value from word_list that appears is "is" and it appears twice.

The result doesn't necessarily have to be PySpark-based either, it could be in Pandas if that's easier.

答:
To count number of occurrences of a substring in string column, you can split that column by the substring. The count corresponds to the size of resulting array minus 1.

So in your case, you can use aggregate function on the word_list array column and for each element, split the text column and get the size - 1:

```<code>from pyspark.sql import functions as F

result = df.withColumn(
    "word_list",
    F.array(*[F.lit(x) for x in word_list])
).withColumn(
    "list_count",
    F.expr("aggregate(word_list, 0, (acc, x) -> acc + size(split(text, x)) -1)")
).drop("word_list")

result.show(truncate=False)
#+---+---------------------+----------+
#|id |text                 |list_count|
#+---+---------------------+----------+
#|1  |Hello my name is John|6         |
#|2  |Yo go Bengals        |2         |
#|3  |this is a text       |2         |
#+---+---------------------+----------+
</code>```

Body:
I have a PySpark DataFrame with a string column text and a separate list word_list and I need to count how many of the word_list values appear in each text row (can be counted more than once).

df = spark.createDataFrame(
  [(1,'Hello my name is John'),
   (2,'Yo go Bengals'),
   (3,'this is a text')
  ]
  , ['id','text']
)

word_list = ['is', 'm', 'o', 'my']

The result would be:

| text                  | list_count   |
| Hello my name is John |       6      |
| Yo go Bengals         |       2      |
| this is a text        |       2      |

For text's first value, "is" occurs once, "m" occurs twice, "o" occurs twice, and "my" occurs once. In the second row, the only value from word_list that appears is "o" and it appears twice. In the third value for text, the only value from word_list that appears is "is" and it appears twice.

The result doesn't necessarily have to be PySpark-based either, it could be in Pandas if that's easier.

Body:
To count number of occurrences of a substring in string column, you can split that column by the substring. The count corresponds to the size of resulting array minus 1.

So in your case, you can use aggregate function on the word_list array column and for each element, split the text column and get the size - 1:

from pyspark.sql import functions as F

result = df.withColumn(
    "word_list",
    F.array(*[F.lit(x) for x in word_list])
).withColumn(
    "list_count",
    F.expr("aggregate(word_list, 0, (acc, x) -> acc + size(split(text, x)) -1)")
).drop("word_list")

result.show(truncate=False)
#+---+---------------------+----------+
#|id |text                 |list_count|
#+---+---------------------+----------+
#|1  |Hello my name is John|6         |
#|2  |Yo go Bengals        |2         |
#|3  |this is a text       |2         |
#+---+---------------------+----------+


问:
To unpack a zip file from url request
I want to get this XML file from a danish website with the URL https://www.foedevarestyrelsen.dk/_layouts/15/sdata/smileystatus.zip, but the data comes in a zip file. This is problematic because I want to get the data sheet directly into Python for a school project, and not to save it local and convert it into csv. So far I have tried following codes inspired from answers to previous questions about this subject....

```<code>from zipfile import ZipFile
from io import BytesIO
import requests
import pandas as pd

def get_zip(file_url):
    url = requests.get(file_url)
    zipfile = ZipFile(BytesIO(url.content))
    zip_names = zipfile.namelist()
    if len(zip_names) == 1:
        SmileyStatus = zip_names.pop()
        extracted_file = zipfile.open("SmileyStatus.xls")
        return extracted_file

xls = get_zip("https://www.foedevarestyrelsen.dk/_layouts/15/sdata/smileystatus.zip")

data = pd.read_excel(xls)
</code>```

and I have also tried:

```<code>from zipfile import ZipFile
import requests
import pandas as pd

url = 'https://www.foedevarestyrelsen.dk/_layouts/15/sdata/smileystatus.zip'
df = pd.read_csv(url,
                 compression = "zip")
</code>```

答:
Know its an old post, but I just had a similar need and found a good solution.

import pandas as pd

import io

import requests

url = 'https://whatever.website/some_file.zip'

r = requests.get(url)

df = pd.read_csv(io.BytesIO(r.content), compression="zip")

print(df.head())

print(f"{len(df)} rows")

Title: To unpack a zip file from url request

Body:
I want to get this XML file from a danish website with the URL https://www.foedevarestyrelsen.dk/_layouts/15/sdata/smileystatus.zip, but the data comes in a zip file. This is problematic because I want to get the data sheet directly into Python for a school project, and not to save it local and convert it into csv. So far I have tried following codes inspired from answers to previous questions about this subject....

from zipfile import ZipFile
from io import BytesIO
import requests
import pandas as pd

def get_zip(file_url):
    url = requests.get(file_url)
    zipfile = ZipFile(BytesIO(url.content))
    zip_names = zipfile.namelist()
    if len(zip_names) == 1:
        SmileyStatus = zip_names.pop()
        extracted_file = zipfile.open("SmileyStatus.xls")
        return extracted_file

xls = get_zip("https://www.foedevarestyrelsen.dk/_layouts/15/sdata/smileystatus.zip")

data = pd.read_excel(xls)

and I have also tried:

from zipfile import ZipFile
import requests
import pandas as pd

url = 'https://www.foedevarestyrelsen.dk/_layouts/15/sdata/smileystatus.zip'
df = pd.read_csv(url,
                 compression = "zip")


问:
How does this while loop exit?
So, how does this code exit the while statement when the thread is started? (Please do not consider indentation)

```<code>class ThreadUrl(threading.Thread):
    """Threaded Url Grab"""
    def __init__(self, queue, out_queue):
        threading.Thread.__init__(self)
        self.queue = queue
        self.out_queue = out_queue

    def run(self):
        while True:
            #grabs host from queue
            host = self.queue.get()

            #grabs urls of hosts and then grabs chunk of webpage
            url = urllib2.urlopen(host)
            chunk = url.read()

            #place chunk into out queue
            self.out_queue.put(chunk)

            #signals to queue job is done
            self.queue.task_done()
</code>```

** EDIT *

The code that starts the thread:

```<code>def main():

#spawn a pool of threads, and pass them queue instance
    for i in range(5):
        t = ThreadUrl(queue)
        t.setDaemon(True)
        t.start()

    queue.join()
</code>```

答:
It doesn't have to exit the while statement for the code to terminate. All that is happening here is that the thread has consumed everything in the queue at which point queue.join() returns.

As soon as the call to queue.join() in the main code returns the main code will exit and because you marked the thread as a daemon the entire application will exit and your background thread will be killed.

Title: How does this while loop exit?

Body:
So, how does this code exit the while statement when the thread is started? (Please do not consider indentation)

class ThreadUrl(threading.Thread):
    """Threaded Url Grab"""
    def __init__(self, queue, out_queue):
        threading.Thread.__init__(self)
        self.queue = queue
        self.out_queue = out_queue

    def run(self):
        while True:
            #grabs host from queue
            host = self.queue.get()

            #grabs urls of hosts and then grabs chunk of webpage
            url = urllib2.urlopen(host)
            chunk = url.read()

            #place chunk into out queue
            self.out_queue.put(chunk)

            #signals to queue job is done
            self.queue.task_done()

** EDIT *

The code that starts the thread:

def main():

#spawn a pool of threads, and pass them queue instance
    for i in range(5):
        t = ThreadUrl(queue)
        t.setDaemon(True)
        t.start()

    queue.join()


问:
How to use System.Text.Encoding.GetEncoding("") function for other charset than 8 supported in C# - .Net Core?
I am trying to use an encoding page that is not in the common initialized encoding pages in C#.

```<code>var greekEncoding = System.Text.Encoding.GetEncoding("1253");
using (var httpClient = new HttpClient())
        {
            var httpContent = new StringContent(xmlString, greekEncoding, "text/xml");
            return await httpClient.PostAsync(baseUrl, httpContent);
        }
</code>```

System.Text.Encoding has a function GetEncoding("iso-8859-7") or GetEncodings() which returns all the possible encoding pages.

When I try to retrieve a encoding page such as "ISO-8859-7" or "Windows-1253" the Encoding Pages are not registered by default and the result is unrecognizable characters.

How can I register ALL Code Pages in my dotnet core Solution  ?

答:
After a lot of days of searching I found in .net-core, we have to insert a registration in the Encoding.

The Solution in this problem is to Register a provider in the Encoding Class.

```<code>EncodingProvider provider = CodePagesEncodingProvider.Instance;
Encoding.RegisterProvider(provider);
</code>```

Just put this two lines in Startup.cs or Program.cs or Main.cs and your solution will have registered provider to use all charsets that is not common.

Common Encoding Pages :

UTF7

UTF8

UTF32

Unicode

UTF-16BE (BigEndianUnicode)

ASCII

Latin1

Default (Computer encoding page)

The solution has been explained in this web page (https://learn.microsoft.com/en-us/dotnet/api/system.text.codepagesencodingprovider?view=net-6.0#remarks) without example.

This misunderstanding appeared in dotnet core.

Body:
I am trying to use an encoding page that is not in the common initialized encoding pages in C#.

var greekEncoding = System.Text.Encoding.GetEncoding("1253");
using (var httpClient = new HttpClient())
        {
            var httpContent = new StringContent(xmlString, greekEncoding, "text/xml");
            return await httpClient.PostAsync(baseUrl, httpContent);
        }

System.Text.Encoding has a function GetEncoding("iso-8859-7") or GetEncodings() which returns all the possible encoding pages.

When I try to retrieve a encoding page such as "ISO-8859-7" or "Windows-1253" the Encoding Pages are not registered by default and the result is unrecognizable characters.

How can I register ALL Code Pages in my dotnet core Solution  ?

Body:
After a lot of days of searching I found in .net-core, we have to insert a registration in the Encoding.

The Solution in this problem is to Register a provider in the Encoding Class.

EncodingProvider provider = CodePagesEncodingProvider.Instance;
Encoding.RegisterProvider(provider);

Just put this two lines in Startup.cs or Program.cs or Main.cs and your solution will have registered provider to use all charsets that is not common.

Common Encoding Pages :

UTF7

UTF8

UTF32

Unicode

UTF-16BE (BigEndianUnicode)

ASCII

Latin1

Default (Computer encoding page)

The solution has been explained in this web page (https://learn.microsoft.com/en-us/dotnet/api/system.text.codepagesencodingprovider?view=net-6.0#remarks) without example.

This misunderstanding appeared in dotnet core.


问:
HTML .gitignore
I currently have my api keys and list id sitting in my app.js file. I am trying to add those API keys to another file and hide the file using .gitignore. But how do I do that and even if I hide the file in the new secret file how do I get those keys back in my original app.js file</p>

答:
Using .env file

Install the dotenv npm package

npm install dotenv --save

Create a .env file at the root of your project and store your SECRET_KEY like shown below.

SECRET_KEY="YOURSECRETKEYGOESHERE"

To get the value from the key use the following code

require('dotenv').config()

console.log(process.env)

For more information do check the link.

Using .gitignore file
.gitignore file is used to add those files which you don't want to commit to your git repository. In this case, you can create a file called.gitignore and in that file add the file names which should not be committed.

.gitignore

```<code>.DS_Store
secrets.txt
.env

#This is comments(# used for comments)

*.txt  #this means all files with .txt extention will be ignored
</code>```

To get the prebuild template for .gitignore files for nodeJs or any kind of project do check the repository down below.

https://github.com/github/gitignore

Title: HTML .gitignore

Body:
Using .env file

Install the dotenv npm package

npm install dotenv --save

Create a .env file at the root of your project and store your SECRET_KEY like shown below.

SECRET_KEY="YOURSECRETKEYGOESHERE"

To get the value from the key use the following code

require('dotenv').config()

console.log(process.env)

For more information do check the link.

Using .gitignore file
.gitignore file is used to add those files which you don't want to commit to your git repository. In this case, you can create a file called.gitignore and in that file add the file names which should not be committed.

.gitignore

.DS_Store
secrets.txt
.env

#This is comments(# used for comments)

*.txt  #this means all files with .txt extention will be ignored

To get the prebuild template for .gitignore files for nodeJs or any kind of project do check the repository down below.

https://github.com/github/gitignore


问:
How to fix this problem? Login if statement not working
This is my views.py

```<code>def user_login(request):
   if request.method == "POST":
    username = request.POST.get('username')
    password = request.POST.get('password')
    user = authenticate(username=username, password=password)
    if user:
        if user.is_active:
            login(request, user)
            return HttpResponseRedirect(reverse('index'))
        else:
            return HttpResponse("Your account is Inactive.")
    else:
        return HttpResponse("Invalid User Credentials Provided!!!!")
else:
    return render(request, "MyTestApp/login.html", {})
</code>```

And this is my login page:

```<code><div class="container">
<div class="jumbotron">
    <h2 class="text-dark"> Login </h2>
    <form method="post" action="{ url 'MyTestApp:user_login '}">
        {%csrf_token%}
        <label for="username"> Username </label>
        <input type="text" name="username" placeholder=" Write Your UserName Here"> <br></br>

        <label for="password"> Password </label>
        <input type="text" name="password" placeholder=" Write Your Password Here"> <br></br>

        <input  type="submit" class="btn btn-dark" name="savebutton" value="login">
    </form>
</div>
</code>```

When I try to login it works. If I try to login with a unregistered account then it doesn't allow me returns the message "Invalid User Credentials Provided", which is good. But When I try to login with a inactive account it still returns "Invalid User Credentials Provided". It doesn't return the message "Your account is Inactive.", which it should return when I login with a inactive account. Does anyone know why this is happening. Any help will be very much appreciated.

答:
As authenticate returns None if the account is inactive, you can't know if the account is inactive or the user does not exist. You have to check yourself the status of the user:

```<code>from django.shortcuts import render, reverse
from django.contrib.auth import login, get_user_model
from django.http import HttpResponse, HttpResponseRedirect

def user_login(request):
    if request.method == "POST":
        username = request.POST.get('username')
        password = request.POST.get('password')

        try:
            user_model = get_user_model()
            user = user_model.objects.get(username=username)
            if not user.is_active:
                return HttpResponse("Your account is Inactive.")

            if not user.check_password(password):
                return HttpResponse("Invalid User Credentials Provided!!!!")

            login(request, user)
            return HttpResponseRedirect(reverse('index'))
        except user_model.DoesNotExist:
            return HttpResponse("User does not exist!!!!")

    else:
        return render(request, "MyTestApp/login.html", {})
</code>```

Body:
This is my views.py

def user_login(request):
   if request.method == "POST":
    username = request.POST.get('username')
    password = request.POST.get('password')
    user = authenticate(username=username, password=password)
    if user:
        if user.is_active:
            login(request, user)
            return HttpResponseRedirect(reverse('index'))
        else:
            return HttpResponse("Your account is Inactive.")
    else:
        return HttpResponse("Invalid User Credentials Provided!!!!")
else:
    return render(request, "MyTestApp/login.html", {})

And this is my login page:

 Login

    <form method="post" action="{ url 'MyTestApp:user_login '}">
        {%csrf_token%}
         Username
        <input type="text" name="username" placeholder=" Write Your UserName Here">

         Password
        <input type="text" name="password" placeholder=" Write Your Password Here">

        <input  type="submit" class="btn btn-dark" name="savebutton" value="login">
    </form>

When I try to login it works. If I try to login with a unregistered account then it doesn't allow me returns the message "Invalid User Credentials Provided", which is good. But When I try to login with a inactive account it still returns "Invalid User Credentials Provided". It doesn't return the message "Your account is Inactive.", which it should return when I login with a inactive account. Does anyone know why this is happening. Any help will be very much appreciated.

Body:
As authenticate returns None if the account is inactive, you can't know if the account is inactive or the user does not exist. You have to check yourself the status of the user:

from django.shortcuts import render, reverse
from django.contrib.auth import login, get_user_model
from django.http import HttpResponse, HttpResponseRedirect

def user_login(request):
    if request.method == "POST":
        username = request.POST.get('username')
        password = request.POST.get('password')

        try:
            user_model = get_user_model()
            user = user_model.objects.get(username=username)
            if not user.is_active:
                return HttpResponse("Your account is Inactive.")

            if not user.check_password(password):
                return HttpResponse("Invalid User Credentials Provided!!!!")

            login(request, user)
            return HttpResponseRedirect(reverse('index'))
        except user_model.DoesNotExist:
            return HttpResponse("User does not exist!!!!")

    else:
        return render(request, "MyTestApp/login.html", {})


问:
Vertical alignment of Label inside TextBlock is wrong
In a WPF popup window that I display to the user I want to put a text that is bound to a variable inside a block of text.
I've tried to do so by putting a  inside a <TextBlock>.
However, this leads to alignment problems, see markup and picture below.
I wonder how I can get the text in the Label to align vertically with the text in the TextBlock, or if there is a better solution?

I could put the entire text in a variable, but then I don't know how to get <Bold> formatting for part of the text.

```<code><TextBlock HorizontalAlignment="Left" TextWrapping="Wrap"
 VerticalAlignment="Top" Height="99" Width="339" Grid.RowSpan="3">
    The user is <Bold>responsible</Bold> for
    <Bold><Label Content="00" Padding="0"/></Bold> vehicles
</TextBlock>
</code>```

答:
You can use the Run inline element for data binding text.

Starting in the .NET Framework 4, the Text property of the Run object is a dependency property, which means that you can bind the Text property to a data source.

It also has properties for styling the text, like FontWeight, no need for <Bold> here.

```<code><TextBlock HorizontalAlignment="Left" TextWrapping="Wrap"
 VerticalAlignment="Top" Height="99" Width="339" Grid.RowSpan="3">
    The user is <Bold>responsible</Bold> for
    <Run Text="{Binding YourProperty}" FontWeight="Bold"/> vehicles
</TextBlock>
</code>```

The result looks like this:

As a general note on the issue: The elements inside TextBlock should be inline elements. Here is an article that has links to other inline elements that could be useful to you, like span that allows for grouping other inline elements and applying styles or to them.

How to: Manipulate Flow Content Elements through the Inlines Property

WPF has two fundamental base types, UIElement and ContentElement. While a TextBlock and Label are UIElements, the content of TextBlock are inlines, which are ContentElements. That is why the alignment is off, they serve very different purposes. You can read up more on the differences and concepts here:

Base Element APIs in WPF Classes

UIElement

UIElement is a base class for WPF core level implementations building on Windows Presentation Foundation (WPF) elements and basic presentation characteristics.

ContentElement

Provides a WPF core-level base class for content elements. Content elements are designed for flow-style presentation, using an intuitive markup-oriented layout model and a deliberately simple object model.

Flow Document Overview

Body:
In a WPF popup window that I display to the user I want to put a text that is bound to a variable inside a block of text.
I've tried to do so by putting a  inside a <TextBlock>.
However, this leads to alignment problems, see markup and picture below.
I wonder how I can get the text in the Label to align vertically with the text in the TextBlock, or if there is a better solution?

I could put the entire text in a variable, but then I don't know how to get <Bold> formatting for part of the text.

<TextBlock HorizontalAlignment="Left" TextWrapping="Wrap"
 VerticalAlignment="Top" Height="99" Width="339" Grid.RowSpan="3">
    The user is <Bold>responsible</Bold> for
    <Bold></Bold> vehicles
</TextBlock>

Body:
You can use the Run inline element for data binding text.

Starting in the .NET Framework 4, the Text property of the Run object is a dependency property, which means that you can bind the Text property to a data source.

It also has properties for styling the text, like FontWeight, no need for <Bold> here.

<TextBlock HorizontalAlignment="Left" TextWrapping="Wrap"
 VerticalAlignment="Top" Height="99" Width="339" Grid.RowSpan="3">
    The user is <Bold>responsible</Bold> for
    <Run Text="{Binding YourProperty}" FontWeight="Bold"/> vehicles
</TextBlock>

The result looks like this:

As a general note on the issue: The elements inside TextBlock should be inline elements. Here is an article that has links to other inline elements that could be useful to you, like span that allows for grouping other inline elements and applying styles or to them.

How to: Manipulate Flow Content Elements through the Inlines Property

WPF has two fundamental base types, UIElement and ContentElement. While a TextBlock and Label are UIElements, the content of TextBlock are inlines, which are ContentElements. That is why the alignment is off, they serve very different purposes. You can read up more on the differences and concepts here:

Base Element APIs in WPF Classes

UIElement

UIElement is a base class for WPF core level implementations building on Windows Presentation Foundation (WPF) elements and basic presentation characteristics.

ContentElement

Provides a WPF core-level base class for content elements. Content elements are designed for flow-style presentation, using an intuitive markup-oriented layout model and a deliberately simple object model.

Flow Document Overview


问:
Access Control in Elastic - missing authentication credentials for REST request
I am using Elastic 7.9.2 version and wanted to use security.
so I ran :

```<code>bin/elasticsearch-certutil cert -out config/elastic-certificates.p12 -pass ""
</code>```

and then added

```<code>xpack.security.enabled: true
xpack.security.transport.ssl.enabled: true
xpack.security.transport.ssl.verification_mode: certificate
xpack.security.transport.ssl.keystore.path: elastic-certificates.p12
xpack.security.transport.ssl.truststore.path: elastic-certificates.p1
</code>```

in config/elasticsearch.yaml

Now when I am running the ES by

```<code> bin/elasticsearch
</code>```

getting below error :

```<code>"error":{"root_cause":[{"type":"security_exception","reason":"missing authentication credentials
 for REST request [/]","header":{"WWW-Authenticate":"Basic realm=\"security\" charset=\"UTF-
8\""}}],"type":"security_exception","reason":"missing authentication credentials for REST
request [/]","header":{"WWW-Authenticate":"Basic realm=\"security\" charset=\"UTF-
8\""}},"status":401}root@ip-localhost:/var/log/elasticsearch
</code>```

Can anyone please help!

答:
Just pass authentication credential with url like below</p>
```<code>curl -X GET "http://localhost:9200" -u elastic:pass123
</code>```

Body:
I am using Elastic 7.9.2 version and wanted to use security.
so I ran :

bin/elasticsearch-certutil cert -out config/elastic-certificates.p12 -pass ""

and then added

xpack.security.enabled: true
xpack.security.transport.ssl.enabled: true
xpack.security.transport.ssl.verification_mode: certificate
xpack.security.transport.ssl.keystore.path: elastic-certificates.p12
xpack.security.transport.ssl.truststore.path: elastic-certificates.p1

in config/elasticsearch.yaml

Now when I am running the ES by

 bin/elasticsearch

getting below error :

"error":{"root_cause":[{"type":"security_exception","reason":"missing authentication credentials
 for REST request [/]","header":{"WWW-Authenticate":"Basic realm=\"security\" charset=\"UTF-
8\""}}],"type":"security_exception","reason":"missing authentication credentials for REST
request [/]","header":{"WWW-Authenticate":"Basic realm=\"security\" charset=\"UTF-
8\""}},"status":401}root@ip-localhost:/var/log/elasticsearch

Can anyone please help!

Body:
Just pass authentication credential with url like below

curl -X GET "http://localhost:9200" -u elastic:pass123


问:
slick carousel individual slide duration
Looking for a way to use slick carousel and be able to change the amount of time the slide is displayed on an individual slide basis.

In case I'm not explaining it well, assume I have 5 slides.  I want to be able to define the display of slide one for 5s, slide 2 for 10s, slide 3 for 7s, etc...

ref: http://kenwheeler.github.io/slick/

答:
I fixed the above code https://stackoverflow.com/a/45593522/2931874
The problems that were fixed are Prev slide had the wrong time, because the code just set the next slide for the duration.
And Important correction was clearInterval, all was worked correctly until we change the slide with swipe or arrow. so i removed the prev interval.

```<code>let intervalId = 0;
    if ($slider.length > 0) {
        $slider.slick({
            slidesToShow: 1,
            slidesToScroll: 1,
            dots: false,
            speed: 1000
        });

        var activeSlides,
            currActiveSlide,
            firstSlide = $slider.find("[data-slick-index='0']");

        $slider.on('beforeChange', function (event, slick, currentSlide, nextSlide) {
            currActiveSlide = slick.$slides.eq(nextSlide);
        });

        $slider.on('afterChange', function (event, slick) {
            clearInterval(intervalId);
            intervalId = setTimeout(function () {
                $slider.slick('slickNext');
            }, currActiveSlide.data('time') - 1000);
        });

        // on init
        intervalId = setTimeout(function () {
            $slider.slick('slickNext');
        }, firstSlide.data('time'));
    }
</code>```

Body:
I fixed the above code https://stackoverflow.com/a/45593522/2931874
The problems that were fixed are Prev slide had the wrong time, because the code just set the next slide for the duration.
And Important correction was clearInterval, all was worked correctly until we change the slide with swipe or arrow. so i removed the prev interval.

let intervalId = 0;
    if ($slider.length > 0) {
        $slider.slick({
            slidesToShow: 1,
            slidesToScroll: 1,
            dots: false,
            speed: 1000
        });

        var activeSlides,
            currActiveSlide,
            firstSlide = $slider.find("[data-slick-index='0']");

        $slider.on('beforeChange', function (event, slick, currentSlide, nextSlide) {
            currActiveSlide = slick.$slides.eq(nextSlide);
        });

        $slider.on('afterChange', function (event, slick) {
            clearInterval(intervalId);
            intervalId = setTimeout(function () {
                $slider.slick('slickNext');
            }, currActiveSlide.data('time') - 1000);
        });

        // on init
        intervalId = setTimeout(function () {
            $slider.slick('slickNext');
        }, firstSlide.data('time'));
    }


问:
Checking a remote host (Linux) hard disk space
I need to check the available hard disk space for a remote linux host in Python.

Currently i am using shutil to check the same on my host.

import shutil
total, used, free = shutil.disk_usage("D:/")

答:
Since I can't comment, here as answer:
If you are on a linux system you can use simply an os call, no need to include a new library.</p>
```<code>import os
stream = os.popen('ssh host@target "df -h"')
output = stream.read()
</code>```

Body:
Since I can't comment, here as answer:
If you are on a linux system you can use simply an os call, no need to include a new library.

import os
stream = os.popen('ssh host@target "df -h"')
output = stream.read()


问:
UITextView get the current line
Is there a way (crazy hacks welcome) to get the current line as a string of a UITextView? This would include word wrapping, etc. For example, in this case:

The method would return "stack overflow. Isn't it great? I" because that is the current line based on the cursor.

It could also return "This is a test I made for" or "think so", based on the position of the cursor. I have tried working with both the UITextView methods and those of UITextInput protocol.

EDIT:

Here is the code I have attempted to use. The reason I need to find the string is to get it's length, so this is why you'll see UI based code.

```<code>NSRange location = self.textView.selectedRange;
NSString *searchString = [self.textView.text substringWithRange:NSMakeRange(0, location)];
CGSize currentStringDimensions = [searchString sizeWithFont:self.textView.font constrainedToSize:CGSizeMake(self.textView.frame.size.width, self.textView.frame.size.height) lineBreakMode:NSLineBreakByWordWrapping];
float numberOfRows = (currentStringDimensions.width/(self.textView.frame.size.width));
float left = (float)(numberOfRows - (int)numberOfRows) * (self.textView.frame.size.width);
</code>```

This doesn't work, however. I think it might have something to with words being wrapped or the differently sized characters, but the left value is inconsistent or off after the first line.

答:
Swift 5 extension version of Gil's answer:</p>
```<code>extension UITextView {
    func getLineString() -> String {
        guard let text = text else { return "" }
        return (text as NSString).substring(with: (text as NSString).lineRange(for: self.selectedRange))
    }
}
</code>```

Title: UITextView get the current line

Body:
Is there a way (crazy hacks welcome) to get the current line as a string of a UITextView? This would include word wrapping, etc. For example, in this case:

The method would return "stack overflow. Isn't it great? I" because that is the current line based on the cursor.

It could also return "This is a test I made for" or "think so", based on the position of the cursor. I have tried working with both the UITextView methods and those of UITextInput protocol.

EDIT:

Here is the code I have attempted to use. The reason I need to find the string is to get it's length, so this is why you'll see UI based code.

NSRange location = self.textView.selectedRange;
NSString *searchString = [self.textView.text substringWithRange:NSMakeRange(0, location)];
CGSize currentStringDimensions = [searchString sizeWithFont:self.textView.font constrainedToSize:CGSizeMake(self.textView.frame.size.width, self.textView.frame.size.height) lineBreakMode:NSLineBreakByWordWrapping];
float numberOfRows = (currentStringDimensions.width/(self.textView.frame.size.width));
float left = (float)(numberOfRows - (int)numberOfRows) * (self.textView.frame.size.width);

This doesn't work, however. I think it might have something to with words being wrapped or the differently sized characters, but the left value is inconsistent or off after the first line.

Body:
Swift 5 extension version of Gil's answer:

extension UITextView {
    func getLineString() -> String {
        guard let text = text else { return "" }
        return (text as NSString).substring(with: (text as NSString).lineRange(for: self.selectedRange))
    }
}


问:
How do I extend a class definition that's missing types from DefinitelyTyped?
I want to use the Driver instance method setNetworkConditions from selenium-webdriver, which is available in the source.

DefinitelyTyped is currently missing the types for this function. In fact, all it has is this:

export class Driver extends webdriver.WebDriver {
  /**
   * Creates a new session with the ChromeDriver.
   *
   * @param {(Capabilities|Options)=} opt_config The configuration options.
   * @param {(remote.DriverService|http.Executor)=} opt_serviceExecutor Either
   *     a  DriverService to use for the remote end, or a preconfigured executor
   *     for an externally managed endpoint. If neither is provided, the
   *     {@linkplain ##getDefaultService default service} will be used by
   *     default.
   * @return {!Driver} A new driver instance.
   */
  static createSession(
      opt_config?: Options|webdriver.CreateSessionCapabilities,
      opt_service?: remote.DriverService|http.Executor): Driver;
}
```
<p>I want to extend this definition within my <code>ambient.d.ts</code> file, which I have successfully used for projects that do not have any TS definitions at all.</p>
<p>Now, how go about doing this? I have tried adding this:</p>
<pre class="lang-js prettyprint-override"><code>declare module 'selenium-webdriver/chrome' {
  class Driver {
    setNetworkConditions(spec: {});
  }
}
</code>```

But as soon as I add this, all other function type definitions from the Driver class that it inherits from webdriver.WebDriver appear as missing.

I have seen this question but it does not seem to match the use case of extending existing definitions.

How could I merge the definitions, or extend them, without having to copy-paste the DefinitelyTyped definitions for webdriver.WebDriver?

答:
Here's a rather dirty workaround. I have to create a completely new interface:

```<code>export interface ChromeDriverNetworkConditionsSpec {
  offline?: boolean;
  latency: number;
  download_throughput: number; // in Bit/s
  upload_throughput: number; // in Bit/s
}

export interface DriverWithNetworkOptions {
  getNetworkConditions(): Promise<ChromeDriverNetworkConditionsSpec>;
  setNetworkConditions(spec: ChromeDriverNetworkConditionsSpec): Promise<void>;
}
</code>```

Then, use it like so:

```<code>const driver = // create webdriver as usual
await (driver as unknown as DriverWithNetworkOptions).setNetworkConditions({
  // ...
});
</code>```

This will mask all other properties, but if you only use it in one place, that can be managed, e.g. by abstracting it away in another function.

Body:
I want to use the Driver instance method setNetworkConditions from selenium-webdriver, which is available in the source.

DefinitelyTyped is currently missing the types for this function. In fact, all it has is this:

export class Driver extends webdriver.WebDriver {
  /**
   * Creates a new session with the ChromeDriver.
   *
   * @param {(Capabilities|Options)=} opt_config The configuration options.
   * @param {(remote.DriverService|http.Executor)=} opt_serviceExecutor Either
   *     a  DriverService to use for the remote end, or a preconfigured executor
   *     for an externally managed endpoint. If neither is provided, the
   *     {@linkplain ##getDefaultService default service} will be used by
   *     default.
   * @return {!Driver} A new driver instance.
   */
  static createSession(
      opt_config?: Options|webdriver.CreateSessionCapabilities,
      opt_service?: remote.DriverService|http.Executor): Driver;
}

I want to extend this definition within my ambient.d.ts file, which I have successfully used for projects that do not have any TS definitions at all.

Now, how go about doing this? I have tried adding this:

declare module 'selenium-webdriver/chrome' {
  class Driver {
    setNetworkConditions(spec: {});
  }
}

But as soon as I add this, all other function type definitions from the Driver class that it inherits from webdriver.WebDriver appear as missing.

I have seen this question but it does not seem to match the use case of extending existing definitions.

How could I merge the definitions, or extend them, without having to copy-paste the DefinitelyTyped definitions for webdriver.WebDriver?

Body:
Here's a rather dirty workaround. I have to create a completely new interface:

export interface ChromeDriverNetworkConditionsSpec {
  offline?: boolean;
  latency: number;
  download_throughput: number; // in Bit/s
  upload_throughput: number; // in Bit/s
}

export interface DriverWithNetworkOptions {
  getNetworkConditions(): Promise<ChromeDriverNetworkConditionsSpec>;
  setNetworkConditions(spec: ChromeDriverNetworkConditionsSpec): Promise<void>;
}

Then, use it like so:

const driver = // create webdriver as usual
await (driver as unknown as DriverWithNetworkOptions).setNetworkConditions({
  // ...
});

This will mask all other properties, but if you only use it in one place, that can be managed, e.g. by abstracting it away in another function.