问:
Reducing number of Line Breaks/chr(10) in a Cell
I have an excel sheet that has cells with variable amounts of line breaks and I want to reduce it so that there is only one line break between each new line.

For example

```<code>HELLO

WORLD

GOODBYE
</code>```

will be modified to:

```<code>HELLO

WORLD

GOODBYE
</code>```

I've been banging my head over this for hours and have come up with a few ways but none are very efficient or produce the best results.

This is made especially difficult because I'm working with a dataset that has spaces preceeding the Line Breaks.

And so a regular parse doesn't work as well.

I've tried to replace all the instances of chr(10) in the cell with ~ to make it easier to work with, however i'm still not getting it to an exact amount. I'm wondering if there are better ways.

here is what I have so far:

```<code> myString = Replace(myString, Chr(10), "~")

    Do While InStr(myString, "~~") > 0
        str1 = Split(myString, "~")
        For k = 0 To UBound(str1)
        myString = Replace(myString, "~~", "~")
        Next k
    Loop

    Do While InStr(myString, "   ~") > 0
        str1 = Split(myString, "~")
        For k = 0 To UBound(str1)
        myString = Replace(myString, "  ~", "")
        Next k
    Loop

myString = Replace(myString, "   ~", " ~")
myString = Replace(myString, " ~", "~")
myString = Replace(myString, "~", Chr(10))

Cells(2, 2).Value = myString
</code>```

So i'm using a few do while loops to catch instances of different types of line breaks (or in this case, tildes) but I don't think this is the best way to tackle this.

I was thinking of ways to loop through the characters in the cell, and if there is an instance where there is more than one chr(10), replace it with "".

So the psuedocode would look like:

```<code>for i to len(mystring)
    if mystring(i) = chr(10) AND myString(i+1) = chr(10) Then
       myString(i + 1) = ""
</code>```

but unfortunately I don't think this is possible through vba.

If anyone is kind enough to help me adjust my current code or assist me with the aforementioned psuedocode, it would be greatly appreciated!

答:
You can do it with a formula:

```<code>=SUBSTITUTE(SUBSTITUTE(TRIM(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(TRIM(A1)," ","|"),"|"&CHAR(10)," "),CHAR(10)," "))," ",CHAR(10)),"|"," ")
</code>```

This changes all the spaces to | and then the Char(10) to spaces.  The trim removes the extra spaces.  The we reverse, space to Char(10) and | to spaces.

VBA:

```<code>Function manytoone(str As String)
    str = Replace(Application.Trim(str), " ", "|")
    str = Replace(str, "|" & Chr(10), " ")
    str = Replace(str, Chr(10), " ")
    str = Application.Trim(str)
    str = Replace(str, " ", Chr(10))
    str = Replace(str, "|", " ")
    manytoone = str

End Function
</code>```

Body:
I have an excel sheet that has cells with variable amounts of line breaks and I want to reduce it so that there is only one line break between each new line.

For example

HELLO

WORLD

GOODBYE

will be modified to:

HELLO

WORLD

GOODBYE

I've been banging my head over this for hours and have come up with a few ways but none are very efficient or produce the best results.

This is made especially difficult because I'm working with a dataset that has spaces preceeding the Line Breaks.

And so a regular parse doesn't work as well.

I've tried to replace all the instances of chr(10) in the cell with ~ to make it easier to work with, however i'm still not getting it to an exact amount. I'm wondering if there are better ways.

here is what I have so far:

 myString = Replace(myString, Chr(10), "~")

    Do While InStr(myString, "~~") > 0
        str1 = Split(myString, "~")
        For k = 0 To UBound(str1)
        myString = Replace(myString, "~~", "~")
        Next k
    Loop

    Do While InStr(myString, "   ~") > 0
        str1 = Split(myString, "~")
        For k = 0 To UBound(str1)
        myString = Replace(myString, "  ~", "")
        Next k
    Loop

myString = Replace(myString, "   ~", " ~")
myString = Replace(myString, " ~", "~")
myString = Replace(myString, "~", Chr(10))

Cells(2, 2).Value = myString

So i'm using a few do while loops to catch instances of different types of line breaks (or in this case, tildes) but I don't think this is the best way to tackle this.

I was thinking of ways to loop through the characters in the cell, and if there is an instance where there is more than one chr(10), replace it with "".

So the psuedocode would look like:

for i to len(mystring)
    if mystring(i) = chr(10) AND myString(i+1) = chr(10) Then
       myString(i + 1) = ""

but unfortunately I don't think this is possible through vba.

If anyone is kind enough to help me adjust my current code or assist me with the aforementioned psuedocode, it would be greatly appreciated!

Body:
You can do it with a formula:

=SUBSTITUTE(SUBSTITUTE(TRIM(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(TRIM(A1)," ","|"),"|"&CHAR(10)," "),CHAR(10)," "))," ",CHAR(10)),"|"," ")

This changes all the spaces to | and then the Char(10) to spaces.  The trim removes the extra spaces.  The we reverse, space to Char(10) and | to spaces.

VBA:

Function manytoone(str As String)
    str = Replace(Application.Trim(str), " ", "|")
    str = Replace(str, "|" & Chr(10), " ")
    str = Replace(str, Chr(10), " ")
    str = Application.Trim(str)
    str = Replace(str, " ", Chr(10))
    str = Replace(str, "|", " ")
    manytoone = str

End Function


来源: stackexchange

问:
Android: How to create my own cursor class?
I'm using Sqlite in Android and to get a value from the database I use something like this:

```<code>Cursor cursor = sqliteDatabase.rawQuery("select title,category from table", null);

int columnIndexTitle = cursor.getColumnIndex("title");
iny columnIndexCategory = cursor.getColumnIndex("category");

cursor.moveToFirst();
while (cursor.moveToNext()) {
    String title = cursor.getString(columnIndexTitle);
    String category = cursor.getString(columnIndexCategory);
}
cursor.close();
</code>```

I want to create my own Cursor so that I can do getColumnIndex() and getString() with one method. Something like this:

```<code>String title = cursor.getString("title");
</code>```

I want to create my own class that extends the cursor that I get from sqliteDatabase.rawQuery, but I'm not sure how to accomplish this. Should I extend SQLiteCursor or how should I do this? Is it even a possible and is it a good idea?

答:
Creating your own getString will cause a map lookup for each call instead of only for getColumnIndex.

Here's the code for SQLiteCursor.getColumnIndex and AbstractCursor.getColumnIndex. If you have many rows, reducing calls to this function will prevent unnecessary string processing and map lookups.

ContentLicense: CC BY-SA 3.0

Body:
I'm using Sqlite in Android and to get a value from the database I use something like this:

Cursor cursor = sqliteDatabase.rawQuery("select title,category from table", null);

int columnIndexTitle = cursor.getColumnIndex("title");
iny columnIndexCategory = cursor.getColumnIndex("category");

cursor.moveToFirst();
while (cursor.moveToNext()) {
    String title = cursor.getString(columnIndexTitle);
    String category = cursor.getString(columnIndexCategory);
}
cursor.close();

I want to create my own Cursor so that I can do getColumnIndex() and getString() with one method. Something like this:

String title = cursor.getString("title");

I want to create my own class that extends the cursor that I get from sqliteDatabase.rawQuery, but I'm not sure how to accomplish this. Should I extend SQLiteCursor or how should I do this? Is it even a possible and is it a good idea?


问:
combine two pictures(different size) horizontally?
I have 2 pictures, need to combine them horizontally. I know numpy and cv2(opencv) should help me to do this. But don't know how.
I used img1 = cv2.imread(file1), img2 = cv2.imread(file2)
the 2 images' shape are (2048, 1334, 3) and (720, 1200, 3)
How could I do this? when I open These 2 images, they have similar height, different width.
I only know if the 2 pics have the same size, then just use concate, but my 2 pics are different sizes.
For the final output, I want to have them keep their own width, height choose the biggest/smallest...
So I imagine the final output should maybe 2/3 width one picture, 1/3 width the other pic which is totally good. I don't need these 2 are evenly distributed. Just keep their own width. Thanks!</p>

答:
You need to either trim a bit of the bottom of the taller image or add some black pixels.

In order to trim a part of the image, you can do:

```<code>trimmed = image2[:image1.shape[0],:,:]
</code>```

This keeps only the lines from 0 up to the height of image1.

Or, you can add some black pixels:

```<code>black = np.zeros(image1.shape[0] - image2.shape[0], image1.shape[1])
image2 = np.hstack(image2, black)
</code>```

And then you vertically concatenate.

ContentLicense: CC BY-SA 4.0

Body:
You need to either trim a bit of the bottom of the taller image or add some black pixels.

In order to trim a part of the image, you can do:

trimmed = image2[:image1.shape[0],:,:]

This keeps only the lines from 0 up to the height of image1.

Or, you can add some black pixels:

black = np.zeros(image1.shape[0] - image2.shape[0], image1.shape[1])
image2 = np.hstack(image2, black)

And then you vertically concatenate.


问:
ParcelJs add extra "/" before all files link
I'm actually working on a ts project with ParcelJs. When I build my project and open it on the ParcelJs server on http://localhost:1234/ everything work great. But when I try to open it outside this server all my files are not found because there is an extra / at the beginning of each file link.

For example ParcelJs give in my index.html links like this that do not work:

But when I remove this / like this everything is working as expected:

So what have I to do to fix it ?

答:
To make all links relative (with no /) you will need to add an extra parameter --public-url with the value ./ when you run ParcelJs like this :

parcel index.html  --public-url ./


问:
What pkg creates symlink from /lib/libncurses.so.5 to /lib/aarch64-linux-gnu/libncurses.so.5?
what package would setup a symlink from "/lib/libncurses.so.5" to the actual library, /lib/aarch64-linux-gnu/libncurses.so.5?

This is a programming question, because I'm trying to compile/link a program that wants to use -lncurses, and I strongly prefer not to have to kludge the makefile with references to architecture specific libncurses.

Yes, I know I could create my own symlink in /lib, but it sure seems like "apt-get install" of something should have done it for me.

/lib/aarch64-linux-gnu/libncurses.so.5 was installed with: apt-get install libncurses5 and/or libncurses5-dev.

I've seen a few symlinks from /lib/foo.so (for various values of "foo") to /lib//foo.so on various Linux systems, so I know this is not a completely uncommon practice.

In this case, I'm on a Pinebook (ARM64) running Ubuntu.

thanks,
Stan

答: The place to look is the ldconfig configuration.  This thread might give you some insight.


问:
Is there a way to export the variable in a ForEach loop to my CSV output on each line
I am attempting to run a script against our AD that spits out the AD Users in a group, for all the groups in a list. Essentially attempting to audit the groups to find the users. I have a functioning script, except I have no way to determine when the output of one group ends, and where the output of the next begins.

I have tried looking for previous examples, but nothing fits exactly the method I am using, and with me just dipping my toes into powershell I have not been able to combine other examples with my own.

```<code>$groups = Get-Content "C:\Folder\File_with_lines_of_ADGroup_Names.txt"
foreach ($group in $groups) { Get-ADGroupMember -Identity "$group" | Where-Object { $_.ObjectClass -eq "user" } | Get-ADUser -Property Description,DisplayName | Select Name,DisplayName,Description,$group | Export-csv -append -force -path "C:\Folder\File_of_outputs.csv" -NoTypeInformation }
</code>```

Right now the problem lies with getting the $group variable to be exported along with the Name, DisplayName, and Description of each user returned. This is the best way I can think of to tag each user's group and keep all the results in a single file. However, only the first line of results works which is the HEADERS of the CSV, and everything after it is either listed as "Microsoft.ActiveDirectory.Management.ADPropertyValueCollection"or simply blank after the first group of results.

Hoping someone can show me how to easily add my variable $group to the output for each user found for filtering/pivoting purposes.

Thanks and let me know if you have questions.

答:
I believe what you are after are calculated properties on your select statement.

```<code>Select Name,DisplayName,Description,$group
</code>```

Should Probably be something like

```<code>Select Name,DisplayName,Description,@{n='Group'; e={$group};}
</code>```

See also https://serverfault.com/questions/890559/powershell-calculated-properties-for-multiple-values

Body:
I am attempting to run a script against our AD that spits out the AD Users in a group, for all the groups in a list. Essentially attempting to audit the groups to find the users. I have a functioning script, except I have no way to determine when the output of one group ends, and where the output of the next begins.

I have tried looking for previous examples, but nothing fits exactly the method I am using, and with me just dipping my toes into powershell I have not been able to combine other examples with my own.

$groups = Get-Content "C:\Folder\File_with_lines_of_ADGroup_Names.txt"
foreach ($group in $groups) { Get-ADGroupMember -Identity "$group" | Where-Object { $_.ObjectClass -eq "user" } | Get-ADUser -Property Description,DisplayName | Select Name,DisplayName,Description,$group | Export-csv -append -force -path "C:\Folder\File_of_outputs.csv" -NoTypeInformation }

Right now the problem lies with getting the $group variable to be exported along with the Name, DisplayName, and Description of each user returned. This is the best way I can think of to tag each user's group and keep all the results in a single file. However, only the first line of results works which is the HEADERS of the CSV, and everything after it is either listed as "Microsoft.ActiveDirectory.Management.ADPropertyValueCollection"or simply blank after the first group of results.

Hoping someone can show me how to easily add my variable $group to the output for each user found for filtering/pivoting purposes.

Thanks and let me know if you have questions.

Body:
I believe what you are after are calculated properties on your select statement.

Select Name,DisplayName,Description,$group

Should Probably be something like

Select Name,DisplayName,Description,@{n='Group'; e={$group};}

See also https://serverfault.com/questions/890559/powershell-calculated-properties-for-multiple-values


问:
Compacting multiple similar if statements in C#
I would like to make some code for a game a little more compact. Here is the original.

```<code>if (killPosX != 0) // float x position you would like the object to be destroyed at
{
    killX = true;  // automatically makes the value of killX true
}

if (killPosY != 0) // float y position you would like the object to be destroyed at
{
    killY = true;  // automatically makes the value of killY true
}

if (killPosT != 0) // float position in time you would like the object to be destroyed at
{
    killT = true;  // automatically makes the value of killT true
}
</code>```

And I want to turn it into something like this:

```<code>if ([killPosX, killPosY, killPosT] != 0)
{
    [killPosX, killPosY, killPosT] = true;
}
</code>```

How would I do that?

答:
```<code>if (killPosX != 0)
{
    killX = true;
}
</code>```

Could be translated as follow

```<code>killX = (killPosX != 0) ? true : killX;
</code>```

Or more simply

```<code>killX |= killPosX != 0;
</code>```

```<code>if (killPosX != 0)
{
    killX = true;
}
else
{
    killX = false;
}
</code>```

Could be translated as follow

```<code>killX = (killPosX != 0) ? true : false;
</code>```

Or more simply

```<code>killX = killPosX != 0;
</code>```

But since comparing floats using == or != is not advised, I would go for:

```<code>killX |= !Mathf.Approximately( killPosX, 0 );
killY |= !Mathf.Approximately( killPosY, 0 );
killT |= !Mathf.Approximately( killPosT, 0 );
</code>```

AFAIK, there is no built-in syntax similar to what you wrote in order to achieve what you want.

Body:
I would like to make some code for a game a little more compact. Here is the original.

if (killPosX != 0) // float x position you would like the object to be destroyed at
{
    killX = true;  // automatically makes the value of killX true
}

if (killPosY != 0) // float y position you would like the object to be destroyed at
{
    killY = true;  // automatically makes the value of killY true
}

if (killPosT != 0) // float position in time you would like the object to be destroyed at
{
    killT = true;  // automatically makes the value of killT true
}

And I want to turn it into something like this:

if ([killPosX, killPosY, killPosT] != 0)
{
    [killPosX, killPosY, killPosT] = true;
}

How would I do that?

Body:
if (killPosX != 0)
{
    killX = true;
}

Could be translated as follow

killX = (killPosX != 0) ? true : killX;

Or more simply

killX |= killPosX != 0;

if (killPosX != 0)
{
    killX = true;
}
else
{
    killX = false;
}

Could be translated as follow

killX = (killPosX != 0) ? true : false;

Or more simply

killX = killPosX != 0;

But since comparing floats using == or != is not advised, I would go for:

killX |= !Mathf.Approximately( killPosX, 0 );
killY |= !Mathf.Approximately( killPosY, 0 );
killT |= !Mathf.Approximately( killPosT, 0 );

AFAIK, there is no built-in syntax similar to what you wrote in order to achieve what you want.


问:
Delete a json inside another in React
Imagine that I have this kind of JSON object on my react state:

```<code>this.state={
   parent:{
      childs:[
      child1:{
      },
      child2:{
      },
      child3:null,
       (...)
      ]

   }
}
</code>```

to delete the child1 I did the following method:

```<code>deleteChild1  = (index,test) => {

    const childs= [...this.state.parent.childs];

    childs[index] = {
        ...childs[index],
        child1: null
    }

    this.setState(prevState => ({
        ...prevState,
        parent: {
            ...prevState.parent,
            childs: [
                ...childs,
            ]
        }
    }))

}
</code>```

This works with no problem, but imagine that I have 100 childs, I have to do 100 methods like this but instead putting the child1 to null I have to put the child100, child99, you get the idea.

My question is that is another way to put the variable null.

Thanks!

答:
The answer is very simple, this would be my approach.

Create a function which updates your state with the expect result (removing that property).

If you wish to assign null that you can replace .filter() with a .map() solution. Typically if you are removing a piece of data it does not make sense to null it, but to remove it.

FYI your property childs is an array you have an object within, so you need a list of objects to fix this.

E.g.

```<code>[
  {
    name: "child1"
  },
  {
    name: "child2"
  },
  {
    name: "child3"
  }
]
</code>```

```<code>removeChild = (child) => {
  const newChildList = this.state.parent.childs.filter(({name}) => name !== child);

  this.setState(previousState => ({
    ...previousState,
    parent: {
      ...previousState.parent,
      childs: newChildList
    }
  }));
}
</code>```

The key part here is that the data is being updated and overriding the original array. Because you have nested data structure we don’t want to delete any pre-existing data (hence the spreading).

Call the function however you want and if your childs array has an object with the property called name that matches the child function argument, it will be not be present on the next re-render.

Hope this helps.

Title: Delete a json inside another in React

Body:
Imagine that I have this kind of JSON object on my react state:

this.state={
   parent:{
      childs:[
      child1:{
      },
      child2:{
      },
      child3:null,
       (...)
      ]

   }
}

to delete the child1 I did the following method:

deleteChild1  = (index,test) => {

    const childs= [...this.state.parent.childs];

    childs[index] = {
        ...childs[index],
        child1: null
    }

    this.setState(prevState => ({
        ...prevState,
        parent: {
            ...prevState.parent,
            childs: [
                ...childs,
            ]
        }
    }))

}

This works with no problem, but imagine that I have 100 childs, I have to do 100 methods like this but instead putting the child1 to null I have to put the child100, child99, you get the idea.

My question is that is another way to put the variable null.

Thanks!

Body:
The answer is very simple, this would be my approach.

Create a function which updates your state with the expect result (removing that property).

If you wish to assign null that you can replace .filter() with a .map() solution. Typically if you are removing a piece of data it does not make sense to null it, but to remove it.

FYI your property childs is an array you have an object within, so you need a list of objects to fix this.

E.g.

[
  {
    name: "child1"
  },
  {
    name: "child2"
  },
  {
    name: "child3"
  }
]

removeChild = (child) => {
  const newChildList = this.state.parent.childs.filter(({name}) => name !== child);

  this.setState(previousState => ({
    ...previousState,
    parent: {
      ...previousState.parent,
      childs: newChildList
    }
  }));
}

The key part here is that the data is being updated and overriding the original array. Because you have nested data structure we don’t want to delete any pre-existing data (hence the spreading).

Call the function however you want and if your childs array has an object with the property called name that matches the child function argument, it will be not be present on the next re-render.

Hope this helps.


问:
How to define manual colors for text on individual facets?
Trying to define manual colors for text on individual facets created by ggplot. But the code is assigning random colors.

I have included the code I tried to get the colors right.

library(ggplot2)

p <- ggplot(mtcars, aes(mpg, wt)) +
  geom_point() +
  facet_grid(. ~ cyl) +
  theme(panel.spacing = unit(1, "lines"))

dat_text <- data.frame(
  label = c("4 cylinders", "6 cylinders", "8 cylinders"),
  cyl   = c(4, 6, 8),
  cl = c("red", "blue", "black"),
  x     = c(20, 27.5, 25),
  y     = c(4, 4, 4.5)
)

p + geom_text(
  data    = dat_text,
  mapping = aes(x = x, y = y, label = label, colour= cl)
)

```

The code is working except it is giving random colors instead of assigned colors.

答:
Use scale_color_manual to manually set the colors:

```<code>dat_text <- data.frame(
  label = c("4 cylinders", "6 cylinders", "8 cylinders"),
  cyl   = c(4, 6, 8),
  cl = c("A", "B", "C"),
  x     = c(20, 27.5, 25),
  y     = c(4, 4, 4.5)
)

p + geom_text(
  data    = dat_text,
  mapping = aes(x = x, y = y, label = label, colour= cl)
) +
  scale_color_manual(values = c("red","blue","black"))
</code>```

Note that the order is the alphabetical order of the levels, that's why I set the levels to A, B, C.

You probably don't want a legend for the text, so remove it:

```<code>p + geom_text(
  data    = dat_text,
  mapping = aes(x = x, y = y, label = label, colour= cl), show.legend = FALSE
) +
  scale_color_manual(values = c("red","blue","black"))
</code>```

Body:
Trying to define manual colors for text on individual facets created by ggplot. But the code is assigning random colors.

I have included the code I tried to get the colors right.

library(ggplot2)

p <- ggplot(mtcars, aes(mpg, wt)) +
  geom_point() +
  facet_grid(. ~ cyl) +
  theme(panel.spacing = unit(1, "lines"))

dat_text <- data.frame(
  label = c("4 cylinders", "6 cylinders", "8 cylinders"),
  cyl   = c(4, 6, 8),
  cl = c("red", "blue", "black"),
  x     = c(20, 27.5, 25),
  y     = c(4, 4, 4.5)
)

p + geom_text(
  data    = dat_text,
  mapping = aes(x = x, y = y, label = label, colour= cl)
)

The code is working except it is giving random colors instead of assigned colors.

Body:
Use scale_color_manual to manually set the colors:

dat_text <- data.frame(
  label = c("4 cylinders", "6 cylinders", "8 cylinders"),
  cyl   = c(4, 6, 8),
  cl = c("A", "B", "C"),
  x     = c(20, 27.5, 25),
  y     = c(4, 4, 4.5)
)

p + geom_text(
  data    = dat_text,
  mapping = aes(x = x, y = y, label = label, colour= cl)
) +
  scale_color_manual(values = c("red","blue","black"))

Note that the order is the alphabetical order of the levels, that's why I set the levels to A, B, C.

You probably don't want a legend for the text, so remove it:

p + geom_text(
  data    = dat_text,
  mapping = aes(x = x, y = y, label = label, colour= cl), show.legend = FALSE
) +
  scale_color_manual(values = c("red","blue","black"))


问:
How to fix the problem of opening an .exe file which flashes(closes instantly after the program's end)?
I've been coding for a while with codeblocks and I've coded some C programs. In my project folder of my programs there is the .exe file that I used to click on and get its console output. But today when I click on them and when the program ends it closes instantly without asking me to press a key to quit the program.

The solutions for this problem I've found are to add "system("pause")" and other stuff like that or to compile it directly on the cmd or on codeblocks(and they don't fix the problem as well). But I would like to know how I could be able to open the .exe files like back then.

答:
did you try something like that at the end of your program?</p>

```<code>    scanf("%c",waitVar);
</code>```

Body:
did you try something like that at the end of your program?

    scanf("%c",waitVar);


问:
How to separate each elements of a nested list and convert the list to the list of tuples?
I have a nested list like below:

```<code>Zeros = [[1], [2], [3, 4], [5, 6]]

</code>```

How can I separate each element and make a list of tuples, like below:

```<code>Modified_zeros = [(1), (2), (3), (4), (5), (6)]

</code>```

Thanks

答:
Based off this answer:

flat_list = [(item,) for sublist in l for item in sublist]
```

Where l is your original list (Zeros in your case)

Body:
I have a nested list like below:

Zeros = [[1], [2], [3, 4], [5, 6]]

How can I separate each element and make a list of tuples, like below:

Modified_zeros = [(1), (2), (3), (4), (5), (6)]

Thanks

Body:
Based off this answer:

flat_list = [(item,) for sublist in l for item in sublist]

Where l is your original list (Zeros in your case)


问:
Can I escape curly bracket symbol in terraform?
I'm using the terraform template_file data resource to create a file that should be written to the dynamically-created EC2 instance when I apply the stack. In other words, I want this file to be created in the home folder of the newly-created EC2 instance. However, this file contains curly bracket syntax ${}, which terraform is trying to interpolate. How can I escape these curly brackets?

As background, I'm using the cloud-config syntax to write these files.

Ex:

${username} should be written to the file, not interpolated in terraform.

Even when I use the double dollar sign $$, terraform still fails because it can't find the variable:

... failed to render : <template_file>:105,18-26: Unknown variable; There is no variable named "username".

答:
FYI I ended up working around this by writing the template in another file, then reading it into the terraform stack using the file method:

```<code>data "template_file" "config" {
  template = "${file("./user_data.tpl")}"
}
</code>```

Body:
FYI I ended up working around this by writing the template in another file, then reading it into the terraform stack using the file method:

data "template_file" "config" {
  template = "${file("./user_data.tpl")}"
}


问:
Storing Browser Window Size in Variable and Updating It on Change
I'm storing window width into a variable using const deviceWidth = window.innerWidth;. This is great however, I would like the variable to update anytime the user resizes the window. How is this achieved?

答:
When the window changes size it triggers a 'resize' event.
Details here

You need to listen out for this event and update your variable accordingly.
Details here


答:
I would leverage the window resize event to keep your variable updated:

https://developer.mozilla.org/en-US/docs/Web/API/Window/resize_event

Essentially, you can create a function that is ran on any window resize and then set your variable.

const heightOutput = document.querySelector('#height');
const widthOutput = document.querySelector('#width');

function reportWindowSize() {
  heightOutput.textContent = window.innerHeight;
  widthOutput.textContent = window.innerWidth;
}

window.onresize = reportWindowSize;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Resize the browser window to fire the <code>resize</code> event.</p>
<p>Window height: <span id="height"></span></p>
<p>Window width: <span id="width"></span></p></code>```

Title: Storing Browser Window Size in Variable and Updating It on Change

Body: I'm storing window width into a variable using const deviceWidth = window.innerWidth;. This is great however, I would like the variable to update anytime the user resizes the window. How is this achieved?

Body:
I would leverage the window resize event to keep your variable updated:

https://developer.mozilla.org/en-US/docs/Web/API/Window/resize_event

Essentially, you can create a function that is ran on any window resize and then set your variable.

const heightOutput = document.querySelector('#height');
const widthOutput = document.querySelector('#width');

function reportWindowSize() {
  heightOutput.textContent = window.innerHeight;
  widthOutput.textContent = window.innerWidth;
}

window.onresize = reportWindowSize;

<p>Resize the browser window to fire the <code>resize</code> event.</p>
<p>Window height: <span id="height"></span></p>
<p>Window width: <span id="width"></span></p>


问:
Java JDBC connection pool library choice in 2011/2012?
Which JDBC connection pool library should I use for a new application project (not web application)?

Apache DBCP has enough unresolved issues which are pushed until 2.0 I think.

C3P0 development seems to be stopped.

And both of them looks relatively slow.

Proxool is dead.

DBPool has almost no community (at least I've found no public one - no forums, no mailing lists...)

Apache Tomcat Pool looks to be unusable without Tomcat

I've found SQL Datasources article at Oracle website, but it seems, that it can be applied only to applets running in containers like servlets and web services.

Should I choose BoneCP may be? I don't have any huge requirements. I just need a good and easy to use database connection pool, that is in active development. Library, whose author can respond to bug reports, answer some specific question etc.

BTW, actually, I'm using MySQL only. I've found, that MySQL driver supports DriverManager interface, but I'm unsure if it actually pools connections or not.

答: You've done good research. I'd say, go ahead with BoneCP. Some years ago I would have suggested c3p0, but it has currently some open and unresolved issues as well. Too bad, actually. The BoneCP author is by the way also active here at SO.</p>


问:
Import css and sass files nextjs 7
I want be able to import in any file in my project the two types of files.

```<code>    import 'styles/index.scss';
    import 'styles/build/_style.css'
</code>```

Its important to note im using Nextjs 7 and webpack 4 (comes with nextjs7)

In Nextjs 6 we used to use in next.config.js

```<code>const withCSS = require('@zeit/next-css')
const withSass = require('@zeit/next-sass')

const commonsChunkConfig = (config, test = /\.css$/) => {
  config.plugins = config.plugins.map(plugin => {
      if (
          plugin.constructor.name === 'CommonsChunkPlugin' &&
          plugin.minChunks != null
  ) {
      const defaultMinChunks = plugin.minChunks;
      plugin.minChunks = (module, count) => {
          if (module.resource && module.resource.match(test)) {
              return true;
          }
          return defaultMinChunks(module, count);
      };
  }
  return plugin;
  });
  return config;
};

module.exports = withCSS(withSass({
  webpack: (config, { isServer }) => {
      config = commonsChunkConfig(config, /\.(sass|scss|css)$/)
      return config
  }
}))
</code>```

答:
Use the next-compose-plugins.

It provides a cleaner API for creating next.js configurations, you DONT need to install @zeit/next-css and you ALSO DON'T have to do any webpack loader configuration to make it work.

Here is an example with the @zeit/next-source-maps plugin for demo purposes:

```<code>/* Import modules */
const withSourceMaps = require( '@zeit/next-source-maps' );
const withSass = require( '@zeit/next-sass' );
const withPlugins = require( 'next-compose-plugins' );

/* Configuration */
const NextAppConfig = ({
  // config stuff goes here, no webpack loader config required
})

/* Export declaration */
module.exports = withPlugins([
  [ withSourceMaps ],
  [ withSass ]
], NextAppConfig );
</code>```

I prefer to declare the array before the export because it is even cleaner setup:

```<code>// ... imports go here

/* Plugins array variable */
var plugins = [ [ withSourceMaps ], [ withSass ] ];

/* CONFIGURATION */
const NextAppConfig = ({
  // Config stuff goes here, no webpack configuration required
})

/* EXPORT DECLARATION */
module.exports = withPlugins( plugins, NextAppConfig );
</code>```

https://github.com/cyrilwanner/next-compose-plugins

Title: Import css and sass files nextjs 7

Body:
I want be able to import in any file in my project the two types of files.

    import 'styles/index.scss';
    import 'styles/build/_style.css'

Its important to note im using Nextjs 7 and webpack 4 (comes with nextjs7)

In Nextjs 6 we used to use in next.config.js

const withCSS = require('@zeit/next-css')
const withSass = require('@zeit/next-sass')

const commonsChunkConfig = (config, test = /\.css$/) => {
  config.plugins = config.plugins.map(plugin => {
      if (
          plugin.constructor.name === 'CommonsChunkPlugin' &&
          plugin.minChunks != null
  ) {
      const defaultMinChunks = plugin.minChunks;
      plugin.minChunks = (module, count) => {
          if (module.resource && module.resource.match(test)) {
              return true;
          }
          return defaultMinChunks(module, count);
      };
  }
  return plugin;
  });
  return config;
};

module.exports = withCSS(withSass({
  webpack: (config, { isServer }) => {
      config = commonsChunkConfig(config, /\.(sass|scss|css)$/)
      return config
  }
}))

Body:
Use the next-compose-plugins.

It provides a cleaner API for creating next.js configurations, you DONT need to install @zeit/next-css and you ALSO DON'T have to do any webpack loader configuration to make it work.

Here is an example with the @zeit/next-source-maps plugin for demo purposes:

/* Import modules */
const withSourceMaps = require( '@zeit/next-source-maps' );
const withSass = require( '@zeit/next-sass' );
const withPlugins = require( 'next-compose-plugins' );

/* Configuration */
const NextAppConfig = ({
  // config stuff goes here, no webpack loader config required
})

/* Export declaration */
module.exports = withPlugins([
  [ withSourceMaps ],
  [ withSass ]
], NextAppConfig );

I prefer to declare the array before the export because it is even cleaner setup:

// ... imports go here

/* Plugins array variable */
var plugins = [ [ withSourceMaps ], [ withSass ] ];

/* CONFIGURATION */
const NextAppConfig = ({
  // Config stuff goes here, no webpack configuration required
})

/* EXPORT DECLARATION */
module.exports = withPlugins( plugins, NextAppConfig );

https://github.com/cyrilwanner/next-compose-plugins


问:
Is there an easy way to completely freeze object and its children in Javascript, (Deep Freeze)?
Often you have to pass an object as parameter. Functions accessing those objects are pass by reference and can change original object. Which depending on situation can be  unwanted outcome. So is there a way to freeze object. I know about Object.freeze()

But it doesn't affect objects/arrays inside it.

For example

```<code>a = { arr: [1,2,3]};
Object.freeze(a);
a.arr.push(4); // still works
</code>```

答:
If you look at MDN, there is a function there that suggests deepFreeze functionality however it is not stack safe. I personally have an ES5 version to async iterate. For ES6 something along these lines might work, I did not test it thoroughly though:

```<code>function deepFreeze(o,promises,oldestParent){
    promises = promises || [];
    oldestParent = oldestParent || o;
    promises.push(
        Promise.resolve().then(function(){
            Object.values(Object.freeze(o)).forEach(function(d,i){
                typeof d === "object" && deepFreeze(d,promises,oldestParent);
            });
            return oldestParent;
        })
    );
    return Promise.all(promises).then((a)=>a[0]);
}

var o = {a:3,b:{test:1,test2:2},c:1};
deepFreeze(o).then(function(x){console.log(x)}); //o is deep frozen
</code>```

Warning: I assume your object's properties are enumerable, if not then use getOwnPropertyNames instead.

Body:
Often you have to pass an object as parameter. Functions accessing those objects are pass by reference and can change original object. Which depending on situation can be  unwanted outcome. So is there a way to freeze object. I know about Object.freeze()

But it doesn't affect objects/arrays inside it.

For example

a = { arr: [1,2,3]};
Object.freeze(a);
a.arr.push(4); // still works

Body:
If you look at MDN, there is a function there that suggests deepFreeze functionality however it is not stack safe. I personally have an ES5 version to async iterate. For ES6 something along these lines might work, I did not test it thoroughly though:

function deepFreeze(o,promises,oldestParent){
    promises = promises || [];
    oldestParent = oldestParent || o;
    promises.push(
        Promise.resolve().then(function(){
            Object.values(Object.freeze(o)).forEach(function(d,i){
                typeof d === "object" && deepFreeze(d,promises,oldestParent);
            });
            return oldestParent;
        })
    );
    return Promise.all(promises).then((a)=>a[0]);
}

var o = {a:3,b:{test:1,test2:2},c:1};
deepFreeze(o).then(function(x){console.log(x)}); //o is deep frozen

Warning: I assume your object's properties are enumerable, if not then use getOwnPropertyNames instead.


问:
How to programmatically change settings for WMI instead of using wmimgmt.msc snappin?
Normally you go this way:

start -> run

enter wmimgmt.msc and press enter

riht click on "WMI Control" node ->
properties

on security tab click button security

add new user

for user you just add allow "Remote
enable"

How can this be done programmatically(C# or vbs) ?
I searched the web and found sometning about doing it by using WMIC, but I don't understand how to do it.
Here are the links if they helps you.
http://msdn.microsoft.com/en-us/library/aa393613%28v=vs.85%29.aspx

http://msdn.microsoft.com/en-us/library/aa393611%28v=vs.85%29.aspx

http://msdn.microsoft.com/en-us/library/aa822575%28v=vs.85%29.aspx

http://msdn.microsoft.com/en-us/library/aa822576%28v=vs.85%29.aspx

http://msdn.microsoft.com/en-us/library/aa394531%28v=VS.85%29.aspx

Thank you very much

答:
I won't explain exactly how to do this, but since you are doing something that involves some good understanding of windows, programming and administering I will simply give you a link to the source code that you can adapt into your project to manage the WMI security:

http://www.codeproject.com/KB/system/WmiSecurity.aspx

Basically what you should note is the following paragraph:

So at this point, some examples should suffice to illustrate the use of the utility. Suppose you wanted to add the domain HelpDesk group to the CIMV2 and subsequent namespaces on the S223001 computer. Further, suppose this group should have the ability to remotely connect and read WMI objects. To do this:

WmiSecurity /C=S223001 /A /N=Root\CimV2 /M=MyDomain\HelpDesk:REMOTEACCESS /R

Hope that it can help.

Cheers.

ContentLicense: CC BY-SA 2.5


问:
Polly downloading mp3 as int? Trying to put it up to S3 using Lambda
I'm a beginner with Python. Trying to figure out what's wrong with Polly, since it doesn't seem to be outputting a valid mp3.

I'm following these tutorials loosely: 1 2

but since I'm not concatenating any files due to character restriction I don't think I need to use Audiosegment or ffmpeg right?

Here's my code:

```<code>import hashlib
import json
import tempfile
import praw, boto3
import os
import random
import time

polly = boto3.client('polly')
s3 = boto3.client('s3')
s3r = boto3.resource('s3')

DEFAULT_VOICE = os.getenv("DEFAULT_VOICE", "Celine")
SAMPLE_RATE = os.getenv("SAMPLE_RATE", "8000")
BUCKET_NAME = os.getenv("BUCKET_NAME", "pollybotreddit")
FILE_FORMAT = os.getenv("FILE_FORMAT", "mp3")

def build_sound(content, voice = 'Justin', SampleRate = SAMPLE_RATE):
    for text in content:
        resp = polly.synthesize_speech(
            OutputFormat = "mp3",
            Text = text,
            TextType = "text",
            VoiceId = voice
        )
    with open('test.mp3' , 'wb') as f:
        sound = f.write(resp['AudioStream'].read())
    return sound

def lambda_handler(event, content):
    slashr = event.get('subreddit')
    voice = event.get('voice', 'Joanna')
    if not slashr:
        raise ValueError("Bad Request: Not a subreddit")

    reddit = praw.Reddit('bot1')
    sub = reddit.subreddit(slashr)
    titles = []
    for submission in sub.hot(limit=5):
        if not submission.stickied:
            titles.append(submission.title)
    article = random.choice(titles)

    sound_data = build_sound(article, voice=voice)
    final = sound_data + '.mp3'

    s3.put_object(Bucket=BUCKET_NAME, ACL='public-read', Body=final, Key=article)

    item = {
        'subreddit': slashr,
        's3': "{}/{}/{}".format(s3.meta.endpoint_url, BUCKET_NAME, article)
        }
    return item

lambda_handler({'subreddit':"politics"}, None)
</code>```

error gives me this:

```<code>  File "pollybot.py", line 91, in <module>
    lambda_handler({'subreddit':"politics"}, None)
  File "pollybot.py", line 79, in lambda_handler
    final = sound_data + '.mp3'
TypeError: unsupported operand type(s) for +: 'int' and 'str'
</code>```

and if I take out

```<code>final = sound_data + '.mp3'
</code>```

Polly's output is still an int, not a File object, so it gives me this

```<code>botocore.exceptions.ParamValidationError: Parameter validation failed:
Invalid type for parameter Body, value: 3493, type: <class 'int'>, valid types: <class 'bytes'>, <class 'bytearray'>, file-like object
</code>```

Any help? Thanks in advance.

答:
Thanks to @Daniel Roseman, the following code block worked for me:</p>

```<code>def build_sound(content, voice = 'Justin', SampleRate = SAMPLE_RATE):
    for text in content:
        resp = polly.synthesize_speech(
            OutputFormat = "mp3",
            Text = text,
            TextType = "text",
            VoiceId = voice
        )
    filetospeech = resp['AudioStream'].read()
    return filetospeech
</code>```

Body:
I'm a beginner with Python. Trying to figure out what's wrong with Polly, since it doesn't seem to be outputting a valid mp3.

I'm following these tutorials loosely: 1 2

but since I'm not concatenating any files due to character restriction I don't think I need to use Audiosegment or ffmpeg right?

Here's my code:

import hashlib
import json
import tempfile
import praw, boto3
import os
import random
import time

polly = boto3.client('polly')
s3 = boto3.client('s3')
s3r = boto3.resource('s3')

DEFAULT_VOICE = os.getenv("DEFAULT_VOICE", "Celine")
SAMPLE_RATE = os.getenv("SAMPLE_RATE", "8000")
BUCKET_NAME = os.getenv("BUCKET_NAME", "pollybotreddit")
FILE_FORMAT = os.getenv("FILE_FORMAT", "mp3")

def build_sound(content, voice = 'Justin', SampleRate = SAMPLE_RATE):
    for text in content:
        resp = polly.synthesize_speech(
            OutputFormat = "mp3",
            Text = text,
            TextType = "text",
            VoiceId = voice
        )
    with open('test.mp3' , 'wb') as f:
        sound = f.write(resp['AudioStream'].read())
    return sound

def lambda_handler(event, content):
    slashr = event.get('subreddit')
    voice = event.get('voice', 'Joanna')
    if not slashr:
        raise ValueError("Bad Request: Not a subreddit")

    reddit = praw.Reddit('bot1')
    sub = reddit.subreddit(slashr)
    titles = []
    for submission in sub.hot(limit=5):
        if not submission.stickied:
            titles.append(submission.title)
    article = random.choice(titles)

    sound_data = build_sound(article, voice=voice)
    final = sound_data + '.mp3'

    s3.put_object(Bucket=BUCKET_NAME, ACL='public-read', Body=final, Key=article)

    item = {
        'subreddit': slashr,
        's3': "{}/{}/{}".format(s3.meta.endpoint_url, BUCKET_NAME, article)
        }
    return item

lambda_handler({'subreddit':"politics"}, None)

error gives me this:

  File "pollybot.py", line 91, in <module>
    lambda_handler({'subreddit':"politics"}, None)
  File "pollybot.py", line 79, in lambda_handler
    final = sound_data + '.mp3'
TypeError: unsupported operand type(s) for +: 'int' and 'str'

and if I take out

final = sound_data + '.mp3'

Polly's output is still an int, not a File object, so it gives me this

botocore.exceptions.ParamValidationError: Parameter validation failed:
Invalid type for parameter Body, value: 3493, type: <class 'int'>, valid types: <class 'bytes'>, <class 'bytearray'>, file-like object

Any help? Thanks in advance.

Body:
Thanks to @Daniel Roseman, the following code block worked for me:

def build_sound(content, voice = 'Justin', SampleRate = SAMPLE_RATE):
    for text in content:
        resp = polly.synthesize_speech(
            OutputFormat = "mp3",
            Text = text,
            TextType = "text",
            VoiceId = voice
        )
    filetospeech = resp['AudioStream'].read()
    return filetospeech


问:
Angular 6 ng2-file upload can't read property of queue as undefined
Using Angular 6 to upload pictures to the server with Valor Software's ng2 file uploader and consistently getting errors. The thing is, I've used ng2 file uploader before with Visual Studio Code and it worked fine. This project was started with Visual Studio 2017 with the .NET Core & Angular bundle and I'm wondering if that has something to do with why this doesn't operate the same (or nearly as easily).

I'm using "ng2-file-upload": "^1.3.0" in package.json.

I've imported and declared import { FileUploadModule } from 'ng2-file-upload'; in my imports array of my module.

my html:

```<code><div class="row">
  <div class="col-12">
    <h3>Upload queue</h3>
    <p>Queue length: {{ uploader?.queue?.length }}</p>
    <table class="table">
      <thead>
        <tr>
          <th width="50%">Name</th>
          <th>Size</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let item of uploader.queue">
          <td><strong>{{ item?.file?.name }}</strong></td>
          <td *ngIf="uploader.options.isHTML5" nowrap>{{ item?.file?.size/1024/1024 | number:'.2' }} MB</td>
        </tr>
      </tbody>
    </table>
    <div class="progress mb-4">
      <div class="progress-bar" role="progressbar" [ngStyle]="{ 'width': uploader.progress + '%' }"></div>
    </div>
  </div>
  <div class="col-12">
    <div ng2FileDrop
         [ngClass]="{'nv-file-over': hasBaseDropZoneOver}"
         (fileOver)="fileOverBase($event)"
         [uploader]="uploader"
         class="well my-drop-zone">
      Base drop zone
    </div>
  </div>
</div>
</code>```

My component.ts:

```<code>export class PhotoEditorComponent implements OnInit {
  @Input() photos: Photo[];
  baseUrl = environment.levanaBaseUrl;
  uploader: FileUploader;
  hasBaseDropZoneOver = false;

  constructor(private auth: AuthService,
    private userService: UserService) { }

  ngOnInit() {
  }

  fileOverBase(e: any): void {
    this.hasBaseDropZoneOver = e;
  }

  initializeUploader() {
    this.uploader = new FileUploader({
      url: this.baseUrl + 'users/' + this.auth.currentUser.id + '/photos',
      authToken: 'Bearer ' + localStorage.getItem('token'),
      isHTML5: true,
      allowedFileType: ['image'],
      removeAfterUpload: true,
      autoUpload: false,
      maxFileSize: 10 * 1024 * 1024
    });

    this.uploader.onAfterAddingFile = (file) => { file.withCredentials = false; };

    this.uploader.onSuccessItem = (item, response, status, headers) => {
      if (response) {
        const res: Photo = JSON.parse(response);
        const photo = {
          id: res.id,
          url: res.url,
          dateAdded: res.dateAdded,
          description: res.description,
          isMain: res.isMain
        };
        this.photos.push(photo);
        if (photo.isMain) {
          localStorage.setItem('user', JSON.stringify(this.auth.currentUser));
        }
      }
    };
  }

}
</code>```

And I consistently get these errors when the html is rendering messing everything up.

答:
You have a function called initializeUploader that you are never calling anywhere.
I suspect calling that from ngOnInit will fix your problem.

Body:
Using Angular 6 to upload pictures to the server with Valor Software's ng2 file uploader and consistently getting errors. The thing is, I've used ng2 file uploader before with Visual Studio Code and it worked fine. This project was started with Visual Studio 2017 with the .NET Core & Angular bundle and I'm wondering if that has something to do with why this doesn't operate the same (or nearly as easily).

I'm using "ng2-file-upload": "^1.3.0" in package.json.

I've imported and declared import { FileUploadModule } from 'ng2-file-upload'; in my imports array of my module.

my html:

Upload queue

Queue length: {{ uploader?.queue?.length }}

          Name
          Size

          {{ item?.file?.name }}
          {{ item?.file?.size/1024/1024 | number:'.2' }} MB

      Base drop zone

My component.ts:

export class PhotoEditorComponent implements OnInit {
  @Input() photos: Photo[];
  baseUrl = environment.levanaBaseUrl;
  uploader: FileUploader;
  hasBaseDropZoneOver = false;

  constructor(private auth: AuthService,
    private userService: UserService) { }

  ngOnInit() {
  }

  fileOverBase(e: any): void {
    this.hasBaseDropZoneOver = e;
  }

  initializeUploader() {
    this.uploader = new FileUploader({
      url: this.baseUrl + 'users/' + this.auth.currentUser.id + '/photos',
      authToken: 'Bearer ' + localStorage.getItem('token'),
      isHTML5: true,
      allowedFileType: ['image'],
      removeAfterUpload: true,
      autoUpload: false,
      maxFileSize: 10 * 1024 * 1024
    });

    this.uploader.onAfterAddingFile = (file) => { file.withCredentials = false; };

    this.uploader.onSuccessItem = (item, response, status, headers) => {
      if (response) {
        const res: Photo = JSON.parse(response);
        const photo = {
          id: res.id,
          url: res.url,
          dateAdded: res.dateAdded,
          description: res.description,
          isMain: res.isMain
        };
        this.photos.push(photo);
        if (photo.isMain) {
          localStorage.setItem('user', JSON.stringify(this.auth.currentUser));
        }
      }
    };
  }

}

And I consistently get these errors when the html is rendering messing everything up.


问:
Java - get the newest file in a directory?
Does anybody have a snippet of Java that can return the newest file in a directory (or knowledge of a library that simplifies this sort of thing)?</p>

答:
This code works for me well:</p>

```<code>public String pickLatestFileFromDownloads() {

        String currentUsersHomeDir = System.getProperty("user.home");

        String downloadFolder = currentUsersHomeDir + File.separator + "Downloads" + File.separator;

        File dir = new File(downloadFolder);
        File[] files = dir.listFiles();
        if (files == null || files.length == 0) {
            testLogger.info("There is no file in the folder");
        }

        File lastModifiedFile = files[0];
        for (int i = 1; i < files.length; i++) {
            if (lastModifiedFile.lastModified() < files[i].lastModified()) {
                lastModifiedFile = files[i];
            }
        }
        String k = lastModifiedFile.toString();

        System.out.println(lastModifiedFile);
        Path p = Paths.get(k);
        String file = p.getFileName().toString();
        return file;

    }

//PostedBy: saurabh Gupta Aricent-provar
</code>```

OwnerDisplayName: tpark

Body:
This code works for me well:

public String pickLatestFileFromDownloads() {

        String currentUsersHomeDir = System.getProperty("user.home");

        String downloadFolder = currentUsersHomeDir + File.separator + "Downloads" + File.separator;

        File dir = new File(downloadFolder);
        File[] files = dir.listFiles();
        if (files == null || files.length == 0) {
            testLogger.info("There is no file in the folder");
        }

        File lastModifiedFile = files[0];
        for (int i = 1; i < files.length; i++) {
            if (lastModifiedFile.lastModified() < files[i].lastModified()) {
                lastModifiedFile = files[i];
            }
        }
        String k = lastModifiedFile.toString();

        System.out.println(lastModifiedFile);
        Path p = Paths.get(k);
        String file = p.getFileName().toString();
        return file;

    }

//PostedBy: saurabh Gupta Aricent-provar


问:
Reducing number of Line Breaks/chr(10) in a Cell
I have an excel sheet that has cells with variable amounts of line breaks and I want to reduce it so that there is only one line break between each new line.

For example

```<code>HELLO

WORLD

GOODBYE
</code>```

will be modified to:

```<code>HELLO

WORLD

GOODBYE
</code>```

I've been banging my head over this for hours and have come up with a few ways but none are very efficient or produce the best results.

This is made especially difficult because I'm working with a dataset that has spaces preceeding the Line Breaks.

And so a regular parse doesn't work as well.

I've tried to replace all the instances of chr(10) in the cell with ~ to make it easier to work with, however i'm still not getting it to an exact amount. I'm wondering if there are better ways.

here is what I have so far:

```<code> myString = Replace(myString, Chr(10), "~")

    Do While InStr(myString, "~~") > 0
        str1 = Split(myString, "~")
        For k = 0 To UBound(str1)
        myString = Replace(myString, "~~", "~")
        Next k
    Loop

    Do While InStr(myString, "   ~") > 0
        str1 = Split(myString, "~")
        For k = 0 To UBound(str1)
        myString = Replace(myString, "  ~", "")
        Next k
    Loop

myString = Replace(myString, "   ~", " ~")
myString = Replace(myString, " ~", "~")
myString = Replace(myString, "~", Chr(10))

Cells(2, 2).Value = myString
</code>```

So i'm using a few do while loops to catch instances of different types of line breaks (or in this case, tildes) but I don't think this is the best way to tackle this.

I was thinking of ways to loop through the characters in the cell, and if there is an instance where there is more than one chr(10), replace it with "".

So the psuedocode would look like:

```<code>for i to len(mystring)
    if mystring(i) = chr(10) AND myString(i+1) = chr(10) Then
       myString(i + 1) = ""
</code>```

but unfortunately I don't think this is possible through vba.

If anyone is kind enough to help me adjust my current code or assist me with the aforementioned psuedocode, it would be greatly appreciated!

答:
A VBA method would be replacing consecutive vbLf constants with a single one.

Loop through the string as long as there are more than one vbLf together, once removed, replace the string.

```<code>Sub RemoveExcessLinebreaks()

    Dim s As String, rng As Range
    Set rng = ThisWorkbook.Worksheets(1).Range("B4")
    s = rng.Value

    While InStr(1, s, vbLf & vbLf) > 0
        s = Replace(s, vbLf & vbLf, vbLf)
    Wend

    rng.Value = s

End Sub
</code>```

Obviously, you would need to modify the rng object to your purposes, or turn it into a parameter to the sub itself.

vbLf is a constant for a "LineFeed". There are multiple types of new lines, such as a vbCr (Carriage Return) or a vbCrLf (combined). Pressing Alt + Enter in a cell appears to use the vbLf variant, which is why I used this constant over the others.

Body:
I have an excel sheet that has cells with variable amounts of line breaks and I want to reduce it so that there is only one line break between each new line.

For example

HELLO

WORLD

GOODBYE

will be modified to:

HELLO

WORLD

GOODBYE

I've been banging my head over this for hours and have come up with a few ways but none are very efficient or produce the best results.

This is made especially difficult because I'm working with a dataset that has spaces preceeding the Line Breaks.

And so a regular parse doesn't work as well.

I've tried to replace all the instances of chr(10) in the cell with ~ to make it easier to work with, however i'm still not getting it to an exact amount. I'm wondering if there are better ways.

here is what I have so far:

 myString = Replace(myString, Chr(10), "~")

    Do While InStr(myString, "~~") > 0
        str1 = Split(myString, "~")
        For k = 0 To UBound(str1)
        myString = Replace(myString, "~~", "~")
        Next k
    Loop

    Do While InStr(myString, "   ~") > 0
        str1 = Split(myString, "~")
        For k = 0 To UBound(str1)
        myString = Replace(myString, "  ~", "")
        Next k
    Loop

myString = Replace(myString, "   ~", " ~")
myString = Replace(myString, " ~", "~")
myString = Replace(myString, "~", Chr(10))

Cells(2, 2).Value = myString

So i'm using a few do while loops to catch instances of different types of line breaks (or in this case, tildes) but I don't think this is the best way to tackle this.

I was thinking of ways to loop through the characters in the cell, and if there is an instance where there is more than one chr(10), replace it with "".

So the psuedocode would look like:

for i to len(mystring)
    if mystring(i) = chr(10) AND myString(i+1) = chr(10) Then
       myString(i + 1) = ""

but unfortunately I don't think this is possible through vba.

If anyone is kind enough to help me adjust my current code or assist me with the aforementioned psuedocode, it would be greatly appreciated!

Body:
A VBA method would be replacing consecutive vbLf constants with a single one.

Loop through the string as long as there are more than one vbLf together, once removed, replace the string.

Sub RemoveExcessLinebreaks()

    Dim s As String, rng As Range
    Set rng = ThisWorkbook.Worksheets(1).Range("B4")
    s = rng.Value

    While InStr(1, s, vbLf & vbLf) > 0
        s = Replace(s, vbLf & vbLf, vbLf)
    Wend

    rng.Value = s

End Sub

Obviously, you would need to modify the rng object to your purposes, or turn it into a parameter to the sub itself.

vbLf is a constant for a "LineFeed". There are multiple types of new lines, such as a vbCr (Carriage Return) or a vbCrLf (combined). Pressing Alt + Enter in a cell appears to use the vbLf variant, which is why I used this constant over the others.


问:
Set column names in pandas data frame from_dict with orient = 'index'
I looked already at this question: pandas create named columns in dataframe from dict. However, my example is slightly different.

I have a dictionary:
my_dict = {'key1' : [1,2,3], 'key2' : [4,5,6], 'key3' :[7,8,9]}

And I created a pandas dataframe: df = pd.DataFrame.from_dict(my_dict, orient='index'), which is row oriented. However, when writing columns = ['one', 'two', 'three'] I get an error, as in the link above.

How do I name them?

答:
```<code>my_dict = {'key1' : [1,2,3], 'key2' : [4,5,6], 'key3' :[7,8,9]}
df = pd.DataFrame.from_dict(my_dict, orient='columns')
df.columns = ['one', 'two', 'three']
</code>```

Changed orient from index to columns. This worked for me.

Body:
my_dict = {'key1' : [1,2,3], 'key2' : [4,5,6], 'key3' :[7,8,9]}
df = pd.DataFrame.from_dict(my_dict, orient='columns')
df.columns = ['one', 'two', 'three']

Changed orient from index to columns. This worked for me.


问:
How to get the K smallest Products from pairs from two sorted Arrays?
Two sorted arrays are given. We have to find the K smallest products from the pairs from these arrays. I could think of a mnlogk solution but this solution works even if the arrays are not in sorted order. Can we make use of this sorted order and find a better solution?

I tried using max heap of size k for obtaining the mnlogk solution.

Input: nums1 = [-2, -1, 0, 1, 2], nums2 = [-3, -1, 2, 4, 5], k = 3
Output: [-10, -8, -6]
Explanation: -2 * 5, -2 * 4, 2 * -3

答:
Here is an algorithm that has O(k min(n, m)) time complexity.

Let A and B be sorted lists of integers, i.e. A = [a1 a2 a3 ... am] with ai ≤ ai+1, and B = [b1 b2 b3 ... bn] with bi ≤ bi+1.

Assume for now that ai ≥ 0 and bi ≥ 0. We will show below how to account for negative integers.

Let p = (i j) be a pair, where i and j are the indexes of ai and bj. Let P be a list of pairs. Set P = [(1 1) (1 2) (1 3) ... (1 n)]. Assume k > 0 (and k ≤ m x n). Let R be the list of the pairs of the k first products. Initialize R = [].

Add the first pair p = (i j) of P to R.

If R is of size k, terminate.

Set p = (i+1 j). While the product of p is greater than the product
of the next pair q in P, exchange p and q.

Go to step 1.

The above algorithm has time complexity O(k n) and works for A and B containing non-negative integers only. Note that if m < n, we can exchange A and B to get a lower bound on the time complexity.

Here is an example that illustrates the algorithm with A = [2 6 13] and B = [1 6 9]. The matrix below shows the product ai x bj for every (i j).

```<code>  B   1   6   9
 A  ------------
 2 |  2  12  18
 6 |  6  36  54
13 | 13  78 117
</code>```

This is the initial states of P and R at the start of the alogrithm. We suffix each pair (i j) in P with the value of the product ai x bj.

```<code>P = [(1 1):2 (1 2):12 (1 3):18] R = []
</code>```

On the first iteration, (1 1):2 is added to R, and the first pair in P becomes (1+1 1).

```<code>R = [(1 1):2]
P = [(2 1):6 (1 2):12 (1 3):18]
</code>```

On the next iteration, (2 1):6 is added to R, and the first pair in P becomes (2+1 1). Because the product of that pair is greater than the product of the next pair in P, they are exchanged.

```<code>R = [(1 1):2 (2 1):6]
P = [(3 1):13 (1 2):12 (1 3):18]
P = [(1 2):12 (3 1):13 (1 3):18]
</code>```

Next iteration, similar operations as the previous iteration.

```<code>R = [(1 1):2 (2 1):6 (1 2):12]
P = [(2 2):36 (3 1):13 (1 3):18]
P = [(3 1):13 (1 3):18 (2 2):36]
</code>```

In this iteration, after adding (3 1):13 to R, the first pair of P becomes (3+1 1), but that pair does not exist. So, it is simply removed from P.

```<code>R = [(1 1):2 (2 1):6 (1 2):12 (3 1):13]
P = [(1 3):18 (2 2):36]
</code>```

Following are all remaining iterations until P is empty.

```<code>R = [(1 1):2 (2 1):6 (1 2):12 (3 1):13 (1 3):18]
P = [(2 3):54 (2 2):36]
P = [(2 2):36 (2 3):54]

R = [(1 1):2 (2 1):6 (1 2):12 (3 1):13 (1 3):18 (2 2):36]
P = [(3 2):78 (2 3):54]
P = [(2 3):54 (3 2):78]

R = [(1 1):2 (2 1):6 (1 2):12 (3 1):13 (1 3):18 (2 2):36 (2 3):54]
P = [(3 3):117 (3 2):78]
P = [(3 2):78 (3 3):117]

R = [(1 1):2 (2 1):6 (1 2):12 (3 1):13 (1 3):18 (2 2):36 (2 3):54 (3 2):78]
P = [(3 3):117]

R = [(1 1):2 (2 1):6 (1 2):12 (3 1):13 (1 3):18 (2 2):36 (2 3):54 (3 2):78 (3 3):117]
P = []
</code>```

Now, if A and B contain both non-negative and negative integers, we can use the above algorithm to solve at most 4 sub-problems concurrently to get the k smallest integers. For this, we define the iterator function F(A, B) that on each call yields the next product in increasing order using the above algorithm. Let A- and A+ be the sublists of A containing its negative and non-negative integers respectively. Same thing for B- and B+. We call our iterator function for the following 4 sub-problems.

```<code>F(A+, B+)
F(A+, reverse(B-))
F(reverse(A-), B+)
F(reverse(A-), reverse(B-))
</code>```

where reverse(L) returns list L with its elements in reverse order. We iterate over these four iterators choosing the k smallest returned pairs.

Body:
Here is an algorithm that has O(k min(n, m)) time complexity.

Let A and B be sorted lists of integers, i.e. A = [a1 a2 a3 ... am] with ai ≤ ai+1, and B = [b1 b2 b3 ... bn] with bi ≤ bi+1.

Assume for now that ai ≥ 0 and bi ≥ 0. We will show below how to account for negative integers.

Let p = (i j) be a pair, where i and j are the indexes of ai and bj. Let P be a list of pairs. Set P = [(1 1) (1 2) (1 3) ... (1 n)]. Assume k > 0 (and k ≤ m x n). Let R be the list of the pairs of the k first products. Initialize R = [].

Add the first pair p = (i j) of P to R.

If R is of size k, terminate.

Set p = (i+1 j). While the product of p is greater than the product
of the next pair q in P, exchange p and q.

Go to step 1.

The above algorithm has time complexity O(k n) and works for A and B containing non-negative integers only. Note that if m < n, we can exchange A and B to get a lower bound on the time complexity.

Here is an example that illustrates the algorithm with A = [2 6 13] and B = [1 6 9]. The matrix below shows the product ai x bj for every (i j).

  B   1   6   9
 A  ------------
 2 |  2  12  18
 6 |  6  36  54
13 | 13  78 117

This is the initial states of P and R at the start of the alogrithm. We suffix each pair (i j) in P with the value of the product ai x bj.

P = [(1 1):2 (1 2):12 (1 3):18] R = []

On the first iteration, (1 1):2 is added to R, and the first pair in P becomes (1+1 1).

R = [(1 1):2]
P = [(2 1):6 (1 2):12 (1 3):18]

On the next iteration, (2 1):6 is added to R, and the first pair in P becomes (2+1 1). Because the product of that pair is greater than the product of the next pair in P, they are exchanged.

R = [(1 1):2 (2 1):6]
P = [(3 1):13 (1 2):12 (1 3):18]
P = [(1 2):12 (3 1):13 (1 3):18]

Next iteration, similar operations as the previous iteration.

R = [(1 1):2 (2 1):6 (1 2):12]
P = [(2 2):36 (3 1):13 (1 3):18]
P = [(3 1):13 (1 3):18 (2 2):36]

In this iteration, after adding (3 1):13 to R, the first pair of P becomes (3+1 1), but that pair does not exist. So, it is simply removed from P.

R = [(1 1):2 (2 1):6 (1 2):12 (3 1):13]
P = [(1 3):18 (2 2):36]

Following are all remaining iterations until P is empty.

R = [(1 1):2 (2 1):6 (1 2):12 (3 1):13 (1 3):18]
P = [(2 3):54 (2 2):36]
P = [(2 2):36 (2 3):54]

R = [(1 1):2 (2 1):6 (1 2):12 (3 1):13 (1 3):18 (2 2):36]
P = [(3 2):78 (2 3):54]
P = [(2 3):54 (3 2):78]

R = [(1 1):2 (2 1):6 (1 2):12 (3 1):13 (1 3):18 (2 2):36 (2 3):54]
P = [(3 3):117 (3 2):78]
P = [(3 2):78 (3 3):117]

R = [(1 1):2 (2 1):6 (1 2):12 (3 1):13 (1 3):18 (2 2):36 (2 3):54 (3 2):78]
P = [(3 3):117]

R = [(1 1):2 (2 1):6 (1 2):12 (3 1):13 (1 3):18 (2 2):36 (2 3):54 (3 2):78 (3 3):117]
P = []

Now, if A and B contain both non-negative and negative integers, we can use the above algorithm to solve at most 4 sub-problems concurrently to get the k smallest integers. For this, we define the iterator function F(A, B) that on each call yields the next product in increasing order using the above algorithm. Let A- and A+ be the sublists of A containing its negative and non-negative integers respectively. Same thing for B- and B+. We call our iterator function for the following 4 sub-problems.

F(A+, B+)
F(A+, reverse(B-))
F(reverse(A-), B+)
F(reverse(A-), reverse(B-))

where reverse(L) returns list L with its elements in reverse order. We iterate over these four iterators choosing the k smallest returned pairs.


问:
How tom chain several transitions?
Hot to play transitions one after another in motionlayout to make it look as single animation?  While keyframe can be used  to make intermediate states between two constaintset they are also limited and cannot modify all desired properties.<br>
 </p>

```<code>    <Transition

        app:constraintSetEnd="@layout/simple_start"
        app:constraintSetStart="@layout/simple_middle"

        >
        <OnSwipe
            app:dragDirection="dragUp"
            app:touchAnchorId="@id/scrollable"
            app:touchAnchorSide="top" />

    </Transition>
    <Transition

        app:constraintSetEnd="@layout/simple_middle"
        app:constraintSetStart="@layout/simple_end"

        >
        <OnSwipe
            app:dragDirection="dragUp"
            app:touchAnchorId="@id/scrollable"
            app:touchAnchorSide="top" />

    </Transition>

</MotionScene>
</code>```

答:
did You try to start the transitions direct in your code like?</p>

```<code>((MotionLayout)findViewById(R.id.simple_start)).transitionToEnd();
((MotionLayout)findViewById(R.id.simple_middle)).transitionToEnd();
</code>```

Title: How tom chain several transitions?

Body:
Hot to play transitions one after another in motionlayout to make it look as single animation?  While keyframe can be used  to make intermediate states between two constaintset they are also limited and cannot modify all desired properties.

    <Transition

        app:constraintSetEnd="@layout/simple_start"
        app:constraintSetStart="@layout/simple_middle"

        >
        <OnSwipe
            app:dragDirection="dragUp"
            app:touchAnchorId="@id/scrollable"
            app:touchAnchorSide="top" />

    </Transition>
    <Transition

        app:constraintSetEnd="@layout/simple_middle"
        app:constraintSetStart="@layout/simple_end"

        >
        <OnSwipe
            app:dragDirection="dragUp"
            app:touchAnchorId="@id/scrollable"
            app:touchAnchorSide="top" />

    </Transition>

</MotionScene>

Body:
did You try to start the transitions direct in your code like?

((MotionLayout)findViewById(R.id.simple_start)).transitionToEnd();
((MotionLayout)findViewById(R.id.simple_middle)).transitionToEnd();


问:
How to close or dismiss a modal dialog
I have a modal dialog which I need to close/dismiss after I have identified it's presence and extracted it's text. The modal comes up when I click on the button to download a file and it says "Generating the debuginfo file. Please wait." This modal is present until the file download starts which is too long depending upon the debuginfo file size. Is there a way to close this dialog and exit with text extracted from it.

I am extracting the text using following code:

```<code>downloadText = WebDriverWait(self.driver,40).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.ui-dialog-content.ui-widgetcontent#dialog"))).get_attribute("innerHTML").split(">")[1]
</code>```

Following is the html code for this modal:

```<code>     <div class="ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix">
     <span id="ui-id-1" class="ui-dialog-title">Download debug info</span>
     <button class="ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only ui-dialog-titlebar-close" role="button" aria-disabled="false" title="close">
       <span class="ui-button-icon-primary ui-icon ui-icon-closethick">
       </span>
       <span class="ui-button-text">close</span>
     </button>
   </div>
   <div id="dialog" class="ui-dialog-content ui-widget-content" style="width: auto; min-height: 0px; max-height: none; height: 177px;">
     <br>Generating the debuginfo file. Please wait.</div>
     <div class="ui-resizable-handle ui-resizable-n" style="z-index: 90;">
     </div>
     <div class="ui-resizable-handle ui-resizable-e" style="z-index: 90;">
     </div>
     <div class="ui-resizable-handle ui-resizable-s" style="z-index: 90;">
     </div>
     <div class="ui-resizable-handle ui-resizable-w" style="z-index: 90;">
     </div>
     <div class="ui-resizable-handle ui-resizable-se ui-icon ui-icon-gripsmall-diagonal-se" style="z-index: 90;">
     </div>
     <div class="ui-resizable-handle ui-resizable-sw" style="z-index: 90;">
     </div>
     <div class="ui-resizable-handle ui-resizable-ne" style="z-index: 90;">
     </div>
     <div class="ui-resizable-handle ui-resizable-nw" style="z-index: 90;">

 </div> ```
```

答:
The close the Modal Dialog Box you have to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

Using CSS_SELECTOR:

```<code>WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.ui-button.ui-widget.ui-state-default.ui-corner-all.ui-button-icon-only.ui-dialog-titlebar-close[title='close'] span.ui-button-icon-primary.ui-icon.ui-icon-closethick"))).click()
</code>```

Using XPATH:

```<code>WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only ui-dialog-titlebar-close' and @title='close']//span[@class='ui-button-icon-primary ui-icon ui-icon-closethick']"))).click()
</code>```

Note : You have to add the following imports :

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
</code>```

Title: How to close or dismiss a modal dialog

Body:
I have a modal dialog which I need to close/dismiss after I have identified it's presence and extracted it's text. The modal comes up when I click on the button to download a file and it says "Generating the debuginfo file. Please wait." This modal is present until the file download starts which is too long depending upon the debuginfo file size. Is there a way to close this dialog and exit with text extracted from it.

I am extracting the text using following code:

downloadText = WebDriverWait(self.driver,40).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.ui-dialog-content.ui-widgetcontent#dialog"))).get_attribute("innerHTML").split(">")[1]

Following is the html code for this modal:

     Download debug info
     <button class="ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only ui-dialog-titlebar-close" role="button" aria-disabled="false" title="close">

       close
     </button>

Generating the debuginfo file. Please wait.

 ```

Body:
The close the Modal Dialog Box you have to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

Using CSS_SELECTOR:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.ui-button.ui-widget.ui-state-default.ui-corner-all.ui-button-icon-only.ui-dialog-titlebar-close[title='close'] span.ui-button-icon-primary.ui-icon.ui-icon-closethick"))).click()

Using XPATH:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only ui-dialog-titlebar-close' and @title='close']//span[@class='ui-button-icon-primary ui-icon ui-icon-closethick']"))).click()

Note : You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


问:
Java get a group of user names
I've coded a program where there is like 5 people "killing" a monster, and i need a piece of code to get all of the members "nickname" (getName() ) and display them with a coma beetwen, how could I do that?

I guess I could do a for loop but ye, not sure how to add the comas beetwen then..

答:
Assuming your players are in a collection, you can indeed use a loop, or you can use some 3rd party library, like guava:

```<code>Joiner.on(',').join(players);
</code>```

Or commons-lang:

```<code>StringUtils.join(players, ',');
</code>```

Title: Java get a group of user names

Body:
Assuming your players are in a collection, you can indeed use a loop, or you can use some 3rd party library, like guava:

Joiner.on(',').join(players);

Or commons-lang:

StringUtils.join(players, ',');


问:
Postgres convert json with duplicate IDs
With this select:

```<code>json_agg(json_build_object("id", price::money))
</code>```

I get the resulting value:

```<code>[
  {"6" : "$475.00"},
  {"6" : "$1,900.00"},
  {"3" : "$3,110.00"},
  {"3" : "$3,110.00"}
]
</code>```

I would like the data in this format instead:

```<code>{
  "6": ["$475.00","$1,900.00"],
  "3": ["$3,110.00","$3,110.00"]
}
</code>```

When queried on the server or used with jsonb, the IDs are duplicate and only one of the key value pairs make it through.

答:
You should aggregate prices in groups by ids and use the aggregate function json_object_agg(). You have to use a derived table (subquery in the from clause) because aggregates cannot be nested:

```<code>select json_object_agg(id, prices)
from (
    select id, json_agg(price::money) as prices
    from my_table
    group by id
    ) s
</code>```

Working example in rextester.

Body:
With this select:

json_agg(json_build_object("id", price::money))

I get the resulting value:

[
  {"6" : "$475.00"},
  {"6" : "$1,900.00"},
  {"3" : "$3,110.00"},
  {"3" : "$3,110.00"}
]

I would like the data in this format instead:

{
  "6": ["$475.00","$1,900.00"],
  "3": ["$3,110.00","$3,110.00"]
}

When queried on the server or used with jsonb, the IDs are duplicate and only one of the key value pairs make it through.

Body:
You should aggregate prices in groups by ids and use the aggregate function json_object_agg(). You have to use a derived table (subquery in the from clause) because aggregates cannot be nested:

select json_object_agg(id, prices)
from (
    select id, json_agg(price::money) as prices
    from my_table
    group by id
    ) s

Working example in rextester.


问:
When exactly does the TCP handshake occur in a XMLHttpRequest?
The XMLHttpRequest interface provides both an open() and a send() method.

In the following sample code:

```<code>var xhr = new XMLHttpRequest();
xhr.open('GET', '/server', true);

xhr.onload = function () {
  // Request finished. Do processing here.
};

xhr.send('string');
</code>```

Does the TCP handshake occur when send() is invoked, or open()?

答:
Some brief testing with tcpdump verified what has been suspected in the comments. No network calls are made at all when open() is called. All network information is transmitted when send() is invoked.

In addition, there is no guarantee that send() performs the handshake either. XMLHttpRequests sometimes reuse persistent connections from previous requests, and as such don't require a new handshake.

Body:
The XMLHttpRequest interface provides both an open() and a send() method.

In the following sample code:

var xhr = new XMLHttpRequest();
xhr.open('GET', '/server', true);

xhr.onload = function () {
  // Request finished. Do processing here.
};

xhr.send('string');

Does the TCP handshake occur when send() is invoked, or open()?


问:
How to find the percentage of NAs in a data.frame?
I am trying to find the percentage of NAs in columns as well as inside the whole dataframe:

The first method which I have commented gives me zero and the second method which is not commented gives me a matrix. Not sure what I am missing. Any hint is truly appreciated!

```<code>cp.2006<-read.csv(file="cp2006.csv",head=TRUE)

#countNAs <- function(x) {
#  sum(is.na(x))
#}
#total=0
#for (i in col(cp.2006)) {
#  total=countNAs(i)+total
#}
#print(total)
count<-apply(cp.2006, 1, function(x) sum(is.na(x)))
dims<-dim(cp.2006)
num<-dims[1]*dims[2]
NApercentage<-(count/num) * 100
print(NApercentage)
</code>```

答:
Updated version of dplyr which doesnt support funs anymore:

x%>% summarise_all(list(name = ~sum(is.na(.))/length(.)))

Body:
I am trying to find the percentage of NAs in columns as well as inside the whole dataframe:

The first method which I have commented gives me zero and the second method which is not commented gives me a matrix. Not sure what I am missing. Any hint is truly appreciated!

cp.2006<-read.csv(file="cp2006.csv",head=TRUE)

#countNAs <- function(x) {
#  sum(is.na(x))
#}
#total=0
#for (i in col(cp.2006)) {
#  total=countNAs(i)+total
#}
#print(total)
count<-apply(cp.2006, 1, function(x) sum(is.na(x)))
dims<-dim(cp.2006)
num<-dims[1]*dims[2]
NApercentage<-(count/num) * 100
print(NApercentage)


问:
Is it possible to include a C# variable in a string variable without using a concatenator?
Does .NET 3.5 C# allow us to include a variable within a string variable without having to use the + concatenator (or string.Format(), for that matter).

For example (In the pseudo, I'm using a $ symbol to specify the variable):

```<code>DateTime d = DateTime.Now;
string s = "The date is $d";
Console.WriteLine(s);
</code>```

Output:

The date is 4/12/2011 11:56:39 AM

Edit

Due to the handful of responses that suggested string.Format(), I can only assume that my original post wasn't clear when I mentioned "...(or string.Format(), for that matter)". To be clear, I'm well aware of the string.Format() method. However, in my specific project that I'm working on, string.Format() doesn't help me (it's actually worse than the + concatenator).

Also, I'm inferring that most/all of you are wondering what the motive behind my question is (I suppose I'd feel the same way if I read my question as is).

If you are one of the curious, here's the short of it:

I'm creating a web app running on a Windows CE device. Due to how the web server works, I create the entire web page content (css, js, html, etc) within a string variable. For example, my .cs managed code might have something like this:

```<code>string GetPageData()
    {
    string title = "Hello";
    DateTime date = DateTime.Now;

    string html = @"
    <!DOCTYPE html PUBLIC ...>
    <html>
    <head>
        <title>$title</title>
    </head>
    <body>
    <div>Hello StackO</div>
    <div>The date is $date</div>
    </body>
    </html>
    ";

}
</code>```

As you can see, having the ability to specify a variable without the need to concatenate, makes things a bit easier - especially when the content increases in size.

答:
```<code>string output = "the date is $d and time is $t";
output = output.Replace("$t", t).Replace("$d", d);  //and so on
</code>```

Body:
Does .NET 3.5 C# allow us to include a variable within a string variable without having to use the + concatenator (or string.Format(), for that matter).

For example (In the pseudo, I'm using a $ symbol to specify the variable):

DateTime d = DateTime.Now;
string s = "The date is $d";
Console.WriteLine(s);

Output:

The date is 4/12/2011 11:56:39 AM

Edit

Due to the handful of responses that suggested string.Format(), I can only assume that my original post wasn't clear when I mentioned "...(or string.Format(), for that matter)". To be clear, I'm well aware of the string.Format() method. However, in my specific project that I'm working on, string.Format() doesn't help me (it's actually worse than the + concatenator).

Also, I'm inferring that most/all of you are wondering what the motive behind my question is (I suppose I'd feel the same way if I read my question as is).

If you are one of the curious, here's the short of it:

I'm creating a web app running on a Windows CE device. Due to how the web server works, I create the entire web page content (css, js, html, etc) within a string variable. For example, my .cs managed code might have something like this:

string GetPageData()
    {
    string title = "Hello";
    DateTime date = DateTime.Now;

    string html = @"
    <!DOCTYPE html PUBLIC ...>

        <title>$title</title>

Hello StackO

The date is $date

    ";

}

As you can see, having the ability to specify a variable without the need to concatenate, makes things a bit easier - especially when the content increases in size.


问:
Removing SKVideoNode does not stop the audio from the video node
I've added an SKVideoNode to my GameScene. When I try to remove the video, the video image disappears, but the audio continues to play. I've tried to stop and pause the video before removing, but the audio continues to play regardless.

```<code>var introVideoIsPlaying = false
var introVideo: SKVideoNode!

func playIntroVideo() {

    introVideoIsPlaying = true

    if let videoURL = Bundle.main.url(forResource: "video", withExtension: "mp4") {

        introVideo = SKVideoNode(url: videoURL)
        introVideo.position = CGPoint(x: frame.midX, y: frame.midY)
        introVideo.size = self.frame.size

        self.addChild(introVideo)
        introVideo.play()

    }
}
</code>```

Then I remove the video in my touchesBegan -

```<code>if introVideoIsPlaying == true {

        introVideo.removeFromParent()
    }
</code>```

What could I be missing? Is there a way to independently stop the audio in an SKVideoNode?

答:
It is better to use AVPlayer in connection with SKVideoNose like below:

(you will have more options to control the video)

```<code>var player: AVPlayer?
player = AVPlayer(url: videoURL)
let videoNode = SKVideoNode(avPlayer: player!)
</code>```

You can then use the function didUpdate that fires anytime the the node changes. You can pause the video when the node is out of view like below

```<code>func renderer(_ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor) {
    if node.isHidden == true {
        print("Node is out of view")
        self.player?.pause()

    }

}
</code>```

Body:
I've added an SKVideoNode to my GameScene. When I try to remove the video, the video image disappears, but the audio continues to play. I've tried to stop and pause the video before removing, but the audio continues to play regardless.

var introVideoIsPlaying = false
var introVideo: SKVideoNode!

func playIntroVideo() {

    introVideoIsPlaying = true

    if let videoURL = Bundle.main.url(forResource: "video", withExtension: "mp4") {

        introVideo = SKVideoNode(url: videoURL)
        introVideo.position = CGPoint(x: frame.midX, y: frame.midY)
        introVideo.size = self.frame.size

        self.addChild(introVideo)
        introVideo.play()

    }
}

Then I remove the video in my touchesBegan -

if introVideoIsPlaying == true {

        introVideo.removeFromParent()
    }

What could I be missing? Is there a way to independently stop the audio in an SKVideoNode?

Body:
It is better to use AVPlayer in connection with SKVideoNose like below:

(you will have more options to control the video)

var player: AVPlayer?
player = AVPlayer(url: videoURL)
let videoNode = SKVideoNode(avPlayer: player!)

You can then use the function didUpdate that fires anytime the the node changes. You can pause the video when the node is out of view like below

func renderer(_ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor) {
    if node.isHidden == true {
        print("Node is out of view")
        self.player?.pause()

    }

}


答:
You can make a very simple recursive solution like so:

let a = {
  arr: [1, 2, 3],
  name: "A. Bc"
};

const deepFreeze = o => {
  for (let [key, value] of Object.entries(o)) {
    if (o.hasOwnProperty(key) && typeof value == "object") {
      deepFreeze(value);
    }
  }
  Object.freeze(o);
  return o;
}

deepFreeze(a);

try {
  a.arr.push(4);
} catch(e) {
  console.log("Error: ", e);
}
console.log(a);```

Title: Is there an easy way to completely freeze object and its children in Javascript, (Deep Freeze)?

Body:
Often you have to pass an object as parameter. Functions accessing those objects are pass by reference and can change original object. Which depending on situation can be  unwanted outcome. So is there a way to freeze object. I know about Object.freeze()

But it doesn't affect objects/arrays inside it.

For example

a = { arr: [1,2,3]};
Object.freeze(a);
a.arr.push(4); // still works


问:
Assigning method that takes a pointer to Func<>
I'm trying to conditionally assign a Method to a Func<>. The method I'm trying to assign takes a pointer argument, which it seems C# does not seem to allow me to use along with a Func<>. Here's the code.

```<code>Func<ulong, ulong, ulong*, ulong> Multiply64Func;

if (Bmi2.X64.IsSupported)
{
    Multiply64Func = Bmi2.X64.MultiplyNoFlags;
}
else
{
    Multiply64Func = Multiply64;
}
</code>```

And here's how I want to use it later:

```<code>hi = Multiply64Func(c[0], b[0], loPtr);
</code>```

And the corresponding error: error CS0306: The type 'ulong*' may not be used as a type argument

What's a workaround for this, or is there a way to get it to work?

Of course, I could just do this:

```<code>hi = Bmi2.X64.IsSupported ? Bmi2.X64.MultiplyNoFlags(c[0], b[0], loPtr) : Multiply64(c[0], b[0], loPtr);
</code>```

However, this section of code is very performance critical, and I see a notable speed decrease from checking this in a hot loop - hence why I want to perform the comparison once, and assign the corresponding method to a function.

The more C# thing to do would be to take a ref param - But I can't change the signature of Bmi2.X64.MultiplyNoFlags; since it's not my code.

答:
However, this section of code is very performance critical, and I see a notable speed decrease from checking this in a hot loop - hence why I want to perform the comparison once

Cache the result in a Boolean and use your simple answer.

```<code>bool useBmi = Bmi2.X64.IsSupported;

while (expensiveLoop)
{
    hi =  useBmi ? Bmi2.X64.MultiplyNoFlags(c[0], b[0], loPtr) : Multiply64(c[0], b[0], loPtr);
}
</code>```

If you insist on using a delegate you could do this:

```<code>bool useBmi = Bmi2.X64.IsSupported;
ulong hi;  //Must be declared outside the loop

Action multiply = useBmi
                ? new Action( () => { hi = Bmi2.X64.MultiplyNoFlags(c[0], b[0], loPtr); })
                : new Action( () => { hi = Multiply64(c[0], b[0], loPtr); } );

while (expensiveLoop)
{
    multiply();
}
</code>```

Body:
I'm trying to conditionally assign a Method to a Func<>. The method I'm trying to assign takes a pointer argument, which it seems C# does not seem to allow me to use along with a Func<>. Here's the code.

Func<ulong, ulong, ulong*, ulong> Multiply64Func;

if (Bmi2.X64.IsSupported)
{
    Multiply64Func = Bmi2.X64.MultiplyNoFlags;
}
else
{
    Multiply64Func = Multiply64;
}

And here's how I want to use it later:

hi = Multiply64Func(c[0], b[0], loPtr);

And the corresponding error: error CS0306: The type 'ulong*' may not be used as a type argument

What's a workaround for this, or is there a way to get it to work?

Of course, I could just do this:

hi = Bmi2.X64.IsSupported ? Bmi2.X64.MultiplyNoFlags(c[0], b[0], loPtr) : Multiply64(c[0], b[0], loPtr);

However, this section of code is very performance critical, and I see a notable speed decrease from checking this in a hot loop - hence why I want to perform the comparison once, and assign the corresponding method to a function.

The more C# thing to do would be to take a ref param - But I can't change the signature of Bmi2.X64.MultiplyNoFlags; since it's not my code.

Body:
However, this section of code is very performance critical, and I see a notable speed decrease from checking this in a hot loop - hence why I want to perform the comparison once

Cache the result in a Boolean and use your simple answer.

bool useBmi = Bmi2.X64.IsSupported;

while (expensiveLoop)
{
    hi =  useBmi ? Bmi2.X64.MultiplyNoFlags(c[0], b[0], loPtr) : Multiply64(c[0], b[0], loPtr);
}

If you insist on using a delegate you could do this:

bool useBmi = Bmi2.X64.IsSupported;
ulong hi;  //Must be declared outside the loop

Action multiply = useBmi
                ? new Action( () => { hi = Bmi2.X64.MultiplyNoFlags(c[0], b[0], loPtr); })
                : new Action( () => { hi = Multiply64(c[0], b[0], loPtr); } );

while (expensiveLoop)
{
    multiply();
}


问:
urllib.parse.urlparse not reading params
I'm trying to read parameters in python

```<code> urlparse('jdbc:mysql:@localhost:3306/mysql;user:pass?jdbc_driver_name=com.mysql.jdbc.Driver')
</code>```

According to documentation params are placed after semicolon, but I'm getting empty string for params in my example url.

答:
From the source code:

```<code>uses_params = ['', 'ftp', 'hdl', 'prospero', 'http', 'imap',
               'https', 'shttp', 'rtsp', 'rtspu', 'sip', 'sips',
               'mms', 'sftp', 'tel']
</code>```

It only parses params if thee scheme in this list.

```<code>def urlparse(url, scheme='', allow_fragments=True):
    url, scheme, _coerce_result = _coerce_args(url, scheme)
    splitresult = urlsplit(url, scheme, allow_fragments)
    scheme, netloc, url, query, fragment = splitresult
    if scheme in uses_params and ';' in url: # <------------------------------ Right here
        url, params = _splitparams(url)
    else:
        params = ''
    result = ParseResult(scheme, netloc, url, params, query, fragment)
    return _coerce_result(result)
</code>```

Body:
I'm trying to read parameters in python

 urlparse('jdbc:mysql:@localhost:3306/mysql;user:pass?jdbc_driver_name=com.mysql.jdbc.Driver')

According to documentation params are placed after semicolon, but I'm getting empty string for params in my example url.

Body:
From the source code:

uses_params = ['', 'ftp', 'hdl', 'prospero', 'http', 'imap',
               'https', 'shttp', 'rtsp', 'rtspu', 'sip', 'sips',
               'mms', 'sftp', 'tel']

It only parses params if thee scheme in this list.

def urlparse(url, scheme='', allow_fragments=True):
    url, scheme, _coerce_result = _coerce_args(url, scheme)
    splitresult = urlsplit(url, scheme, allow_fragments)
    scheme, netloc, url, query, fragment = splitresult
    if scheme in uses_params and ';' in url: # <------------------------------ Right here
        url, params = _splitparams(url)
    else:
        params = ''
    result = ParseResult(scheme, netloc, url, params, query, fragment)
    return _coerce_result(result)


答:
Well, what you do in your loop depends on the way you have this information stored and the structure you are using for things...

But an example would be:

```<code> String namesList = "";
    for(int i = 0; i != 5; ++i){
        String name = users[i].getName()
        namesList += name;
        namesList += ", ";
        ... //do something else
    }
</code>```

Title: Java get a group of user names

Body:
I've coded a program where there is like 5 people "killing" a monster, and i need a piece of code to get all of the members "nickname" (getName() ) and display them with a coma beetwen, how could I do that?

I guess I could do a for loop but ye, not sure how to add the comas beetwen then..

Body:
Well, what you do in your loop depends on the way you have this information stored and the structure you are using for things...

But an example would be:

 String namesList = "";
    for(int i = 0; i != 5; ++i){
        String name = users[i].getName()
        namesList += name;
        namesList += ", ";
        ... //do something else
    }


问:
Whether i can hit non public URL from Dialog flow through web hook?
I want to use Dialogflow for my enterprise usage. So want to know whether Dialog flow will be able to hit Non public URLs?</p>

答:
Since Dialogflow is a service hosted by Google, fulfillment requests specified by Webhook URLs must be able to be reached by Dialogflow for them to be invoked.  In addition, the webhook endpoints must expose themselves using SSL/TLS and must be associated with a non-self-signed certificate.  When a request is made from Dialogflow, dialogflow can provide authentication credentials to ensure that it is indeed Dialogflow that is making the request.

One pattern for your usage is to expose the Webhooks to the Internet and only allow connections from the Google IP address range and also require authentication (known only to Dialogflow).  This would go a long way in preventing malicious access to your Webhook.

An alternative would be to define your Webhook as a GCP hosted endpoint and then you would own the routing back to your internal system from there.  That could use a variety of technologies beyond HTTP including Pub/Sub.  For example, when Dialogflow invokes the Webhook, a GCP application could be called that posts a message to PubSub.  Your Enterprise application could be a subscriber and be notified that it has work to do.  It does work and responds with a new message which is received by your GCP hosted Webhook that then returns the response to Dialogflow.  As such, there is no surface area for an attacker to try and penetrate.


问:
Does Django pyodbc support Nexus DB or is it Database dependent?
I have a project where i need to connect Nexus DB in a Django application. I have tried with Django-pyodbc,

```<code>DATABASES = {
'default': {
    'ENGINE': "django_pyodbc",
    'HOST': "nexusdb@xxx.xxx.x.xx",
    'USER': "",
    'PASSWORD': "",
    'NAME': "testDB",
    'OPTIONS': {
        'driver': '{NexusDB V3.10 Driver}',
        'host_is_server': True,

    },
}
</code>```

}

but failed to establish connection.

I have tried latest alpha release of Django-pyodbc2.0.0a1 and django-pyodbc-azure, but found so many SQL Server specific issues. found that it is specific toMS SQL Server and Microsoft azure Database.

Does pyodbc on its own connect to NexusDB? If so, can it execute queries?

Does Django-pyodbc work correctly with a different ODBC driver?

Does Django-pyodbc support Nexus DB?

Can anyone help me on this ?

Thanks

答:
As far as I know, django-pyodbc only supports MS SQL Server. It uses the underlying pyodbc package, but many of the mappings needed for the Django engine are SQL Server specific. The most up-to-date Django engine package for SQL Server is django-pyodbc-azure.

You may want to take a look at this list; the more popular databases are much more likely to have support in any web framework. https://db-engines.com/en/ranking

If you could use another database for Django's default database, you could use pyodbc on its own to pull data from your Nexus DB. I've done this before where I use PostgreSQL for Django, and make alternate connections to both SAS and SQL Server to grab data.

Body:
I have a project where i need to connect Nexus DB in a Django application. I have tried with Django-pyodbc,

DATABASES = {
'default': {
    'ENGINE': "django_pyodbc",
    'HOST': "nexusdb@xxx.xxx.x.xx",
    'USER': "",
    'PASSWORD': "",
    'NAME': "testDB",
    'OPTIONS': {
        'driver': '{NexusDB V3.10 Driver}',
        'host_is_server': True,

    },
}

}

but failed to establish connection.

I have tried latest alpha release of Django-pyodbc2.0.0a1 and django-pyodbc-azure, but found so many SQL Server specific issues. found that it is specific toMS SQL Server and Microsoft azure Database.

Does pyodbc on its own connect to NexusDB? If so, can it execute queries?

Does Django-pyodbc work correctly with a different ODBC driver?

Does Django-pyodbc support Nexus DB?

Can anyone help me on this ?

Thanks