问:
writing R function with ggplot
I have to plot multiple datasets in the same format, and after copy-pasting the code several times, I decided to write a function.
I understand simple function in R, and managed to write the following:

```<code>testplot <- function(data, mapping){
output <- ggplot(data) +
  geom_bar(mapping,
           stat="identity",
             position='stack')
}
p <- testplot(df, aes(x=xvar, y=yvar, fill=type))
</code>```

this works fine, however, my plot is more complicated and requires the "data" argument to go separately into each component:

```<code>output <- ggplot() +
  geom_bar(df1, mapping,
           stat="identity",
             position='stack')+
geom_errorbar(df1, ...)+
geom+bar(df2, mapping,
...+
geom_errorbar(df2, ...)
</code>```

but when I write the function and try to run it as

```<code>output <- ggplot() +
  geom_bar(data, mapping,
           stat="identity",
             position='stack')
}
p <- testplot(df, aes(x=xvar, y=yvar, fill=type))
</code>```

it gives me an error:

```<code>Error: `data` must be a data frame, or other object coercible by `fortify()`, not an S3 object with class uneval Did you accidentally pass `aes()` to the `data` argument?
</code>```

Is there a way around it?

EDIT: when I try to include 2 dataframes like this:

```<code>testplot <- function(data, data2, mapping){
output <- ggplot() +
 geom_bar(data=data, mapping=mapping,
           stat="identity",
             position='stack',
           width = barwidth)+
geom_bar(data2=data2, mapping=mapping,
           stat="identity",
             position='stack',
           width = barwidth)
}

p <- testplot(data=df, data2=df2, mapping=aes(x=norms_number, y=coeff.BLDRT, fill=type))
</code>```

it says "Ignoring unknown parameters: data2"

答:
The reason I split my dataframe was because I wanted a grouped and stacked plot, and used this question:
How to plot a Stacked and grouped bar chart in ggplot?

The mapping has to be different so that they don't end up on top on each other (so it's x=var1, and then x=var1+barwidth)

Anyway, I can make a plot with multiple geom_bar, but it's the subsequent geom_errorbar that doesn't work in a single function. I just added the error bars separately in the end, and maybe I'll look into the other options some other time.

I realise these are already functions so probably not meant to be used this way, and maybe that's why I can't do multiple geom_errorbar in one function. I just wanted my code to be more readable because I had to plot the same thing 12 times, with very minor differences and it was very long. Perhaps there is a more elegant way to do it though.

Title: writing R function with ggplot

Body:
I have to plot multiple datasets in the same format, and after copy-pasting the code several times, I decided to write a function.
I understand simple function in R, and managed to write the following:

testplot <- function(data, mapping){
output <- ggplot(data) +
  geom_bar(mapping,
           stat="identity",
             position='stack')
}
p <- testplot(df, aes(x=xvar, y=yvar, fill=type))

this works fine, however, my plot is more complicated and requires the "data" argument to go separately into each component:

output <- ggplot() +
  geom_bar(df1, mapping,
           stat="identity",
             position='stack')+
geom_errorbar(df1, ...)+
geom+bar(df2, mapping,
...+
geom_errorbar(df2, ...)

but when I write the function and try to run it as

output <- ggplot() +
  geom_bar(data, mapping,
           stat="identity",
             position='stack')
}
p <- testplot(df, aes(x=xvar, y=yvar, fill=type))

it gives me an error:

Error: `data` must be a data frame, or other object coercible by `fortify()`, not an S3 object with class uneval Did you accidentally pass `aes()` to the `data` argument?

Is there a way around it?

EDIT: when I try to include 2 dataframes like this:

testplot <- function(data, data2, mapping){
output <- ggplot() +
 geom_bar(data=data, mapping=mapping,
           stat="identity",
             position='stack',
           width = barwidth)+
geom_bar(data2=data2, mapping=mapping,
           stat="identity",
             position='stack',
           width = barwidth)
}

p <- testplot(data=df, data2=df2, mapping=aes(x=norms_number, y=coeff.BLDRT, fill=type))

it says "Ignoring unknown parameters: data2"


来源: stackexchange

问:
var module = require() or const {module} = require()?
Whats the diference between this two require methods:

```<code>1. var xx = require('module')
2. const {xx} = require('module')
</code>```

I saw the first onde I can access xx as variable, with all script exported by module.. and second xx are undefined. How to access second "method" or is it a method too construct module to use {}

thanks

答:
These two differ in two aspects:

Constness of xx: in the first case, adding the statement xx = 5; is legal, but not in the second case, since you declared xx as const.

In the second example, you use destructuring. Destructuring takes elements from objects and assigns them directly to variables. For instance:

```<code>var a = { "x": 1, "y": 2};

var { y } = a;
// This is equivalent to:
var y = a.y;
</code>```

Then your second statement just takes the xx attribute from your module as if you did:

```<code>const xx = require('module').xx;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Whats the diference between this two require methods:

1. var xx = require('module')
2. const {xx} = require('module')

I saw the first onde I can access xx as variable, with all script exported by module.. and second xx are undefined. How to access second "method" or is it a method too construct module to use {}

thanks

Body:
These two differ in two aspects:

Constness of xx: in the first case, adding the statement xx = 5; is legal, but not in the second case, since you declared xx as const.

In the second example, you use destructuring. Destructuring takes elements from objects and assigns them directly to variables. For instance:

var a = { "x": 1, "y": 2};

var { y } = a;
// This is equivalent to:
var y = a.y;

Then your second statement just takes the xx attribute from your module as if you did:

const xx = require('module').xx;


问:
std::list<const SomeClass> can not be defined
I'm trying to define a constant list of constant objects and I can't seem to get it done.
Here is my example that compiles fine:

```<code>#include <string>
#include <list>

class Person { public:
    std::string name;
    Person(const std::string &in_name){name=in_name;}
};

class MyClass { public:
    const std::list</* const */Person> l;
    MyClass(const std::list</* const */Person> &in_l):l(in_l){}
};

int main(int argc, char **argv) {
    Person dave("dave");
    MyClass c(std::list<const Person>(dave));
    return 0;
}
</code>```

When I remove the comments from const in those 2 places,
I get the following errors:

```<code>In file included from /usr/include/x86_64-linux-gnu/c++/7/bits/c++allocator.h:33:0,
                 from /usr/include/c++/7/bits/allocator.h:46,
                 from /usr/include/c++/7/string:41,
                 from main66.cpp:1:
/usr/include/c++/7/ext/new_allocator.h: In instantiation of ‘class __gnu_cxx::new_allocator<const Person>’:
/usr/include/c++/7/bits/allocator.h:108:11:   required from ‘class std::allocator<const Person>’
main66.cpp:11:53:   required from here
/usr/include/c++/7/ext/new_allocator.h:93:7: error: ‘const _Tp* __gnu_cxx::new_allocator<_Tp>::address(__gnu_cxx::new_allocator<_Tp>::const_reference) const [with _Tp = const Person; __gnu_cxx::new_allocator<_Tp>::const_pointer = const Person*; __gnu_cxx::new_allocator<_Tp>::const_reference = const Person&]’ cannot be overloaded
       address(const_reference __x) const _GLIBCXX_NOEXCEPT
       ^~~~~~~
/usr/include/c++/7/ext/new_allocator.h:89:7: error: with ‘_Tp* __gnu_cxx::new_allocator<_Tp>::address(__gnu_cxx::new_allocator<_Tp>::reference) const [with _Tp = const Person; __gnu_cxx::new_allocator<_Tp>::pointer = const Person*; __gnu_cxx::new_allocator<_Tp>::reference = const Person&]’
       address(reference __x) const _GLIBCXX_NOEXCEPT
       ^~~~~~~
</code>```

Is there any way to define a std::list of const objects?

答:
Allocator-aware containers, such as std::list, cannot take const value types, because the Allocator requirements specify behavior only for cv-unqualified types. This means that the container is not guaranteed to be able to create the element objects through the allocator interface if the value type is const or volatile qualified.

This is not a problem though, because the container being const is enough to guarantee that the elements are not changed. If you access an element of the container through a const reference to the container, you will only ever get a const reference to the element.

So, just use const std::list<Person>, instead of const std::list<const Person>.

Technically someone could const_cast the constness away from such a reference to be able to modify the elements and that would probably be legal, i.e. not undefined behavior, but that is something that a user can always do, just that it would cause undefined behavior with const objects.

See also Does C++11 allow vector<const T>? for details.

Body:
I'm trying to define a constant list of constant objects and I can't seem to get it done.
Here is my example that compiles fine:

#include <string>
#include <list>

class Person { public:
    std::string name;
    Person(const std::string &in_name){name=in_name;}
};

class MyClass { public:
    const std::list</* const */Person> l;
    MyClass(const std::list</* const */Person> &in_l):l(in_l){}
};

int main(int argc, char **argv) {
    Person dave("dave");
    MyClass c(std::list<const Person>(dave));
    return 0;
}

When I remove the comments from const in those 2 places,
I get the following errors:

In file included from /usr/include/x86_64-linux-gnu/c++/7/bits/c++allocator.h:33:0,
                 from /usr/include/c++/7/bits/allocator.h:46,
                 from /usr/include/c++/7/string:41,
                 from main66.cpp:1:
/usr/include/c++/7/ext/new_allocator.h: In instantiation of ‘class __gnu_cxx::new_allocator<const Person>’:
/usr/include/c++/7/bits/allocator.h:108:11:   required from ‘class std::allocator<const Person>’
main66.cpp:11:53:   required from here
/usr/include/c++/7/ext/new_allocator.h:93:7: error: ‘const _Tp* __gnu_cxx::new_allocator<_Tp>::address(__gnu_cxx::new_allocator<_Tp>::const_reference) const [with _Tp = const Person; __gnu_cxx::new_allocator<_Tp>::const_pointer = const Person*; __gnu_cxx::new_allocator<_Tp>::const_reference = const Person&]’ cannot be overloaded
       address(const_reference __x) const _GLIBCXX_NOEXCEPT
       ^~~~~~~
/usr/include/c++/7/ext/new_allocator.h:89:7: error: with ‘_Tp* __gnu_cxx::new_allocator<_Tp>::address(__gnu_cxx::new_allocator<_Tp>::reference) const [with _Tp = const Person; __gnu_cxx::new_allocator<_Tp>::pointer = const Person*; __gnu_cxx::new_allocator<_Tp>::reference = const Person&]’
       address(reference __x) const _GLIBCXX_NOEXCEPT
       ^~~~~~~

Is there any way to define a std::list of const objects?


问:
vim displaying live formula without document body
I know there is a plugin called vim-live-latex-preview, which also requires a root tex file with \begin{document}\end{document} body.
What I need is actually when I type in a formula in a tex file with vim, there could be some live display rendering the formula as I typed, just like the R studio notebook.

An easy hack I could think up of is to automatically insert the formula I typed into a \begin{document}\end{document} body, but I actually do not know how to do that. Any suggestions? ideas?

答: one solution is to wrap around document around pdflatex with the bare math latex file to show quickly if the formula displays good </p>


问:
Movable window in silverlight
I have window which is now movable in the application but the issue is the window get move out of the context as well with in the context it get go behind the control and than the window is not reachable.

Please suggest the solution for it.

Thank you

答: I am not sure this is what you are looking for, but you can try using FloatableWindow instead.  If you want to know how it works, the source code is public and I am sure you can find the answer looking through it.  I can say that it is normally pretty complex to get this working right with window resizing and all the other things you need to think about.

ContentLicense: CC BY-SA 3.0

Title: Movable window in silverlight


问:
Get the error of a JSON Validation List in ReactJS
On my api test, it was able to run as the image below. but, when I try to code in React.JS, the user Id cannot be pass in. What is the problem of this?

But when I try to code in front end, the user Id cannot be pass in to api.
Consider the code below:

```<code>  constructor (props){
    super(props);
    const Users_id = localStorage.getItem('id');
    this.state ={
      users_id: Users_id,
      event_name: '',
      event_email: '',
      event_description: '',
      event_type: '',
      event_location: '',
      start_date: '',
      end_date: '',
      history: PropTypes.object.isRequired
    }
    this.create = this.create.bind(this);
    this.onChange = this.onChange.bind(this);
  }

  create(){
    // const loginEmail = localStorage.getItem('loginEmail');
    const Users_id = localStorage.getItem('id');
    this.setState({Users_id})
    // console.log(loginEmail)
    PostData('api/event/submit', this.state).then ((result) => {
        let responseJSON = result;
        console.log(responseJSON);
        console.log(this.state)

      });
   }
</code>```

The error show in console.log(responseJSON):

//Updated PostData

```<code>    return new Promise((resolve, reject) => {
        fetch( BaseUrl+type, {
            method: "POST",
            body: JSON.stringify(userData),
            Accept: 'application/json',
            // mode: 'no-cors',
            headers:
                {
                    'Content-Type': 'application/json'
                },
          })
        .then((response) => response.json())
        .then((responseJson) => {
            resolve(responseJson);
        })
        .catch((error)=>{
            console.error('Error:', error);
        })

    });
</code>```

答:
Storage.getItem returns a string. The id should be casted to a number

const Users_id = parseInt(localStorage.getItem('id'));

You may want to check isNaN(Users_id) before sending it. Or just let it fail, and handle the error.

Body:
On my api test, it was able to run as the image below. but, when I try to code in React.JS, the user Id cannot be pass in. What is the problem of this?

But when I try to code in front end, the user Id cannot be pass in to api.
Consider the code below:

  constructor (props){
    super(props);
    const Users_id = localStorage.getItem('id');
    this.state ={
      users_id: Users_id,
      event_name: '',
      event_email: '',
      event_description: '',
      event_type: '',
      event_location: '',
      start_date: '',
      end_date: '',
      history: PropTypes.object.isRequired
    }
    this.create = this.create.bind(this);
    this.onChange = this.onChange.bind(this);
  }

  create(){
    // const loginEmail = localStorage.getItem('loginEmail');
    const Users_id = localStorage.getItem('id');
    this.setState({Users_id})
    // console.log(loginEmail)
    PostData('api/event/submit', this.state).then ((result) => {
        let responseJSON = result;
        console.log(responseJSON);
        console.log(this.state)

      });
   }

The error show in console.log(responseJSON):

//Updated PostData

    return new Promise((resolve, reject) => {
        fetch( BaseUrl+type, {
            method: "POST",
            body: JSON.stringify(userData),
            Accept: 'application/json',
            // mode: 'no-cors',
            headers:
                {
                    'Content-Type': 'application/json'
                },
          })
        .then((response) => response.json())
        .then((responseJson) => {
            resolve(responseJson);
        })
        .catch((error)=>{
            console.error('Error:', error);
        })

    });


问:
Notification of instance state changes
Is there any way to get a some logs out of AWS for things like "instance i-XXXX was started using ami-YYYY at 13:45.34 UTC" perhaps dumping a load of other information about the instance at the same time, e.g. az, key pair etc... Sure I can use cloud watch to monitor CPU usage, but I just want a simple log I can look at to see what amazon thinks happened in our cloud overnight.</p>

答: CloudTrail has all those infomation. You don't need to do anything:

Title: Notification of instance state changes


问:
Why isn't this simple color change of a Font Awesome SVG icon not working?
I'm trying to change the color of a Font Awesome icon. I'm not using the font or the  markup. I'm using a downloaded .svg image file.

The SVG inside the file is pretty simple:

<svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="cat" class="svg-inline--fa fa-cat fa-w-16"
  role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
  <path fill="currentColor" d="M290.59 192c-20.18 0-106.82 1.98-162.59 85.95V192c0-52.94-43.06-96-96-96-17.67 0-32 14.33-32 32s14.33 32 32 32c17.64 0 32 14.36 32
    32v256c0 35.3 28.7 64 64 64h176c8.84 0 16-7.16 16-16v-16c0-17.67-14.33-32-32-32h-32l128-96v144c0 8.84
    7.16 16 16 16h32c8.84 0 16-7.16 16-16V289.86c-10.29 2.67-20.89 4.54-32 4.54-61.81
    0-113.52-44.05-125.41-102.4zM448 96h-64l-64-64v134.4c0 53.02 42.98 96 96 96s96-42.98
    96-96V32l-64 64zm-72 80c-8.84 0-16-7.16-16-16s7.16-16 16-16 16 7.16 16 16-7.16 16-16
    16zm80 0c-8.84 0-16-7.16-16-16s7.16-16 16-16 16 7.16 16 16-7.16 16-16 16z"></path></svg>
```

<p>I was expecting that the <code>fill="currentColor"</code> setting inside the .svg file would allow the image to change color with simple CSS styling, but that doesn't seem to be the case. Do SVG images <em>as files</em> always behave as if <code>currentColor</code> is black? Is there a way around this?</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <img src="https://shetline.com/img/cat-solid.svg" width=50 height=50> ← SVG image defaults to black<br>
  <div style="color: red"><img src="https://shetline.com/img/cat-solid.svg" width=50 height=50> ← This SVG image should be red</div>
  <img style="color: blue" src="https://shetline.com/img/cat-solid.svg" width=50 height=50> ← This SVG image should be blue<br>
</div>
<div style="display: inline-block; color: green; width: 50px; height: 50px;">
<svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="cat" class="svg-inline--fa fa-cat fa-w-16"
  role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
  <path fill="currentColor" d="M290.59 192c-20.18 0-106.82 1.98-162.59 85.95V192c0-52.94-43.06-96-96-96-17.67 0-32 14.33-32 32s14.33 32 32 32c17.64 0 32 14.36 32
32v256c0 35.3 28.7 64 64 64h176c8.84 0 16-7.16 16-16v-16c0-17.67-14.33-32-32-32h-32l128-96v144c0 8.84
7.16 16 16 16h32c8.84 0 16-7.16 16-16V289.86c-10.29 2.67-20.89 4.54-32 4.54-61.81
0-113.52-44.05-125.41-102.4zM448 96h-64l-64-64v134.4c0 53.02 42.98 96 96 96s96-42.98
96-96V32l-64 64zm-72 80c-8.84 0-16-7.16-16-16s7.16-16 16-16 16 7.16 16 16-7.16 16-16
16zm80 0c-8.84 0-16-7.16-16-16s7.16-16 16-16 16 7.16 16 16-7.16 16-16 16z"></path></svg></div>
← Applying color works when using inline SVG instead of SVG image file</code>```

答:
SVG files accessed as standalone external images (for instance  or background-image) have to be self-contained. Styling outside the file does not affect the SVG.

You can think of it as if it were just a PNG file.

Body:
I'm trying to change the color of a Font Awesome icon. I'm not using the font or the  markup. I'm using a downloaded .svg image file.

The SVG inside the file is pretty simple:

<svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="cat" class="svg-inline--fa fa-cat fa-w-16"
  role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
  <path fill="currentColor" d="M290.59 192c-20.18 0-106.82 1.98-162.59 85.95V192c0-52.94-43.06-96-96-96-17.67 0-32 14.33-32 32s14.33 32 32 32c17.64 0 32 14.36 32
    32v256c0 35.3 28.7 64 64 64h176c8.84 0 16-7.16 16-16v-16c0-17.67-14.33-32-32-32h-32l128-96v144c0 8.84
    7.16 16 16 16h32c8.84 0 16-7.16 16-16V289.86c-10.29 2.67-20.89 4.54-32 4.54-61.81
    0-113.52-44.05-125.41-102.4zM448 96h-64l-64-64v134.4c0 53.02 42.98 96 96 96s96-42.98
    96-96V32l-64 64zm-72 80c-8.84 0-16-7.16-16-16s7.16-16 16-16 16 7.16 16 16-7.16 16-16
    16zm80 0c-8.84 0-16-7.16-16-16s7.16-16 16-16 16 7.16 16 16-7.16 16-16 16z"></path></svg>

I was expecting that the fill="currentColor" setting inside the .svg file would allow the image to change color with simple CSS styling, but that doesn't seem to be the case. Do SVG images as files always behave as if currentColor is black? Is there a way around this?

   ← SVG image defaults to black

 ← This SVG image should be red

   ← This SVG image should be blue

<svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="cat" class="svg-inline--fa fa-cat fa-w-16"
  role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
  <path fill="currentColor" d="M290.59 192c-20.18 0-106.82 1.98-162.59 85.95V192c0-52.94-43.06-96-96-96-17.67 0-32 14.33-32 32s14.33 32 32 32c17.64 0 32 14.36 32
32v256c0 35.3 28.7 64 64 64h176c8.84 0 16-7.16 16-16v-16c0-17.67-14.33-32-32-32h-32l128-96v144c0 8.84
7.16 16 16 16h32c8.84 0 16-7.16 16-16V289.86c-10.29 2.67-20.89 4.54-32 4.54-61.81
0-113.52-44.05-125.41-102.4zM448 96h-64l-64-64v134.4c0 53.02 42.98 96 96 96s96-42.98
96-96V32l-64 64zm-72 80c-8.84 0-16-7.16-16-16s7.16-16 16-16 16 7.16 16 16-7.16 16-16
16zm80 0c-8.84 0-16-7.16-16-16s7.16-16 16-16 16 7.16 16 16-7.16 16-16 16z"></path></svg>

← Applying color works when using inline SVG instead of SVG image file

Body:
SVG files accessed as standalone external images (for instance <img> or background-image) have to be self-contained. Styling outside the file does not affect the SVG.

You can think of it as if it were just a PNG file.


问:
Mysql Connection with out password using corejava program
I want to connect to a MySQL database. While installing MySQL I did not give any password, so in my program I did the same but I am getting error on connection. I am using properties file to get the driver, URL, username and password. Help me pleas.

This is my code:

```<code>try
{
    Class.forName("com.mysql.jdbc.Driver");
    con=DriverManager.getConnection("jdbc:mysql://localhost:3306/easylibdb1","root","");
}
catch (Exception e)
{
    System.out.println("Got Error While Connecting To Database...!");
    e.printStackTrace();
}
</code>```

This is my properties file content:

```<code>driver=com.mysql.jdbc.Driver
url=jdbc:mysql://192.168.1.51:3306/easylibdb1
user=root
password=""
</code>```

答:
According to you, you are passing username as root and password as empty string.And your connection is established through

```<code>con=DriverManager.getConnection("jdbc:mysql://localhost:3306/easylibdb1","root","");
</code>```

So change your function as

```<code>con=DriverManager.getConnection("jdbc:mysql://localhost:3306/easylibdb1","root",null);
</code>```

Then it will work.
Or change the password in the application.properties file as

```<code>password=
</code>```

Body:
I want to connect to a MySQL database. While installing MySQL I did not give any password, so in my program I did the same but I am getting error on connection. I am using properties file to get the driver, URL, username and password. Help me pleas.

This is my code:

try
{
    Class.forName("com.mysql.jdbc.Driver");
    con=DriverManager.getConnection("jdbc:mysql://localhost:3306/easylibdb1","root","");
}
catch (Exception e)
{
    System.out.println("Got Error While Connecting To Database...!");
    e.printStackTrace();
}

This is my properties file content:

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://192.168.1.51:3306/easylibdb1
user=root
password=""

Body:
According to you, you are passing username as root and password as empty string.And your connection is established through

con=DriverManager.getConnection("jdbc:mysql://localhost:3306/easylibdb1","root","");

So change your function as

con=DriverManager.getConnection("jdbc:mysql://localhost:3306/easylibdb1","root",null);

Then it will work.
Or change the password in the application.properties file as

password=


问:
Skipping blank cell from csv file in a python loop
I am curently extracting values in a csv file to incorporate them in yaml files.

The issue is that in the ~6000 lines in my csv files, a few cells are empty and I would like to skip those cells and continue my loop, which is like:

```<code>import csv
import ruamel.yaml
from csv import reader
from ruamel.yaml import YAML

yaml = ruamel.yaml.YAML()
yaml.preserve_quotes = True

with open('config.yaml') as yml:
    doc = yaml.load(yml)

with open('params.csv') as f:
    next(f)
    for i, data in enumerate(reader(f)):
        doc['components']['star']['init'][0]['values']['logg'] = float(data[4])
        filename = data[1].split(".")[0]
        with open(f'{filename}.yaml', 'w') as out:
            yaml.dump(doc, out)

</code>```

With the csv file looking like:

```<code>Starid   filename                                   Teff           TeffErr        logg
1        ngc6397id000000002jd2456871p6250f000.fits  6304.19055182  97.72410249    4.21614564
2        pgc6397id000000002jd2456871p6250f000.fits  7304.19055182  97.72410249
3        qgc6397id000000002jd2456871p6250f000.fits  8304.19055182  97.72410249    5.21614564

</code>```

I have tried the solution from Python: How to check if cell in CSV file is empty?
But I think I do it wrong, I can not see where to integrate the if not row[0] loop at the right place, any idea ?
Thanks !

答:
If I understand your problem correctly, you can just insert a check of the value like this:</p>

```<code>with open('params.csv') as f:
    next(f)
    for i, data in enumerate(reader(f)):
        if data[4] != '':
            doc['components']['star']['init'][0]['values']['logg'] = float(data[4])
            filename = data[1].split(".")[0]
            with open(f'{filename}.yaml', 'w') as out:
                yaml.dump(doc, out)
</code>```

Body:
I am curently extracting values in a csv file to incorporate them in yaml files.

The issue is that in the ~6000 lines in my csv files, a few cells are empty and I would like to skip those cells and continue my loop, which is like:

import csv
import ruamel.yaml
from csv import reader
from ruamel.yaml import YAML

yaml = ruamel.yaml.YAML()
yaml.preserve_quotes = True

with open('config.yaml') as yml:
    doc = yaml.load(yml)

with open('params.csv') as f:
    next(f)
    for i, data in enumerate(reader(f)):
        doc['components']['star']['init'][0]['values']['logg'] = float(data[4])
        filename = data[1].split(".")[0]
        with open(f'{filename}.yaml', 'w') as out:
            yaml.dump(doc, out)

With the csv file looking like:

Starid   filename                                   Teff           TeffErr        logg
1        ngc6397id000000002jd2456871p6250f000.fits  6304.19055182  97.72410249    4.21614564
2        pgc6397id000000002jd2456871p6250f000.fits  7304.19055182  97.72410249
3        qgc6397id000000002jd2456871p6250f000.fits  8304.19055182  97.72410249    5.21614564

I have tried the solution from Python: How to check if cell in CSV file is empty?
But I think I do it wrong, I can not see where to integrate the if not row[0] loop at the right place, any idea ?
Thanks !

Body:
If I understand your problem correctly, you can just insert a check of the value like this:

with open('params.csv') as f:
    next(f)
    for i, data in enumerate(reader(f)):
        if data[4] != '':
            doc['components']['star']['init'][0]['values']['logg'] = float(data[4])
            filename = data[1].split(".")[0]
            with open(f'{filename}.yaml', 'w') as out:
                yaml.dump(doc, out)


问:
Simple Powershell: Output basic Text instead of formatted from Get-ADOrganizationalUnit
This really applies to almost any PS command but I'm running:

```<code>Get-ADOrganizationalUnit -LDAPFilter '(name=*)' -SearchBase $strDomainDN -SearchScope OneLevel
</code>```

and the output looks like:

```<code>$_.Name
------
OU1
OU2
OU3
...
</code>```

And all I want is the actual list with not heading ($_.Name or the "------").  I know this is probably amazingly simple but also very frustrating when trying to format strings.  Any help would be appreciated.

答:
PowerShell is what would happen if Perl and .Net reproduced.

This isn't an answer, but the reason Andy's answer works so well has everything to do with your unfamiliarity with this new tool. PowerShell "thinks" in objects. PowerShell's answer to the question, "Can you get me some organizational units?" is a handful of OU's. Those objects have methods and properties. Perl pipes strings and .NET doesn't "pipe" per se. PowerShell pipes objects.

The output you received is a CLI-formatted table of object properties. You asked PowerShell to return names, so it returned objects containing the property of Name. To represent those objects conveniently in a CLI/text way, PowerShell generates a table with a label, a separator "-----", and rows of data by calling their toString() method.

"Foreach" does the magic because it lets you control the formatting, but you'll want to become comfortable with this thing of objects being emitted by functions. Direct manipulation of "the object" itself, rather than a string representation of it, is what makes PowerShell so powerful.

Body:
This really applies to almost any PS command but I'm running:

Get-ADOrganizationalUnit -LDAPFilter '(name=*)' -SearchBase $strDomainDN -SearchScope OneLevel

and the output looks like:

$_.Name
------
OU1
OU2
OU3
...

And all I want is the actual list with not heading ($_.Name or the "------").  I know this is probably amazingly simple but also very frustrating when trying to format strings.  Any help would be appreciated.


问:
LLVM C++ API create struct seg faults
I'm learning LLVM using the C++ API and am trying to figure out how to create structures and use them. The problem I'm running into is that when I try to allocate the structure, it seg faults.

```<code>    llvm::LLVMContext ctx;
    llvm::IRBuilder<> builder(ctx);
    std::unique_ptr<llvm::Module> module;

    std::vector<llvm::Type *> types;
    types.push_back(llvm::Type::getInt16Ty(ctx));

    auto structType = llvm::StructType::create(ctx, "Foo");
    structType->setBody(types);

    auto bb = llvm::BasicBlock::Create(ctx, "entry", nullptr);
    builder.SetInsertPoint(bb);

    builder.CreateAlloca(structType, nullptr, "alloctmp");
</code>```

I'm obviously missing something simple. Why does the CreateAlloca call seg fault?

After getting a debug version, it was seg faulting in the CreateAlloca code because BasicBlock was null. So, I added a BasicBlock and now it's seg faulting because GlobalValue is null. How should that get set?

答:
A couple important safety tips learned on this one.

A module must be created.

```<code>    std::unique_ptr<llvm::Module> module(new llvm::Module("mod", ctx));
</code>```

CreateAlloca allocates on the stack. Apparently there isn't one for top level stuff, so it has to be used within a function.

```<code>    auto ft = llvm::FunctionType::get(structType, types, false);
    auto fn = llvm::Function::Create(ft, llvm::Function::ExternalLinkage, "func", module.get());

    auto bb = llvm::BasicBlock::Create(ctx, "entry", fn);
</code>```

Title: LLVM C++ API create struct seg faults

Body:
I'm learning LLVM using the C++ API and am trying to figure out how to create structures and use them. The problem I'm running into is that when I try to allocate the structure, it seg faults.

    llvm::LLVMContext ctx;
    llvm::IRBuilder<> builder(ctx);
    std::unique_ptr<llvm::Module> module;

    std::vector<llvm::Type *> types;
    types.push_back(llvm::Type::getInt16Ty(ctx));

    auto structType = llvm::StructType::create(ctx, "Foo");
    structType->setBody(types);

    auto bb = llvm::BasicBlock::Create(ctx, "entry", nullptr);
    builder.SetInsertPoint(bb);

    builder.CreateAlloca(structType, nullptr, "alloctmp");

I'm obviously missing something simple. Why does the CreateAlloca call seg fault?

After getting a debug version, it was seg faulting in the CreateAlloca code because BasicBlock was null. So, I added a BasicBlock and now it's seg faulting because GlobalValue is null. How should that get set?

Body:
A couple important safety tips learned on this one.

A module must be created.

    std::unique_ptr<llvm::Module> module(new llvm::Module("mod", ctx));

CreateAlloca allocates on the stack. Apparently there isn't one for top level stuff, so it has to be used within a function.

    auto ft = llvm::FunctionType::get(structType, types, false);
    auto fn = llvm::Function::Create(ft, llvm::Function::ExternalLinkage, "func", module.get());

    auto bb = llvm::BasicBlock::Create(ctx, "entry", fn);


问:
How to play random Mp3 files in Pygame
hi everyone i'm currently working on a project and i'm stuck with this problem. how can i randomly play Mp3 from one folder using Pygame? here is my code.

path = "C:/Users/pc/Desktop/sample_songs/"
mixer.init()
mixer.music.load(path)
mixer.music.play()
```

答:
You can use os.listdir() to get a list of all files in a folder. Then use random.choice() to choose a random file.

If all files in the directory are MP3 files, you could use something like this:

import os
import random

path = "C:/Users/pc/Desktop/sample_songs/"
file = os.path.join(path, random.choice(os.listdir(path)))
mixer.init()
mixer.music.load(file)
mixer.music.play()
```

Title: How to play random Mp3 files in Pygame


答:
First you have to get a list of all the files which ends with '.mp3' in the directory (os.listdir, see os):

import os

path = "C:/Users/pc/Desktop/sample_songs/"
all_mp3 = [os.path.join(path, f) for f in os.listdir(path) if f.endswith('.mp3')]
```
<p>then select a random file from the list (<code>random.choice</code>, see <code>random</code>):</p>
<pre class="lang-py prettyprint-override"><code>import random

randomfile = random.choice(all_mp3)
</code>```

Play the random file:

import pygame

pygame.mixer.init()
pygame.mixer.music.load(randomfile)
pygame.mixer.music.play()
```
<hr />
<p>Minimal example:</p>
<pre class="lang-py prettyprint-override"><code>import os
import random
import pygame

directory = 'music'
play_list = [f for f in os.listdir(directory) if f.endswith('.mp3')]
print(play_list)
current_list = []

pygame.init()
window = pygame.display.set_mode((600, 100))
font = pygame.font.SysFont(None, 40)
clock = pygame.time.Clock()

window_center = window.get_rect().center
title_surf = None

run = True
while run:
    clock.tick(100)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    if not pygame.mixer.music.get_busy():
        if not current_list:
           current_list = play_list[:]
           random.shuffle(current_list)
        current_song = current_list.pop(0)
        pygame.mixer.music.load(os.path.join(directory, current_song))
        pygame.mixer.music.play()
        title_surf = font.render(current_song, True, (255, 255, 0))

    window.fill(0)
    if title_surf:
        window.blit(title_surf, title_surf.get_rect(center = window_center))
    pygame.display.flip()

pygame.quit()
exit()
</code>```

Title: How to play random Mp3 files in Pygame

Body:
hi everyone i'm currently working on a project and i'm stuck with this problem. how can i randomly play Mp3 from one folder using Pygame? here is my code.

path = "C:/Users/pc/Desktop/sample_songs/"
mixer.init()
mixer.music.load(path)
mixer.music.play()

Body:
First you have to get a list of all the files which ends with '.mp3' in the directory (os.listdir, see os):

import os

path = "C:/Users/pc/Desktop/sample_songs/"
all_mp3 = [os.path.join(path, f) for f in os.listdir(path) if f.endswith('.mp3')]

then select a random file from the list (random.choice, see random):

import random

randomfile = random.choice(all_mp3)

Play the random file:

import pygame

pygame.mixer.init()
pygame.mixer.music.load(randomfile)
pygame.mixer.music.play()

Minimal example:

import os
import random
import pygame

directory = 'music'
play_list = [f for f in os.listdir(directory) if f.endswith('.mp3')]
print(play_list)
current_list = []

pygame.init()
window = pygame.display.set_mode((600, 100))
font = pygame.font.SysFont(None, 40)
clock = pygame.time.Clock()

window_center = window.get_rect().center
title_surf = None

run = True
while run:
    clock.tick(100)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    if not pygame.mixer.music.get_busy():
        if not current_list:
           current_list = play_list[:]
           random.shuffle(current_list)
        current_song = current_list.pop(0)
        pygame.mixer.music.load(os.path.join(directory, current_song))
        pygame.mixer.music.play()
        title_surf = font.render(current_song, True, (255, 255, 0))

    window.fill(0)
    if title_surf:
        window.blit(title_surf, title_surf.get_rect(center = window_center))
    pygame.display.flip()

pygame.quit()
exit()


问:
Finding all paths in JUNG?
Hi I was wondering if there is any way to find all the possible paths between two nodes N1 and N2 in JUNG.
Thanks in advance for any help :) </p>

答:
I had some tasks in which i required all paths from vertex A to B.

Here, I took the ShortestPathDemo.java and modified it a bit to call it PathDemo.java. One can find both shortest and full path in a graph.

```<code>/******************************
        PathDemo.java
******************************/

    /*
 * Created on Jan 2, 2004
 */
package exasym;

import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Paint;
import java.awt.Stroke;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Point2D;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

import org.apache.commons.collections15.Transformer;

import edu.uci.ics.jung.algorithms.layout.FRLayout;
import edu.uci.ics.jung.algorithms.layout.Layout;
import edu.uci.ics.jung.algorithms.shortestpath.BFSDistanceLabeler;
import edu.uci.ics.jung.algorithms.shortestpath.DijkstraShortestPath;
import edu.uci.ics.jung.graph.DirectedSparseGraph;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.visualization.Layer;
import edu.uci.ics.jung.visualization.VisualizationViewer;
import edu.uci.ics.jung.visualization.control.DefaultModalGraphMouse;
import edu.uci.ics.jung.visualization.decorators.ToStringLabeller;
import edu.uci.ics.jung.visualization.renderers.Renderer;

/**
 * Demonstrates use of the shortest path algorithm and visualization of the
 * results.
 *
 * @author danyelf
 */
public class PathDemo extends JPanel {

    /**
     *
     */
    private static final long serialVersionUID = 7526217664458188502L;

    /**
     * Starting vertex
     */
    private String mFrom;

    /**
     * Ending vertex
     */
    private String mTo;
    private Graph<String, String> mGraph;
    private Set<String> mPred;

    private BFSDistanceLabeler<String, String> bdl;

    private Graph<String, String> path;

    protected boolean full = true;

    private JLabel label;

    public PathDemo() {

        this.mGraph = getGraph();
        setBackground(Color.WHITE);
        // show graph
        final Layout<String, String> layout = new FRLayout<String, String>(
                mGraph);
        final VisualizationViewer<String, String> vv = new VisualizationViewer<String, String>(
                layout);
        vv.setBackground(Color.WHITE);

        vv.getRenderContext().setVertexDrawPaintTransformer(
                new MyVertexDrawPaintFunction<String>());
        vv.getRenderContext().setVertexFillPaintTransformer(
                new MyVertexFillPaintFunction<String>());
        vv.getRenderContext().setEdgeDrawPaintTransformer(
                new MyEdgePaintFunction());
        vv.getRenderContext().setEdgeStrokeTransformer(
                new MyEdgeStrokeFunction());
        vv.getRenderContext().setVertexLabelTransformer(
                new ToStringLabeller<String>());
        vv.setGraphMouse(new DefaultModalGraphMouse<String, String>());
        vv.addPostRenderPaintable(new VisualizationViewer.Paintable() {

            public boolean useTransform() {
                return true;
            }

            public void paint(Graphics g) {
                if (mPred == null)
                    return;

                // for all edges, paint edges that are in shortest path
                for (String e : layout.getGraph().getEdges()) {

                    if (isBlessed(e)) {
                        String v1 = mGraph.getEndpoints(e).getFirst();
                        String v2 = mGraph.getEndpoints(e).getSecond();
                        Point2D p1 = layout.transform(v1);
                        Point2D p2 = layout.transform(v2);
                        p1 = vv.getRenderContext().getMultiLayerTransformer()
                                .transform(Layer.LAYOUT, p1);
                        p2 = vv.getRenderContext().getMultiLayerTransformer()
                                .transform(Layer.LAYOUT, p2);
                        Renderer<String, String> renderer = vv.getRenderer();
                        renderer.renderEdge(vv.getRenderContext(), layout, e);
                    }
                }
            }
        });

        setLayout(new BorderLayout());
        add(vv, BorderLayout.CENTER);
        // set up controls
        add(setUpControls(), BorderLayout.SOUTH);
    }

    boolean isBlessed(String e) {
        Iterator<String> it = path.getEdges().iterator();
        while (it.hasNext()) {
            String edge = it.next();
            if (edge.equalsIgnoreCase(e.toString()))
                return true;
        }
        return false;
    }

    /**
     * @author danyelf
     */
    public class MyEdgePaintFunction implements Transformer<String, Paint> {

        public Paint transform(String e) {
            if (path == null || path.getEdges().size() == 0)
                return Color.BLACK;
            if (isBlessed(e)) {
                return new Color(0.0f, 0.0f, 1.0f, 0.5f);// Color.BLUE;
            } else {
                return Color.LIGHT_GRAY;
            }
        }
    }

    public class MyEdgeStrokeFunction implements Transformer<String, Stroke> {
        protected final Stroke THIN = new BasicStroke(1);
        protected final Stroke THICK = new BasicStroke(2);

        public Stroke transform(String e) {
            if (path == null || path.getEdges().size() == 0)
                return THIN;
            if (isBlessed(e)) {
                return THICK;
            } else
                return THIN;
        }

    }

    /**
     * @author danyelf
     */
    public class MyVertexDrawPaintFunction<V> implements Transformer<V, Paint> {

        public Paint transform(V v) {
            return Color.black;
        }

    }

    public class MyVertexFillPaintFunction<String> implements
            Transformer<String, Paint> {

        public Paint transform(String v) {
            if (v.equals(mFrom)) {
                return Color.BLUE;
            }
            if (v.equals(mTo)) {
                return Color.BLUE;
            }
            if (path == null) {
                return Color.LIGHT_GRAY;
            } else {
                if (mGraph.getVertices().contains(v)) {
                    return Color.RED;
                } else {
                    return Color.LIGHT_GRAY;
                }
            }
        }

    }

    /**
     *
     */
    private JPanel setUpControls() {
        JPanel panel = new JPanel();
        panel.setBackground(Color.WHITE);
        panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
        panel.setBorder(BorderFactory.createLineBorder(Color.black, 3));
        label = new JLabel(
                "Select a pair of vertices for which all possible paths will be displayed");
        panel.add(label);
        JPanel jpPathType = new JPanel();
        jpPathType.add(new JLabel("Path type", SwingConstants.LEFT));
        jpPathType.add(getPathBox());

        JPanel jpFrom = new JPanel();
        jpFrom.add(new JLabel("vertex from", SwingConstants.LEFT));
        jpFrom.add(getSelectionBox(true));
        JPanel jpTo = new JPanel();
        jpTo.add(new JLabel("vertex to", SwingConstants.LEFT));
        jpTo.add(getSelectionBox(false));
        panel.add(jpPathType);
        panel.add(jpFrom);
        panel.add(jpTo);
        return panel;
    }

    public Component getPathBox() {
        Set<String> str = new HashSet<String>();
        str.add("Shortest");
        str.add("Full");
        final JComboBox path = new JComboBox(str.toArray());
        path.setSelectedItem("Full");
        path.setBackground(Color.WHITE);
        path.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                String option = (String) path.getSelectedItem();
                if (option.equals("Full")) {
                    full = true;
                    label.setText("Select a pair of vertices for which all possible paths will be displayed");
                } else {
                    full = false;
                    label.setText("Select a pair of vertices for which a shortest path will be displayed");
                }
                drawPath();
                repaint();
            }
        });
        return path;
    }

    protected void drawPath() {
        if (mFrom == null || mTo == null) {
            return;
        }
        path = getNewGraph();
        if (full) {
            path = getPaths();
        } else {
            path = drawShortest();
        }
    }

    private Component getSelectionBox(final boolean from) {

        Set<String> s = new TreeSet<String>();

        for (String v : mGraph.getVertices()) {
            s.add(v);
        }
        final JComboBox choices = new JComboBox(s.toArray());
        choices.setSelectedIndex(-1);
        choices.setBackground(Color.WHITE);
        choices.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                String v = (String) choices.getSelectedItem();

                if (from) {
                    mFrom = v;
                } else {
                    mTo = v;
                }
                drawPath();
                repaint();
            }
        });
        return choices;
    }

    /**
     * @return
     *
     */
    protected Graph<String, String> getPaths() {
        path = getNewGraph();

        Set<String> visited = new HashSet<String>();
        LinkedList<String> currpath = new LinkedList<String>();

        findAllPaths(mFrom, visited, path, currpath);

        return path;

    }

    private void findAllPaths(String start, Set<String> visited,
            Graph<String, String> path, LinkedList<String> currpath) {

        if (visited.contains(start)) {
            return;
        }

        visited.add(start);

        currpath.addLast(start);

        if (start.equals(mTo)) {

            String pred = null;

            for (String l : currpath) {
                if (pred != null) {
                    path.addVertex(l);
                    path.addVertex(pred);
                    path.addEdge((pred + l), pred, l);
                }
                pred = l;
            }
            currpath.removeLast();
            visited.remove(start);
            return;
        }

        for (String edge : mGraph.getOutEdges(start)) {
            String succ = mGraph.getDest(edge);
            findAllPaths(succ, visited, path, currpath);
        }

        visited.remove(start);
        currpath.removeLast();
    }

    protected Graph<String, String> drawShortest() {
        path = getNewGraph();
        LinkedList<String> currpath = new LinkedList<String>();
        DijkstraShortestPath<String, String> alg = new DijkstraShortestPath(
                mGraph);
        List<String> l = alg.getPath(mFrom, mTo);
        Iterator<String> itrCon = l.iterator();
        while (itrCon.hasNext()) {
            String c = (String) itrCon.next();
            String source = mGraph.getSource(c);
            String dest = mGraph.getDest(c);
            path.addEdge(source + dest, source, dest);
        }
        return path;
    }

    public static void main(String[] s) {
        JFrame jf = new JFrame();
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.getContentPane().add(new PathDemo());
        jf.pack();
        jf.setVisible(true);
    }

    /**
     * @return the graph for this demo
     */
    Graph<String, String> getGraph() {

        // Graph<V, E> where V is the type of the vertices and E is the type of
        // the edges
        Graph<String, String> g = new DirectedSparseGraph<String, String>();
        // Add some vertices. From above we defined these to be type Integer.
        g.addVertex("A");
        g.addVertex("B");
        g.addVertex("C");
        g.addVertex("D");
        // Note that the default is for undirected edges, our Edges are Strings.
        g.addEdge("AB", "A", "B"); // Note that Java 1.5 auto-boxes primitives
        g.addEdge("BC", "B", "C");
        g.addEdge("AC", "A", "C");
        g.addEdge("BA", "B", "A");
        g.addEdge("CB", "C", "B");
        g.addEdge("CA", "C", "A");
        g.addEdge("AD", "A", "D");
        g.addEdge("CD", "C", "D");

        /*
         * g.addEdge("AB", "A", "B", EdgeType.DIRECTED); // Note that Java 1.5
         * auto-boxes primitives g.addEdge("BC", "B", "C", EdgeType.DIRECTED);
         * g.addEdge("AC", "A", "C", EdgeType.DIRECTED);
         */

        return g;
    }

    Graph<String, String> getNewGraph() {
        return new DirectedSparseGraph<String, String>();
    }
}
</code>```

Title: Finding all paths in JUNG?

Body:
I had some tasks in which i required all paths from vertex A to B.

Here, I took the ShortestPathDemo.java and modified it a bit to call it PathDemo.java. One can find both shortest and full path in a graph.

/******************************
        PathDemo.java
******************************/

    /*
 * Created on Jan 2, 2004
 */
package exasym;

import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Paint;
import java.awt.Stroke;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Point2D;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

import org.apache.commons.collections15.Transformer;

import edu.uci.ics.jung.algorithms.layout.FRLayout;
import edu.uci.ics.jung.algorithms.layout.Layout;
import edu.uci.ics.jung.algorithms.shortestpath.BFSDistanceLabeler;
import edu.uci.ics.jung.algorithms.shortestpath.DijkstraShortestPath;
import edu.uci.ics.jung.graph.DirectedSparseGraph;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.visualization.Layer;
import edu.uci.ics.jung.visualization.VisualizationViewer;
import edu.uci.ics.jung.visualization.control.DefaultModalGraphMouse;
import edu.uci.ics.jung.visualization.decorators.ToStringLabeller;
import edu.uci.ics.jung.visualization.renderers.Renderer;

/**
 * Demonstrates use of the shortest path algorithm and visualization of the
 * results.
 *
 * @author danyelf
 */
public class PathDemo extends JPanel {

    /**
     *
     */
    private static final long serialVersionUID = 7526217664458188502L;

    /**
     * Starting vertex
     */
    private String mFrom;

    /**
     * Ending vertex
     */
    private String mTo;
    private Graph<String, String> mGraph;
    private Set<String> mPred;

    private BFSDistanceLabeler<String, String> bdl;

    private Graph<String, String> path;

    protected boolean full = true;

    private JLabel label;

    public PathDemo() {

        this.mGraph = getGraph();
        setBackground(Color.WHITE);
        // show graph
        final Layout<String, String> layout = new FRLayout<String, String>(
                mGraph);
        final VisualizationViewer<String, String> vv = new VisualizationViewer<String, String>(
                layout);
        vv.setBackground(Color.WHITE);

        vv.getRenderContext().setVertexDrawPaintTransformer(
                new MyVertexDrawPaintFunction<String>());
        vv.getRenderContext().setVertexFillPaintTransformer(
                new MyVertexFillPaintFunction<String>());
        vv.getRenderContext().setEdgeDrawPaintTransformer(
                new MyEdgePaintFunction());
        vv.getRenderContext().setEdgeStrokeTransformer(
                new MyEdgeStrokeFunction());
        vv.getRenderContext().setVertexLabelTransformer(
                new ToStringLabeller<String>());
        vv.setGraphMouse(new DefaultModalGraphMouse<String, String>());
        vv.addPostRenderPaintable(new VisualizationViewer.Paintable() {

            public boolean useTransform() {
                return true;
            }

            public void paint(Graphics g) {
                if (mPred == null)
                    return;

                // for all edges, paint edges that are in shortest path
                for (String e : layout.getGraph().getEdges()) {

                    if (isBlessed(e)) {
                        String v1 = mGraph.getEndpoints(e).getFirst();
                        String v2 = mGraph.getEndpoints(e).getSecond();
                        Point2D p1 = layout.transform(v1);
                        Point2D p2 = layout.transform(v2);
                        p1 = vv.getRenderContext().getMultiLayerTransformer()
                                .transform(Layer.LAYOUT, p1);
                        p2 = vv.getRenderContext().getMultiLayerTransformer()
                                .transform(Layer.LAYOUT, p2);
                        Renderer<String, String> renderer = vv.getRenderer();
                        renderer.renderEdge(vv.getRenderContext(), layout, e);
                    }
                }
            }
        });

        setLayout(new BorderLayout());
        add(vv, BorderLayout.CENTER);
        // set up controls
        add(setUpControls(), BorderLayout.SOUTH);
    }

    boolean isBlessed(String e) {
        Iterator<String> it = path.getEdges().iterator();
        while (it.hasNext()) {
            String edge = it.next();
            if (edge.equalsIgnoreCase(e.toString()))
                return true;
        }
        return false;
    }

    /**
     * @author danyelf
     */
    public class MyEdgePaintFunction implements Transformer<String, Paint> {

        public Paint transform(String e) {
            if (path == null || path.getEdges().size() == 0)
                return Color.BLACK;
            if (isBlessed(e)) {
                return new Color(0.0f, 0.0f, 1.0f, 0.5f);// Color.BLUE;
            } else {
                return Color.LIGHT_GRAY;
            }
        }
    }

    public class MyEdgeStrokeFunction implements Transformer<String, Stroke> {
        protected final Stroke THIN = new BasicStroke(1);
        protected final Stroke THICK = new BasicStroke(2);

        public Stroke transform(String e) {
            if (path == null || path.getEdges().size() == 0)
                return THIN;
            if (isBlessed(e)) {
                return THICK;
            } else
                return THIN;
        }

    }

    /**
     * @author danyelf
     */
    public class MyVertexDrawPaintFunction<V> implements Transformer<V, Paint> {

        public Paint transform(V v) {
            return Color.black;
        }

    }

    public class MyVertexFillPaintFunction<String> implements
            Transformer<String, Paint> {

        public Paint transform(String v) {
            if (v.equals(mFrom)) {
                return Color.BLUE;
            }
            if (v.equals(mTo)) {
                return Color.BLUE;
            }
            if (path == null) {
                return Color.LIGHT_GRAY;
            } else {
                if (mGraph.getVertices().contains(v)) {
                    return Color.RED;
                } else {
                    return Color.LIGHT_GRAY;
                }
            }
        }

    }

    /**
     *
     */
    private JPanel setUpControls() {
        JPanel panel = new JPanel();
        panel.setBackground(Color.WHITE);
        panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
        panel.setBorder(BorderFactory.createLineBorder(Color.black, 3));
        label = new JLabel(
                "Select a pair of vertices for which all possible paths will be displayed");
        panel.add(label);
        JPanel jpPathType = new JPanel();
        jpPathType.add(new JLabel("Path type", SwingConstants.LEFT));
        jpPathType.add(getPathBox());

        JPanel jpFrom = new JPanel();
        jpFrom.add(new JLabel("vertex from", SwingConstants.LEFT));
        jpFrom.add(getSelectionBox(true));
        JPanel jpTo = new JPanel();
        jpTo.add(new JLabel("vertex to", SwingConstants.LEFT));
        jpTo.add(getSelectionBox(false));
        panel.add(jpPathType);
        panel.add(jpFrom);
        panel.add(jpTo);
        return panel;
    }

    public Component getPathBox() {
        Set<String> str = new HashSet<String>();
        str.add("Shortest");
        str.add("Full");
        final JComboBox path = new JComboBox(str.toArray());
        path.setSelectedItem("Full");
        path.setBackground(Color.WHITE);
        path.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                String option = (String) path.getSelectedItem();
                if (option.equals("Full")) {
                    full = true;
                    label.setText("Select a pair of vertices for which all possible paths will be displayed");
                } else {
                    full = false;
                    label.setText("Select a pair of vertices for which a shortest path will be displayed");
                }
                drawPath();
                repaint();
            }
        });
        return path;
    }

    protected void drawPath() {
        if (mFrom == null || mTo == null) {
            return;
        }
        path = getNewGraph();
        if (full) {
            path = getPaths();
        } else {
            path = drawShortest();
        }
    }

    private Component getSelectionBox(final boolean from) {

        Set<String> s = new TreeSet<String>();

        for (String v : mGraph.getVertices()) {
            s.add(v);
        }
        final JComboBox choices = new JComboBox(s.toArray());
        choices.setSelectedIndex(-1);
        choices.setBackground(Color.WHITE);
        choices.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                String v = (String) choices.getSelectedItem();

                if (from) {
                    mFrom = v;
                } else {
                    mTo = v;
                }
                drawPath();
                repaint();
            }
        });
        return choices;
    }

    /**
     * @return
     *
     */
    protected Graph<String, String> getPaths() {
        path = getNewGraph();

        Set<String> visited = new HashSet<String>();
        LinkedList<String> currpath = new LinkedList<String>();

        findAllPaths(mFrom, visited, path, currpath);

        return path;

    }

    private void findAllPaths(String start, Set<String> visited,
            Graph<String, String> path, LinkedList<String> currpath) {

        if (visited.contains(start)) {
            return;
        }

        visited.add(start);

        currpath.addLast(start);

        if (start.equals(mTo)) {

            String pred = null;

            for (String l : currpath) {
                if (pred != null) {
                    path.addVertex(l);
                    path.addVertex(pred);
                    path.addEdge((pred + l), pred, l);
                }
                pred = l;
            }
            currpath.removeLast();
            visited.remove(start);
            return;
        }

        for (String edge : mGraph.getOutEdges(start)) {
            String succ = mGraph.getDest(edge);
            findAllPaths(succ, visited, path, currpath);
        }

        visited.remove(start);
        currpath.removeLast();
    }

    protected Graph<String, String> drawShortest() {
        path = getNewGraph();
        LinkedList<String> currpath = new LinkedList<String>();
        DijkstraShortestPath<String, String> alg = new DijkstraShortestPath(
                mGraph);
        List<String> l = alg.getPath(mFrom, mTo);
        Iterator<String> itrCon = l.iterator();
        while (itrCon.hasNext()) {
            String c = (String) itrCon.next();
            String source = mGraph.getSource(c);
            String dest = mGraph.getDest(c);
            path.addEdge(source + dest, source, dest);
        }
        return path;
    }

    public static void main(String[] s) {
        JFrame jf = new JFrame();
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.getContentPane().add(new PathDemo());
        jf.pack();
        jf.setVisible(true);
    }

    /**
     * @return the graph for this demo
     */
    Graph<String, String> getGraph() {

        // Graph<V, E> where V is the type of the vertices and E is the type of
        // the edges
        Graph<String, String> g = new DirectedSparseGraph<String, String>();
        // Add some vertices. From above we defined these to be type Integer.
        g.addVertex("A");
        g.addVertex("B");
        g.addVertex("C");
        g.addVertex("D");
        // Note that the default is for undirected edges, our Edges are Strings.
        g.addEdge("AB", "A", "B"); // Note that Java 1.5 auto-boxes primitives
        g.addEdge("BC", "B", "C");
        g.addEdge("AC", "A", "C");
        g.addEdge("BA", "B", "A");
        g.addEdge("CB", "C", "B");
        g.addEdge("CA", "C", "A");
        g.addEdge("AD", "A", "D");
        g.addEdge("CD", "C", "D");

        /*
         * g.addEdge("AB", "A", "B", EdgeType.DIRECTED); // Note that Java 1.5
         * auto-boxes primitives g.addEdge("BC", "B", "C", EdgeType.DIRECTED);
         * g.addEdge("AC", "A", "C", EdgeType.DIRECTED);
         */

        return g;
    }

    Graph<String, String> getNewGraph() {
        return new DirectedSparseGraph<String, String>();
    }
}


问:
Convert a single data frame into list of data frames (parsing column names into prefixes and suffixes)
I am hoping to determine an efficient way to convert a single data frame into a list of data frames. Below is my reproducible MWE:

```<code>set.seed(1)
ABAge = runif(100)
ABPoints = rnorm(100)
ACAge = runif(100)
ACPoints = rnorm(100)
BCAge = runif(100)
BCPoints = rnorm(100)

A_B <- data.frame(ID = as.character(paste0("ID", 1:100)), Age = ABAge, Points = ABPoints)
A_C <- data.frame(ID = as.character(paste0("ID", 1:100)), Age = ACAge, Points = ACPoints)
B_C <- data.frame(ID = as.character(paste0("ID", 1:100)), Age = BCAge, Points = BCPoints)
A_B$ID <- as.character(A_B$ID)
A_C$ID <- as.character(A_C$ID)
B_C$ID <- as.character(B_C$ID)

listFormat <- list("A_B" = A_B, "A_C" = A_C, "B_C" = B_C)

dfFormat <- data.frame(ID = as.character(paste0("ID", 1:100)), A_B.Age = ABAge, A_B.Points = ABPoints, A_C.Age = ACAge, A_C.Points = ACPoints, B_C.Age = BCAge, B_C.Points = BCPoints)
dfFormat$ID = as.character(dfFormat$ID)
</code>```

This results in a data frame format (dfFormat) that looks like this:

```<code>'data.frame':   100 obs. of  7 variables:
 $ ID        : chr  "ID1" "ID2" "ID3" "ID4" ...
 $ A_B.Age   : num  0.266 0.372 0.573 0.908 0.202 ...
 $ A_B.Points: num  0.398 -0.612 0.341 -1.129 1.433 ...
 $ A_C.Age   : num  0.6737 0.0949 0.4926 0.4616 0.3752 ...
 $ A_C.Points: num  0.409 1.689 1.587 -0.331 -2.285 ...
 $ B_C.Age   : num  0.814 0.929 0.147 0.75 0.976 ...
 $ B_C.Points: num  1.474 0.677 0.38 -0.193 1.578 ...
</code>```

and a list of data frames listFormat that looks like this:

```<code>List of 3
 $ A_B:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.266 0.372 0.573 0.908 0.202 ...
  ..$ Points: num [1:100] 0.398 -0.612 0.341 -1.129 1.433 ...
 $ A_C:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.6737 0.0949 0.4926 0.4616 0.3752 ...
  ..$ Points: num [1:100] 0.409 1.689 1.587 -0.331 -2.285 ...
 $ B_C:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.814 0.929 0.147 0.75 0.976 ...
  ..$ Points: num [1:100] 1.474 0.677 0.38 -0.193 1.578 ...
</code>```

I am hoping to come up with an automated way to convert the dfFormat to listFormat. As can be seen in the above objects there are two main conditions:

The column ID is always the first column in dfFormat and it is always the first column in each sublist of listFormat.

The number of sublists is equal to the number of unique column names in dfFormat before the underscore ('_'). In this case, that is three prefixes (ex. "A_B", "A_C", and "B_C"). These prefixes are also the names of the three sublists.

Within each sublist, it contains the number of columns that had the associated prefix ("A_B"). For each sublist, this was two ("Age" and "Points"). These suffixes are the names of the columns.

I asked the reverse question here (i.e. how to go from listFormat to dfFormat) and got some helpful answers that I am learning from. I need to have code to reverse both directions and it seems the reverse direction may need new types of code. I put my attempt below to show how I am stuck!

```<code>conUnd <- which(sapply(colnames(dfFormat), function(x) grepl("_", x)))
listName <- sapply(colnames(dfFormat[,conUnd]), function(x) strsplit(x, "[.]")[[1]][1])
uListName <- unique(sapply(colnames(dfFormat[,conUnd]), function(x) strsplit(x, "[.]")[[1]][1]))
listCol <- sapply(colnames(dfFormat[,conUnd]), function(x) strsplit(x, "[.]")[[1]][2])

listFormat = list()
for (i in 1:length(uListName)){
   [Gets messy here trying to define column names based on string variables]
}
</code>```

Any advice would be greatly appreciated. I know my code is not efficient.

Body:
I am hoping to determine an efficient way to convert a single data frame into a list of data frames. Below is my reproducible MWE:

set.seed(1)
ABAge = runif(100)
ABPoints = rnorm(100)
ACAge = runif(100)
ACPoints = rnorm(100)
BCAge = runif(100)
BCPoints = rnorm(100)

A_B <- data.frame(ID = as.character(paste0("ID", 1:100)), Age = ABAge, Points = ABPoints)
A_C <- data.frame(ID = as.character(paste0("ID", 1:100)), Age = ACAge, Points = ACPoints)
B_C <- data.frame(ID = as.character(paste0("ID", 1:100)), Age = BCAge, Points = BCPoints)
A_B$ID <- as.character(A_B$ID)
A_C$ID <- as.character(A_C$ID)
B_C$ID <- as.character(B_C$ID)

listFormat <- list("A_B" = A_B, "A_C" = A_C, "B_C" = B_C)

dfFormat <- data.frame(ID = as.character(paste0("ID", 1:100)), A_B.Age = ABAge, A_B.Points = ABPoints, A_C.Age = ACAge, A_C.Points = ACPoints, B_C.Age = BCAge, B_C.Points = BCPoints)
dfFormat$ID = as.character(dfFormat$ID)

This results in a data frame format (dfFormat) that looks like this:

'data.frame':   100 obs. of  7 variables:
 $ ID        : chr  "ID1" "ID2" "ID3" "ID4" ...
 $ A_B.Age   : num  0.266 0.372 0.573 0.908 0.202 ...
 $ A_B.Points: num  0.398 -0.612 0.341 -1.129 1.433 ...
 $ A_C.Age   : num  0.6737 0.0949 0.4926 0.4616 0.3752 ...
 $ A_C.Points: num  0.409 1.689 1.587 -0.331 -2.285 ...
 $ B_C.Age   : num  0.814 0.929 0.147 0.75 0.976 ...
 $ B_C.Points: num  1.474 0.677 0.38 -0.193 1.578 ...

and a list of data frames listFormat that looks like this:

List of 3
 $ A_B:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.266 0.372 0.573 0.908 0.202 ...
  ..$ Points: num [1:100] 0.398 -0.612 0.341 -1.129 1.433 ...
 $ A_C:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.6737 0.0949 0.4926 0.4616 0.3752 ...
  ..$ Points: num [1:100] 0.409 1.689 1.587 -0.331 -2.285 ...
 $ B_C:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.814 0.929 0.147 0.75 0.976 ...
  ..$ Points: num [1:100] 1.474 0.677 0.38 -0.193 1.578 ...

I am hoping to come up with an automated way to convert the dfFormat to listFormat. As can be seen in the above objects there are two main conditions:

The column ID is always the first column in dfFormat and it is always the first column in each sublist of listFormat.

The number of sublists is equal to the number of unique column names in dfFormat before the underscore ('_'). In this case, that is three prefixes (ex. "A_B", "A_C", and "B_C"). These prefixes are also the names of the three sublists.

Within each sublist, it contains the number of columns that had the associated prefix ("A_B"). For each sublist, this was two ("Age" and "Points"). These suffixes are the names of the columns.

I asked the reverse question here (i.e. how to go from listFormat to dfFormat) and got some helpful answers that I am learning from. I need to have code to reverse both directions and it seems the reverse direction may need new types of code. I put my attempt below to show how I am stuck!

conUnd <- which(sapply(colnames(dfFormat), function(x) grepl("_", x)))
listName <- sapply(colnames(dfFormat[,conUnd]), function(x) strsplit(x, "[.]")[[1]][1])
uListName <- unique(sapply(colnames(dfFormat[,conUnd]), function(x) strsplit(x, "[.]")[[1]][1]))
listCol <- sapply(colnames(dfFormat[,conUnd]), function(x) strsplit(x, "[.]")[[1]][2])

listFormat = list()
for (i in 1:length(uListName)){
   [Gets messy here trying to define column names based on string variables]
}

Any advice would be greatly appreciated. I know my code is not efficient.

Body:
Using mget, ls, and regular expression seems to get what you want.

DATA:

Edit:
Your dataframe dfFormat, which has this structure:

str(dfFormat)
'data.frame':   100 obs. of  7 variables:
 $ ID        : chr  "ID1" "ID2" "ID3" "ID4" ...
 $ A_B.Age   : num  0.266 0.372 0.573 0.908 0.202 ...
 $ A_B.Points: num  0.398 -0.612 0.341 -1.129 1.433 ...
 $ A_C.Age   : num  0.6737 0.0949 0.4926 0.4616 0.3752 ...
 $ A_C.Points: num  0.409 1.689 1.587 -0.331 -2.285 ...
 $ B_C.Age   : num  0.814 0.929 0.147 0.75 0.976 ...
 $ B_C.Points: num  1.474 0.677 0.38 -0.193 1.578 ...

SOLUTION:

The solution picks up on the column names in dfFormat, matching the columns by which you want to convert the dataframe into a list of dataframes using regex:

listFormat <-  mget(ls(pattern = "^A_B|^A_C|^B_C"))

RESULT:

str(listFormat)
List of 3
 $ A_B:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.266 0.372 0.573 0.908 0.202 ...
  ..$ Points: num [1:100] 0.398 -0.612 0.341 -1.129 1.433 ...
 $ A_C:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.6737 0.0949 0.4926 0.4616 0.3752 ...
  ..$ Points: num [1:100] 0.409 1.689 1.587 -0.331 -2.285 ...
 $ B_C:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.814 0.929 0.147 0.75 0.976 ...
  ..$ Points: num [1:100] 1.474 0.677 0.38 -0.193 1.578 ...


问:
How can I check if a process was started by Visual Studio > 2015
In Visual Studio 2015 it was possible to check whether a running application had been started from Visual Studio by checking if a debugger is active and if the process was vshost.exe like this:

```<code>bool isInVisualStudio = Debugger.IsAttached && AppDomain.CurrentDomain.FriendlyName.EndsWith("vshost.exe");
</code>```

Since Visual Studio 2017 this is no longer possible as the current domain is always the application executable name regardless of how it was started.

I have been trying without success to do the same thing in VS2019.  The closest I can get is to check if a debugger is attached and if Visual Studio is running at the same time:

```<code>bool devEnvIsRunning = Process.GetProcessesByName("devenv").Length > 0;
bool isInVisualStudio = Debugger.IsAttached && devEnvIsRunning;
</code>```

The problem with this for my purposes is that I want to skip some code when it is running from source in my copy of VS on my machine, but I definitely do NOT want to skip that code just because another debugger is installed.

I have been trying to find a way to get the name of the attached debugger which would solve the problem, but have been unable to do so.

Anyone got any suggestions on how to achieve in VS2019 that which was so easy in VS2015 and earlier?

答:
I think the easiest ways for you to achieve this is with Command line arguments or environment variables.

Command line arguments can be configured in the project's debug tab in the project properties, and then you can check to see what arguments have been passed through by checking Environment. GetCommandLineArgs for any values you may be expecting. You can do that at any time and you should be good.

If setting a command line variable isn't what you want to do, using an environment variable can also work. The basic idea is the same, you can configure environment variables in the debug tab (some projects have VS specific variables by default) and check for them. I'm not sure exactly how to do that one from memory and I'm typing on mobile at the moment, but one of those options should cover you.

I personally would go for the command line arguments option. It allows you to skip whatever task it is you want to skip whenever, not just when VS launching the program.

Body:
In Visual Studio 2015 it was possible to check whether a running application had been started from Visual Studio by checking if a debugger is active and if the process was vshost.exe like this:

bool isInVisualStudio = Debugger.IsAttached && AppDomain.CurrentDomain.FriendlyName.EndsWith("vshost.exe");

Since Visual Studio 2017 this is no longer possible as the current domain is always the application executable name regardless of how it was started.

I have been trying without success to do the same thing in VS2019.  The closest I can get is to check if a debugger is attached and if Visual Studio is running at the same time:

bool devEnvIsRunning = Process.GetProcessesByName("devenv").Length > 0;
bool isInVisualStudio = Debugger.IsAttached && devEnvIsRunning;

The problem with this for my purposes is that I want to skip some code when it is running from source in my copy of VS on my machine, but I definitely do NOT want to skip that code just because another debugger is installed.

I have been trying to find a way to get the name of the attached debugger which would solve the problem, but have been unable to do so.

Anyone got any suggestions on how to achieve in VS2019 that which was so easy in VS2015 and earlier?


问:
Handle multiple registers with Vue and API endpoint
I have an application with clients stored in a database, the quantity of clients is variable, currently I have 2 hundreds but I could have 2 million. Also I have a web service that queries this database and exposes an endpoint. To display those clients I have a simple Vue application that shows a form filled with one client at time and next and previous buttons to get more clients.

The point is, what is the best approach to get clients from my database to Vue:

Should I get all clients from database and store them in vuex? With this options, next and prev buttons just take one or other index from stored array.

Should I just get the current client I'm displaying and store it in vuex? With this options, next and prev buttons call the endpoint requesting the next or prev client.

Maybe should make a chunk loading and store n clients in vuex? With this option, next and prev buttons search the client in the array, if the index is out of bounds should call the endpoint requesting the n next or previous clients and will store them in the vuex array.

Thanks

答:
Chunk loading would be an ideal situation where users need not for wait for client load to complete on click of 'next' to view the next client and also not bloating the browser storage with a large number of unused client details.

A slightly modified chunk loading approach would be to always fetch the next and previous client details when loading particular client details so that users need not wait for network call to complete when going to the next client.

eg when fetching client 2 - fetch 1,3.
when user clicks next directly render 3rd client details from the store but fetch client 4 in the background so that next and previous click is smooth.


问:
A script that reads and outputs in a list in which rows it was used
I'm using a .py file with "some text", then using my code to produce a dictionary of how many times a word is being used in the text.

```<code>{}
for x in text:

        x = x.lower()

</code>```

However, I'm looking for a way to execute a list on which rows the element (i.e. x, words, isalpha, and more) is used, I do not want to include for or if etc.
To print out the script above, I use

```<code>filename = 'test.py'

        print(n, line, end='')
</code>```

This is what I want in the final output:

```<code>1
2 words = {}
          words[x] += 1

10 print(words)

x
words         ]

lower        [3]
</code>```

I'm assuming I could use re Module, however, I would appreciate tips

答:
If I have clearly understand what you want to perform, you can use the following code:

import re
from keyword import kwlist

i = 1
map = {}
with open("script.py", "r") as file:
    while True:
        line = file.readline()
        if not line: break

        # iterates over each real word on each line
        for x in re.split(r'[^\w]', line):
            # adds the world to the map only if it is not '', nor a number, nor a python keyword
            if x and not x.isdigit() and x not in kwlist:
                if not x in map: map[x] = [i]
                else: map[x].append(i)
        i += 1

# displays the map
for key in map:
    print(key, map[key], sep='\t\t')
```

<p>This will produce :</p>

```words       [2, 6, 7, 9, 10]
x           [3, 4, 5, 5, 6, 7, 9]
text        [3]
isalpha     [4]
lower       [5]
print       [10]
```

Body:
I'm using a .py file with "some text", then using my code to produce a dictionary of how many times a word is being used in the text.

{}
for x in text:

        x = x.lower()

However, I'm looking for a way to execute a list on which rows the element (i.e. x, words, isalpha, and more) is used, I do not want to include for or if etc.
To print out the script above, I use

filename = 'test.py'

        print(n, line, end='')

This is what I want in the final output:

1
2 words = {}
          words[x] += 1

10 print(words)

x
words         ]

lower        [3]

I'm assuming I could use re Module, however, I would appreciate tips

Body:
If I have clearly understand what you want to perform, you can use the following code:

import re
from keyword import kwlist

i = 1
map = {}
with open("script.py", "r") as file:
    while True:
        line = file.readline()
        if not line: break

        # iterates over each real word on each line
        for x in re.split(r'[^\w]', line):
            # adds the world to the map only if it is not '', nor a number, nor a python keyword
            if x and not x.isdigit() and x not in kwlist:
                if not x in map: map[x] = [i]
                else: map[x].append(i)
        i += 1

# displays the map
for key in map:
    print(key, map[key], sep='\t\t')

This will produce :

words       [2, 6, 7, 9, 10]
x           [3, 4, 5, 5, 6, 7, 9]
text        [3]
isalpha     [4]
lower       [5]
print       [10]


问:
Distinguish between one-, two- and three-word commands
Right now, I am using this method to check if the user just typed in a command with wrong arguments:

```<code>    private boolean relatedCommand(String input) {
        // make sure the split afterwards has at least size one
        if (input.matches(" .*")) {
            return false;
        }
        final String command = input.split(" ".toString())[0];
        return COMMAND_PACKAGE
                .keySet()
                .stream()
                .map(Pattern::toString)
                .anyMatch(patternText -> patternText.startsWith(command + " ");
    }
</code>```

(COMMAND_PACKAGE contains all registered commands)

Now, this works perfectly fine for one-word commands. E. g. get <argument1> <argument2>, remove <argument1>.

However, I am currently working on a project that has both one-word and two-word commands.
Here is a range of commands that doesn't really work with this method:
add track <argument1>, add switch <argument1>, step <argument>. In this case, for the command add track <argument1>, "track" is seen as an argument but it really belongs to the command itself.

If the use just types in "add" the error message is "invalid arguments". Instead, the error message should be more precise and tell him that this command doesn't exist (as there is only "add track" or "add switch").

Does anyone have any idea how to distinguish between one-word and two-word commands? The user can also use the command delete rolling stock <argument> which consists of a three-word command.

All in all, it is therefore necessary to differentiate between commands of one, two and three words.

答:
The method String.split("\s+") splits your input at whitespaces into an array. You can query the length of that arrays, then you know how many words your input contained.

```<code>import java.util.Arrays;
import java.util.Scanner;

class Main
{
    public static void main(String[] args)
    {
        System.out.println("Enter a command");
        Scanner in=new Scanner(System.in);
        String command=in.nextLine();
        String[] parts=command.split("\\s+");
        System.out.println("parts="+Arrays.toString(parts));
        if (parts.length==0)
        {
            System.out.println("Zero parts");
        }
        else if (parts.length==1)
        {
            System.out.println("One part");
        }
        else if (parts.length==2)
        {
            System.out.println("Two parts");
        }
        else if (parts.length==3)
        {
            System.out.println("Three parts");
        }
        else
        {
            System.out.println("More than three parts");
        }
    }
}
</code>```

Outputs:

```<code>Enter a command
a b c
parts=[a, b, c]
Three parts
</code>```

Process finished with exit code 0

Body:
Right now, I am using this method to check if the user just typed in a command with wrong arguments:

    private boolean relatedCommand(String input) {
        // make sure the split afterwards has at least size one
        if (input.matches(" .*")) {
            return false;
        }
        final String command = input.split(" ".toString())[0];
        return COMMAND_PACKAGE
                .keySet()
                .stream()
                .map(Pattern::toString)
                .anyMatch(patternText -> patternText.startsWith(command + " ");
    }

(COMMAND_PACKAGE contains all registered commands)

Now, this works perfectly fine for one-word commands. E. g. get <argument1> <argument2>, remove <argument1>.

However, I am currently working on a project that has both one-word and two-word commands.
Here is a range of commands that doesn't really work with this method:
add track <argument1>, add switch <argument1>, step <argument>. In this case, for the command add track <argument1>, "track" is seen as an argument but it really belongs to the command itself.

If the use just types in "add" the error message is "invalid arguments". Instead, the error message should be more precise and tell him that this command doesn't exist (as there is only "add track" or "add switch").

Does anyone have any idea how to distinguish between one-word and two-word commands? The user can also use the command delete rolling stock <argument> which consists of a three-word command.

All in all, it is therefore necessary to differentiate between commands of one, two and three words.

Body:
The method String.split("\s+") splits your input at whitespaces into an array. You can query the length of that arrays, then you know how many words your input contained.

import java.util.Arrays;
import java.util.Scanner;

class Main
{
    public static void main(String[] args)
    {
        System.out.println("Enter a command");
        Scanner in=new Scanner(System.in);
        String command=in.nextLine();
        String[] parts=command.split("\\s+");
        System.out.println("parts="+Arrays.toString(parts));
        if (parts.length==0)
        {
            System.out.println("Zero parts");
        }
        else if (parts.length==1)
        {
            System.out.println("One part");
        }
        else if (parts.length==2)
        {
            System.out.println("Two parts");
        }
        else if (parts.length==3)
        {
            System.out.println("Three parts");
        }
        else
        {
            System.out.println("More than three parts");
        }
    }
}

Outputs:

Enter a command
a b c
parts=[a, b, c]
Three parts

Process finished with exit code 0


问:
How does the WMD editor like the one StackOverFlow uses work?
I'm interested in knowing how does the text you type on the text box doesn't require a page refresh?
Some similar alternatives include:

lixlpixel

But they tend to do a page refresh every time a keystroke is pressed...

答:
They have a Markdown to HTML translator implemented in Javascript. Whenever the content of the 'textarea' changes the preview area is updated with the result of running the Markdown to HTML converter. There's obviously more to it than that -- making this sort of thing perform well can be tricky -- but that's the essence of it.

If you inspect the textarea in a browser like Safari you can see that they are using Javascript event handlers for drop, input, keydown, keypress, keyup, mousedown and paste events. When one of these events happen the script responds appropriately, including to run the Javacript Markdown-to-HTML converter and putting the resulting HTML into the preview area.


问:
FormArray return null?
Greeting. I've tried multiple ways, but none of them work. I'm on this, right now. I need to initiate a formArray of emails

```<code>email: [testestest]
</code>```

But I got:

```<code>email: [testestest]
</code>```

But my email return  n click. Check my ts

And my html:

答:
Alex, you has an Form Array of FormControls, not an Form Array of formGroups. So you .html must be like

```<code><form *ngIf="addForm" [formGroup]="addForm">
    <div class="form-control-row" formArrayName="email"
        *ngFor="let item of addForm.get('email').controls; let i = index;">
        <div class="input-box">
            <input type="text" placeholder="E - mail" [formControlName]="i">
            <img src="../../assets/Delete.svg" alt="x-icon">
      </div>
        </div>
</form>
</code>```

See that you has no [fomGroupName]="i", and you use [formControlName]="i"

Other way is

```<code><form *ngIf="addForm" [formGroup]="addForm">
    <div class="form-control-row" formArrayName="email"
        *ngFor="let item of addForm.get('email').controls; let i = index;">
        <div class="input-box">
            <input type="text" placeholder="E - mail" [formControl]="item">
            <img src="../../assets/Delete.svg" alt="x-icon">
      </div>
        </div>
</form>
</code>```

See that in this case we use [formControl]="item" (item is the variable you use in the
*ngFor)

Well, how you create the formArray?

If you has an array of emails you can do

```<code>    email:  this.formBuilder.array(
             this.email.map(x=>this.formBuilder.control(x))
          )
</code>```

That's you create an array of FormControls using map (transform each element of the array in a FormControl who value the element of the array.

NOTE: In production you need create a getter for the array

```<code>get emails()
{
    return this.form.get('email') as FormArray;
}
</code>```

And iterate over

```<code>    *ngFor="let item of emails.controls; let i = index;">
</code>```

The use of [formGroupName]="i" and formControl it's used with a FormArray of FormGroups. e.g. you can has

```<code>    email:  this.formBuilder.array(
             this.email.map(x=>this.formBuilder.group({email:x}))
          )
</code>```

See that in this case transform each element of the array in a formGroup that has a FormControl "called" email

You can see all this in this stackblitz. I hope the example help you understand the diference

If we want to add an element to the formArray we can make a function

```<code>  addEmail(email:any)
  {
    const array=this.addForm.get('email') as FormArray
    array.push(this.formBuilder.control(email)) //if is a FormArray of FormControl

    const array2=this.addForm.get('email2') as FormArray
    array2.push(this.formBuilder.group({email:email})) //if is a FormArray of FormGroup
  }
</code>```

NOTE: At first, if we want to create a empty formArray we need use

```<code>    email:  this.formBuilder.array([])
</code>```

When we want delete an element of the array, we need pass the "index" of the array, so our function delete is

```<code>delete(index:number)
  {
    const array=this.addForm.get('email') as FormArray
    array.removeAt(index)

  }
</code>```

and our .html is

```<code>  <div class="input-box">
        <input type="text" placeholder="E - mail" [formControl]="item">
        <img src="../../assets/Delete.svg" alt="x-icon" (click)="delete(i)">
  </div>
</code>```

Title: FormArray return null?

Body:
Greeting. I've tried multiple ways, but none of them work. I'm on this, right now. I need to initiate a formArray of emails

email: [testestest]

But I got:

email: [testestest]

But my email return  n click. Check my ts

And my html:

Body:
Alex, you has an Form Array of FormControls, not an Form Array of formGroups. So you .html must be like

<form *ngIf="addForm" [formGroup]="addForm">
    <div class="form-control-row" formArrayName="email"
        *ngFor="let item of addForm.get('email').controls; let i = index;">
        <div class="input-box">
            <input type="text" placeholder="E - mail" [formControlName]="i">
            <img src="../../assets/Delete.svg" alt="x-icon">
      </div>
        </div>
</form>

See that you has no [fomGroupName]="i", and you use [formControlName]="i"

Other way is

<form *ngIf="addForm" [formGroup]="addForm">
    <div class="form-control-row" formArrayName="email"
        *ngFor="let item of addForm.get('email').controls; let i = index;">
        <div class="input-box">
            <input type="text" placeholder="E - mail" [formControl]="item">
            <img src="../../assets/Delete.svg" alt="x-icon">
      </div>
        </div>
</form>

See that in this case we use [formControl]="item" (item is the variable you use in the
*ngFor)

Well, how you create the formArray?

If you has an array of emails you can do

    email:  this.formBuilder.array(
             this.email.map(x=>this.formBuilder.control(x))
          )

That's you create an array of FormControls using map (transform each element of the array in a FormControl who value the element of the array.

NOTE: In production you need create a getter for the array

get emails()
{
    return this.form.get('email') as FormArray;
}

And iterate over

    *ngFor="let item of emails.controls; let i = index;">

The use of [formGroupName]="i" and formControl it's used with a FormArray of FormGroups. e.g. you can has

    email:  this.formBuilder.array(
             this.email.map(x=>this.formBuilder.group({email:x}))
          )

See that in this case transform each element of the array in a formGroup that has a FormControl "called" email

You can see all this in this stackblitz. I hope the example help you understand the diference

If we want to add an element to the formArray we can make a function

  addEmail(email:any)
  {
    const array=this.addForm.get('email') as FormArray
    array.push(this.formBuilder.control(email)) //if is a FormArray of FormControl

    const array2=this.addForm.get('email2') as FormArray
    array2.push(this.formBuilder.group({email:email})) //if is a FormArray of FormGroup
  }

NOTE: At first, if we want to create a empty formArray we need use

    email:  this.formBuilder.array([])

When we want delete an element of the array, we need pass the "index" of the array, so our function delete is

delete(index:number)
  {
    const array=this.addForm.get('email') as FormArray
    array.removeAt(index)

  }

and our .html is

  <div class="input-box">
        <input type="text" placeholder="E - mail" [formControl]="item">
        <img src="../../assets/Delete.svg" alt="x-icon" (click)="delete(i)">
  </div>


问:
zipWith in Scala using map
Define zipWith. It should zip two lists, but instead of zipping elements into a tuple,
 it should use a function to combine two elements.

Example: zipWith(List(1, 2, 3),
                  List(10, 11, 12),
                  (x: Int, y: Int) => x+y)
 Should return: List(11,13,15)

use map and zip.

```<code>def zipWith[A,B,C](xs: List[A], ys: List[B], f: (A, B) => C): List[C] = {
        val zs = xs.zip(ys)
        //I don't know how to do this because if myMap(zs, f)

        //myMap takes a functin f:(a)=>b instead of f: (A, B) => C
    }
}
</code>```

答:
It sounds like you looking for something like this:

```<code>def zipWith[A,B,C](xs: List[A], ys: List[B], f: (A, B) => C): List[C] = {
  (xs, ys) match {
    case (Nil, _) => Nil
    case (_, Nil) => Nil
    case (x :: xs, y :: ys) => f(x, y) :: zipWith(xs, ys, f)
  }
}
</code>```

Hope that helps.

Update

Here is the same function but being tail-recursive:

```<code>    def zipWith[A, B, C](xs: List[A], ys: List[B], f: (A, B) => C): List[C] = {
      @tailrec
      def zipAccumulatingResult(xs: List[A], ys: List[B], f: (A, B) => C, acc: List[C]): List[C] = {
        (xs, ys) match {
          case (Nil, _) => acc
          case (_, Nil) => acc
          case (x :: xs, y :: ys) => zipAccumulatingResult(xs, ys, f, acc :+ f(x, y))
        }
      }

      zipAccumulatingResult(xs, ys, f, Nil)
    }
</code>```

Title: zipWith in Scala using map

Body:
Define zipWith. It should zip two lists, but instead of zipping elements into a tuple,
 it should use a function to combine two elements.

Example: zipWith(List(1, 2, 3),
                  List(10, 11, 12),
                  (x: Int, y: Int) => x+y)
 Should return: List(11,13,15)

use map and zip.

def zipWith[A,B,C](xs: List[A], ys: List[B], f: (A, B) => C): List[C] = {
        val zs = xs.zip(ys)
        //I don't know how to do this because if myMap(zs, f)

        //myMap takes a functin f:(a)=>b instead of f: (A, B) => C
    }
}

Body:
It sounds like you looking for something like this:

def zipWith[A,B,C](xs: List[A], ys: List[B], f: (A, B) => C): List[C] = {
  (xs, ys) match {
    case (Nil, _) => Nil
    case (_, Nil) => Nil
    case (x :: xs, y :: ys) => f(x, y) :: zipWith(xs, ys, f)
  }
}

Hope that helps.

Update

Here is the same function but being tail-recursive:

    def zipWith[A, B, C](xs: List[A], ys: List[B], f: (A, B) => C): List[C] = {
      @tailrec
      def zipAccumulatingResult(xs: List[A], ys: List[B], f: (A, B) => C, acc: List[C]): List[C] = {
        (xs, ys) match {
          case (Nil, _) => acc
          case (_, Nil) => acc
          case (x :: xs, y :: ys) => zipAccumulatingResult(xs, ys, f, acc :+ f(x, y))
        }
      }

      zipAccumulatingResult(xs, ys, f, Nil)
    }


问:
how in python Remove files with .log Extension
How can I list all file of a directory in Python and remove them by .log?

```<code>for root, dirs, files in os.walk(r'/home/m110/public_html/ts/'):
print(files)

output1281.log
output1020.log
log3.log
mem.py
output1087.log
bunker3.py
output1248.log
output1311.log
output1099.log
output1261.log
output1282.log
output1213.log
log43.log
output1291.log
output1095.log
output1209.log
usr.txt
output1210.log
log7.log
output1042.log
attack.py
output1032.log
output1318.log
</code>```

i run this code in Centos7 but i just need list file with .log file extension for delete times

答:
If you want to use os:

```<code>for root, dirs, files in os.walk('/home/m110/public_html/ts/'):
    for file in files:
        if file.endswith('.log'):
            os.remove(root +  '/' + file)
</code>```

In Python 3+, you can use pathlib:

```<code>paths = pathlib.Path('/home/m110/public_html/ts/').glob('*.log')
for path in paths:
    path.unlink()
</code>```

Body:
How can I list all file of a directory in Python and remove them by .log?

for root, dirs, files in os.walk(r'/home/m110/public_html/ts/'):
print(files)

output1281.log
output1020.log
log3.log
mem.py
output1087.log
bunker3.py
output1248.log
output1311.log
output1099.log
output1261.log
output1282.log
output1213.log
log43.log
output1291.log
output1095.log
output1209.log
usr.txt
output1210.log
log7.log
output1042.log
attack.py
output1032.log
output1318.log

i run this code in Centos7 but i just need list file with .log file extension for delete times

Body:
If you want to use os:

for root, dirs, files in os.walk('/home/m110/public_html/ts/'):
    for file in files:
        if file.endswith('.log'):
            os.remove(root +  '/' + file)

In Python 3+, you can use pathlib:

paths = pathlib.Path('/home/m110/public_html/ts/').glob('*.log')
for path in paths:
    path.unlink()