问:
How to build .sqlproj projects using "dotnet" tool?
Unable to build .Net .sqlproj using "dotnet" command line tool. Here's the error:

```<code>dotnet\sdk\3.1.300\Microsoft\VisualStudio\v11.0\SSDT\Microsoft.Data.Tools.Schema.SqlTasks.targets" was not found
</code>```

I have installed SSDT tool but it's not available at the above location.

Note: It's buildings without any error using Visual Studio and MSBuild

答:
How to build .sqlproj projects using “dotnet” tool?

Sorry but as I know this is not supported scenario for now. It's by design that dotnet cli can't build the Database Project with old-framework style project file.

As for the reason why it's buildings without any error using Visual Studio and MSBuild but failing using dotnet. Please check your SSDT installation path, it should be under pathC:\Program Files (x86)\Microsoft Visual Studio\2019\VSEditon\MSBuild\Microsoft\VisualStudio\v16.0\SSDT.

The SSDT is installed as a sub-module of MSBuild(VS build tools) or MSBuild from VS, so it works well when building it via VS/MSbuild. But dotnet cli won't know where to find this module which is under MSBuild folder's sub-folder, so it throws error.

There's once a discussion about this in github, in my opinion the feature to support build SQLProj via Dotnet hasn't come true. If you're interested in that feature, I suggest you can open a new ticket there to post your idea.

Body:
Unable to build .Net .sqlproj using "dotnet" command line tool. Here's the error:

dotnet\sdk\3.1.300\Microsoft\VisualStudio\v11.0\SSDT\Microsoft.Data.Tools.Schema.SqlTasks.targets" was not found

I have installed SSDT tool but it's not available at the above location.

Note: It's buildings without any error using Visual Studio and MSBuild


来源: stackexchange

问:
Convert repetitive pattern into JSON file with python
Hope you are doing fine,

I have a data file(containing 1000s of a structured pattern of data), like below

```<code>PARTNER="ABC"
  ADDRESS1="ABC Country INN"
  DEPARTMENT="ABC Department"
  CONTACT_PERSON="HR"
  TELEPHONE="+91.90.XX XX X XXX"
  FAX="+01.XX.XX XX XX XX"
  EMAIL=""

PARTNER="DEF"
  ADDRESS1="DEF Malaysia"
  DEPARTMENT=""
  CONTACT_PERSON=""
  TELEPHONE="(YYY)YYYYY"
  FAX="(001)YYYYYYYY"
  EMAIL=""

PARTNER="GEH-LOP"
  ADDRESS1="GEH LOP Street"
  DEPARTMENT="HR"
  CONTACT_PERSON="Adam"
  TELEPHONE="+91.ZZ.ZZ.ZZZZ"
  FAX="+91.ZZ.ZZ.ZZZ"
  EMAIL=""
</code>```

I tried to convert the datafile(partner.txt) to JSON with below code:

Created empty dictionaries dict1 and dict2

Reading the data file line by line

used this if not line.isspace() to make sure the linefeed is read is written in dictionary dict1

When linebreak(empty line appears) appended the content of dict1 to dict2 using dict2.update(dict1)

```<code>import json

dict1 = {}
dict2 ={}

with open("partner.txt", "r") as fh:
    out_file = open("test1.json", "w")
    for line in fh:
        if not line.isspace():
            command, description = line.strip().split("=")
            dict1[command] = description.strip('"')

        else:
            dict2.update(dict1)
            print("space found")
    json.dump(dict2,out_file,indent=1)

out_file.close()

print("json file created")

</code>```

But this code creates a json(test1.json) with only the single block of PARTNER

```<code>{
 "PARTNER": "DEF",
 "ADDRESS1": "DEF Malaysia",
 "DEPARTMENT": "",
 "CONTACT_PERSON": "",
 "TELEPHONE": "(YYY)YYYYY",
 "FAX": "(001)YYYYYYYY",
 "EMAIL": ""
}
</code>```

Expected Output
I tried looking up a lot but couldn't find a way:-

```<code>{
"data":[
{
 "PARTNER": "ABC",
 "ADDRESS1": "ABC Country INN",
 "DEPARTMENT": "ABC Department",
 "CONTACT_PERSON": "HR",
 "TELEPHONE": "+91.90.XX XX X XXX",
 "FAX": "+01.XX.XX XX XX XX",
 "EMAIL": ""
},
{
 "PARTNER": "DEF",
 "ADDRESS1": "DEF Malaysia",
 "DEPARTMENT": "",
 "CONTACT_PERSON": "",
 "TELEPHONE": "(YYY)YYYYY",
 "FAX": "(001)YYYYYYYY",
 "EMAIL": ""
},
{
 "PARTNER": "GEH-LOP",
 "ADDRESS1": "GEH LOP Street",
 "DEPARTMENT": "HR",
 "CONTACT_PERSON": "Adam",
 "TELEPHONE": "+91.ZZ.ZZ.ZZZZ",
 "FAX": "+91.ZZ.ZZ.ZZZ",
 "EMAIL": ""
}
]
}
</code>```

答:
there are many ways to do this. maybe we should make it maintainable

def list_to_dict(lines):
    obj = {}
    for liner in lines:
        idx = liner.find("=")
        obj[liner[0:idx]] = liner[idx + 2 : len(liner) - 1]
    return obj

with open("file", "r") as f:
    results = []
    group = []
    for line in list(map(lambda x: x.strip(), f.read().split("\n"))):
        if line == "":
            results.append(list_to_dict(group))
            group = []
        else:
            group.append(line)

    print(results)

```

ContentLicense: CC BY-SA 4.0

Body:
Hope you are doing fine,

I have a data file(containing 1000s of a structured pattern of data), like below

PARTNER="ABC"
  ADDRESS1="ABC Country INN"
  DEPARTMENT="ABC Department"
  CONTACT_PERSON="HR"
  TELEPHONE="+91.90.XX XX X XXX"
  FAX="+01.XX.XX XX XX XX"
  EMAIL=""

PARTNER="DEF"
  ADDRESS1="DEF Malaysia"
  DEPARTMENT=""
  CONTACT_PERSON=""
  TELEPHONE="(YYY)YYYYY"
  FAX="(001)YYYYYYYY"
  EMAIL=""

PARTNER="GEH-LOP"
  ADDRESS1="GEH LOP Street"
  DEPARTMENT="HR"
  CONTACT_PERSON="Adam"
  TELEPHONE="+91.ZZ.ZZ.ZZZZ"
  FAX="+91.ZZ.ZZ.ZZZ"
  EMAIL=""

I tried to convert the datafile(partner.txt) to JSON with below code:

Created empty dictionaries dict1 and dict2

Reading the data file line by line

used this if not line.isspace() to make sure the linefeed is read is written in dictionary dict1

When linebreak(empty line appears) appended the content of dict1 to dict2 using dict2.update(dict1)

import json

dict1 = {}
dict2 ={}

with open("partner.txt", "r") as fh:
    out_file = open("test1.json", "w")
    for line in fh:
        if not line.isspace():
            command, description = line.strip().split("=")
            dict1[command] = description.strip('"')

        else:
            dict2.update(dict1)
            print("space found")
    json.dump(dict2,out_file,indent=1)

out_file.close()

print("json file created")

But this code creates a json(test1.json) with only the single block of PARTNER

{
 "PARTNER": "DEF",
 "ADDRESS1": "DEF Malaysia",
 "DEPARTMENT": "",
 "CONTACT_PERSON": "",
 "TELEPHONE": "(YYY)YYYYY",
 "FAX": "(001)YYYYYYYY",
 "EMAIL": ""
}

Expected Output
I tried looking up a lot but couldn't find a way:-

{
"data":[
{
 "PARTNER": "ABC",
 "ADDRESS1": "ABC Country INN",
 "DEPARTMENT": "ABC Department",
 "CONTACT_PERSON": "HR",
 "TELEPHONE": "+91.90.XX XX X XXX",
 "FAX": "+01.XX.XX XX XX XX",
 "EMAIL": ""
},
{
 "PARTNER": "DEF",
 "ADDRESS1": "DEF Malaysia",
 "DEPARTMENT": "",
 "CONTACT_PERSON": "",
 "TELEPHONE": "(YYY)YYYYY",
 "FAX": "(001)YYYYYYYY",
 "EMAIL": ""
},
{
 "PARTNER": "GEH-LOP",
 "ADDRESS1": "GEH LOP Street",
 "DEPARTMENT": "HR",
 "CONTACT_PERSON": "Adam",
 "TELEPHONE": "+91.ZZ.ZZ.ZZZZ",
 "FAX": "+91.ZZ.ZZ.ZZZ",
 "EMAIL": ""
}
]
}


问:
Combine nested columns
I have the following:

```<code>df1 = pd.DataFrame({'data': [1,2,3]})
df2 = pd.DataFrame({'data': [4,5,6]})
df = pd.concat([df1,df2], keys=['hello','world'], axis=1)
df[('hello','new_col')] = df[('world','data')]*2
print (df)
  hello world   hello
   data  data new_col
0     1     4       8
1     2     5      10
2     3     6      12
</code>```

When I add a new nested column as above, it separates it from the existing hello column. How do I add a new nested column such that new_col is associated/beneath with the existing hello column? Can this be done during assignment or only after? I.e. I want the below

```<code>    hello        world
   data  new_col  data
0     1     4       8
1     2     5      10
2     3     6      12
</code>```

答:
You can do this after:</p>

```<code>df = df[['hello', 'world']]
print(df)

  hello         world
   data new_col  data
0     1       8     4
1     2      10     5
2     3      12     6
</code>```

Title: Combine nested columns

Body:
I have the following:

df1 = pd.DataFrame({'data': [1,2,3]})
df2 = pd.DataFrame({'data': [4,5,6]})
df = pd.concat([df1,df2], keys=['hello','world'], axis=1)
df[('hello','new_col')] = df[('world','data')]*2
print (df)
  hello world   hello
   data  data new_col
0     1     4       8
1     2     5      10
2     3     6      12

When I add a new nested column as above, it separates it from the existing hello column. How do I add a new nested column such that new_col is associated/beneath with the existing hello column? Can this be done during assignment or only after? I.e. I want the below

    hello        world
   data  new_col  data
0     1     4       8
1     2     5      10
2     3     6      12

Body:
You can do this after:

df = df[['hello', 'world']]
print(df)

  hello         world
   data new_col  data
0     1       8     4
1     2      10     5
2     3      12     6


问:
Can't get nav to be centered
I cannot get my nav to be centered on my website. Here is my code that I have tried to get working:

a:link { color: gold; }
a:visited { color: gold; }

a:hover { color: gold; }
.class1 {
  background-color: navy;
}
.class2 {
  background-color: black;
}
div p {
  background-color: navy;
}
header h1 {
  background-color: navy;
}
#idAttrubite1 {
  color: gold;
  padding: 40px;
  text-align: center;
}
#idAttrubite2 {
  color: gold;
  padding: 40px;
  text-align: center;
  font-style: italic;
}

p {
  color: gold;
  background-color: navy;
}
h1 {
  background-color: navy;
  color: gold;
  font-weight: bold;
  text-align: center;
}
h2 {
  font-weight: bold;
  color: gold;
  background-color: navy;
  text-align: left;
}
h3 {
  background-color: navy;
  color: gold;
}
ul {
  background-color: navy;
  color: gold;
}
li {
  font-style: italic;
  font-family: "Times New Roman", SansSerif, Tahoma, serif;
}
body {
  background-color: navy;
}

footer {
  background-color: white;
  text-align: center;
  font-style: italic;
  font-size: small;
  padding: 1em;
}
header {
  font-weight: bold;
  text-align: center;
  background-color: navy;
}
nav {
  overflow: hidden;
  background-color: navy;
  font-family: Arial;
  float: top;
  margin: 0;
  padding: 0;
  border-radius: 10px;
}
p img {
  transform: rotate(90deg);
  padding-top: 250px;
  padding-right: 300px;
  text-align: center;
}

#center {
  margin-right: auto;
  margin-left: auto;
}

form {
  color: gold;
}
nav a {
  float: left;
  font-size: 20px;
  color: white;
  text-align: center;
  padding: 15px 20px;
  text-decoration: none;
  list-style-type: none;
  color: white;
  height: 15px;
  border: 3px outset gold;
  background-color: navy;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml%22%3E?">
<head>
  <meta charset="utf-8" />
  <title>About My Dogs</title>
  <link rel="stylesheet" href="css.css" />
</head>
<body>
  <header>
    <h1>Home</h1>
    <img src="ellielick.jpg" height="700" />
  </header>
  <nav>
    Home
    Dogs
    Pictures
    Form
  </nav>
  <main>
    <h2><br/><br/>My Dogs</h2>
    <footer>
      Copyright © 2020 Dogs - Kolton Ukena - Phone: 316-617-6853
      <br/>
      kukena@my.wctc.edu
    </footer>
  </main>
</body></code>```

I have tried floats, I have also tried margins, and I have tried padding. What should I try next? I am working on this for my final for my web development class.

答:
You just need to wrap the nav in a UL and the links in li's (more semantic that way anyway).

Example:

```<code>   <nav>
      <ul id="nav">
        <li><a href="Index.html">Home</a></li>
        <li><a href="Dogs.html">Dogs</a></li>
        <li><a href="Pictures.html">Pictures</a></li>
        <li><a href="form.html">Form</a></li>
      </ul>
    </nav>
</code>```

CSS:

```<code>nav ul#nav{
  list-style:none;
  text-align:center;
}
nav ul#nav li{
  display:inline-block;
}
</code>```

Title: Can't get nav to be centered

Body:
I cannot get my nav to be centered on my website. Here is my code that I have tried to get working:

a:link { color: gold; }
a:visited { color: gold; }

a:hover { color: gold; }
.class1 {
  background-color: navy;
}
.class2 {
  background-color: black;
}
div p {
  background-color: navy;
}
header h1 {
  background-color: navy;
}
#idAttrubite1 {
  color: gold;
  padding: 40px;
  text-align: center;
}
#idAttrubite2 {
  color: gold;
  padding: 40px;
  text-align: center;
  font-style: italic;
}

p {
  color: gold;
  background-color: navy;
}
h1 {
  background-color: navy;
  color: gold;
  font-weight: bold;
  text-align: center;
}
h2 {
  font-weight: bold;
  color: gold;
  background-color: navy;
  text-align: left;
}
h3 {
  background-color: navy;
  color: gold;
}
ul {
  background-color: navy;
  color: gold;
}
li {
  font-style: italic;
  font-family: "Times New Roman", SansSerif, Tahoma, serif;
}
body {
  background-color: navy;
}

footer {
  background-color: white;
  text-align: center;
  font-style: italic;
  font-size: small;
  padding: 1em;
}
header {
  font-weight: bold;
  text-align: center;
  background-color: navy;
}
nav {
  overflow: hidden;
  background-color: navy;
  font-family: Arial;
  float: top;
  margin: 0;
  padding: 0;
  border-radius: 10px;
}
p img {
  transform: rotate(90deg);
  padding-top: 250px;
  padding-right: 300px;
  text-align: center;
}

#center {
  margin-right: auto;
  margin-left: auto;
}

form {
  color: gold;
}
nav a {
  float: left;
  font-size: 20px;
  color: white;
  text-align: center;
  padding: 15px 20px;
  text-decoration: none;
  list-style-type: none;
  color: white;
  height: 15px;
  border: 3px outset gold;
  background-color: navy;
}

<!DOCTYPE html>

  <meta charset="utf-8" />
  <title>About My Dogs</title>
  <link rel="stylesheet" href="css.css" />

Home

    Home
    Dogs
    Pictures
    Form

My Dogs

      Copyright © 2020 Dogs - Kolton Ukena - Phone: 316-617-6853

      kukena@my.wctc.edu

I have tried floats, I have also tried margins, and I have tried padding. What should I try next? I am working on this for my final for my web development class.

Body:
You just need to wrap the nav in a UL and the links in li's (more semantic that way anyway).

Example:

   <nav>
      <ul id="nav">
        <li><a href="Index.html">Home</a></li>
        <li><a href="Dogs.html">Dogs</a></li>
        <li><a href="Pictures.html">Pictures</a></li>
        <li><a href="form.html">Form</a></li>
      </ul>
    </nav>

CSS:

nav ul#nav{
  list-style:none;
  text-align:center;
}
nav ul#nav li{
  display:inline-block;
}


问:
Python for-loop won't iterate past first character in stirng
My python function is supposed to take an input that is a string (of only letters and only lowercase letters). The function should output true if there are no repeating letters ( regardless of whether they are consecutive letters or not) and it's suppose to return false if there are repeating letters. My code only checks if the first letter is repeating or not, but doesn't check any other letter in the string. What is the issue?

答:
Try this

```<code>def is_isogram(string):
    for x in string:
        if string.count(x) > 1:
            return False
    return True

</code>```

You want to return True only if you pass through all the for loop

Body:
Try this

def is_isogram(string):
    for x in string:
        if string.count(x) > 1:
            return False
    return True

You want to return True only if you pass through all the for loop


问:
Google App Script Insert new sheet and append columns
I will start out that I am extremely new to this. I am attempting to create a script that adds a new tab to the current google sheet document but then also extends the number of columns by 26 additional columns. So far, no matter how I try it, when the new sheet is inserted, it always only adds 26 columns. I can't figure out what I'm doing wrong. Below is the most recent code I am trying to use. It is very messy (mostly because I did it using the macro builder) and I apologize for that in advance.</p>

```<code>function AddSheet() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  //spreadsheet.getRange('D10').activate();
  spreadsheet.insertSheet(4);
  var currentCell = spreadsheet.getCurrentCell();
  var sheet = spreadsheet.getActiveSheet();
  sheet.getRange(1, 1, sheet.getMaxRows(), sheet.getMaxColumns()).activate();
  currentCell.activateAsCurrentCell();
  spreadsheet
    .getActiveSheet()
    .insertRowsAfter(spreadsheet.getActiveSheet().getMaxRows(), 99);
}
</code>```

答:
Insert new sheet and append 26 columns and 100 rows

```<code>function runOne() {
  var ss = SpreadsheetApp.getActive();
  var sh=ss.insertSheet(1);//returns sheet object
  sh.insertColumnsAfter(sh.getMaxColumns(), 26);
  sh.insertRowsAfter(sh.getMaxRows(), 100);
}
</code>```

You could also do it this way:

```<code>function runOne() {
  var ss = SpreadsheetApp.getActive();
  var sh=ss.insertSheet();
  sh.insertColumnsAfter(sh.getMaxColumns(), 26).insertRowsAfter(sh.getMaxRows(), 100);
}
</code>```

Sheet.insertColumnsAfter(afterposition,howmany)

Spreadsheet.insertSheet

Sheet.insertRowsAfter(position, howmany)

Body:
I will start out that I am extremely new to this. I am attempting to create a script that adds a new tab to the current google sheet document but then also extends the number of columns by 26 additional columns. So far, no matter how I try it, when the new sheet is inserted, it always only adds 26 columns. I can't figure out what I'm doing wrong. Below is the most recent code I am trying to use. It is very messy (mostly because I did it using the macro builder) and I apologize for that in advance.

function AddSheet() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  //spreadsheet.getRange('D10').activate();
  spreadsheet.insertSheet(4);
  var currentCell = spreadsheet.getCurrentCell();
  var sheet = spreadsheet.getActiveSheet();
  sheet.getRange(1, 1, sheet.getMaxRows(), sheet.getMaxColumns()).activate();
  currentCell.activateAsCurrentCell();
  spreadsheet
    .getActiveSheet()
    .insertRowsAfter(spreadsheet.getActiveSheet().getMaxRows(), 99);
}

Body:
Insert new sheet and append 26 columns and 100 rows

function runOne() {
  var ss = SpreadsheetApp.getActive();
  var sh=ss.insertSheet(1);//returns sheet object
  sh.insertColumnsAfter(sh.getMaxColumns(), 26);
  sh.insertRowsAfter(sh.getMaxRows(), 100);
}

You could also do it this way:

function runOne() {
  var ss = SpreadsheetApp.getActive();
  var sh=ss.insertSheet();
  sh.insertColumnsAfter(sh.getMaxColumns(), 26).insertRowsAfter(sh.getMaxRows(), 100);
}

Sheet.insertColumnsAfter(afterposition,howmany)

Spreadsheet.insertSheet

Sheet.insertRowsAfter(position, howmany)


问:
How do I make fonts of different sizes vertically centered in html spans?
I'm making a pitch controller:

```<code><div id="pitchWrapper">
  <span id="pitchButtons">-</span>
  <span id="pitchValue">0</span>
  <span id="pitchButtons">+</span>
</div>
</code>```

I want the minus, plus, and pitch value all to be vertically centered. I want the plus and minus to be a bigger font-size than the pitch value.

It works reasonably well when I set the font sizes to all be the same...

...but when I try to make the pitch buttons bigger, they align below center:

Here's my css:

```<code>#pitchWrapper {
  display: flex;
  align-items: center;
  vertical-align: middle;
}

#pitchValue {
  font-size: 200%;
}

#pitchButtons {
  font-size: 300%;
}
</code>```

How can I increase the font size of the pitch buttons while keeping everything vertically centered please?

Thank you.

答:
You can use align-items: baseline;.

#pitchWrapper {
    display: flex;
    align-items: baseline;
}
#pitchValue {
    font-size: 200%;
}
.pitchButtons {
    font-size: 300%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="pitchWrapper">
  <span class="pitchButtons">-</span>
  <span id="pitchValue">0</span>
  <span class="pitchButtons">+</span>
</div></code>```

Body:
I'm making a pitch controller:

  -
  0
  +

I want the minus, plus, and pitch value all to be vertically centered. I want the plus and minus to be a bigger font-size than the pitch value.

It works reasonably well when I set the font sizes to all be the same...

...but when I try to make the pitch buttons bigger, they align below center:

Here's my css:

#pitchWrapper {
  display: flex;
  align-items: center;
  vertical-align: middle;
}

#pitchValue {
  font-size: 200%;
}

#pitchButtons {
  font-size: 300%;
}

How can I increase the font size of the pitch buttons while keeping everything vertically centered please?

Thank you.

Body:
You can use align-items: baseline;.

#pitchWrapper {
    display: flex;
    align-items: baseline;
}
#pitchValue {
    font-size: 200%;
}
.pitchButtons {
    font-size: 300%;
}

<div id="pitchWrapper">
  <span class="pitchButtons">-</span>
  <span id="pitchValue">0</span>
  <span class="pitchButtons">+</span>
</div>


问:
How to use my own vgg19 file instead of downloading
```<code>vgg = tf.keras.applications.vgg19.VGG19(include_top=False, weights='imagenet')
vgg.trainable = False
</code>```

I have this file already downloaded on my PC, how to use that, since I don't want to download again? What will be the alternate code to use the vgg19 weights file I have?

答:
Take a look at here keras.io/api/applications. Try to locate your model into ~/.keras/models/ folder

Please make sure that your model has the same architecture with Keras's model

Body:
vgg = tf.keras.applications.vgg19.VGG19(include_top=False, weights='imagenet')
vgg.trainable = False

I have this file already downloaded on my PC, how to use that, since I don't want to download again? What will be the alternate code to use the vgg19 weights file I have?


问:
react-google-maps calls empty InfoWindow
I have problem with first call InfoWindow, it calling like 2 times and one have not any text/info and the second infoWindow have correct my info (number 2 on-screen). If I will click to another my Markeк this empty InfoWindow will stay in the first place. But if I will try to close the empty window and open any my marker this empty window will shows again in a new place.

my code:

```<code>    function MapCreator() {
  const [selectedPoint, setselectedPoint] = useState(null);
  const [data,setData] = useState([]);

  useEffect(() => {
    axios.get('api/coordinates')
    .then(values=>{
        console.log(values.data);
        setData(values.data);
    })
    const listener = e => {
      if (e.key === "Escape") {
        setselectedPoint(null);
      }
    };
    window.addEventListener("keydown", listener);

    return () => {
      window.removeEventListener("keydown", listener);
    };
  }, []);
  return (
    <GoogleMap
      defaultZoom={14}
      defaultCenter={{ lat: 50.444571, lng: 30.559099 }}
    >
      {data.map(park => (
        <Marker
          key={park._id}
          position={{
            lat: park.coordinates.latitude,
            lng: park.coordinates.longitude
          }}
          onClick={() => {
            setselectedPoint(park);
          }}
          icon={{
            url: nfcIcon,
            scaledSize: new window.google.maps.Size(60, 60)
          }}
        />
      ))}

      {selectedPoint && (
        <InfoWindow
          onCloseClick={() => {
            setselectedPoint(null);
          }}
          position={{
            lat: selectedPoint.coordinates.latitude,
            lng: selectedPoint.coordinates.longitude
          }}
        >
          <div>
                <h2>Device ID: {selectedPoint.identificatorNFC}</h2>
                <p>Date: {new Date(selectedPoint.date) .toUTCString()}</p>
          </div>
        </InfoWindow>
      )}
    </GoogleMap>
  );
}

const MapWrapped = withScriptjs(withGoogleMap(MapCreator));

export default function App() {
  return (
    <div style={{ width: `100%`, height: "100vh" }}>
      <MapWrapped
        googleMapURL={`https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places&key=${
        keys.googleApi
        }`}
        loadingElement={<div style={{ height: `100%` }} />}
        containerElement={<div style={{ height: `100%` }} />}
        mapElement={<div style={{ height: `100%` }} />}
      />
    </div>
  );
}
</code>```

答:
Tbh, I don't see any kind of problem in your code but I suggest try this out:</p>

```<code>  function MapCreator() {
  const [selectedPoint, setselectedPoint] = useState(null);
  const [data,setData] = useState([]);

  useEffect(() => {
    axios.get('api/coordinates')
    .then(values=>{
        console.log(values.data);
        setData(values.data);
    })
    const listener = e => {
      if (e.key === "Escape") {
        setselectedPoint(null);
      }
    };
    window.addEventListener("keydown", listener);

    return () => {
      window.removeEventListener("keydown", listener);
    };
  }, []);
  return (
    <GoogleMap
      defaultZoom={14}
      defaultCenter={{ lat: 50.444571, lng: 30.559099 }}
    >
      {data.map(park => (
        <Marker
          key={park._id}
          position={{
            lat: park.coordinates.latitude,
            lng: park.coordinates.longitude
          }}
          onClick={() => {
            setselectedPoint(park);
          }}
          icon={{
            url: nfcIcon,
            scaledSize: new window.google.maps.Size(60, 60)
          }}
        >
         {selectedPoint && selectedPoint._id === park._id && (
           <InfoWindow onCloseClick={() => setselectedPoint(null)}
           >
             <div>
                <h2>Device ID: {selectedPoint.identificatorNFC}</h2>
                <p>Date: {new Date(selectedPoint.date) .toUTCString()}</p>
             </div>
           </InfoWindow>
         )}
        </Marker>
      ))}

    </GoogleMap>
  );
}

const MapWrapped = withScriptjs(withGoogleMap(MapCreator));

export default function App() {
  return (
    <div style={{ width: `100%`, height: "100vh" }}>
      <MapWrapped
        googleMapURL={`https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places&key=${
        keys.googleApi
        }`}
        loadingElement={<div style={{ height: `100%` }} />}
        containerElement={<div style={{ height: `100%` }} />}
        mapElement={<div style={{ height: `100%` }} />}
      />
    </div>
  );
}
</code>```

Body:
I have problem with first call InfoWindow, it calling like 2 times and one have not any text/info and the second infoWindow have correct my info (number 2 on-screen). If I will click to another my Markeк this empty InfoWindow will stay in the first place. But if I will try to close the empty window and open any my marker this empty window will shows again in a new place.

my code:

    function MapCreator() {
  const [selectedPoint, setselectedPoint] = useState(null);
  const [data,setData] = useState([]);

  useEffect(() => {
    axios.get('api/coordinates')
    .then(values=>{
        console.log(values.data);
        setData(values.data);
    })
    const listener = e => {
      if (e.key === "Escape") {
        setselectedPoint(null);
      }
    };
    window.addEventListener("keydown", listener);

    return () => {
      window.removeEventListener("keydown", listener);
    };
  }, []);
  return (
    <GoogleMap
      defaultZoom={14}
      defaultCenter={{ lat: 50.444571, lng: 30.559099 }}
    >
      {data.map(park => (
        <Marker
          key={park._id}
          position={{
            lat: park.coordinates.latitude,
            lng: park.coordinates.longitude
          }}
          onClick={() => {
            setselectedPoint(park);
          }}
          icon={{
            url: nfcIcon,
            scaledSize: new window.google.maps.Size(60, 60)
          }}
        />
      ))}

      {selectedPoint && (
        <InfoWindow
          onCloseClick={() => {
            setselectedPoint(null);
          }}
          position={{
            lat: selectedPoint.coordinates.latitude,
            lng: selectedPoint.coordinates.longitude
          }}
        >

Device ID: {selectedPoint.identificatorNFC}

Date: {new Date(selectedPoint.date) .toUTCString()}

        </InfoWindow>
      )}
    </GoogleMap>
  );
}

const MapWrapped = withScriptjs(withGoogleMap(MapCreator));

export default function App() {
  return (
    <div style={{ width: `100%`, height: "100vh" }}>
      <MapWrapped
        googleMapURL={`https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places&key=${
        keys.googleApi
        }`}
        loadingElement={<div style={{ height: `100%` }} />}
        containerElement={<div style={{ height: `100%` }} />}
        mapElement={<div style={{ height: `100%` }} />}
      />

  );
}

Body:
Tbh, I don't see any kind of problem in your code but I suggest try this out:

  function MapCreator() {
  const [selectedPoint, setselectedPoint] = useState(null);
  const [data,setData] = useState([]);

  useEffect(() => {
    axios.get('api/coordinates')
    .then(values=>{
        console.log(values.data);
        setData(values.data);
    })
    const listener = e => {
      if (e.key === "Escape") {
        setselectedPoint(null);
      }
    };
    window.addEventListener("keydown", listener);

    return () => {
      window.removeEventListener("keydown", listener);
    };
  }, []);
  return (
    <GoogleMap
      defaultZoom={14}
      defaultCenter={{ lat: 50.444571, lng: 30.559099 }}
    >
      {data.map(park => (
        <Marker
          key={park._id}
          position={{
            lat: park.coordinates.latitude,
            lng: park.coordinates.longitude
          }}
          onClick={() => {
            setselectedPoint(park);
          }}
          icon={{
            url: nfcIcon,
            scaledSize: new window.google.maps.Size(60, 60)
          }}
        >
         {selectedPoint && selectedPoint._id === park._id && (
           <InfoWindow onCloseClick={() => setselectedPoint(null)}
           >
             <div>
                <h2>Device ID: {selectedPoint.identificatorNFC}</h2>
                <p>Date: {new Date(selectedPoint.date) .toUTCString()}</p>
             </div>
           </InfoWindow>
         )}
        </Marker>
      ))}

    </GoogleMap>
  );
}

const MapWrapped = withScriptjs(withGoogleMap(MapCreator));

export default function App() {
  return (
    <div style={{ width: `100%`, height: "100vh" }}>
      <MapWrapped
        googleMapURL={`https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places&key=${
        keys.googleApi
        }`}
        loadingElement={<div style={{ height: `100%` }} />}
        containerElement={<div style={{ height: `100%` }} />}
        mapElement={<div style={{ height: `100%` }} />}
      />
    </div>
  );
}


问:
Get value from json in LogicApp
Rephrasing question entirely, as first attempt was unclear.

In my logic app I am reading a .json from blob which contains:

```<code>{
    "alpha": {
        "url": "https://linktoalpha.com",
        "meta": "This logic app does job aaaa"
    },
    "beta": {
        "url": "https://linktobeta.com",
        "meta": "This logic app does job beta"
    },
    "theta": {
        "url": "https://linktotheta.com",
        "meta": "This logic app does job theta"
    }
}
</code>```

I'm triggering the logic app with a http post which contains in the body:

```<code>{ "logicappname": "beta" }
</code>```

But the value for 'logicappname' could be alpha, beta or theta. I now need to set a variable which contains the url value for 'beta'. How can this be achieved without jsonpath support?

I am already json parsing the file contents from the blob and this IS giving me the tokens... but I cannot see how to select the value I need. Would appreciate any assistance, thank you.

答:
For your requirement, I think just use "Parse JSON" action to do it. Please refer to the steps below:

1. I upload a file testJson.json to my blob storage, then get it and parse it in my logic app.

2. We can see there are three url in the screenshot below. As you want to get the url value for beta, it is the second one, so we can choose the second one.

If you want to get the url value by the param logicappname from the "When a HTTP request is received" trigger, you can use a expression when you create the result variable.

In my screenshot, the expression is:

```<code>body('Parse_JSON')?[triggerBody()?['logicappname']]?['url']
</code>```

As the description of your question is a little unclear and I'm confused about the meaning of I am already json parsing the file contents from the blob and this IS giving me the tokens, why is "tokens" involved in it ? And in the original question it seems you want to do it by jsonpath but in the latest description you said without jsonpath ? So if I misunderstand your question, please let me know. Thanks.

Title: Get value from json in LogicApp

Body:
Rephrasing question entirely, as first attempt was unclear.

In my logic app I am reading a .json from blob which contains:

{
    "alpha": {
        "url": "https://linktoalpha.com",
        "meta": "This logic app does job aaaa"
    },
    "beta": {
        "url": "https://linktobeta.com",
        "meta": "This logic app does job beta"
    },
    "theta": {
        "url": "https://linktotheta.com",
        "meta": "This logic app does job theta"
    }
}

I'm triggering the logic app with a http post which contains in the body:

{ "logicappname": "beta" }

But the value for 'logicappname' could be alpha, beta or theta. I now need to set a variable which contains the url value for 'beta'. How can this be achieved without jsonpath support?

I am already json parsing the file contents from the blob and this IS giving me the tokens... but I cannot see how to select the value I need. Would appreciate any assistance, thank you.

Body:
For your requirement, I think just use "Parse JSON" action to do it. Please refer to the steps below:

1. I upload a file testJson.json to my blob storage, then get it and parse it in my logic app.

2. We can see there are three url in the screenshot below. As you want to get the url value for beta, it is the second one, so we can choose the second one.

If you want to get the url value by the param logicappname from the "When a HTTP request is received" trigger, you can use a expression when you create the result variable.

In my screenshot, the expression is:

body('Parse_JSON')?[triggerBody()?['logicappname']]?['url']

As the description of your question is a little unclear and I'm confused about the meaning of I am already json parsing the file contents from the blob and this IS giving me the tokens, why is "tokens" involved in it ? And in the original question it seems you want to do it by jsonpath but in the latest description you said without jsonpath ? So if I misunderstand your question, please let me know. Thanks.


问:
Doing a custom legend of marker sizes in matplotlib using a lambda function?
I am playing with the third example of "Scatter plots with a legend" in the matplotlib manual.

I have tweaked the marker sizes to:

```<code>s = (50 / price) ** 2
</code>```

And as an input to legend_elements I am using:

```<code>func=lambda s: 50 / np.sqrt(s)
</code>```

I get the output below. The marker sizes of the legend are wrong. Why is that?

Here is the code:

```<code>import numpy as np
import matplotlib.pyplot as plt

volume = np.random.rayleigh(27, size=40)
amount = np.random.poisson(10, size=40)
ranking = np.random.normal(size=40)
price = np.random.uniform(1, 10, size=40)

fig, ax = plt.subplots()

s = (50 / price) ** 2

scatter = ax.scatter(volume, amount, c=ranking, s=s,
                     vmin=-3, vmax=3, cmap="Spectral", label=price)

legend1 = ax.legend(*scatter.legend_elements(num=5),
                    loc="upper left", title="Ranking")
ax.add_artist(legend1)

kw = dict(prop="sizes", num=5, color=scatter.cmap(0.7), fmt="$ {x:.2f}",
          func=lambda s: 50 / np.sqrt(s),
          )
legend2 = ax.legend(*scatter.legend_elements(**kw),
                    loc="lower right", title="Price")

for p, v, a in zip(price, volume, amount):
    ax.annotate(round(p, 0), (v, a))
plt.show()
</code>```

答:
The issue appears to be related to the inverse relationship between price and marker size. The way the data is calculated in legend_elements doesn't account for this, and the calculation doesn't quite work. I've submitted a pull request.

The problem is in np.interp that expects increasing input for the second argument. Here is a work around for now that sorts the input first:

```<code>legend2 = ax.legend(*legend_elements(scatter, **kw),
                loc="lower right", title="Price")
</code>```

Run this after defining legend_elements as:

```<code>def legend_elements(self, prop="colors", num="auto",
                 fmt=None, func=lambda x: x, **kwargs):
    """
    Creates legend handles and labels for a PathCollection. This is useful
    for obtaining a legend for a :meth:`~.Axes.scatter` plot. E.g.::

        scatter = plt.scatter([1, 2, 3],  [4, 5, 6],  c=[7, 2, 3])
        plt.legend(*scatter.legend_elements())

    Also see the :ref:`automatedlegendcreation` example.

    Parameters
    ----------
    prop : string, optional, default *"colors"*
        Can be *"colors"* or *"sizes"*. In case of *"colors"*, the legend
        handles will show the different colors of the collection. In case
        of "sizes", the legend will show the different sizes.
    num : int, None, "auto" (default), array-like, or `~.ticker.Locator`,
        optional
        Target number of elements to create.
        If None, use all unique elements of the mappable array. If an
        integer, target to use *num* elements in the normed range.
        If *"auto"*, try to determine which option better suits the nature
        of the data.
        The number of created elements may slightly deviate from *num* due
        to a `~.ticker.Locator` being used to find useful locations.
        If a list or array, use exactly those elements for the legend.
        Finally, a `~.ticker.Locator` can be provided.
    fmt : str, `~matplotlib.ticker.Formatter`, or None (default)
        The format or formatter to use for the labels. If a string must be
        a valid input for a `~.StrMethodFormatter`. If None (the default),
        use a `~.ScalarFormatter`.
    func : function, default *lambda x: x*
        Function to calculate the labels. Often the size (or color)
        argument to :meth:`~.Axes.scatter` will have been pre-processed
        by the user using a function *s = f(x)* to make the markers
        visible; e.g. *size = np.log10(x)*. Providing the inverse of this
        function here allows that pre-processing to be inverted, so that
        the legend labels have the correct values;
        e.g. *func = np.exp(x, 10)*.
    kwargs : further parameters
        Allowed keyword arguments are *color* and *size*. E.g. it may be
        useful to set the color of the markers if *prop="sizes"* is used;
        similarly to set the size of the markers if *prop="colors"* is
        used. Any further parameters are passed onto the `.Line2D`
        instance. This may be useful to e.g. specify a different
        *markeredgecolor* or *alpha* for the legend handles.

    Returns
    -------
    tuple (handles, labels)
        with *handles* being a list of `.Line2D`  objects
        and *labels* a matching list of strings.
    """
    handles = []
    labels = []
    hasarray = self.get_array() is not None
    if fmt is None:
        fmt = mpl.ticker.ScalarFormatter(useOffset=False, useMathText=True)
    elif isinstance(fmt, str):
        fmt = mpl.ticker.StrMethodFormatter(fmt)
    fmt.create_dummy_axis()

    if prop == "colors":
        if not hasarray:
            warnings.warn("Collection without array used. Make sure to "
                          "specify the values to be colormapped via the "
                          "`c` argument.")
            return handles, labels
        u = np.unique(self.get_array())
        size = kwargs.pop("size", mpl.rcParams["lines.markersize"])
    elif prop == "sizes":
        u = np.unique(self.get_sizes())
        color = kwargs.pop("color", "k")
    else:
        raise ValueError("Valid values for `prop` are 'colors' or "
                         f"'sizes'. You supplied '{prop}' instead.")

    fmt.set_bounds(func(u).min(), func(u).max())
    if num == "auto":
        num = 9
        if len(u) <= num:
            num = None
    if num is None:
        values = u
        label_values = func(values)
    else:
        if prop == "colors":
            arr = self.get_array()
        elif prop == "sizes":
            arr = self.get_sizes()
        if isinstance(num, mpl.ticker.Locator):
            loc = num
        elif np.iterable(num):
            loc = mpl.ticker.FixedLocator(num)
        else:
            num = int(num)
            loc = mpl.ticker.MaxNLocator(nbins=num, min_n_ticks=num-1,
                                         steps=[1, 2, 2.5, 3, 5, 6, 8, 10])
        label_values = loc.tick_values(func(arr).min(), func(arr).max())
        cond = ((label_values >= func(arr).min()) &
                (label_values <= func(arr).max()))
        label_values = label_values[cond]
        yarr = np.linspace(arr.min(), arr.max(), 256)
        xarr = func(yarr)
        ix = np.argsort(xarr)
        values = np.interp(label_values, xarr[ix], yarr[ix])

    kw = dict(markeredgewidth=self.get_linewidths()[0],
              alpha=self.get_alpha())
    kw.update(kwargs)

    for val, lab in zip(values, label_values):
        if prop == "colors":
            color = self.cmap(self.norm(val))
        elif prop == "sizes":
            size = np.sqrt(val)
            if np.isclose(size, 0.0):
                continue
        h = mlines.Line2D([0], [0], ls="", color=color, ms=size,
                          marker=self.get_paths()[0], **kw)
        handles.append(h)
        if hasattr(fmt, "set_locs"):
            fmt.set_locs(label_values)
        l = fmt(lab)
        labels.append(l)

    return handles, labels
</code>```

Body:
I am playing with the third example of "Scatter plots with a legend" in the matplotlib manual.

I have tweaked the marker sizes to:

s = (50 / price) ** 2

And as an input to legend_elements I am using:

func=lambda s: 50 / np.sqrt(s)

I get the output below. The marker sizes of the legend are wrong. Why is that?

Here is the code:

import numpy as np
import matplotlib.pyplot as plt

volume = np.random.rayleigh(27, size=40)
amount = np.random.poisson(10, size=40)
ranking = np.random.normal(size=40)
price = np.random.uniform(1, 10, size=40)

fig, ax = plt.subplots()

s = (50 / price) ** 2

scatter = ax.scatter(volume, amount, c=ranking, s=s,
                     vmin=-3, vmax=3, cmap="Spectral", label=price)

legend1 = ax.legend(*scatter.legend_elements(num=5),
                    loc="upper left", title="Ranking")
ax.add_artist(legend1)

kw = dict(prop="sizes", num=5, color=scatter.cmap(0.7), fmt="$ {x:.2f}",
          func=lambda s: 50 / np.sqrt(s),
          )
legend2 = ax.legend(*scatter.legend_elements(**kw),
                    loc="lower right", title="Price")

for p, v, a in zip(price, volume, amount):
    ax.annotate(round(p, 0), (v, a))
plt.show()

Body:
The issue appears to be related to the inverse relationship between price and marker size. The way the data is calculated in legend_elements doesn't account for this, and the calculation doesn't quite work. I've submitted a pull request.

The problem is in np.interp that expects increasing input for the second argument. Here is a work around for now that sorts the input first:

legend2 = ax.legend(*legend_elements(scatter, **kw),
                loc="lower right", title="Price")

Run this after defining legend_elements as:

def legend_elements(self, prop="colors", num="auto",
                 fmt=None, func=lambda x: x, **kwargs):
    """
    Creates legend handles and labels for a PathCollection. This is useful
    for obtaining a legend for a :meth:`~.Axes.scatter` plot. E.g.::

        scatter = plt.scatter([1, 2, 3],  [4, 5, 6],  c=[7, 2, 3])
        plt.legend(*scatter.legend_elements())

    Also see the :ref:`automatedlegendcreation` example.

    Parameters
    ----------
    prop : string, optional, default *"colors"*
        Can be *"colors"* or *"sizes"*. In case of *"colors"*, the legend
        handles will show the different colors of the collection. In case
        of "sizes", the legend will show the different sizes.
    num : int, None, "auto" (default), array-like, or `~.ticker.Locator`,
        optional
        Target number of elements to create.
        If None, use all unique elements of the mappable array. If an
        integer, target to use *num* elements in the normed range.
        If *"auto"*, try to determine which option better suits the nature
        of the data.
        The number of created elements may slightly deviate from *num* due
        to a `~.ticker.Locator` being used to find useful locations.
        If a list or array, use exactly those elements for the legend.
        Finally, a `~.ticker.Locator` can be provided.
    fmt : str, `~matplotlib.ticker.Formatter`, or None (default)
        The format or formatter to use for the labels. If a string must be
        a valid input for a `~.StrMethodFormatter`. If None (the default),
        use a `~.ScalarFormatter`.
    func : function, default *lambda x: x*
        Function to calculate the labels. Often the size (or color)
        argument to :meth:`~.Axes.scatter` will have been pre-processed
        by the user using a function *s = f(x)* to make the markers
        visible; e.g. *size = np.log10(x)*. Providing the inverse of this
        function here allows that pre-processing to be inverted, so that
        the legend labels have the correct values;
        e.g. *func = np.exp(x, 10)*.
    kwargs : further parameters
        Allowed keyword arguments are *color* and *size*. E.g. it may be
        useful to set the color of the markers if *prop="sizes"* is used;
        similarly to set the size of the markers if *prop="colors"* is
        used. Any further parameters are passed onto the `.Line2D`
        instance. This may be useful to e.g. specify a different
        *markeredgecolor* or *alpha* for the legend handles.

    Returns
    -------
    tuple (handles, labels)
        with *handles* being a list of `.Line2D`  objects
        and *labels* a matching list of strings.
    """
    handles = []
    labels = []
    hasarray = self.get_array() is not None
    if fmt is None:
        fmt = mpl.ticker.ScalarFormatter(useOffset=False, useMathText=True)
    elif isinstance(fmt, str):
        fmt = mpl.ticker.StrMethodFormatter(fmt)
    fmt.create_dummy_axis()

    if prop == "colors":
        if not hasarray:
            warnings.warn("Collection without array used. Make sure to "
                          "specify the values to be colormapped via the "
                          "`c` argument.")
            return handles, labels
        u = np.unique(self.get_array())
        size = kwargs.pop("size", mpl.rcParams["lines.markersize"])
    elif prop == "sizes":
        u = np.unique(self.get_sizes())
        color = kwargs.pop("color", "k")
    else:
        raise ValueError("Valid values for `prop` are 'colors' or "
                         f"'sizes'. You supplied '{prop}' instead.")

    fmt.set_bounds(func(u).min(), func(u).max())
    if num == "auto":
        num = 9
        if len(u) <= num:
            num = None
    if num is None:
        values = u
        label_values = func(values)
    else:
        if prop == "colors":
            arr = self.get_array()
        elif prop == "sizes":
            arr = self.get_sizes()
        if isinstance(num, mpl.ticker.Locator):
            loc = num
        elif np.iterable(num):
            loc = mpl.ticker.FixedLocator(num)
        else:
            num = int(num)
            loc = mpl.ticker.MaxNLocator(nbins=num, min_n_ticks=num-1,
                                         steps=[1, 2, 2.5, 3, 5, 6, 8, 10])
        label_values = loc.tick_values(func(arr).min(), func(arr).max())
        cond = ((label_values >= func(arr).min()) &
                (label_values <= func(arr).max()))
        label_values = label_values[cond]
        yarr = np.linspace(arr.min(), arr.max(), 256)
        xarr = func(yarr)
        ix = np.argsort(xarr)
        values = np.interp(label_values, xarr[ix], yarr[ix])

    kw = dict(markeredgewidth=self.get_linewidths()[0],
              alpha=self.get_alpha())
    kw.update(kwargs)

    for val, lab in zip(values, label_values):
        if prop == "colors":
            color = self.cmap(self.norm(val))
        elif prop == "sizes":
            size = np.sqrt(val)
            if np.isclose(size, 0.0):
                continue
        h = mlines.Line2D([0], [0], ls="", color=color, ms=size,
                          marker=self.get_paths()[0], **kw)
        handles.append(h)
        if hasattr(fmt, "set_locs"):
            fmt.set_locs(label_values)
        l = fmt(lab)
        labels.append(l)

    return handles, labels


答:
the following should rectify.

def is_isogram(s: str):

    # loop through all unique chars
    for x in set(s):
        if s.count(x) > 1:
            return True

    # terminate after looping through all chars
    return False
```

additionally convert string to a set to eliminate iterating over same char twice.

Title: Python for-loop won't iterate past first character in stirng

Body: My python function is supposed to take an input that is a string (of only letters and only lowercase letters). The function should output true if there are no repeating letters ( regardless of whether they are consecutive letters or not) and it's suppose to return false if there are repeating letters. My code only checks if the first letter is repeating or not, but doesn't check any other letter in the string. What is the issue?

Body:
the following should rectify.

def is_isogram(s: str):

    # loop through all unique chars
    for x in set(s):
        if s.count(x) > 1:
            return True

    # terminate after looping through all chars
    return False

additionally convert string to a set to eliminate iterating over same char twice.


问:
Create TestNg Xml file programmatically using Java
I have a following testNg xml file.

Can someone please advice how to create this dynamically using java.

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
  <test name="Test">
    <groups>
     <run>
       <include name="PrometheusHome" />
       <include name="AlertMgrHome" />
     </run>
   </groups>
    <classes>
      <class name="com.amex.eag.telemetry.testcases.PrometheusTests"/>
      <class name="com.amex.eag.telemetry.testcases.AlertManagerTests"/>
    </classes>
  </test>
</suite>
</code>```

答:
TestNG Official Documentation on Programattic Execution
If you are looking to run your tests programmatically, it's best to read an existing testng XML file, do some runtime modifications and run it programmatically. This would basically avoid the problem of hardcoding class names and test names in the code. If you are hardcoding test names and class names, then you would need to change the test names and class names every time you need to run a different case. So please avoid hardcoding. Please follow the below approach, it would suit your need.

```<code>    List<String> deviceNames = StringUtils.isEmpty(System.getProperty("deviceNames")) ?
new ArrayList<>() : Arrays.asList(System.getProperty("deviceNames").split(","));
                TestNG tng = new TestNG();
                File initialFile = new File("testng.xml");
                InputStream inputStream = FileUtils.openInputStream(initialFile);
                Parser p = new Parser(inputStream);
                List<XmlSuite> suites = p.parseToList();
                List<XmlSuite> modifiedSuites = new ArrayList<>();
                for (XmlSuite suite : suites) {
                    XmlSuite modifiedSuite = new XmlSuite();
                    modifiedSuite.setParallel(suite.getParallel());
                    modifiedSuite.setThreadCount(deviceNames.size());
                    modifiedSuite.setName(suite.getName());
                    modifiedSuite.setListeners(suite.getListeners());
                    List<XmlTest> tests = suite.getTests();
                    for (XmlTest test : tests) {
                        for (int i = 0; i < deviceNames.size(); i++) {
                            XmlTest modifedtest = new XmlTest(modifiedSuite);
                            HashMap<String, String> parametersMap = new HashMap<>();
                            parametersMap.put("deviceName", deviceNames.get(i));
                            modifedtest.setParameters(parametersMap);
                            modifedtest.setName(test.getName() + "Device - " + deviceNames.get(i) +
                                    ", OS Version - " + platformVersions.get(i));
                            modifedtest.setXmlClasses(test.getXmlClasses());
                        }
                    }
                    modifiedSuites.add(modifiedSuite);
                }
                inputStream.close();
                tng.setXmlSuites(modifiedSuites);
                tng.run();
</code>```

I am adding runtime parameters to each and every test based on the parameters passed in the maven runtime arguments. You could use the same approach for passing test names or class names as runtime arguments and update your testng XML file as per your need.

Body:
I have a following testNg xml file.

Can someone please advice how to create this dynamically using java.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
  <test name="Test">
    <groups>
     <run>
       <include name="PrometheusHome" />
       <include name="AlertMgrHome" />
     </run>
   </groups>
    <classes>
      <class name="com.amex.eag.telemetry.testcases.PrometheusTests"/>
      <class name="com.amex.eag.telemetry.testcases.AlertManagerTests"/>
    </classes>
  </test>
</suite>

Body:
TestNG Official Documentation on Programattic Execution
If you are looking to run your tests programmatically, it's best to read an existing testng XML file, do some runtime modifications and run it programmatically. This would basically avoid the problem of hardcoding class names and test names in the code. If you are hardcoding test names and class names, then you would need to change the test names and class names every time you need to run a different case. So please avoid hardcoding. Please follow the below approach, it would suit your need.

    List<String> deviceNames = StringUtils.isEmpty(System.getProperty("deviceNames")) ?
new ArrayList<>() : Arrays.asList(System.getProperty("deviceNames").split(","));
                TestNG tng = new TestNG();
                File initialFile = new File("testng.xml");
                InputStream inputStream = FileUtils.openInputStream(initialFile);
                Parser p = new Parser(inputStream);
                List<XmlSuite> suites = p.parseToList();
                List<XmlSuite> modifiedSuites = new ArrayList<>();
                for (XmlSuite suite : suites) {
                    XmlSuite modifiedSuite = new XmlSuite();
                    modifiedSuite.setParallel(suite.getParallel());
                    modifiedSuite.setThreadCount(deviceNames.size());
                    modifiedSuite.setName(suite.getName());
                    modifiedSuite.setListeners(suite.getListeners());
                    List<XmlTest> tests = suite.getTests();
                    for (XmlTest test : tests) {
                        for (int i = 0; i < deviceNames.size(); i++) {
                            XmlTest modifedtest = new XmlTest(modifiedSuite);
                            HashMap<String, String> parametersMap = new HashMap<>();
                            parametersMap.put("deviceName", deviceNames.get(i));
                            modifedtest.setParameters(parametersMap);
                            modifedtest.setName(test.getName() + "Device - " + deviceNames.get(i) +
                                    ", OS Version - " + platformVersions.get(i));
                            modifedtest.setXmlClasses(test.getXmlClasses());
                        }
                    }
                    modifiedSuites.add(modifiedSuite);
                }
                inputStream.close();
                tng.setXmlSuites(modifiedSuites);
                tng.run();

I am adding runtime parameters to each and every test based on the parameters passed in the maven runtime arguments. You could use the same approach for passing test names or class names as runtime arguments and update your testng XML file as per your need.


问:
Create azure application through Az module and assign API permissions using powershell
I have written a script which creates azure application using Az module, creates secret key, assigns owner. But assigning API permission gives insufficient permission error. The user is an admin user. Still unable to assign API permission. What wrong am I doing?

```<code>$ErrorActionPreference = 'Stop'
Connect-AzAccount
Import-Module Az.Resources
$tenant = Get-AzTenant
Set-AzContext -TenantId $tenant.Id
$AppName = Read-Host -Prompt 'Enter Application name '
$myApp = New-AzADApplication -DisplayName $AppName -IdentifierUris "http://$AppName.com"
Write-Host "App registered.."
$sp = New-AzADServicePrincipal -ApplicationId $myApp.ApplicationId -Role Owner
Write-Host "Service principal registered.."
$startDate = Get-Date
$endDate = $startDate.AddYears(100)
$secret = Read-Host -Prompt 'Enter App Secret Key ' -AsSecureString
$secPassword = ConvertTo-SecureString -AsPlainText -Force -String $secret
New-AzADAppCredential -ObjectId $myApp.ObjectId  -StartDate $startDate -EndDate $endDate -Password $secPassword

$ResourceAppIdURI = "https://graph.windows.net/"
# $authority = "https://login.microsoftonline.com/$tenant/oauth2/v2.0/token"
$authority = "https://login.windows.net/$tenant/oauth2/token"
$ClientCred = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential" -ArgumentList $myApp.ApplicationId, $secret
$AuthContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority,$false
$AuthContext.TokenCache.Clear()
Start-Sleep -Seconds 10
$Token = $Authcontext.AcquireTokenAsync($ResourceAppIdURI, $ClientCred)

$AuthHeader = @{"Authorization" = $Token.Result.CreateAuthorizationHeader();"Content-Type"="application/json"}
$url = "https://graph.windows.net/$tenant/applications/$($myApp.ObjectID)?api-version=1.6"
Write-Host "URL: " $url

$postData = "{`"requiredResourceAccess`":[{`"resourceAppId`":`"00000003-0000-0000-c000-000000000000`",
`"resourceAccess`":[{`"id`":`"e1fe6dd8-ba31-4d61-89e7-88639da4683d`",`"type`":`"Scope`"}]}]}";
$result = Invoke-RestMethod -Uri $url -Method "PATCH" -Headers $AuthHeader -Body $postData
Write-Host "Result of App API permission: " $result
</code>```

答:
If you want to call Azure AAD graph API to assign permissions with OAuth 2.0 client credentials flow, we need to provide enough permissions(Azure AD Graph -> Aapplication permissions -> Application.ReadWrite.All)

Besides, regarding how to assign permissions to AD application with PowerShell, we also can use PowerShell module AzureAD.

For example

```<code>Connect-AzureAD
$AppAccess = [Microsoft.Open.AzureAD.Model.RequiredResourceAccess]@{
    ResourceAppId = "00000003-0000-0000-c000-000000000000";
    ResourceAccess =
        [Microsoft.Open.AzureAD.Model.ResourceAccess]@{
            Id = "";
            Type = ""},
        [Microsoft.Open.AzureAD.Model.ResourceAccess]@{
            Id = "";
            Type = ""}
}
Set-AzureADApplication -ObjectId <the app object id> -RequiredResourceAccess $AppAccess
</code>```

Update

According to my test, when we use Az module, we can use the following method to get access token and call AAD graph rest API. But please note that when you use the method, the account you use to run Connect-AzAccount should be Azure AD Global Admin

```<code>Connect-AzAccount

$context =Get-AzContext
$dexResourceUrl='https://graph.windows.net/'
$token = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account,
                                $context.Environment,
                                $context.Tenant.Id.ToString(),
                                 $null,
                                 [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never,
                                 $null, $dexResourceUrl).AccessToken

# assign permissions
$headers =@{}
$headers.Add("Content-Type", "application/json")
$headers.Add("Accept", "application/json")
$headers.Add("Authorization", "Bearer $($token)")
$body = "{
`n    `"requiredResourceAccess`": [{
`n            `"resourceAppId`": `"00000003-0000-0000-c000-000000000000`",
`n            `"resourceAccess`": [
`n              {
`n                  `"id`": `"405a51b5-8d8d-430b-9842-8be4b0e9f324`",
`n                  `"type`": `"Role`"
`n              },
`n              {
`n                  `"id`": `"09850681-111b-4a89-9bed-3f2cae46d706`",
`n                  `"type`": `"Role`"
`n              }
`n          ]
`n        }
`n    ]
`n}
`n"
$url ='https://graph.windows.net/hanxia.onmicrosoft.com/applications/d4975420-841f-47d5-a3d2-0870901f13cd?api-version=1.6'
Invoke-RestMethod $url  -Method 'PATCH' -Headers $headers -Body $body

#check if adding the permissions you need
$headers =@{}
$headers.Add("Accept", "application/json")
$headers.Add("Authorization", "Bearer $($token)")
$url ='https://graph.windows.net/hanxia.onmicrosoft.com/applications/<aad application object id>?api-version=1.6'
$response=Invoke-RestMethod $url  -Method 'GET' -Headers $headers
$response.requiredResourceAccess | ConvertTo-Json
</code>```

Body:
I have written a script which creates azure application using Az module, creates secret key, assigns owner. But assigning API permission gives insufficient permission error. The user is an admin user. Still unable to assign API permission. What wrong am I doing?

$ErrorActionPreference = 'Stop'
Connect-AzAccount
Import-Module Az.Resources
$tenant = Get-AzTenant
Set-AzContext -TenantId $tenant.Id
$AppName = Read-Host -Prompt 'Enter Application name '
$myApp = New-AzADApplication -DisplayName $AppName -IdentifierUris "http://$AppName.com"
Write-Host "App registered.."
$sp = New-AzADServicePrincipal -ApplicationId $myApp.ApplicationId -Role Owner
Write-Host "Service principal registered.."
$startDate = Get-Date
$endDate = $startDate.AddYears(100)
$secret = Read-Host -Prompt 'Enter App Secret Key ' -AsSecureString
$secPassword = ConvertTo-SecureString -AsPlainText -Force -String $secret
New-AzADAppCredential -ObjectId $myApp.ObjectId  -StartDate $startDate -EndDate $endDate -Password $secPassword

$ResourceAppIdURI = "https://graph.windows.net/"
# $authority = "https://login.microsoftonline.com/$tenant/oauth2/v2.0/token"
$authority = "https://login.windows.net/$tenant/oauth2/token"
$ClientCred = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential" -ArgumentList $myApp.ApplicationId, $secret
$AuthContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority,$false
$AuthContext.TokenCache.Clear()
Start-Sleep -Seconds 10
$Token = $Authcontext.AcquireTokenAsync($ResourceAppIdURI, $ClientCred)

$AuthHeader = @{"Authorization" = $Token.Result.CreateAuthorizationHeader();"Content-Type"="application/json"}
$url = "https://graph.windows.net/$tenant/applications/$($myApp.ObjectID)?api-version=1.6"
Write-Host "URL: " $url

$postData = "{`"requiredResourceAccess`":[{`"resourceAppId`":`"00000003-0000-0000-c000-000000000000`",
`"resourceAccess`":[{`"id`":`"e1fe6dd8-ba31-4d61-89e7-88639da4683d`",`"type`":`"Scope`"}]}]}";
$result = Invoke-RestMethod -Uri $url -Method "PATCH" -Headers $AuthHeader -Body $postData
Write-Host "Result of App API permission: " $result

Body:
If you want to call Azure AAD graph API to assign permissions with OAuth 2.0 client credentials flow, we need to provide enough permissions(Azure AD Graph -> Aapplication permissions -> Application.ReadWrite.All)

Besides, regarding how to assign permissions to AD application with PowerShell, we also can use PowerShell module AzureAD.

For example

Connect-AzureAD
$AppAccess = [Microsoft.Open.AzureAD.Model.RequiredResourceAccess]@{
    ResourceAppId = "00000003-0000-0000-c000-000000000000";
    ResourceAccess =
        [Microsoft.Open.AzureAD.Model.ResourceAccess]@{
            Id = "";
            Type = ""},
        [Microsoft.Open.AzureAD.Model.ResourceAccess]@{
            Id = "";
            Type = ""}
}
Set-AzureADApplication -ObjectId <the app object id> -RequiredResourceAccess $AppAccess

Update

According to my test, when we use Az module, we can use the following method to get access token and call AAD graph rest API. But please note that when you use the method, the account you use to run Connect-AzAccount should be Azure AD Global Admin

Connect-AzAccount

$context =Get-AzContext
$dexResourceUrl='https://graph.windows.net/'
$token = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account,
                                $context.Environment,
                                $context.Tenant.Id.ToString(),
                                 $null,
                                 [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never,
                                 $null, $dexResourceUrl).AccessToken

# assign permissions
$headers =@{}
$headers.Add("Content-Type", "application/json")
$headers.Add("Accept", "application/json")
$headers.Add("Authorization", "Bearer $($token)")
$body = "{
`n    `"requiredResourceAccess`": [{
`n            `"resourceAppId`": `"00000003-0000-0000-c000-000000000000`",
`n            `"resourceAccess`": [
`n              {
`n                  `"id`": `"405a51b5-8d8d-430b-9842-8be4b0e9f324`",
`n                  `"type`": `"Role`"
`n              },
`n              {
`n                  `"id`": `"09850681-111b-4a89-9bed-3f2cae46d706`",
`n                  `"type`": `"Role`"
`n              }
`n          ]
`n        }
`n    ]
`n}
`n"
$url ='https://graph.windows.net/hanxia.onmicrosoft.com/applications/d4975420-841f-47d5-a3d2-0870901f13cd?api-version=1.6'
Invoke-RestMethod $url  -Method 'PATCH' -Headers $headers -Body $body

#check if adding the permissions you need
$headers =@{}
$headers.Add("Accept", "application/json")
$headers.Add("Authorization", "Bearer $($token)")
$url ='https://graph.windows.net/hanxia.onmicrosoft.com/applications/<aad application object id>?api-version=1.6'
$response=Invoke-RestMethod $url  -Method 'GET' -Headers $headers
$response.requiredResourceAccess | ConvertTo-Json


答: You're not making it past the first character because in the first iteration of the for loop, your "else" exits the function if the if statement returns false.</p>


问:
Vue JS - How to get window size whenever it changes
I'm new to vuejs but I was trying to get the window size whenever I
   resize it so that i can compare it to some value for a function that I
   need to apply depending on the screen size. I also tried using the
   watch property but not sure how to handle it so that's probably why it didn't work </p>

```<code>  methods: {

    elem() {
     this.size = window.innerWidth;
     return this.size;
   },
  mounted() {
    if (this.elem < 767){ //some code }
   }
</code>```

答:
I looked at the code of that library vue-window-size, and besides the additional logic, it's just adding an event listener on window resize, and it looks like it can be instructed to debounce. Source

The critical problem for me is that my Vue SPA app does not emit a window resize event when a vue-router route changes that makes the  element go from 1000px to 4000px, so it's causing me all kinds of problems watching a canvas element controlled by p5.js to redraw a wallpaper using p5.resizeCanvas().

I have a different solution now that involves actively polling the page's offset height.

The first thing to be aware of is JavaScript memory management, so to avoid memory leaks, I put setInterval in the created lifecycle method and clearInterval in the beforeDestroy lifecycle method:

```<code>created() {
    this.refreshScrollableArea = setInterval(() => {
        const { offsetWidth, offsetHeight } = document.getElementById('app');
        this.offsetWidth = offsetWidth;
        this.offsetHeight = offsetHeight;
    }, 100);
},

beforeDestroy() {
    return clearInterval(this.refreshScrollableArea);
},
</code>```

As hinted in the above code, I also placed some initial state:

```<code>data() {
    const { offsetWidth, offsetHeight } = document.querySelector('#app');

    return {
        offsetWidth,
        offsetHeight,
        refreshScrollableArea: undefined,
    };
},
</code>```

Note: if you are using getElementById with something like this.id (ie: an element that is a child in this component), document.getElementById(this.id) will be undefined because DOM elements load outer-to-inner, so if you see an error stemming from the data instantiation, set the width/height to 0 initially.

Then, I put a watcher on offsetHeight to listen for height changes and perform business logic:

```<code>    watch: {
        offsetHeight() {
            console.log('offsetHeight changed', this.offsetHeight);

            this.state = IS_RESET;
            this.setState(this.sketch);
            return this.draw(this.sketch);
        },
    },
</code>```

Conclusion: I tested with performance.now() and:

```<code>document.querySelector('#app').offsetHeight
document.getElementById('app').offsetHeight
document.querySelector('#app').getClientBoundingRect().height
</code>```

all execute in about the exact same amount of time: 0.2ms, so the above code is costing about 0.2ms every 100ms. I currently find that reasonable in my app including after I adjust for slow clients that operate an order of magnitude slower than my localmachine.

Here is the test logic for your own R&D:

```<code>const t0 = performance.now();
const { offsetWidth, offsetHeight } = document.getElementById('app');
const t1 = performance.now();

console.log('execution time:', (t1 - t0), 'ms');
</code>```

Bonus: if you get any performance issue due to long-running execution time on your setInterval function, try wrapping it in a double-requestAnimationFrame:

```<code>created() {
    this.refreshScrollableArea = setInterval(() => {
        return requestAnimationFrame(() => requestAnimationFrame(() => {
            const { offsetWidth, offsetHeight } = document.getElementById(this.id);
            this.offsetWidth = offsetWidth;
            this.offsetHeight = offsetHeight;
        }));
    }, 100);
},
</code>```

requestAnimationFrame itself a person should research. I will leave it out of the scope of this answer.

In closing, another idea I researched later, but am not using is to use a recursive setTimeout function with a dynamic timeout on it (ie: a timeout that decays after the page loads); however, if you consider the recursive setTimeout technique, be conscious of callstack/function-queue length and tail call optimization. Stack size could run away on you.

ContentLicense: CC BY-SA 3.0

Body:
I'm new to vuejs but I was trying to get the window size whenever I
   resize it so that i can compare it to some value for a function that I
   need to apply depending on the screen size. I also tried using the
   watch property but not sure how to handle it so that's probably why it didn't work

  methods: {

    elem() {
     this.size = window.innerWidth;
     return this.size;
   },
  mounted() {
    if (this.elem < 767){ //some code }
   }

Body:
I looked at the code of that library vue-window-size, and besides the additional logic, it's just adding an event listener on window resize, and it looks like it can be instructed to debounce. Source

The critical problem for me is that my Vue SPA app does not emit a window resize event when a vue-router route changes that makes the <html> element go from 1000px to 4000px, so it's causing me all kinds of problems watching a canvas element controlled by p5.js to redraw a wallpaper using p5.resizeCanvas().

I have a different solution now that involves actively polling the page's offset height.

The first thing to be aware of is JavaScript memory management, so to avoid memory leaks, I put setInterval in the created lifecycle method and clearInterval in the beforeDestroy lifecycle method:

created() {
    this.refreshScrollableArea = setInterval(() => {
        const { offsetWidth, offsetHeight } = document.getElementById('app');
        this.offsetWidth = offsetWidth;
        this.offsetHeight = offsetHeight;
    }, 100);
},

beforeDestroy() {
    return clearInterval(this.refreshScrollableArea);
},

As hinted in the above code, I also placed some initial state:

data() {
    const { offsetWidth, offsetHeight } = document.querySelector('#app');

    return {
        offsetWidth,
        offsetHeight,
        refreshScrollableArea: undefined,
    };
},

Note: if you are using getElementById with something like this.id (ie: an element that is a child in this component), document.getElementById(this.id) will be undefined because DOM elements load outer-to-inner, so if you see an error stemming from the data instantiation, set the width/height to 0 initially.

Then, I put a watcher on offsetHeight to listen for height changes and perform business logic:

    watch: {
        offsetHeight() {
            console.log('offsetHeight changed', this.offsetHeight);

            this.state = IS_RESET;
            this.setState(this.sketch);
            return this.draw(this.sketch);
        },
    },

Conclusion: I tested with performance.now() and:

document.querySelector('#app').offsetHeight
document.getElementById('app').offsetHeight
document.querySelector('#app').getClientBoundingRect().height

all execute in about the exact same amount of time: 0.2ms, so the above code is costing about 0.2ms every 100ms. I currently find that reasonable in my app including after I adjust for slow clients that operate an order of magnitude slower than my localmachine.

Here is the test logic for your own R&D:

const t0 = performance.now();
const { offsetWidth, offsetHeight } = document.getElementById('app');
const t1 = performance.now();

console.log('execution time:', (t1 - t0), 'ms');

Bonus: if you get any performance issue due to long-running execution time on your setInterval function, try wrapping it in a double-requestAnimationFrame:

created() {
    this.refreshScrollableArea = setInterval(() => {
        return requestAnimationFrame(() => requestAnimationFrame(() => {
            const { offsetWidth, offsetHeight } = document.getElementById(this.id);
            this.offsetWidth = offsetWidth;
            this.offsetHeight = offsetHeight;
        }));
    }, 100);
},

requestAnimationFrame itself a person should research. I will leave it out of the scope of this answer.

In closing, another idea I researched later, but am not using is to use a recursive setTimeout function with a dynamic timeout on it (ie: a timeout that decays after the page loads); however, if you consider the recursive setTimeout technique, be conscious of callstack/function-queue length and tail call optimization. Stack size could run away on you.


问:
Can't assign empty initializer to vector of unique_ptrs
I have the following code:

```<code>std::unordered_map<std::string, std::vector<std::unique_ptr<class EventTrigger>>> triggers;

if (triggers.end() == triggers.find(eventName)) {
   triggers[eventName] = {};
}
</code>```

That results in an error about using a deleted constructor of unique_ptr. If, on the other hand, I do this, everything compiles fine:

```<code>if (triggers.end() == triggers.find(eventName)) {
   triggers[eventName] = std::vector<std::unique_ptr<class EventTrigger>>();
}
</code>```

Can anyone explain why this is happening? I thought the empty initializer list would have resulted in an empty vector being assigned to triggers[eventName].

答:
triggers[eventName] = {} resolves to vector<T>::operator=(std::initializer_list<T>). This operator requires copying elements from the initializer list to the vector.

triggers[eventName] = std::vector<...>() resolves to vector<T>::operator=(vector<T>&&) - the move assignment operator. This doesn't require copying any elements, just transferring ownership of existing storage.

Body:
I have the following code:

std::unordered_map<std::string, std::vector<std::unique_ptr<class EventTrigger>>> triggers;

if (triggers.end() == triggers.find(eventName)) {
   triggers[eventName] = {};
}

That results in an error about using a deleted constructor of unique_ptr. If, on the other hand, I do this, everything compiles fine:

if (triggers.end() == triggers.find(eventName)) {
   triggers[eventName] = std::vector<std::unique_ptr<class EventTrigger>>();
}

Can anyone explain why this is happening? I thought the empty initializer list would have resulted in an empty vector being assigned to triggers[eventName].


问:
Reset Jest mock of id generator on every test
I'm trying to mock id generation function.
Content of my generateIdsSet.js file is:

```<code>import nanoid from 'nanoid/generate'

const generateId = (): string => {
  return nanoid('1234567890abcdefghijklmnopqrstuvwxyz', 5)
}

export const generateIdsSet = (setLength) => {
  const setIds = []

  for (let i = 0; i < setLength; i++) {
    setIds.push(generateId())
  }

  return setIds
}
</code>```

In the mock file generateIdsSet.spec.js for generateIdsSet I need to create array of predictable ids. I came up with that implementation:

```<code>import { generateIdsSet } from './generateIdsSet.js'

jest.mock('nanoid/generate', () => {
  let value = 0

  return () => String(++value)
})

describe('generateIdsSet', () => {
  it('One element', () => {
    expect(generateIdsSet(1)).toEqual(['1'])
  })

  it('Four elements', () => {
    expect(generateIdsSet(4)).toEqual(['1', '2', '3', '4'])
  })

  ....
})
</code>```

Everything is OK except that on every test counter doesn't reset to 1 and keeps incrementing for every call.

Maybe it's something obvious I'm missing but I can't figure it out. I will be grateful for the help.

答:
When you want to mock an ES import you need to also import the module in the test file. There are multiple ways of doing this, but the two easiest ways are:

Use autoMock and create a __mock__ directory adjacent to the test (adds boilerplate)

Import the module you want to mock in the file (easier)

```<code>import nanoid from 'nanoid/generate'
import { generateIdsSet } from './generateIdsSet.js'

jest.mock('nanoid')

nanoid.mockImplementation(() => {
  let value = 0

  return () => String(++value)
});

afterAll(() => {
  // don't forget to restore when done!
  nanoid.mockRestore()
});

describe('generateIdsSet', () => {
  it('One element', () => {
    expect(generateIdsSet(1)).toEqual(['1'])
  })

  it('Four elements', () => {
    expect(generateIdsSet(4)).toEqual(['1', '2', '3', '4'])
  })

  ....
})
</code>```

More mocking goodness can be found in this medium article (note, I am not the author).

Body:
I'm trying to mock id generation function.
Content of my generateIdsSet.js file is:

import nanoid from 'nanoid/generate'

const generateId = (): string => {
  return nanoid('1234567890abcdefghijklmnopqrstuvwxyz', 5)
}

export const generateIdsSet = (setLength) => {
  const setIds = []

  for (let i = 0; i < setLength; i++) {
    setIds.push(generateId())
  }

  return setIds
}

In the mock file generateIdsSet.spec.js for generateIdsSet I need to create array of predictable ids. I came up with that implementation:

import { generateIdsSet } from './generateIdsSet.js'

jest.mock('nanoid/generate', () => {
  let value = 0

  return () => String(++value)
})

describe('generateIdsSet', () => {
  it('One element', () => {
    expect(generateIdsSet(1)).toEqual(['1'])
  })

  it('Four elements', () => {
    expect(generateIdsSet(4)).toEqual(['1', '2', '3', '4'])
  })

  ....
})

Everything is OK except that on every test counter doesn't reset to 1 and keeps incrementing for every call.

Maybe it's something obvious I'm missing but I can't figure it out. I will be grateful for the help.

Body:
When you want to mock an ES import you need to also import the module in the test file. There are multiple ways of doing this, but the two easiest ways are:

Use autoMock and create a __mock__ directory adjacent to the test (adds boilerplate)

Import the module you want to mock in the file (easier)

import nanoid from 'nanoid/generate'
import { generateIdsSet } from './generateIdsSet.js'

jest.mock('nanoid')

nanoid.mockImplementation(() => {
  let value = 0

  return () => String(++value)
});

afterAll(() => {
  // don't forget to restore when done!
  nanoid.mockRestore()
});

describe('generateIdsSet', () => {
  it('One element', () => {
    expect(generateIdsSet(1)).toEqual(['1'])
  })

  it('Four elements', () => {
    expect(generateIdsSet(4)).toEqual(['1', '2', '3', '4'])
  })

  ....
})

More mocking goodness can be found in this medium article (note, I am not the author).


问:
can json.loads() take function reslut(string) as input?
As I know json.loads() take string as input, so I don't know why below code doesn't work.

```<code>import json
fileref = open("olympics.txt", "r").readline()  # the output is str
print(fileref)
print(type(fileref))
d = json.loads(fileref)
</code>```

Error:

```<code>ExternalError: SyntaxError: Unexpected token N in JSON at position 0 on line 8
</code>```

Thank you!

答:
Thats because fileref is not a syntactically valid JSON string. Unless you know the first line of the file is supposed to be a JSON object then I'm assuming the entire file is a JSON object (which is common). You can use the json.load function to read in a file https://docs.python.org/2/library/json.html.

Or you could store the file into a string and then use loads like

```<code>content = ""
with open("file.txt","r") as f:
     for line in f:
         content += line
json.loads(content)
</code>```

EDIT: I do not know you're file structure, I am just assuming that its a JSON file (i.e its all JSON). If that is the case then what I mentioned would be accurate. Otherwise the error you are seeing is because the string being parsed is not valid JSON.

Body:
As I know json.loads() take string as input, so I don't know why below code doesn't work.

import json
fileref = open("olympics.txt", "r").readline()  # the output is str
print(fileref)
print(type(fileref))
d = json.loads(fileref)

Error:

ExternalError: SyntaxError: Unexpected token N in JSON at position 0 on line 8

Thank you!

Body:
Thats because fileref is not a syntactically valid JSON string. Unless you know the first line of the file is supposed to be a JSON object then I'm assuming the entire file is a JSON object (which is common). You can use the json.load function to read in a file https://docs.python.org/2/library/json.html.

Or you could store the file into a string and then use loads like

content = ""
with open("file.txt","r") as f:
     for line in f:
         content += line
json.loads(content)

EDIT: I do not know you're file structure, I am just assuming that its a JSON file (i.e its all JSON). If that is the case then what I mentioned would be accurate. Otherwise the error you are seeing is because the string being parsed is not valid JSON.


问:
How to modify list of list elements python
I have a list of lists

```<code> check = [['KH8X070.jpeg', 'ZDO9A8O.jpeg', 'ZW25RD8.jpeg', '6ZLXW92.jpeg', 'HVLA5UT.jpeg', 'A4UDC12.jpeg', '2X5KO9A.jpeg', '5HZR4VV.jpeg', '24FWS4S.jpeg'], ['Z2QC6PW.jpeg', 'EHMK14E.jpeg', 'RTV0PRH.jpeg', '71S643D.jpeg', 'KECHDQ9.jpeg', 'RU6PYPB.jpeg'], ['UG9Z4SQ.jpeg', 'H0Y3SYV.jpeg', '61HCFOK.jpeg', '14KE527.jpeg', 'XMSM050.jpeg', '5KFI2V3.jpeg', 'QSJMKUB.jpeg', 'S6TX0ZM.jpeg', '8JV3K1Y.jpeg', 'XI9OOI7.jpeg', 'JMWDOPM.jpeg'], ['0SAXG3I.jpeg', 'LA5HJNO.jpeg', 'PHHAUSA.jpeg', '900Z7S7.jpeg']]
</code>```

such that I have:

```<code> check = [[0,0,0,0,0,0,0,0,0],[1,1,1,1,1,1], [2,2,2,2,2,2,2,2,2,2,2], [3,3,3,3]]
</code>```

I want to modify it such that in index list 0 of the list of list, I'll have 0's all through, in index 1 I would have 1's all through, in index 2 I'll have 2's all through and so on like that.

```<code>for i, j in enumerate(check):
  checks = [...]
</code>```

I know it should be a list comprehension there, but don't just know how to go about it. That's why I have come here for help.

答:
The above won't quite give you the result you need. But what you can do is </p>

```<code>arr = []
for i, j in enumerate(check):
    length = j
    arr.append([i]*length)
</code>```

<p>This should work perfectly, I tried it out and it worked fine. Let me know how it works for you. </p>

Body:
I have a list of lists

 check = [['KH8X070.jpeg', 'ZDO9A8O.jpeg', 'ZW25RD8.jpeg', '6ZLXW92.jpeg', 'HVLA5UT.jpeg', 'A4UDC12.jpeg', '2X5KO9A.jpeg', '5HZR4VV.jpeg', '24FWS4S.jpeg'], ['Z2QC6PW.jpeg', 'EHMK14E.jpeg', 'RTV0PRH.jpeg', '71S643D.jpeg', 'KECHDQ9.jpeg', 'RU6PYPB.jpeg'], ['UG9Z4SQ.jpeg', 'H0Y3SYV.jpeg', '61HCFOK.jpeg', '14KE527.jpeg', 'XMSM050.jpeg', '5KFI2V3.jpeg', 'QSJMKUB.jpeg', 'S6TX0ZM.jpeg', '8JV3K1Y.jpeg', 'XI9OOI7.jpeg', 'JMWDOPM.jpeg'], ['0SAXG3I.jpeg', 'LA5HJNO.jpeg', 'PHHAUSA.jpeg', '900Z7S7.jpeg']]

such that I have:

 check = [[0,0,0,0,0,0,0,0,0],[1,1,1,1,1,1], [2,2,2,2,2,2,2,2,2,2,2], [3,3,3,3]]

I want to modify it such that in index list 0 of the list of list, I'll have 0's all through, in index 1 I would have 1's all through, in index 2 I'll have 2's all through and so on like that.

for i, j in enumerate(check):
  checks = [...]

I know it should be a list comprehension there, but don't just know how to go about it. That's why I have come here for help.

Body:
The above won't quite give you the result you need. But what you can do is

arr = []
for i, j in enumerate(check):
    length = j
    arr.append([i]*length)

This should work perfectly, I tried it out and it worked fine. Let me know how it works for you.


问:
Next.js Unable to serve dynamic images on the runtine
So I am using Next.js API for the backend of my project and Mongodb for the database.
I have to serve images which have been uploaded by users on the runtine. As these files weren't available yet during the build time, they are not recognized as static files which can be stored in public directory.

I have tried next-images, added some configurations in the next.config.js and in my code: <img src={require(../../../images/${picture.src})} alt={picture.legend} />.

But still I have this error:.

I also tried with file-loader but still got no luck.

What did I miss?

Thanks for any reply!

答:
This configuration has worked for me in the past when running into these issues with loading images and/or fonts:

npm install url-loader --save-dev

next.config.js

module.exports = {
  webpack: function (config) {
    config.module.rules.push({
      test: /\.(eot|woff|woff2|ttf|svg|png|jpg|gif)$/,
      use: {
        loader: 'url-loader',
        options: {
          limit: 100000,
          name: '[name].[ext]',
        },
      },
    });
    return config;
  },
}
```


问:
Inferring function signature from tuple in Typescript
I tried for long hours now and honestly it wasn't worth the effort, bu I'd still like to see if there's a solution to this:

I'm trying to force TS to infer my function signature from tuples. I tried to play with conditional types, but I don't seem to get it right:

// model
interface User {
    name: string
}

interface Article {
    title: string
}

/// api
type Resource = 'user' | 'articles'
type Params = Record<string, number | string | boolean>

type GetSignature =
    | ['user', undefined, User]
    | ['articles', { articleId: number }, Article[]]
    | ['articles', undefined, Article]

// get request
interface ObjArg {
    resource: Resource
    params?: Params
}

type RetType<TResult> = TResult & { cancel: () => void }

async function get<TResult>(args: ObjArg): Promise<RetType<TResult>>
async function get<TResult>(resource: Resource, params?: Params): Promise<RetType<TResult>>
async function get<TResult>(args: [ObjArg | Resource, Params?]): Promise<RetType<TResult>>{
    const { resource, params } = typeof args[0] === 'object' ? args[0] : { resource: args[0], params: args[1] }
    const result = await someAsyncFetch(resource, params)
    return { ...result, cancel: () => { cancelAsyncFetch() }}
}
```

<p>I'd like TS to be able to infer the <code>get</code>'s signature from provided arguments, so it automatically knows that e.g. when calling <code>get('articles', { articleId: 1 }) the return type should be</code>Article<code>as well as that I need the second argument to be of type</code>{articleId: number}<code>(or</code>undefined<code>for array of articles). This is what</code>GetSignature` union type should define.</p>

<p>So the desired usage would be something like</p>

<pre class="lang-js prettyprint-override"><code>const user = get('user') // returns User
const article = get('articles', { articleId: 1 }) // returns Article
const articles = get('articles') // returns Article[]
</code>```

I tried dozens of approaches and none seemed to provide the interface I aim for. Just to mention one of them, I tried to expect signature as a type argument (get<TSignature exntends GetSignature>(...))  and tried to infer the desired signature like in likes of this:

resource: TSignature[0] extends infer T ? T : never
```

<p>or even</p>

<pre class="lang-js prettyprint-override"><code>resource: TSignature[0] extends infer T ? Extract<GetSignature, T> : never
</code>```

But nothing seemed to work. For now I think I'll stick to providing the type argument for TResult, but I'd like to know whether there a way to do what I describe in TS?

答:
You can try this:

type GetSignature = {
  user: [User, undefined, User]
  articles: [Article, { articleId: number }, Article[]]
}

declare function get<K extends keyof GetSignature>(type: K): Promise<RetType<GetSignature[K][0]>>
declare function get<K extends keyof GetSignature>(type: K, param: GetSignature[K][1]): Promise<RetType<GetSignature[K][2]>>
async function get(type, param) {
  ...
}
```

Playground:
https://www.typescriptlang.org/play?#code/KYDwDg9gTgLgBAbwL4CgUHp1wLYQCbAA2KAlgHYzBQBmAhgMbBwCqAzlYinN3GbdsABccVjCjkA5ilSkKVOozgBBWCXqEmCLjxgkYG4aPFkpMzFlpgSKGAE8wTAErBWEAK5RFAXjgByN+xQvnAAPn60quouvjb2TAAKEfyscD7O9NB4ADxGkgA0vG7YAEYcYbkmoXDFEBAatGQAfLEOcM4wACpxWR3OrG6EMI2pcL0uA-AAZIhw9A2MhMIAFACUqcMAbhAkeHAydq0A4sAwAMokEnwwHkw+WtwBVMIA2mxUBW5kBNTkwHgFbygAF1tBFdFFWC8VOCNAUEHAwWoNABJPDCMhFUpQPYFaFI4DPIEgmQEdQRJjUT70XQQMhwCQnLIAaTgoEoXxSAGtgLYINQ4MczhcrjdGksDkI4EyVsJ4lAINgSOwsu0ug4soLzpdaNcoASmUDngAGIGNZqkwjkuCUsjUki0+mMlls4AcuDc3n8zXCnWi8VxYRMgpgJLYYTe7W6-WGgCMQJlcDlCqVwBVJzVqYjIr1zwNzwATKbmiglrQAO60PSOmBLfyBXwrFYAOj4AibNUIeFWAG4S+XK-AGTXfIiIQ3m7p9MB23Uuyte6WK1Wh7XRxpWL44WvgKjhDGkI3jUCm5ONDPOz2gA

Body:
I tried for long hours now and honestly it wasn't worth the effort, bu I'd still like to see if there's a solution to this:

I'm trying to force TS to infer my function signature from tuples. I tried to play with conditional types, but I don't seem to get it right:

// model
interface User {
    name: string
}

interface Article {
    title: string
}

/// api
type Resource = 'user' | 'articles'
type Params = Record<string, number | string | boolean>

type GetSignature =
    | ['user', undefined, User]
    | ['articles', { articleId: number }, Article[]]
    | ['articles', undefined, Article]

// get request
interface ObjArg {
    resource: Resource
    params?: Params
}

type RetType<TResult> = TResult & { cancel: () => void }

async function get<TResult>(args: ObjArg): Promise<RetType<TResult>>
async function get<TResult>(resource: Resource, params?: Params): Promise<RetType<TResult>>
async function get<TResult>(args: [ObjArg | Resource, Params?]): Promise<RetType<TResult>>{
    const { resource, params } = typeof args[0] === 'object' ? args[0] : { resource: args[0], params: args[1] }
    const result = await someAsyncFetch(resource, params)
    return { ...result, cancel: () => { cancelAsyncFetch() }}
}

I'd like TS to be able to infer the get's signature from provided arguments, so it automatically knows that e.g. when calling get('articles', { articleId: 1 }) the return type should beArticleas well as that I need the second argument to be of type{articleId: number}(orundefinedfor array of articles). This is whatGetSignature` union type should define.

So the desired usage would be something like

const user = get('user') // returns User
const article = get('articles', { articleId: 1 }) // returns Article
const articles = get('articles') // returns Article[]

I tried dozens of approaches and none seemed to provide the interface I aim for. Just to mention one of them, I tried to expect signature as a type argument (get<TSignature exntends GetSignature>(...))  and tried to infer the desired signature like in likes of this:

resource: TSignature[0] extends infer T ? T : never

or even

resource: TSignature[0] extends infer T ? Extract<GetSignature, T> : never

But nothing seemed to work. For now I think I'll stick to providing the type argument for TResult, but I'd like to know whether there a way to do what I describe in TS?

Body:
You can try this:

type GetSignature = {
  user: [User, undefined, User]
  articles: [Article, { articleId: number }, Article[]]
}

declare function get<K extends keyof GetSignature>(type: K): Promise<RetType<GetSignature[K][0]>>
declare function get<K extends keyof GetSignature>(type: K, param: GetSignature[K][1]): Promise<RetType<GetSignature[K][2]>>
async function get(type, param) {
  ...
}

Playground:
<a href="https://www.typescriptlang.org/play?#code/KYDwDg9gTgLgBAbwL4CgUHp1wLYQCbAA2KAlgHYzBQBmAhgMbBwCqAzlYinN3GbdsABccVjCjkA5ilSkKVOozgBBWCXqEmCLjxgkYG4aPFkpMzFlpgSKGAE8wTAErBWEAK5RFAXjgByN+xQvnAAPn60quouvjb2TAAKEfyscD7O9NB4ADxGkgA0vG7YAEYcYbkmoXDFEBAatGQAfLEOcM4wACpxWR3OrG6EMI2pcL0uA-AAZIhw9A2MhMIAFACUqcMAbhAkeHAydq0A4sAwAMokEnwwHkw+WtwBVMIA2mxUBW5kBNTkwHgFbygAF1tBFdFFWC8VOCNAUEHAwWoNABJPDCMhFUpQPYFaFI4DPIEgmQEdQRJjUT70XQQMhwCQnLIAaTgoEoXxSAGtgLYINQ4MczhcrjdGksDkI4EyVsJ4lAINgSOwsu0ug4soLzpdaNcoASmUDngAGIGNZqkwjkuCUsjUki0+mMlls4AcuDc3n8zXCnWi8VxYRMgpgJLYYTe7W6-WGgCMQJlcDlCqVwBVJzVqYjIr1zwNzwATKbmiglrQAO60PSOmBLfyBXwrFYAOj4AibNUIeFWAG4S+XK-AGTXfIiIQ3m7p9MB23Uuyte6WK1Wh7XRxpWL44WvgKjhDGkI3jUCm5ONDPOz2gA" rel="nofollow noreferrer">https://www.typescriptlang.org/play?#code/KYDwDg9gTgLgBAbwL4CgUHp1wLYQCbAA2KAlgHYzBQBmAhgMbBwCqAzlYinN3GbdsABccVjCjkA5ilSkKVOozgBBWCXqEmCLjxgkYG4aPFkpMzFlpgSKGAE8wTAErBWEAK5RFAXjgByN+xQvnAAPn60quouvjb2TAAKEfyscD7O9NB4ADxGkgA0vG7YAEYcYbkmoXDFEBAatGQAfLEOcM4wACpxWR3OrG6EMI2pcL0uA-AAZIhw9A2MhMIAFACUqcMAbhAkeHAydq0A4sAwAMokEnwwHkw+WtwBVMIA2mxUBW5kBNTkwHgFbygAF1tBFdFFWC8VOCNAUEHAwWoNABJPDCMhFUpQPYFaFI4DPIEgmQEdQRJjUT70XQQMhwCQnLIAaTgoEoXxSAGtgLYINQ4MczhcrjdGksDkI4EyVsJ4lAINgSOwsu0ug4soLzpdaNcoASmUDngAGIGNZqkwjkuCUsjUki0+mMlls4AcuDc3n8zXCnWi8VxYRMgpgJLYYTe7W6-WGgCMQJlcDlCqVwBVJzVqYjIr1zwNzwATKbmiglrQAO60PSOmBLfyBXwrFYAOj4AibNUIeFWAG4S+XK-AGTXfIiIQ3m7p9MB23Uuyte6WK1Wh7XRxpWL44WvgKjhDGkI3jUCm5ONDPOz2gA


问:
Amplify w/Cognito: How do I get the Current User's Email?
I am using AWS Amplify, with Cognito for user Auth.

Users go into a user pool, and register and sign in just with email address and password.

When a user that has signed in through Cognito navigates to a certain page, I want to be retrieve their email address. How can I do this?

I am able to retrieve some user data with this code (I am using javascript/Angular):

```<code>import Auth from '@aws-amplify/auth';
...

ngOnInit(){
  Auth.currentAuthenticatedUser().then((user)=>{
        console.log('user = ' + JSON.stringify(user.pool))
 })
}
</code>```

The email does appear on the response, but I haven't yet been able to isolate the email from the returned JSON.

I've tried going through the docs, but I haven't yet found info on stuff like the attribute options I can add to currentAuthenticatedUser(), or if there is another method that is cleaner (which I assume there is).

EDIT: It looks like the following works:

```<code>Auth.currentAuthenticatedUser().then((user) => {
  console.log('user email = ' + user.attributes.email);
});
</code>```

But I am still hoping to understand the documentation better. I found this solution in a random github question, not the official docs. Where would I find this solution in the AWS Amplify / Cognito documentation?

答:
The following works for me after the user is logged in...</p>

```<code>import { Auth, Amplify } from 'aws-amplify'

console.log(Auth.user.attributes.email)
</code>```

Body:
I am using AWS Amplify, with Cognito for user Auth.

Users go into a user pool, and register and sign in just with email address and password.

When a user that has signed in through Cognito navigates to a certain page, I want to be retrieve their email address. How can I do this?

I am able to retrieve some user data with this code (I am using javascript/Angular):

import Auth from '@aws-amplify/auth';
...

ngOnInit(){
  Auth.currentAuthenticatedUser().then((user)=>{
        console.log('user = ' + JSON.stringify(user.pool))
 })
}

The email does appear on the response, but I haven't yet been able to isolate the email from the returned JSON.

I've tried going through the docs, but I haven't yet found info on stuff like the attribute options I can add to currentAuthenticatedUser(), or if there is another method that is cleaner (which I assume there is).

EDIT: It looks like the following works:

Auth.currentAuthenticatedUser().then((user) => {
  console.log('user email = ' + user.attributes.email);
});

But I am still hoping to understand the documentation better. I found this solution in a random github question, not the official docs. Where would I find this solution in the AWS Amplify / Cognito documentation?

Body:
The following works for me after the user is logged in...

import { Auth, Amplify } from 'aws-amplify'

console.log(Auth.user.attributes.email)