问:
How do I change android:layout_below dynamically in a Constraint Layout?
I'm trying to programmatically add/remove the         android:layout_below="@+id/relativeLayout_progress_circles"
attribute from the ConstraintLayout element. how do I do this?

```<code>  <android.support.constraint.ConstraintLayout
        android:id="@+id/my_constraint_layout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/view1"
        android:layout_above="@+id/view2"
        android:layout_centerHorizontal="true"
        android:scaleType="centerInside">
...
/>
</code>```

答:
Hey you can use the following code to dynamically apply this changes.</p>

```<code>    ((RelativeLayout.LayoutParams)my_constraint_layout.getLayoutParams()).addRule(RelativeLayout.BELOW,view.getId());
    //Here my_constraint_layout is your constraint layout and view is the view below which you want to set your constraint layout.
</code>```

Body:
I'm trying to programmatically add/remove the         android:layout_below="@+id/relativeLayout_progress_circles"
attribute from the ConstraintLayout element. how do I do this?

  <android.support.constraint.ConstraintLayout
        android:id="@+id/my_constraint_layout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/view1"
        android:layout_above="@+id/view2"
        android:layout_centerHorizontal="true"
        android:scaleType="centerInside">
...
/>

Body:
Hey you can use the following code to dynamically apply this changes.

    ((RelativeLayout.LayoutParams)my_constraint_layout.getLayoutParams()).addRule(RelativeLayout.BELOW,view.getId());
    //Here my_constraint_layout is your constraint layout and view is the view below which you want to set your constraint layout.


来源: stackexchange

问:
obtain session Id from cookies using javascript
I am trying to learn about cookies and what all they store. Since I am an active user of Google Chrome, I was thinking of accessing the session Id of a webpage from the cookie using only Javascript. I have obtained the list of all cookies stored in the browser using chrome.cookies.getAll().

However I can't understand how to access the session Id from the cookies since there is no keyword for it ?

How can I obtain the session ID from the cookies?

The code from obtaining the cookies is below :

```<code><html><head>
<script>
chrome.browserAction.onClicked.addListener(getCookies);

var cacheMap = {};
var cookie_nameArr = [];
var cookie_valArr = [];

    function getCookies(){
        chrome.cookies.getAll({}, function(cookies){

            for(var b in cookies){
            var cookieVal = cookies[b].value;
            var cookieName = cookies[b].domain;
                    cookie_nameArr.push(cookieName);
                    cookie_valArr.push(cookieVal);
                if(!cacheMap[cookieName])
                {
                    cacheMap[cookieName] = 1;
                }
                else
                    cacheMap[cookieName]++;
    }//alert(cookie_nameArr.length + "," + cookie_valArr.length);
        for(var i=0;i<3;i++)
    {
        alert(cookie_nameArr[i] + ", " + cookie_valArr[i]);

    }

});
}

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

答:
First you need to figure out what you are looking for. It's hard to look for a black cat in a dark room, especially if it is not there.

Open Chrome dev tools on the page you are interested in and check Resources tab. Do you see your cookie under "Cookies"? If yes, then you will be able to read it with your method. If not, then check your page url - maybe it is passed as url parameter? If not, then maybe session is used only for ajax requests? Maybe it is not used at all?

You need to find it manually first, then do it programmatically. Sessions come in all shapes and sizes, each site has its own way of implementing it. You can't build an extension that reads session for all sites.

Your approach is pretty much the way to go, just there is an easy way of inspecting objects using console instead of alert:

```<code>    chrome.cookies.getAll({domain: "stackoverflow.com"}, function(cookies){
        console.log(cookies);
    });
</code>```

Click on background.html link on your extensions tab and check the console.

ContentLicense: CC BY-SA 3.0

Body:
First you need to figure out what you are looking for. It's hard to look for a black cat in a dark room, especially if it is not there.

Open Chrome dev tools on the page you are interested in and check Resources tab. Do you see your cookie under "Cookies"? If yes, then you will be able to read it with your method. If not, then check your page url - maybe it is passed as url parameter? If not, then maybe session is used only for ajax requests? Maybe it is not used at all?

You need to find it manually first, then do it programmatically. Sessions come in all shapes and sizes, each site has its own way of implementing it. You can't build an extension that reads session for all sites.

Your approach is pretty much the way to go, just there is an easy way of inspecting objects using console instead of alert:

    chrome.cookies.getAll({domain: "stackoverflow.com"}, function(cookies){
        console.log(cookies);
    });

Click on background.html link on your extensions tab and check the console.


问:
r bump/slope chart set custom thickness and color
Consider a dataframe as follows, which has 5 items that were ranked at 3 time points

```<code>item<-rep(c(1:5),3)
time<-rep(c('a','b','c'),15)
rank<-round(runif(15,2,10),1)
stack<-as.data.frame(cbind(item,time,rank))
</code>```

looks something like

```<code>  item time rank
1    1    a  3.2
2    2    b  4.8
3    3    c  5.6
4    4    a  9.6
5    5    b  2.1
6    1    c  6.6
</code>```

I plot it like this

```<code>ggplot(data = stack, aes(x = time, y = rank, group = item)) +
  geom_line(aes(color = item, alpha = 1), size=2 )+
  geom_point(aes(color = item, alpha = 1), size = 4)
</code>```

There are a few ways I want to manipulate this graph:

I would like to be able to show the magnitude of changes by size of
the line, so that thicker lines represent bigger changes, but I want to do this for each time point a-b and b-c

I would like to show the same through color, where a positive change is a green line and a negative change is a red line, again this should be by each timepoint a-b, b-c

so far I have only been able to change the overall color or thickness, not by intervals a-b, and b-c

any other ideas of representing level of change are welcome (alpha is an option).

答:
First, made a quick change to your sample data to make it fully reproducible.

```<code>item<-factor(rep(c(1:5),3))
time<-rep(c('a','b','c'),15)
rank<-round(runif(15,2,10),1)
stack<-data.frame(item,time,rank)
</code>```

You can manipulate colour and size of the connecting line by calculating those values and adding them as an aesthetic. For example

```<code>library(dplyr)
stack <- stack %>%
  group_by(item) %>%
  mutate(delta = rank-lag(rank),
         direction =  ifelse(delta >  0, "Positive","Negative"))
</code>```

If you wanted to use relative difference instead of absolute difference, you can modify the above easily.

```<code>ggplot(stack, aes(x = time, y = rank, colour = direction, group = item)) +
  geom_line(aes(size = delta)) +
  geom_point(colour = "black") +
  scale_colour_manual(values = c("green","red"))
</code>```

Which does what you looked to do, but is admittedly kind of hideous. You can play around with colours and sizes until you get something you are happy with, or use alpha as an accepted aes, but overall I'd suggest thinking of an alternative. The objective of a bump chart is to make it easy to follow the changes in relative position across multiple periods or dimensions. By changing colour and size with direction, you're actually making it more difficult to track which line you're on as you go through time. I think your initial approach made more visual sense. Adjusting that slightly, you get something like this:

```<code>ggplot(stack, aes(x = time, y = rank, group = item)) +
  geom_line(aes(colour = item)) +
  geom_point(aes(colour = item), size = 4) +
  geom_point(colour = "black", pch = 1, size = 4) +
  geom_label(data = stack %>%
               filter(time == "c"),aes(label = item,
                                       fill = item)) +
  theme_minimal() +
  scale_fill_discrete(guide = FALSE) +
  scale_colour_discrete(guide = FALSE) +
  labs(x = "Time", y = "Rank")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Consider a dataframe as follows, which has 5 items that were ranked at 3 time points

item<-rep(c(1:5),3)
time<-rep(c('a','b','c'),15)
rank<-round(runif(15,2,10),1)
stack<-as.data.frame(cbind(item,time,rank))

looks something like

  item time rank
1    1    a  3.2
2    2    b  4.8
3    3    c  5.6
4    4    a  9.6
5    5    b  2.1
6    1    c  6.6

I plot it like this

ggplot(data = stack, aes(x = time, y = rank, group = item)) +
  geom_line(aes(color = item, alpha = 1), size=2 )+
  geom_point(aes(color = item, alpha = 1), size = 4)

There are a few ways I want to manipulate this graph:

I would like to be able to show the magnitude of changes by size of
the line, so that thicker lines represent bigger changes, but I want to do this for each time point a-b and b-c

I would like to show the same through color, where a positive change is a green line and a negative change is a red line, again this should be by each timepoint a-b, b-c

so far I have only been able to change the overall color or thickness, not by intervals a-b, and b-c

any other ideas of representing level of change are welcome (alpha is an option).

Body:
First, made a quick change to your sample data to make it fully reproducible.

item<-factor(rep(c(1:5),3))
time<-rep(c('a','b','c'),15)
rank<-round(runif(15,2,10),1)
stack<-data.frame(item,time,rank)

You can manipulate colour and size of the connecting line by calculating those values and adding them as an aesthetic. For example

library(dplyr)
stack <- stack %>%
  group_by(item) %>%
  mutate(delta = rank-lag(rank),
         direction =  ifelse(delta >  0, "Positive","Negative"))

If you wanted to use relative difference instead of absolute difference, you can modify the above easily.

ggplot(stack, aes(x = time, y = rank, colour = direction, group = item)) +
  geom_line(aes(size = delta)) +
  geom_point(colour = "black") +
  scale_colour_manual(values = c("green","red"))

Which does what you looked to do, but is admittedly kind of hideous. You can play around with colours and sizes until you get something you are happy with, or use alpha as an accepted aes, but overall I'd suggest thinking of an alternative. The objective of a bump chart is to make it easy to follow the changes in relative position across multiple periods or dimensions. By changing colour and size with direction, you're actually making it more difficult to track which line you're on as you go through time. I think your initial approach made more visual sense. Adjusting that slightly, you get something like this:

ggplot(stack, aes(x = time, y = rank, group = item)) +
  geom_line(aes(colour = item)) +
  geom_point(aes(colour = item), size = 4) +
  geom_point(colour = "black", pch = 1, size = 4) +
  geom_label(data = stack %>%
               filter(time == "c"),aes(label = item,
                                       fill = item)) +
  theme_minimal() +
  scale_fill_discrete(guide = FALSE) +
  scale_colour_discrete(guide = FALSE) +
  labs(x = "Time", y = "Rank")


问:
Python Reg ex needed to read till end of the line \n
Below is my byte class, am trying to read data till Suj using regex like below

```<code>stderr=b'ok: [localhost] => () fatal: [localhost]: Failed! => {"changed":true,"stdout":"Error": Invalid user or pwd\nJoin AD\n Suj}'
</code>```

Regex#

```<code>searchVal= re.search(r'fatal: \[localhost\]: Failed! =>(.*)[\n$](.*)',stderr.decode('utf-8'))
</code>```

but above reg ex is giving response till first '\n', but I want to read till end i.e second \n. I am not sure what is missing, any clue would be appreciated.

The response needed is like "changed":true,"stdout":"Error": Invalid user or pwd\nJoin AD\n Suj}". But am getting like"changed":true,"stdout":"Error": Invalid user or pwd\nJoin AD".

Thanks for your time

答:
The problem is the use of the dot character, which doesn't match new-line by default. use the DOTALL flag to change that:

```<code>stderr=b'ok: [localhost] => () fatal: [localhost]: Failed! => {"changed":true,"stdout":"Error": Invalid user or pwd\nJoin AD\n Suj}'
exp = re.compile(r'fatal: \[localhost\]: Failed! =>(.*)[\n$](.*)', re.DOTALL)
res = exp.search(stderr.decode('utf-8'))
res.group() # Results in the following:
</code>```

Result:

```<code>'fatal: [localhost]: Failed! => {"changed":true,"stdout":"Error": Invalid user or pwd\nJoin AD\n Suj}'
</code>```

Body:
Below is my byte class, am trying to read data till Suj using regex like below

stderr=b'ok: [localhost] => () fatal: [localhost]: Failed! => {"changed":true,"stdout":"Error": Invalid user or pwd\nJoin AD\n Suj}'

Regex#

searchVal= re.search(r'fatal: \[localhost\]: Failed! =>(.*)[\n$](.*)',stderr.decode('utf-8'))

but above reg ex is giving response till first '\n', but I want to read till end i.e second \n. I am not sure what is missing, any clue would be appreciated.

The response needed is like "changed":true,"stdout":"Error": Invalid user or pwd\nJoin AD\n Suj}". But am getting like"changed":true,"stdout":"Error": Invalid user or pwd\nJoin AD".

Thanks for your time

Body:
The problem is the use of the dot character, which doesn't match new-line by default. use the DOTALL flag to change that:

stderr=b'ok: [localhost] => () fatal: [localhost]: Failed! => {"changed":true,"stdout":"Error": Invalid user or pwd\nJoin AD\n Suj}'
exp = re.compile(r'fatal: \[localhost\]: Failed! =>(.*)[\n$](.*)', re.DOTALL)
res = exp.search(stderr.decode('utf-8'))
res.group() # Results in the following:

Result:

'fatal: [localhost]: Failed! => {"changed":true,"stdout":"Error": Invalid user or pwd\nJoin AD\n Suj}'


问:
How to create a higher order DCG parser in Prolog?
I would like to have some more general parsers, like for example paren that would take a parser and wrap it with parentheses:

```<code>paren(Parser, Result) -->
  "(", some_magic_dcg_call(Parser, Result), ")".

:- phrase(paren(number, N), "(123)").
123
:- phrase(paren(someatom, A), "(a)").
a
</code>```

I tried call and dcg_call, but they don't seem to solve the problem. How can I run an arbitrary parser inside another parser?

答:
This solution using call works in SWI-Prolog:

```<code>:- set_prolog_flag(double_quotes, chars).

paren(Parser, Result) -->
    "(",
    call(Parser, Result),
    ")".

number(123) -->
    "123".

someatom(a) -->
    "a".
</code>```

Tests:

```<code>?- phrase(paren(number, N), "(123)").
N = 123.

?- phrase(paren(someatom, A), "(a)").
A = a.
</code>```

Body:
I would like to have some more general parsers, like for example paren that would take a parser and wrap it with parentheses:

paren(Parser, Result) -->
  "(", some_magic_dcg_call(Parser, Result), ")".

:- phrase(paren(number, N), "(123)").
123
:- phrase(paren(someatom, A), "(a)").
a

I tried call and dcg_call, but they don't seem to solve the problem. How can I run an arbitrary parser inside another parser?

Body:
This solution using call works in SWI-Prolog:

:- set_prolog_flag(double_quotes, chars).

paren(Parser, Result) -->
    "(",
    call(Parser, Result),
    ")".

number(123) -->
    "123".

someatom(a) -->
    "a".

Tests:

?- phrase(paren(number, N), "(123)").
N = 123.

?- phrase(paren(someatom, A), "(a)").
A = a.


问:
React render siblings on Multiple Select Material UI
This is my problem:
I need to create a multiple select (with checkboxes) on React using material UI, just like the following image:

I have the data in an array like the following

```<code>data = [
  {
    id: 199,
    name: "Argentina",
    state: [
      { name: "Buenos Aires", id: 1 },
      { name: "Cordoba", id: 2 },
      { name: "Chaco", id: 2 }
    ]
  },
  {
    id: 200,
    name: "USA",
    state: [
      { name: "California", id: 4 },
      { name: "Florida", id: 5 },
      { name: "Texas", id: 6 }
    ]
  }
]
</code>```

Perfect. Everything seems to have to do 2 nested maps, nothing out of the ordinary. Meanwhile, I try this:

```<code><InputLabel htmlFor="grouped-select">Grouping</InputLabel>
<Select
  defaultValue={[]}
  id="grouped-select"
  onChange={handleChange}
  multiple
>
  <MenuItem value="">
    <Checkbox />
    <em>All</em>
  </MenuItem>
  {data.map(country => (
    <>
      <ListSubheader key={country.id}>{country.name}</ListSubheader>
      {country.state.map(state => (
        <MenuItem key={state.id} value={state.id}>
          <Checkbox />
          {state.name}
        </MenuItem>
      ))}
    </>
  ))}
</Select>
</code>```

That renders the select well, makes it look nice. But my problem is that (apparently) material doesn't accept React.Fragment (<></>) inside select. Meanwhile, I can't generate the structure that Material UI specifies in the documentation looping through an array:

```<code><ListSubheader>Parent 1</ListSubHeader>
<MenuItem key={state.id} value={state.id}>Child1</MenuItem>
<MenuItem key={state.id} value={state.id}>Child2</MenuItem>
<MenuItem key={state.id} value={state.id}>Child...n</MenuItem>

<ListSubheader>Parent 2</ListSubHeader>
<MenuItem key={state.id} value={state.id}>Child</MenuItem>
<MenuItem key={state.id} value={state.id}>Child...n</MenuItem>
</code>```

If i put a
 or other element instead of <></>, the onchange event stops working.

I also tried to use rendering with arrays, but did not have good results since the second sibling is not a jsx, but I have to loop through the array.

```<code>{data.map(country => [
    <ListSubheader key={country.id}>{country.name}</ListSubheader>
    {country.state.map(state => (
      <MenuItem key={state.id} value={state.id}>
        <Checkbox />
        {state.name}
      </MenuItem>
    ))}
  ])}
</code>```

I am blocked, I do not know how it can be solved. I thought of a child component but I am going to have the same problem when rendering it.

Is there a way to solve it?

I leave a link with the example snippet: https://codesandbox.io/s/material-demo-h77i8

Thank you very much.

答:
I've created an example which is similar to your code. You can try it in codesandbox here. Hopefully, it can help you.

This is my code:

...
const names = [
  "Oliver Hansen",
  "Van Henry",
  "April Tucker",
  "Ralph Hubbard",
  "Omar Alexander",
  "Carlos Abbott",
  "Miriam Wagner",
  "Bradley Wilkerson",
  "Virginia Andrews",
  "Kelly Snyder"
];

export default function MultipleSelect() {
  const classes = useStyles();
  const [personName, setPersonName] = React.useState([]);

  const handleChangeMultiple = event => {
    const { value } = event.target;
    const allIndex = value.indexOf("All");
    if (allIndex > -1) {
      const values = ["All"];
      for (let name of names) {
        values.push(name);
      }
      setPersonName(values);
    } else {
      setPersonName([]);
    }
  };

  return (

      <FormControl className={classes.formControl}>
        <InputLabel id="demo-mutiple-checkbox-label">Tag</InputLabel>
        <Select
          labelId="demo-mutiple-checkbox-label"
          id="demo-mutiple-checkbox"
          multiple
          value={personName}
          onChange={handleChangeMultiple}
          input={<Input />}
          renderValue={selected => selected.join(", ")}
          MenuProps={MenuProps}
        >
          <MenuItem key="All" value="All">
            <Checkbox checked={personName.indexOf("All") > -1} />
            All
          </MenuItem>
          {names.map(name => (
            <MenuItem key={name} value={name}>
              <Checkbox checked={personName.indexOf(name) > -1} />
              <ListItemText primary={name} />
            </MenuItem>
          ))}
        </Select>
      </FormControl>

  );
}```

Body:
This is my problem:
I need to create a multiple select (with checkboxes) on React using material UI, just like the following image:

I have the data in an array like the following

data = [
  {
    id: 199,
    name: "Argentina",
    state: [
      { name: "Buenos Aires", id: 1 },
      { name: "Cordoba", id: 2 },
      { name: "Chaco", id: 2 }
    ]
  },
  {
    id: 200,
    name: "USA",
    state: [
      { name: "California", id: 4 },
      { name: "Florida", id: 5 },
      { name: "Texas", id: 6 }
    ]
  }
]

Perfect. Everything seems to have to do 2 nested maps, nothing out of the ordinary. Meanwhile, I try this:

<InputLabel htmlFor="grouped-select">Grouping</InputLabel>
<Select
  defaultValue={[]}
  id="grouped-select"
  onChange={handleChange}
  multiple
>
  <MenuItem value="">
    <Checkbox />
    All
  </MenuItem>
  {data.map(country => (
    <>
      <ListSubheader key={country.id}>{country.name}</ListSubheader>
      {country.state.map(state => (
        <MenuItem key={state.id} value={state.id}>
          <Checkbox />
          {state.name}
        </MenuItem>
      ))}
    </>
  ))}
</Select>

That renders the select well, makes it look nice. But my problem is that (apparently) material doesn't accept React.Fragment (<></>) inside select. Meanwhile, I can't generate the structure that Material UI specifies in the documentation looping through an array:

<ListSubheader>Parent 1</ListSubHeader>
<MenuItem key={state.id} value={state.id}>Child1</MenuItem>
<MenuItem key={state.id} value={state.id}>Child2</MenuItem>
<MenuItem key={state.id} value={state.id}>Child...n</MenuItem>

<ListSubheader>Parent 2</ListSubHeader>
<MenuItem key={state.id} value={state.id}>Child</MenuItem>
<MenuItem key={state.id} value={state.id}>Child...n</MenuItem>

If i put a
 or other element instead of <></>, the onchange event stops working.

I also tried to use rendering with arrays, but did not have good results since the second sibling is not a jsx, but I have to loop through the array.

{data.map(country => [
    <ListSubheader key={country.id}>{country.name}</ListSubheader>
    {country.state.map(state => (
      <MenuItem key={state.id} value={state.id}>
        <Checkbox />
        {state.name}
      </MenuItem>
    ))}
  ])}

I am blocked, I do not know how it can be solved. I thought of a child component but I am going to have the same problem when rendering it.

Is there a way to solve it?

I leave a link with the example snippet: https://codesandbox.io/s/material-demo-h77i8

Thank you very much.

Body:
I've created an example which is similar to your code. You can try it in codesandbox here. Hopefully, it can help you.

This is my code:

...
const names = [
  "Oliver Hansen",
  "Van Henry",
  "April Tucker",
  "Ralph Hubbard",
  "Omar Alexander",
  "Carlos Abbott",
  "Miriam Wagner",
  "Bradley Wilkerson",
  "Virginia Andrews",
  "Kelly Snyder"
];

export default function MultipleSelect() {
  const classes = useStyles();
  const [personName, setPersonName] = React.useState([]);

  const handleChangeMultiple = event => {
    const { value } = event.target;
    const allIndex = value.indexOf("All");
    if (allIndex > -1) {
      const values = ["All"];
      for (let name of names) {
        values.push(name);
      }
      setPersonName(values);
    } else {
      setPersonName([]);
    }
  };

  return (
    <div>
      <FormControl className={classes.formControl}>
        <InputLabel id="demo-mutiple-checkbox-label">Tag</InputLabel>
        <Select
          labelId="demo-mutiple-checkbox-label"
          id="demo-mutiple-checkbox"
          multiple
          value={personName}
          onChange={handleChangeMultiple}
          input={<Input />}
          renderValue={selected => selected.join(", ")}
          MenuProps={MenuProps}
        >
          <MenuItem key="All" value="All">
            <Checkbox checked={personName.indexOf("All") > -1} />
            <em>All</em>
          </MenuItem>
          {names.map(name => (
            <MenuItem key={name} value={name}>
              <Checkbox checked={personName.indexOf(name) > -1} />
              <ListItemText primary={name} />
            </MenuItem>
          ))}
        </Select>
      </FormControl>
    </div>
  );
}


问:
linux msmtp configuration sends from shell but fails from PHP/apache
linux (fedora 20) msmtp configuration sends from shell but fails from PHP/apache, I am stumped... my objective is just to send email, through my gmail smtp from my localhost development webserver, to test output of code that sends mail

php.ini sendmail file reads :
sendmail_path = /usr/bin/msmtp --debug -C /etc/msmtprc --read-recipients

there is only one php.ini on the system, used for both CLI and webserver located at /etc/php.ini

permissions on /etc/msmtprc are set to apache:apache 600

the following commands as root work and produce a test email :

php -r "mail('emily@emilytench.net', 'Newest Test Email', 'Test email body');"

runuser -l apache -c '/usr/bin/msmtp --debug -C /etc/msmtprc --read-recipients < /var/www/html/test.mail'  (test.mail includes to and from lines)

but apache/php produces an error when the php mail function is called from the following script:

```<code>if (mail('emily@emilytench.net', 'Newest Test Email', 'Test email body'))
print "Email successfully sent";
else
print "An error occured";
</code>```

Log files during error read as follows :

/var/log/httpd/error_log :
      msmtp: cannot connect to smtp.gmail.com, port 587: Permission denied
      msmtp: could not send mail (account default from /etc/msmtprc)

/etc/msmtprc contains :

```<code>defaults
auth on
tls on
tls_trust_file /etc/pki/tls/cert.pem
account default
host smtp.gmail.com
port 587
user emily@emilytench.net
from emily@emilytench.net
password [******]
auth on
syslog on
</code>```

any pointers in the correct direction are welcomed... only trying to achieve a simple avenue for localhost php mail function to send emails through my gmail smtp server - this is not a production server configuration, it is my local apache/php webserver for web development

答:
FIXED - msmtp: cannot log to /var/log/msmtp: cannot open: Permission
  denied

This is for the next person who runs into this issue.

System config file for msmtp
-rw-rw-rw- 1 root root 266 Jun  3 06:07 /etc/msmtprc

```<code># mimecast
account mimecast
host smtp.mail.com
port 587
protocol smtp
from admin@company.com
auth on
user authuser@company.com
password mypassword
tls on
tls_certcheck off
logfile ~/.msmtp.log
syslog off
account default : mimecast

.#mimecast is just a section header and can be deleted
account mimecast - is a title if multiple send accounts are available or needed
account default : mimecast  - is saying this is the default account used
</code>```

The configuration file per user if needed can be the same as the system file with a different userid, password and from fields.  note the "." before the .msmtprc

-rw------- 1 ubuntu ubuntu      267 Jun  3 05:50 .msmtprc

The log file gets created per user in their home directory with the correct permissions - no need to mess with the permissions.

-rw-r--r--  1 root msmtp      344 Jun  3 06:09 .msmtp.log

To send an email from the command line

```<code>echo -e "Subject: MySubject\r\n\r\nThis is mybody" |msmtp recipient@company.com

use the -C configfilename  to specify alternate local config files
use the -a account mimecast to switch between accounts to send from within the config file  ( did not try this option )
</code>```

or use

```<code>msmtp recipient@company.com
Subject: This is my subjectline
Blank line ( press enter )
Here is the body of the email

CTRL-D ( to send )
</code>```

or use this option to send mail from the command line

```<code>msmtp recipient@company.com < filename
</code>```

where the filename contains

```<code>To: recipient@company.com
From: sender@company.com
Subject: Here is the Subject

body body body .....
</code>```

Body:
linux (fedora 20) msmtp configuration sends from shell but fails from PHP/apache, I am stumped... my objective is just to send email, through my gmail smtp from my localhost development webserver, to test output of code that sends mail

php.ini sendmail file reads :
sendmail_path = /usr/bin/msmtp --debug -C /etc/msmtprc --read-recipients

there is only one php.ini on the system, used for both CLI and webserver located at /etc/php.ini

permissions on /etc/msmtprc are set to apache:apache 600

the following commands as root work and produce a test email :

php -r "mail('emily@emilytench.net', 'Newest Test Email', 'Test email body');"

runuser -l apache -c '/usr/bin/msmtp --debug -C /etc/msmtprc --read-recipients < /var/www/html/test.mail'  (test.mail includes to and from lines)

but apache/php produces an error when the php mail function is called from the following script:

if (mail('emily@emilytench.net', 'Newest Test Email', 'Test email body'))
print "Email successfully sent";
else
print "An error occured";

Log files during error read as follows :

/var/log/httpd/error_log :
      msmtp: cannot connect to smtp.gmail.com, port 587: Permission denied
      msmtp: could not send mail (account default from /etc/msmtprc)

/etc/msmtprc contains :

defaults
auth on
tls on
tls_trust_file /etc/pki/tls/cert.pem
account default
host smtp.gmail.com
port 587
user emily@emilytench.net
from emily@emilytench.net
password [******]
auth on
syslog on

any pointers in the correct direction are welcomed... only trying to achieve a simple avenue for localhost php mail function to send emails through my gmail smtp server - this is not a production server configuration, it is my local apache/php webserver for web development

Body:
FIXED - msmtp: cannot log to /var/log/msmtp: cannot open: Permission
  denied

This is for the next person who runs into this issue.

System config file for msmtp
-rw-rw-rw- 1 root root 266 Jun  3 06:07 /etc/msmtprc

# mimecast
account mimecast
host smtp.mail.com
port 587
protocol smtp
from admin@company.com
auth on
user authuser@company.com
password mypassword
tls on
tls_certcheck off
logfile ~/.msmtp.log
syslog off
account default : mimecast

.#mimecast is just a section header and can be deleted
account mimecast - is a title if multiple send accounts are available or needed
account default : mimecast  - is saying this is the default account used

The configuration file per user if needed can be the same as the system file with a different userid, password and from fields.  note the "." before the .msmtprc

-rw------- 1 ubuntu ubuntu      267 Jun  3 05:50 .msmtprc

The log file gets created per user in their home directory with the correct permissions - no need to mess with the permissions.

-rw-r--r--  1 root msmtp      344 Jun  3 06:09 .msmtp.log

To send an email from the command line

echo -e "Subject: MySubject\r\n\r\nThis is mybody" |msmtp recipient@company.com

use the -C configfilename  to specify alternate local config files
use the -a account mimecast to switch between accounts to send from within the config file  ( did not try this option )

or use

msmtp recipient@company.com
Subject: This is my subjectline
Blank line ( press enter )
Here is the body of the email

CTRL-D ( to send )

or use this option to send mail from the command line

msmtp recipient@company.com < filename

where the filename contains

To: recipient@company.com
From: sender@company.com
Subject: Here is the Subject

body body body .....


问:
How to get and modify a property value through a custom Attribute?
I want to create a custom attribute that can be used on a property like:

```<code>[TrimInputString]
public string FirstName { get; set; }
</code>```

that will be functional equivalent of

```<code>private string _firstName
public string FirstName {
  set {
    _firstName = value.Trim();
  }
  get {
    return _firstName;
  }
}
</code>```

So basically every time property is set the value will be trimmed.

How do I get the value parsed, modify that value and then set the property with the new value all from within the attribute?

```<code>[AttributeUsage(AttributeTargets.Property)]
public class TrimInputAttribute : Attribute {

  public TrimInputAttribute() {
    //not sure how to get and modify the property here
  }

}
</code>```

答:
iam doing this , not very convincing way but its working

demo class

```<code>public class User
{

[TitleCase]
public string FirstName { get; set; }

[TitleCase]
public string LastName { get; set; }

[UpperCase]
public string Salutation { get; set; }

[LowerCase]
public string Email { get; set; }

}
</code>```

Writing Attribute for LowerCase, others can be written in the similar manner

```<code>public class LowerCaseAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
       //try to modify text
            try
            {
                validationContext
                .ObjectType
                .GetProperty(validationContext.MemberName)
                .SetValue(validationContext.ObjectInstance, value.ToString().ToLower(), null);
            }
            catch (System.Exception)
            {
            }

        //return null to make sure this attribute never say iam invalid
        return null;
    }
}
</code>```

Not very elegant way as its actually implementing Validation attribute but it works

ContentLicense: CC BY-SA 2.5

Body:
I want to create a custom attribute that can be used on a property like:

[TrimInputString]
public string FirstName { get; set; }

that will be functional equivalent of

private string _firstName
public string FirstName {
  set {
    _firstName = value.Trim();
  }
  get {
    return _firstName;
  }
}

So basically every time property is set the value will be trimmed.

How do I get the value parsed, modify that value and then set the property with the new value all from within the attribute?

[AttributeUsage(AttributeTargets.Property)]
public class TrimInputAttribute : Attribute {

  public TrimInputAttribute() {
    //not sure how to get and modify the property here
  }

}

Body:
iam doing this , not very convincing way but its working

demo class

public class User
{

[TitleCase]
public string FirstName { get; set; }

[TitleCase]
public string LastName { get; set; }

[UpperCase]
public string Salutation { get; set; }

[LowerCase]
public string Email { get; set; }

}

Writing Attribute for LowerCase, others can be written in the similar manner

public class LowerCaseAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
       //try to modify text
            try
            {
                validationContext
                .ObjectType
                .GetProperty(validationContext.MemberName)
                .SetValue(validationContext.ObjectInstance, value.ToString().ToLower(), null);
            }
            catch (System.Exception)
            {
            }

        //return null to make sure this attribute never say iam invalid
        return null;
    }
}

Not very elegant way as its actually implementing Validation attribute but it works


问:
How to upload images or static files in a django project
Ive tried everything. I cannot upload images in my website. How to do that. It just gives an icon of an image not the image itself. When i write {% load static %} in my html5 file which is running bootstrap css stuff it simply displays that on the webpage. it takes this command as text. Also ive tried to shift the whole iconic folder i downloaded to static directory but py manage.py collectstatic showed 0 files  , 130 unmodified.

答:
static folder should be inside project with manage.py file as shown in the image below.

and add this in setting

```<code>STATIC_URL = '/static/'

STATICFILES_DIRS = (
  os.path.join(BASE_DIR, 'static'),
)
</code>```

You have created multiple static folder and for what I think django only allows single static folder and wrap everything inside it.

Body:
static folder should be inside project with manage.py file as shown in the image below.

and add this in setting

STATIC_URL = '/static/'

STATICFILES_DIRS = (
  os.path.join(BASE_DIR, 'static'),
)

You have created multiple static folder and for what I think django only allows single static folder and wrap everything inside it.


问:
Prevent WebView from Opening the Browser
I'm already active JavaScript for a given WebView, and opens new link inside the WebView, not in the Browser.
This Is Main Activity

```<code>    package com.Afrogfx.pronouns;

    import android.os.Bundle;
    import android.annotation.SuppressLint;
    import android.app.Activity;
    import android.view.Menu;
    import android.webkit.WebView;

    @SuppressLint("SetJavaScriptEnabled")
    public class MainActivityPronouns extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_activity_pronouns);

    WebView wvHtml = (WebView) findViewById(R.id.webview);
    wvHtml.getSettings().setBuiltInZoomControls(true);
    wvHtml.getSettings().setJavaScriptEnabled(true);
    wvHtml.loadUrl("http://afrogfx.com/appcatcategories.php?catid=13&parentid=11");
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main_activity_pronouns, menu);
    return true;
    }
    }
</code>```

how can i handel my code to open all link in site inside the WebView (App) , not in the Browser & ( don't show to user Open in browser).

答:
In case you use Kotlin:</p>

```<code>webView.webViewClient = object : WebViewClient() {
                override fun shouldOverrideUrlLoading(
                    view: WebView?,
                    request: WebResourceRequest?
                ): Boolean {
                    return false
                }
            }
</code>```

Body:
I'm already active JavaScript for a given WebView, and opens new link inside the WebView, not in the Browser.
This Is Main Activity

    package com.Afrogfx.pronouns;

    import android.os.Bundle;
    import android.annotation.SuppressLint;
    import android.app.Activity;
    import android.view.Menu;
    import android.webkit.WebView;

    @SuppressLint("SetJavaScriptEnabled")
    public class MainActivityPronouns extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_activity_pronouns);

    WebView wvHtml = (WebView) findViewById(R.id.webview);
    wvHtml.getSettings().setBuiltInZoomControls(true);
    wvHtml.getSettings().setJavaScriptEnabled(true);
    wvHtml.loadUrl("http://afrogfx.com/appcatcategories.php?catid=13&parentid=11");
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main_activity_pronouns, menu);
    return true;
    }
    }

how can i handel my code to open all link in site inside the WebView (App) , not in the Browser & ( don't show to user Open in browser).

Body:
In case you use Kotlin:

webView.webViewClient = object : WebViewClient() {
                override fun shouldOverrideUrlLoading(
                    view: WebView?,
                    request: WebResourceRequest?
                ): Boolean {
                    return false
                }
            }


问:
Grouping of data with certain criteria
I have a following data frame of user stats:

```<code>ID    User      VisitTime
1     Ra          08:00
1     Ma          15:13
2     Da          20:15
2     La          11:00
</code>```

How do I create  a datafram ewith another column named as "label" to show time in Morning, Afternoon and Evening?
 I referred some of the posts on Stackoverflow and used dplyr group_by but not able to produce desire results.

Basically I am looking for this  data frames:

```<code>ID    User      VisitTime    Label
1     Ra          08:00      Morning
1     Ma          15:13      Evening
2     Da          20:15      Night
2     La          11:00      Morning
</code>```

答:
Convert VisitTime to POSIXct format, extract hour from it, define "Morning", "Afternoon", "Evening" and "Night" and assign labels.

```<code>library(dplyr)

df %>%
  mutate(time = as.POSIXct(VisitTime, format = "%H:%M"),
         hour = as.integer(format(time, '%H')),
         Label  = case_when(between(hour, 6, 11) ~ "Morning",
                            between(hour, 12, 15) ~"Afternoon",
                            between(hour, 16, 19) ~"Evening",
                            TRUE ~"Night"))
</code>```

Title: Grouping of data with certain criteria

Body:
I have a following data frame of user stats:

ID    User      VisitTime
1     Ra          08:00
1     Ma          15:13
2     Da          20:15
2     La          11:00

How do I create  a datafram ewith another column named as "label" to show time in Morning, Afternoon and Evening?
 I referred some of the posts on Stackoverflow and used dplyr group_by but not able to produce desire results.

Basically I am looking for this  data frames:

ID    User      VisitTime    Label
1     Ra          08:00      Morning
1     Ma          15:13      Evening
2     Da          20:15      Night
2     La          11:00      Morning

Body:
Convert VisitTime to POSIXct format, extract hour from it, define "Morning", "Afternoon", "Evening" and "Night" and assign labels.

library(dplyr)

df %>%
  mutate(time = as.POSIXct(VisitTime, format = "%H:%M"),
         hour = as.integer(format(time, '%H')),
         Label  = case_when(between(hour, 6, 11) ~ "Morning",
                            between(hour, 12, 15) ~"Afternoon",
                            between(hour, 16, 19) ~"Evening",
                            TRUE ~"Night"))


问:
Python and random keys of 21 char max
I am using an api which takes a name of 21 char max to represent an internal session which has a lifetime of around "two days". I would like the name not to be meaningfull using some kind of hasing ? md5 generates 40 chars, is there something else i could use ?

For now i use 'userid[:10]' + creation time: ddhhmmss + random 3 chars.

Thanks,

答:
Characters, or bytes? If it takes arbitrary strings, you can just use the bytes and not worry about expanding to readable characters (for which base64 would be better than hex anyway).

MD5 generates 16 chars if you don't use the hexadecimal expansion of it. SHA1 generates 20 under the same condition.

```<code>>>> import hashlib
>>> len(hashlib.md5('foobar').digest())
16
>>> len(hashlib.sha1('foobar').digest())
20
</code>```

Few extra bytes are needed after that.

OwnerDisplayName: coulix

Title: Python and random keys of 21 char max

Body:
Characters, or bytes? If it takes arbitrary strings, you can just use the bytes and not worry about expanding to readable characters (for which base64 would be better than hex anyway).

MD5 generates 16 chars if you don't use the hexadecimal expansion of it. SHA1 generates 20 under the same condition.

>>> import hashlib
>>> len(hashlib.md5('foobar').digest())
16
>>> len(hashlib.sha1('foobar').digest())
20

Few extra bytes are needed after that.

OwnerDisplayName: Devin Jeanpierre


问:
Twitter streaming API with Python - controlling the process
I'm writing a script that uses Python to consume Twitter's streaming API. My issue is that I would like to collect tweets for only a specific time frame (i.e. 1 hr worth of tweets). I've used a Timer object to stop the process and attempt to close the connection but this works half the time. I also tried to catch KeyboardInterrupt errors and automatically close the connection but this doesn't seem to work either.

My question is:
Is there a proper way of dealing with streaming API's and how can I have control over when I want to start and stop consuming the stream? I was thinking about using a child process but am not sure.

Thanks!

答:
urllib2 is a blocking API and includes buffering. There is little you can do to cleanly interrupt its read() at a given time.

You'll need a more flexible HTTP library. Here's a tutorial for Twitter with PyCurl.


问:
How to get rid of the use of "end" in loops(python) for only the last element?
By using end="-" I got this loop. I want to remove that '-' for the last element.

```<code>  m=4
  n=1
  for i in range(1,4):
      for x in range(5,n,-1):
          print(" ",end="")
      n+=2
      for y in range(3,3-i,-1):
          print(y,end="-")
      for z in range(m,4):
          print(z,end="-")
      m-=1
      print()
</code>```

Output:

```<code>           3-
       3-2-3-
    3-2-1-2-3-
</code>```

答:
Instead of using end, you can actually use sep, which only separates between elements which sounds like what you want. This will even reduce your loops a bit.

You will have to change the prints to be something like: print(*range(m, 4), sep='-').

The spaces (' ') loop is also not necessary and can be a single print, so your whole code can look like:

m = 4
n = 1
for i in range(1, 4):
    print(" " * abs(5-n), end='')
    n += 2
    print(*range(3, 3-i, -1), *range(m, 4), sep='-')
    m -= 1
```

<p>It is also possible to only use the loop variable <code>i</code> and avoid maintaining <code>m</code> and <code>n</code>. So the code can be reduced to:</p>

<pre class="lang-py prettyprint-override"><code>m = 4
for i in range(1, m):
    print(" " * abs(5-i*2+1), end='')
    print(*range(3, 3-i, -1), *range(m-i+1, m), sep='-')
</code>```

which gives:

    3
  3-2-3
3-2-1-2-3
```

<p>Finally, to make it more <em>reasonable</em> by <code>m</code> being the range being printed, and making it completely generic to allow any <code>m</code> you can do:</p>

<pre class="lang-py prettyprint-override"><code>m = 4
for i in range(1, m+1):
    print(" " * (m*2-i*2), end='')
    print(*range(m, m-i, -1), *range(m-i+2, m+1), sep='-')
</code>```

Which will now print up-to 4:

      4
    4-3-4
  4-3-2-3-4
4-3-2-1-2-3-4
```

Body:
By using end="-" I got this loop. I want to remove that '-' for the last element.

  m=4
  n=1
  for i in range(1,4):
      for x in range(5,n,-1):
          print(" ",end="")
      n+=2
      for y in range(3,3-i,-1):
          print(y,end="-")
      for z in range(m,4):
          print(z,end="-")
      m-=1
      print()

Output:

           3-
       3-2-3-
    3-2-1-2-3-

Body:
Instead of using end, you can actually use sep, which only separates between elements which sounds like what you want. This will even reduce your loops a bit.

You will have to change the prints to be something like: print(*range(m, 4), sep='-').

The spaces (' ') loop is also not necessary and can be a single print, so your whole code can look like:

m = 4
n = 1
for i in range(1, 4):
    print(" " * abs(5-n), end='')
    n += 2
    print(*range(3, 3-i, -1), *range(m, 4), sep='-')
    m -= 1

It is also possible to only use the loop variable i and avoid maintaining m and n. So the code can be reduced to:

m = 4
for i in range(1, m):
    print(" " * abs(5-i*2+1), end='')
    print(*range(3, 3-i, -1), *range(m-i+1, m), sep='-')

which gives:

    3
  3-2-3
3-2-1-2-3

Finally, to make it more reasonable by m being the range being printed, and making it completely generic to allow any m you can do:

m = 4
for i in range(1, m+1):
    print(" " * (m*2-i*2), end='')
    print(*range(m, m-i, -1), *range(m-i+2, m+1), sep='-')

Which will now print up-to 4:

      4
    4-3-4
  4-3-2-3-4
4-3-2-1-2-3-4


问:
AWS Glue Job - pass glue catalog table names as parameters
I have a AWS Glue job in pyspark language which loads data from S3/Glue catalog db to snowflake. How can we achieve passing table names as parameters and run the aws glue job in parallel.

can we do it inside glue job or any lambda functions?

Please suggest and share any code/articles.

Thank you in advance.

Thanks,
Jo

答:
AWS Glue lets you enter your own script, so it's very flexible. You can pass table names as parameters:

https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-pyspark-extensions-get-resolved-options.html

In this case, Glue job can process these tables sequentially:

parse the input parameters

create a loop for each table

create_dynamic_frame for reading table

transform if necessary

write to snowflake

process next table

If you want to run separate Glue jobs for each table to process them in parallel, then you need to pass only one table to the Glue job, and call the same job for multiple time with a different table name.

https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-python-calling.html

Glue launches an EMR cluster based on the "Number of workers".

I do not know how many tables you will process, and the frequency of calling the Glue job, but it could be better to process the tables sequentialy  with a bigger cluster to utilize resources.


问:
How do I create a GUID / UUID?
How do I create GUIDs (globally-unique identifiers) in JavaScript? The GUID / UUID should be at least 32 characters and should stay in the ASCII range to avoid trouble when passing them around.

I'm not sure what routines are available on all browsers, how "random" and seeded the built-in random number generator is, etc.

答:
Don't use Math.random in any case since it generates a non-cryptographic source of random numbers.

The solution below using crypto.getRandomValues

```<code>function uuidv4() {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
    // tslint:disable-next-line: no-bitwise
    const r =
      (window.crypto.getRandomValues(new Uint32Array(1))[0] *
        Math.pow(2, -32) * 16) |
      0;
    // tslint:disable-next-line: no-bitwise
    const v = c === "x" ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}
</code>```

This link helps you to understand the insecure randomness thrown by Fortify Scanner.

OwnerDisplayName: Jason Cohen

Title: How do I create a GUID / UUID?

Body:
Don't use Math.random in any case since it generates a non-cryptographic source of random numbers.

The solution below using crypto.getRandomValues

function uuidv4() {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
    // tslint:disable-next-line: no-bitwise
    const r =
      (window.crypto.getRandomValues(new Uint32Array(1))[0] *
        Math.pow(2, -32) * 16) |
      0;
    // tslint:disable-next-line: no-bitwise
    const v = c === "x" ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}

This link helps you to understand the insecure randomness thrown by Fortify Scanner.


问:
Always output raw HTML using MVC3 and Razor
I’ve got a class with a property that looks like this:

```<code>[AllowHtml]
[DataType(DataType.MultilineText)]
public string Description { get; set; }
</code>```

I’ve already put in the [AllowHtml] attribute to let me submit HTML to this property via the form that I’ve built, but what I want to do is output the value of the property as the raw HTML without it being escaped.

I know I can use Html.Raw(Model.Description) but what I’m looking for is some way of telling Html.DisplayFor(m => m.Description) to always output the raw HTML. Is there an attribute I can use to decorate the properties in my class that I wish to behave like that?

Basically it’s me being lazy—I don’t want to have to remember which properties might contain HTML, so I don’t want to have to think about using Html.Raw(…) when I need to do the above—I’d much rather my Model know what it should do and do it automatically. I’ve tried searching for an answer, but either I’m not phrasing it correctly or there’s no way of doing it :(

Thanks,

答: Just to provide a bit more info here - your issue is that @ will always HtmlEncode unless you have IHtmlString returned - so the issue is sourced at the @ symbol. It's one of the benefits of the razor syntax - its safer to htmlencode than to not. So there is no 'quick' way here since the root of your issue is the @ symbol which will exclude HtmlEncoding if it finds IHtmlString. So - no 'quick' way around this unless you use the old <% syntax which IMHO sucks compared to razor : )</p>

Body:
I’ve got a class with a property that looks like this:

[AllowHtml]
[DataType(DataType.MultilineText)]
public string Description { get; set; }

I’ve already put in the [AllowHtml] attribute to let me submit HTML to this property via the form that I’ve built, but what I want to do is output the value of the property as the raw HTML without it being escaped.

I know I can use Html.Raw(Model.Description) but what I’m looking for is some way of telling Html.DisplayFor(m => m.Description) to always output the raw HTML. Is there an attribute I can use to decorate the properties in my class that I wish to behave like that?

Basically it’s me being lazy—I don’t want to have to remember which properties might contain HTML, so I don’t want to have to think about using Html.Raw(…) when I need to do the above—I’d much rather my Model know what it should do and do it automatically. I’ve tried searching for an answer, but either I’m not phrasing it correctly or there’s no way of doing it :(

Thanks,


问:
to find class distribution for breast cancer data set - python
As a part of the assignment of the applied machine learning course in python ( assignment1 question 2 ) I have to find the class distribution of the breast cancer data set ( sklearn.dataset) . The code I used is give below. the function answer_one converts the data set into a data frame of 569x30 ( 569 instances and 30 features). The code gives me an error which states AttributeError: 'tuple' object has no attribute 'target'. Can anyone help?

The code is

```<code>def answer_two():
    cancerdf = answer_one()
    counts = cancerdf.target.value_counts(ascending=True)
    counts.index = "malignant benign".split()
    return counts
answer_two()
</code>```

答:
```<code>def answer_two():

    cancerdf = answer_one()
    counts = cancerdf.target.value_counts(ascending = True)
    target = pd.Series(counts)
    target.index=['malignant', 'benign']

    return target

answer_two()
</code>```

<p>"This will return a series of index = ['malignant', 'benign']"</p>

Body:
As a part of the assignment of the applied machine learning course in python ( assignment1 question 2 ) I have to find the class distribution of the breast cancer data set ( sklearn.dataset) . The code I used is give below. the function answer_one converts the data set into a data frame of 569x30 ( 569 instances and 30 features). The code gives me an error which states AttributeError: 'tuple' object has no attribute 'target'. Can anyone help?

The code is

def answer_two():
    cancerdf = answer_one()
    counts = cancerdf.target.value_counts(ascending=True)
    counts.index = "malignant benign".split()
    return counts
answer_two()

Body:
def answer_two():

    cancerdf = answer_one()
    counts = cancerdf.target.value_counts(ascending = True)
    target = pd.Series(counts)
    target.index=['malignant', 'benign']

    return target

answer_two()

"This will return a series of index = ['malignant', 'benign']"


问:
How can I count the number of unique elements in an array using NodeJS?
I have a csv file with one particular column. This column has multiple rows, each row with an array comprising of multiple elements. Following are four sample rows in the csv file:

```<code>['Rose', 'Lily', 'Jasmine', 'Rose']

['Google', 'Microsoft', 'Apple', 'Apple', 'Uber', 'Google']

['Norway', 'Norway', 'Norway']

[]
</code>```

I want to count the number of unique elements in each row/array.

The output for the above four sample rows should be in an array as follows:

```<code>[3, 4, 1, 0]
</code>```

Please note that the last row/array is null and hence has 0 elements in it.

This is my code so far:

```<code>const csv = require('csv-parser')
const fs = require('fs')
const results = [];

fs.createReadStream('filepath/filename.csv')
.pipe(csv())
.on('data', (data) => results.push(data))
.on('end', () => {

    var Column_Name = []

    for (var item in results) {
        Column_Name.push(results[item]["Column_Name"])
        console.log(countUnique(Column_Name))
        console.log('Column_Name'.length)
    }
});
</code>```

答:
Look at sets for javascript. A set is a data structure that only allows unique elements, you could convert your array to a set and then count the elements in the set. Here is an example:</p>

```<code>var arr = [55, 44, 65, 55];
var set = new Set(arr);
console.log(set.size === arr.length);
</code>```

Body:
I have a csv file with one particular column. This column has multiple rows, each row with an array comprising of multiple elements. Following are four sample rows in the csv file:

['Rose', 'Lily', 'Jasmine', 'Rose']

['Google', 'Microsoft', 'Apple', 'Apple', 'Uber', 'Google']

['Norway', 'Norway', 'Norway']

[]

I want to count the number of unique elements in each row/array.

The output for the above four sample rows should be in an array as follows:

[3, 4, 1, 0]

Please note that the last row/array is null and hence has 0 elements in it.

This is my code so far:

const csv = require('csv-parser')
const fs = require('fs')
const results = [];

fs.createReadStream('filepath/filename.csv')
.pipe(csv())
.on('data', (data) => results.push(data))
.on('end', () => {

    var Column_Name = []

    for (var item in results) {
        Column_Name.push(results[item]["Column_Name"])
        console.log(countUnique(Column_Name))
        console.log('Column_Name'.length)
    }
});

Body:
Look at sets for javascript. A set is a data structure that only allows unique elements, you could convert your array to a set and then count the elements in the set. Here is an example:

var arr = [55, 44, 65, 55];
var set = new Set(arr);
console.log(set.size === arr.length);


问:
Get Propportions of One Hot Encoded Values While Aggregation - Pandas
I have a df like this,

```<code>    Date        Value

0   2019-03-01  0
1   2019-04-01  1
2   2019-09-01  0
3   2019-10-01  1
4   2019-12-01  0
5   2019-12-20  0
6   2019-12-20  0
7   2020-01-01  0
</code>```

Now, I need to group them by quarter and get the proportions of 1 and 0. So, I get my final output like this,

```<code>  Date          Value1 Value0

0 2019-03-31    0      1
1 2019-06-30    1      0
2 2019-09-30    0      1
3 2019-12-31    0.25   0.75
4 2020-03-31    0      1
</code>```

I tried the following code, doesn't seem to work.

```<code>def custom_resampler(array):
    import numpy as np

    return array/np.sum(array)

>>df.set_index('Date').resample('Q')['Value'].apply(custom_resampler)
</code>```

Is there a pandastic way I can achieve my desired output?

答:
Resample by quarter, get the value_counts, and unstack. Next, rename the columns, using the name property of the columns. Last, divide each row value by the total per row : </p>

```<code>df = pd.read_clipboard(sep='\s{2,}', parse_dates = ['Date'])

res = (df
       .resample(rule="Q",on="Date")
       .Value
       .value_counts()
       .unstack("Value",fill_value=0)
      )

res.columns = [f"{res.columns.name}{ent}" for ent in res.columns]

res = res.div(res.sum(axis=1),axis=0)
res

          Value0   Value1
Date
2019-03-31  1.00    0.00
2019-06-30  0.00    1.00
2019-09-30  1.00    0.00
2019-12-31  0.75    0.25
2020-03-31  1.00    0.00
</code>```

Body:
I have a df like this,

    Date        Value

0   2019-03-01  0
1   2019-04-01  1
2   2019-09-01  0
3   2019-10-01  1
4   2019-12-01  0
5   2019-12-20  0
6   2019-12-20  0
7   2020-01-01  0

Now, I need to group them by quarter and get the proportions of 1 and 0. So, I get my final output like this,

  Date          Value1 Value0

0 2019-03-31    0      1
1 2019-06-30    1      0
2 2019-09-30    0      1
3 2019-12-31    0.25   0.75
4 2020-03-31    0      1

I tried the following code, doesn't seem to work.

def custom_resampler(array):
    import numpy as np

    return array/np.sum(array)

>>df.set_index('Date').resample('Q')['Value'].apply(custom_resampler)

Is there a pandastic way I can achieve my desired output?

Body:
Resample by quarter, get the value_counts, and unstack. Next, rename the columns, using the name property of the columns. Last, divide each row value by the total per row :

df = pd.read_clipboard(sep='\s{2,}', parse_dates = ['Date'])

res = (df
       .resample(rule="Q",on="Date")
       .Value
       .value_counts()
       .unstack("Value",fill_value=0)
      )

res.columns = [f"{res.columns.name}{ent}" for ent in res.columns]

res = res.div(res.sum(axis=1),axis=0)
res

          Value0   Value1
Date
2019-03-31  1.00    0.00
2019-06-30  0.00    1.00
2019-09-30  1.00    0.00
2019-12-31  0.75    0.25
2020-03-31  1.00    0.00


问:
Helm import map and array from values.yaml
'I have created a helm chart using  helm create <chart-name>

In values.yaml I added the following map and array

```<code>nodeSelector:
  instance-type: "re"

tolerations:
  - key: "re"
    operator: "Equal"
    value: "true"
    effect: "NoSchedule"
</code>```

I am trying to import these in templates/deployment.yaml The config over there looks like with the right indentation

```<code>apiVersion: apps/v1beta2
kind: Deployment
metadata:
  name: {{ include "dummy-app.fullname" . }}
  labels:
    app.kubernetes.io/name: {{ include "dummy-app.name" . }}
    helm.sh/chart: {{ include "dummy-app.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
spec:
  replicas: {{ .Values.replicaCount }}
  selector:
    matchLabels:
      app.kubernetes.io/name: {{ include "dummy-app.name" . }}
      app.kubernetes.io/instance: {{ .Release.Name }}
  template:
    metadata:
      labels:
        app.kubernetes.io/name: {{ include "dummy-app.name" . }}
        app.kubernetes.io/instance: {{ .Release.Name }}
        log_group_name: {{ .Values.logging.log_group_name }}
      annotations:
        jitsi.io/metrics_path: {{.Values.service.metricsPath | default "/actuator/prometheus" | quote }}
        jitsi.io/scrape_port: {{.Values.service.actuatorPort | default "8083" | quote }}
        jitsi.io/should_be_scraped: {{.Values.service.shouldScrapp | default "true" | quote}}
    spec:
      containers:
        - name: {{ .Chart.Name }}
          image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          ports:
            - name: http
              containerPort: {{.Values.service.targetPort}}
              protocol: TCP
            - name: http-actuator
              containerPort: {{.Values.service.actuatorPort}}
              protocol: TCP
          livenessProbe:
            httpGet:
              path: /actuator/health
              port: http-actuator
            initialDelaySeconds: 30
          readinessProbe:
            httpGet:
              path: /actuator/health
              port: http-actuator
            initialDelaySeconds: 30
          env:
            - name: PROFILES
              value: {{ required "Environment name is required." .Values.env.environment | quote }}
          resources:
            {{- toYaml .Values.resources | nindent 12 }}
    {{- with .Values.nodeSelector }}
    nodeSelector:
      {{- toYaml . | nindent 8 }}
    {{- end }}
    {{- with .Values.affinity }}
    affinity:
      {{- toYaml . | nindent 8 }}
    {{- end }}
    {{- with .Values.tolerations }}
    tolerations:
      {{- toYaml . | nindent 8 }}
    {{- end }}
</code>```

when I run this I get:

```<code>Error: validation failed: error validating "": error validating data: [ValidationError(Deployment.spec.template): unknown field "nodeSelector" in io.k8s.api.core.v1.PodTemplateSpec, ValidationError(Deployment.spec.template): unknown field "tolerations" in io.k8s.api.core.v1.PodTemplateSpec]
</code>```

I tried many other ways but none seems to work. My guess is the array and map there is something I need to change in deployment.yaml but I can't figure out how

答:
It seems you're indenting wrongly affinity, nodeSelector and tolerations:

```<code>apiVersion: apps/v1beta2
kind: Deployment
metadata:
  name: {{ include "dummy-app.fullname" . }}
  labels:
    ...
spec:
  replicas: {{ .Values.replicaCount }}
  selector:
    matchLabels:
      ...
  template:
    metadata:
      labels:
        ...
      annotations:
        ...
    spec:
      containers:
        - name: {{ .Chart.Name }}
          image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          ports:
            ...
          livenessProbe:
            ...
          readinessProbe:
            ...
          env:
            ...
          resources:
            ...
    nodeSelector:  # <<< this are at the same level of `spec`
      ...
    affinity:      # <<< this are at the same level of `spec`
      ...
    tolerations:   # <<< this are at the same level of `spec`
      ...
</code>```

The following keys must be at the same level of containers, so indenting with additional two blank spaces should fix your issue.

Body:
'I have created a helm chart using  helm create <chart-name>

In values.yaml I added the following map and array

nodeSelector:
  instance-type: "re"

tolerations:
  - key: "re"
    operator: "Equal"
    value: "true"
    effect: "NoSchedule"

I am trying to import these in templates/deployment.yaml The config over there looks like with the right indentation

apiVersion: apps/v1beta2
kind: Deployment
metadata:
  name: {{ include "dummy-app.fullname" . }}
  labels:
    app.kubernetes.io/name: {{ include "dummy-app.name" . }}
    helm.sh/chart: {{ include "dummy-app.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
spec:
  replicas: {{ .Values.replicaCount }}
  selector:
    matchLabels:
      app.kubernetes.io/name: {{ include "dummy-app.name" . }}
      app.kubernetes.io/instance: {{ .Release.Name }}
  template:
    metadata:
      labels:
        app.kubernetes.io/name: {{ include "dummy-app.name" . }}
        app.kubernetes.io/instance: {{ .Release.Name }}
        log_group_name: {{ .Values.logging.log_group_name }}
      annotations:
        jitsi.io/metrics_path: {{.Values.service.metricsPath | default "/actuator/prometheus" | quote }}
        jitsi.io/scrape_port: {{.Values.service.actuatorPort | default "8083" | quote }}
        jitsi.io/should_be_scraped: {{.Values.service.shouldScrapp | default "true" | quote}}
    spec:
      containers:
        - name: {{ .Chart.Name }}
          image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          ports:
            - name: http
              containerPort: {{.Values.service.targetPort}}
              protocol: TCP
            - name: http-actuator
              containerPort: {{.Values.service.actuatorPort}}
              protocol: TCP
          livenessProbe:
            httpGet:
              path: /actuator/health
              port: http-actuator
            initialDelaySeconds: 30
          readinessProbe:
            httpGet:
              path: /actuator/health
              port: http-actuator
            initialDelaySeconds: 30
          env:
            - name: PROFILES
              value: {{ required "Environment name is required." .Values.env.environment | quote }}
          resources:
            {{- toYaml .Values.resources | nindent 12 }}
    {{- with .Values.nodeSelector }}
    nodeSelector:
      {{- toYaml . | nindent 8 }}
    {{- end }}
    {{- with .Values.affinity }}
    affinity:
      {{- toYaml . | nindent 8 }}
    {{- end }}
    {{- with .Values.tolerations }}
    tolerations:
      {{- toYaml . | nindent 8 }}
    {{- end }}

when I run this I get:

Error: validation failed: error validating "": error validating data: [ValidationError(Deployment.spec.template): unknown field "nodeSelector" in io.k8s.api.core.v1.PodTemplateSpec, ValidationError(Deployment.spec.template): unknown field "tolerations" in io.k8s.api.core.v1.PodTemplateSpec]

I tried many other ways but none seems to work. My guess is the array and map there is something I need to change in deployment.yaml but I can't figure out how

Body:
It seems you're indenting wrongly affinity, nodeSelector and tolerations:

apiVersion: apps/v1beta2
kind: Deployment
metadata:
  name: {{ include "dummy-app.fullname" . }}
  labels:
    ...
spec:
  replicas: {{ .Values.replicaCount }}
  selector:
    matchLabels:
      ...
  template:
    metadata:
      labels:
        ...
      annotations:
        ...
    spec:
      containers:
        - name: {{ .Chart.Name }}
          image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          ports:
            ...
          livenessProbe:
            ...
          readinessProbe:
            ...
          env:
            ...
          resources:
            ...
    nodeSelector:  # <<< this are at the same level of `spec`
      ...
    affinity:      # <<< this are at the same level of `spec`
      ...
    tolerations:   # <<< this are at the same level of `spec`
      ...

The following keys must be at the same level of containers, so indenting with additional two blank spaces should fix your issue.


问:
How do I completely uninstall Deno and its cached packages
I want to uninstall Deno and all of its cached packages. Where it caches its packages? And how to make sure that all of cached packages are uninstalled before installing a new version of Deno.

答:
So here are deno cache locations on your system if you are used default install location:

By default, DENO_DIR is located in $HOME/.deno. However, the user
  could also change its location by modifying the $DENO_DIR environment
  variable. Explicitly setting DENO_DIR is recommended in production.

Also, this is hiararchy structure:

```<code> DIRECTORIES
gen/: Cache for files compiled to JavaScript
deps/: Cache for remote url imported files
  |__ http/: For http imports
  |__ https/: For https imports

# FILES
deno_history.txt: History of Deno REPL
</code>```

So, in general I think that you can clear your deno installation with simple deleting folder $HOME/.deno on your computer. Also, you could try simple uninstall command which depends on your system and install tool you use here are info about installing deno with different tools so try use your tool and correct uninstall command https://github.com/denoland/deno_install

Body:
So here are deno cache locations on your system if you are used default install location:

By default, DENO_DIR is located in $HOME/.deno. However, the user
  could also change its location by modifying the $DENO_DIR environment
  variable. Explicitly setting DENO_DIR is recommended in production.

Also, this is hiararchy structure:

 DIRECTORIES
gen/: Cache for files compiled to JavaScript
deps/: Cache for remote url imported files
  |__ http/: For http imports
  |__ https/: For https imports

# FILES
deno_history.txt: History of Deno REPL

So, in general I think that you can clear your deno installation with simple deleting folder $HOME/.deno on your computer. Also, you could try simple uninstall command which depends on your system and install tool you use here are info about installing deno with different tools so try use your tool and correct uninstall command https://github.com/denoland/deno_install


问:
How to modify the orientation of a
 spanning multiple columns?
I am producing a
 of alphabetically sorted items, which spans over multiple lines. An example of this can be seen here:

http://jsfiddle.net/H4FPw/1/

currently the list is laid out horizontally, as follows:

```<code>a  b  c

d  e  f

g  h  i

j  k  l
</code>```

But clients being clients, I have now been asked to change this so that the list is vertically oriented, as follows:

```<code>a  e  i

b  f  j

c  g  k

d  h  l
</code>```

Unfortunately I don't know how to do this in the nice and tidy way that I've originally done it.

Can somebody please fill me in if this is possible to do with single
 and CSS? Or do I have to make multiple lists?

答:
You can't do it by only changing CSS.

Well, you can if you don't care about IE: http://caniuse.com/#search=multiple%20column

You have to compromise somewhere:

Split the
 into three
s manually.

As hinted at by @PeeHaa, use server-side code to change the order that the
s are output (but still keep them inside one
).

Use JavaScript to reorder the
s. I did this using jQuery here, but it would probably make more sense to use a plugin like this: http://welcome.totheinter.net/columnizer-jquery-plugin/

Title: How to modify the orientation of a <ul> spanning multiple columns?

Body:
I am producing a
 of alphabetically sorted items, which spans over multiple lines. An example of this can be seen here:

http://jsfiddle.net/H4FPw/1/

currently the list is laid out horizontally, as follows:

a  b  c

d  e  f

g  h  i

j  k  l

But clients being clients, I have now been asked to change this so that the list is vertically oriented, as follows:

a  e  i

b  f  j

c  g  k

d  h  l

Unfortunately I don't know how to do this in the nice and tidy way that I've originally done it.

Can somebody please fill me in if this is possible to do with single
 and CSS? Or do I have to make multiple lists?

Body:
You can't do it by only changing CSS.

Well, you can if you don't care about IE: http://caniuse.com/#search=multiple%20column

You have to compromise somewhere:

Split the <ul> into three <ul>s manually.

As hinted at by @PeeHaa, use server-side code to change the order that the <li>s are output (but still keep them inside one <ul>).

Use JavaScript to reorder the <li>s. I did this using jQuery here, but it would probably make more sense to use a plugin like this: http://welcome.totheinter.net/columnizer-jquery-plugin/


问:
How to collapse 2D scatter plot into a dot plot?
I have a very large 2d array of shape (186295, 2) with the first element of every 2-element sub-array being x and the second element being y. Here is how I produce the scatter plot by separating x and y components in matplotlib:

```<code>ax.scatter(A[:, 0]+np.random.uniform(-.02, .02, A.shape[0]), A[:, 1], s=2, color='b', alpha=0.5, zorder=3)
</code>```

However, I would like

all points with x-value in the range [8,9.2] be shown as a dot plot at the mid point x=8.6,

all points with x-value in the range [9.2,10.4] be shown as a dot plot at the mid point x=9.8,

all points with x-value in the range [10.4,12.2] be shown as a dot plot at the mid point x=11.3.

Your help is greatly appreciated,

答:
You can use np.select:

Example:

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

n=100
x = np.random.uniform(8, 12, n)
y = np.random.uniform(.01, 1, n)
a = np.array(list(zip(x,y)))

fig,ax = plt.subplots(2, sharex=True)
ax[0].scatter(a[:,0], a[:,1])
ax[0].title.set_text('Scatter Plot')

conditions = [a[:,0]<=8, a[:,0]<=9.2, a[:,0]<=10.4, a[:,0]<=12.2, a[:,0]>12.2]
choices = [a[:,0], 8.6, 9.8, 11.3, a[:,0]]
a[:,0] = np.select(conditions, choices)

ax[1].scatter(a[:,0], a[:,1])
ax[1].title.set_text('Dot Plot')
</code>```

Result:

Another possibility is using np.digitize which saves some typing as it uses a list of bins (upper bounds) instead of a list of conditions.

Body:
I have a very large 2d array of shape (186295, 2) with the first element of every 2-element sub-array being x and the second element being y. Here is how I produce the scatter plot by separating x and y components in matplotlib:

ax.scatter(A[:, 0]+np.random.uniform(-.02, .02, A.shape[0]), A[:, 1], s=2, color='b', alpha=0.5, zorder=3)

However, I would like

all points with x-value in the range [8,9.2] be shown as a dot plot at the mid point x=8.6,

all points with x-value in the range [9.2,10.4] be shown as a dot plot at the mid point x=9.8,

all points with x-value in the range [10.4,12.2] be shown as a dot plot at the mid point x=11.3.

Your help is greatly appreciated,

Body:
You can use np.select:

Example:

import numpy as np
from matplotlib import pyplot as plt

n=100
x = np.random.uniform(8, 12, n)
y = np.random.uniform(.01, 1, n)
a = np.array(list(zip(x,y)))

fig,ax = plt.subplots(2, sharex=True)
ax[0].scatter(a[:,0], a[:,1])
ax[0].title.set_text('Scatter Plot')

conditions = [a[:,0]<=8, a[:,0]<=9.2, a[:,0]<=10.4, a[:,0]<=12.2, a[:,0]>12.2]
choices = [a[:,0], 8.6, 9.8, 11.3, a[:,0]]
a[:,0] = np.select(conditions, choices)

ax[1].scatter(a[:,0], a[:,1])
ax[1].title.set_text('Dot Plot')

Result:

Another possibility is using np.digitize which saves some typing as it uses a list of bins (upper bounds) instead of a list of conditions.


问:
Node express app using cluster is not working
I have an application that is using node.js (express) as backend.
I am now trying to use node.js cluster to improve the application performance but with no luck...

Here's my working app.js :

```<code>import { Server } from "./server";
import { Debug } from "./utils/Debug";
const cluster = require("cluster");
const http = require("http");
const numCPUs = require("os").cpus().length;
const httpPort = 3000;

 var app = Server.bootstrap().app;
 app.set("port", httpPort);
 var httpServer = http.createServer(app);
 httpServer.listen(httpPort);
</code>```

And here is the code using cluster (which is not working) :

```<code>import { Server } from "./server";
import { Debug } from "./utils/Debug";
const cluster = require("cluster");
const http = require("http");
const numCPUs = require("os").cpus().length;
const httpPort = 3000;

Debug.log(numCPUs + " CPU(s)!");
if (cluster.isMaster) {
  // Fork workers.
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  // If a worker dies, log it to the console and start another worker.
  cluster.on("exit", function (worker, code, signal) {
    console.log("Worker " + worker.process.pid + " died.");
    cluster.fork();
  });
  cluster.on("online", function (worker) {
    console.log("Worker " + worker.process.pid + " is online");
  });

  // Log when a worker starts listening
  cluster.on("listening", function (worker, address) {
    console.log("Worker started with PID " + worker.process.pid + ".");
  });
} else {
  /**
   * Create HTTP server.
   */
  var app = Server.bootstrap().app;
  app.set("port", httpPort);
  var httpServer = http.createServer(app);
  httpServer.listen(httpPort);
}
</code>```

When I run the above my localhost:3000 is not listening.

What is wrong here ?

Thank you.

答:
I decided to let PM2 manage the cluster thing.
So I installed it and manage my application with it using a ecosystem.config.js file like this :

```<code>module.exports = {
  apps: [
    {
      name: "myApp",
      script: "./dist/app.js",
      instances: "max",
      exec_mode: "cluster",
      max_memory_restart: "300M",
      error_file: 'err.log',
      out_file: 'out.log',
      log_file: 'combined.log',
      time: true,
      env: {
        NODE_ENV: "development",
      },
      env_production: {
        NODE_ENV: "production",
      },
    },
  ],
};
</code>```

I hope this will help.

Body:
I have an application that is using node.js (express) as backend.
I am now trying to use node.js cluster to improve the application performance but with no luck...

Here's my working app.js :

import { Server } from "./server";
import { Debug } from "./utils/Debug";
const cluster = require("cluster");
const http = require("http");
const numCPUs = require("os").cpus().length;
const httpPort = 3000;

 var app = Server.bootstrap().app;
 app.set("port", httpPort);
 var httpServer = http.createServer(app);
 httpServer.listen(httpPort);

And here is the code using cluster (which is not working) :

import { Server } from "./server";
import { Debug } from "./utils/Debug";
const cluster = require("cluster");
const http = require("http");
const numCPUs = require("os").cpus().length;
const httpPort = 3000;

Debug.log(numCPUs + " CPU(s)!");
if (cluster.isMaster) {
  // Fork workers.
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  // If a worker dies, log it to the console and start another worker.
  cluster.on("exit", function (worker, code, signal) {
    console.log("Worker " + worker.process.pid + " died.");
    cluster.fork();
  });
  cluster.on("online", function (worker) {
    console.log("Worker " + worker.process.pid + " is online");
  });

  // Log when a worker starts listening
  cluster.on("listening", function (worker, address) {
    console.log("Worker started with PID " + worker.process.pid + ".");
  });
} else {
  /**
   * Create HTTP server.
   */
  var app = Server.bootstrap().app;
  app.set("port", httpPort);
  var httpServer = http.createServer(app);
  httpServer.listen(httpPort);
}

When I run the above my localhost:3000 is not listening.

What is wrong here ?

Thank you.

Body:
I decided to let PM2 manage the cluster thing.
So I installed it and manage my application with it using a ecosystem.config.js file like this :

module.exports = {
  apps: [
    {
      name: "myApp",
      script: "./dist/app.js",
      instances: "max",
      exec_mode: "cluster",
      max_memory_restart: "300M",
      error_file: 'err.log',
      out_file: 'out.log',
      log_file: 'combined.log',
      time: true,
      env: {
        NODE_ENV: "development",
      },
      env_production: {
        NODE_ENV: "production",
      },
    },
  ],
};

I hope this will help.


问:
Why properties of an XMLHttpRequest object are only printable through console.log()?
```<code>var obj = new XMLHttpRequest();
console.log("Object.keys():",Object.keys(obj));
console.log("Object.getOwnPropertyNames():",Object.getOwnPropertyNames(obj))
console.log("Object.entries():",Object.entries(obj))
console.log("JSON.stringify():",JSON.stringify(obj))

console.log("console.log:"); console.log(obj)
</code>```

output:

Object.keys(): []

  Object.getOwnPropertyNames(): []

  Object.entries(): []

  JSON.stringify(): {}

  console.log:

  XMLHttpRequest {onreadystatechange: null, readyState: 0, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}

How can I create such an object in javascript, whose properties are only printed using console.log(obj), but not returned by any of the above functions?

I have already tried to create objects using constructor function, object.create() (with enumerable:false),  Object.assign(), using getters, instatiating from a class, instatiating from an extended class e.t.c

答:
All the properties on an XMLHttpRequest instance are inherited properties, what i mean by that is that they don't exist on the instance itself but rather on its prototype chain.

This explains why

```<code>const x = new XMLHttpRequest()
// all these methods consider only instance properties (owned properties) and thats why they return empty results
console.log(Object.keys(x)) // []
console.log(Object.getOwnPropertyNames(x)) // []
console.log(Object.entries(x)) // []
console.log(JSON.stringify(x)) // {}

// however if you try this you will get the results you want

console.log(Object.keys(x.__proto__)) // will not return symbol keys
console.log(Object.getOwnPropertyDescriptors(x.__proto__)) // will return descriptiors of every property whether its symbol or not

// you can see these results also by logging the xmlRequest, and looking at its __proto__ property in the console

// i will be calling the XMLHttpRequest instance for short as xmlRequest
</code>```

You can create such an object simply like this

```<code>class A {}
A.prototype.someProperty = 10
const a = new A()
// again if you try these you will get results like the XMLHttpRequest instance
console.log(Object.keys(a)) // []
console.log(Object.getOwnPropertyNames(a)) // []
console.log(Object.entries(a)) // []
console.log(JSON.stringify(a)) // {}
</code>```

however when you try to console.log(a) you won't see the someProperty like you do with the xmlRequest instance, and this is expected, since it is an inherited property. The reason that you see these properties when you log the xmlRequest is that this object is recieving special treatment.

Luckily you can recreate such a special treatment using chrome custom object formatters, for this to work you have to enable custom formatters from chrome developer tools settings

```<code>window.devtoolsFormatters = [{
    header: function(obj){
        if (!(obj instanceof A)){
         return null;
        }
        // to get the exact results like the xmlRequest, you need to remove quotes from the object keys in the json string, can be done with a regex
        return ["div",{}, JSON.stringify(obj.__proto__)]
    },
    hasBody: function(){
        return false;
    }
}]

class A {}
A.prototype.someProperty = 10

console.log(new A()) // {"someProperty":10}

</code>```

Body:
var obj = new XMLHttpRequest();
console.log("Object.keys():",Object.keys(obj));
console.log("Object.getOwnPropertyNames():",Object.getOwnPropertyNames(obj))
console.log("Object.entries():",Object.entries(obj))
console.log("JSON.stringify():",JSON.stringify(obj))

console.log("console.log:"); console.log(obj)

output:

Object.keys(): []

  Object.getOwnPropertyNames(): []

  Object.entries(): []

  JSON.stringify(): {}

  console.log:

  XMLHttpRequest {onreadystatechange: null, readyState: 0, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}

How can I create such an object in javascript, whose properties are only printed using console.log(obj), but not returned by any of the above functions?

I have already tried to create objects using constructor function, object.create() (with enumerable:false),  Object.assign(), using getters, instatiating from a class, instatiating from an extended class e.t.c

Body:
All the properties on an XMLHttpRequest instance are inherited properties, what i mean by that is that they don't exist on the instance itself but rather on its prototype chain.

This explains why

const x = new XMLHttpRequest()
// all these methods consider only instance properties (owned properties) and thats why they return empty results
console.log(Object.keys(x)) // []
console.log(Object.getOwnPropertyNames(x)) // []
console.log(Object.entries(x)) // []
console.log(JSON.stringify(x)) // {}

// however if you try this you will get the results you want

console.log(Object.keys(x.__proto__)) // will not return symbol keys
console.log(Object.getOwnPropertyDescriptors(x.__proto__)) // will return descriptiors of every property whether its symbol or not

// you can see these results also by logging the xmlRequest, and looking at its __proto__ property in the console

// i will be calling the XMLHttpRequest instance for short as xmlRequest

You can create such an object simply like this

class A {}
A.prototype.someProperty = 10
const a = new A()
// again if you try these you will get results like the XMLHttpRequest instance
console.log(Object.keys(a)) // []
console.log(Object.getOwnPropertyNames(a)) // []
console.log(Object.entries(a)) // []
console.log(JSON.stringify(a)) // {}

however when you try to console.log(a) you won't see the someProperty like you do with the xmlRequest instance, and this is expected, since it is an inherited property. The reason that you see these properties when you log the xmlRequest is that this object is recieving special treatment.

Luckily you can recreate such a special treatment using chrome custom object formatters, for this to work you have to enable custom formatters from chrome developer tools settings

window.devtoolsFormatters = [{
    header: function(obj){
        if (!(obj instanceof A)){
         return null;
        }
        // to get the exact results like the xmlRequest, you need to remove quotes from the object keys in the json string, can be done with a regex
        return ["div",{}, JSON.stringify(obj.__proto__)]
    },
    hasBody: function(){
        return false;
    }
}]

class A {}
A.prototype.someProperty = 10

console.log(new A()) // {"someProperty":10}


问:
Vue Js: How to add serial number column in Vue Data Table Component
I am using <v-data-table> component to show data table in in my app. Is there any way to add the serial number column in this data-table. which starts from 1 to length of my articles array.

and it should start from 1 if any article with any id comes to first.

答:
There is no built-in way to do this, but you can achieve it by adding a computed property and use .map() method to add a new property to each items like sno, which stands for serial number. You can rename it anything you want.

```<code>computed: {
   itemsWithSno() {
      return this.desserts.map((d, index) => ({ ...d, sno: index + 1 }))
   }
},
</code>```

Next, just add a new column in header array to map this new property like:

```<code>{
   text: 'Serial #',
   value: 'sno'
},
</code>```

The value here needs to be exactly same as the new property name sno that you have added in the computed property.

Next, just update v-data-table items prop to use the computed property itemsWithSno instead of the original array like:

```<code><v-data-table :headers="headers" :items="itemsWithSno">
</v-data-table>
</code>```

That's it.

Working Demo:

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  computed: {
    itemsWithSno() {
      return this.desserts.map((d, index) => ({ ...d, sno: index + 1 }))
    }
  },
  data() {
    return {
      headers: [{
          text: 'Serial #',
          value: 'sno'
        },
        {
          text: 'Dessert (100g serving)',
          align: 'start',
          sortable: false,
          value: 'name',
        },
        {
          text: 'Calories',
          value: 'calories'
        },
        {
          text: 'Fat (g)',
          value: 'fat'
        }
      ],
      desserts: [{
          name: 'Frozen Yogurt',
          calories: 159,
          fat: 6.0
        },
        {
          name: 'Ice cream sandwich',
          calories: 237,
          fat: 9.0
        },
        {
          name: 'Eclair',
          calories: 262,
          fat: 16.0
        },
        {
          name: 'Cupcake',
          calories: 305,
          fat: 3.7
        },
        {
          name: 'Gingerbread',
          calories: 356,
          fat: 16.0
        }
      ],
    }
  },
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/font@5.x/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js"></script>

<div id="app">
  <v-app>
    <v-main>
      <v-container>
        <v-data-table :headers="headers" :items="itemsWithSno" class="elevation-1">
        </v-data-table>
      </v-container>
    </v-main>
  </v-app>
</div></code>```

Body:
There is no built-in way to do this, but you can achieve it by adding a computed property and use .map() method to add a new property to each items like sno, which stands for serial number. You can rename it anything you want.

computed: {
   itemsWithSno() {
      return this.desserts.map((d, index) => ({ ...d, sno: index + 1 }))
   }
},

Next, just add a new column in header array to map this new property like:

{
   text: 'Serial #',
   value: 'sno'
},

The value here needs to be exactly same as the new property name sno that you have added in the computed property.

Next, just update v-data-table items prop to use the computed property itemsWithSno instead of the original array like:

<v-data-table :headers="headers" :items="itemsWithSno">
</v-data-table>

That's it.

Working Demo:

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  computed: {
    itemsWithSno() {
      return this.desserts.map((d, index) => ({ ...d, sno: index + 1 }))
    }
  },
  data() {
    return {
      headers: [{
          text: 'Serial #',
          value: 'sno'
        },
        {
          text: 'Dessert (100g serving)',
          align: 'start',
          sortable: false,
          value: 'name',
        },
        {
          text: 'Calories',
          value: 'calories'
        },
        {
          text: 'Fat (g)',
          value: 'fat'
        }
      ],
      desserts: [{
          name: 'Frozen Yogurt',
          calories: 159,
          fat: 6.0
        },
        {
          name: 'Ice cream sandwich',
          calories: 237,
          fat: 9.0
        },
        {
          name: 'Eclair',
          calories: 262,
          fat: 16.0
        },
        {
          name: 'Cupcake',
          calories: 305,
          fat: 3.7
        },
        {
          name: 'Gingerbread',
          calories: 356,
          fat: 16.0
        }
      ],
    }
  },
})

<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/font@5.x/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js"></script>

<div id="app">
  <v-app>
    <v-main>
      <v-container>
        <v-data-table :headers="headers" :items="itemsWithSno" class="elevation-1">
        </v-data-table>
      </v-container>
    </v-main>
  </v-app>
</div>


问:
New to Angular 9, redirecting works but going directly to URL does not
I have a very simple routing module in Angular 9.

```<code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CalculatorsComponent } from './calculators/calculators.component';

const routes: Routes = [
  { path: 'calculators', component: CalculatorsComponent },
  { path: '', redirectTo: '/calculators', pathMatch: 'full' },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
</code>```

I'm running a local server, and when I go to http://localhost:4200, it properly redirects me to http://localhost:4200/calculators. However, if I try to access http://localhost:4200/calculators directly either by entering it in  my address bar or by refreshing the page after it redirects, I get a 404 status code and Cannot GET /calculators as a response.

I feel like this is just how Angular works as a Single Page Application, but please correct me if I'm wrong. If this is expected, how would I deal with my website when a user tries to navigate to http://localhost:4200/calculators. I would expect that they should be able to access that URL without having to navigate through the root view to the /calculators view.

答:
The problem is in how you run the angular app.

If it's inside of nginx or apache you need to configure rewrites.

for nginx

```<code>    location / {
        index index.html;
        try_files $uri /index.html;
    }
</code>```

for apache you need to add / change .htaccess in the root dir

```<code>RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.html
</code>```

Body:
I have a very simple routing module in Angular 9.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CalculatorsComponent } from './calculators/calculators.component';

const routes: Routes = [
  { path: 'calculators', component: CalculatorsComponent },
  { path: '', redirectTo: '/calculators', pathMatch: 'full' },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

I'm running a local server, and when I go to http://localhost:4200, it properly redirects me to http://localhost:4200/calculators. However, if I try to access http://localhost:4200/calculators directly either by entering it in  my address bar or by refreshing the page after it redirects, I get a 404 status code and Cannot GET /calculators as a response.

I feel like this is just how Angular works as a Single Page Application, but please correct me if I'm wrong. If this is expected, how would I deal with my website when a user tries to navigate to http://localhost:4200/calculators. I would expect that they should be able to access that URL without having to navigate through the root view to the /calculators view.

Body:
The problem is in how you run the angular app.

If it's inside of nginx or apache you need to configure rewrites.

for nginx

    location / {
        index index.html;
        try_files $uri /index.html;
    }

for apache you need to add / change .htaccess in the root dir

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.html