问:
Dash app deployed on Heroku cannot read CSV file
I'm trying to use Heroku to deploy my Dash app, which is supposed to read data from a local CSV file. The deployment was successful, but if I open the URL of the app, it gives me an Application Error.

I have checked the Heroku logs and I found a FileNotFoundError which tells me the CSV file from which the app reads the data does not exist, but it works if I run the app locally. In fact, the CSV file exists in my directory, so I want to know if there's another way to go about this.

EDIT: Actually, this is how my app.py code starts. The FileNotFoundError points to the part where I read the CSV file with pandas.
How can I get my app to read the CSV file?

import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_table as tablefrom

from dash.dependencies import Input, Output
import plotly as py
import plotly.graph_objs as go
import numpy as np
import pandas as pd

filepath='C:\\Users\\DELL\\Desktop\\EDUCATE\\DATA CSV\\crop_prod_estimates_GH.csv'

data=pd.read_csv(filepath,sep=',',thousands=',')
data.dropna(inplace=True)

data[['REGION','DISTRICT','CROP']]=data[['REGION','DISTRICT','CROP']].astype('category')
data.CROP=data.CROP.str.strip()
data.drop(data.columns[0],axis=1,inplace=True)
```

答:
You can store the csv file at the same location where your app.py exists.

Change from:

```<code>filepath='C:\\Users\\DELL\\Desktop\\EDUCATE\\DATA CSV\\crop_prod_estimates_GH.csv'
</code>```

To:

```<code>filepath='crop_prod_estimates_GH.csv'
</code>```

It should work.

Body:
You can store the csv file at the same location where your app.py exists.

Change from:

filepath='C:\\Users\\DELL\\Desktop\\EDUCATE\\DATA CSV\\crop_prod_estimates_GH.csv'

To:

filepath='crop_prod_estimates_GH.csv'

It should work.


来源: stackexchange

问:
change stylesheet by button click for specific element only
So, this question is based on a piece of homework that I'm currently working on. I was provided with an HTML document and two stylesheets. The HTML document is really simple:

```<code><html>
<head>
   <title>DOM-scripting: change style</title>
   <link rel="stylesheet" href="style/style1.css" id="stylesheet"/>
</head>
<body>
    <nav class="chooseStyle">
        <input type="button" id="style1Button" value="Style 1"/>
        <input type="button" id="style2Button" value="Style 2"/>
    </nav>
    <article>
        <h1>Style change using DOM-scripting</h1>
        <p> sample text </p>
        <p> sample text </p>
        <p> sample text </p>
    </article>
    <nav class="links">
        <ul>
            <li><a href="link">school name</a></li>
            <li><a href="link">school name</a></li>
       </nav>

    <script src="scriptToUse.js"></script>
</body>
</html>
</code>```

style1.css consists of the following:

```<code>body {
    background-color: #676632;
}

input[type="button"] {
    color: #F5F265;
    background-color: #9B9302;
}

article {
    margin-left: 150px;
    margin-right: 150px;
    text-indent: 20px;
    color: #C9C892;
}

h1 {
    color: #EEF1BA;
    text-align: center;
}

a {
    color: #A1FA56;
    text-decoration: none;
    font-weight: bold;
}

ul {
    padding: 0;
}

li {
    list-style-type: none;
}
</code>```

Style2.css consists of the following:

```<code>body {
    color: #EEEEAA;
}

input[type="button"] {
    color: #9B9302;
    background-color: #F5F265;
}

article {
    margin-left: auto;
    margin-right: auto;
    text-align: justify;

    color: #A3A163;
}

h1 {
    color: #AAAA66;
    text-align: left;
}

a {
    color: #CDCF9B;
}

ul {
    padding: 0;
}

li {
    list-style-type: none;
}
</code>```

The first part of the exercise states that I need to create a javascript file which allows the stylesheet for the webpage to change according to the button that was clicked. The first button refers to the first stylesheet and the second refers to the second stylesheet. I figured this out fairly easy and everything works fine.

However, the second part of the exercise states the following: "Now edit the javascript file so that only the style of the article is changed when the buttons are clicked. DO NOT edit the CSS file." Meaning that the href for the stylesheets should still be changed, like in the first part, but now it may only affect the style of the article element instead of the style of the whole page.

I have been searching for related questions for the past hour but nothing seems to really provide a solution. I have read some questions stating that it is impossible to apply a stylesheet only to a specific element without changing anything in the stylesheet itself. Keep in mind that I am only in my first year of college and have only just begun learning javascript, meaning that a solution should not be that hard to find. I guess?

The Javascript code I wrote so far:

```<code>'use strict';

const handleLoad = () => {
    let style1 = document.getElementById('style1Button');
    let style2 = document.getElementById('style2Button');
    style1.addEventListener('click', handleClick);
    style2.addEventListener('click', handleClick);
};

const handleClick = (event) => {
    if(event.target.value === "Style 1") {
        document.getElementById("stylesheet").href = "style/style1.css";
        // should only change article style
        // currently still referring to the whole document
    } else {
        document.getElementById("stylesheet").href = "style/style2.css";
        // should also only change article style
        // also still referring to the whole document
    }
};

window.addEventListener('load', handleLoad);
</code>```

Is there any way I could block the CSS rules for all elements except the article element? Or maybe change the classes or ID's for the elements that should not be affected?

Thanks a lot in advance :)

This is what finally solved it. (code is probably not as compact and correct as it could be but it works so I'm more than happy :D):

```<code>'use strict';

const handleLoad = () => {
    let style1 = document.getElementById('style1Button');
    let style2 = document.getElementById('style2Button');
    style1.addEventListener('click', handleClick);
    style2.addEventListener('click', handleClick);
    makeShadow();
};

const handleClick = (event) => {
    let article = document.querySelector('article');
    let shadow = article.shadowRoot;

    let style = event.target.value === "Style 1" ? "style/style2.css" : "style/style1.css";

    for(let node of shadow.childNodes) {
        if(node.hasAttribute('href')){
            node.href = style;
        }
    }
};

const makeShadow = () => {
    let article = document.querySelector('article');
    let articleClone = makeClone(article);

    let shadow = article.attachShadow({mode:'open'});

    let link = document.createElement('link');
    link.rel = "stylesheet";
    link.href = 'style/style1.css';

    shadow.appendChild(articleClone);
    shadow.prepend(link);
};

const makeClone = (article) => {
    let clone = article.cloneNode();
    clone.innerHTML = article.innerHTML;
    return clone;
};

window.addEventListener('load', handleLoad);
</code>```

答:
In This case we can make use of shadowRoot as an encapsulation for styles.

The idea is like adding a css file which contains a ton of styles to a page which only have the article element, obviously the other styles won't have any effect.

We can do the same using a shadowRoot put the article in it's own little world and add a file which contains more styles.

The code is heavily commented. If you have any question leave a comment :)

First on load we prepare the shadow Element:

```<code>const handleLoad = () => {

    // Old Code for button handlers still needed
    let style1 = document.getElementById('style1Button');
    let style2 = document.getElementById('style2Button');
    style1.addEventListener('click', handleClick);
    style2.addEventListener('click', handleClick);

    // New Code Below

    // Select the article from the page
    const article = document.querySelector('article');
    // Create an empty div Element to work as a bucket
    const placeholderElement = document.createElement('div');
    // set it's id attribute to select it later
    placeholderElement.setAttribute('id', 'placeholderElementShadowRot')
    // replace the article with our div in the document
    // the article element is not completly lose at this point
    // we still have in the variable article
    article.replaceWith(placeholderElement);
    // attache a shadow to the div element
    const shadow = placeholderElement.attachShadow({ mode: 'open' });
    // sets the shadow's innerHTML equal to article outerHTML
    shadow.innerHTML = article.outerHTML;

    // create a link
    const link = document.createElement('link');
    // set it's href attribute to the first style file
    link.setAttribute("href", 'style1.css');
    // set the rel attribute
    link.setAttribute("rel", "stylesheet");
    // add the link to the shadow
    shadow.appendChild(link)
};
</code>```

And on button click

```<code>const handleClick = (event) => {
    // Select our div we created before using the id
    const placeholderElement = document.querySelector('#placeholderElementShadowRot');
    // since we already attached a shadow
    // we can use it through the property .shadowRoot
    const shadow = placeholderElement.shadowRoot;

    // based on which button we add the relevant style file
    if (event.target.value === "Style 1") {
        shadow.querySelector('link').setAttribute("href", "style1.css")
    } else {
        shadow.querySelector('link').setAttribute("href", "style2.css")
    }
};
</code>```

Note: You have a typo in your JS, The handler is called handleclick lower case click but you're adding an uppercase Click  handleClick to addEventListener

ContentLicense: CC BY-SA 4.0

Body:
So, this question is based on a piece of homework that I'm currently working on. I was provided with an HTML document and two stylesheets. The HTML document is really simple:

   <title>DOM-scripting: change style</title>
   <link rel="stylesheet" href="style/style1.css" id="stylesheet"/>

        <input type="button" id="style1Button" value="Style 1"/>
        <input type="button" id="style2Button" value="Style 2"/>

Style change using DOM-scripting

 sample text

 sample text

 sample text

school name

school name

style1.css consists of the following:

body {
    background-color: #676632;
}

input[type="button"] {
    color: #F5F265;
    background-color: #9B9302;
}

article {
    margin-left: 150px;
    margin-right: 150px;
    text-indent: 20px;
    color: #C9C892;
}

h1 {
    color: #EEF1BA;
    text-align: center;
}

a {
    color: #A1FA56;
    text-decoration: none;
    font-weight: bold;
}

ul {
    padding: 0;
}

li {
    list-style-type: none;
}

Style2.css consists of the following:

body {
    color: #EEEEAA;
}

input[type="button"] {
    color: #9B9302;
    background-color: #F5F265;
}

article {
    margin-left: auto;
    margin-right: auto;
    text-align: justify;

    color: #A3A163;
}

h1 {
    color: #AAAA66;
    text-align: left;
}

a {
    color: #CDCF9B;
}

ul {
    padding: 0;
}

li {
    list-style-type: none;
}

The first part of the exercise states that I need to create a javascript file which allows the stylesheet for the webpage to change according to the button that was clicked. The first button refers to the first stylesheet and the second refers to the second stylesheet. I figured this out fairly easy and everything works fine.

However, the second part of the exercise states the following: "Now edit the javascript file so that only the style of the article is changed when the buttons are clicked. DO NOT edit the CSS file." Meaning that the href for the stylesheets should still be changed, like in the first part, but now it may only affect the style of the article element instead of the style of the whole page.

I have been searching for related questions for the past hour but nothing seems to really provide a solution. I have read some questions stating that it is impossible to apply a stylesheet only to a specific element without changing anything in the stylesheet itself. Keep in mind that I am only in my first year of college and have only just begun learning javascript, meaning that a solution should not be that hard to find. I guess?

The Javascript code I wrote so far:

'use strict';

const handleLoad = () => {
    let style1 = document.getElementById('style1Button');
    let style2 = document.getElementById('style2Button');
    style1.addEventListener('click', handleClick);
    style2.addEventListener('click', handleClick);
};

const handleClick = (event) => {
    if(event.target.value === "Style 1") {
        document.getElementById("stylesheet").href = "style/style1.css";
        // should only change article style
        // currently still referring to the whole document
    } else {
        document.getElementById("stylesheet").href = "style/style2.css";
        // should also only change article style
        // also still referring to the whole document
    }
};

window.addEventListener('load', handleLoad);

Is there any way I could block the CSS rules for all elements except the article element? Or maybe change the classes or ID's for the elements that should not be affected?

Thanks a lot in advance :)

This is what finally solved it. (code is probably not as compact and correct as it could be but it works so I'm more than happy :D):

'use strict';

const handleLoad = () => {
    let style1 = document.getElementById('style1Button');
    let style2 = document.getElementById('style2Button');
    style1.addEventListener('click', handleClick);
    style2.addEventListener('click', handleClick);
    makeShadow();
};

const handleClick = (event) => {
    let article = document.querySelector('article');
    let shadow = article.shadowRoot;

    let style = event.target.value === "Style 1" ? "style/style2.css" : "style/style1.css";

    for(let node of shadow.childNodes) {
        if(node.hasAttribute('href')){
            node.href = style;
        }
    }
};

const makeShadow = () => {
    let article = document.querySelector('article');
    let articleClone = makeClone(article);

    let shadow = article.attachShadow({mode:'open'});

    let link = document.createElement('link');
    link.rel = "stylesheet";
    link.href = 'style/style1.css';

    shadow.appendChild(articleClone);
    shadow.prepend(link);
};

const makeClone = (article) => {
    let clone = article.cloneNode();
    clone.innerHTML = article.innerHTML;
    return clone;
};

window.addEventListener('load', handleLoad);

Body:
In This case we can make use of shadowRoot as an encapsulation for styles.

The idea is like adding a css file which contains a ton of styles to a page which only have the article element, obviously the other styles won't have any effect.

We can do the same using a shadowRoot put the article in it's own little world and add a file which contains more styles.

The code is heavily commented. If you have any question leave a comment :)

First on load we prepare the shadow Element:

const handleLoad = () => {

    // Old Code for button handlers still needed
    let style1 = document.getElementById('style1Button');
    let style2 = document.getElementById('style2Button');
    style1.addEventListener('click', handleClick);
    style2.addEventListener('click', handleClick);

    // New Code Below

    // Select the article from the page
    const article = document.querySelector('article');
    // Create an empty div Element to work as a bucket
    const placeholderElement = document.createElement('div');
    // set it's id attribute to select it later
    placeholderElement.setAttribute('id', 'placeholderElementShadowRot')
    // replace the article with our div in the document
    // the article element is not completly lose at this point
    // we still have in the variable article
    article.replaceWith(placeholderElement);
    // attache a shadow to the div element
    const shadow = placeholderElement.attachShadow({ mode: 'open' });
    // sets the shadow's innerHTML equal to article outerHTML
    shadow.innerHTML = article.outerHTML;

    // create a link
    const link = document.createElement('link');
    // set it's href attribute to the first style file
    link.setAttribute("href", 'style1.css');
    // set the rel attribute
    link.setAttribute("rel", "stylesheet");
    // add the link to the shadow
    shadow.appendChild(link)
};

And on button click

const handleClick = (event) => {
    // Select our div we created before using the id
    const placeholderElement = document.querySelector('#placeholderElementShadowRot');
    // since we already attached a shadow
    // we can use it through the property .shadowRoot
    const shadow = placeholderElement.shadowRoot;

    // based on which button we add the relevant style file
    if (event.target.value === "Style 1") {
        shadow.querySelector('link').setAttribute("href", "style1.css")
    } else {
        shadow.querySelector('link').setAttribute("href", "style2.css")
    }
};

Note: You have a typo in your JS, The handler is called handleclick lower case click but you're adding an uppercase Click  handleClick to addEventListener


问:
Function for linear interpolation of data points based on a fixed continuous increase in the time-variable
I have three treatment groups stored in CIF in my data res. Based on the reproducible example:

```<code>> table(res$CIF)

Control     SSA    SSTR
     35      25       5
</code>```

For each res$CIF, there is an estimated probability res$P of an outcome at time res$time. The probability comes with a 95%-CI as in res$lower and res$upper.

Hence

```<code>> head(res,10)
     CIF          P time       lower     upper
 1: SSTR 0.12500000 1.00 0.032811154 0.4140186
 2: SSTR 0.31250000 2.00 0.143720822 0.5953967
 3: SSTR 0.62500000 3.00 0.402281539 0.8457738
 4: SSTR 0.81250000 4.00 0.597544067 0.9539839
 5: SSTR 0.87500000 5.00 0.672015645 0.9793250
 6:  SSA 0.02777778 0.72 0.003960129 0.1812693
 7:  SSA 0.08333333 1.00 0.027663184 0.2365298
 8:  SSA 0.11111111 1.02 0.043219272 0.2694809
 9:  SSA 0.13888889 1.08 0.060294215 0.3020083
10:  SSA 0.16666667 1.48 0.078561410 0.3338737
</code>```

I need to interpolate res$P and the corresponding res$lower + res$upper linearly at time points not currently given in res$time.

I am looking for a function (or similar solutions - perhaps a solution in dplyr?) that expand res so that res$time ranges from 0 to the maximum res$time for each res$CIF. The res$time should increase continuously by .01.

Ie, from 0 to 105.16, 30.85 and 5.00 by .01, respectively:

```<code>> tapply(res$time,res$CIF,max)
Control     SSA    SSTR
 105.16   30.85    5.00
</code>```

An example of the expected output

```<code># Before interpolation
> head(res[res$CIF=="SSA"],5)
   CIF          P time       lower     upper
1: SSA 0.02777778 0.72 0.003960129 0.1812693
2: SSA 0.08333333 1.00 0.027663184 0.2365298
3: SSA 0.11111111 1.02 0.043219272 0.2694809
4: SSA 0.13888889 1.08 0.060294215 0.3020083
5: SSA 0.16666667 1.48 0.078561410 0.3338737
</code>```

Should give something like

```<code>CIF           P   time       lower        upper
SSA           0   0.00           0            0
SSA interpolate   0.01 interpolate  interpolate
(....)
SSA  0.02777778   0.72 0.003960129    0.1812693
(....)
SSA  0.08333333   1.00 0.027663184    0.2365298
SSA interpolate   1.01 interpolate  interpolate
SSA  0.11111111   1.02 0.043219272    0.2694809
SSA interpolate   1.03 interpolate  interpolate
SSA interpolate   1.04 interpolate  interpolate
SSA interpolate   1.05 interpolate  interpolate
SSA interpolate   1.06 interpolate  interpolate
SSA interpolate   1.07 interpolate  interpolate
SSA  0.13888889   1.08 0.060294215    0.3020083
</code>```

My data res

```<code>res <- structure(list(CIF = c("SSTR", "SSTR", "SSTR", "SSTR", "SSTR",
"SSA", "SSA", "SSA", "SSA", "SSA", "SSA", "SSA", "SSA", "SSA",
"SSA", "SSA", "SSA", "SSA", "SSA", "SSA", "SSA", "SSA", "SSA",
"SSA", "SSA", "SSA", "SSA", "SSA", "SSA", "SSA", "Control", "Control",
"Control", "Control", "Control", "Control", "Control", "Control",
"Control", "Control", "Control", "Control", "Control", "Control",
"Control", "Control", "Control", "Control", "Control", "Control",
"Control", "Control", "Control", "Control", "Control", "Control",
"Control", "Control", "Control", "Control", "Control", "Control",
"Control", "Control", "Control"), P = c(0.125, 0.3125, 0.625,
0.8125, 0.875, 0.0277777777777778, 0.0833333333333333, 0.111111111111111,
0.138888888888889, 0.166666666666667, 0.305555555555556, 0.361111111111111,
0.388888888888889, 0.416666666666667, 0.444444444444445, 0.472222222222222,
0.527777777777778, 0.555555555555556, 0.583333333333333, 0.613095238095238,
0.642857142857143, 0.672619047619048, 0.672619047619048, 0.732142857142857,
0.761904761904762, 0.791666666666667, 0.821428571428572, 0.858630952380953,
0.895833333333333, 0.970238095238095, 0.025, 0.025, 0.025, 0.025,
0.025, 0.05, 0.075, 0.1, 0.125, 0.15, 0.15, 0.175, 0.2, 0.225,
0.25, 0.275, 0.3, 0.325, 0.35, 0.375, 0.4, 0.425, 0.45, 0.478333333333333,
0.506666666666667, 0.535, 0.565909090909091, 0.596818181818182,
0.631590909090909, 0.666363636363636, 0.701136363636364, 0.735909090909091,
0.770681818181818, 0.805454545454545, 0.840227272727273), time = c(1,
2, 3, 4, 5, 0.72, 1, 1.02, 1.08, 1.48, 2, 2.76, 2.82, 2.83, 3,
3.08, 3.57, 5.07, 5.49, 8.03, 9, 9.2, 9.25, 10.8, 11, 11.04,
14.2, 15.05, 21.42, 30.85, 0.23, 0.26, 0.49, 0.53, 0.69, 3.15,
3.25, 4.5, 5.12, 5.78, 6.67, 7.65, 7.79, 7.85, 9, 9.99, 11.37,
12.68, 13.11, 15.05, 15.83, 16.89, 18.17, 22.7, 23.59, 29.6,
32.65, 35.81, 43, 43.79, 45.37, 46.45, 46.65, 69.02, 105.16),
    lower = c(0.0328111539708764, 0.143720822077878, 0.402281538850257,
    0.597544067030214, 0.672015645447537, 0.00396012891352548,
    0.0276631838805069, 0.0432192720492351, 0.0602942151317983,
    0.0785614100173507, 0.18231512406141, 0.228150254051563,
    0.251830579852024, 0.275990636539769, 0.300615683301302,
    0.32569554091635, 0.377199241260733, 0.403622389357051, 0.430498943169836,
    0.45921123839169, 0.48851369241709, 0.518429809974778, 0.518429809974778,
    0.580243253031609, 0.612241368451204, 0.645062949439568,
    0.678811652981003, 0.718192077960655, 0.761035083198697,
    0.86875565093952, 0.00355981698627006, 0.00355981698627006,
    0.00355981698627006, 0.00355981698627006, 0.00355981698627006,
    0.0127444761396915, 0.0248237564000704, 0.0387548083597935,
    0.0540289278928447, 0.0703518337133965, 0.0703518337133965,
    0.0875349177801499, 0.105448804967606, 0.124000413393049,
    0.143120415258911, 0.162755851975246, 0.182865529959695,
    0.20341701986178, 0.22438463188234, 0.245748013164318, 0.267491158005832,
    0.289601702577961, 0.312070423267255, 0.337084153386502,
    0.362632734261147, 0.388713550110491, 0.417009262625303,
    0.446060748331539, 0.478344299849033, 0.511927776545623,
    0.546903575783177, 0.583428286459313, 0.621755981338108,
    0.662308487815083, 0.705837515898454), upper = c(0.414018563190984,
    0.595396721303893, 0.845773808747176, 0.953983876394769,
    0.979324974514942, 0.181269269945454, 0.236529759895451,
    0.269480930499581, 0.302008337476789, 0.333873667543882,
    0.483459160112475, 0.539346001089099, 0.566541091565836,
    0.593255777919075, 0.619498863619302, 0.645275418976181,
    0.695431242848002, 0.719802607844794, 0.743691288858428,
    0.769343219994671, 0.794279647503738, 0.818479990760844,
    0.818479990760844, 0.864527983506889, 0.886263823263894,
    0.907030011614637, 0.926703065538918, 0.951295364401731,
    0.971948922997515, 0.997717755344036, 0.164514540888494,
    0.164514540888494, 0.164514540888494, 0.164514540888494,
    0.164514540888494, 0.185453879855473, 0.214782436042548,
    0.244858945502003, 0.274592902916402, 0.303763783420835,
    0.303763783420835, 0.332343773644891, 0.360355238540763,
    0.387832132523894, 0.414808316400823, 0.441314057995926,
    0.467375240079267, 0.493013472868414, 0.518246474164134,
    0.543088485840094, 0.56755064509021, 0.591641285440807, 0.615366163389952,
    0.642996938577391, 0.669919078034907, 0.696160621236471,
    0.724897048548371, 0.752630120302531, 0.78395657751485, 0.813600779732339,
    0.841596636148257, 0.867931528334935, 0.892542509012415,
    0.91530398695896, 0.935999137248638)), row.names = c(NA,
-65L), class = c("data.table", "data.frame"))
</code>```

答:
Here's an approach with complete from tidyr and na.approx from zoo:

```<code>library(dplyr)
library(tidyr)
library(zoo)
res %>%
  group_by(CIF) %>%
  complete(time = seq(0, max(time), by = 0.01)) %>%
  mutate_at(vars(P,lower,upper),
            .funs = list(~ifelse(time == 0 & is.na(.), 0, .))) %>%
  mutate_at(vars(P,lower,upper),
            .funs = list(~ zoo::na.approx(.)))
</code>```

If you wanted to use a non-linear approach, you might try spline:

```<code>res %>%
  group_by(CIF) %>%
  complete(time = seq(0, max(time), by = 0.01)) %>%
  mutate_at(vars(P,lower,upper),
            .funs = list(~ifelse(time == 0 & is.na(.), 0, .))) %>%
  mutate_at(vars(P,lower,upper),
            .funs = list(~ spline(time, . ,n=n())$y))
</code>```

This doesn't replace the NAs, but instead replaces all the values with the interpolated ones.

Body:
I have three treatment groups stored in CIF in my data res. Based on the reproducible example:

> table(res$CIF)

Control     SSA    SSTR
     35      25       5

For each res$CIF, there is an estimated probability res$P of an outcome at time res$time. The probability comes with a 95%-CI as in res$lower and res$upper.

Hence

> head(res,10)
     CIF          P time       lower     upper
 1: SSTR 0.12500000 1.00 0.032811154 0.4140186
 2: SSTR 0.31250000 2.00 0.143720822 0.5953967
 3: SSTR 0.62500000 3.00 0.402281539 0.8457738
 4: SSTR 0.81250000 4.00 0.597544067 0.9539839
 5: SSTR 0.87500000 5.00 0.672015645 0.9793250
 6:  SSA 0.02777778 0.72 0.003960129 0.1812693
 7:  SSA 0.08333333 1.00 0.027663184 0.2365298
 8:  SSA 0.11111111 1.02 0.043219272 0.2694809
 9:  SSA 0.13888889 1.08 0.060294215 0.3020083
10:  SSA 0.16666667 1.48 0.078561410 0.3338737

I need to interpolate res$P and the corresponding res$lower + res$upper linearly at time points not currently given in res$time.

I am looking for a function (or similar solutions - perhaps a solution in dplyr?) that expand res so that res$time ranges from 0 to the maximum res$time for each res$CIF. The res$time should increase continuously by .01.

Ie, from 0 to 105.16, 30.85 and 5.00 by .01, respectively:

> tapply(res$time,res$CIF,max)
Control     SSA    SSTR
 105.16   30.85    5.00

An example of the expected output

# Before interpolation
> head(res[res$CIF=="SSA"],5)
   CIF          P time       lower     upper
1: SSA 0.02777778 0.72 0.003960129 0.1812693
2: SSA 0.08333333 1.00 0.027663184 0.2365298
3: SSA 0.11111111 1.02 0.043219272 0.2694809
4: SSA 0.13888889 1.08 0.060294215 0.3020083
5: SSA 0.16666667 1.48 0.078561410 0.3338737

Should give something like

CIF           P   time       lower        upper
SSA           0   0.00           0            0
SSA interpolate   0.01 interpolate  interpolate
(....)
SSA  0.02777778   0.72 0.003960129    0.1812693
(....)
SSA  0.08333333   1.00 0.027663184    0.2365298
SSA interpolate   1.01 interpolate  interpolate
SSA  0.11111111   1.02 0.043219272    0.2694809
SSA interpolate   1.03 interpolate  interpolate
SSA interpolate   1.04 interpolate  interpolate
SSA interpolate   1.05 interpolate  interpolate
SSA interpolate   1.06 interpolate  interpolate
SSA interpolate   1.07 interpolate  interpolate
SSA  0.13888889   1.08 0.060294215    0.3020083

My data res

res <- structure(list(CIF = c("SSTR", "SSTR", "SSTR", "SSTR", "SSTR",
"SSA", "SSA", "SSA", "SSA", "SSA", "SSA", "SSA", "SSA", "SSA",
"SSA", "SSA", "SSA", "SSA", "SSA", "SSA", "SSA", "SSA", "SSA",
"SSA", "SSA", "SSA", "SSA", "SSA", "SSA", "SSA", "Control", "Control",
"Control", "Control", "Control", "Control", "Control", "Control",
"Control", "Control", "Control", "Control", "Control", "Control",
"Control", "Control", "Control", "Control", "Control", "Control",
"Control", "Control", "Control", "Control", "Control", "Control",
"Control", "Control", "Control", "Control", "Control", "Control",
"Control", "Control", "Control"), P = c(0.125, 0.3125, 0.625,
0.8125, 0.875, 0.0277777777777778, 0.0833333333333333, 0.111111111111111,
0.138888888888889, 0.166666666666667, 0.305555555555556, 0.361111111111111,
0.388888888888889, 0.416666666666667, 0.444444444444445, 0.472222222222222,
0.527777777777778, 0.555555555555556, 0.583333333333333, 0.613095238095238,
0.642857142857143, 0.672619047619048, 0.672619047619048, 0.732142857142857,
0.761904761904762, 0.791666666666667, 0.821428571428572, 0.858630952380953,
0.895833333333333, 0.970238095238095, 0.025, 0.025, 0.025, 0.025,
0.025, 0.05, 0.075, 0.1, 0.125, 0.15, 0.15, 0.175, 0.2, 0.225,
0.25, 0.275, 0.3, 0.325, 0.35, 0.375, 0.4, 0.425, 0.45, 0.478333333333333,
0.506666666666667, 0.535, 0.565909090909091, 0.596818181818182,
0.631590909090909, 0.666363636363636, 0.701136363636364, 0.735909090909091,
0.770681818181818, 0.805454545454545, 0.840227272727273), time = c(1,
2, 3, 4, 5, 0.72, 1, 1.02, 1.08, 1.48, 2, 2.76, 2.82, 2.83, 3,
3.08, 3.57, 5.07, 5.49, 8.03, 9, 9.2, 9.25, 10.8, 11, 11.04,
14.2, 15.05, 21.42, 30.85, 0.23, 0.26, 0.49, 0.53, 0.69, 3.15,
3.25, 4.5, 5.12, 5.78, 6.67, 7.65, 7.79, 7.85, 9, 9.99, 11.37,
12.68, 13.11, 15.05, 15.83, 16.89, 18.17, 22.7, 23.59, 29.6,
32.65, 35.81, 43, 43.79, 45.37, 46.45, 46.65, 69.02, 105.16),
    lower = c(0.0328111539708764, 0.143720822077878, 0.402281538850257,
    0.597544067030214, 0.672015645447537, 0.00396012891352548,
    0.0276631838805069, 0.0432192720492351, 0.0602942151317983,
    0.0785614100173507, 0.18231512406141, 0.228150254051563,
    0.251830579852024, 0.275990636539769, 0.300615683301302,
    0.32569554091635, 0.377199241260733, 0.403622389357051, 0.430498943169836,
    0.45921123839169, 0.48851369241709, 0.518429809974778, 0.518429809974778,
    0.580243253031609, 0.612241368451204, 0.645062949439568,
    0.678811652981003, 0.718192077960655, 0.761035083198697,
    0.86875565093952, 0.00355981698627006, 0.00355981698627006,
    0.00355981698627006, 0.00355981698627006, 0.00355981698627006,
    0.0127444761396915, 0.0248237564000704, 0.0387548083597935,
    0.0540289278928447, 0.0703518337133965, 0.0703518337133965,
    0.0875349177801499, 0.105448804967606, 0.124000413393049,
    0.143120415258911, 0.162755851975246, 0.182865529959695,
    0.20341701986178, 0.22438463188234, 0.245748013164318, 0.267491158005832,
    0.289601702577961, 0.312070423267255, 0.337084153386502,
    0.362632734261147, 0.388713550110491, 0.417009262625303,
    0.446060748331539, 0.478344299849033, 0.511927776545623,
    0.546903575783177, 0.583428286459313, 0.621755981338108,
    0.662308487815083, 0.705837515898454), upper = c(0.414018563190984,
    0.595396721303893, 0.845773808747176, 0.953983876394769,
    0.979324974514942, 0.181269269945454, 0.236529759895451,
    0.269480930499581, 0.302008337476789, 0.333873667543882,
    0.483459160112475, 0.539346001089099, 0.566541091565836,
    0.593255777919075, 0.619498863619302, 0.645275418976181,
    0.695431242848002, 0.719802607844794, 0.743691288858428,
    0.769343219994671, 0.794279647503738, 0.818479990760844,
    0.818479990760844, 0.864527983506889, 0.886263823263894,
    0.907030011614637, 0.926703065538918, 0.951295364401731,
    0.971948922997515, 0.997717755344036, 0.164514540888494,
    0.164514540888494, 0.164514540888494, 0.164514540888494,
    0.164514540888494, 0.185453879855473, 0.214782436042548,
    0.244858945502003, 0.274592902916402, 0.303763783420835,
    0.303763783420835, 0.332343773644891, 0.360355238540763,
    0.387832132523894, 0.414808316400823, 0.441314057995926,
    0.467375240079267, 0.493013472868414, 0.518246474164134,
    0.543088485840094, 0.56755064509021, 0.591641285440807, 0.615366163389952,
    0.642996938577391, 0.669919078034907, 0.696160621236471,
    0.724897048548371, 0.752630120302531, 0.78395657751485, 0.813600779732339,
    0.841596636148257, 0.867931528334935, 0.892542509012415,
    0.91530398695896, 0.935999137248638)), row.names = c(NA,
-65L), class = c("data.table", "data.frame"))

Body:
Here's an approach with complete from tidyr and na.approx from zoo:

library(dplyr)
library(tidyr)
library(zoo)
res %>%
  group_by(CIF) %>%
  complete(time = seq(0, max(time), by = 0.01)) %>%
  mutate_at(vars(P,lower,upper),
            .funs = list(~ifelse(time == 0 & is.na(.), 0, .))) %>%
  mutate_at(vars(P,lower,upper),
            .funs = list(~ zoo::na.approx(.)))

If you wanted to use a non-linear approach, you might try spline:

res %>%
  group_by(CIF) %>%
  complete(time = seq(0, max(time), by = 0.01)) %>%
  mutate_at(vars(P,lower,upper),
            .funs = list(~ifelse(time == 0 & is.na(.), 0, .))) %>%
  mutate_at(vars(P,lower,upper),
            .funs = list(~ spline(time, . ,n=n())$y))

This doesn't replace the NAs, but instead replaces all the values with the interpolated ones.


问:
How to setup Corda Node for Production?
After checking some examples and tutorials I wonder if there is a guide how to start a productive Corda Node.

I would expect something like a docker(compose) with Message Server, DB and Web Server (Spring ???) to start the whole infrastructure which enables deployments of new CordApps or updates.

Anyone here who could share a e.g. Jenkins pipeline which could act as blueprint ?

答:
Here are some general steps of deploying a Cordapp.

Install the Corda Node

Implement the Corda Firewall PKI

Generate Bridge and Float keystores for your the Artemis server (message queue)

You can take a look at this official guide for a detailed explanation.

And if you are working on Docker, there is a guide available now here.

For CI/CD, there is a few samples already been done with Jenkins on in the Corda github. Besides you can look at CircleCI for an alternative option

Title: How to setup Corda Node for Production?


问:
hide Navigation Bar only on first page - Swift UI
My app running on Swift UI, and my main page is Home(), In the home page there is NavigationView and NavigationLink(destination: SaveThePlanet()), I have hide the Navigation View on the main page "Home", its also hide in SaveThePlanet().
How can I unhide the navigation back button in the SaveThePlanet() page?

```<code>import SwiftUI

struct Home: View {

    @State var show = false
    @State var showSaveThePlanet = false
    var body: some View {
        NavigationView {
            ZStack {
                Color.gray
                ContentView()
                    .blur(radius: show ? 10 : 0)
                    .scaleEffect(show ? 0.90 : 1)
                    .blur(radius: showSaveThePlanet ? 10 : 0)
                    .scaleEffect(showSaveThePlanet ? 0.90 : 1)
                    .animation(.default)

                leftIcon(show: $show)
                    .offset(x: 0, y: showSaveThePlanet ? 300 : 70)
                    .scaleEffect(show ? 0.90 : 1)
                    .blur(radius: show ? 10 : 0)
                    .animation(.easeInOut)

                SaveThePlanet()
                    .background(Color("Bg"))
                    .cornerRadius(10)
                    .shadow(color: Color("Green-Sh"), radius: 10, x: 0, y: 0)
                    .animation(.spring())
                    .offset(y: showSaveThePlanet ? 120 : UIScreen.main.bounds.height)
                    .padding()

                rightIcon(show: $showSaveThePlanet)
                    .offset(x: 0, y: 70)
                    .animation(.easeInOut)
                    .scaleEffect(show ? 0.90 : 1)
                    .blur(radius: show ? 10 : 0)
                    .opacity(showSaveThePlanet ? 0 : 1)

                rightIconClose(show: $showSaveThePlanet)
                    .offset(x: 0, y: 70)
                    .animation(.easeInOut)
                    .scaleEffect(show ? 0.90 : 1)
                    .blur(radius: show ? 10 : 0)
                    .opacity(showSaveThePlanet ? 1 : 0)

                MenuView(show: $show)
            }
            .edgesIgnoringSafeArea(.all)
            .navigationBarTitle("Home")
            .navigationBarHidden(true)
            .navigationBarBackButtonHidden(false)

        }
    }
}
</code>```

答:
Best way that I found is toggling the navBarHidden in destination views. This way incomplete swipe to pop gestures will not remove the navigation bar.

So in your main view you would write

```<code>@State private var navBarHidden = true

var body: some View {
NavigationView {
    NavigationLink(
        destination: DetailView(navBarHidden: self.$navBarHidden)
    ) {
        Text("Go to detail view")
    }
}
.navigationBarTitle("")
.navigationBarHidden(self.navBarHidden)
}
</code>```

And in your destination view:

```<code>@Binding var navBarHidden : Bool
var body: some View {
Text("Hello Detail View!")
    .navigationBarTitle("Detail")
    .onAppear {
        self.navBarHidden = false
    }
    .onDisappear {
        self.navBarHidden = true
    }
}
</code>```

Body:
My app running on Swift UI, and my main page is Home(), In the home page there is NavigationView and NavigationLink(destination: SaveThePlanet()), I have hide the Navigation View on the main page "Home", its also hide in SaveThePlanet().
How can I unhide the navigation back button in the SaveThePlanet() page?

import SwiftUI

struct Home: View {

    @State var show = false
    @State var showSaveThePlanet = false
    var body: some View {
        NavigationView {
            ZStack {
                Color.gray
                ContentView()
                    .blur(radius: show ? 10 : 0)
                    .scaleEffect(show ? 0.90 : 1)
                    .blur(radius: showSaveThePlanet ? 10 : 0)
                    .scaleEffect(showSaveThePlanet ? 0.90 : 1)
                    .animation(.default)

                leftIcon(show: $show)
                    .offset(x: 0, y: showSaveThePlanet ? 300 : 70)
                    .scaleEffect(show ? 0.90 : 1)
                    .blur(radius: show ? 10 : 0)
                    .animation(.easeInOut)

                SaveThePlanet()
                    .background(Color("Bg"))
                    .cornerRadius(10)
                    .shadow(color: Color("Green-Sh"), radius: 10, x: 0, y: 0)
                    .animation(.spring())
                    .offset(y: showSaveThePlanet ? 120 : UIScreen.main.bounds.height)
                    .padding()

                rightIcon(show: $showSaveThePlanet)
                    .offset(x: 0, y: 70)
                    .animation(.easeInOut)
                    .scaleEffect(show ? 0.90 : 1)
                    .blur(radius: show ? 10 : 0)
                    .opacity(showSaveThePlanet ? 0 : 1)

                rightIconClose(show: $showSaveThePlanet)
                    .offset(x: 0, y: 70)
                    .animation(.easeInOut)
                    .scaleEffect(show ? 0.90 : 1)
                    .blur(radius: show ? 10 : 0)
                    .opacity(showSaveThePlanet ? 1 : 0)

                MenuView(show: $show)
            }
            .edgesIgnoringSafeArea(.all)
            .navigationBarTitle("Home")
            .navigationBarHidden(true)
            .navigationBarBackButtonHidden(false)

        }
    }
}

Body:
Best way that I found is toggling the navBarHidden in destination views. This way incomplete swipe to pop gestures will not remove the navigation bar.

So in your main view you would write

@State private var navBarHidden = true

var body: some View {
NavigationView {
    NavigationLink(
        destination: DetailView(navBarHidden: self.$navBarHidden)
    ) {
        Text("Go to detail view")
    }
}
.navigationBarTitle("")
.navigationBarHidden(self.navBarHidden)
}

And in your destination view:

@Binding var navBarHidden : Bool
var body: some View {
Text("Hello Detail View!")
    .navigationBarTitle("Detail")
    .onAppear {
        self.navBarHidden = false
    }
    .onDisappear {
        self.navBarHidden = true
    }
}


问:
Use loop for create multiple columns from another columns in dataframe in R
I have a CSV file with 19 columns and 9 lines about average of rain months from pluviometers and coordinates (LongLat) of them. The columns are averages and the lines are the pluviometers. The CSV file can be acessed here:  https://drive.google.com/file/d/1wGVT5etZomYW-Cb6R3KgHaV4mXrTjlu4/view?usp=sharing

The aim is create more columns to calculate rainfall factor by months applying a equation from average columns. The rainfall factor for January for each pluviometer (9 lines) will be calculate using column 7, rainfall for february using column 8, march by column 9...

I'm trying this code for each column and it works, but this code can be reduce and made with a loop?

```<code>library(tidyverse)

setwd("C:/scriptsr/R_postos_pluviometricos_interp_FUNCEME/")

#Code
pluviometros <- read.csv("postos_fatorR.csv",
                                 header = T,
                                 sep = ",",
                                 stringsAsFactors = FALSE)

View(pluviometros)

pluviometros <- mutate(.data=pluviometros,R.JAN=67.355*((pluviometros[1:nrow(pluviometros),7]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.FEV=67.355*((pluviometros[1:nrow(pluviometros),8]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.MAR=67.355*((pluviometros[1:nrow(pluviometros),9]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.APR=67.355*((pluviometros[1:nrow(pluviometros),10]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.MAY=67.355*((pluviometros[1:nrow(pluviometros),11]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.JUN=67.355*((pluviometros[1:nrow(pluviometros),12]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.JUL=67.355*((pluviometros[1:nrow(pluviometros),13]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.AGO=67.355*((pluviometros[1:nrow(pluviometros),14]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.SEP=67.355*((pluviometros[1:nrow(pluviometros),15]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.OCT=67.355*((pluviometros[1:nrow(pluviometros),16]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.NOV=67.355*((pluviometros[1:nrow(pluviometros),17]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.DEC=67.355*((pluviometros[1:nrow(pluviometros),18]^2)/pluviometros[1:nrow(pluviometros),19])^0.85
                                       )
View(pluviometros)
</code>```

答:
Using R base there is no no need for looping, just using vectorized operations capability of R: </p>

```<code>result <- 67.355 *(pluviometros[,7:18]^2 / pluviometros[,"TOTAL_pa"])^0.85
names(result) <- paste("R", names(pluviometros)[7:18], sep=".")
pluviometros <- cbind(pluviometros, result)
</code>```

Body:
I have a CSV file with 19 columns and 9 lines about average of rain months from pluviometers and coordinates (LongLat) of them. The columns are averages and the lines are the pluviometers. The CSV file can be acessed here:  https://drive.google.com/file/d/1wGVT5etZomYW-Cb6R3KgHaV4mXrTjlu4/view?usp=sharing

The aim is create more columns to calculate rainfall factor by months applying a equation from average columns. The rainfall factor for January for each pluviometer (9 lines) will be calculate using column 7, rainfall for february using column 8, march by column 9...

I'm trying this code for each column and it works, but this code can be reduce and made with a loop?

library(tidyverse)

setwd("C:/scriptsr/R_postos_pluviometricos_interp_FUNCEME/")

#Code
pluviometros <- read.csv("postos_fatorR.csv",
                                 header = T,
                                 sep = ",",
                                 stringsAsFactors = FALSE)

View(pluviometros)

pluviometros <- mutate(.data=pluviometros,R.JAN=67.355*((pluviometros[1:nrow(pluviometros),7]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.FEV=67.355*((pluviometros[1:nrow(pluviometros),8]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.MAR=67.355*((pluviometros[1:nrow(pluviometros),9]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.APR=67.355*((pluviometros[1:nrow(pluviometros),10]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.MAY=67.355*((pluviometros[1:nrow(pluviometros),11]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.JUN=67.355*((pluviometros[1:nrow(pluviometros),12]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.JUL=67.355*((pluviometros[1:nrow(pluviometros),13]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.AGO=67.355*((pluviometros[1:nrow(pluviometros),14]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.SEP=67.355*((pluviometros[1:nrow(pluviometros),15]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.OCT=67.355*((pluviometros[1:nrow(pluviometros),16]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.NOV=67.355*((pluviometros[1:nrow(pluviometros),17]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.DEC=67.355*((pluviometros[1:nrow(pluviometros),18]^2)/pluviometros[1:nrow(pluviometros),19])^0.85
                                       )
View(pluviometros)

Body:
Using R base there is no no need for looping, just using vectorized operations capability of R:

result <- 67.355 *(pluviometros[,7:18]^2 / pluviometros[,"TOTAL_pa"])^0.85
names(result) <- paste("R", names(pluviometros)[7:18], sep=".")
pluviometros <- cbind(pluviometros, result)


问:
get data from MarketWatch
Using BeautifulSoup I am trying to scrape MarketWatch

```<code>from bs4 import BeautifulSoup
import requests
import pandas

url = "https://www.marketwatch.com/investing/stock/khc/profile"
# Make a GET request to fetch the raw HTML content
html_content = requests.get(url).text

soup = BeautifulSoup(html_content, "lxml")
</code>```

Now I would like to extract the "P/E Current" and the "Price to Sales Ratio" that in the html are in the class

```<code>[...]
<div class="sixwide addgutter">

    <div class="block threewide addgutter">

        <h2>Valuation</h2>
                <div class="section">
            <p class="column">P/E Current</p>
            <p class="data lastcolumn">19.27</p>
        </div>
                <div class="section">
            <p class="column">P/E Ratio (with extraordinary items)</p>
            <p class="data lastcolumn">19.55</p>
        </div>
                <div class="section">
            <p class="column">P/E Ratio (without extraordinary items)</p>
            <p class="data lastcolumn">20.00</p>
        </div>
                <div class="section">
            <p class="column">Price to Sales Ratio</p>
            <p class="data lastcolumn">1.55</p>
        </div>
                <div class="section">
            <p class="column">Price to Book Ratio</p>
            <p class="data lastcolumn">0.75</p>
        </div>
        [...]
</code>```

How can I get them?

I use the command

```<code>section = soup.findAll('div', {'class' : 'section'})
</code>```

but then I don't know how to go ahead to get the values I am interested in, can you help?

答:
This solution will get data from all sections under div with class "sixwide addgutter". The result is in the form of list of dictionaries:

```<code>soup = BeautifulSoup(req.content, 'lxml')

base = soup.find('div', attrs={'class' : 'sixwide addgutter'})
section = base.find_all('div', attrs={'class' : 'section'})

all_data=[]
for item in section:
    data = {}
    data['name']=item.p.text
    data['value']=item.p.findNext('p').text
    all_data.append(data)
</code>```

Output sample:

If you want the specifics, "P/E Current" and "Price to Sales Ratio" are all_data[0], all_data[3] respectively.

Title: get data from MarketWatch

Body:
Using BeautifulSoup I am trying to scrape MarketWatch

from bs4 import BeautifulSoup
import requests
import pandas

url = "https://www.marketwatch.com/investing/stock/khc/profile"
# Make a GET request to fetch the raw HTML content
html_content = requests.get(url).text

soup = BeautifulSoup(html_content, "lxml")

Now I would like to extract the "P/E Current" and the "Price to Sales Ratio" that in the html are in the class

[...]

Valuation

P/E Current

19.27

P/E Ratio (with extraordinary items)

19.55

P/E Ratio (without extraordinary items)

20.00

Price to Sales Ratio

1.55

Price to Book Ratio

0.75

        [...]

How can I get them?

I use the command

section = soup.findAll('div', {'class' : 'section'})

but then I don't know how to go ahead to get the values I am interested in, can you help?

Body:
This solution will get data from all sections under div with class "sixwide addgutter". The result is in the form of list of dictionaries:

soup = BeautifulSoup(req.content, 'lxml')

base = soup.find('div', attrs={'class' : 'sixwide addgutter'})
section = base.find_all('div', attrs={'class' : 'section'})

all_data=[]
for item in section:
    data = {}
    data['name']=item.p.text
    data['value']=item.p.findNext('p').text
    all_data.append(data)

Output sample:

If you want the specifics, "P/E Current" and "Price to Sales Ratio" are all_data[0], all_data[3] respectively.


问:
Unknown format error on running examples on coral board along with coral camera
I was running examples from google coral. They worked fine on my coral board. Then i modified the examples after following this post to increase fps output  of camera.

The details of platform :

```<code>mendel@coral2:~$ uname -a
Linux coral2 4.14.98-imx #1 SMP PREEMPT Fri Nov 8 23:28:21 UTC 2019 aarch64 GNU/Linux
</code>```

The example runs fine with usb camera (standard one) however with coral camera results in following error. (VISIBLE IN SYSLOGS)

```<code>Jun  1 10:32:28 coral2 kernel: [378824.885837] unknown pixelformat:'BGR3'
Jun  1 10:32:28 coral2 kernel: [378824.889798] mx6s-csi 30a90000.csi1_bridge: Fourcc format (0x33524742) invalid.
Jun  1 10:32:28 coral2 kernel: [378824.897302] unknown pixelformat:'YV12'
Jun  1 10:32:28 coral2 kernel: [378824.901344] mx6s-csi 30a90000.csi1_bridge: Fourcc format (0x32315659) invalid.
Jun  1 10:32:28 coral2 kernel: [378824.908784] unknown pixelformat:'411P'
Jun  1 10:32:28 coral2 kernel: [378824.912753] mx6s-csi 30a90000.csi1_bridge: Fourcc format (0x50313134) invalid.
Jun  1 10:32:28 coral2 kernel: [378824.920308] unknown pixelformat:'MJPG'
Jun  1 10:32:28 coral2 kernel: [378824.924268] mx6s-csi 30a90000.csi1_bridge: Fourcc format (0x47504a4d) invalid.
Jun  1 10:32:28 coral2 kernel: [378824.931818] unknown pixelformat:'JPEG'
Jun  1 10:32:28 coral2 kernel: [378824.935778] mx6s-csi 30a90000.csi1_bridge: Fourcc format (0x4745504a) invalid.
</code>```

Steps to produce error

git clone https://github.com/deepanshu-yadav/coral_bug.git

./download_models.sh

cd opencv

./install_requirements.sh

python3 detect.py

To sum it up it only reads the first frame and never shows the subsequent frames.

答:
I believe you have also reached out to us via our private support channel, but I'm pasting it here for other to reference also.

Unfortunately, I cannot reproduce this issue on my side using your code. A quick look at the code base, it appears that you haven't commit your changes.
On another note, I don't believe this is going to work in the first place. This is because the Camera module that we ship doesn't have supports for BGR3 format and only YUYV. You can confirm this with this command:

```<code>$ v4l2-ctl --list-formats-ext --device /dev/video0
ioctl: VIDIOC_ENUM_FMT
        Type: Video Capture

        [0]: 'YUYV' (YUYV 4:2:2)
                Size: Discrete 640x480
                        Interval: Discrete 0.033s (30.000 fps)
                Size: Discrete 720x480
                        Interval: Discrete 0.033s (30.000 fps)
                Size: Discrete 1280x720
                        Interval: Discrete 0.033s (30.000 fps)
                Size: Discrete 1920x1080
                        Interval: Discrete 0.067s (15.000 fps)
                        Interval: Discrete 0.033s (30.000 fps)
                Size: Discrete 2592x1944
                        Interval: Discrete 0.067s (15.000 fps)
                Size: Discrete 0x0
</code>```

Body:
I was running examples from google coral. They worked fine on my coral board. Then i modified the examples after following this post to increase fps output  of camera.

The details of platform :

mendel@coral2:~$ uname -a
Linux coral2 4.14.98-imx #1 SMP PREEMPT Fri Nov 8 23:28:21 UTC 2019 aarch64 GNU/Linux

The example runs fine with usb camera (standard one) however with coral camera results in following error. (VISIBLE IN SYSLOGS)

Jun  1 10:32:28 coral2 kernel: [378824.885837] unknown pixelformat:'BGR3'
Jun  1 10:32:28 coral2 kernel: [378824.889798] mx6s-csi 30a90000.csi1_bridge: Fourcc format (0x33524742) invalid.
Jun  1 10:32:28 coral2 kernel: [378824.897302] unknown pixelformat:'YV12'
Jun  1 10:32:28 coral2 kernel: [378824.901344] mx6s-csi 30a90000.csi1_bridge: Fourcc format (0x32315659) invalid.
Jun  1 10:32:28 coral2 kernel: [378824.908784] unknown pixelformat:'411P'
Jun  1 10:32:28 coral2 kernel: [378824.912753] mx6s-csi 30a90000.csi1_bridge: Fourcc format (0x50313134) invalid.
Jun  1 10:32:28 coral2 kernel: [378824.920308] unknown pixelformat:'MJPG'
Jun  1 10:32:28 coral2 kernel: [378824.924268] mx6s-csi 30a90000.csi1_bridge: Fourcc format (0x47504a4d) invalid.
Jun  1 10:32:28 coral2 kernel: [378824.931818] unknown pixelformat:'JPEG'
Jun  1 10:32:28 coral2 kernel: [378824.935778] mx6s-csi 30a90000.csi1_bridge: Fourcc format (0x4745504a) invalid.

Steps to produce error

git clone https://github.com/deepanshu-yadav/coral_bug.git

./download_models.sh

cd opencv

./install_requirements.sh

python3 detect.py

To sum it up it only reads the first frame and never shows the subsequent frames.

Body:
I believe you have also reached out to us via our private support channel, but I'm pasting it here for other to reference also.

Unfortunately, I cannot reproduce this issue on my side using your code. A quick look at the code base, it appears that you haven't commit your changes.
On another note, I don't believe this is going to work in the first place. This is because the Camera module that we ship doesn't have supports for BGR3 format and only YUYV. You can confirm this with this command:

$ v4l2-ctl --list-formats-ext --device /dev/video0
ioctl: VIDIOC_ENUM_FMT
        Type: Video Capture

        [0]: 'YUYV' (YUYV 4:2:2)
                Size: Discrete 640x480
                        Interval: Discrete 0.033s (30.000 fps)
                Size: Discrete 720x480
                        Interval: Discrete 0.033s (30.000 fps)
                Size: Discrete 1280x720
                        Interval: Discrete 0.033s (30.000 fps)
                Size: Discrete 1920x1080
                        Interval: Discrete 0.067s (15.000 fps)
                        Interval: Discrete 0.033s (30.000 fps)
                Size: Discrete 2592x1944
                        Interval: Discrete 0.067s (15.000 fps)
                Size: Discrete 0x0


问:
Not able to update the database in hibernate
I am new to hibernate and I am using hibernate 3.0 with MySQL and I want to make the simple database operations like insert update and delete with the database.I am getting the successful results for insert and delete but not able to update the particular field.
I have persistent class named Employee with Fname,Lname,Id and mail with getters and setters.

This is my main method :-

```<code>public static void main(String[] args) {
    Session session = null;
    Random r = new Random();
    try {
        /*
         * This step will read hibernate.cfg.xml
         *
         * and prepare hibernate for use
         */
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
        session = sessionFactory.openSession();
        Transaction trx = session.beginTransaction();
        Contact contact = new Contact();
        contact = (Contact) session.get(Contact.class, new Long(1));
        // Create new instance of Contact and set
        // values in it by reading them from form object
        System.out.println("Inserting Record");
        contact.setId(r.nextLong() % 100);
        contact.setFirstName("123anand");
        contact.setLastName("nandurbarkar");
        contact.setEmail("anand_it1990@yahoo.com");
        trx.commit();
        session.update(contact);
</code>```

And this is my conf file :-

```<code>    <hibernate-configuration>
    <session-factory>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
   <property name="hibernate.connection.url">jdbc:mysql://localhost/hibernatetutorial</property>
   <property name="hibernate.connection.username">root</property>
   <property name="hibernate.connection.password">root</property>
  <property name="hibernate.connection.pool_size">1</property>
 <property name="show_sql">true</property>
 <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
 <property name="hibernate.hbm2ddl.auto">update</property>
    <!-- Mapping files -->
 <mapping resource="contact.hbm.xml"/>
 </session-factory>
</hibernate-configuration>
</code>```

Please help if u know how to resolve this issue.
Thanks in Advance...

答:
I think you need to do your update before you commit the session

So swapping your last two lines around should make it work:-

```<code>session.update(contact);
trx.commit();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am new to hibernate and I am using hibernate 3.0 with MySQL and I want to make the simple database operations like insert update and delete with the database.I am getting the successful results for insert and delete but not able to update the particular field.
I have persistent class named Employee with Fname,Lname,Id and mail with getters and setters.

This is my main method :-

public static void main(String[] args) {
    Session session = null;
    Random r = new Random();
    try {
        /*
         * This step will read hibernate.cfg.xml
         *
         * and prepare hibernate for use
         */
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
        session = sessionFactory.openSession();
        Transaction trx = session.beginTransaction();
        Contact contact = new Contact();
        contact = (Contact) session.get(Contact.class, new Long(1));
        // Create new instance of Contact and set
        // values in it by reading them from form object
        System.out.println("Inserting Record");
        contact.setId(r.nextLong() % 100);
        contact.setFirstName("123anand");
        contact.setLastName("nandurbarkar");
        contact.setEmail("anand_it1990@yahoo.com");
        trx.commit();
        session.update(contact);

And this is my conf file :-

    <hibernate-configuration>
    <session-factory>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
   <property name="hibernate.connection.url">jdbc:mysql://localhost/hibernatetutorial</property>
   <property name="hibernate.connection.username">root</property>
   <property name="hibernate.connection.password">root</property>
  <property name="hibernate.connection.pool_size">1</property>
 <property name="show_sql">true</property>
 <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
 <property name="hibernate.hbm2ddl.auto">update</property>

 <mapping resource="contact.hbm.xml"/>
 </session-factory>
</hibernate-configuration>

Please help if u know how to resolve this issue.
Thanks in Advance...

Body:
I think you need to do your update before you commit the session

So swapping your last two lines around should make it work:-

session.update(contact);
trx.commit();


问:
JDK cannot be opened after MacOS upgraded to 10.15.X (Catalina)
After MacOS is upgraded to 10.15.X (Catalina), JDK cannot be opened. The message shows "JDK cannot be opened because the developer cannot be verified".</p>

答:
According to java.com:

Changes introduced with macOS 10.15 (Catalina) cause certain Java
  applications to behave incorrectly. Therefore, we cannot certify any
  JDK version on macOS 10.15 yet. However, as of now, you can install
  and run non-notarized software on macOS 10.15 systems by modifying
  your security preferences.

You can find detailed information about it here.


问:
How do I indicate my Windows Service is not pausable?
https://serverfault.com/questions/70028/pausing-a-not-pausable-service-pausing-a-not-pausable-service-from-the-command talks about pausing a NOT_PAUSABLE service. How do I indicate my service is not pausable to begin with? I want my service to only support the start/stop operations.</p>

答:
I came to this post trying to make my service pausable. I was able to set this via the CanPauseAndContinue property in the constructor of my service.

https://learn.microsoft.com/en-us/dotnet/api/system.serviceprocess.servicebase.canpauseandcontinue?view=dotnet-plat-ext-3.1


问:
Variadic generic function accepting generic types as input arguments
Suppose we have some concrete types A, B, C, etc. Also we have a wrapper type: Wrapper<T> where T could be any types e.g. A, B.

I need a variadic function that takes some Wrapper<T>s and returns the wrapped values as a tuple: [].

```<code>let wa: Wrapper<A>;
let wb: Wrapper<B>;
let wc: Wrapper<C>;
let result = myFunction(wa, wb, wc);
</code>```

In this example result should be of type [A, B, C]. I don't know how to write the type of myFunction. Can you help?

答:
this can be done with a tuple type

```<code>function foo<T extends any[]>(...args: T): T {
    return args;
}
// you dont need to pass generic parameters ofc. typescript will infer same type anyway
// return type of this function is now [string, number, object]
foo<[string, number, object]>("a", 1, {});
</code>```

here is Playground

Body:
Suppose we have some concrete types A, B, C, etc. Also we have a wrapper type: Wrapper<T> where T could be any types e.g. A, B.

I need a variadic function that takes some Wrapper<T>s and returns the wrapped values as a tuple: [].

let wa: Wrapper;
let wb: Wrapper;
let wc: Wrapper<C>;
let result = myFunction(wa, wb, wc);

In this example result should be of type [A, B, C]. I don't know how to write the type of myFunction. Can you help?

Body:
this can be done with a tuple type

function foo<T extends any[]>(...args: T): T {
    return args;
}
// you dont need to pass generic parameters ofc. typescript will infer same type anyway
// return type of this function is now [string, number, object]
foo<[string, number, object]>("a", 1, {});

here is Playground


问:
(Java) How to store selected elements from a list into array
I have a list of elements:

```<code>private List<Track> selection;
</code>```

And I want to implement a function public Track[] selection()

which returns an array of selected tracks. How to implement this?

I was going to implement this: Swings: storing the selected values from List into an array. method, however it applies only for known number of elements.

EDIT: Sorry to ask such a newbie question, but I tried any possible ways previously and nothing worked. OOP is new for me, and where else to find answers for questions if not here? ^_^

答:
```<code>public Track[] selection() {
    return this.selection.stream().filter(predicate-here).toArray(Track[]::new);
}
</code>```

Your predicate might be, for instance: elem -> elem.getName().equals("something")

Body:
I have a list of elements:

private List<Track> selection;

And I want to implement a function public Track[] selection()

which returns an array of selected tracks. How to implement this?

I was going to implement this: Swings: storing the selected values from List into an array. method, however it applies only for known number of elements.

EDIT: Sorry to ask such a newbie question, but I tried any possible ways previously and nothing worked. OOP is new for me, and where else to find answers for questions if not here? ^_^

Body:
public Track[] selection() {
    return this.selection.stream().filter(predicate-here).toArray(Track[]::new);
}

Your predicate might be, for instance: elem -> elem.getName().equals("something")


问:
How can I dock a div in IE 8?
you amazingly kind and intelligent people.  Consider the following HTML:

```<code><html>
<body>
    <div id="Panel1" style="position: absolute; bottom: 0; right: 0; top: 0;
        width: 259; background-color: #00FF00">
        <input type="button" style="position: absolute;
            left: 161; top: 30; width: 75; height: 25" tabindex="3"/>
    </div>
</body>
</html>
</code>```

What I'm doing here is docking the div to the right hand side of the screen so that it extends from the top to the bottom.  This works perfectly in Google Chrome, but not in IE8.

I've uploaded the page here http://losthobbit.net/temp/testdoc.html  in order to make your life just a little bit easier.

Any idea as to how I can get this working in IE?

Thanks!

答:
Well, just add a valid doctype and your done ;)

Ex.:

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
</code>```

Title: How can I dock a div in IE 8?

Body:
you amazingly kind and intelligent people.  Consider the following HTML:

        <input type="button" style="position: absolute;
            left: 161; top: 30; width: 75; height: 25" tabindex="3"/>

What I'm doing here is docking the div to the right hand side of the screen so that it extends from the top to the bottom.  This works perfectly in Google Chrome, but not in IE8.

I've uploaded the page here http://losthobbit.net/temp/testdoc.html  in order to make your life just a little bit easier.

Any idea as to how I can get this working in IE?

Thanks!

Body:
Well, just add a valid doctype and your done ;)

Ex.:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">


问:
do we need write try catch when we want get data from database in laravel?
I have developed many APIs in Laravel and I want to know for example if I want to have a list of posts in my /api/posts route I should write codes in try catch block or it does not needed?</p>

答:
The Eloquent ORM and the DB facade generally don't raise exceptions, so in most cases, you don't need to use Try/Catch blocks when performing normal queries. If you are going to use any other library or elements in your queries where you are expecting exceptions to be raised, you should use Try/Catch blocks.

For example, querying the database for posts will either return a collection of models if the criteria meet, or it will not return any results if criteria don't meet. No exceptions will be raised for your queries. So in such a scenario, using Try/Catch blocks will not make any differnce. Chances are that your code will never hit the catch block.


问:
Javascript – use X amount of object variables in if statement
I'd like to make the following code more generic/page-independent so that I can use it for other projects too.

The code is checking if a certain value in the localCache exists and if the location.pathname has a certain string. If so, it should scroll to top etc.

Now it looks like this:

```<code>if (referrer == "home" && location.pathname == "projects"){
    window.scrollTo(0,0);
    localStorage.setItem('referrer', 'projects');
}
</code>```

I'd like to make more generic so that it's not depending on the exact amount of strings of the location.pathname and so that it can refer to an X amount of location.pathnames.

I tried to make an object out of the different strings like this:

```<code>let object = {
    homePage: "home",
    noScrollPages: {[
      "projects",
      "about",
      "info"
    ]}
}

if (referrer == homePage && (location.pathname == "/" + noScrollPages[0]) || location.pathname == "/" + noScrollPages[1] || location.pathname == "/" + noScrollPages[2]){
    window.scrollTo(0,0);
    localStorage.setItem("referrer", noScrollPages[0, 1, 2 or X, whichever resolves as true in the if statement]);
    console.log(localStorage.getItem("referrer"));
}
</code>```

So, basically I don't know how code it so that it doesn't rely on the explicit declaration of [0] or [1], because it could be X number of pages.

Thanks for any tips!

答:
The previous solution works, but this is an alternative. If you have many different pages, it may be more efficient to use a Set, which comes with the has method, which allows you to check for existence of an element in constant time.

In this example, the location's pathname is "/projects", so locationName evaluates to "projects"; instead of checking each page for equality to the location's pathname when the page is prepended with a "/", we check for existence of a page equal to locationName (location without the initial slash).

```<code>let location  = {pathname: "/projects"} // setting this as test (REMOVE THIS)

let object = {
    homePage: "home",
    noScrollPages: new Set([
      "projects",
      "about",
      "info"
    ])
}
let locationName = location.pathname.substring(1) // location without first slash

if (referrer == homePage && object.noScrollPages.has(locationName)){
    window.scrollTo(0,0);
    localStorage.setItem("referrer", locationName);
    console.log(localStorage.getItem("referrer"));
}
</code>```

Body:
I'd like to make the following code more generic/page-independent so that I can use it for other projects too.

The code is checking if a certain value in the localCache exists and if the location.pathname has a certain string. If so, it should scroll to top etc.

Now it looks like this:

if (referrer == "home" && location.pathname == "projects"){
    window.scrollTo(0,0);
    localStorage.setItem('referrer', 'projects');
}

I'd like to make more generic so that it's not depending on the exact amount of strings of the location.pathname and so that it can refer to an X amount of location.pathnames.

I tried to make an object out of the different strings like this:

let object = {
    homePage: "home",
    noScrollPages: {[
      "projects",
      "about",
      "info"
    ]}
}

if (referrer == homePage && (location.pathname == "/" + noScrollPages[0]) || location.pathname == "/" + noScrollPages[1] || location.pathname == "/" + noScrollPages[2]){
    window.scrollTo(0,0);
    localStorage.setItem("referrer", noScrollPages[0, 1, 2 or X, whichever resolves as true in the if statement]);
    console.log(localStorage.getItem("referrer"));
}

So, basically I don't know how code it so that it doesn't rely on the explicit declaration of [0] or [1], because it could be X number of pages.

Thanks for any tips!

Body:
The previous solution works, but this is an alternative. If you have many different pages, it may be more efficient to use a Set, which comes with the has method, which allows you to check for existence of an element in constant time.

In this example, the location's pathname is "/projects", so locationName evaluates to "projects"; instead of checking each page for equality to the location's pathname when the page is prepended with a "/", we check for existence of a page equal to locationName (location without the initial slash).

let location  = {pathname: "/projects"} // setting this as test (REMOVE THIS)

let object = {
    homePage: "home",
    noScrollPages: new Set([
      "projects",
      "about",
      "info"
    ])
}
let locationName = location.pathname.substring(1) // location without first slash

if (referrer == homePage && object.noScrollPages.has(locationName)){
    window.scrollTo(0,0);
    localStorage.setItem("referrer", locationName);
    console.log(localStorage.getItem("referrer"));
}


问:
C++ including functional header gives error '__dest' does not name a type
I have a C++ that used to work. However, after including the <functional> header, compilation fails with the message

```<code>c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\bits\std_function.h: In static member function 'static void std::_Function_base::_Base_manager<_Functor>::_M_clone(std::_Any_data&, const std::_Any_data&, std::true_type)':
c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\bits\std_function.h:167:11: error: '__dest' does not name a type
  167 |    ::new (__dest._M_access()) _Functor(__source._M_access<_Functor>());
      |           ^~~~~~
c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\bits\std_function.h:167:17: error: expected ')' before '.' token
  167 |    ::new (__dest._M_access()) _Functor(__source._M_access<_Functor>());
      |          ~      ^
      |                 )
</code>```

I am using MinGW GCC 8.2.0, but it also occurs with version 9.2.0.

答:
This was part of a test suite. It turns out that the error was caused by CppUTest doing operator overloading. The overloads were included using -include/path/to/MemoryLeakDetectorNewMacros.h so it was not directly obvious from looking at just the code.

Solution for when using CppUTest: make sure that the C++ STL header is included before the CppUTest header MemoryLeakDetectorNewMacros.h. See the CppUTest manual section "Resolving conflicts with STL" for more information.

Body:
I have a C++ that used to work. However, after including the <functional> header, compilation fails with the message

c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\bits\std_function.h: In static member function 'static void std::_Function_base::_Base_manager<_Functor>::_M_clone(std::_Any_data&, const std::_Any_data&, std::true_type)':
c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\bits\std_function.h:167:11: error: '__dest' does not name a type
  167 |    ::new (__dest._M_access()) _Functor(__source._M_access<_Functor>());
      |           ^~~~~~
c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\bits\std_function.h:167:17: error: expected ')' before '.' token
  167 |    ::new (__dest._M_access()) _Functor(__source._M_access<_Functor>());
      |          ~      ^
      |                 )

I am using MinGW GCC 8.2.0, but it also occurs with version 9.2.0.


问:
Atlassian Crowd, OpenLDAP connector, "Password Encryption" option
When configuring the OpenLDAP directory connector connection configuration in Crowd, there is a section labeled "password encryption" (which should be re-labeled password hashing btw....)

When one has a directory connection for OpenLDAP how does authn in crowd actually work?

1) Is crowd just doing an LDAP bind against the target directory and letting the ldap server handle the hash comparison internally?

OR

2) is crowd loading the LDAP record's userPassword attribute and doing its own hash and comparison within crowd itself?

I see the "password encryption" available hashing options are DES, MD5, PLAINTEXT, SHA, SSHA. What effect does changing this option affect?

If the authn method is (1) above, why is this even relevant unless crowd is mutating user creds in the configured LDAP?

Why is the list of options for "password encryption" limited to this set of old algorithms. OpenLDAP supports many more than this.

What decides what shows up in this list? Does the "connector" interrogate the LDAP backend for supported methods? Is this a hardwired list? Is this limited to only the hash routines that Atlassian Crowd has implemented?

答:
1) is correct, authentication uses an LDAP bind.

You say:

unless crowd is mutating user creds in the configured LDAP

and that's exactly when it's used, as an encoder for changing passwords, or adding new users.

The list is not generally queried from the server, but it is possible to add encoders through plugins.


问:
javascript, parse an html string and recognize parts
I have a string like this:

```<code>"this is a string with <em>html</em> values"
</code>```

and I need to recognize the em part and the before and after part of the html tags.

can I use javascript to split the string into an array, as example:

```<code>["this is a string with", "html", "values"]
</code>```

答:
You can use DOMParser to parse the string into HTML, and once you create an instance and pass the string to it, you can get the generated document childNodes then iterate through them using .forEach(), note how I check the nodes we are iterating through for #text as a name for the node, since this check is for text nodes and not actual HTML tags:

let domparser = new DOMParser();
let doc = domparser.parseFromString('this is a string with html values', 'text/html');

doc.body.childNodes.forEach(function(node) {
  if (node.nodeName === "#text") {
    console.log(node.nodeValue);
  } else {
    console.log(node);
  }
});```

Body:
I have a string like this:

"this is a string with html values"

and I need to recognize the em part and the before and after part of the html tags.

can I use javascript to split the string into an array, as example:

["this is a string with", "html", "values"]

Body:
You can use DOMParser to parse the string into HTML, and once you create an instance and pass the string to it, you can get the generated document childNodes then iterate through them using .forEach(), note how I check the nodes we are iterating through for #text as a name for the node, since this check is for text nodes and not actual HTML tags:

let domparser = new DOMParser();
let doc = domparser.parseFromString('this is a string with <em>html</em> values', 'text/html');

doc.body.childNodes.forEach(function(node) {
  if (node.nodeName === "#text") {
    console.log(node.nodeValue);
  } else {
    console.log(node);
  }
});


问:
how to populate a column by seeing another column in source whether it has a particular value then set it to a single value
I have one doubt, I have a table in that for particular distinct sk column I have two different indicators (Y,N) so for a particular sk if I have one "Y" then set every value to Y if the values all the values are N then set to N.
Sources:

Result which I needed:

答:
Just use max() as a window function:

```<code>select t.*, max(indicator) over (partition by number_sk) as column_3
from t;
</code>```

Body:
Just use max() as a window function:

select t.*, max(indicator) over (partition by number_sk) as column_3
from t;


问:
SSRS Calling a Subreport in Footer Through a URL
I have several SSRS reports that all need to have the same footer, a payment stub.

Rather than have the footer recreated for each report, I want to have the footer as it's own report, and included as an independent subreport.

The problem, is you can't put a subreport in a footer in SSRS. So my idea is to make the footer an image called by a URL, and the URL is the subreport sitting on the SSRS server.

So if the subreport URL is this:
http://localhost/ReportServer?/TAS/Reports/STUBTEST/REP90016&rc:PageHeight=3.7in&rc:PageWidth=8.5in&rs:format=IMAGE&rc:OutputFormat=JPEG&rs:Command=Render&rc:Parameters=Collapsed&P_ACC_ID=1&P_DATE=7-MAY-2020&P_PROP_ADDRESS=%27123%20Fake%20St%27&P_AMOUNT_DUE=1.78

And I put the above URL as the image URL, it does show the image I want in the footer in Visual Studio when I preview the report. However when I move the report to the SSRS server, and call the report as a PDF, the footer is blank.

Any ideas how I can achieve this?

答:
My solution was this:
Create a webservice that will call the URL for the subreport and covert it to base64 string.

In the main report, put some code in a function that creates a webrequest to the above ws and returns the string.

In the main report footer, create and image that calls the above function and convert it from a bass64 string to show the subreport as an image.


问:
Is it possible to setText for an Edittext for a long data type element in android
Is it possible to setText for an Edittext view for a long data type element in android XML? I know that setText can take integer but it is not accepting any long data type. So how can I write a long variable in an Edittext without converting it to integer?</p>

答:
Why not you make it to String first:</p>

```<code>yourEditText.setText(String.valueOf(yourLongVariable));
</code>```

Body:
Why not you make it to String first:

yourEditText.setText(String.valueOf(yourLongVariable));


问:
Spark [Scala] Timestamp field being converted into string even after explicit casting while doing "filter"
I have a dataframe, say df1, which I am trying to filter based on a date range.

Example:

```<code>| id | name | disconnect_dt_time  |
|----|------|---------------------|
| 1  | "a"  | 2020-05-19 00:00:00 |
| 2  | "b"  | 2020-05-20 00:00:00 |

val df = spark.table("df1")
               .filter(col("disconnect_dt_time").cast("timestamp").between(analysisStartDate , analysisEndDate) )
</code>```

I am getting the below issue:

Reason: [ cannot resolve '((((CAST(CAST(df1.disconnect_dt_time AS
  TIMESTAMP) AS STRING) >= '20200520T00:00:00+0000') AND
  (CAST(CAST(df1.disconnect_date_datetime AS
  TIMESTAMP) AS STRING) <= '20200530T00:00:00+0000'))

What is the reason for this double casting? CAST(CAST(df1.disconnect_dt_time AS TIMESTAMP) AS STRING)? How can this be fixed?

答:
The casting depends on how you have defined analysisStartDate and analysisEndDate

Case 1 : If your analysisStartDate and analysisEndDate are String:

```<code>val df = List((1,"a","2020-05-19 00:00:00"),(2,"b","2020-05-20 00:00:00")).toDF("id","name","disconnect_dt_time")
df.filter(col("disconnect_dt_time").cast("timestamp").between( "2020-05-20 00:00:00", "2020-05-30 00:00:00" ) ).explain(true)

== Analyzed Logical Plan ==
id: int, name: string, disconnect_dt_time: string
Filter ((cast(cast(disconnect_dt_time#22 as timestamp) as string) >= 2020-05-20 00:00:00) && (cast(cast(disconnect_dt_time#22 as timestamp) as string) <= 2020-05-30 00:00:00))
+- Project [_1#16 AS id#20, _2#17 AS name#21, _3#18 AS disconnect_dt_time#22]
   +- LocalRelation [_1#16, _2#17, _3#18]

+---+----+-------------------+
| id|name| disconnect_dt_time|
+---+----+-------------------+
|  2|   b|2020-05-20 00:00:00|
+---+----+-------------------+
</code>```

Case 2: If your analysisStartDate and analysisEndDate are timestamp:

```<code>val df = List((1,"a","2020-05-19 00:00:00"),(2,"b","2020-05-20 00:00:00")).toDF("id","name","disconnect_dt_time")
df.filter(col("disconnect_dt_time").cast("timestamp").between( lit("2020-05-20 00:00:00").cast("timestamp"), lit("2020-05-30 00:00:00").cast("timestamp") ) ).explain(true)

== Analyzed Logical Plan ==
id: int, name: string, disconnect_dt_time: string
Filter ((cast(disconnect_dt_time#22 as timestamp) >= cast(2020-05-20 00:00:00 as timestamp)) && (cast(disconnect_dt_time#22 as timestamp) <= cast(2020-05-30 00:00:00 as timestamp)))
+- Project [_1#16 AS id#20, _2#17 AS name#21, _3#18 AS disconnect_dt_time#22]
   +- LocalRelation [_1#16, _2#17, _3#18]

+---+----+-------------------+
| id|name| disconnect_dt_time|
+---+----+-------------------+
|  2|   b|2020-05-20 00:00:00|
+---+----+-------------------+
</code>```

Body:
I have a dataframe, say df1, which I am trying to filter based on a date range.

Example:

| id | name | disconnect_dt_time  |
|----|------|---------------------|
| 1  | "a"  | 2020-05-19 00:00:00 |
| 2  | "b"  | 2020-05-20 00:00:00 |

val df = spark.table("df1")
               .filter(col("disconnect_dt_time").cast("timestamp").between(analysisStartDate , analysisEndDate) )

I am getting the below issue:

Reason: [ cannot resolve '((((CAST(CAST(df1.disconnect_dt_time AS
  TIMESTAMP) AS STRING) >= '20200520T00:00:00+0000') AND
  (CAST(CAST(df1.disconnect_date_datetime AS
  TIMESTAMP) AS STRING) <= '20200530T00:00:00+0000'))

What is the reason for this double casting? CAST(CAST(df1.disconnect_dt_time AS TIMESTAMP) AS STRING)? How can this be fixed?

Body:
The casting depends on how you have defined analysisStartDate and analysisEndDate

Case 1 : If your analysisStartDate and analysisEndDate are String:

val df = List((1,"a","2020-05-19 00:00:00"),(2,"b","2020-05-20 00:00:00")).toDF("id","name","disconnect_dt_time")
df.filter(col("disconnect_dt_time").cast("timestamp").between( "2020-05-20 00:00:00", "2020-05-30 00:00:00" ) ).explain(true)

== Analyzed Logical Plan ==
id: int, name: string, disconnect_dt_time: string
Filter ((cast(cast(disconnect_dt_time#22 as timestamp) as string) >= 2020-05-20 00:00:00) && (cast(cast(disconnect_dt_time#22 as timestamp) as string) <= 2020-05-30 00:00:00))
+- Project [_1#16 AS id#20, _2#17 AS name#21, _3#18 AS disconnect_dt_time#22]
   +- LocalRelation [_1#16, _2#17, _3#18]

+---+----+-------------------+
| id|name| disconnect_dt_time|
+---+----+-------------------+
|  2|   b|2020-05-20 00:00:00|
+---+----+-------------------+

Case 2: If your analysisStartDate and analysisEndDate are timestamp:

val df = List((1,"a","2020-05-19 00:00:00"),(2,"b","2020-05-20 00:00:00")).toDF("id","name","disconnect_dt_time")
df.filter(col("disconnect_dt_time").cast("timestamp").between( lit("2020-05-20 00:00:00").cast("timestamp"), lit("2020-05-30 00:00:00").cast("timestamp") ) ).explain(true)

== Analyzed Logical Plan ==
id: int, name: string, disconnect_dt_time: string
Filter ((cast(disconnect_dt_time#22 as timestamp) >= cast(2020-05-20 00:00:00 as timestamp)) && (cast(disconnect_dt_time#22 as timestamp) <= cast(2020-05-30 00:00:00 as timestamp)))
+- Project [_1#16 AS id#20, _2#17 AS name#21, _3#18 AS disconnect_dt_time#22]
   +- LocalRelation [_1#16, _2#17, _3#18]

+---+----+-------------------+
| id|name| disconnect_dt_time|
+---+----+-------------------+
|  2|   b|2020-05-20 00:00:00|
+---+----+-------------------+


问:
Teams Graph API call to get chats filtered by last modified doesn't return recent chat
I'm pulling group chats from teams with the notion being my code remembers the last-run-time and only asks Graph API for chats modified after that time.

In general this works a treat. Calls look something like this:

```<code>https://graph.microsoft.com/beta/teams/<guidyteamname>/channels/19:<guidychannel>@thread.skype/messages/delta?$filter=lastModifiedDateTime%20**gt%202020-06-01T*10:27:53*.00Z**
</code>```

So I'd expect all chats back last modified greater than 10:27, so say chats I posted at 11:00. Only it doesn't. If I leave it several hours (or wind back "the greater than" to, say, 05:00) then it works. Consistent with GraphAPI Explorer and my code.

It looks like how ever the filter works is seriously delayed? A few minutes seems reasonable but this is an extended period, and I cannot find documentation suggesting this?

答: I did a List channel message and the created time for a message is shown in GMT time, not my local time zone. So I would suggest you to try with GMT time filter. </p>

Body:
I'm pulling group chats from teams with the notion being my code remembers the last-run-time and only asks Graph API for chats modified after that time.

In general this works a treat. Calls look something like this:

https://graph.microsoft.com/beta/teams/<guidyteamname>/channels/19:<guidychannel>@thread.skype/messages/delta?$filter=lastModifiedDateTime%20**gt%202020-06-01T*10:27:53*.00Z**

So I'd expect all chats back last modified greater than 10:27, so say chats I posted at 11:00. Only it doesn't. If I leave it several hours (or wind back "the greater than" to, say, 05:00) then it works. Consistent with GraphAPI Explorer and my code.

It looks like how ever the filter works is seriously delayed? A few minutes seems reasonable but this is an extended period, and I cannot find documentation suggesting this?


问:
Adding new column, based on values of another column pandas
Can anyone help, i'm new to Python so bear with me.

My data looks like this but has all the region information available. I'm trying to create a new column 'actual price' that works out the price based on the region. as for every entry I have each price for every region. is this possible.

```<code>data = [[1, 'EDF', 'Eastern', 400, 500, 300], [2, 'EDF', 'Southern', 200, 100, 300], [3, 'NPower',
        'Eastern', 600, 500, 700]]

df = pd.DataFrame(data, columns = ['ID', 'Supplier', 'Region', 'Av Price', 'Eastern Price',
'Southern Price'])

df
</code>```

答:
I believe this is what you're looking for:

```<code>df["actual_price"] = np.where(df.Region == "Eastern", df["Eastern Price"], df["Southern Price"])
</code>```

result:

Body:
Can anyone help, i'm new to Python so bear with me.

My data looks like this but has all the region information available. I'm trying to create a new column 'actual price' that works out the price based on the region. as for every entry I have each price for every region. is this possible.

data = [[1, 'EDF', 'Eastern', 400, 500, 300], [2, 'EDF', 'Southern', 200, 100, 300], [3, 'NPower',
        'Eastern', 600, 500, 700]]

df = pd.DataFrame(data, columns = ['ID', 'Supplier', 'Region', 'Av Price', 'Eastern Price',
'Southern Price'])

df

Body:
I believe this is what you're looking for:

df["actual_price"] = np.where(df.Region == "Eastern", df["Eastern Price"], df["Southern Price"])

result:


问:
Size and Location of Elements inside a form are different than they got defined, but why?
I have defined a form having a GroupBox that contains some Buttons. I have then defined a second mode called "developer mode" that can be entered for certain purpose. For this mode I want to move and change the size of one of the buttons to make space for an other control element (that is only available in this
developer mode).

The task seemed to be easy. Simply do this:

```<code>Button1.Location = new Point(x1, y1);
Button1.Size = new Size(x2, y2);
</code>```

The outcomes was, that the buttons got located somewhere totally unpredictable and resized in a different why as expected.

So I tried to find out what the problem is. What I found out is that when I write out the credentials of that button after it got loaded into the form (and before I changed any parameter) it says something different than I have defined inside the properties of Button1. It appears as I defined it in the designer, but its size and location do have different value. E.g.

I defined the Size as 125,35.
 The output "Button1.Size.Width" than says 94 and 28 for "Button1.Size.Height".

I define the Location as 495, 280.

The output "Button1.Locaction.X" than says 371 and 228 for "Button1.Location.Y"

Ahm,... so what just happened?
Is there any resizing/relocation due to... I don't know... screentype one has? And what ever there is, how can I get control it?

Thanks for any input!
Cheers

答:
Your code sample defines 2 different sizes. Only one can be effective at a certain time. The second one (x3, y3) will overwrite the first one.

Docking affects size and location.

Anchoring affects location and possibly also size.

MinimumSize and MaximumSize of the button may override your manual settings of the size.

Body:
I have defined a form having a GroupBox that contains some Buttons. I have then defined a second mode called "developer mode" that can be entered for certain purpose. For this mode I want to move and change the size of one of the buttons to make space for an other control element (that is only available in this
developer mode).

The task seemed to be easy. Simply do this:

Button1.Location = new Point(x1, y1);
Button1.Size = new Size(x2, y2);

The outcomes was, that the buttons got located somewhere totally unpredictable and resized in a different why as expected.

So I tried to find out what the problem is. What I found out is that when I write out the credentials of that button after it got loaded into the form (and before I changed any parameter) it says something different than I have defined inside the properties of Button1. It appears as I defined it in the designer, but its size and location do have different value. E.g.

I defined the Size as 125,35.
 The output "Button1.Size.Width" than says 94 and 28 for "Button1.Size.Height".

I define the Location as 495, 280.

The output "Button1.Locaction.X" than says 371 and 228 for "Button1.Location.Y"

Ahm,... so what just happened?
Is there any resizing/relocation due to... I don't know... screentype one has? And what ever there is, how can I get control it?

Thanks for any input!
Cheers


问:
autofill cell values based on upper cell values in google sheets
I have customer purchase data which is exported from SQL database. The output format in Google sheets looks like this:

```<code>ID  name   address          phone       product name
1   Bob    2030 random road 6265609245  A
1                                       B
2   Peter  5453 golden drive            A
2                                       D
3   Jason  1 dna way                    C
4   James  sfo drive                    A
4                                       B
4                                       C
</code>```

I'd like to know if I could autofill the blank cells with the upper cell values if they have the same ID. To illustrate this please see the desired output format below:

```<code>ID  name   address          phone       product name
1   Bob    2030 random road 6265609245  A
1   Bob    2030 random road 6265609245  B
2   Peter  5453 golden drive            A
2   Peter  5453 golden drive            D
3   Jason  1 dna way                    C
4   James  sfo drive                    A
4   James  sfo drive                    B
4   James  sfo drive                    C
</code>```

Any help will be greatly appreciated!

答:
I assume that you want to complete the row based on the ID. If my assumption is correct, you can use this Apps Script code:

```<code>function so62048323() {
  var data = SpreadsheetApp.getActive().getDataRange().getValues();
  var nameDictionary = new Object();
  var addressDictionary = new Object();
  var phoneDictionary = new Object();

  for (var r = 1; r < data.length; r++) {
    if (data[r][0] != '') {
      if (data[r][1] != '') {
        nameDictionary[data[r][0]] = data[r][1];
      }
      if (data[r][2] != '') {
        addressDictionary[data[r][0]] = data[r][2];
      }
      if (data[r][3] != '') {
        phoneDictionary[data[r][0]] = data[r][3];
      }
    }
  }

  for (var r = 1; r < data.length; r++) {
    if (data[r][1] == '') {
      data[r][1] = nameDictionary[data[r][0]];
    }
    if (data[r][2] == '') {
      data[r][2] = addressDictionary[data[r][0]]
    }
    if (data[r][3] == '') {
      data[r][3] = phoneDictionary[data[r][0]];
    }
  }

  SpreadsheetApp.getActive().getDataRange().setValues(data)
}
</code>```

The code will initiate reading all your table with SpreadsheetApp.getActive(), Spreadsheet.getDataRange() and Range.getValues(). After that it will create three objects as dictionaries.

After that the code will iterate each row and record in the dictionaries each value (name, phone and address) associated with the ID. Afterwards, the code will repeat the operation but writing down the values. Finally, all the data is loaded in the sheet with Range.setValues(). For example, if we have this spreadsheet:

And we use the script, we will end up with this:

Please, notice how some ID doesn't have any phones; these are left empty. I understand that you may be using a very big database, so I optimized the code so it will run the fastest possible without taking into account the data size. Also, this code will work even if the rows aren't ordered. Don't hesitate to ask me any question if you have doubts.

Body:
I have customer purchase data which is exported from SQL database. The output format in Google sheets looks like this:

ID  name   address          phone       product name
1   Bob    2030 random road 6265609245  A
1                                       B
2   Peter  5453 golden drive            A
2                                       D
3   Jason  1 dna way                    C
4   James  sfo drive                    A
4                                       B
4                                       C

I'd like to know if I could autofill the blank cells with the upper cell values if they have the same ID. To illustrate this please see the desired output format below:

ID  name   address          phone       product name
1   Bob    2030 random road 6265609245  A
1   Bob    2030 random road 6265609245  B
2   Peter  5453 golden drive            A
2   Peter  5453 golden drive            D
3   Jason  1 dna way                    C
4   James  sfo drive                    A
4   James  sfo drive                    B
4   James  sfo drive                    C

Any help will be greatly appreciated!

Body:
I assume that you want to complete the row based on the ID. If my assumption is correct, you can use this Apps Script code:

function so62048323() {
  var data = SpreadsheetApp.getActive().getDataRange().getValues();
  var nameDictionary = new Object();
  var addressDictionary = new Object();
  var phoneDictionary = new Object();

  for (var r = 1; r < data.length; r++) {
    if (data[r][0] != '') {
      if (data[r][1] != '') {
        nameDictionary[data[r][0]] = data[r][1];
      }
      if (data[r][2] != '') {
        addressDictionary[data[r][0]] = data[r][2];
      }
      if (data[r][3] != '') {
        phoneDictionary[data[r][0]] = data[r][3];
      }
    }
  }

  for (var r = 1; r < data.length; r++) {
    if (data[r][1] == '') {
      data[r][1] = nameDictionary[data[r][0]];
    }
    if (data[r][2] == '') {
      data[r][2] = addressDictionary[data[r][0]]
    }
    if (data[r][3] == '') {
      data[r][3] = phoneDictionary[data[r][0]];
    }
  }

  SpreadsheetApp.getActive().getDataRange().setValues(data)
}

The code will initiate reading all your table with SpreadsheetApp.getActive(), Spreadsheet.getDataRange() and Range.getValues(). After that it will create three objects as dictionaries.

After that the code will iterate each row and record in the dictionaries each value (name, phone and address) associated with the ID. Afterwards, the code will repeat the operation but writing down the values. Finally, all the data is loaded in the sheet with Range.setValues(). For example, if we have this spreadsheet:

And we use the script, we will end up with this:

Please, notice how some ID doesn't have any phones; these are left empty. I understand that you may be using a very big database, so I optimized the code so it will run the fastest possible without taking into account the data size. Also, this code will work even if the rows aren't ordered. Don't hesitate to ask me any question if you have doubts.