问:
handle mutliple dropdown menus
I have multiple buttons where a menu drops down when you click on one button AND all the other dropdown menus will be closed. I currently have 9 of those and corresponding 9 functions for that purpose:

```<code>function myFunction5() {
    document.getElementById("myDropdown1").classList.remove("show");
    document.getElementById("myDropdown2").classList.remove("show");
    document.getElementById("myDropdown3").classList.remove("show");
    document.getElementById("myDropdown4").classList.remove("show");
    document.getElementById("myDropdown5").classList.toggle("show");
    document.getElementById("myDropdown6").classList.remove("show");
    document.getElementById("myDropdown7").classList.remove("show");
    document.getElementById("myDropdown9").classList.remove("show"); }
</code>```

This opens dropdown menu 5 and closes all others.

I would like to have only one function for that instead of 9. How do i do that?

EDIT:

Complete code example:

```<code><!DOCTYPE html>
<html>
<head>
<style>
.dropbtn {
  background-color: #3498DB;
  color: white;
  padding: 16px;
  font-size: 16px;
  border: none;
  cursor: pointer;
}

.dropbtn:hover, .dropbtn:focus {
  background-color: #2980B9;
}

.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f1f1f1;
  min-width: 160px;
  overflow: auto;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.dropdown a:hover {background-color: #ddd;}

.show {display: block;}
</style>
</head>
<body>

<div class="dropdown">
  <button onclick="myFunction1()" class="dropbtn">Dropdown</button>
  <div id="myDropdown1" class="dropdown-content">
    <a href="#home">Home</a>
    <a href="#about">About</a>
    <a href="#contact">Contact</a>
  </div>
</div>

<div class="dropdown">
  <button onclick="myFunction2()" class="dropbtn">Dropdown</button>
  <div id="myDropdown2" class="dropdown-content">
    <a href="#home">Home</a>
    <a href="#about">About</a>
    <a href="#contact">Contact</a>
  </div>
</div>

<script>
function myFunction1() {
  document.getElementById("myDropdown1").classList.toggle("show");
  document.getElementById("myDropdown2").classList.remove("show");
}

function myFunction2() {
  document.getElementById("myDropdown1").classList.remove("show");
  document.getElementById("myDropdown2").classList.toggle("show");
}

</script>
</body>
</html>
</code>```

Imagine this 9 times...

答:
Try this:-</p>

```<code><script type="text/javascript">
    function manageDropdown(id)
    {
        var dropdown = document.getElementsByClassName('dropdown-content');
        for(i=0;i<dropdown.length;i++)
        {
             var innerId = dropdown[i].getAttribute('id');
             if (innerId == id) {
                dropdown[i].classList.remove("hide");
             } else {
                dropdown[i].classList.add("hide");
             }
        }
    }
</script>

<div class="dropdown">
  <button onclick="manageDropdown('myDropdown1')" class="dropbtn">Dropdown</button>
  <div id="myDropdown1" class="dropdown-content">
    <a href="#home">Home</a>
    <a href="#about">About</a>
    <a href="#contact">Contact</a>
  </div>
</div>

<div class="dropdown">
  <button onclick="manageDropdown('myDropdown2')" class="dropbtn">Dropdown</button>
  <div id="myDropdown2" class="dropdown-content hide">
    <a href="#home">Home</a>
    <a href="#about">About</a>
    <a href="#contact">Contact</a>
  </div>
</div>
</code>```

Title: handle mutliple dropdown menus

Body:
I have multiple buttons where a menu drops down when you click on one button AND all the other dropdown menus will be closed. I currently have 9 of those and corresponding 9 functions for that purpose:

function myFunction5() {
    document.getElementById("myDropdown1").classList.remove("show");
    document.getElementById("myDropdown2").classList.remove("show");
    document.getElementById("myDropdown3").classList.remove("show");
    document.getElementById("myDropdown4").classList.remove("show");
    document.getElementById("myDropdown5").classList.toggle("show");
    document.getElementById("myDropdown6").classList.remove("show");
    document.getElementById("myDropdown7").classList.remove("show");
    document.getElementById("myDropdown9").classList.remove("show"); }

This opens dropdown menu 5 and closes all others.

I would like to have only one function for that instead of 9. How do i do that?

EDIT:

Complete code example:

<!DOCTYPE html>

  <button onclick="myFunction1()" class="dropbtn">Dropdown</button>

    Home
    About
    Contact

  <button onclick="myFunction2()" class="dropbtn">Dropdown</button>

    Home
    About
    Contact

Imagine this 9 times...

Body:
Try this:-

<script type="text/javascript">
    function manageDropdown(id)
    {
        var dropdown = document.getElementsByClassName('dropdown-content');
        for(i=0;i<dropdown.length;i++)
        {
             var innerId = dropdown[i].getAttribute('id');
             if (innerId == id) {
                dropdown[i].classList.remove("hide");
             } else {
                dropdown[i].classList.add("hide");
             }
        }
    }
</script>

<div class="dropdown">
  <button onclick="manageDropdown('myDropdown1')" class="dropbtn">Dropdown</button>
  <div id="myDropdown1" class="dropdown-content">
    <a href="#home">Home</a>
    <a href="#about">About</a>
    <a href="#contact">Contact</a>
  </div>
</div>

<div class="dropdown">
  <button onclick="manageDropdown('myDropdown2')" class="dropbtn">Dropdown</button>
  <div id="myDropdown2" class="dropdown-content hide">
    <a href="#home">Home</a>
    <a href="#about">About</a>
    <a href="#contact">Contact</a>
  </div>
</div>


来源: stackexchange

问:
DStream to Rdd in Spark-Straming
I have a DStream[String,String] and I need to convert it to RDD[String,String]. Is there any way to do it? I need to do using Scala language.

Thanks in advance!!

答:
A DStream is a discretized sequence of RDDs. Take a look to the direct stream API.

Having your DStream,with the forEach function you can apply transformations for each RDD:

```<code>val yourStream: DStream[String] = //...

yourStream.forEachRDD{ rdd =>
   // your rdd transformations...
}
</code>```

You can take a look to examples here

ContentLicense: CC BY-SA 4.0

Title: DStream to Rdd in Spark-Straming

Body:
A DStream is a discretized sequence of RDDs. Take a look to the direct stream API.

Having your DStream,with the forEach function you can apply transformations for each RDD:

val yourStream: DStream[String] = //...

yourStream.forEachRDD{ rdd =>
   // your rdd transformations...
}

You can take a look to examples here


问:
Converter works for RequestParameter but not for RequestBody field
I have the following converter:

```<code>@Component
public class CountryEnumConverter implements Converter<String, CountryEnum> {

    @Override
    public CountryEnum convert(String country) {
        CountryEnum countryEnum = CountryEnum.getBySign(country);

        if (countryEnum == null) {
            throw new IllegalArgumentException(country + " - Country is not supported!");
        }

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

Registered it is invoked when used for RequestParam

```<code>@GetMapping(value = RestApiEndpoints.RESULTS, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResultDto> getResults(
        Principal principal,
        @RequestParam CountryEnum country) {
    ....
}
</code>```

But this converter is never invoked when used for field in the RequstBody:

```<code>@GetMapping(value = RestApiEndpoints.RESULTS, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResultDto> getResults(
        Principal principal,
        @RequestBody MyBody myBody) {
    ....
}
</code>```

```<code>public class MyBody {

    @NotNull
    private CountryEnum country;

    public MyBody() {
    }

    public CountryEnum getCountry() {
        return country;
    }

    public void setCountry(CountryEnum country) {
        this.country = country;
    }

}
</code>```

答:
I found out that if I add the following code to my CountryEnum will do the trick.

```<code>@JsonCreator
public static CountryEnum fromString(String value) {
    CountryEnumConverter converter = new CountryEnumConverter();
    return converter.convert(value);
}
</code>```

Body:
I have the following converter:

@Component
public class CountryEnumConverter implements Converter<String, CountryEnum> {

    @Override
    public CountryEnum convert(String country) {
        CountryEnum countryEnum = CountryEnum.getBySign(country);

        if (countryEnum == null) {
            throw new IllegalArgumentException(country + " - Country is not supported!");
        }

        return countryEnum;
    }
}

Registered it is invoked when used for RequestParam

@GetMapping(value = RestApiEndpoints.RESULTS, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResultDto> getResults(
        Principal principal,
        @RequestParam CountryEnum country) {
    ....
}

But this converter is never invoked when used for field in the RequstBody:

@GetMapping(value = RestApiEndpoints.RESULTS, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResultDto> getResults(
        Principal principal,
        @RequestBody MyBody myBody) {
    ....
}

public class MyBody {

    @NotNull
    private CountryEnum country;

    public MyBody() {
    }

    public CountryEnum getCountry() {
        return country;
    }

    public void setCountry(CountryEnum country) {
        this.country = country;
    }

}

Body:
I found out that if I add the following code to my CountryEnum will do the trick.

@JsonCreator
public static CountryEnum fromString(String value) {
    CountryEnumConverter converter = new CountryEnumConverter();
    return converter.convert(value);
}


问:
Deserialize subclasses with Jackson by parent class field value
I have a parent class:

```<code>open class NetworkMessage(var type: NetworkMessageType)
</code>```

and a bunch of it's subclasses, like

```<code>class ConnectionAcceptedResponseMessage(
    val accepted: Boolean,
    val uid: String
) : NetworkMessage(NetworkMessageType.CONNECTION_ACCEPTED)
</code>```

so every message type is clearly determined by parent class field value. Is there any way to deserialize concrete subclass using only annotations and without using treeNode?

答:
In Java, you can do something like this on the parent class:

```<code>@JsonTypeInfo(
    use = JsonTypeInfo.Id.NAME,
    include = JsonTypeInfo.As.EXISTING_PROPERTY,
    property = "type"
)
@JsonSubTypes({
        @JsonSubTypes.Type(value = ConnectionAcceptedResponseMessage.class, name = "CONNECTION_ACCEPTED"),
        @JsonSubTypes.Type(value = OtherResponseMessage.class, name = "OTHER")
})
</code>```

I guess in Kotlin this will be similar.

Body:
I have a parent class:

open class NetworkMessage(var type: NetworkMessageType)

and a bunch of it's subclasses, like

class ConnectionAcceptedResponseMessage(
    val accepted: Boolean,
    val uid: String
) : NetworkMessage(NetworkMessageType.CONNECTION_ACCEPTED)

so every message type is clearly determined by parent class field value. Is there any way to deserialize concrete subclass using only annotations and without using treeNode?

Body:
In Java, you can do something like this on the parent class:

@JsonTypeInfo(
    use = JsonTypeInfo.Id.NAME,
    include = JsonTypeInfo.As.EXISTING_PROPERTY,
    property = "type"
)
@JsonSubTypes({
        @JsonSubTypes.Type(value = ConnectionAcceptedResponseMessage.class, name = "CONNECTION_ACCEPTED"),
        @JsonSubTypes.Type(value = OtherResponseMessage.class, name = "OTHER")
})

I guess in Kotlin this will be similar.


问:
replace all odd values in vector with coresponing value from new vector
Given following vectors:

```<code>std::vector<int> foo{1,2,3,4,5,6,7};
std::vector<int> bar{10,20,30,40,50,60,70};
</code>```

In the end I want foo to contain values { 10, 2, 30, 4, 50, 6, 70 } meaning replacing all odd values.

I've tried the algorithm std::replace_if, but how to access the bars corresponding value?

```<code>// replace_copy_if example
#include <iostream>     // std::cout
#include <algorithm>    // std::replace_copy_if
#include <vector>       // std::vector

bool IsOdd (int i) { return ((i%2)==1); }

int main () {
  std::vector<int> foo{1,2,3,4,5,6,7};
  std::vector<int> bar{10,20,30,40,50,60,70};

  std::replace_if (foo.begin(), foo.end(), IsOdd, 0);

  std::cout << "foo contains:";
  for (auto i: foo){ std::cout << ' ' << i; }
  std::cout << '\n';

  return 0;
}

// output         : foo contains: 0 2 0 4 0 6 0
// desired output : foo contains: 10 2 30 4 50 6 70
</code>```

答:
Adding to the answers here you can make a function of your own:

Demo: https://godbolt.org/z/yf3jYx

```<code>void IsOdd (const std::vector<int>& a, std::vector<int>& b) {
    for(size_t i = 0; i < a.size() && i < b.size(); i++){
        if(b[i] % 2 == 1)
            b[i] = a[i];
    }
}
</code>```

and call it in main:

```<code>IsOdd(bar, foo);
</code>```

Body:
Given following vectors:

std::vector<int> foo{1,2,3,4,5,6,7};
std::vector<int> bar{10,20,30,40,50,60,70};

In the end I want foo to contain values { 10, 2, 30, 4, 50, 6, 70 } meaning replacing all odd values.

I've tried the algorithm std::replace_if, but how to access the bars corresponding value?

// replace_copy_if example
#include <iostream>     // std::cout
#include <algorithm>    // std::replace_copy_if
#include <vector>       // std::vector

bool IsOdd (int i) { return ((i%2)==1); }

int main () {
  std::vector<int> foo{1,2,3,4,5,6,7};
  std::vector<int> bar{10,20,30,40,50,60,70};

  std::replace_if (foo.begin(), foo.end(), IsOdd, 0);

  std::cout << "foo contains:";
  for (auto i: foo){ std::cout << ' ' << i; }
  std::cout << '\n';

  return 0;
}

// output         : foo contains: 0 2 0 4 0 6 0
// desired output : foo contains: 10 2 30 4 50 6 70

Body:
Adding to the answers here you can make a function of your own:

Demo: https://godbolt.org/z/yf3jYx

void IsOdd (const std::vector<int>& a, std::vector<int>& b) {
    for(size_t i = 0; i < a.size() && i < b.size(); i++){
        if(b[i] % 2 == 1)
            b[i] = a[i];
    }
}

and call it in main:

IsOdd(bar, foo);


问:
Uninstall old version of Microsoft.AnalysisServices.AdomdClient from GAC
I need to uninstall an old version of this DLL from the GAC in order to run an installer, but I receive an "Access Denied" error. Does anybody have an idea on how I can remove this DLL?</p>

答:
The command you're looking for is:

```<code>gacutil.exe /u <assemblyname>
</code>```

The documentation for gacutil.exe is available here. You obviously will need the SDK for this, gacutil.exe is no longer installed with the .NET Framework.

Also, make sure that you're running the correct version of gacutil.exe. It should match the version of the assembly that you're trying to uninstall.

Finally, make sure that you're running with administrative privileges. You may need to start an elevated command prompt to execute the command.

ContentLicense: CC BY-SA 3.0

Body:
The command you're looking for is:

gacutil.exe /u <assemblyname>

The documentation for gacutil.exe is available here. You obviously will need the SDK for this, gacutil.exe is no longer installed with the .NET Framework.

Also, make sure that you're running the correct version of gacutil.exe. It should match the version of the assembly that you're trying to uninstall.

Finally, make sure that you're running with administrative privileges. You may need to start an elevated command prompt to execute the command.


问:
Optaplanner with Drools score director -- why not empty solution
I've been looking at the Cloud Balancing demo of OptaPlanner with Drools implementation.

There are 2 rules for this demo (there actually are 4, but 3 of those rules are of the same logic) --

```<code>rule "requiredCpuPowerTotal"
when
    $computer : CloudComputer($cpuPower : cpuPower)
    accumulate(
        CloudProcess(
            computer == $computer,
            $requiredCpuPower : requiredCpuPower);
        $requiredCpuPowerTotal : sum($requiredCpuPower);
        $requiredCpuPowerTotal > $cpuPower
    )
then
    scoreHolder.addHardConstraintMatch(kcontext, $cpuPower - $requiredCpuPowerTotal);
end
</code>```

and

```<code>rule "computerCost"  // "Minimize the total maintenance cost."
when
    $computer : CloudComputer($cost : cost)
    exists CloudProcess(computer == $computer)
then
    scoreHolder.addSoftConstraintMatch(kcontext, - $cost);
end
</code>```

Going by these rules, the optimum solution is NOT to assign ANY of the processes to anyone of the computers. This will satisfy the first rule perfectly-- the cpuPower capacity is never exhausted, let alone gone over.
And no computers will be used and thus no maintenance cost.

But the system finds a solution with these 2 rules only-- suboptimizes to assign the processes there are to the computers.

what am i missing, where?

Where is OptaPlanner/Drools told to allocate as many processes as possible?

new to Drools. excuse the naive question, if it is.

//--- UPDATE

the @PlanningEntity() instances to be initialized and put on @PlanningSolution() is the key I think. either explicitly in the code, or by a Construction Heuristic configuration as @yurloc suggested, or .. {don't know what else here if any}

答:
https://docs.optaplanner.org/latest/optaplanner-docs/html_single/#localSearchOverview:

Local Search needs to start from an initialized solution, therefore it’s usually required to configure a Construction Heuristic phase before it.

By default, Local Search expects that all entities are initialized and is not allowed to uninitialize them when making changes on the solution. The answer to your last question is that the Construction Heuristic phase assigns a computer to each process even though it actually worsens the score. The Local Search will improve the score in the next phase.

Thanks to this default behavior you don't have to write rules that penalize processes that haven't been assigned any computer.

For completeness, note that you can make planning variables nullable but that is an advanced topic. Nullable planning variables are usually only useful for over-constrained planning.

Body:
I've been looking at the Cloud Balancing demo of OptaPlanner with Drools implementation.

There are 2 rules for this demo (there actually are 4, but 3 of those rules are of the same logic) --

rule "requiredCpuPowerTotal"
when
    $computer : CloudComputer($cpuPower : cpuPower)
    accumulate(
        CloudProcess(
            computer == $computer,
            $requiredCpuPower : requiredCpuPower);
        $requiredCpuPowerTotal : sum($requiredCpuPower);
        $requiredCpuPowerTotal > $cpuPower
    )
then
    scoreHolder.addHardConstraintMatch(kcontext, $cpuPower - $requiredCpuPowerTotal);
end

and

rule "computerCost"  // "Minimize the total maintenance cost."
when
    $computer : CloudComputer($cost : cost)
    exists CloudProcess(computer == $computer)
then
    scoreHolder.addSoftConstraintMatch(kcontext, - $cost);
end

Going by these rules, the optimum solution is NOT to assign ANY of the processes to anyone of the computers. This will satisfy the first rule perfectly-- the cpuPower capacity is never exhausted, let alone gone over.
And no computers will be used and thus no maintenance cost.

But the system finds a solution with these 2 rules only-- suboptimizes to assign the processes there are to the computers.

what am i missing, where?

Where is OptaPlanner/Drools told to allocate as many processes as possible?

new to Drools. excuse the naive question, if it is.

//--- UPDATE

the @PlanningEntity() instances to be initialized and put on @PlanningSolution() is the key I think. either explicitly in the code, or by a Construction Heuristic configuration as @yurloc suggested, or .. {don't know what else here if any}


问:
"maxContains" limit not working for JSON schema
How do I check if in the following JSON, the property isCorrect has value truestrictly once. Think of it as a multiple choice question with only one answer, so there can be many elements in the array but answer can only be true once in all the elements.

```<code>  "answers": [
    {
      "id": 1,
      "text": "choice1",
      "isCorrect": true
    },
    {
      "id": 1,
      "text": "choice2",
      "isCorrect": true
    },
    {
      "id": 1,
      "text": "choice3",
      "isCorrect": false
    },
    {
      "id": 1,
      "text": "choice4",
      "isCorrect": false
    }
  ]
}
</code>```

I used containsto validate if at least one of the elements satisfies the condition, but it validates even if there are more than 1 elements with isCorrectbeing true, so I used maxContainsbut it doesn't work.

My schema:

```<code>{
  "definitions": {},
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "http://eg.com/schema2.json",
  "type": "object",
  "title": "Example",
  "required": ["answers"],
  "properties": {
    "answers": {
      "type": "array",
      "contains": {
        "type": "object",
        "properties": {
          "id": {
            "type": "integer"
          },
          "text": {
            "type": "string"
          },
          "isCorrect": {
            "type": "boolean",
            "enum": [true]
          }
        }
      },
      "maxContains": 1,
      "items": {
        "type": "object",
        "properties": {
          "id": {
            "type": "integer"
          },
          "text": {
            "type": "string"
          },
          "isCorrect": {
            "type": "boolean"
          }
        }
      }
    }
  }
}
</code>```

This instance should not be validated since it has true value occurring twice for isCorrect and the schema mentions maxContains as 1, however it is not working. What am I doing wrong, is the placement of maxContains wrong? Any help is appreciated!

答:
minContains and maxContains were added in draft 2019-09.
They are not part of draft-07, and unknown keywords are ignored.

At the time of writing, draft 2019-09 is quite new, and only has one known implementation.

For now, you'll have to either implement the keyword yourself as an extension (if the library you're using supports such things), or write additional business logic code which happens after JSON Schema validation.

Body:
How do I check if in the following JSON, the property isCorrect has value truestrictly once. Think of it as a multiple choice question with only one answer, so there can be many elements in the array but answer can only be true once in all the elements.

  "answers": [
    {
      "id": 1,
      "text": "choice1",
      "isCorrect": true
    },
    {
      "id": 1,
      "text": "choice2",
      "isCorrect": true
    },
    {
      "id": 1,
      "text": "choice3",
      "isCorrect": false
    },
    {
      "id": 1,
      "text": "choice4",
      "isCorrect": false
    }
  ]
}

I used containsto validate if at least one of the elements satisfies the condition, but it validates even if there are more than 1 elements with isCorrectbeing true, so I used maxContainsbut it doesn't work.

My schema:

{
  "definitions": {},
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "http://eg.com/schema2.json",
  "type": "object",
  "title": "Example",
  "required": ["answers"],
  "properties": {
    "answers": {
      "type": "array",
      "contains": {
        "type": "object",
        "properties": {
          "id": {
            "type": "integer"
          },
          "text": {
            "type": "string"
          },
          "isCorrect": {
            "type": "boolean",
            "enum": [true]
          }
        }
      },
      "maxContains": 1,
      "items": {
        "type": "object",
        "properties": {
          "id": {
            "type": "integer"
          },
          "text": {
            "type": "string"
          },
          "isCorrect": {
            "type": "boolean"
          }
        }
      }
    }
  }
}

This instance should not be validated since it has true value occurring twice for isCorrect and the schema mentions maxContains as 1, however it is not working. What am I doing wrong, is the placement of maxContains wrong? Any help is appreciated!


问:
How can I use Jupyter Notebook on macOS Catalina (without anaconda)?
I've tried since yesterday to launch anaconda after I install the new version of macOS Catalina (before I understand that it is a beta version), and I finally find a way. But unfortunately, I can not launch Jupiter notebook from terminal because apparently it is not installed and it doesn't want to neither. How can I fix that ? </p>

答:
Try installing Jupyter with Homebrew, this method has worked for me.

Use the following command in Terminal:

brew install jupyter

Then launch a Jupyter notebook with:

jupyter notebook

This should also work for JupyterLab:

jupyter lab

And in case you don't have Homebrew installed, start with the following command:

```<code>/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
</code>```

Body:
Try installing Jupyter with Homebrew, this method has worked for me.

Use the following command in Terminal:

brew install jupyter

Then launch a Jupyter notebook with:

jupyter notebook

This should also work for JupyterLab:

jupyter lab

And in case you don't have Homebrew installed, start with the following command:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"


问:
Parameter with that position [1] did not exist after moving the native query into a NamedNativeQuery?
Why do I get the following error when I move a JPA native query no longer work when I move it into a named one?

```<code>java.lang.IllegalArgumentException: Parameter with that position [1] did not exist
</code>```

Not working query:

```<code>@NamedNativeQuery(
                name = Test.TEST,
                query = "SELECT * FROM test_table where id = ?",

Query q = entityManager.createNativeQuery(Test.TEST);
q.setParameter(1, 362L);
List<Object> result = q.getResultList();
</code>```

This works:

```<code>Query q = entityManager.createNativeQuery("SELECT * FROM test_table where id = ?");
q.setParameter(1, 362L);
List<Object> result = q.getResultList();
</code>```

答:
If you want to move you are native query in to named one.
-Then you will have to do something like below.

Considering you are example i have one class by name Test and i have one native query which i would like to convert it into a named one let name it as "testQuery"

so you are TestRepository looks like below which contains one method by same name of named query and further we can call that by its name so it will point your namedQuery(name-testQuery).

Test testQuery(@param("id")int id)

And below is your namednative query and you can place it above the entity

@NamedNativeQuery(
            name = Test.testQuery,
            query = "SELECT * FROM test_table where id = :id")

-Hop it will be helpful.

Body:
Why do I get the following error when I move a JPA native query no longer work when I move it into a named one?

java.lang.IllegalArgumentException: Parameter with that position [1] did not exist

Not working query:

@NamedNativeQuery(
                name = Test.TEST,
                query = "SELECT * FROM test_table where id = ?",

Query q = entityManager.createNativeQuery(Test.TEST);
q.setParameter(1, 362L);
List<Object> result = q.getResultList();

This works:

Query q = entityManager.createNativeQuery("SELECT * FROM test_table where id = ?");
q.setParameter(1, 362L);
List<Object> result = q.getResultList();


问:
Change color of a background on click to a multiple choice of color us with jquery
I am trying to add multiple color choices? How can I do it with HTML and CSS?
i dont know how to correctly add multiple color choice
here are my codes

$(document).ready(function() {
      $('#btn').click(function() {
        $('body').css('background', '#ff0000', '#80ff33');
      });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  height: ;
  background: #D8D8D8;
}

.text {
  color: #686868;
  font-family: arial;
  font-size: 2em;
  text-align: center;
  margin-top: 50px;
  margin-bottom: 20px;
}

#btn {
  margin-left: 550px;
  width: 200px;
  height: 100px;
  font-size: 2em;
  border-radius: 10px;
  background: #ffffff;
}

#btn:hover {
  background: #ff0000;
  background: #80ff33;
  color: #ffffff;
}</code>```

  CLICK THE BUTTON TO
 CHANGE THE BACKGROUND!

<button id="btn">CLICK ME!</button>```

答:
You did not close properly your function

```<code>$(document).ready(function() {
  $('#btn').click(function() {
    $('body').css('background', '#ff0000', '#80ff33');
  });
});
</code>```

demo :

$(document).ready(function() {
  $('#btn').click(function() {
    $('body').css('background', '#ff0000', '#80ff33');

  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    height: ;
    background: #D8D8D8;
}

.text {
    color: #686868;
    font-family: arial;
    font-size: 2em;
    text-align: center;
    margin-top: 50px;
    margin-bottom: 20px;
}

#btn {
    margin-left: 550px;
    width: 200px;
    height: 100px;
    font-size: 2em;
    border-radius: 10px;
    background: #ffffff;
}

#btn:hover {
    background: #ff0000;
    background: #80ff33 ;
    color: #ffffff;
}</code>```

  CLICK THE BUTTON TO
 CHANGE THE BACKGROUND!

<button id="btn">CLICK ME!</button>```
</div>
</div>
</p>

<hr>

<p><strong>you may use a few methods, one is to update a css custom property</strong> </p>

<p>Possible example from a <code>data-attribute</code> , so you can easily add as many button colors you wish:</p>

<ul>
<li>javascript version</li>
</ul>

<p>DEMO or snippet below </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>for (let e of document.querySelectorAll("button")) {
  cust = e.dataset.bgcolor;
  e.style.background = cust;
  e.textContent = cust;
  e.addEventListener("click", function() {
    cust = e.dataset.bgcolor;
    document.documentElement.style.setProperty("--bgColor", cust);

  });
}</code>```

html {
  background: #D8D8D8;
}

body {
  margin: 0;
  height: 100vh;
  background: var(--bgColor);
}

.text {
  color: #686868;
  font-family: arial;
  font-size: 2em;
  text-align: center;
  margin-top: 50px;
  margin-bottom: 20px;
}

.grid {
  display: grid;
  width: 200px;
  grid-template-columns: repeat(2, 1fr);
  margin: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="text">
  CLICK THE BUTTON TO<br> CHANGE THE BACKGROUND!
</section>
<div class="grid">
  <button data-bgcolor="orange">bgcolor:</button>
  <button data-bgcolor="white">bgcolor:</button>
  <button data-bgcolor="lightblue">bgcolor:</button>
  <button data-bgcolor="lightgreen">bgcolor:</button>
  <button data-bgcolor="brown">bgcolor:</button></code>```

jQuery equivalent snippet :

$("button").each(function() {
  bg = $(this).data("bgcolor");
  $(this).css("background", bg);
  $(this).html(bg);
  $(this).click(function() {
    bg = $(this).data("bgcolor");
    $("html").css("--bgColor", bg);
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html {
  background: #D8D8D8;
}

body {
  margin: 0;
  height: 100vh;
  background: var(--bgColor);
}

.text {
  color: #686868;
  font-family: arial;
  font-size: 2em;
  text-align: center;
  margin-top: 50px;
  margin-bottom: 20px;
}

.grid {
  display: grid;
  width: 200px;
  grid-template-columns: repeat(2, 1fr);
  margin: auto;
}</code>```

  CLICK THE BUTTON TO
 CHANGE THE BACKGROUND!

  <button data-bgcolor="orange">bgcolor:</button>
  <button data-bgcolor="white">bgcolor:</button>
  <button data-bgcolor="lightblue">bgcolor:</button>
  <button data-bgcolor="lightgreen">bgcolor:</button>
  <button data-bgcolor="brown">bgcolor:</button>```

Body:
I am trying to add multiple color choices? How can I do it with HTML and CSS?
i dont know how to correctly add multiple color choice
here are my codes

$(document).ready(function() {
      $('#btn').click(function() {
        $('body').css('background', '#ff0000', '#80ff33');
      });

body {
  height: ;
  background: #D8D8D8;
}

.text {
  color: #686868;
  font-family: arial;
  font-size: 2em;
  text-align: center;
  margin-top: 50px;
  margin-bottom: 20px;
}

#btn {
  margin-left: 550px;
  width: 200px;
  height: 100px;
  font-size: 2em;
  border-radius: 10px;
  background: #ffffff;
}

#btn:hover {
  background: #ff0000;
  background: #80ff33;
  color: #ffffff;
}

  CLICK THE BUTTON TO
 CHANGE THE BACKGROUND!

<button id="btn">CLICK ME!</button>

Body:
You did not close properly your function

$(document).ready(function() {
  $('#btn').click(function() {
    $('body').css('background', '#ff0000', '#80ff33');
  });
});

demo :

$(document).ready(function() {
  $('#btn').click(function() {
    $('body').css('background', '#ff0000', '#80ff33');

  });

});

body {
    height: ;
    background: #D8D8D8;
}

.text {
    color: #686868;
    font-family: arial;
    font-size: 2em;
    text-align: center;
    margin-top: 50px;
    margin-bottom: 20px;
}

#btn {
    margin-left: 550px;
    width: 200px;
    height: 100px;
    font-size: 2em;
    border-radius: 10px;
    background: #ffffff;
}

#btn:hover {
    background: #ff0000;
    background: #80ff33 ;
    color: #ffffff;
}

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<section class="text">
  CLICK THE BUTTON TO<br> CHANGE THE BACKGROUND!
</section>
<button id="btn">CLICK ME!</button>

you may use a few methods, one is to update a css custom property

Possible example from a data-attribute , so you can easily add as many button colors you wish:

javascript version

DEMO or snippet below

for (let e of document.querySelectorAll("button")) {
  cust = e.dataset.bgcolor;
  e.style.background = cust;
  e.textContent = cust;
  e.addEventListener("click", function() {
    cust = e.dataset.bgcolor;
    document.documentElement.style.setProperty("--bgColor", cust);

  });
}

html {
  background: #D8D8D8;
}

body {
  margin: 0;
  height: 100vh;
  background: var(--bgColor);
}

.text {
  color: #686868;
  font-family: arial;
  font-size: 2em;
  text-align: center;
  margin-top: 50px;
  margin-bottom: 20px;
}

.grid {
  display: grid;
  width: 200px;
  grid-template-columns: repeat(2, 1fr);
  margin: auto;
}

<section class="text">
  CLICK THE BUTTON TO<br> CHANGE THE BACKGROUND!
</section>
<div class="grid">
  <button data-bgcolor="orange">bgcolor:</button>
  <button data-bgcolor="white">bgcolor:</button>
  <button data-bgcolor="lightblue">bgcolor:</button>
  <button data-bgcolor="lightgreen">bgcolor:</button>
  <button data-bgcolor="brown">bgcolor:</button>

jQuery equivalent snippet :

$("button").each(function() {
  bg = $(this).data("bgcolor");
  $(this).css("background", bg);
  $(this).html(bg);
  $(this).click(function() {
    bg = $(this).data("bgcolor");
    $("html").css("--bgColor", bg);
  });
});

html {
  background: #D8D8D8;
}

body {
  margin: 0;
  height: 100vh;
  background: var(--bgColor);
}

.text {
  color: #686868;
  font-family: arial;
  font-size: 2em;
  text-align: center;
  margin-top: 50px;
  margin-bottom: 20px;
}

.grid {
  display: grid;
  width: 200px;
  grid-template-columns: repeat(2, 1fr);
  margin: auto;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="text">
  CLICK THE BUTTON TO<br> CHANGE THE BACKGROUND!
</section>
<div class="grid">
  <button data-bgcolor="orange">bgcolor:</button>
  <button data-bgcolor="white">bgcolor:</button>
  <button data-bgcolor="lightblue">bgcolor:</button>
  <button data-bgcolor="lightgreen">bgcolor:</button>
  <button data-bgcolor="brown">bgcolor:</button>


问:
How to execute a loop with sequential summation?
I have an array with this loop:

var arr = [5, 4, 9, 6, 4];

var sum = 0;

arr.forEach(function(item) {
  sum += parseInt(item);
  console.log(sum)
});```
</div>
</div>
</p>

<p>At the moment, I get this result:</p>

```5
9
18
24
28
```

<p>But how to make sure that the result always starts with 0 and ends with the penultimate digit, i.e. it should look like this:</p>

```0
5
9
18
24
```

答:
This has already been answered but it's worth mentioning that the forEach api actually has 3 parameters not just 1 and you can use that, here's an example:

```<code>var arr = [5, 4, 9, 6, 4];

var sum = 0;

arr.forEach((item,i)=>{
    //"item" is the item
    //"i" is the current index
    //the third argument is the whole array
    sum += parseInt(item);
    console.log(sum);//as pointed out by @Jacob you can just move this line up
    if(i === arr.length+1) return; //but you can also just stop the iteration on the exact index you want like this
});
</code>```

This is not the best solution for your needs, as you're using a sum operation every iteration to check the index, but it's more flexible and it's good to know the api offers the current index.

Body:
I have an array with this loop:

var arr = [5, 4, 9, 6, 4];

var sum = 0;

arr.forEach(function(item) {
  sum += parseInt(item);
  console.log(sum)
});

At the moment, I get this result:

5
9
18
24
28

But how to make sure that the result always starts with 0 and ends with the penultimate digit, i.e. it should look like this:

0
5
9
18
24

Body:
This has already been answered but it's worth mentioning that the forEach api actually has 3 parameters not just 1 and you can use that, here's an example:

var arr = [5, 4, 9, 6, 4];

var sum = 0;

arr.forEach((item,i)=>{
    //"item" is the item
    //"i" is the current index
    //the third argument is the whole array
    sum += parseInt(item);
    console.log(sum);//as pointed out by @Jacob you can just move this line up
    if(i === arr.length+1) return; //but you can also just stop the iteration on the exact index you want like this
});

This is not the best solution for your needs, as you're using a sum operation every iteration to check the index, but it's more flexible and it's good to know the api offers the current index.


问:
Listview background drawing problem C# Winform
I have a little problem with a Listview.

I can load it with listview items fine, but when I set the background color it doesn't draw the color all the way to the left side of the row [The listViewItems are loaded with ListViewSubItems to make a grid view, only the first column shows the error].  There is a a narrow strip that doesn't paint.  The width of that strip is approximately the same as a row header would be if I had a row header.

If you have a thought on what can be done to make the background draw I'd love to hear it.

Now just to try a new idea, I'm offering a ten vote bounty for the first solution that still has me using this awful construct of a mess of a pseudo grid view.  [I love legacy code.]

Edit:

Here is a sample that exhibits the problem.

```<code>public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        ListView lv = new ListView();

        lv.Dock = System.Windows.Forms.DockStyle.Fill;
        lv.FullRowSelect = true;
        lv.GridLines = true;
        lv.HideSelection = false;
        lv.Location = new System.Drawing.Point(0, 0);
        lv.TabIndex = 0;
        lv.View = System.Windows.Forms.View.Details;
        lv.AllowColumnReorder = true;

        this.Controls.Add(lv);

        lv.MultiSelect = true;

        ColumnHeader ch = new ColumnHeader();
        ch.Name = "Foo";
        ch.Text = "Foo";
        ch.Width = 40;
        ch.TextAlign = HorizontalAlignment.Left;

        lv.Columns.Add(ch);

        ColumnHeader ch2 = new ColumnHeader();
        ch.Name = "Bar";
        ch.Text = "Bar";
        ch.Width = 40;
        ch.TextAlign = HorizontalAlignment.Left;

        lv.Columns.Add(ch2);

        lv.BeginUpdate();

        for (int i = 0; i < 3; i++)
        {

            ListViewItem lvi = new ListViewItem("1", "2");

            lvi.BackColor = Color.Black;
            lvi.ForeColor = Color.White;

            lv.Items.Add(lvi);
        }
        lv.EndUpdate();
    }
}
</code>```

答:
(Prior to the Edit...)

I've just tried setting the BackColor on a System.Windows.Forms.ListView, and the color is applied across the control just fine (with and without images).

Are you doing any Custom Painting at all?

OwnerDisplayName: Dan Blair

ContentLicense: CC BY-SA 2.5

Body:
I have a little problem with a Listview.

I can load it with listview items fine, but when I set the background color it doesn't draw the color all the way to the left side of the row [The listViewItems are loaded with ListViewSubItems to make a grid view, only the first column shows the error].  There is a a narrow strip that doesn't paint.  The width of that strip is approximately the same as a row header would be if I had a row header.

If you have a thought on what can be done to make the background draw I'd love to hear it.

Now just to try a new idea, I'm offering a ten vote bounty for the first solution that still has me using this awful construct of a mess of a pseudo grid view.  [I love legacy code.]

Edit:

Here is a sample that exhibits the problem.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        ListView lv = new ListView();

        lv.Dock = System.Windows.Forms.DockStyle.Fill;
        lv.FullRowSelect = true;
        lv.GridLines = true;
        lv.HideSelection = false;
        lv.Location = new System.Drawing.Point(0, 0);
        lv.TabIndex = 0;
        lv.View = System.Windows.Forms.View.Details;
        lv.AllowColumnReorder = true;

        this.Controls.Add(lv);

        lv.MultiSelect = true;

        ColumnHeader ch = new ColumnHeader();
        ch.Name = "Foo";
        ch.Text = "Foo";
        ch.Width = 40;
        ch.TextAlign = HorizontalAlignment.Left;

        lv.Columns.Add(ch);

        ColumnHeader ch2 = new ColumnHeader();
        ch.Name = "Bar";
        ch.Text = "Bar";
        ch.Width = 40;
        ch.TextAlign = HorizontalAlignment.Left;

        lv.Columns.Add(ch2);

        lv.BeginUpdate();

        for (int i = 0; i < 3; i++)
        {

            ListViewItem lvi = new ListViewItem("1", "2");

            lvi.BackColor = Color.Black;
            lvi.ForeColor = Color.White;

            lv.Items.Add(lvi);
        }
        lv.EndUpdate();
    }
}

LastEditorDisplayName: Dan Blair

OwnerDisplayName: moobaa

LastEditorDisplayName: moobaa


问:
What caching model/framework with Websphere Spring Hibernate Oracle?
We are looking at implementing a caching framework for our application to help improve the overall performance of our site.

We are running on Websphere 6.1, Spring, Hibernate and Oracle.  The focus currently is on the static data or data that changes very little through out the day but is used a lot.

So any info would be great.  I have started my google search and reading but wanted to get a feel for what has worked for members of the community.  One of the things that we are interested in is the ability to have the system invalidate the cache when a change does happen in the underlining data.

Thanks

Update:

I came across an article on the IBM web site where it says that Hibernate's Cluster aware caches in conjunction with WebSphere Application Server has not been determined yet; therefore, is is not yet determined whether or not their use is supported.

Thoughts on that?  We are running in a clustered environment.

答:
One of the things that we are
  interested in is the ability to have
  the system invalidate the cache when a
  change does happen in the underlining
  data.

From what I can see, Hibernate doesn't actually do the above - from Hibernate's docs:

Be careful. Caches are never aware of
  changes made to the persistent store
  by another application (though they
  may be configured to regularly expire
  cached data).

Obviously what it means is that a cache doesn't have ESP, and can't tell if an app not in the cluster has called straight DML on the database - but I am guessing that what you want is an ability to expose a service for legacy apps to hook in and invalidate the cache when they do update that data. And there isn't, to my knowledge, a suggestion about how this might be done.

LastEditorDisplayName: cletus

OwnerDisplayName: The Last One


问:
Android studio do not show devices for flutter
I am new to Flutter and android studio, I followed the instructions of flutter.io ,  I created a blank app, and while I try to run I am unable to see the device lists. but it is available in device manager
Please see the screenshot.

答:
You've not run your device....
Under Actions Click the Run button......
The emulator will start and your problem solved..</p>


问:
appveyor matrix vs tox matrix
I've found many references to use tox and a CI server, like appveyor for Python testing. However, the dependency matrices have confused me. It seems redundant for me and I don't know why to use both, like it acts in several examples. (Appveyor's docs, or an example repo.)

I mean, I will list the same environment-settings under environment -> matrix in appveyor.yml as in envlist in the tox.ini.

Is it really redundant? Then why we use both matrices?

答: One matrix is for AppVeyor, another (well, it's the list of environments) is for tox. They are to some extend redundant but there is no way to avoid that redundancy because neither tox nor AppVeyor could read each other config files.

Title: appveyor matrix vs tox matrix


问:
Adding an arrow function to input field results an error
Here is a React class I'm working on:

```<code>import React from 'react';

export default class ExpenseForm extends React.Component {
    state = {
        title: ''
    };

    onTitleChange = (e) => {
        const title = e.target.value;
        this.setState(() => ({title}));
    };

    render() {
        return (
            <div>
                <form>
                    <input
                        type='text'
                        placeholder='title'
                        value={this.state.title}
                        onChange={(e) => this.setState(() => ({title: e.target.value}))}
                        required autoFocus/>
                    <textarea placeholder='Add a note for your expense'/>
                    <input type='number' placeholder='amount' required/>
                    <input type='submit' value='Add Expense'/>
                </form>
            </div>
        );
    }
}
</code>```

This throws an error Uncaught TypeError: Cannot read property 'value' of null when executing onChange.

But when I restructure inner js of onChange into a separate function onTitleChange and calling that function: onChange={this.onTitleChange}, it works perfectly. What could be the reason behind this behavior?

答:
That is because of React is utilizing event pooling and setState is a function executed in asynchronous context, so you observe them as nulls in the asynchronous setState callback.

You need to either persist event using e.persist() or save the value of event to variable, as in your method.

Body:
Here is a React class I'm working on:

import React from 'react';

export default class ExpenseForm extends React.Component {
    state = {
        title: ''
    };

    onTitleChange = (e) => {
        const title = e.target.value;
        this.setState(() => ({title}));
    };

    render() {
        return (

                <form>
                    <input
                        type='text'
                        placeholder='title'
                        value={this.state.title}
                        onChange={(e) => this.setState(() => ({title: e.target.value}))}
                        required autoFocus/>
                    <textarea placeholder='Add a note for your expense'/>
                    <input type='number' placeholder='amount' required/>
                    <input type='submit' value='Add Expense'/>
                </form>

        );
    }
}

This throws an error Uncaught TypeError: Cannot read property 'value' of null when executing onChange.

But when I restructure inner js of onChange into a separate function onTitleChange and calling that function: onChange={this.onTitleChange}, it works perfectly. What could be the reason behind this behavior?


问:
DAX sum filtered by multiple columns of related tables
I have a measure, which is being added to a table and a Card. The measure is used to show the total hours posted where Calls.[Sch Engineer]=Hours.Employee AND Calls.ProjID=Hours.ProjID

The value on each row of the table is correct. However the total value for this measure is incorrect in the table and also the Card, and I cant work out why.

So the measure is:

```<code>SchEngHrsOnly =
VAR main =
    MAX ( Calls[Sch Engineer] )
RETURN
    CALCULATE ( SUM ( 'Hours'[Hrs] ), Hours[Employee] = main )
</code>```

When I add this to a table visual I get the following - both Table total and Card value for measure are incorrect - they should be 163.50:

If I select a row in the table visual, then the Card visual shows a correct value, otherwise it shows an incorrect value:

My data model is:

My relationships are:

What I am looking to get is:

Also, please see here the PBIX file:

PBIX File

Can anyone help with this issue please?

答:
If you want SUM of MAX values, then go this way:

```<code>SumOfMaxes =
SUMX(
  VALUES( Hours[ProjID] ),
  CALCULATE( MAX( Hours[Hrs]) )
)
</code>```

It produces:

You might be also interested in:

DAX ALLEXCEPT to sum by category of multiple dimension tables

DAX Median of category sums

Edit

After your explanations I see that you want filtered sum.

```<code>FilteredSum =
CALCULATE (
    SUM ( Hours[Hrs] ),
    FILTER (
        Hours,
        Hours[Employee] = RELATED ( Calls[Sch Engineer] )
            && Hours[ProjID] = RELATED ( Calls[Proj ID] )
    )
)
</code>```

https://www.sqlbi.com/blog/marco/2010/02/09/how-to-relate-tables-in-dax-without-using-relationships/

Body:
I have a measure, which is being added to a table and a Card. The measure is used to show the total hours posted where Calls.[Sch Engineer]=Hours.Employee AND Calls.ProjID=Hours.ProjID

The value on each row of the table is correct. However the total value for this measure is incorrect in the table and also the Card, and I cant work out why.

So the measure is:

SchEngHrsOnly =
VAR main =
    MAX ( Calls[Sch Engineer] )
RETURN
    CALCULATE ( SUM ( 'Hours'[Hrs] ), Hours[Employee] = main )

When I add this to a table visual I get the following - both Table total and Card value for measure are incorrect - they should be 163.50:

If I select a row in the table visual, then the Card visual shows a correct value, otherwise it shows an incorrect value:

My data model is:

My relationships are:

What I am looking to get is:

Also, please see here the PBIX file:

PBIX File

Can anyone help with this issue please?

Body:
If you want SUM of MAX values, then go this way:

SumOfMaxes =
SUMX(
  VALUES( Hours[ProjID] ),
  CALCULATE( MAX( Hours[Hrs]) )
)

It produces:

You might be also interested in:

DAX ALLEXCEPT to sum by category of multiple dimension tables

DAX Median of category sums

Edit

After your explanations I see that you want filtered sum.

FilteredSum =
CALCULATE (
    SUM ( Hours[Hrs] ),
    FILTER (
        Hours,
        Hours[Employee] = RELATED ( Calls[Sch Engineer] )
            && Hours[ProjID] = RELATED ( Calls[Proj ID] )
    )
)

https://www.sqlbi.com/blog/marco/2010/02/09/how-to-relate-tables-in-dax-without-using-relationships/


答:
Here you assigned onchange event as onChange={(e) => this.setState(() => ({title: e.target.value}))}, here e.target.value will not work, because its inside the setState() scope.

On expanding your function, we will get

```<code>function(e){
   this.setState(function(){
     return {
       title: e.target.value
     }
   })
}
</code>```

Here there is no e in function inside setSate(), so e.target.value will be error;

Since you dont want to compare with previous value and only need to set the value to title, you can use like

```<code>onChange={(e) => this.setState({title: e.target.value})}
</code>```

There is no need for an extra function inside setState

Title: Adding an arrow function to input field results an error

Body:
Here you assigned onchange event as onChange={(e) => this.setState(() => ({title: e.target.value}))}, here e.target.value will not work, because its inside the setState() scope.

On expanding your function, we will get

function(e){
   this.setState(function(){
     return {
       title: e.target.value
     }
   })
}

Here there is no e in function inside setSate(), so e.target.value will be error;

Since you dont want to compare with previous value and only need to set the value to title, you can use like

onChange={(e) => this.setState({title: e.target.value})}

There is no need for an extra function inside setState


问:
Squid proxy at ubuntu 18.04 impossible to connect
I'm new with Google Cloud so I may explain not precise.\
I have VM with Ubuntu 18.04 at Google Cloud Platform and I have installed Squid 3 proxy server on it.
Proxy is already configured a little.

```<code>http_port 3128 transparent
auth_param basic program /usr/lib/squid3/basic_ncsa_auth /etc/squid/passwd
auth_param basic children 2
auth_param basic realm My Proxy Server
auth_param basic credentialsttl 24 hours
auth_params basic casesensitive off

#add acl rules
acl users proxy_auth REQUIRED

#http access rules
http_access deny !users
http_access allow users
</code>```

In Google console I can see server's outer IP address but It does not work through it.

The ifconfig command shows next

```<code>ens4: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1460
        inet 10.156.0.3  netmask 255.255.255.255  broadcast 0.0.0.0
        inet6 fe80::4001:aff:fe9c:3  prefixlen 64  scopeid 0x20<link>
        ether 42:01:0a:9c:00:03  txqueuelen 1000  (Ethernet)
        RX packets 104399  bytes 83418274 (83.4 MB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 93840  bytes 12598292 (12.5 MB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 16697  bytes 1149429 (1.1 MB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 16697  bytes 1149429 (1.1 MB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
</code>```

where inet 10.156.0.3 means my inner IP.
I suppose I don't understand some simple rule of work with Google Platform or just with proxy configuration.

May you show me where I'm wrong?
Thank you.

答:
To solve your issue you need to check with nmap which ports are open on your VM and if 3128 is closed set Network tag for your VM and add firewall rule to allow access to it.

I've tried to replicate your issue on my test VM:

create VM instance or use existing one

install Squid

check if Squid is running:

```<code>$ sudo systemctl status squid
 ● squid.service - LSB: Squid HTTP Proxy version 3.x
   Loaded: loaded (/etc/init.d/squid; generated)
   **Active: active (running)** since Wed 2020-02-19 11:47:50 UTC; 26s ago
</code>```

check accessibility to Squid with nmap:

```<code>$ nmap -Pn 35.XXX.155.XXX
Starting Nmap 7.80 ( https://nmap.org ) at 2020-02-19 12:53 CET
...
Host is up (0.023s latency).
Not shown: 996 filtered ports
PORT     STATE  SERVICE
22/tcp   open   ssh
3389/tcp closed ms-wbt-server
8000/tcp closed http-alt
8081/tcp closed blackice-icecap
</code>```

Squid is not available

edit VM and set Network tag proxy-server

add firewall rule to enable connections to Squid by using Network tag:

```<code>$ gcloud compute --project=test-prj firewall-rules create proxy-server-rule --direction=INGRESS --priority=999 --network=default --action=ALLOW --rules=tcp:3128 --source-ranges=0.0.0.0/0 --target-tags=proxy-server
</code>```

check accessibility to Squid with nmap again

```<code>$ nmap -Pn 35.XXX.155.XXX
Starting Nmap 7.80 ( https://nmap.org ) at 2020-02-19 12:53 CET
...
Host is up (0.022s latency).
Not shown: 995 filtered ports
PORT     STATE  SERVICE
22/tcp   open   ssh
3128/tcp open   squid-http
3389/tcp closed ms-wbt-server
8000/tcp closed http-alt
8081/tcp closed blackice-icecap
</code>```

now Squid is ready to use.

Body:
I'm new with Google Cloud so I may explain not precise.\
I have VM with Ubuntu 18.04 at Google Cloud Platform and I have installed Squid 3 proxy server on it.
Proxy is already configured a little.

http_port 3128 transparent
auth_param basic program /usr/lib/squid3/basic_ncsa_auth /etc/squid/passwd
auth_param basic children 2
auth_param basic realm My Proxy Server
auth_param basic credentialsttl 24 hours
auth_params basic casesensitive off

#add acl rules
acl users proxy_auth REQUIRED

#http access rules
http_access deny !users
http_access allow users

In Google console I can see server's outer IP address but It does not work through it.

The ifconfig command shows next

ens4: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1460
        inet 10.156.0.3  netmask 255.255.255.255  broadcast 0.0.0.0
        inet6 fe80::4001:aff:fe9c:3  prefixlen 64  scopeid 0x20<link>
        ether 42:01:0a:9c:00:03  txqueuelen 1000  (Ethernet)
        RX packets 104399  bytes 83418274 (83.4 MB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 93840  bytes 12598292 (12.5 MB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 16697  bytes 1149429 (1.1 MB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 16697  bytes 1149429 (1.1 MB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

where inet 10.156.0.3 means my inner IP.
I suppose I don't understand some simple rule of work with Google Platform or just with proxy configuration.

May you show me where I'm wrong?
Thank you.

Body:
To solve your issue you need to check with nmap which ports are open on your VM and if 3128 is closed set Network tag for your VM and add firewall rule to allow access to it.

I've tried to replicate your issue on my test VM:

create VM instance or use existing one

install Squid

check if Squid is running:

$ sudo systemctl status squid
 ● squid.service - LSB: Squid HTTP Proxy version 3.x
   Loaded: loaded (/etc/init.d/squid; generated)
   **Active: active (running)** since Wed 2020-02-19 11:47:50 UTC; 26s ago

check accessibility to Squid with nmap:

$ nmap -Pn 35.XXX.155.XXX
Starting Nmap 7.80 ( https://nmap.org ) at 2020-02-19 12:53 CET
...
Host is up (0.023s latency).
Not shown: 996 filtered ports
PORT     STATE  SERVICE
22/tcp   open   ssh
3389/tcp closed ms-wbt-server
8000/tcp closed http-alt
8081/tcp closed blackice-icecap

Squid is not available

edit VM and set Network tag proxy-server

add firewall rule to enable connections to Squid by using Network tag:

$ gcloud compute --project=test-prj firewall-rules create proxy-server-rule --direction=INGRESS --priority=999 --network=default --action=ALLOW --rules=tcp:3128 --source-ranges=0.0.0.0/0 --target-tags=proxy-server

check accessibility to Squid with nmap again

$ nmap -Pn 35.XXX.155.XXX
Starting Nmap 7.80 ( https://nmap.org ) at 2020-02-19 12:53 CET
...
Host is up (0.022s latency).
Not shown: 995 filtered ports
PORT     STATE  SERVICE
22/tcp   open   ssh
3128/tcp open   squid-http
3389/tcp closed ms-wbt-server
8000/tcp closed http-alt
8081/tcp closed blackice-icecap

now Squid is ready to use.


问:
Python 3.5.1 urllib has no attribute request
I have tried

```<code>import urllib.request
</code>```

or

```<code>import urllib
</code>```

The path for my urllib is
/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/__init__.py

I am wondering where is urlopen, or is my python module pointing to the wrong file?

答:
Use this way</p>

```<code>import urllib.request
urllib.request.urlopen('http://216.58.192.142',timeout=1)
</code>```

Body:
I have tried

import urllib.request

or

import urllib

The path for my urllib is
/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/__init__.py

I am wondering where is urlopen, or is my python module pointing to the wrong file?

Body:
Use this way

import urllib.request
urllib.request.urlopen('http://216.58.192.142',timeout=1)


问:
How to get allocated GPU spec in Google Colab
I'm using Google Colab for deep learning and I'm aware that they randomly allocate GPU's to users. I'd like to be able to see which GPU I've been allocated in any given session. Is there a way to do this in Google Colab notebooks?

Note that I am using Tensorflow if that helps.

答: Since you can run bash command in colab, just run !nvidia-smi:


问:
Rsyslog to PostgreSQL works fine but not all columns are filled
I configured correctly to store the syslog messages in PostgreSQL as shown in this image, but ntseverity, importance, eventsource, etc are null:

This is my configuration until now:

```<code>## Configuration file for rsyslog-pgsql
### Changes are preserved

module (load="ompgsql")
*.* action(type="ompgsql" server="localhost" db="syslog" uid="rsyslogu" pwd="*********")
</code>```

Seems a template has to be created as shown in:
https://www.rsyslog.com/doc/v8-stable/configuration/modules/ompgsql.html

How can I set the template for those extra columns to be filled?
Does someone have the remaining columns in the template?

```<code>template(name="sql-syslog" type="list" option.sql="on") {
  constant(value="INSERT INTO SystemEvents (message, timereported) values ('")
  property(name="msg")
  constant(value="','")
  property(name="timereported" dateformat="pgsql" date.inUTC="on")
  constant(value="')")
}
</code>```

答:
your fields are empty because in the insert statement you only send two fields.

Try somethig like:

```<code>$template SQLWithProcessID,"insert into SystemEvents (Message, Facility, FromHost, Priority, DeviceReportedTime, ReceivedAt, InfoUnitID, SysLogTag) values ('%msg:R,ERE,1,FIELD:([a-zA-Z\/]+)(\[[0-9]{1,5}\])*:--end%', %syslogfacility%, '%HOSTNAME%', %syslogpriority%, '%timereported:::date-pgsql%', '%timegenerated:::date-pgsql%', %iut%, '%syslogtag:R,ERE,1,FIELD:([a-zA-Z\/]+)(\[[0-9]{1,5}\])*:--end%')",sql

module(load="ompgsql")
*.* :ompgsql:10.40.30.10,rsyslog,rsyslog,rsyslog;SQLWithProcessID
</code>```

Body:
I configured correctly to store the syslog messages in PostgreSQL as shown in this image, but ntseverity, importance, eventsource, etc are null:

This is my configuration until now:

## Configuration file for rsyslog-pgsql
### Changes are preserved

module (load="ompgsql")
*.* action(type="ompgsql" server="localhost" db="syslog" uid="rsyslogu" pwd="*********")

Seems a template has to be created as shown in:
https://www.rsyslog.com/doc/v8-stable/configuration/modules/ompgsql.html

How can I set the template for those extra columns to be filled?
Does someone have the remaining columns in the template?

template(name="sql-syslog" type="list" option.sql="on") {
  constant(value="INSERT INTO SystemEvents (message, timereported) values ('")
  property(name="msg")
  constant(value="','")
  property(name="timereported" dateformat="pgsql" date.inUTC="on")
  constant(value="')")
}

Body:
your fields are empty because in the insert statement you only send two fields.

Try somethig like:

$template SQLWithProcessID,"insert into SystemEvents (Message, Facility, FromHost, Priority, DeviceReportedTime, ReceivedAt, InfoUnitID, SysLogTag) values ('%msg:R,ERE,1,FIELD:([a-zA-Z\/]+)(\[[0-9]{1,5}\])*:--end%', %syslogfacility%, '%HOSTNAME%', %syslogpriority%, '%timereported:::date-pgsql%', '%timegenerated:::date-pgsql%', %iut%, '%syslogtag:R,ERE,1,FIELD:([a-zA-Z\/]+)(\[[0-9]{1,5}\])*:--end%')",sql

module(load="ompgsql")
*.* :ompgsql:10.40.30.10,rsyslog,rsyslog,rsyslog;SQLWithProcessID


问:
How to pass parameter of oracle sql script file to sqlplus from shell prompt?
Objective: To invoke sqlplus with sql script file path as parameter from shell prompt

Scenario:

logged in as root and would like to execute the sql script file as oracle

Command:

```<code>sudo -u oracle bash -c ". ~/.bash_profile; sqlplus / as sysdba@/tmp/downloads/oracle/instl/script/createschema.sql
</code>```

Expected: sql commands in createschema.sql are to be executed

Actual: getting only sql prompt

Also, tried:

a)

```<code>sudo -u oracle bash -c ". ~/.bash_profile; sqlplus@/tmp/downloads/oracle/instl/script/createschema.sql / as sysdba
</code>```

b)

```<code>sudo -u oracle bash -c ". ~/.bash_profile; sqlplus -s /as sysdba << EOF
</code>```

whenever sqlerror exit sql.sqlcode; set echo off; set heading off; /tmp/downloads/oracle/instl/script/createschema.sql; exit; EOF"

but getting error in both a) and b).

Please guide me in invoking sqlplus with sql script file path as parameter from shell prompt.

答:
Example 1

```<code>#!/bin/sh

username=\"Scott\"
password=\"@T!ger\"
host=10.x.xx.xxx
port=1521
service=esmd
ezconnect=$host:$port/$service

echo username:  $username
echo password:  $password
echo host:      $host
echo port:      $port
echo service:   $servive
echo ezconnect  $ezconnect

echo -e 'show user \n  select 1 from dual; \n select sysdate from dual; \nexit;' |  sqlplus -s  $username/$password@$ezconnect
</code>```

Output:

```<code>oracle@esmd:~> ./test_echo.sh
username: "Scott"
password: "@T!ger"
host: 10.x.xx.xxx
port: 1521
service:
ezconnect 10.x.xx.xxx:1521/esmd
USER is "Scott"

         1
----------
         1

SYSDATE
---------
19-FEB-20

oracle@esmd:~>
</code>```

Example 2

```<code>#!/bin/sh

username=\"Scott\"
password=\"@T!ger\"

echo username:  $username
echo password:  $password

testoutput=$(sqlplus -s $username/$password  << EOF
set pagesize 0 feedback off verify off heading off echo off;
show user
SELECT to_char(sysdate,'DD-MM-YYYY HH24:MI')||' Test passed' from dual;
@ulcase1.sql
exit;
EOF
)

echo $testoutput
</code>```

Output:

```<code>oracle@esmd:~> ./test_Upper_case.sh
username: "Scott"
password: "@T!ger"
USER is "Scott" 19-02-2020 15:08 Test passed
oracle@esmd:~>
</code>```

Example 3  test.sh

```<code>#!/bin/bash

sudo  -H -E  -u oracle  -s "/opt/oracle/test_Upper_case.sh"
</code>```

Output

```<code>esmd:~ # ./test.sh
username: "Scott"
password: "@T!ger"
USER is "Scott" 19-02-2020 15:50 Test passed
</code>```

/opt/oracle/test_Upper_case.sh

```<code>!/bin/sh

username=\"Scott\"
password=\"@T!ger\"

echo username:  $username
echo password:  $password

testoutput=$($ORACLE_HOME/bin/sqlplus -s $username/$password  << EOF
set pagesize 0 feedback off verify off heading off echo off;
show user
SELECT to_char(sysdate,'DD-MM-YYYY HH24:MI')||' Test passed' from dual;
@/opt/oracle/ulcase1.sql
exit;
EOF
)

echo $testoutput
</code>```

Body:
Objective: To invoke sqlplus with sql script file path as parameter from shell prompt

Scenario:

logged in as root and would like to execute the sql script file as oracle

Command:

sudo -u oracle bash -c ". ~/.bash_profile; sqlplus / as sysdba@/tmp/downloads/oracle/instl/script/createschema.sql

Expected: sql commands in createschema.sql are to be executed

Actual: getting only sql prompt

Also, tried:

a)

sudo -u oracle bash -c ". ~/.bash_profile; sqlplus@/tmp/downloads/oracle/instl/script/createschema.sql / as sysdba

b)

sudo -u oracle bash -c ". ~/.bash_profile; sqlplus -s /as sysdba << EOF

whenever sqlerror exit sql.sqlcode; set echo off; set heading off; /tmp/downloads/oracle/instl/script/createschema.sql; exit; EOF"

but getting error in both a) and b).

Please guide me in invoking sqlplus with sql script file path as parameter from shell prompt.

Body:
Example 1

#!/bin/sh

username=\"Scott\"
password=\"@T!ger\"
host=10.x.xx.xxx
port=1521
service=esmd
ezconnect=$host:$port/$service

echo username:  $username
echo password:  $password
echo host:      $host
echo port:      $port
echo service:   $servive
echo ezconnect  $ezconnect

echo -e 'show user \n  select 1 from dual; \n select sysdate from dual; \nexit;' |  sqlplus -s  $username/$password@$ezconnect

Output:

oracle@esmd:~> ./test_echo.sh
username: "Scott"
password: "@T!ger"
host: 10.x.xx.xxx
port: 1521
service:
ezconnect 10.x.xx.xxx:1521/esmd
USER is "Scott"

         1
----------
         1

SYSDATE
---------
19-FEB-20

oracle@esmd:~>

Example 2

#!/bin/sh

username=\"Scott\"
password=\"@T!ger\"

echo username:  $username
echo password:  $password

testoutput=$(sqlplus -s $username/$password  << EOF
set pagesize 0 feedback off verify off heading off echo off;
show user
SELECT to_char(sysdate,'DD-MM-YYYY HH24:MI')||' Test passed' from dual;
@ulcase1.sql
exit;
EOF
)

echo $testoutput

Output:

oracle@esmd:~> ./test_Upper_case.sh
username: "Scott"
password: "@T!ger"
USER is "Scott" 19-02-2020 15:08 Test passed
oracle@esmd:~>

Example 3  test.sh

#!/bin/bash

sudo  -H -E  -u oracle  -s "/opt/oracle/test_Upper_case.sh"

Output

esmd:~ # ./test.sh
username: "Scott"
password: "@T!ger"
USER is "Scott" 19-02-2020 15:50 Test passed

/opt/oracle/test_Upper_case.sh

!/bin/sh

username=\"Scott\"
password=\"@T!ger\"

echo username:  $username
echo password:  $password

testoutput=$($ORACLE_HOME/bin/sqlplus -s $username/$password  << EOF
set pagesize 0 feedback off verify off heading off echo off;
show user
SELECT to_char(sysdate,'DD-MM-YYYY HH24:MI')||' Test passed' from dual;
@/opt/oracle/ulcase1.sql
exit;
EOF
)

echo $testoutput


答:
You don't need to use arrow function inside setstate.

change
onChange={(e) => this.setState(() => ({title: e.target.value}))}

to:
onChange={(e) => this.setState({title: e.target.value})}


问:
Do split one class hierarchy into several or not?
For now, we have a .NET application that leans on the standard .NET XML serialization/deserialization mechanism. The example is simplified but the meaning is the same.

```<code>public abstract class Shape
{
    [XmlAttribute("id")]
    public string Id { get; set; }
    [XmlAttribute("level")]
    public int Level { get; set; }

    public abstract void Draw();
    public abstract void Clear();
    public abstract void Scale(double scale);
}

[XmlType("Circle")]
public class Circle : Shape
{
    public double Radius { get; set; }

    public override void Draw() {}

    public override void Clear() {}

    public override void Scale(double scale) {}
}

[XmlType("Rectangle")]
public class Rectangle: Shape
{
    public double Height { get; set; }
    public double Width { get; set; }

    public override void Draw() {}

    public override void Clear() {}

    public override void Scale(double scale) {}
}

public class Picture
{
    public double Scale { get; set; }
    [XmlArrayAttribute("Shapes")]
    public Collection<Shape> Shapes { get; set; }

    public void Setup()
    {
        foreach (Shape shape in Shapes)
        {
            shape.Draw();
        }

        foreach (Shape shape in Shapes)
        {
            shape.Scale(Scale);
        }
    }

    public void Cleanup()
    {
        foreach (Shape shape in Shapes)
        {
            shape.Clear();
        }
    }

    public static Picture FromXml(XmlReader xmlReader)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(Picture));
        return serializer.Deserialize(xmlReader) as Picture;
    }
}
</code>```

And for example the input XML file will look like:

```<code><Picture>
    <Scale>0.9</Scale>
    <Shapes>
        <Circle id="1">
            <Radius>1.5</Radius>
        </Circle>
        <Circle id="2">
            <Radius>3</Radius>
        </Circle>
        <Rectangle id="3">
            <Height>300</Height>
            <Width>300</Width>
        </Rectangle>
    </Shapes>
</Picture>
</code>```

But model classes contain a logic (Draw(), Clear() and Scale() methods) and it seems that it breaks a single responsibility principle. And therefore we don't know does it make sense to split that logic into several classes or not?

If yes, then how? Because once we read the XML file, all objects are accessible only as Shape objects and therefore we will have to explicitly cast the object either before passing if to the handler class or inside that method, for example:

```<code>public abstract class Drawer
{
    public abstract void Draw(Shape shape);
}

public class CircleDrawer : Drawer
{
    public override void Draw(Shape shape)
    {
        Circle circle = shape as Circle;
        if (circle == null)
        {
            throw new ArgumentException("Passed object is not of type Circle");
        }
    }
}
</code>```

If that issue is known, please just redirect me to that resource.

Thank you in advance.

答:
The question in this case would be, is it needed that the caller knows the concrete type or is everything mapped through the common base class?

In your example all implementations share a common abstract base class. If all users can happily work with this common behaviour you just push around all instances casted to the base type. Nevertheless as you already mentioned this tends to put more and more business logic into each concrete class. Depending on how much (or better less) this is, it is absolutely okay to let it there (this seems to be your current solution).

If this is getting more or quite complex it would be a good way to move this into its own class and/or methods. In that case you need some kind of dispatcher, that decides which takes care for the given object. I start to use a dictionary for these cases that works as a dispatcher and has the given type as key and an Action or Func as value like this:

```<code>var dispatcher = new Dictionary<Type, Action<Shape>>
{
    { typeof(Rectangle), DoSomethingWithRectangle },
    { typeof(Circle), DoSomethingWithCircle }
}

private void DoSomethingWithRectangle(Shape shape)
{
    var rectangle = (Rectangle)shape;
    Console.WriteLine($"Rectangle Height: {rectangle.Height} Width: {rectangle.Width}");
}

private void DoSomethingWithCircle(Shape shape)
{
    var circle = (Circle)shape;
    Console.WriteLine($"Circle Radius: {circle.Radius}");
}
</code>```

This is just a trivial example. The dictionary should be live within a dispatcher where you have some methods to register different types and instead of methods you could also register types or instances of classes that could handle each specific instance type. If this kind of dispatching is still not matching all your cases you could maybe take a look at MediatR which formalized these things much more with a bunch of type-safe interfaces which you use to define your input types, the desired return value and an handler that is capable of doing this job.

Body:
For now, we have a .NET application that leans on the standard .NET XML serialization/deserialization mechanism. The example is simplified but the meaning is the same.

public abstract class Shape
{
    [XmlAttribute("id")]
    public string Id { get; set; }
    [XmlAttribute("level")]
    public int Level { get; set; }

    public abstract void Draw();
    public abstract void Clear();
    public abstract void Scale(double scale);
}

[XmlType("Circle")]
public class Circle : Shape
{
    public double Radius { get; set; }

    public override void Draw() {}

    public override void Clear() {}

    public override void Scale(double scale) {}
}

[XmlType("Rectangle")]
public class Rectangle: Shape
{
    public double Height { get; set; }
    public double Width { get; set; }

    public override void Draw() {}

    public override void Clear() {}

    public override void Scale(double scale) {}
}

public class Picture
{
    public double Scale { get; set; }
    [XmlArrayAttribute("Shapes")]
    public Collection<Shape> Shapes { get; set; }

    public void Setup()
    {
        foreach (Shape shape in Shapes)
        {
            shape.Draw();
        }

        foreach (Shape shape in Shapes)
        {
            shape.Scale(Scale);
        }
    }

    public void Cleanup()
    {
        foreach (Shape shape in Shapes)
        {
            shape.Clear();
        }
    }

    public static Picture FromXml(XmlReader xmlReader)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(Picture));
        return serializer.Deserialize(xmlReader) as Picture;
    }
}

And for example the input XML file will look like:

<Picture>
    <Scale>0.9</Scale>
    <Shapes>
        <Circle id="1">
            <Radius>1.5</Radius>
        </Circle>
        <Circle id="2">
            <Radius>3</Radius>
        </Circle>
        <Rectangle id="3">
            <Height>300</Height>
            <Width>300</Width>
        </Rectangle>
    </Shapes>
</Picture>

But model classes contain a logic (Draw(), Clear() and Scale() methods) and it seems that it breaks a single responsibility principle. And therefore we don't know does it make sense to split that logic into several classes or not?

If yes, then how? Because once we read the XML file, all objects are accessible only as Shape objects and therefore we will have to explicitly cast the object either before passing if to the handler class or inside that method, for example:

public abstract class Drawer
{
    public abstract void Draw(Shape shape);
}

public class CircleDrawer : Drawer
{
    public override void Draw(Shape shape)
    {
        Circle circle = shape as Circle;
        if (circle == null)
        {
            throw new ArgumentException("Passed object is not of type Circle");
        }
    }
}

If that issue is known, please just redirect me to that resource.

Thank you in advance.

Body:
The question in this case would be, is it needed that the caller knows the concrete type or is everything mapped through the common base class?

In your example all implementations share a common abstract base class. If all users can happily work with this common behaviour you just push around all instances casted to the base type. Nevertheless as you already mentioned this tends to put more and more business logic into each concrete class. Depending on how much (or better less) this is, it is absolutely okay to let it there (this seems to be your current solution).

If this is getting more or quite complex it would be a good way to move this into its own class and/or methods. In that case you need some kind of dispatcher, that decides which takes care for the given object. I start to use a dictionary for these cases that works as a dispatcher and has the given type as key and an Action or Func as value like this:

var dispatcher = new Dictionary<Type, Action<Shape>>
{
    { typeof(Rectangle), DoSomethingWithRectangle },
    { typeof(Circle), DoSomethingWithCircle }
}

private void DoSomethingWithRectangle(Shape shape)
{
    var rectangle = (Rectangle)shape;
    Console.WriteLine($"Rectangle Height: {rectangle.Height} Width: {rectangle.Width}");
}

private void DoSomethingWithCircle(Shape shape)
{
    var circle = (Circle)shape;
    Console.WriteLine($"Circle Radius: {circle.Radius}");
}

This is just a trivial example. The dictionary should be live within a dispatcher where you have some methods to register different types and instead of methods you could also register types or instances of classes that could handle each specific instance type. If this kind of dispatching is still not matching all your cases you could maybe take a look at MediatR which formalized these things much more with a bunch of type-safe interfaces which you use to define your input types, the desired return value and an handler that is capable of doing this job.


问:
Bulk update Postgres table
I have a table with around 200 million records and I have added 2 new columns to it. Now the 2 columns need values from a different table. Nearly 80% of the rows will be updated.

I tried update but it takes more than 2 hours to complete.

The main table has a composite primary key of 4 columns. I have dropped it and dropped an index that is present on a column before updating. Now the update takes little over than 1 hour.

Is there any other way to speed up this update process (like batch processing).

Edit: I used the other table(from where values will be matched for update) in from clause of the update statement.

答:
Do you need whole update in single transaction? I had quite similar problem, with table that was under heavy load, and column required not null constraint. Do deal with it - I did some steps:

Add columns without constraints like not null, but with defaults. That way it went really fast.

Update columns in steps like 1000 entries per transaction. In my case load of the DB rise, so I had to put small delay.

Update columns to have not null constraints.

That way you don't block table for long time, but that is not an answer to your question.

First to validate where you are - I would check iostats to see if that is not the limit... To speed up, I would consider:

higher free space map - to be sure DB is aware of entries that can be removed, but note that if pages are packed to the limit it would not bring much...

maybe foreign keys referring to the table can be also removed? To stop locking the table,

removing all indices since they are slowing down, and create them afterwords - that looks like slicing problem but other way, but is an option, so counts...

Title: Bulk update Postgres table


问:
Convert a List of Object/Strings into substrings separated by comma
Please help on converting a list of objects got from DB into substrings separated by a comma

Take for example I have a sample code below:

```<code>List<string> CategoryNames = new List<string>();
CategoryNames.Add("myName1");
CategoryNames.Add("myName2");
CategoryNames.Add("myName3");
</code>```

I want to convert CategoryNames into a format like this

"myName1","myName2","myName3"

From the above CatgoryNames happen to be retrieved from db.

```<code>var categoryNames = _context.BillingCategory.ToList();
</code>```

How do I convert the categoryNames into substrings as shown above?
Any help will be appreciated.

答:
You can use String.Join() method by combining with LINQ for preserving the quotes before joining:

```<code>var result = String.Join(",", CategoryNames.Select(item => $"\"{item}\""));
</code>```

And here is the clearer version of the code if you don't linke singleliner:

```<code>var QuotedCategroyNames = CategoryNames
    .Select(item => $"\"{item}\"");

var result = String.Join(",", QuotedCategroyNames);
</code>```

Body:
Please help on converting a list of objects got from DB into substrings separated by a comma

Take for example I have a sample code below:

List<string> CategoryNames = new List<string>();
CategoryNames.Add("myName1");
CategoryNames.Add("myName2");
CategoryNames.Add("myName3");

I want to convert CategoryNames into a format like this

"myName1","myName2","myName3"

From the above CatgoryNames happen to be retrieved from db.

var categoryNames = _context.BillingCategory.ToList();

How do I convert the categoryNames into substrings as shown above?
Any help will be appreciated.

Body:
You can use String.Join() method by combining with LINQ for preserving the quotes before joining:

var result = String.Join(",", CategoryNames.Select(item => $"\"{item}\""));

And here is the clearer version of the code if you don't linke singleliner:

var QuotedCategroyNames = CategoryNames
    .Select(item => $"\"{item}\"");

var result = String.Join(",", QuotedCategroyNames);


问:
Removing all commas from list in Python
My issue: I'd like to add all the digits in this string '1.14,2.14,3.14,4.14' but the commas are causing my sum function to not work correctly.

I figured using a strip function would solve my issue but it seems as though there is still something I'm missing or not quite understanding.

```<code>total = 0
for c in '1.14,2.14,3.14'.strip(","):
    total = total + float(c)
print total
</code>```

I have searched how to remove commas from a string but I only found information on how to remove commas from the beginning or ending of a string.

Additional Info: Python 2.7

答:
Use this to remove commas and white spaces

```<code>a = [1,2,3,4,5]
print(*a, sep = "")
</code>```

Output:-
12345

Title: Removing all commas from list in Python

Body:
My issue: I'd like to add all the digits in this string '1.14,2.14,3.14,4.14' but the commas are causing my sum function to not work correctly.

I figured using a strip function would solve my issue but it seems as though there is still something I'm missing or not quite understanding.

total = 0
for c in '1.14,2.14,3.14'.strip(","):
    total = total + float(c)
print total

I have searched how to remove commas from a string but I only found information on how to remove commas from the beginning or ending of a string.

Additional Info: Python 2.7

Body:
Use this to remove commas and white spaces

a = [1,2,3,4,5]
print(*a, sep = "")

Output:-
12345


问:
Error converting String to java.sql.LocalDateTime
I tried converting string to LocalDateTime. Here is my code

```<code>String val = "2015-07-18T13:32:56.971-0400"
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZ");
java.time.LocalDateTime dateTime = java.time.LocalDateTime.parse(val, formatter);
</code>```

But doing so I am getting the following errors

```<code>The method ofPattern(String) is undefined for the type DateTimeFormatter
The method parse(CharSequence, DateTimeFormatter) in the type LocalDateTime is not applicable for the arguments (String, DateTimeFormatter)
</code>```

Can someone suggest me what to do

答:
Remove the leading - from your String.

```<code>import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

String val = "2015-07-18T13:32:56.971-0400";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZ");
LocalDateTime dateTime = LocalDateTime.parse(val, formatter);
System.out.println(dateTime);
</code>```

2015-07-18T13:32:56.971

Body:
I tried converting string to LocalDateTime. Here is my code

String val = "2015-07-18T13:32:56.971-0400"
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZ");
java.time.LocalDateTime dateTime = java.time.LocalDateTime.parse(val, formatter);

But doing so I am getting the following errors

The method ofPattern(String) is undefined for the type DateTimeFormatter
The method parse(CharSequence, DateTimeFormatter) in the type LocalDateTime is not applicable for the arguments (String, DateTimeFormatter)

Can someone suggest me what to do

Body:
Remove the leading - from your String.

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

String val = "2015-07-18T13:32:56.971-0400";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZ");
LocalDateTime dateTime = LocalDateTime.parse(val, formatter);
System.out.println(dateTime);

2015-07-18T13:32:56.971


问:
Translate a MySql query in a Laravel query builder
```<code>SELECT apartment_id, COUNT(created_at) AS n_view,
DATE_FORMAT(created_at, '%Y-%m-%d') as day_view
FROM views
WHERE apartment_id=36 GROUP BY day_view
ORDER BY COUNT(created_at) DESC
</code>```

how can I Translate this  MySql query in a Laravel query builder ?

答:
You can do like that   use App\Views;     use DB;

```<code>Views::select('apartment_id', DB::raw("COUNT(created_at) as n_view") ,DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d') as day_view"))->where('apartment_id' ,36)->orderBy('n_view', 'desc')->get();
</code>```

Body:
SELECT apartment_id, COUNT(created_at) AS n_view,
DATE_FORMAT(created_at, '%Y-%m-%d') as day_view
FROM views
WHERE apartment_id=36 GROUP BY day_view
ORDER BY COUNT(created_at) DESC

how can I Translate this  MySql query in a Laravel query builder ?

Body:
You can do like that   use App\Views;     use DB;

Views::select('apartment_id', DB::raw("COUNT(created_at) as n_view") ,DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d') as day_view"))->where('apartment_id' ,36)->orderBy('n_view', 'desc')->get();


问:
AttributeError: module 'tensorflow._api.v1.compat' has no attribute 'v2' For Tensorflow Object Detection API
I'm working on Tensorflow Object Detection API on Python. I'm training a custom object detection algorithm and the pretrained model which is been used is ssd_mobilenet_v1_pets.config when I try to run train.py from the legacy folder from Models/object_detection i get this particular error

```<code> Traceback (most recent call last):
  File "train.py", line 48, in <module>
    from object_detection.builders import model_builder
  File "C:\Users\Captain\AppData\Local\Programs\Python\Python36\lib\site-packages\object_detection-0.1-py3.6.egg\object_detection\builders\model_builder.py", line 47, in <module>
    from object_detection.models.ssd_mobilenet_edgetpu_feature_extractor import SSDMobileNetEdgeTPUFeatureExtractor
  File "C:\Users\Captain\AppData\Local\Programs\Python\Python36\lib\site-packages\object_detection-0.1-py3.6.egg\object_detection\models\ssd_mobilenet_edgetpu_feature_extractor.py", line 19, in <module>
    from object_detection.models import ssd_mobilenet_v3_feature_extractor
  File "C:\Users\Captain\AppData\Local\Programs\Python\Python36\lib\site-packages\object_detection-0.1-py3.6.egg\object_detection\models\ssd_mobilenet_v3_feature_extractor.py", line 25, in <module>
    from nets.mobilenet import mobilenet
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 656, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 626, in _load_backward_compatible
  File "C:\Users\Captain\AppData\Local\Programs\Python\Python36\lib\site-packages\slim-0.1-py3.6.egg\nets\mobilenet\mobilenet.py", line 399, in <module>
AttributeError: module 'tensorflow._api.v1.compat' has no attribute 'v2'
</code>```

I have

Tensorflow 1.13.2

Python 3.6

Windows 10

This is the command I'm trying to run on windows command prompt.

```<code>python train.py --logtostderr --train_dir=Users/Captain/Desktop/ANPR V1/ --pipeline_config_path=Users/Captain/Desktop/ANPR V1/ssd_inception_v2_coco.config
</code>```

I thought it might be because I was using another model so also tried this command

```<code>python train.py --logtostderr --train_dir=Users/Captain/Desktop/ANPR V1/ --pipeline_config_path=Users/Captain/Desktop/ANPR V1/ssd_mobilenet_v1_pets.config
</code>```

but I got the same error

答: I faced the same problem. If you downloaded the latest repository of tensorflow models then try downloading this tensorflow models of version 1.13.0 instead the latest repo as you are using Tensorflow 1.13.2. It solved my problem.

Body:
I'm working on Tensorflow Object Detection API on Python. I'm training a custom object detection algorithm and the pretrained model which is been used is ssd_mobilenet_v1_pets.config when I try to run train.py from the legacy folder from Models/object_detection i get this particular error

 Traceback (most recent call last):
  File "train.py", line 48, in <module>
    from object_detection.builders import model_builder
  File "C:\Users\Captain\AppData\Local\Programs\Python\Python36\lib\site-packages\object_detection-0.1-py3.6.egg\object_detection\builders\model_builder.py", line 47, in <module>
    from object_detection.models.ssd_mobilenet_edgetpu_feature_extractor import SSDMobileNetEdgeTPUFeatureExtractor
  File "C:\Users\Captain\AppData\Local\Programs\Python\Python36\lib\site-packages\object_detection-0.1-py3.6.egg\object_detection\models\ssd_mobilenet_edgetpu_feature_extractor.py", line 19, in <module>
    from object_detection.models import ssd_mobilenet_v3_feature_extractor
  File "C:\Users\Captain\AppData\Local\Programs\Python\Python36\lib\site-packages\object_detection-0.1-py3.6.egg\object_detection\models\ssd_mobilenet_v3_feature_extractor.py", line 25, in <module>
    from nets.mobilenet import mobilenet
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 656, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 626, in _load_backward_compatible
  File "C:\Users\Captain\AppData\Local\Programs\Python\Python36\lib\site-packages\slim-0.1-py3.6.egg\nets\mobilenet\mobilenet.py", line 399, in <module>
AttributeError: module 'tensorflow._api.v1.compat' has no attribute 'v2'

I have

Tensorflow 1.13.2

Python 3.6

Windows 10

This is the command I'm trying to run on windows command prompt.

python train.py --logtostderr --train_dir=Users/Captain/Desktop/ANPR V1/ --pipeline_config_path=Users/Captain/Desktop/ANPR V1/ssd_inception_v2_coco.config

I thought it might be because I was using another model so also tried this command

python train.py --logtostderr --train_dir=Users/Captain/Desktop/ANPR V1/ --pipeline_config_path=Users/Captain/Desktop/ANPR V1/ssd_mobilenet_v1_pets.config

but I got the same error


问:
Kafka to ES and other sink DB
Using a mysql source connector, I can capture the mysql change and post to them ES or another db for backup. But for that I need separate connector(both source and sink) for each table I have in my source db.
So my question is:

Without creating same amount of source and sink connector for each tables, how can I achieve the same purpose? As this is cumbersome to create that many connectors. So that backing up db(replica) and making faster response service for clients would become much easier for me. Or there is no way to do this?

答:
For the source connectors, you can use table.whitelist. For example,

```<code>table.whitelist: "User, Address, Email"
</code>```

Sink connectors can only be configured for one table at a time.

And I wouldn't say that it is hard to maintain multiple sink/source connectors and topics. From my experience, it is harder to maintain connectors which are replicating data from multiple topics/sources. For example, if you want to apply SMT (Simple Message Transform) on a particular topic, you won't be able to achieve it if you don't have isolated connectors as SMTs are applied on a connector level. Furthermore, if you configure a single connector for all of your sources and at some point it fails, all of your target systems will encounter downtime.

Title: Kafka to ES and other sink DB

Body:
For the source connectors, you can use table.whitelist. For example,

table.whitelist: "User, Address, Email"

Sink connectors can only be configured for one table at a time.

And I wouldn't say that it is hard to maintain multiple sink/source connectors and topics. From my experience, it is harder to maintain connectors which are replicating data from multiple topics/sources. For example, if you want to apply SMT (Simple Message Transform) on a particular topic, you won't be able to achieve it if you don't have isolated connectors as SMTs are applied on a connector level. Furthermore, if you configure a single connector for all of your sources and at some point it fails, all of your target systems will encounter downtime.


问:
How can i make flat button size as it's child size
i want to make button size like it's text child size
i will attach  example photo , and i'll attach the code that i write

this is my code :

```<code>        Expanded(
        child: FlatButton(
          minWidth: double.infinity,
          height: 20,
          child: FlatButton(
            onPressed: (){},
            color: Colors.grey,
           shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(10) ,
            ),
            child: Text(
              'SHOP' ,
              style: TextStyle(
                color: Colors.blueAccent,
                fontWeight: FontWeight.bold ,
                fontSize: 16 ,
              ),
</code>```

and this is the photo
photo

答:
How about this?

```<code>RawMaterialButton(
  constraints: BoxConstraints(),
  padding: EdgeInsets.fromLTRB(14, 4, 14, 4),
  elevation: 0,
  onPressed: () {},
  fillColor: Color(0xFFF2F2F2),
  shape: StadiumBorder(),
  child: Text(
    'SHOP',
    style: TextStyle(
      color: Colors.blueAccent,
      fontWeight: FontWeight.bold,
      fontSize: 16,
    ),
  ),
),
</code>```

Body:
i want to make button size like it's text child size
i will attach  example photo , and i'll attach the code that i write

this is my code :

        Expanded(
        child: FlatButton(
          minWidth: double.infinity,
          height: 20,
          child: FlatButton(
            onPressed: (){},
            color: Colors.grey,
           shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(10) ,
            ),
            child: Text(
              'SHOP' ,
              style: TextStyle(
                color: Colors.blueAccent,
                fontWeight: FontWeight.bold ,
                fontSize: 16 ,
              ),

and this is the photo
photo

Body:
How about this?

RawMaterialButton(
  constraints: BoxConstraints(),
  padding: EdgeInsets.fromLTRB(14, 4, 14, 4),
  elevation: 0,
  onPressed: () {},
  fillColor: Color(0xFFF2F2F2),
  shape: StadiumBorder(),
  child: Text(
    'SHOP',
    style: TextStyle(
      color: Colors.blueAccent,
      fontWeight: FontWeight.bold,
      fontSize: 16,
    ),
  ),
),