问:
SwiftUI static List weird reuse behavior
I'm facing a strange behavior using a static List in SwiftUI. I can't determine if it's a SwiftUI bug or something I'm doing wrong. I have a very simple List that looks like this :

var body: some View {
    List {
        SettingsPickerView<TrigonometryUnit>(title: "Trigonometry Units", selection: $viewModel.trigonometryUnitIndex, items: TrigonometryUnit.allCases)
        SettingsPickerView<DecimalSeparator>(title: "Decimal Separator", selection: $viewModel.decimalSeparatorIndex, items: DecimalSeparator.allCases)
        SettingsPickerView<GroupingSeparator>(title: "Grouping Separator", selection: $viewModel.groupingSeparatorIndex, items: GroupingSeparator.allCases)
        SettingsPickerView<ExponentSymbol>(title: "Exponent Symbol", selection: $viewModel.exponentSymbolIndex, items: ExponentSymbol.allCases)
    }
}
```

<p>Each cell of the List looks like this :</p>

<pre class="lang-swift prettyprint-override"><code>struct SettingsPickerView<T: Segmentable>: View {

    let title: String
    @Binding var selection: Int
    let items: [T]

    var body: some View {
        Section(header: Text(title)) {
            ForEach(items.indices) { index in
                self.cell(for: self.items[index], index: index)
            }
        }
    }

    private func cell(for item: T, index: Int) -> some View {
        print(title, item.title, items.map({ $0.title }))
        return Button(action: {
            self.selection = index
        }, label: {
            HStack {
                Text(item.title)
                Spacer()
                if index == self.selection {
                    Image(systemName: "checkmark")
                        .font(.headline)
                        .foregroundColor(.rpnCalculatorOrange)
                }
            }
        })
    }

}
</code>```

And finally, this is what a Segmentable object looks like:

enum GroupingSeparator: Int, CaseIterable {

    case defaultSeparator
    case space
    case comma

}

extension GroupingSeparator: Segmentable {

    var id: String {
        switch self {
        case .defaultSeparator:
            return "groupingSeparator.default"
        case .space:
            return "groupingSeparator.space"
        case .comma:
            return "groupingSeparator.comma"
        }
    }

    var title: String {
        switch self {
        case .defaultSeparator:
            return "Default"
        case .space:
            return "Space"
        case .comma:
            return "Comma"
        }
    }

}
```

<p>When the <code>SettingsView</code> is loaded. everything looks fine. But as soon as I start scrolling, and some other cells are instantiated, there are some cell displayed, but not the proper ones. Here is some screenshots and logs.</p>

<p>When the view is loaded, no scrolling, here is what the screen looks like:</p>

<p><img src="https://i.stack.imgur.com/xnohK.png" alt="enter image description here"></p>

<p>But, what I got on the console is pretty weird and doesn't follow the order of the <code>SettingsPickerView</code> written in the main View:</p>

```Trigonometry Units Radians ["Radians", "Degrees"] <-- Fine
Trigonometry Units Degrees ["Radians", "Degrees"] <-- Fine
Decimal Separator Default ["Default", "Dot", "Comma"] <-- Fine
Decimal Separator Default ["Default", "Dot", "Comma"] <-- Fine
Trigonometry Units Degrees ["Radians", "Degrees"] <-- Not expected. Should be Grouping Separator
Trigonometry Units Radians ["Radians", "Degrees"] <-- Not expected. Should be Grouping Separator
```

<p>The second section is ok and properly displayed:</p>

<p><img src="https://i.stack.imgur.com/Fps02.png" alt="enter image description here"></p>

<p>But the third section is completely broken:</p>

<p><img src="https://i.stack.imgur.com/9Myi9.png" alt="enter image description here"></p>

<p>The third section displays its title properly, but display some of the data of the first section. I tried to add an identifier to the button in the cell because the issue looks like SwiftUI can't identify the proper data. But adding an identifier to the button broke the binding, and the checkbox don't change anymore.</p>

<pre class="lang-swift prettyprint-override"><code>private func cell(for item: T, index: Int) -> some View {
    print(title, item.title, items.map({ $0.title }))
    return Button(action: {
        self.selection = index
    }, label: {
        HStack {
            Text(item.title)
            Spacer()
            if index == self.selection {
                Image(systemName: "checkmark")
                    .font(.headline)
                    .foregroundColor(.rpnCalculatorOrange)
            }
        }
    })
        .id(UUID().uuidString) // This solve the display issue but broke the binding.
}
</code>```

Does someone experienced something like this before ?

Thanks in advance for your help.

答:
Here is fixed block of code (due to used indexes only List is confused and reuses rows, so solution is to make rows identifiable by items).

Tested with Xcode 11.4

```<code>struct PickerView<T: Segmentable>: View {

    // ... other code here

    var body: some View {
        Section(header: Text(title)) {
            // Corrected section construction !!
            ForEach(Array(items.enumerated()), id: \.element.id) { index, _ in
                self.cell(for: self.items[index], index: index)
            }
        }
    }

    // ... other code here
</code>```

Body:
I'm facing a strange behavior using a static List in SwiftUI. I can't determine if it's a SwiftUI bug or something I'm doing wrong. I have a very simple List that looks like this :

var body: some View {
    List {
        SettingsPickerView<TrigonometryUnit>(title: "Trigonometry Units", selection: $viewModel.trigonometryUnitIndex, items: TrigonometryUnit.allCases)
        SettingsPickerView<DecimalSeparator>(title: "Decimal Separator", selection: $viewModel.decimalSeparatorIndex, items: DecimalSeparator.allCases)
        SettingsPickerView<GroupingSeparator>(title: "Grouping Separator", selection: $viewModel.groupingSeparatorIndex, items: GroupingSeparator.allCases)
        SettingsPickerView<ExponentSymbol>(title: "Exponent Symbol", selection: $viewModel.exponentSymbolIndex, items: ExponentSymbol.allCases)
    }
}

Each cell of the List looks like this :

struct SettingsPickerView<T: Segmentable>: View {

    let title: String
    @Binding var selection: Int
    let items: [T]

    var body: some View {
        Section(header: Text(title)) {
            ForEach(items.indices) { index in
                self.cell(for: self.items[index], index: index)
            }
        }
    }

    private func cell(for item: T, index: Int) -> some View {
        print(title, item.title, items.map({ $0.title }))
        return Button(action: {
            self.selection = index
        }, label: {
            HStack {
                Text(item.title)
                Spacer()
                if index == self.selection {
                    Image(systemName: "checkmark")
                        .font(.headline)
                        .foregroundColor(.rpnCalculatorOrange)
                }
            }
        })
    }

}

And finally, this is what a Segmentable object looks like:

enum GroupingSeparator: Int, CaseIterable {

    case defaultSeparator
    case space
    case comma

}

extension GroupingSeparator: Segmentable {

    var id: String {
        switch self {
        case .defaultSeparator:
            return "groupingSeparator.default"
        case .space:
            return "groupingSeparator.space"
        case .comma:
            return "groupingSeparator.comma"
        }
    }

    var title: String {
        switch self {
        case .defaultSeparator:
            return "Default"
        case .space:
            return "Space"
        case .comma:
            return "Comma"
        }
    }

}

When the SettingsView is loaded. everything looks fine. But as soon as I start scrolling, and some other cells are instantiated, there are some cell displayed, but not the proper ones. Here is some screenshots and logs.

When the view is loaded, no scrolling, here is what the screen looks like:

But, what I got on the console is pretty weird and doesn't follow the order of the SettingsPickerView written in the main View:

Trigonometry Units Radians ["Radians", "Degrees"] <-- Fine
Trigonometry Units Degrees ["Radians", "Degrees"] <-- Fine
Decimal Separator Default ["Default", "Dot", "Comma"] <-- Fine
Decimal Separator Default ["Default", "Dot", "Comma"] <-- Fine
Trigonometry Units Degrees ["Radians", "Degrees"] <-- Not expected. Should be Grouping Separator
Trigonometry Units Radians ["Radians", "Degrees"] <-- Not expected. Should be Grouping Separator

The second section is ok and properly displayed:

But the third section is completely broken:

The third section displays its title properly, but display some of the data of the first section. I tried to add an identifier to the button in the cell because the issue looks like SwiftUI can't identify the proper data. But adding an identifier to the button broke the binding, and the checkbox don't change anymore.

private func cell(for item: T, index: Int) -> some View {
    print(title, item.title, items.map({ $0.title }))
    return Button(action: {
        self.selection = index
    }, label: {
        HStack {
            Text(item.title)
            Spacer()
            if index == self.selection {
                Image(systemName: "checkmark")
                    .font(.headline)
                    .foregroundColor(.rpnCalculatorOrange)
            }
        }
    })
        .id(UUID().uuidString) // This solve the display issue but broke the binding.
}

Does someone experienced something like this before ?

Thanks in advance for your help.

Body:
Here is fixed block of code (due to used indexes only List is confused and reuses rows, so solution is to make rows identifiable by items).

Tested with Xcode 11.4

struct PickerView<T: Segmentable>: View {

    // ... other code here

    var body: some View {
        Section(header: Text(title)) {
            // Corrected section construction !!
            ForEach(Array(items.enumerated()), id: \.element.id) { index, _ in
                self.cell(for: self.items[index], index: index)
            }
        }
    }

    // ... other code here


来源: stackexchange

问:
improve performance for postgres
I count the number of users in this way, it runs for 5 seconds to produce results, I am looking for a better solution</p>

```<code>SELECT COUNT(*)
FROM (SELECT user_id
      FROM slot_result_primary
      WHERE session_timestamp BETWEEN 1590598800000 AND 1590685199999
      GROUP BY user_id) AS foo
</code>```

答:
Counting is a very heavy operation in Postgres. It should be avoided if possible.
It is very difficult to make it better so for each row Postgress needs to go the the disc. You can indeed create a better index to choose which rows to pick from the disc faster but even with this count time will always go up in time in a linear time compared to the size of the data.

Your index should be:

```<code>CREATE INDEX session_timestamp_user_id_index ON slot_result_primary (session_timestamp, user_id)
</code>```

for best results.

Still an index will not solve your count problems fully. In a similar situation I faced two days ago (with a SELECT query running 3s and count
 running 1s) dedicated indexes allowed to push down the time of select to 0,3ms but best I could do with count was 700ms.

Here you can find a good article with a summary why count is difficult and different ways to make it better:
https://www.citusdata.com/blog/2016/10/12/count-performance/

ContentLicense: CC BY-SA 4.0

Title: improve performance for postgres

Body:
I count the number of users in this way, it runs for 5 seconds to produce results, I am looking for a better solution

SELECT COUNT(*)
FROM (SELECT user_id
      FROM slot_result_primary
      WHERE session_timestamp BETWEEN 1590598800000 AND 1590685199999
      GROUP BY user_id) AS foo

Body:
Counting is a very heavy operation in Postgres. It should be avoided if possible.
It is very difficult to make it better so for each row Postgress needs to go the the disc. You can indeed create a better index to choose which rows to pick from the disc faster but even with this count time will always go up in time in a linear time compared to the size of the data.

Your index should be:

CREATE INDEX session_timestamp_user_id_index ON slot_result_primary (session_timestamp, user_id)

for best results.

Still an index will not solve your count problems fully. In a similar situation I faced two days ago (with a SELECT query running 3s and count
 running 1s) dedicated indexes allowed to push down the time of select to 0,3ms but best I could do with count was 700ms.

Here you can find a good article with a summary why count is difficult and different ways to make it better:
https://www.citusdata.com/blog/2016/10/12/count-performance/


问:
SQL group_by and group_concat if all values present in group
```<code>/*
 cars                   cars_location
+------+---------+    +-------------+-----+            garages
| id   | int     |<---| car_id        | int |     +-------+---------+
| name | varchar |    | garage_id     | int | --->| id    | int     |
+------+---------+    +-------------+-----+       | name  | varchar |
                                                  +-------+---------+
*/
drop table if exists cars, garages, cars_location;
create table cars
(
    id   int not null,
    name varchar(255),
    primary key (id)
);
create table garages
(
    id   int not null,
    name varchar(255),
    primary key (id)
);
create table cars_location
(
    car_id     int not null,
    garage_id  int not null,
    primary key (car_id, garage_id)
);
insert into cars (id, name)
values (1, 'BMW'),
       (2, 'Audi'),
       (3, 'Volkswagen');
insert into garages (id, name)
values (1, 'Garage1'),
       (2, 'Garage2'),
       (3, 'Garage3'),
       (4, 'Garage4');
insert into cars_location (car_id, garage_id)
values (1, 1),
       (1, 2),
       (1, 3),
       (2, 1),
       (2, 2),
       (2, 3),
       (2, 4),
       (3, 1),
       (3, 2),
       (3, 4);
-- Find all cars placed in all requested garages at the same time.
-- Example below:
/*
---------------------------------------------------------
cars       |   garages
---------------------------------------------------------
BMW        | Garage1, Garage2, Garage3                 - RETURNED!!
Audi       | Garage1, Garage2, Garage3, Garage4        - RETURNED!!
Volkswagen | Garage1, Garage2,                 Garage4 - NOT returned
---------------------------------------------------------
*/

select cars.name as cars,
       group_concat(
           garages.name
           ) as places
from cars_location
         left join cars on cars.id = cars_location.car_id
         left join garages on garages.id = cars_location.garage_id
-- where places in (1,2,3) # problem here because Volkswagen doesnt exist in garage 3 so should not be visible
group by 1
</code>```

Find all cars placed in all requested garages at the same time. So I want to achieve this

```<code>---------------------------------------------------------
cars       |   garages
---------------------------------------------------------
BMW        | Garage1, Garage2, Garage3                 - RETURNED!!
Audi       | Garage1, Garage2, Garage3, Garage4        - RETURNED!!
Volkswagen | Garage1, Garage2,                 Garage4 - NOT returned because garage3 not present
---------------------------------------------------------
</code>```

I dont know how to build only one sql query

```<code>select cars.name as cars,
       group_concat(
           garages.name
           ) as places
from cars_location
         left join cars on cars.id = cars_location.car_id
         left join garages on garages.id = cars_location.garage_id
-- where places MUST BE in (1,2,3) # problem here because Volkswagen doesnt exist in garage 3 so should not be returned by sql
group by 1
</code>```

http://sqlfiddle.com/#!9/eadd7a/1

答:
You want a having clause:

```<code>having sum(garage.id = 1) > 0 and
       sum(garage.id = 2) > 0 and
       sum(garage.id = 3) > 0
</code>```

Body:
/*
 cars                   cars_location
+------+---------+    +-------------+-----+            garages
| id   | int     |<---| car_id        | int |     +-------+---------+
| name | varchar |    | garage_id     | int | --->| id    | int     |
+------+---------+    +-------------+-----+       | name  | varchar |
                                                  +-------+---------+
*/
drop table if exists cars, garages, cars_location;
create table cars
(
    id   int not null,
    name varchar(255),
    primary key (id)
);
create table garages
(
    id   int not null,
    name varchar(255),
    primary key (id)
);
create table cars_location
(
    car_id     int not null,
    garage_id  int not null,
    primary key (car_id, garage_id)
);
insert into cars (id, name)
values (1, 'BMW'),
       (2, 'Audi'),
       (3, 'Volkswagen');
insert into garages (id, name)
values (1, 'Garage1'),
       (2, 'Garage2'),
       (3, 'Garage3'),
       (4, 'Garage4');
insert into cars_location (car_id, garage_id)
values (1, 1),
       (1, 2),
       (1, 3),
       (2, 1),
       (2, 2),
       (2, 3),
       (2, 4),
       (3, 1),
       (3, 2),
       (3, 4);
-- Find all cars placed in all requested garages at the same time.
-- Example below:
/*
---------------------------------------------------------
cars       |   garages
---------------------------------------------------------
BMW        | Garage1, Garage2, Garage3                 - RETURNED!!
Audi       | Garage1, Garage2, Garage3, Garage4        - RETURNED!!
Volkswagen | Garage1, Garage2,                 Garage4 - NOT returned
---------------------------------------------------------
*/

select cars.name as cars,
       group_concat(
           garages.name
           ) as places
from cars_location
         left join cars on cars.id = cars_location.car_id
         left join garages on garages.id = cars_location.garage_id
-- where places in (1,2,3) # problem here because Volkswagen doesnt exist in garage 3 so should not be visible
group by 1

Find all cars placed in all requested garages at the same time. So I want to achieve this

---------------------------------------------------------
cars       |   garages
---------------------------------------------------------
BMW        | Garage1, Garage2, Garage3                 - RETURNED!!
Audi       | Garage1, Garage2, Garage3, Garage4        - RETURNED!!
Volkswagen | Garage1, Garage2,                 Garage4 - NOT returned because garage3 not present
---------------------------------------------------------

I dont know how to build only one sql query

select cars.name as cars,
       group_concat(
           garages.name
           ) as places
from cars_location
         left join cars on cars.id = cars_location.car_id
         left join garages on garages.id = cars_location.garage_id
-- where places MUST BE in (1,2,3) # problem here because Volkswagen doesnt exist in garage 3 so should not be returned by sql
group by 1

http://sqlfiddle.com/#!9/eadd7a/1

Body:
You want a having clause:

having sum(garage.id = 1) > 0 and
       sum(garage.id = 2) > 0 and
       sum(garage.id = 3) > 0


问:
Jackson JsonNode with empty element key
I am using jackson-dataformat-xml (2.9) to parse an XML into JsonNode and then parse it to JSON
(the XML is very dynamic so that is why I am using JsonNode instead of binding to a POJO. e.g 'elementName' and 'id' names may vary).

It happens that during the JSON parsing phase, one of the element keys is empty string ("").

XML:

```<code><elementName>
      <id type="pid">abcdef123</id>
</elementName>
</code>```

Parsing logic:

```<code>public Parser() {
        ObjectMapper jsonMapper = new ObjectMapper();
        XmlMapper xmlMapper = new XmlMapper(new XmlFactory(new WstxInputFactory()));
}

public InputStream parseXmlResponse(InputStream xmlStream) {
        InputStream stream = null;

        try {
            JsonNode node = xmlMapper.readTree(xmlStream);
            stream = new ByteArrayInputStream(jsonMapper.writer().writeValueAsBytes(node));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return stream;
    }
</code>```

Json:

Result:

```<code>{
   "elementName": {
     "id": {
        "type": "pid",
        "": "abcdef123"
     }
   },
}
</code>```

Expected:

```<code>{
   "elementName": {
     "id": {
        "type": "pid",
        "value": "abcdef123"
     }
   },
}
</code>```

My idea is to find whenever I have the empty key "" and replace it with "value". Either at XML de-serialization or during JSON serialization.
I have tried to use default serializer, filter, but haven't got it working in a nice and concise way.

Suggestions are much appreciated.

Thank you for the help.

Possible Solution:

Based on @shoek suggestion I decided to write a custom serializer to avoid creating an intermediate object (ObjectNode) during the process.

edit: refactor based on the same solution proposed by @shoek.

```<code>public class CustomNode {
    private JsonNode jsonNode;

    public CustomNode(JsonNode jsonNode) {
        this.jsonNode = jsonNode;
    }

    public JsonNode getJsonNode() {
        return jsonNode;
    }
}

public class CustomObjectsResponseSerializer extends StdSerializer<CustomNode> {

    protected CustomObjectsResponseSerializer() {
        super(CustomNode.class);
    }

    @Override
    public void serialize(CustomNode node, JsonGenerator jgen, SerializerProvider provider) throws IOException {
        convertObjectNode(node.getJsonNode(), jgen, provider);
    }

    private void convertObjectNode(JsonNode node, JsonGenerator jgen, SerializerProvider provider) throws IOException {
        jgen.writeStartObject();
        for (Iterator<String> it = node.fieldNames(); it.hasNext(); ) {
            String childName = it.next();
            JsonNode childNode = node.get(childName);
            // XML parser returns an empty string as value name. Replacing it with "value"
            if (Objects.equals("", childName)) {
                childName = "value";
            }

            if (childNode instanceof ArrayNode) {
                jgen.writeFieldName(childName);
                convertArrayNode(childNode, jgen, provider);
            } else if (childNode instanceof ObjectNode) {
                jgen.writeFieldName(childName);
                convertObjectNode(childNode, jgen, provider);
            } else {
                provider.defaultSerializeField(childName, childNode, jgen);
            }
        }
        jgen.writeEndObject();

    }

    private void convertArrayNode(JsonNode node, JsonGenerator jgen, SerializerProvider provider) throws IOException {
        jgen.writeStartArray();
        for (Iterator<JsonNode> it = node.elements(); it.hasNext(); ) {
            JsonNode childNode = it.next();

            if (childNode instanceof ArrayNode) {
                convertArrayNode(childNode, jgen, provider);
            } else if (childNode instanceof ObjectNode) {
                convertObjectNode(childNode, jgen, provider);
            } else {
                provider.defaultSerializeValue(childNode, jgen);
            }
        }
        jgen.writeEndArray();
    }
}
</code>```

答:
You also could simply post-process the JSON DOM, traverse to all objects, and rename the keys that are empty strings to "value".

Race condition: such a key may already exist, and must not be overwritten

(e.g. <id type="pid" value="existing">abcdef123</id>).

Usage:

(note: you should not silently suppress the exception and return null, but allow it to propagate so the caller can decide to catch and apply failover logic if required)

```<code>public InputStream parseXmlResponse(InputStream xmlStream) throws IOException {
    JsonNode node = xmlMapper.readTree(xmlStream);
    postprocess(node);
    return new ByteArrayInputStream(jsonMapper.writer().writeValueAsBytes(node));
}
</code>```

Post-processing:

```<code>private void postprocess(JsonNode jsonNode) {

    if (jsonNode.isArray()) {
        ArrayNode array = (ArrayNode) jsonNode;
        Iterable<JsonNode> elements = () -> array.elements();

        // recursive post-processing
        for (JsonNode element : elements) {
            postprocess(element);
        }
    }
    if (jsonNode.isObject()) {
        ObjectNode object = (ObjectNode) jsonNode;
        Iterable<String> fieldNames = () -> object.fieldNames();

        // recursive post-processing
        for (String fieldName : fieldNames) {
            postprocess(object.get(fieldName));
        }
        // check if an attribute with empty string key exists, and rename it to 'value',
        // unless there already exists another non-null attribute named 'value' which
        // would be overwritten.
        JsonNode emptyKeyValue = object.get("");
        JsonNode existing = object.get("value");
        if (emptyKeyValue != null) {
            if (existing == null || existing.isNull()) {
                object.set("value", emptyKeyValue);
                object.remove("");
            } else {
                System.err.println("Skipping empty key value as a key named 'value' already exists.");
            }
        }
    }
}
</code>```

Output: just as expected.

```<code>{
   "elementName": {
     "id": {
        "type": "pid",
        "value": "abcdef123"
     }
   },
}
</code>```

EDIT: considerations on performance:

I did a test with a large XML file (enwikiquote-20200520-pages-articles-multistream.xml, en.wikiquote XML dump, 498.4 MB), 100 rounds, with following measured times (using deltas with System.nanoTime()):

average read time (File, SSD): 2870.96 ms
(JsonNode node = xmlMapper.readTree(xmlStream);)

average postprocessing time: 0.04 ms
(postprocess(node);)

average write time (memory): 0.31 ms
(new ByteArrayInputStream(jsonMapper.writer().writeValueAsBytes(node));)

That's a fraction of a millisecond for an object tree build from a ~500 MB file - so performance is excellent and no concern.

Title: Jackson JsonNode with empty element key

Body:
I am using jackson-dataformat-xml (2.9) to parse an XML into JsonNode and then parse it to JSON
(the XML is very dynamic so that is why I am using JsonNode instead of binding to a POJO. e.g 'elementName' and 'id' names may vary).

It happens that during the JSON parsing phase, one of the element keys is empty string ("").

XML:

<elementName>
      <id type="pid">abcdef123</id>
</elementName>

Parsing logic:

public Parser() {
        ObjectMapper jsonMapper = new ObjectMapper();
        XmlMapper xmlMapper = new XmlMapper(new XmlFactory(new WstxInputFactory()));
}

public InputStream parseXmlResponse(InputStream xmlStream) {
        InputStream stream = null;

        try {
            JsonNode node = xmlMapper.readTree(xmlStream);
            stream = new ByteArrayInputStream(jsonMapper.writer().writeValueAsBytes(node));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return stream;
    }

Json:

Result:

{
   "elementName": {
     "id": {
        "type": "pid",
        "": "abcdef123"
     }
   },
}

Expected:

{
   "elementName": {
     "id": {
        "type": "pid",
        "value": "abcdef123"
     }
   },
}

My idea is to find whenever I have the empty key "" and replace it with "value". Either at XML de-serialization or during JSON serialization.
I have tried to use default serializer, filter, but haven't got it working in a nice and concise way.

Suggestions are much appreciated.

Thank you for the help.

Possible Solution:

Based on @shoek suggestion I decided to write a custom serializer to avoid creating an intermediate object (ObjectNode) during the process.

edit: refactor based on the same solution proposed by @shoek.

public class CustomNode {
    private JsonNode jsonNode;

    public CustomNode(JsonNode jsonNode) {
        this.jsonNode = jsonNode;
    }

    public JsonNode getJsonNode() {
        return jsonNode;
    }
}

public class CustomObjectsResponseSerializer extends StdSerializer<CustomNode> {

    protected CustomObjectsResponseSerializer() {
        super(CustomNode.class);
    }

    @Override
    public void serialize(CustomNode node, JsonGenerator jgen, SerializerProvider provider) throws IOException {
        convertObjectNode(node.getJsonNode(), jgen, provider);
    }

    private void convertObjectNode(JsonNode node, JsonGenerator jgen, SerializerProvider provider) throws IOException {
        jgen.writeStartObject();
        for (Iterator<String> it = node.fieldNames(); it.hasNext(); ) {
            String childName = it.next();
            JsonNode childNode = node.get(childName);
            // XML parser returns an empty string as value name. Replacing it with "value"
            if (Objects.equals("", childName)) {
                childName = "value";
            }

            if (childNode instanceof ArrayNode) {
                jgen.writeFieldName(childName);
                convertArrayNode(childNode, jgen, provider);
            } else if (childNode instanceof ObjectNode) {
                jgen.writeFieldName(childName);
                convertObjectNode(childNode, jgen, provider);
            } else {
                provider.defaultSerializeField(childName, childNode, jgen);
            }
        }
        jgen.writeEndObject();

    }

    private void convertArrayNode(JsonNode node, JsonGenerator jgen, SerializerProvider provider) throws IOException {
        jgen.writeStartArray();
        for (Iterator<JsonNode> it = node.elements(); it.hasNext(); ) {
            JsonNode childNode = it.next();

            if (childNode instanceof ArrayNode) {
                convertArrayNode(childNode, jgen, provider);
            } else if (childNode instanceof ObjectNode) {
                convertObjectNode(childNode, jgen, provider);
            } else {
                provider.defaultSerializeValue(childNode, jgen);
            }
        }
        jgen.writeEndArray();
    }
}

Body:
You also could simply post-process the JSON DOM, traverse to all objects, and rename the keys that are empty strings to "value".

Race condition: such a key may already exist, and must not be overwritten

(e.g. <id type="pid" value="existing">abcdef123</id>).

Usage:

(note: you should not silently suppress the exception and return null, but allow it to propagate so the caller can decide to catch and apply failover logic if required)

public InputStream parseXmlResponse(InputStream xmlStream) throws IOException {
    JsonNode node = xmlMapper.readTree(xmlStream);
    postprocess(node);
    return new ByteArrayInputStream(jsonMapper.writer().writeValueAsBytes(node));
}

Post-processing:

private void postprocess(JsonNode jsonNode) {

    if (jsonNode.isArray()) {
        ArrayNode array = (ArrayNode) jsonNode;
        Iterable<JsonNode> elements = () -> array.elements();

        // recursive post-processing
        for (JsonNode element : elements) {
            postprocess(element);
        }
    }
    if (jsonNode.isObject()) {
        ObjectNode object = (ObjectNode) jsonNode;
        Iterable<String> fieldNames = () -> object.fieldNames();

        // recursive post-processing
        for (String fieldName : fieldNames) {
            postprocess(object.get(fieldName));
        }
        // check if an attribute with empty string key exists, and rename it to 'value',
        // unless there already exists another non-null attribute named 'value' which
        // would be overwritten.
        JsonNode emptyKeyValue = object.get("");
        JsonNode existing = object.get("value");
        if (emptyKeyValue != null) {
            if (existing == null || existing.isNull()) {
                object.set("value", emptyKeyValue);
                object.remove("");
            } else {
                System.err.println("Skipping empty key value as a key named 'value' already exists.");
            }
        }
    }
}

Output: just as expected.

{
   "elementName": {
     "id": {
        "type": "pid",
        "value": "abcdef123"
     }
   },
}

EDIT: considerations on performance:

I did a test with a large XML file (enwikiquote-20200520-pages-articles-multistream.xml, en.wikiquote XML dump, 498.4 MB), 100 rounds, with following measured times (using deltas with System.nanoTime()):

average read time (File, SSD): 2870.96 ms
(JsonNode node = xmlMapper.readTree(xmlStream);)

average postprocessing time: 0.04 ms
(postprocess(node);)

average write time (memory): 0.31 ms
(new ByteArrayInputStream(jsonMapper.writer().writeValueAsBytes(node));)

That's a fraction of a millisecond for an object tree build from a ~500 MB file - so performance is excellent and no concern.


问:
openpyxl.utils.exceptions.IllegalCharacterError where to fix
```<code>import requests
import html2text
import openpyxl

with open('crawlingweb.csv')as f:
    content=f.readlines()
    content=[x.strip()for x in content]

excel_file=openpyxl.Workbook()
excel_sheet=excel_file.active

for i in range(100):
    url=content[i]
    req=requests.get(url)
    html=req.text
    raw=html2text.html2text(html)
    excel_sheet.append([raw])

excel_file.save('crawling.xlsx')
excel_file.close()
</code>```

<p>I got error openpyxl.utils.exceptions.IllegalCharacterError
and Crawled results do not fully reflect the content of the site.
If I am not satisfied with the results of my crawl, is there another way?
thank you </p>

答:
```<code>import requests
import html2text
import openpyxl
import re
from openpyxl.cell.cell import ILLEGAL_CHARACTERS_RE

with open('crawlingweb.csv')as f:
    content=f.readlines()
    content=[x.strip()for x in content]

excel_file=openpyxl.Workbook()
excel_sheet=excel_file.active

for i in range(50):
    url=content[i]
    req=requests.get(url)
    html=req.text
    raw=html2text.html2text(html)
    raw = ILLEGAL_CHARACTERS_RE.sub(r'', raw)
    excel_sheet.append([raw])

excel_file.save('crawling.xlsx')
excel_file.close()
</code>```

Body:
import requests
import html2text
import openpyxl

with open('crawlingweb.csv')as f:
    content=f.readlines()
    content=[x.strip()for x in content]

excel_file=openpyxl.Workbook()
excel_sheet=excel_file.active

for i in range(100):
    url=content[i]
    req=requests.get(url)
    html=req.text
    raw=html2text.html2text(html)
    excel_sheet.append([raw])

excel_file.save('crawling.xlsx')
excel_file.close()

I got error openpyxl.utils.exceptions.IllegalCharacterError
and Crawled results do not fully reflect the content of the site.
If I am not satisfied with the results of my crawl, is there another way?
thank you


问:
Is there a CuPy version supporting (axis) option in cupy.unique() function? Any workaround?
I'm looking for a GPU CuPy counterpart of numpy.unique() with axis option supported.

I have a Cupy 2D array that I need to remove its duplicated rows. Unfortunately, cupy.unique() function flattens the array and returns 1D array with unique values. I'm looking for a function like numpy.unique(arr, axis=0) to solve this but CuPy does not support the (axis) option yet

x = cp.array([[1,2,3,4], [4,5,6,7], [1,2,3,4], [10,11,12,13]])
y = cp.unique(x)
y_r = np.unique(cp.asnumpy(x), axis=0)

print('The 2D array:\n', x)
print('Required:\n', y_r, 'But using CuPy')
print('The flattened unique array:\n', y)

print('Error producing line:', cp.unique(x, axis=0))

I expect a 2D array with unique rows but I get a 1D array with unique numbers instead. Any ideas about how to implement this with CuPy or numba?
```

答:
As of CuPy version 8.0.0b2, the function cupy.lexsort is correctly implemented. This function can be used as a workaround (albeit probably not the most efficient) for cupy.unique with the axis argument.

Assuming the array is 2D, and that you want to find the unique elements along axis 0 (else transpose/swap as appropriate):

```<code>    ###################################
    # replacement for numpy.unique with option axis=0
    ###################################

    def cupy_unique_axis0(array):
        if len(array.shape) != 2:
            raise ValueError("Input array must be 2D.")
        sortarr     = array[cupy.lexsort(array.T[::-1])]
        mask        = cupy.empty(array.shape[0], dtype=cupy.bool_)
        mask[0]     = True
        mask[1:]    = cupy.any(sortarr[1:] != sortarr[:-1], axis=1)
        return sortarr[mask]
</code>```

Check the original cupy.unique source code (which this is based on) if you want to implement the return_stuff arguments, too. I don't need those myself.

Body:
As of CuPy version 8.0.0b2, the function cupy.lexsort is correctly implemented. This function can be used as a workaround (albeit probably not the most efficient) for cupy.unique with the axis argument.

Assuming the array is 2D, and that you want to find the unique elements along axis 0 (else transpose/swap as appropriate):

    ###################################
    # replacement for numpy.unique with option axis=0
    ###################################

    def cupy_unique_axis0(array):
        if len(array.shape) != 2:
            raise ValueError("Input array must be 2D.")
        sortarr     = array[cupy.lexsort(array.T[::-1])]
        mask        = cupy.empty(array.shape[0], dtype=cupy.bool_)
        mask[0]     = True
        mask[1:]    = cupy.any(sortarr[1:] != sortarr[:-1], axis=1)
        return sortarr[mask]

Check the original cupy.unique source code (which this is based on) if you want to implement the return_stuff arguments, too. I don't need those myself.


问:
Unable to cast object of type 'System.Byte' to type 'System.String'.'
I am trying to populate value from Database to Combobox and when I run it I get this error:

Unable to cast object of type 'System.Byte' to type 'System.String'.'

Status is of type tinyint.

```<code>public void FillStatus()
{
    try
    {
        using (SqlConnection conn = new SqlConnection(@"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=DesignSaoOsig1;Integrated Security=True"))
        {
            conn.Open();
            string query = "SELECT DISTINCT Status FROM tblZaposleni_AD";
            SqlCommand cmd = new SqlCommand(query, conn);
            using (SqlDataReader saReader = cmd.ExecuteReader())
            {
                while (saReader.Read())
                {
                    string name = saReader.GetString(0);
                    ddlStatus.Items.Add(name);
                }
            }
        }
    }
    catch (Exception)
    {
        throw;
    }
}
</code>```

答:
I find where the error comes from. Insted of </p>

```<code>string name = saReader.GetString(0);
</code>```

<p>I just replace this line to this one </p>

```<code> string name = saReader.GetByte(0).ToString();
</code>```

Body:
I am trying to populate value from Database to Combobox and when I run it I get this error:

Unable to cast object of type 'System.Byte' to type 'System.String'.'

Status is of type tinyint.

public void FillStatus()
{
    try
    {
        using (SqlConnection conn = new SqlConnection(@"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=DesignSaoOsig1;Integrated Security=True"))
        {
            conn.Open();
            string query = "SELECT DISTINCT Status FROM tblZaposleni_AD";
            SqlCommand cmd = new SqlCommand(query, conn);
            using (SqlDataReader saReader = cmd.ExecuteReader())
            {
                while (saReader.Read())
                {
                    string name = saReader.GetString(0);
                    ddlStatus.Items.Add(name);
                }
            }
        }
    }
    catch (Exception)
    {
        throw;
    }
}

Body:
I find where the error comes from. Insted of

string name = saReader.GetString(0);

I just replace this line to this one

 string name = saReader.GetByte(0).ToString();


问:
Django - ckeditor is not working - customization
I am trying to customize my ckeditor in Django setting like this. But I am getting 500 error once I save the setting. Otherwise the ckeditor is working but if I am trying to customize it, it fails.

```<code>CKEDITOR_CONFIGS = {
    'awesome_ckeditor': {
        'toolbar': 'Basic',
    },
}
</code>```

Can someone help me please, how to make my own "config" without rewriting the basic one, please ?

答:
in your prJ at settings.py

```<code>INSTALLED_APPS = [ 'ckeditor',]
</code>```

and

```<code>CKEDITOR_CONFIGS = {
    'default': {
        'toolbar': 'Custom',
        'width': '500px',
        'height': '10%',
        'toolbar_Custom': [
            ['Bold', 'Italic', 'Underline'],
            ['NumberedList', 'BulletedList'],

        ],
    }
}

CKEDITOR_BASEPATH = "/static/ckeditor/ckeditor/"
</code>```

Body:
I am trying to customize my ckeditor in Django setting like this. But I am getting 500 error once I save the setting. Otherwise the ckeditor is working but if I am trying to customize it, it fails.

CKEDITOR_CONFIGS = {
    'awesome_ckeditor': {
        'toolbar': 'Basic',
    },
}

Can someone help me please, how to make my own "config" without rewriting the basic one, please ?

Body:
in your prJ at settings.py

INSTALLED_APPS = [ 'ckeditor',]

and

CKEDITOR_CONFIGS = {
    'default': {
        'toolbar': 'Custom',
        'width': '500px',
        'height': '10%',
        'toolbar_Custom': [
            ['Bold', 'Italic', 'Underline'],
            ['NumberedList', 'BulletedList'],

        ],
    }
}

CKEDITOR_BASEPATH = "/static/ckeditor/ckeditor/"


问:
Why mapping not working when data streaming?
I need to map lat, long to geo-point. I stream data every 10 seconds from a website. I get only first occurrence of the position from json. I did mapping. and when I run my code the data is streaming but can't see the mapped in Kibana.

Here is my code.
    es = Elasticsearch('http://ip:port',timeout=600)

```<code>settings = { "settings": {
                     "number_of_shards":1

                     },
          "mappings" : {
                    "properties":{
                         "geo": {
                            "properties": {
                                "location":{
                                   "type": "geo_point"

                                    }
                                  }
                        }
        } } }

es.indices.create(index = "myindex", ignore = 400, body=settings)
def data_collect():
 data = requests.get(url = URL).json()
 del data["positions"][1]
 positions = data['positions']

 if "satlatitude" in positions and "satlongitude" in positions:
  data['positions']['geo'] = { 'location':
                           str(positions['satlatitude'])+","+str(positions['satlongitude'])}

  es.index(index='myindex',doc_type='mydoc',body=data)

schedule.every(10).seconds.do( data_collect)
while True:
 schedule.run_pending()
 time.sleep(1)
</code>```

Results of GET satellitepositions/_mapping as bellow:

```<code> {
 "satellitepositions": {
 "mappings": {
  "satelitepos": {
    "properties": {
      "info": {
        "properties": {
          "satid": {
            "type": "long"
          },
          "satname": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }
          },
          "transactionscount": {
            "type": "long"
          }
        }
      },
      "positions": {
        "properties": {
          "azimuth": {
            "type": "float"
          },
          "dec": {
            "type": "float"
          },
          "eclipsed": {
            "type": "boolean"
          },
          "elevation": {
            "type": "float"
          },
          "ra": {
            "type": "float"
          },
          "sataltitude": {
            "type": "float"
          },
          "satlatitude": {
            "type": "float"
          },
          "satlongitude": {
            "type": "float"
          },
          "timestamp": {
            "type": "long"
          }
        }
      }
    }
    }
    }
    }
    }
</code>```

Results of GET satellitepositions as bellow:

```<code> {
 "satellitepositions": {
 "aliases": {},
  "mappings": {
  "satelitepos": {
    "properties": {
      "info": {
        "properties": {
          "satid": {
            "type": "long"
          },
          "satname": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }
          },
          "transactionscount": {
            "type": "long"
          }
        }
      },
      "positions": {
        "properties": {
          "azimuth": {
            "type": "float"
          },
          "dec": {
            "type": "float"
          },
          "eclipsed": {
            "type": "boolean"
          },
          "elevation": {
            "type": "float"
          },
          "ra": {
            "type": "float"
          },
          "sataltitude": {
            "type": "float"
          },
          "satlatitude": {
            "type": "float"
          },
          "satlongitude": {
            "type": "float"
          },
          "timestamp": {
            "type": "long"
          }
        }
      }
    }
  }
},
"settings": {
  "index": {
    "creation_date": "1590738791943",
    "number_of_shards": "5",
    "number_of_replicas": "1",
    "uuid": "HLstIPiXQcyJC5_laowxNQ",
    "version": {
      "created": "6040399"
    },
    "provided_name": "satellitepositions"
  }
  }
  }
  }
</code>```

答:
Instead of adding that logic in the Python script, let's use an ingest pipeline that does the job for you.

First, run the following call in Kibana to create the geo-pipeline ingest pipeline that will create the geo point out of the lat/lon fields you get from the satellite API.

```<code>PUT _ingest/pipeline/geo-pipeline
{
  "processors": [
    {
      "script": {
        "source": """
          ctx.positions = ctx.positions[0];
          ctx.geo = [
            'lat': ctx.positions.satlatitude,
            'lon': ctx.positions.satlongitude
          ]
          """
      }
    }
  ]
}
</code>```

Next, you can simplify your Python code like shown below. You'll note that I've modified the index settings to make sure all documents that are indexed in your index run through the geo-pipeline first, and get the geo field created properly.

```<code>es = Elasticsearch('http://ip:port',timeout=600)

# create index
settings = {
  "settings": {
    "index.number_of_shards": 1,
    "index.default_pipeline": "geo-pipeline"
  },
  "mappings": {
    "satelitepos": {
      "properties": {
        "geo": {
          "properties": {
            "location": {
              "type": "geo_point"
            }
          }
        }
      }
    }
  }
}
es.indices.create(index = "satellitepositions", ignore = 400, body=settings)

# routine for collecting data
def data_collect():
  data = requests.get(url = URL).json()
  del data["positions"][1]
  es.index(index='satellitepositions', doc_type='satelitepos', body=data)

schedule.every(10).seconds.do(data_collect)

# kick it all off
while True:
 schedule.run_pending()
 time.sleep(1)
</code>```

This should work as you expect and your documents will get a geo field of type geo_point that you can show on a map.

Body:
I need to map lat, long to geo-point. I stream data every 10 seconds from a website. I get only first occurrence of the position from json. I did mapping. and when I run my code the data is streaming but can't see the mapped in Kibana.

Here is my code.
    es = Elasticsearch('http://ip:port',timeout=600)

settings = { "settings": {
                     "number_of_shards":1

                     },
          "mappings" : {
                    "properties":{
                         "geo": {
                            "properties": {
                                "location":{
                                   "type": "geo_point"

                                    }
                                  }
                        }
        } } }

es.indices.create(index = "myindex", ignore = 400, body=settings)
def data_collect():
 data = requests.get(url = URL).json()
 del data["positions"][1]
 positions = data['positions']

 if "satlatitude" in positions and "satlongitude" in positions:
  data['positions']['geo'] = { 'location':
                           str(positions['satlatitude'])+","+str(positions['satlongitude'])}

  es.index(index='myindex',doc_type='mydoc',body=data)

schedule.every(10).seconds.do( data_collect)
while True:
 schedule.run_pending()
 time.sleep(1)

Results of GET satellitepositions/_mapping as bellow:

 {
 "satellitepositions": {
 "mappings": {
  "satelitepos": {
    "properties": {
      "info": {
        "properties": {
          "satid": {
            "type": "long"
          },
          "satname": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }
          },
          "transactionscount": {
            "type": "long"
          }
        }
      },
      "positions": {
        "properties": {
          "azimuth": {
            "type": "float"
          },
          "dec": {
            "type": "float"
          },
          "eclipsed": {
            "type": "boolean"
          },
          "elevation": {
            "type": "float"
          },
          "ra": {
            "type": "float"
          },
          "sataltitude": {
            "type": "float"
          },
          "satlatitude": {
            "type": "float"
          },
          "satlongitude": {
            "type": "float"
          },
          "timestamp": {
            "type": "long"
          }
        }
      }
    }
    }
    }
    }
    }

Results of GET satellitepositions as bellow:

 {
 "satellitepositions": {
 "aliases": {},
  "mappings": {
  "satelitepos": {
    "properties": {
      "info": {
        "properties": {
          "satid": {
            "type": "long"
          },
          "satname": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }
          },
          "transactionscount": {
            "type": "long"
          }
        }
      },
      "positions": {
        "properties": {
          "azimuth": {
            "type": "float"
          },
          "dec": {
            "type": "float"
          },
          "eclipsed": {
            "type": "boolean"
          },
          "elevation": {
            "type": "float"
          },
          "ra": {
            "type": "float"
          },
          "sataltitude": {
            "type": "float"
          },
          "satlatitude": {
            "type": "float"
          },
          "satlongitude": {
            "type": "float"
          },
          "timestamp": {
            "type": "long"
          }
        }
      }
    }
  }
},
"settings": {
  "index": {
    "creation_date": "1590738791943",
    "number_of_shards": "5",
    "number_of_replicas": "1",
    "uuid": "HLstIPiXQcyJC5_laowxNQ",
    "version": {
      "created": "6040399"
    },
    "provided_name": "satellitepositions"
  }
  }
  }
  }

Body:
Instead of adding that logic in the Python script, let's use an ingest pipeline that does the job for you.

First, run the following call in Kibana to create the geo-pipeline ingest pipeline that will create the geo point out of the lat/lon fields you get from the satellite API.

PUT _ingest/pipeline/geo-pipeline
{
  "processors": [
    {
      "script": {
        "source": """
          ctx.positions = ctx.positions[0];
          ctx.geo = [
            'lat': ctx.positions.satlatitude,
            'lon': ctx.positions.satlongitude
          ]
          """
      }
    }
  ]
}

Next, you can simplify your Python code like shown below. You'll note that I've modified the index settings to make sure all documents that are indexed in your index run through the geo-pipeline first, and get the geo field created properly.

es = Elasticsearch('http://ip:port',timeout=600)

# create index
settings = {
  "settings": {
    "index.number_of_shards": 1,
    "index.default_pipeline": "geo-pipeline"
  },
  "mappings": {
    "satelitepos": {
      "properties": {
        "geo": {
          "properties": {
            "location": {
              "type": "geo_point"
            }
          }
        }
      }
    }
  }
}
es.indices.create(index = "satellitepositions", ignore = 400, body=settings)

# routine for collecting data
def data_collect():
  data = requests.get(url = URL).json()
  del data["positions"][1]
  es.index(index='satellitepositions', doc_type='satelitepos', body=data)

schedule.every(10).seconds.do(data_collect)

# kick it all off
while True:
 schedule.run_pending()
 time.sleep(1)

This should work as you expect and your documents will get a geo field of type geo_point that you can show on a map.


问:
'tools:replace="android:allowBackup"' to <application> element
I have issue when i add implementation  'com.github.MdFarhanRaja:SearchableSpinner:2.0'
warning suggest to me

```<code>'tools:replace="android:allowBackup"' to <application> element at AndroidManifest.xml:20:5-123:19 to override.
</code>```

This is my Manifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.together">
    <!--
         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2, but you must specify either coarse or fine
         location permissions for the 'MyLocation' functionality.
    -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <!-- 맵 이용하기 위함 -->
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <!-- 다음 지도 -->
    <uses-permission android:name="android.permission.INTERNET" /> <!-- 대략적인 위치 참조 권한 -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <!-- 정확한 위치 참조 권한 -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.SEND_SMS" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />

    <application
        android:allowBackup="false"
        android:appComponentFactory="whateverString"
        android:icon="@mipmap/ic_launcher"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:usesCleartextTraffic="true"
        tools:replace="android:appComponentFactory">
</code>```

but when i change

```<code> tools:replace="android:appComponentFactory"
</code>```

this to

```<code>'tools:replace="android:allowBackup"
</code>```

with this
the new error show and suggetion to me

```<code>Manifest merger failed : Attribute application@appComponentFactory value=(whateverString) from AndroidManifest.xml:22:9-53
    is also present at [androidx.core:core:1.0.1] AndroidManifest.xml:22:18-86 value=(androidx.core.app.CoreComponentFactory).
    Suggestion: add 'tools:replace="android:appComponentFactory"' to <application> element at AndroidManifest.xml:20:5-123:19 to override.
</code>```

That suggest change android:appComponentFactory this

What should i do if i want to implementation it?

This is my Module: app
+ I add my build.gradle

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.blogapp"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'

        }
    }

    compileOptions {

        sourceCompatibility JavaVersion.VERSION_1_8

        targetCompatibility JavaVersion.VERSION_1_8

    }
}

dependencies {

    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:animated-vector-drawable:28.0.0'//
    implementation 'com.android.support:exifinterface:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3' //있고 ㅇㅇ

    //Expandable 프래그먼트 goodbyepet selectmenu
    implementation 'com.thoughtbot:expandablerecyclerview:1.3'
    implementation 'com.thoughtbot:expandablecheckrecyclerview:1.4'

    //유튜브 강의 3 추가함
    //1장에서 설정한거 추가

    //1장에서 설정한거 추가
    implementation 'com.jakewharton:butterknife:8.8.1'
    //유튜브 강의 3 추가함

    // firebase core

    implementation 'com.google.firebase:firebase-core:16.0.9'

    // firebase auth
    implementation 'com.google.firebase:firebase-auth:17.0.0'

    // firebase storage
    implementation 'com.google.firebase:firebase-storage:17.0.0'

    // firebase realtime database
    implementation 'com.google.firebase:firebase-database:17.0.0'

    implementation "com.wdullaer:materialdatetimepicker:3.6.4"

    implementation 'com.android.support:support-v13:28.0.0'
    implementation 'com.android.support:recyclerview-v7:28.0.0'

    //photo control
    implementation 'com.theartofdev.edmodo:android-image-cropper:2.7.0'

    // card view
    implementation 'com.android.support:cardview-v7:28.0.0'

    // swipe cards for petching
    implementation 'com.lorentzos.swipecards:library:1.0.9'

    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    testImplementation 'junit:junit:4.12'    //있고 ㅇㅇ
    androidTestImplementation 'com.android.support.test:runner:1.0.2'   //있고 ㅇㅇ
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'  //있고 ㅇㅇ

    // Design library for Coordinator Layout and Toolbars
    implementation 'com.android.support:design:28.0.0'

    // circle design
    implementation 'de.hdodenhof:circleimageview:3.0.0'

    // rectangle design
    implementation 'com.github.siyamed:android-shape-imageview:0.9.3@aar'

    // bumptech/glide
    implementation 'com.github.bumptech.glide:glide:4.9.0'

    //picaso/glide
    implementation 'com.squareup.picasso:picasso:2.71828'

    // Edit Text
    implementation 'com.rengwuxian.materialedittext:library:2.1.4'

    // lombok 사용
    compileOnly 'org.projectlombok:lombok:1.18.8'
    annotationProcessor 'org.projectlombok:lombok:1.18.8'
    implementation 'com.android.support:gridlayout-v7:28.0.0'

    // User Map
    implementation 'com.android.support:appcompat-v7:28.0.0'

    implementation 'com.android.support.constraint:constraint-layout:1.1.3'

    implementation 'com.google.android.gms:play-services-maps:16.1.0'

    implementation 'com.google.android.gms:play-services-location:16.0.0'

    implementation 'com.google.android.gms:play-services-places:16.1.0'

    implementation 'noman.placesapi:placesAPI:1.1.3'

    implementation 'com.thoughtbot:expandablecheckrecyclerview:1.4'

    testImplementation 'junit:junit:4.12'

    androidTestImplementation 'com.android.support.test:runner:1.0.2'

    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'org.jetbrains:annotations-java5:15.0'

    //Calendar

    implementation 'joda-time:joda-time:2.10.1'

    // LifeCycle online or offline 여부 판별
    implementation "android.arch.lifecycle:extensions:1.1.1"

    // retrofit2 통신 라이브러리
    implementation 'com.google.firebase:firebase-messaging:19.0.1'
    implementation 'androidx.annotation:annotation:1.1.0'

    //calendar view
    implementation 'com.github.prolificinteractive:material-calendarview:1.5.0'

    // Searchable Spinner

}

apply plugin: 'com.google.gms.google-services'

</code>```

This is my projed build

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.4.1'
        classpath 'com.google.gms:google-services:4.2.0'
        // radio button
        classpath 'lib.kingja.switchbutton:switchbutton:1.1.8'
        classpath 'com.android.support:appcompat-v7:28.0.0'
        classpath 'com.google.android.gms:play-services-maps:17.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven { url "https://jitpack.io" }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

</code>```

答:
After android:allowBackup="false" add tools:replace="android:allowBackup".
use this code in mainfest file do close this issue.

Body:
I have issue when i add implementation  'com.github.MdFarhanRaja:SearchableSpinner:2.0'
warning suggest to me

'tools:replace="android:allowBackup"' to <application> element at AndroidManifest.xml:20:5-123:19 to override.

This is my Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.together">

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.SEND_SMS" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />

    <application
        android:allowBackup="false"
        android:appComponentFactory="whateverString"
        android:icon="@mipmap/ic_launcher"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:usesCleartextTraffic="true"
        tools:replace="android:appComponentFactory">

but when i change

 tools:replace="android:appComponentFactory"

this to

'tools:replace="android:allowBackup"

with this
the new error show and suggetion to me

Manifest merger failed : Attribute application@appComponentFactory value=(whateverString) from AndroidManifest.xml:22:9-53
    is also present at [androidx.core:core:1.0.1] AndroidManifest.xml:22:18-86 value=(androidx.core.app.CoreComponentFactory).
    Suggestion: add 'tools:replace="android:appComponentFactory"' to <application> element at AndroidManifest.xml:20:5-123:19 to override.

That suggest change android:appComponentFactory this

What should i do if i want to implementation it?

This is my Module: app
+ I add my build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.blogapp"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'

        }
    }

    compileOptions {

        sourceCompatibility JavaVersion.VERSION_1_8

        targetCompatibility JavaVersion.VERSION_1_8

    }
}

dependencies {

    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:animated-vector-drawable:28.0.0'//
    implementation 'com.android.support:exifinterface:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3' //있고 ㅇㅇ

    //Expandable 프래그먼트 goodbyepet selectmenu
    implementation 'com.thoughtbot:expandablerecyclerview:1.3'
    implementation 'com.thoughtbot:expandablecheckrecyclerview:1.4'

    //유튜브 강의 3 추가함
    //1장에서 설정한거 추가

    //1장에서 설정한거 추가
    implementation 'com.jakewharton:butterknife:8.8.1'
    //유튜브 강의 3 추가함

    // firebase core

    implementation 'com.google.firebase:firebase-core:16.0.9'

    // firebase auth
    implementation 'com.google.firebase:firebase-auth:17.0.0'

    // firebase storage
    implementation 'com.google.firebase:firebase-storage:17.0.0'

    // firebase realtime database
    implementation 'com.google.firebase:firebase-database:17.0.0'

    implementation "com.wdullaer:materialdatetimepicker:3.6.4"

    implementation 'com.android.support:support-v13:28.0.0'
    implementation 'com.android.support:recyclerview-v7:28.0.0'

    //photo control
    implementation 'com.theartofdev.edmodo:android-image-cropper:2.7.0'

    // card view
    implementation 'com.android.support:cardview-v7:28.0.0'

    // swipe cards for petching
    implementation 'com.lorentzos.swipecards:library:1.0.9'

    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    testImplementation 'junit:junit:4.12'    //있고 ㅇㅇ
    androidTestImplementation 'com.android.support.test:runner:1.0.2'   //있고 ㅇㅇ
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'  //있고 ㅇㅇ

    // Design library for Coordinator Layout and Toolbars
    implementation 'com.android.support:design:28.0.0'

    // circle design
    implementation 'de.hdodenhof:circleimageview:3.0.0'

    // rectangle design
    implementation 'com.github.siyamed:android-shape-imageview:0.9.3@aar'

    // bumptech/glide
    implementation 'com.github.bumptech.glide:glide:4.9.0'

    //picaso/glide
    implementation 'com.squareup.picasso:picasso:2.71828'

    // Edit Text
    implementation 'com.rengwuxian.materialedittext:library:2.1.4'

    // lombok 사용
    compileOnly 'org.projectlombok:lombok:1.18.8'
    annotationProcessor 'org.projectlombok:lombok:1.18.8'
    implementation 'com.android.support:gridlayout-v7:28.0.0'

    // User Map
    implementation 'com.android.support:appcompat-v7:28.0.0'

    implementation 'com.android.support.constraint:constraint-layout:1.1.3'

    implementation 'com.google.android.gms:play-services-maps:16.1.0'

    implementation 'com.google.android.gms:play-services-location:16.0.0'

    implementation 'com.google.android.gms:play-services-places:16.1.0'

    implementation 'noman.placesapi:placesAPI:1.1.3'

    implementation 'com.thoughtbot:expandablecheckrecyclerview:1.4'

    testImplementation 'junit:junit:4.12'

    androidTestImplementation 'com.android.support.test:runner:1.0.2'

    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'org.jetbrains:annotations-java5:15.0'

    //Calendar

    implementation 'joda-time:joda-time:2.10.1'

    // LifeCycle online or offline 여부 판별
    implementation "android.arch.lifecycle:extensions:1.1.1"

    // retrofit2 통신 라이브러리
    implementation 'com.google.firebase:firebase-messaging:19.0.1'
    implementation 'androidx.annotation:annotation:1.1.0'

    //calendar view
    implementation 'com.github.prolificinteractive:material-calendarview:1.5.0'

    // Searchable Spinner

}

apply plugin: 'com.google.gms.google-services'

This is my projed build

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.4.1'
        classpath 'com.google.gms:google-services:4.2.0'
        // radio button
        classpath 'lib.kingja.switchbutton:switchbutton:1.1.8'
        classpath 'com.android.support:appcompat-v7:28.0.0'
        classpath 'com.google.android.gms:play-services-maps:17.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven { url "https://jitpack.io" }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}


问:
Why ball isnt moving when update is called(pygame Pong)?
When calling ball.update() I expected the ball should move, but it didn't.

I'm thinking that perhaps there is a problem with defining bpos as a rect object and passing it in to an ellipse to draw the ball to the screen.

game rects

bpos = pygame.Rect(screen_width / 2 - 15, screen_height / 2 - 15, 30, 30)

The reason i make bpos a rect object and then passs it in as to draw ellipse:

```<code>class Ball:
   def __init__(self):
    self.x = screen_width // 2
    self.y = screen_height // 2
    self.speed = 5
    self.vx = self.speed
    self.vy = self.speed

    def draw(self, screen):
        pygame.draw.ellipse(screen, light_grey, bpos)

    def update(self):
        self.x += self.vx
        self.y += self.vy
</code>```

is because eventually, when it will come to keeping the ball in bounds I would like to use pygame Rect attributes(top,bottom,left,right) in the update method like this if possible.

```<code> def update(self):
            self.x += self.vx
            self.y += self.vy
**if self.top <= 0 or self.bottom >= screen_height:
        self.vy *= -1
    if ball.left <= 0 or self.right >= screen_width:
        self.vx *= -1**

But the ball isnt moving.
</code>```

In the game logic you can see that I'm calling:

ball.draw(screen)
   ball.update()

Would greatly appreciate some input. Thanks. Below is my code.

```<code>    import pygame, sys

    class Paddle:
        def __init__(self):
            self.rect = pygame.Rect(10, screen_height / 2 - 70, 10, 140)

        def draw(self, screen):
            pygame.draw.rect(screen, light_grey, self.rect)

    class Ball:
        def __init__(self):
            self.x = screen_width // 2
            self.y = screen_height // 2
            self.speed = 5
            self.vx = self.speed
            self.vy = self.speed

        def draw(self, screen):
            pygame.draw.ellipse(screen, light_grey, bpos)

        def update(self):
            self.x += self.vx
            self.y += self.vy

    # General setup
    pygame.init()
    clock = pygame.time.Clock()

    # Main Window
    screen_width = 1280
    screen_height = 960

    screen = pygame.display.set_mode((screen_width, screen_height))
    pygame.display.set_caption('Pong')

    # Colors
    light_grey = (200, 200, 200)
    bg_color = pygame.Color('grey12')

    # Game Rectangles
    ball = Ball()
    bpos = pygame.Rect(screen_width / 2 - 15, screen_height / 2 - 15, 30, 30)
    left_paddle = Paddle()
    right_paddle = Paddle()
    right_paddle.rect.x = screen_width - right_paddle.rect.width

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

        # Game logic

        screen.fill(bg_color)
        ball.draw(screen)
        left_paddle.draw(screen)
        right_paddle.draw(screen)
        ball.update()

        pygame.display.flip()
        clock.tick(60)
</code>```

答:
The problem is not that you are using a rect for bpos per say. The problem is that you do not update bpos.

The rect you use for drawing the ellipse needs to be updated in your Ball.update(). You update the self.x,y but not the thing you use to draw the ball.

However, the rect that you use should be a attribute of the Ball instance, not an external variable. You should initialize it in the init and use the self.rect.x and self.rect.y to update and track the balls position. Do not keep the position both in a self.rect.x,and self.rect.y and separately in a self.x, self.y. That will just lead to redundancy and possible inconsistency and error.

I would suggest these changes.

Change this:

```<code># Game Rectangles
ball = Ball()
bpos = pygame.Rect(screen_width / 2 - 15, screen_height / 2 - 15, 30, 30)
</code>```

to something like this:

```<code># Game Rectangles
ball = Ball(screen_width / 2 - 15, screen_height / 2 - 15, 30, 30)
</code>```

and this:

```<code>class Ball:
    def __init__(self):
        self.x = screen_width // 2
        self.y = screen_height // 2
        self.speed = 5
        self.vx = self.speed
        self.vy = self.speed

    def draw(self, screen):
        pygame.draw.ellipse(screen, light_grey, bpos)

    def update(self):
        self.x += self.vx
        self.y += self.vy
</code>```

to something like this:

```<code>class Ball:
    def __init__(self, x, y, width, height):
        self.rect = pygame.Rect(x, y, width, height))
        self.speed = 5
        self.vx = self.speed
        self.vy = self.speed

    def draw(self, screen):
        pygame.draw.ellipse(screen, light_grey, self.rect)

    def update(self):
        self.rect.x += self.vx
        self.rect.y += self.vy
</code>```

Body:
When calling ball.update() I expected the ball should move, but it didn't.

I'm thinking that perhaps there is a problem with defining bpos as a rect object and passing it in to an ellipse to draw the ball to the screen.

game rects

bpos = pygame.Rect(screen_width / 2 - 15, screen_height / 2 - 15, 30, 30)

The reason i make bpos a rect object and then passs it in as to draw ellipse:

class Ball:
   def __init__(self):
    self.x = screen_width // 2
    self.y = screen_height // 2
    self.speed = 5
    self.vx = self.speed
    self.vy = self.speed

    def draw(self, screen):
        pygame.draw.ellipse(screen, light_grey, bpos)

    def update(self):
        self.x += self.vx
        self.y += self.vy

is because eventually, when it will come to keeping the ball in bounds I would like to use pygame Rect attributes(top,bottom,left,right) in the update method like this if possible.

 def update(self):
            self.x += self.vx
            self.y += self.vy
**if self.top <= 0 or self.bottom >= screen_height:
        self.vy *= -1
    if ball.left <= 0 or self.right >= screen_width:
        self.vx *= -1**

But the ball isnt moving.

In the game logic you can see that I'm calling:

ball.draw(screen)
   ball.update()

Would greatly appreciate some input. Thanks. Below is my code.

    import pygame, sys

    class Paddle:
        def __init__(self):
            self.rect = pygame.Rect(10, screen_height / 2 - 70, 10, 140)

        def draw(self, screen):
            pygame.draw.rect(screen, light_grey, self.rect)

    class Ball:
        def __init__(self):
            self.x = screen_width // 2
            self.y = screen_height // 2
            self.speed = 5
            self.vx = self.speed
            self.vy = self.speed

        def draw(self, screen):
            pygame.draw.ellipse(screen, light_grey, bpos)

        def update(self):
            self.x += self.vx
            self.y += self.vy

    # General setup
    pygame.init()
    clock = pygame.time.Clock()

    # Main Window
    screen_width = 1280
    screen_height = 960

    screen = pygame.display.set_mode((screen_width, screen_height))
    pygame.display.set_caption('Pong')

    # Colors
    light_grey = (200, 200, 200)
    bg_color = pygame.Color('grey12')

    # Game Rectangles
    ball = Ball()
    bpos = pygame.Rect(screen_width / 2 - 15, screen_height / 2 - 15, 30, 30)
    left_paddle = Paddle()
    right_paddle = Paddle()
    right_paddle.rect.x = screen_width - right_paddle.rect.width

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

        # Game logic

        screen.fill(bg_color)
        ball.draw(screen)
        left_paddle.draw(screen)
        right_paddle.draw(screen)
        ball.update()

        pygame.display.flip()
        clock.tick(60)

Body:
The problem is not that you are using a rect for bpos per say. The problem is that you do not update bpos.

The rect you use for drawing the ellipse needs to be updated in your Ball.update(). You update the self.x,y but not the thing you use to draw the ball.

However, the rect that you use should be a attribute of the Ball instance, not an external variable. You should initialize it in the init and use the self.rect.x and self.rect.y to update and track the balls position. Do not keep the position both in a self.rect.x,and self.rect.y and separately in a self.x, self.y. That will just lead to redundancy and possible inconsistency and error.

I would suggest these changes.

Change this:

# Game Rectangles
ball = Ball()
bpos = pygame.Rect(screen_width / 2 - 15, screen_height / 2 - 15, 30, 30)

to something like this:

# Game Rectangles
ball = Ball(screen_width / 2 - 15, screen_height / 2 - 15, 30, 30)

and this:

class Ball:
    def __init__(self):
        self.x = screen_width // 2
        self.y = screen_height // 2
        self.speed = 5
        self.vx = self.speed
        self.vy = self.speed

    def draw(self, screen):
        pygame.draw.ellipse(screen, light_grey, bpos)

    def update(self):
        self.x += self.vx
        self.y += self.vy

to something like this:

class Ball:
    def __init__(self, x, y, width, height):
        self.rect = pygame.Rect(x, y, width, height))
        self.speed = 5
        self.vx = self.speed
        self.vy = self.speed

    def draw(self, screen):
        pygame.draw.ellipse(screen, light_grey, self.rect)

    def update(self):
        self.rect.x += self.vx
        self.rect.y += self.vy


答:
As SQL Server tinyint is converted to byte in .NET, you need to read it as such, then convert to a string:

```<code>byte dbValue = saReader.GetByte(0);
string name = dbValue.ToString();
ddlStatus.Items.Add(name);
</code>```

Title: Unable to cast object of type 'System.Byte' to type 'System.String'.'

Body:
As SQL Server tinyint is converted to byte in .NET, you need to read it as such, then convert to a string:

byte dbValue = saReader.GetByte(0);
string name = dbValue.ToString();
ddlStatus.Items.Add(name);


问:
How to calculate the average of an element in the array (salary) in C#
what else do I need to add or change to display my employees between the ages of 25 and 35
years with a higher salary than average salary. This program only displays employees between the ages of 25 and 35.</p>

```<code>        for (int i = 0; i < employeename; i++)
         {
            while (br.PeekChar() != -1)
            {
                function[i].Name= br.ReadString();
                function[i].Function= br.ReadString();
                function[i].Age= br.ReadInt32();
                function[i].salary= br.ReadInt32();
                function[i].Studies= br.ReadString();

                if ((function[i].Age>25) && (function[i].Age<35))
                {
                    string str = String.Format("|{0,-21}|{1,-9}|{2,-7}|{3,-16}|{4,-12}|", function[i].Name, function[i].Function,
                        function[i].Age.ToString(), function[i].Salary.ToString(), function[i].Studies);
                    Console.WriteLine(str);
                }

            }

        }
        Console.ReadKey();
        br.Close();
</code>```

答:
I think you need to read all data and calculate avgSalary before filtering:

Map your data in an Employee class with params Name, Function, Age,
  Salary, Studies.

```<code>    var employees = new List<Employee>();
    while (br.PeekChar() != -1)
    {
        var employee = new Employee() {
           Name= br.ReadString(),
           Function= br.ReadString(),
           Age= br.ReadInt32(),
           Salary= br.ReadInt32(),
           Studies= br.ReadString()
         };
         employees.Add(employee);
     }

var avgSalary = employees.Select(x => x.Salary).Average();

var finalList = employees.Where(x => x.Age > 25 && x.Age < 35 && x.Salary > avgSalary).ToList();
</code>```

You need to use EF & LINQ for that.

Body:
what else do I need to add or change to display my employees between the ages of 25 and 35
years with a higher salary than average salary. This program only displays employees between the ages of 25 and 35.

        for (int i = 0; i < employeename; i++)
         {
            while (br.PeekChar() != -1)
            {
                function[i].Name= br.ReadString();
                function[i].Function= br.ReadString();
                function[i].Age= br.ReadInt32();
                function[i].salary= br.ReadInt32();
                function[i].Studies= br.ReadString();

                if ((function[i].Age>25) && (function[i].Age<35))
                {
                    string str = String.Format("|{0,-21}|{1,-9}|{2,-7}|{3,-16}|{4,-12}|", function[i].Name, function[i].Function,
                        function[i].Age.ToString(), function[i].Salary.ToString(), function[i].Studies);
                    Console.WriteLine(str);
                }

            }

        }
        Console.ReadKey();
        br.Close();

Body:
I think you need to read all data and calculate avgSalary before filtering:

Map your data in an Employee class with params Name, Function, Age,
  Salary, Studies.

    var employees = new List<Employee>();
    while (br.PeekChar() != -1)
    {
        var employee = new Employee() {
           Name= br.ReadString(),
           Function= br.ReadString(),
           Age= br.ReadInt32(),
           Salary= br.ReadInt32(),
           Studies= br.ReadString()
         };
         employees.Add(employee);
     }

var avgSalary = employees.Select(x => x.Salary).Average();

var finalList = employees.Where(x => x.Age > 25 && x.Age < 35 && x.Salary > avgSalary).ToList();

You need to use EF & LINQ for that.


问:
Get element of controls (scrubber) of a video element in HTML5
When generating a standard video object in HTML5 you can activate standard controls for it. When using an inspect tool of a browser I see that the element I am looking for is called a scrubber, which is the timeline that shows where the video is standing at (and start and end position). My browser says that this element is named input#scrubber.scrubber . How can it be accessed through javascript? I need to get its starting and ending x positions, which should not be a problem once I can get the element.
I tried document.getElementsByClassName and document.querySelectorAll to search for it but somehow did it wrong.</p>

答: That's part of the browser's Shadow DOM / pseudo-elements. You can't access them by javascript - see this post.</p>


问:
C++ invalid use of non-static member function?
i have a main cpp file containing something like this

```<code>Leader labourLeader("George Lopez",100,50,50, 75);//sets record for the labour party leader
Candidate labourCandidate("Donna Smith",100,50,50, 75);
compaignMananger labourCampagainManagr("John Gunn",100,50);
nationalcompaignManager labourNationalCampagainManager("Adam Lapel",100,50);
natioanlfinancialManager labourFinancialManager("Sandra Bullac",100,50);

Party labourParty(labourParty.getPartyName(), labourParty.getLeader(), labourParty.getCandidate(), labourParty.getCampagainManager(), labourParty.getNationalCampgainManager(),
labourParty.setnationalcampagainManager, labourParty.getStance()); //create 1st politcal Party

labourParty.setLeader(labourLeader);
labourParty.setCandidate(labourCandidate);
labourParty.setcampaginManager(labourCampagainManagr);
labourParty.setnationalcampagainManager(labourNationalCampagainManager);
labourParty.setnationalFinancalManager(labourFinancialManager);
labourParty.setPartyName("Labour");
labourParty.setStance(1000);
</code>```

However when i compile the main body code i get an error like such.

```<code>error: invalid use of non-static member function ‘void Party::setnationalcampagainManager(nationalcompaignManager)’
 labourParty.setnationalcampagainManager, labourParty.getStance()); //create 1st politcal Party

 note: declared here
      void Party::setnationalcampagainManager(nationalcompaignManager NationalcompaignManangerObject){
</code>```

which corresponds to the following line of code

```<code> void Party::setnationalcampagainManager(nationalcompaignManager NationalcompaignManangerObject){

         newNationalcompaignMananger = NationalcompaignManangerObject;

     }
</code>```

Im not quite sure what might be causing this error as ive never recieved it before. If any more code is needed i am happy to provide. thankyou :)

Party Constructor

```<code>class Party{
     public:
     std::string partyName;
     int initalStance;
     Leader newLeader;
     Candidate newCandidate;
     compaignMananger newcompaignMananger ;
     nationalcompaignManager newNationalcompaignMananger;
     natioanlfinancialManager newNationalfinancialManager;

     Party(std::string partyName, Leader newLeader, Candidate newCandidate, compaignMananger newcompaignMananger,
     nationalcompaignManager newNationalcompaignMananger, natioanlfinancialManager newNationalfinancialManager, int initalStance) {

         this->partyName = partyName;
         this->newLeader = newLeader;
         this-> newNationalcompaignMananger = newNationalcompaignMananger;
         this-> newcompaignMananger = newcompaignMananger;
         this-> newNationalfinancialManager = newNationalfinancialManager;
         this->newCandidate = newCandidate;
         this->initalStance = initalStance;

         setPartyName(getPartyName());
         setLeader(getLeader());
         setCandidate(getCandidate());
         setcampaginManager(getCampagainManager());
         setnationalcampagainManager(getNationalCampgainManager());
         setnationalFinancalManager(getFinancialManager());
         setStance(getStance());
     }
</code>```

答:
There's a few issues with your constructor invocation:

```<code>Party labourParty(
    labourParty.getPartyName(),
    labourParty.getLeader(),
    labourParty.getCandidate(),
    labourParty.getCampagainManager(),
    labourParty.getNationalCampgainManager(),
    labourParty.setnationalcampagainManager,
    labourParty.getStance()
); //create 1st politcal Party
</code>```

You are using the return value of labourParty methods as arguments to the constructor. This does not make any sense; the object is not yet constructed at this point, so you cannot use its methods and expect anything reasonable to happen.

labourParty.setnationalcampagainManager is missing parens indicating that you want to invoke the method.  This is the "invalid use of non-static member function" -- you can't reference a non-static member function by name like this without invoking it.

If you do invoke this method, you need to supply the required argument, but you can't even invoke the method yet because of point 1.

Here are my thoughts after seeing the constructor:

The constructor copies the arguments to the data members but then also invokes the relevant setters.  Assuming the setters do the same thing, this is redundant; do one or the other, but not both.  This just wastes CPU cycles copying the same data to the same place twice.

Since you take the arguments by value, you could also move-construct the data members, which will save some CPU cycles making copies of data that is just going to be destroyed anyway.  I suspect you could apply this same optimization to the setters.

As far as actually invoking the constructor, you can replace all of this code:

```<code>Party labourParty(labourParty.getPartyName(), labourParty.getLeader(), labourParty.getCandidate(), labourParty.getCampagainManager(), labourParty.getNationalCampgainManager(),
labourParty.setnationalcampagainManager, labourParty.getStance()); //create 1st politcal Party

labourParty.setLeader(labourLeader);
labourParty.setCandidate(labourCandidate);
labourParty.setcampaginManager(labourCampagainManagr);
labourParty.setnationalcampagainManager(labourNationalCampagainManager);
labourParty.setnationalFinancalManager(labourFinancialManager);
labourParty.setPartyName("Labour");
labourParty.setStance(1000);
</code>```

With just this:

```<code>Party labourParty(
    "Labour",
    labourLeader,
    labourCandidate,
    labourCampagainManagr,
    labourNationalCampagainManager,
    labourFinancialManager,
    1000
);
</code>```

Body:
i have a main cpp file containing something like this

Leader labourLeader("George Lopez",100,50,50, 75);//sets record for the labour party leader
Candidate labourCandidate("Donna Smith",100,50,50, 75);
compaignMananger labourCampagainManagr("John Gunn",100,50);
nationalcompaignManager labourNationalCampagainManager("Adam Lapel",100,50);
natioanlfinancialManager labourFinancialManager("Sandra Bullac",100,50);

Party labourParty(labourParty.getPartyName(), labourParty.getLeader(), labourParty.getCandidate(), labourParty.getCampagainManager(), labourParty.getNationalCampgainManager(),
labourParty.setnationalcampagainManager, labourParty.getStance()); //create 1st politcal Party

labourParty.setLeader(labourLeader);
labourParty.setCandidate(labourCandidate);
labourParty.setcampaginManager(labourCampagainManagr);
labourParty.setnationalcampagainManager(labourNationalCampagainManager);
labourParty.setnationalFinancalManager(labourFinancialManager);
labourParty.setPartyName("Labour");
labourParty.setStance(1000);

However when i compile the main body code i get an error like such.

error: invalid use of non-static member function ‘void Party::setnationalcampagainManager(nationalcompaignManager)’
 labourParty.setnationalcampagainManager, labourParty.getStance()); //create 1st politcal Party

 note: declared here
      void Party::setnationalcampagainManager(nationalcompaignManager NationalcompaignManangerObject){

which corresponds to the following line of code

 void Party::setnationalcampagainManager(nationalcompaignManager NationalcompaignManangerObject){

         newNationalcompaignMananger = NationalcompaignManangerObject;

     }

Im not quite sure what might be causing this error as ive never recieved it before. If any more code is needed i am happy to provide. thankyou :)

Party Constructor

class Party{
     public:
     std::string partyName;
     int initalStance;
     Leader newLeader;
     Candidate newCandidate;
     compaignMananger newcompaignMananger ;
     nationalcompaignManager newNationalcompaignMananger;
     natioanlfinancialManager newNationalfinancialManager;

     Party(std::string partyName, Leader newLeader, Candidate newCandidate, compaignMananger newcompaignMananger,
     nationalcompaignManager newNationalcompaignMananger, natioanlfinancialManager newNationalfinancialManager, int initalStance) {

         this->partyName = partyName;
         this->newLeader = newLeader;
         this-> newNationalcompaignMananger = newNationalcompaignMananger;
         this-> newcompaignMananger = newcompaignMananger;
         this-> newNationalfinancialManager = newNationalfinancialManager;
         this->newCandidate = newCandidate;
         this->initalStance = initalStance;

         setPartyName(getPartyName());
         setLeader(getLeader());
         setCandidate(getCandidate());
         setcampaginManager(getCampagainManager());
         setnationalcampagainManager(getNationalCampgainManager());
         setnationalFinancalManager(getFinancialManager());
         setStance(getStance());
     }

Body:
There's a few issues with your constructor invocation:

Party labourParty(
    labourParty.getPartyName(),
    labourParty.getLeader(),
    labourParty.getCandidate(),
    labourParty.getCampagainManager(),
    labourParty.getNationalCampgainManager(),
    labourParty.setnationalcampagainManager,
    labourParty.getStance()
); //create 1st politcal Party

You are using the return value of labourParty methods as arguments to the constructor. This does not make any sense; the object is not yet constructed at this point, so you cannot use its methods and expect anything reasonable to happen.

labourParty.setnationalcampagainManager is missing parens indicating that you want to invoke the method.  This is the "invalid use of non-static member function" -- you can't reference a non-static member function by name like this without invoking it.

If you do invoke this method, you need to supply the required argument, but you can't even invoke the method yet because of point 1.

Here are my thoughts after seeing the constructor:

The constructor copies the arguments to the data members but then also invokes the relevant setters.  Assuming the setters do the same thing, this is redundant; do one or the other, but not both.  This just wastes CPU cycles copying the same data to the same place twice.

Since you take the arguments by value, you could also move-construct the data members, which will save some CPU cycles making copies of data that is just going to be destroyed anyway.  I suspect you could apply this same optimization to the setters.

As far as actually invoking the constructor, you can replace all of this code:

Party labourParty(labourParty.getPartyName(), labourParty.getLeader(), labourParty.getCandidate(), labourParty.getCampagainManager(), labourParty.getNationalCampgainManager(),
labourParty.setnationalcampagainManager, labourParty.getStance()); //create 1st politcal Party

labourParty.setLeader(labourLeader);
labourParty.setCandidate(labourCandidate);
labourParty.setcampaginManager(labourCampagainManagr);
labourParty.setnationalcampagainManager(labourNationalCampagainManager);
labourParty.setnationalFinancalManager(labourFinancialManager);
labourParty.setPartyName("Labour");
labourParty.setStance(1000);

With just this:

Party labourParty(
    "Labour",
    labourLeader,
    labourCandidate,
    labourCampagainManagr,
    labourNationalCampagainManager,
    labourFinancialManager,
    1000
);


问:
Save and load weights in keras
Im trying to save and load weights from the model i have trained.

the code im using to save the model is.

```<code>TensorBoard(log_dir='/output')
model.fit_generator(image_a_b_gen(batch_size), steps_per_epoch=1, epochs=1)
model.save_weights('model.hdf5')
model.save_weights('myModel.h5')
</code>```

Let me know if this an incorrect way to do it,or if there is a better way to do it.

but when i try to load them,using this,

```<code>from keras.models import load_model
model = load_model('myModel.h5')
</code>```

but i get this error:

```<code>ValueError                                Traceback (most recent call
last)
<ipython-input-7-27d58dc8bb48> in <module>()
      1 from keras.models import load_model
----> 2 model = load_model('myModel.h5')

/home/decentmakeover2/anaconda3/lib/python3.5/site-
packages/keras/models.py in load_model(filepath, custom_objects, compile)
    235         model_config = f.attrs.get('model_config')
    236         if model_config is None:
--> 237             raise ValueError('No model found in config file.')
    238         model_config = json.loads(model_config.decode('utf-8'))
    239         model = model_from_config(model_config,
custom_objects=custom_objects)

ValueError: No model found in config file.
</code>```

Any suggestions on what i may be doing wrong?
Thank you in advance.

答:
Since this question is quite old, but still comes up in google searches, I thought it would be good to point out the newer (and recommended) way to save Keras models.
Instead of saving them using the older h5 format like has been shown before, it is now advised to use the SavedModel format, which is actually a dictionary that contains both the model configuration and the weights.

More information can be found here: https://www.tensorflow.org/guide/keras/save_and_serialize

The snippets to save & load can be found below:

model.fit(test_input, test_target)
# Calling save('my_model') creates a SavedModel folder 'my_model'.
model.save('my_model')

# It can be used to reconstruct the model identically.
reconstructed_model = keras.models.load_model('my_model')
```

A sample output of this :

ContentLicense: CC BY-SA 3.0

Title: Save and load weights in keras

Body:
Im trying to save and load weights from the model i have trained.

the code im using to save the model is.

TensorBoard(log_dir='/output')
model.fit_generator(image_a_b_gen(batch_size), steps_per_epoch=1, epochs=1)
model.save_weights('model.hdf5')
model.save_weights('myModel.h5')

Let me know if this an incorrect way to do it,or if there is a better way to do it.

but when i try to load them,using this,

from keras.models import load_model
model = load_model('myModel.h5')

but i get this error:

ValueError                                Traceback (most recent call
last)
<ipython-input-7-27d58dc8bb48> in <module>()
      1 from keras.models import load_model
----> 2 model = load_model('myModel.h5')

/home/decentmakeover2/anaconda3/lib/python3.5/site-
packages/keras/models.py in load_model(filepath, custom_objects, compile)
    235         model_config = f.attrs.get('model_config')
    236         if model_config is None:
--> 237             raise ValueError('No model found in config file.')
    238         model_config = json.loads(model_config.decode('utf-8'))
    239         model = model_from_config(model_config,
custom_objects=custom_objects)

ValueError: No model found in config file.

Any suggestions on what i may be doing wrong?
Thank you in advance.

Body:
Since this question is quite old, but still comes up in google searches, I thought it would be good to point out the newer (and recommended) way to save Keras models.
Instead of saving them using the older h5 format like has been shown before, it is now advised to use the SavedModel format, which is actually a dictionary that contains both the model configuration and the weights.

More information can be found here: https://www.tensorflow.org/guide/keras/save_and_serialize

The snippets to save & load can be found below:

model.fit(test_input, test_target)
# Calling save('my_model') creates a SavedModel folder 'my_model'.
model.save('my_model')

# It can be used to reconstruct the model identically.
reconstructed_model = keras.models.load_model('my_model')

A sample output of this :


问:
Inserting a value in particular cell of DB2 blu table
I want to insert a value in a column "column_1" of table "table_1" with a condition where column "column_2" has a particular value and column "column_3" value is not like some value.
"column_2" and "column_3" are both in the same table "table_1".

I tried the following query but I am not getting require result.

INSERT INTO Table_1 (Column_1) VALUES ('Distribution') where column_2 = 'ABC' and column_3 not like '%123%'

Can anyone help me in writing proper query for this requirement.

答:
I think you want update:

```<code>update table_1
    set column_1 = 'Distribution'
    where column_2 = 'ABC' and column_3 not like '%123%';
</code>```

insert adds new rows to the table.  update changes values in columns in existing rows.

Body:
I think you want update:

update table_1
    set column_1 = 'Distribution'
    where column_2 = 'ABC' and column_3 not like '%123%';

insert adds new rows to the table.  update changes values in columns in existing rows.