问:
Index.js Error: UserForm(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null
Hi I am fairly new to react . I am fairly new to react and I am trying add a row in my react app on the click of a button. I followed this link How to add and remove table rows Dynamically in React.js

to do so but I am not able to translate it to my code.

I am getting this error.

Error: UserForm(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.

```<code>Module../src/index.js
D:/react_bpms1/src/index.js:7
   4 | import App from './App';
   5 | import * as serviceWorker from './serviceWorker';
   6 |
>  7 | ReactDOM.render(
   8 |   <React.StrictMode>
   9 |     <App />
  10 |   </React.StrictMode>,
View compiled
__webpack_require__
D:/react_bpms1/webpack/bootstrap:784
  781 | };
  782 |
  783 | // Execute the module function
> 784 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  785 |
  786 | // Flag the module as loaded
  787 | module.l = true;
View compiled
fn
D:/react_bpms1/webpack/bootstrap:150
  147 |         );
  148 |         hotCurrentParents = [];
  149 |     }
> 150 |     return __webpack_require__(request);
      | ^  151 | };
  152 | var ObjectFactory = function ObjectFactory(name) {
  153 |     return {
View compiled
1
http://localhost:3000/static/js/main.chunk.js:2076:18
__webpack_require__
D:/react_bpms1/webpack/bootstrap:784
  781 | };
  782 |
  783 | // Execute the module function
> 784 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  785 |
  786 | // Flag the module as loaded
  787 | module.l = true;
View compiled
checkDeferredModules
D:/react_bpms1/webpack/bootstrap:45
  42 |  }
  43 |  if(fulfilled) {
  44 |      deferredModules.splice(i--, 1);
> 45 |      result = __webpack_require__(__webpack_require__.s = deferredModule[0]);
     | ^  46 |  }
  47 | }
  48 |
View compiled
Array.webpackJsonpCallback [as push]
D:/react_bpms1/webpack/bootstrap:32
  29 |  deferredModules.push.apply(deferredModules, executeModules || []);
  30 |
  31 |  // run deferred modules when all chunks ready
> 32 |  return checkDeferredModules();
     | ^  33 | };
  34 | function checkDeferredModules() {
  35 |  var result;
View compiled
(anonymous function)
http://localhost:3000/static/js/main.chunk.js:1:75
</code>```

Here is my code:

My code here: KPIDetails.js Here I am rendering the view in KPI Details.js file.

```<code><MuiThemeProvider>
  <React.Fragment>
    <Grid container>
      <Grid item xs={6} direction="row" alignItems="center">
        <table className="table table-bordered table-hover" id="tab_logic">
          <thead>
            <tr>
              <th className="text-center"> KPI</th>
              <th className="text-center"> UOM</th>
              <th className="text-center"> Base</th>
              <th className="text-center"> Target</th>
              <th className="text-center"> Target Date</th>
            </tr>
          </thead>
          <tbody>
            {this.state.rows.map((item, idx) => (
              <tr id="addr0" key={idx}>
                <td>{idx}</td>
                <td>
                  <input
                    type="text"
                    name="Kpi_Before"
                    value={this.state.rows[idx].Kpi_Before}
                    onChange={this.handleChangeRows(idx)}
                    className="form-control"
                  />
                </td>
                <td>
                  <input
                    type="text"
                    name="UOM_Before"
                    value={this.state.rows[idx].UOM_Before}
                    onChange={this.handleChangeRows(idx)}
                    className="form-control"
                  />
                </td>
                <td>
                  <input
                    type="text"
                    name="Base_Before"
                    value={this.state.rows[idx].Base_Before}
                    onChange={this.handleChangeRows(idx)}
                    className="form-control"
                  />
                </td>
                <td>
                  <input
                    type="text"
                    name="Target_Before"
                    value={this.state.rows[idx].Target_Before}
                    onChange={this.handleChangeRows(idx)}
                    className="form-control"
                  />
                </td>
                <td>
                  <input
                    type="text"
                    name="Target_Before"
                    value={this.state.rows[idx].dateTime}
                    onChange={this.handleChangeRows(idx)}
                    className="form-control"
                  />
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        <button
          onClick={this.handleRemoveRow}
          className="pull-right btn btn-default"
        >
          Delete Row
        </button>
        <Button
          variant="outlined"
          color="primary"
          onClick={this.handleAddRow}
          size="small"
          style={styles.button}
        >
          +
        </Button>
      </Grid>
    </Grid>
  </React.Fragment>
</MuiThemeProvider>;
</code>```

Here is my code for UserFormjs where I write all the functions:

```<code>export class UserForm extends Component {
  state = {
    step: 1,
    Title: "",
    Details: "",
    What: "",
    Why: "",
    How: "",
    Status: "",
    Cost: "",
    Benefits: "",
    Kpi_Before: "",
    Kpi_After: "",
    Time: "",
    UOM_Before: "",
    Base_Before: "",
    Target_Before: "",
    dateTime: null,
    rows: []
  };

  //1
  handleChangeRows = idx => e => {
    const { Kpi_Before, value } = e.target;
    const rows = [...this.state.rows];
    rows[idx] = {
      [Kpi_Before]: value
    };
    this.setState({
      rows
    });
  };

  //2
  handleAddRow = () => {
    const item = {
      KPI_Before: "",
      UOM_Before: "",
      Base_Before: "",
      Target_Before: "",
      dateTime: ""
    };
    this.setState({
      rows: [...this.state.rows, item]
    });
  };

  //3
  handleRemoveRow = () => {
    this.setState({
      rows: this.state.rows.slice(0, -1)
    });
  };
}
</code>```

This is index.js:

```<code>import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById("root")
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.

serviceWorker.unregister();
</code>```

I don't understand this error. Also is there another way to do this? Achieve creating a table row on the click of a button?

答:
```<code>      class UserForm extends React.Component {
        state = {
        step: 1
        }
      render() {
        const { step } = this.state;
        switch (step) {
        case 1:
          return (
           <h1>Step: case1</h1>
          );
        case 2:
          return (
            <h1>step: case2</h1>
          );
        }
      }
    }
</code>```

I have tried this basic code, this is working fine with switch case. you can also try.It seems that problem is with FormUserDetails component.
Can you post code for that?

Body:
Hi I am fairly new to react . I am fairly new to react and I am trying add a row in my react app on the click of a button. I followed this link How to add and remove table rows Dynamically in React.js

to do so but I am not able to translate it to my code.

I am getting this error.

Error: UserForm(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.

Module../src/index.js
D:/react_bpms1/src/index.js:7
   4 | import App from './App';
   5 | import * as serviceWorker from './serviceWorker';
   6 |
>  7 | ReactDOM.render(
   8 |   <React.StrictMode>
   9 |     <App />
  10 |   </React.StrictMode>,
View compiled
__webpack_require__
D:/react_bpms1/webpack/bootstrap:784
  781 | };
  782 |
  783 | // Execute the module function
> 784 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  785 |
  786 | // Flag the module as loaded
  787 | module.l = true;
View compiled
fn
D:/react_bpms1/webpack/bootstrap:150
  147 |         );
  148 |         hotCurrentParents = [];
  149 |     }
> 150 |     return __webpack_require__(request);
      | ^  151 | };
  152 | var ObjectFactory = function ObjectFactory(name) {
  153 |     return {
View compiled
1
http://localhost:3000/static/js/main.chunk.js:2076:18
__webpack_require__
D:/react_bpms1/webpack/bootstrap:784
  781 | };
  782 |
  783 | // Execute the module function
> 784 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  785 |
  786 | // Flag the module as loaded
  787 | module.l = true;
View compiled
checkDeferredModules
D:/react_bpms1/webpack/bootstrap:45
  42 |  }
  43 |  if(fulfilled) {
  44 |      deferredModules.splice(i--, 1);
> 45 |      result = __webpack_require__(__webpack_require__.s = deferredModule[0]);
     | ^  46 |  }
  47 | }
  48 |
View compiled
Array.webpackJsonpCallback [as push]
D:/react_bpms1/webpack/bootstrap:32
  29 |  deferredModules.push.apply(deferredModules, executeModules || []);
  30 |
  31 |  // run deferred modules when all chunks ready
> 32 |  return checkDeferredModules();
     | ^  33 | };
  34 | function checkDeferredModules() {
  35 |  var result;
View compiled
(anonymous function)
http://localhost:3000/static/js/main.chunk.js:1:75

Here is my code:

My code here: KPIDetails.js Here I am rendering the view in KPI Details.js file.

<MuiThemeProvider>
  <React.Fragment>
    <Grid container>
      <Grid item xs={6} direction="row" alignItems="center">

               KPI
               UOM
               Base
               Target
               Target Date

            {this.state.rows.map((item, idx) => (

                {idx}

                  <input
                    type="text"
                    name="Kpi_Before"
                    value={this.state.rows[idx].Kpi_Before}
                    onChange={this.handleChangeRows(idx)}
                    className="form-control"
                  />

                  <input
                    type="text"
                    name="UOM_Before"
                    value={this.state.rows[idx].UOM_Before}
                    onChange={this.handleChangeRows(idx)}
                    className="form-control"
                  />

                  <input
                    type="text"
                    name="Base_Before"
                    value={this.state.rows[idx].Base_Before}
                    onChange={this.handleChangeRows(idx)}
                    className="form-control"
                  />

                  <input
                    type="text"
                    name="Target_Before"
                    value={this.state.rows[idx].Target_Before}
                    onChange={this.handleChangeRows(idx)}
                    className="form-control"
                  />

                  <input
                    type="text"
                    name="Target_Before"
                    value={this.state.rows[idx].dateTime}
                    onChange={this.handleChangeRows(idx)}
                    className="form-control"
                  />

            ))}

        <button
          onClick={this.handleRemoveRow}
          className="pull-right btn btn-default"
        >
          Delete Row
        </button>
        <Button
          variant="outlined"
          color="primary"
          onClick={this.handleAddRow}
          size="small"
          style={styles.button}
        >
          +
        </Button>
      </Grid>
    </Grid>
  </React.Fragment>
</MuiThemeProvider>;

Here is my code for UserFormjs where I write all the functions:

export class UserForm extends Component {
  state = {
    step: 1,
    Title: "",
    Details: "",
    What: "",
    Why: "",
    How: "",
    Status: "",
    Cost: "",
    Benefits: "",
    Kpi_Before: "",
    Kpi_After: "",
    Time: "",
    UOM_Before: "",
    Base_Before: "",
    Target_Before: "",
    dateTime: null,
    rows: []
  };

  //1
  handleChangeRows = idx => e => {
    const { Kpi_Before, value } = e.target;
    const rows = [...this.state.rows];
    rows[idx] = {
      [Kpi_Before]: value
    };
    this.setState({
      rows
    });
  };

  //2
  handleAddRow = () => {
    const item = {
      KPI_Before: "",
      UOM_Before: "",
      Base_Before: "",
      Target_Before: "",
      dateTime: ""
    };
    this.setState({
      rows: [...this.state.rows, item]
    });
  };

  //3
  handleRemoveRow = () => {
    this.setState({
      rows: this.state.rows.slice(0, -1)
    });
  };
}

This is index.js:

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById("root")
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.

serviceWorker.unregister();

I don't understand this error. Also is there another way to do this? Achieve creating a table row on the click of a button?

Body:
      class UserForm extends React.Component {
        state = {
        step: 1
        }
      render() {
        const { step } = this.state;
        switch (step) {
        case 1:
          return (
           <h1>Step: case1</h1>
          );
        case 2:
          return (
            <h1>step: case2</h1>
          );
        }
      }
    }

I have tried this basic code, this is working fine with switch case. you can also try.It seems that problem is with FormUserDetails component.
Can you post code for that?


来源: stackexchange

问:
how to configure listenerhttp processor in NIFI
i'm using nifi with our web app ...we want to configure listenhttp processor that listen our web service. question is what are the configuration in http listener processor in nifi such that when we will make curl post request this ListenHttp processor will catch the update. basically i didn't understand what i have to put in Base path(is it i have to put nifi add i.e http://localhost:8080/contentListener or our web app service URL???) what is contentListener. And is it i have to put our web app port number in listening port?
in the request command what i have to put in url part

```<code>curl --request POST 'http://(here i have to used the nifi url)' -H 'Authorization: Key demo-key
</code>```

i know this is very basic question but i'm just using this don't know any thing about nifi and curl command .....thanks in advance

答:
The ListenHTTP processor starts an internal web server and allows incoming connections (i.e. some other entity making an HTTP request to this address). It does not monitor an external HTTP resource and notify on changes. For this, you may want an InvokeHTTP processor which performs a GET request against your other service and processes the response, detecting changes via your logic (absence/presence of specific values, etc.).

Additional information

The "Base Path" value is the path for this specific listener. If you had multiple ListenHTTP processors, you would want to differentiate them. The default value is contentListener, which would result in external services needing to connect to http://nifi.service:9999/contentListener. The port is specified by "Listening Port". To enable TLS, configure and reference an SSLContextService in the "SSL Context Service" property.

The ListenHTTP processor does not provide token-based authentication, so if you want to provide a key in the "Authorization" header, you will need to put custom logic in subsequent processors to evaluate the presence and value of that header.

ContentLicense: CC BY-SA 4.0

Body:
i'm using nifi with our web app ...we want to configure listenhttp processor that listen our web service. question is what are the configuration in http listener processor in nifi such that when we will make curl post request this ListenHttp processor will catch the update. basically i didn't understand what i have to put in Base path(is it i have to put nifi add i.e http://localhost:8080/contentListener or our web app service URL???) what is contentListener. And is it i have to put our web app port number in listening port?
in the request command what i have to put in url part

curl --request POST 'http://(here i have to used the nifi url)' -H 'Authorization: Key demo-key

i know this is very basic question but i'm just using this don't know any thing about nifi and curl command .....thanks in advance


问:
Chrome not displaying images though assets are being delivered to browser
I am having an issue only with Chrome (so far that I can tell).  On this website: www.elliott-web.com the homepage displays a random image on load.  After several reloads I get no image showing up, but when checking the http requests I see the image is there.  Similarly, on the portfolio page if you click forward and backward through the images, eventually an image will no longer show up.  Again, looks like the image is there but it's not being displayed.  Thought maybe it has to do w/ Chrome's caching?  I don't think it's webkit because I'm not having this problem in Safari.

Anyone else seen this before?

答:
I too was having the exact same issue, it also does this in Safari (Mac). In Firefox the images display and the inline CSS is not added.

What I noticed was when I turned off all extensions in Safari that the problem resolved.

In both Chrome and Safari I had AdBlockPlus installed - disabling this resolved the problem.

ABP was treating the images as ads (for whatever reason).

If you wish to keep ABP running, you can add the site to it's whitelist.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Loop through array in react onclick using Hooks
I have an array of objects that I load from a json file and I want each item to load separately when I click a button. I completed that but the main problem is when the index goes out of bounds so then it shows

TypeError "Cannot read property 'content' of undefined".

How can I make then index be 0 again when the index reaches the last item? I tried solving it by including some if statements inside the button but no luck.
Here is the related part of the code till now:

```<code>function App() {
  const classes = useStyles();
  const questions_size = Data.length;
  const [num, setNum] = useState(0);
  const current = Data[num].content;

  (...)
  return (
    <Container>
      <Typography variant="h3" gutterBottom>
        About
      </Typography>
      <Button variant="contained" color="primary" onClick={()=> num<questions_size?setNum(num+1): setNum(0)}>Επομενο</Button>
      <Card className={classes.root}>
        <CardContent>

          <Typography variant="body1" gutterBottom>
            <p style={{ fontFamily: 'Tangerine, serif', fontSize: '35px', textShadow: '4px 4px 4px #aaa'}}>{current}</p>
          </Typography>
        </CardContent>
      </Card>
    </Container>
  )
</code>```

答:
this code will only run when the data changes.

useEffect(() => {
  if (num > Data.length) {
    setNum(0)
  }
},[Data])
```

Body:
I have an array of objects that I load from a json file and I want each item to load separately when I click a button. I completed that but the main problem is when the index goes out of bounds so then it shows

TypeError "Cannot read property 'content' of undefined".

How can I make then index be 0 again when the index reaches the last item? I tried solving it by including some if statements inside the button but no luck.
Here is the related part of the code till now:

function App() {
  const classes = useStyles();
  const questions_size = Data.length;
  const [num, setNum] = useState(0);
  const current = Data[num].content;

  (...)
  return (
    <Container>
      <Typography variant="h3" gutterBottom>
        About
      </Typography>
      <Button variant="contained" color="primary" onClick={()=> num<questions_size?setNum(num+1): setNum(0)}>Επομενο</Button>
      <Card className={classes.root}>
        <CardContent>

          <Typography variant="body1" gutterBottom>

{current}

          </Typography>
        </CardContent>
      </Card>
    </Container>
  )


问:
How to modify new records for INSERT ON DUPLICATE in Mysql

Situation

Imagine a table columns A,B,C with a unique key on B and C and an autoincrement primary key on A

When sending new values (B,C) (42,1) and this table already contains a row with B,C being 42 and 1 on lets say ID 10, then the Mysql Server will not allow this and return :

```<code>Duplicate Entry ... for key ... .
</code>```

Problem:

I would like to act on this and modify (increment) the value for C, to 2, so (42,2) could be inserted.

Failed tried solution

I found the INSERT .. ON DUPLICATE UPDATE ... but this updates the existing record. not the new values.

Existing record may not be edited

I have no way to query the table beforehand, everything should be done in 1 query

incremented new values may also already exist, and thus should continue increment (c = 3..4..5...)

Any idea how this can be done ?

答:
You can use UPDATE C=C+1 in your ON DUP statement like this

```<code>INSERT <table> (A,B,C) VALUES(1,23,1)
ON DUPLICATE KEY UPDATE C=C+1;
</code>```

I assumed your table was like this?

```<code>CREATE TABLE `new_table` (
  `A` int(11) NOT NULL AUTO_INCREMENT,
  `B` int(11) DEFAULT NULL,
  `C` int(11) DEFAULT NULL,
  PRIMARY KEY (`A`),
  UNIQUE KEY `BC_IDX` (`B`,`C`)
);
</code>```

I then ran this INSERT

```<code>INSERT test.new_table (A,B,C) VALUES(1,23,1)
ON DUPLICATE KEY UPDATE C=C+1;
</code>```

RESULT

```<code>A   B   C
1   23  1
</code>```

Then ran the same query again

```<code>INSERT test.new_table (A,B,C) VALUES(1,23,1)
ON DUPLICATE KEY UPDATE C=C+1;
</code>```

RESULT

```<code>A   B   C
1   23  2
</code>```

And run query again....
RESULT

```<code>A   B   C
1   23  3
</code>```

Body:
Situation

Imagine a table columns A,B,C with a unique key on B and C and an autoincrement primary key on A

When sending new values (B,C) (42,1) and this table already contains a row with B,C being 42 and 1 on lets say ID 10, then the Mysql Server will not allow this and return :

Duplicate Entry ... for key ... .

Problem:

I would like to act on this and modify (increment) the value for C, to 2, so (42,2) could be inserted.

Failed tried solution

I found the INSERT .. ON DUPLICATE UPDATE ... but this updates the existing record. not the new values.

Existing record may not be edited

I have no way to query the table beforehand, everything should be done in 1 query

incremented new values may also already exist, and thus should continue increment (c = 3..4..5...)

Any idea how this can be done ?

Body:
You can use UPDATE C=C+1 in your ON DUP statement like this

INSERT <table> (A,B,C) VALUES(1,23,1)
ON DUPLICATE KEY UPDATE C=C+1;

I assumed your table was like this?

CREATE TABLE `new_table` (
  `A` int(11) NOT NULL AUTO_INCREMENT,
  `B` int(11) DEFAULT NULL,
  `C` int(11) DEFAULT NULL,
  PRIMARY KEY (`A`),
  UNIQUE KEY `BC_IDX` (`B`,`C`)
);

I then ran this INSERT

INSERT test.new_table (A,B,C) VALUES(1,23,1)
ON DUPLICATE KEY UPDATE C=C+1;

RESULT

A   B   C
1   23  1

Then ran the same query again

INSERT test.new_table (A,B,C) VALUES(1,23,1)
ON DUPLICATE KEY UPDATE C=C+1;

RESULT

A   B   C
1   23  2

And run query again....
RESULT

A   B   C
1   23  3


问:
Why does calling os.tmpDir() produce an error on only some machines?
I am a web development student and a friend of mine is as well. Currently we are utilizing the same files provided by the same textbook in the same class. The point of the exercise is to practice with require.js and explore what it can do. Both of us have taken the same steps to ensure that the proper packages are downloaded and that node and npm versions are up to date.

When node index.js is run on my machine, the server begins listening on ::8080 and prints os.tmpDir() is deprecated. Use os.tmpdir() instead. As I am still fairly new, I'm not 100% sure what deprecation actually is, but I know that the app still works.

When node index.js is run on her machine, she receives an error stating os.tmpDir() is not a function. Where I can go to localhost:8080, she cannot.

We have tried uninstalling and reinstalling node (both stable and latest versions), comparing files (which are identical), and comparing package versions. Somehow, it seems that despite there being no differences between what we are working with (aside from our machines), we are experiencing two different results.

Any suggestions?

The error message:

C:\Users\Nereida\Documents\Classes\Summer2020\WEB.215\requirejs\node_modules\mach\lib\utils\makeTemporaryPath.js:4
var TMP_DIR = require("os").tmpDir();
                            ^

TypeError: require(...).tmpDir is not a function
    at Object.<anonymous> (C:\Users\Nereida\Documents\Classes\Summer2020\WEB.215\requirejs\node_modules[4mmach[24m\lib\utils\makeTemporaryPath.js:4:29)
    at Module._compile (internal/modules/cjs/loader.js:1200:30)[39m
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1220:10)[39m
    at Module.load (internal/modules/cjs/loader.js:1049:32)[39m
    at Function.Module._load (internal/modules/cjs/loader.js:937:14)[39m
    at Module.require (internal/modules/cjs/loader.js:1089:19)[39m
    at require (internal/modules/cjs/helpers.js:73:18)[39m
    at Object.<anonymous> (C:\Users\Nereida\Documents\Classes\Summer2020\WEB.215\requirejs\node_modules[4mmach[24m\lib\utils\saveToDisk.js:6:25)
    at Module._compile (internal/modules/cjs/loader.js:1200:30)[39m
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1220:10)
```

答:
The answer comes as a comment from djfdev:

There's your problem, she needs to use os.tmpdir() with a lowercase d. As you pointed out, there was a deprecation warning about using the version with the uppercase D. It looks like this was removed entirely in node 14.

So simple... so much time. You are my savior djfdev!


问:
How do I conditionally render from three different options in React Native?
I want to conditionally render in React Native, but there are three different options: loading screen, the user has no messages, or display all the users messages. I have a variable called conversations which is fetched from my database, but before the fetch completes it is null, so I want to display a loading indicator. After the fetch is complete, I want to display a message if the user has no current chats, or display a table containing all the users chats if the user does have existing chats. My thought was something like this:

return (
  <View>
    {conversations ? conversations.length === 0 ? (
      <Text>You have no messages.</Text>
    ) : (
      <ConversationTable conversations={conversations} />
    ) : (
      <ActivityIndicator />
    )}
  </View>
)
```

Is there a better way to do this?

答:
You can do something like this:</p>

```<code>return (
  <View>
    {conversations === null && <LoadingIndicator />} //The loading indicator will be present only when conversartions is null
    {conversations !== null && conversations.length === 0 ? ( // The conversations.length will be evaluated only when conversations is different to null
      <Text>You have no messages.</Text>
    ) : (
      <ConversationTable conversations={conversations} />
    )}
  </View>
)
</code>```

Body:
I want to conditionally render in React Native, but there are three different options: loading screen, the user has no messages, or display all the users messages. I have a variable called conversations which is fetched from my database, but before the fetch completes it is null, so I want to display a loading indicator. After the fetch is complete, I want to display a message if the user has no current chats, or display a table containing all the users chats if the user does have existing chats. My thought was something like this:

return (
  <View>
    {conversations ? conversations.length === 0 ? (
      <Text>You have no messages.</Text>
    ) : (
      <ConversationTable conversations={conversations} />
    ) : (
      <ActivityIndicator />
    )}
  </View>
)

Is there a better way to do this?

Body:
You can do something like this:

return (
  <View>
    {conversations === null && <LoadingIndicator />} //The loading indicator will be present only when conversartions is null
    {conversations !== null && conversations.length === 0 ? ( // The conversations.length will be evaluated only when conversations is different to null
      <Text>You have no messages.</Text>
    ) : (
      <ConversationTable conversations={conversations} />
    )}
  </View>
)


问:
How to handle git gc fatal: bad object refs/remotes/origin/HEAD error?
I randomly hit this today while trying to run Git garbage collect:

```<code>$ git gc
fatal: bad object refs/remotes/origin/HEAD
error: failed to run repack
</code>```

How do I deal with this?

答:
The cause of this for me was working in a compressed folder in Windows.  When the folder was uncompressed, it corrupted the pack files, cascading other odd issues, such as not being able to prune nonexistent branches.  </p>

<p>The only fix was to wipe out the working directory and clone the repo remote(s) again. Luckily, I could still push and pull updates to ensure nothing was lost.  All is well now.  </p>

Body:
I randomly hit this today while trying to run Git garbage collect:

$ git gc
fatal: bad object refs/remotes/origin/HEAD
error: failed to run repack

How do I deal with this?

Body:
The cause of this for me was working in a compressed folder in Windows.  When the folder was uncompressed, it corrupted the pack files, cascading other odd issues, such as not being able to prune nonexistent branches.

The only fix was to wipe out the working directory and clone the repo remote(s) again. Luckily, I could still push and pull updates to ensure nothing was lost.  All is well now.


问:
Flask PyMongo HTML show Read Data
I'm with my teams are currently working on some project face recognition presence system for COVID-19 anticipation, so people don't have to touch unnecessary things in the factory.

Right now, i am trying to show the data absence (for HRD / absence administrator access only) from my team's mongoDB atlas. My HTML is loaded but it seems it's only load blank data.

this is my app.route /database on app.py

```<code>@app.route("/database", methods=['GET', 'POST'])
def database():
    if not session.get('email'):
        return redirect(url_for('login'))

    elif request.method == 'POST':
        dataCollection = mongo.db.Presence_Data_Table.find()
        data = []
        for i in dataCollection:
            data.append()

    return render_template('database.html')
</code>```

and this is my database.html

The relevant code:

```<code><body>
    <div class="head-title">
       <h1>Admin Sign up</h1>
    </div>
    <table>
    {% for i in dataCollection %}
    <tr>
        <td>
            <span>{{ i['Nama'] }}</span>
        </td>
        <td>
            <span>{{ i['Tanggal'] }}</span>
        </td>
        <td>
            <span>{{ i['Waktu'] }}</span>
        </td>
        <td>
            <span>{{ i['Activity'] }}</span>
        </td>
    </tr>
    {% endfor %}
    </table>
</body>
</html>
</code>```

Any idea what's wrong with it?
I'm sorry, i'm still newbie in flask development

Here what it's show up on my browser:
https://i.imgur.com/uMVYc59.jpg

And here's what's inside dataCollection
https://i.imgur.com/zkMSFmZ.jpg

答:
In your code above you are using the variable dataCollection , however as mentioned in the comments by ngShravil.py . You do not pass the variable from your back end web server to your browser.

You need to modify the following lines:

```<code>return render_template('database.html')
</code>```

to this:

```<code>return render_template('database.html',data=data)
</code>```

and then in your .html file do this :

```<code>{% for i in data%}
</code>```

Title: Flask PyMongo HTML show Read Data

Body:
I'm with my teams are currently working on some project face recognition presence system for COVID-19 anticipation, so people don't have to touch unnecessary things in the factory.

Right now, i am trying to show the data absence (for HRD / absence administrator access only) from my team's mongoDB atlas. My HTML is loaded but it seems it's only load blank data.

this is my app.route /database on app.py

@app.route("/database", methods=['GET', 'POST'])
def database():
    if not session.get('email'):
        return redirect(url_for('login'))

    elif request.method == 'POST':
        dataCollection = mongo.db.Presence_Data_Table.find()
        data = []
        for i in dataCollection:
            data.append()

    return render_template('database.html')

and this is my database.html

The relevant code:

Admin Sign up

    {% for i in dataCollection %}

            {{ i['Nama'] }}

            {{ i['Tanggal'] }}

            {{ i['Waktu'] }}

            {{ i['Activity'] }}

    {% endfor %}

Any idea what's wrong with it?
I'm sorry, i'm still newbie in flask development

Here what it's show up on my browser:
https://i.imgur.com/uMVYc59.jpg

And here's what's inside dataCollection
https://i.imgur.com/zkMSFmZ.jpg

Body:
In your code above you are using the variable dataCollection , however as mentioned in the comments by ngShravil.py . You do not pass the variable from your back end web server to your browser.

You need to modify the following lines:

return render_template('database.html')

to this:

return render_template('database.html',data=data)

and then in your .html file do this :

{% for i in data%}


问:
Selenium c# - how do i test that an image src file exists (verifying if the image shows on the page)
im new to Selenium and c# so I've hit a dead end.  I need to know how to check weather an images src file exists or not.  When I mean exists, is it showing on the page (not the red x box you get when no image is present).

I have tried file.exists(@c://imagename); and System.File.Exists.

I don't know if this is correct or not.

Any help would be great!! My heads fried with this

Thanks

答:
You can't do it, at least not solely with Selenium.  Depending on which browser you're testing with, you might be able to look into the on-disk browser cache and find the file, but not all browsers cache everything to disk, and figuring out the filename may be very difficult.

Without Selenium, of course, you can use curl, wget, et al. to download the image file, or you could possibly screen-shot the browser and search for the "red X box" yourself.  But neither is really a nice answer.


问:
Scraping using selenium
Hi I am trying to scrape this website I originally was using Bs4 and that was fine to get certain elements. Sector, name etc. But I am not able to use it to get the financial data. Below I have copied some of the page_source the "-" should be in this case 0.0663. I believe I am trying to scrape javascript and I have looked around and none of the solutions I have seen have worked for me. I was wondering if someone could help me crack this.

Although I will be grateful if someone can post some working code I would also really appreciate if you can point me in the right direction as well to understand what to look for in the html which shows me what I need to do and how to get it kinda thing.

URL: https://www.tradingview.com/symbols/LSE-TSCO/

HTML:

    Return on Equity (TTM)

    —

```

<p>Python Code:</p>

<pre class="lang-py prettyprint-override"><code>url = "https://www.tradingview.com/symbols/LSE-TSCO/"
options = webdriver.ChromeOptions()
options.add_argument('headless')
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get(url)
html = driver.page_source
</code>```

答:
The issue here is not with the element being present or not, but the time the page takes to load. The page looks very heavy with all those dynamic graphs..Even before the page is fully loaded in, the DOM start to get created and default values are taking place.

WebDriverWait with find_element_* works when the element is currently not present but will take a certain time to appear. In your context, it is present from the start and adding it won't do much. This is also why you get '-', as the element is present with its default value.

To fix this or reduce the issue, you can add code to wait until the document readyState is completed

Something like this can be used:

```<code>def wait_for_page_ready_state(driver):
    wait = WebDriverWait(driver, 20)

    def _ready_state_script(driver):
        return driver.execute_async_script(
                """
                var callback = arguments[arguments.length - 1];
                callback(document.readyState);
                """) == 'complete'
    wait.until(_ready_state_script)

wait_for_page_ready_state(driver)
</code>```

Then since you brought bs4 in play, this is where I would use it:

```<code>financials = {}
for el in BeautifulSoup(driver.page_source, "lxml").find_all('div', {"class": "tv-widget-fundamentals__row"}):
    try:
        key = re.sub('\s+', ' ', el.find('span', {"class": "tv-widget-fundamentals__label "
                                                       "apply-overflow-tooltip"}).text.strip())
        value = re.sub('\s+', ' ', el.find('span', {"class": "tv-widget-fundamentals__value"}).text.strip())

        financials[key] = value
    except AttributeError:
        pass
</code>```

This will give you every value you need from the financial card.

You can now print the value you need:

```<code>print(financials['Return on Equity (TTM)'])
</code>```

Output:

```<code>'0.0663'
</code>```

Of course you can do the above with selenium as well, but wanted to provide with what you started to work with.

To be noted that this does not guaranty to always return the proper value. It might and did in my case, but since you know the default value you could add a while loop until the default change.

[EDIT]
After running my code in a loop, I was hitting the default value 1/5 times. One way to work around it would be to create a method and loop until a threshold is reached. In my finding, you will always have ~90% of the value updated with digit. When it fails with the default value, all other values were also at '-'. One way will be to use a threshold (i.e 50% and only return the values once it is reached).

```<code>    def get_financial_card_values(default_value='—', threshold=.5):
        financials = {}
        while True:
            for el in BeautifulSoup(driver.page_source, "lxml").find_all('div', {"class": "tv-widget-fundamentals__row"}):
                try:
                    key = re.sub('\s+', ' ', el.find('span', {"class": "tv-widget-fundamentals__label "
                                                                       "apply-overflow-tooltip"}).text.strip())
                    value = re.sub('\s+', ' ', el.find('span', {"class": "tv-widget-fundamentals__value"}).text.strip())

                    financials[key] = value
                except AttributeError:
                    pass
            number_of_updated_values = [value for value in financials.values() if value != default_value]
            if len(number_of_updated_values) / len(financials) > threshold:
                return financials
</code>```

With this method, I was able to always retrieve the value you are expecting. Note that if all values won't change (site issue) you will be in a loop for ever, you might want to use a timer instead of while True. Just want to point this out, but I don't think it will happen.

Title: Scraping using selenium

Body:
Hi I am trying to scrape this website I originally was using Bs4 and that was fine to get certain elements. Sector, name etc. But I am not able to use it to get the financial data. Below I have copied some of the page_source the "-" should be in this case 0.0663. I believe I am trying to scrape javascript and I have looked around and none of the solutions I have seen have worked for me. I was wondering if someone could help me crack this.

Although I will be grateful if someone can post some working code I would also really appreciate if you can point me in the right direction as well to understand what to look for in the html which shows me what I need to do and how to get it kinda thing.

URL: https://www.tradingview.com/symbols/LSE-TSCO/

HTML:

    Return on Equity (TTM)

    —

Python Code:

url = "https://www.tradingview.com/symbols/LSE-TSCO/"
options = webdriver.ChromeOptions()
options.add_argument('headless')
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get(url)
html = driver.page_source

Body:
The issue here is not with the element being present or not, but the time the page takes to load. The page looks very heavy with all those dynamic graphs..Even before the page is fully loaded in, the DOM start to get created and default values are taking place.

WebDriverWait with find_element_* works when the element is currently not present but will take a certain time to appear. In your context, it is present from the start and adding it won't do much. This is also why you get '-', as the element is present with its default value.

To fix this or reduce the issue, you can add code to wait until the document readyState is completed

Something like this can be used:

def wait_for_page_ready_state(driver):
    wait = WebDriverWait(driver, 20)

    def _ready_state_script(driver):
        return driver.execute_async_script(
                """
                var callback = arguments[arguments.length - 1];
                callback(document.readyState);
                """) == 'complete'
    wait.until(_ready_state_script)

wait_for_page_ready_state(driver)

Then since you brought bs4 in play, this is where I would use it:

financials = {}
for el in BeautifulSoup(driver.page_source, "lxml").find_all('div', {"class": "tv-widget-fundamentals__row"}):
    try:
        key = re.sub('\s+', ' ', el.find('span', {"class": "tv-widget-fundamentals__label "
                                                       "apply-overflow-tooltip"}).text.strip())
        value = re.sub('\s+', ' ', el.find('span', {"class": "tv-widget-fundamentals__value"}).text.strip())

        financials[key] = value
    except AttributeError:
        pass

This will give you every value you need from the financial card.

You can now print the value you need:

print(financials['Return on Equity (TTM)'])

Output:

'0.0663'

Of course you can do the above with selenium as well, but wanted to provide with what you started to work with.

To be noted that this does not guaranty to always return the proper value. It might and did in my case, but since you know the default value you could add a while loop until the default change.

[EDIT]
After running my code in a loop, I was hitting the default value 1/5 times. One way to work around it would be to create a method and loop until a threshold is reached. In my finding, you will always have ~90% of the value updated with digit. When it fails with the default value, all other values were also at '-'. One way will be to use a threshold (i.e 50% and only return the values once it is reached).

    def get_financial_card_values(default_value='—', threshold=.5):
        financials = {}
        while True:
            for el in BeautifulSoup(driver.page_source, "lxml").find_all('div', {"class": "tv-widget-fundamentals__row"}):
                try:
                    key = re.sub('\s+', ' ', el.find('span', {"class": "tv-widget-fundamentals__label "
                                                                       "apply-overflow-tooltip"}).text.strip())
                    value = re.sub('\s+', ' ', el.find('span', {"class": "tv-widget-fundamentals__value"}).text.strip())

                    financials[key] = value
                except AttributeError:
                    pass
            number_of_updated_values = [value for value in financials.values() if value != default_value]
            if len(number_of_updated_values) / len(financials) > threshold:
                return financials

With this method, I was able to always retrieve the value you are expecting. Note that if all values won't change (site issue) you will be in a loop for ever, you might want to use a timer instead of while True. Just want to point this out, but I don't think it will happen.


问:
Android sharedpreferences
I've been following this tutorial and i am stuck.

```<code>public class Main extends Activity {

    SharedPreferences mPrefs;

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

        if(getFirstRun())
        {
            Toast.makeText(Main.this, "firstrun", Toast.LENGTH_SHORT).show();
            setRunned();
        }
        else
        {
            Toast.makeText(Main.this, "not firstrun", Toast.LENGTH_SHORT).show();
        }

    }

    public boolean getFirstRun() {
        return mPrefs.getBoolean("firstRun", true);
     }
    public void setRunned() {
        SharedPreferences.Editor edit = mPrefs.edit();
        edit.putBoolean("firstRun", false);
        edit.commit();
     }
    public void firstRunPreferences() {
        Context mContext = Main.this.getApplicationContext();
        mPrefs = mContext.getSharedPreferences("myAppPrefs", 0);
     }

}`
</code>```

Everytime i run it in Eclipse it says "not firstrun". I guess the preferences reset every time the app is reinstalled, so what is wrong with the code? As far as i remember, i saw once "firstrun".

Thanks

答:
SharedPreferences are not cleaned by uninstall.

If you want something cleaned after reinstall, put a field in your database.

Stéphane

Title: Android sharedpreferences

Body:
I've been following this tutorial and i am stuck.

public class Main extends Activity {

    SharedPreferences mPrefs;

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

        if(getFirstRun())
        {
            Toast.makeText(Main.this, "firstrun", Toast.LENGTH_SHORT).show();
            setRunned();
        }
        else
        {
            Toast.makeText(Main.this, "not firstrun", Toast.LENGTH_SHORT).show();
        }

    }

    public boolean getFirstRun() {
        return mPrefs.getBoolean("firstRun", true);
     }
    public void setRunned() {
        SharedPreferences.Editor edit = mPrefs.edit();
        edit.putBoolean("firstRun", false);
        edit.commit();
     }
    public void firstRunPreferences() {
        Context mContext = Main.this.getApplicationContext();
        mPrefs = mContext.getSharedPreferences("myAppPrefs", 0);
     }

}`

Everytime i run it in Eclipse it says "not firstrun". I guess the preferences reset every time the app is reinstalled, so what is wrong with the code? As far as i remember, i saw once "firstrun".

Thanks


问:
How do I replace a cell's contents when it matches a specific string?
I have this line working:

```<code>access$`Reading Score` <- gsub('NA', '', access$`Reading Score`)
</code>```

However, I'd like to apply the same thing to 20+ more columns. Without having to explicitly write out all 20 column changes, is there a way to do this when the cell's contents exactly match 'NA'? I have a few columns that are people names so they have the string NA but I obviously don't want to apply the changes to those names, just the 20 columns where the entire cell's contents is 'NA'

Also, what should the second statement be if I want to properly replace with a NULL value?

答:
If you want to do an exact match use ==. You can use lapply to apply a function for multiple columns. If you have string 'NA' and if you want to replace it by the empty value you can do :

```<code>access[1:20] <- lapply(access[1:20], function(x) {x[x == 'NA'] <- '';x})
</code>```

You can replace '' with NA if you want to replace it NA.

In dplyr you can replace first 20 columns with NA using na_if :

```<code>library(dplyr)
access %>% mutate(across(1:20, na_if, 'NA'))
</code>```

As suggested by @Onyambu we can directly change the values for all the columns.

```<code>access[1:20][access[1:20]=="NA"] <- ''
#Or
access[1:20][access[1:20]=="NA"] <- NA
</code>```

Body:
I have this line working:

access$`Reading Score` <- gsub('NA', '', access$`Reading Score`)

However, I'd like to apply the same thing to 20+ more columns. Without having to explicitly write out all 20 column changes, is there a way to do this when the cell's contents exactly match 'NA'? I have a few columns that are people names so they have the string NA but I obviously don't want to apply the changes to those names, just the 20 columns where the entire cell's contents is 'NA'

Also, what should the second statement be if I want to properly replace with a NULL value?

Body:
If you want to do an exact match use ==. You can use lapply to apply a function for multiple columns. If you have string 'NA' and if you want to replace it by the empty value you can do :

access[1:20] <- lapply(access[1:20], function(x) {x[x == 'NA'] <- '';x})

You can replace '' with NA if you want to replace it NA.

In dplyr you can replace first 20 columns with NA using na_if :

library(dplyr)
access %>% mutate(across(1:20, na_if, 'NA'))

As suggested by @Onyambu we can directly change the values for all the columns.

access[1:20][access[1:20]=="NA"] <- ''
#Or
access[1:20][access[1:20]=="NA"] <- NA


问:
How to go from radio button checked indicator to full button
I am trying to style my wordpress plugin and I'm having a hard time with the radio buttons.

Here is the fiddle: https://jsfiddle.net/cd3wagvh/

I want to hide the radio buttons and instead change the background of the whole label when it is clicked.

I have tried many things but nothing seems to work.

This part in particular is not working as intended:

```<code>.pewc-checkbox-group-wrapper input[type=radio]:checked+label {
  background-color: red !important;
}
</code>```

Edit: I cannot edit the HTML as it's part of a WordPress plugin and that's how they have it.

Edit: I have the part of the php code where I can potentially reverse the order?

```<code>'<li><label for="%s"><input data-option-cost="%s" type="radio" name="%s[]" id="%s" class="pewc-radio-form-field" value="%s" %s> %s</label></li>',
</code>```

My php is no good, any help would be great!

答:
Here's a working fiddle: https://jsfiddle.net/3smfLhk8/3/

First, you need spaces around the +. CSS uses spaces to differentiate elements.

Second, the CSS element + next-element only works for two elements that are placed one after the other, not nested elements like you have in your example. In fact, there is currently no way to get the parent element via CSS selectors.

Instead of nesting the elements, you could structure the HTML with the <input> preceding the , like so:

    <input type="radio" id="first-option" value="option-1">
    First option

    <input type="radio" id="second-option" value="option-2">
    Second option

```

<p>and use the <code>first-element:checked ~ second-element</code> selector.</p>

<pre class="lang-css prettyprint-override"><code>li input[type="radio"] {
    display: none;
}

li label {
    display: inline-block;
    padding: 20px;
    border: 1px solid black;
    background-color: white;
}

li input[type=radio]:checked ~ label {
    background-color: red;
}
</code>```

Body:
I am trying to style my wordpress plugin and I'm having a hard time with the radio buttons.

Here is the fiddle: https://jsfiddle.net/cd3wagvh/

I want to hide the radio buttons and instead change the background of the whole label when it is clicked.

I have tried many things but nothing seems to work.

This part in particular is not working as intended:

.pewc-checkbox-group-wrapper input[type=radio]:checked+label {
  background-color: red !important;
}

Edit: I cannot edit the HTML as it's part of a WordPress plugin and that's how they have it.

Edit: I have the part of the php code where I can potentially reverse the order?

'
<input data-option-cost="%s" type="radio" name="%s[]" id="%s" class="pewc-radio-form-field" value="%s" %s> %s
',

My php is no good, any help would be great!

Body:
Here's a working fiddle: https://jsfiddle.net/3smfLhk8/3/

First, you need spaces around the +. CSS uses spaces to differentiate elements.

Second, the CSS element + next-element only works for two elements that are placed one after the other, not nested elements like you have in your example. In fact, there is currently no way to get the parent element via CSS selectors.

Instead of nesting the elements, you could structure the HTML with the <input> preceding the <label>, like so:

<ul>
<li>
    <input type="radio" id="first-option" value="option-1">
    <label for="first-option">First option</label>
</li>
<li>
    <input type="radio" id="second-option" value="option-2">
    <label for="second-option">Second option</label>
</li>
</ul>

and use the first-element:checked ~ second-element selector.

li input[type="radio"] {
    display: none;
}

li label {
    display: inline-block;
    padding: 20px;
    border: 1px solid black;
    background-color: white;
}

li input[type=radio]:checked ~ label {
    background-color: red;
}


问:
Move files from one s3 bucket to another in AWS using AWS lambda
I am trying to move files older than a hour from one s3 bucket to another s3 bucket using python boto3 AWS lambda function with following cases:

Both buckets can be in same account and different region.

Both buckets can be in different account and different region.

Both buckets can be in different account and same region.

I got some help to move files using the python code mentioned by @John Rotenstein

```<code>import boto3
from datetime import datetime, timedelta

SOURCE_BUCKET = 'bucket-a'
DESTINATION_BUCKET = 'bucket-b'

s3_client = boto3.client('s3')

# Create a reusable Paginator
paginator = s3_client.get_paginator('list_objects_v2')

# Create a PageIterator from the Paginator
page_iterator = paginator.paginate(Bucket=SOURCE_BUCKET)

# Loop through each object, looking for ones older than a given time period
for page in page_iterator:
    for object in page['Contents']:
        if object['LastModified'] < datetime.now().astimezone() - timedelta(hours=1):   # <-- Change time period here
            print(f"Moving {object['Key']}")

            # Copy object
            s3_client.copy_object(
                Bucket=DESTINATION_BUCKET,
                Key=object['Key'],
                CopySource={'Bucket':SOURCE_BUCKET, 'Key':object['Key']}
            )

            # Delete original object
            s3_client.delete_object(Bucket=SOURCE_BUCKET, Key=object['Key'])
</code>```

How can this be modified to cater the requirement

答:
An alternate approach would be to use Amazon S3 Replication, which can replicate bucket contents:

Within the same region, or between regions

Within the same AWS Account, or between different Accounts

Replication is frequently used when organizations need another copy of their data in a different region, or simply for backup purposes. For example, critical company information can be replicated to another AWS Account that is not accessible to normal users. This way, if some data was deleted, there is another copy of it elsewhere.

Replication requires versioning to be activated on both the source and destination buckets. If you require encryption, use standard Amazon S3 encryption options. The data will also be encrypted during transit.

You configure a source bucket and a destination bucket, then specify which objects to replicate by providing a prefix or a tag. Objects will only be replicated once Replication is activated. Existing objects will not be copied. Deletion is intentionally not replicated to avoid malicious actions. See: What Does Amazon S3 Replicate?

There is no "additional" cost for S3 replication, but you will still be charge for any Data Transfer charges when moving objects between regions, and for API Requests (that are tiny charges), plus storage of course.

Body:
I am trying to move files older than a hour from one s3 bucket to another s3 bucket using python boto3 AWS lambda function with following cases:

Both buckets can be in same account and different region.

Both buckets can be in different account and different region.

Both buckets can be in different account and same region.

I got some help to move files using the python code mentioned by @John Rotenstein

import boto3
from datetime import datetime, timedelta

SOURCE_BUCKET = 'bucket-a'
DESTINATION_BUCKET = 'bucket-b'

s3_client = boto3.client('s3')

# Create a reusable Paginator
paginator = s3_client.get_paginator('list_objects_v2')

# Create a PageIterator from the Paginator
page_iterator = paginator.paginate(Bucket=SOURCE_BUCKET)

# Loop through each object, looking for ones older than a given time period
for page in page_iterator:
    for object in page['Contents']:
        if object['LastModified'] < datetime.now().astimezone() - timedelta(hours=1):   # <-- Change time period here
            print(f"Moving {object['Key']}")

            # Copy object
            s3_client.copy_object(
                Bucket=DESTINATION_BUCKET,
                Key=object['Key'],
                CopySource={'Bucket':SOURCE_BUCKET, 'Key':object['Key']}
            )

            # Delete original object
            s3_client.delete_object(Bucket=SOURCE_BUCKET, Key=object['Key'])

How can this be modified to cater the requirement


问:
Firebase Test Lab. GameLoop - marking test completed doesn't work for IOS
Desired behavior
When the finish loop test in the Firebase TestLab matrix should be marked as completed.

Current behavior
The test is not marked as completed. And fails due to timeout.

Example Matrix
matrix-301t6tmiencqn

Platform
IOS 12.0, 12.3. Unity 2019.1.14f1.

I am working on the implementation of the IOS game loop for Unity https://firebase.google.com/docs/test-lab/game-loop. I was able to implement all steps.
But when I am trying to mark the test completed it gets stuck on the "Game Loop Complete" screen and nothing happens.

I am using the method described in docs https://firebase.google.com/docs/test-lab/game-loop#end-early
 - to open the "firebase-game-loop-complete://" URL.

Here is Objective-C snippet of the method I call from my IOS wrapper:

```<code>// Your Game Loop test terminates the current loop and executes the next loop. When there are no more loops to run, the test ends.
-(void) finishLoop
{
    NSLog(@"[NativeIOSTestLab] FinishLoop called");
    UIApplication *app = [UIApplication sharedApplication];
    NSLog(@"[NativeIOSTestLab] Calling openURL method");
    [app openURL:[NSURL URLWithString:@"firebase-game-loop-complete://"] options:@{} completionHandler:^(BOOL success) {}];
}
</code>```

I have also tried to close the app with the exit(0) method, but it still doesn't get marked as completed.This is the result of the finish loop call - it looks like it gets to complete the screen. But the test gets marked as failed after reaching the timeout.

Are there any known solutions, thank you!

答:
Thank you!
The issue actually was that the default timeout wasn't enough to finish the test, even if the video shows that tests have completed, there are expected offset for device pre-setup and post-run.
After increasing the timeout, the test completed successfully.
The question has been answered in the slack community.
Here is the page to get into slack workspace
https://firebase.community/</p>

Body:
Desired behavior
When the finish loop test in the Firebase TestLab matrix should be marked as completed.

Current behavior
The test is not marked as completed. And fails due to timeout.

Example Matrix
matrix-301t6tmiencqn

Platform
IOS 12.0, 12.3. Unity 2019.1.14f1.

I am working on the implementation of the IOS game loop for Unity https://firebase.google.com/docs/test-lab/game-loop. I was able to implement all steps.
But when I am trying to mark the test completed it gets stuck on the "Game Loop Complete" screen and nothing happens.

I am using the method described in docs https://firebase.google.com/docs/test-lab/game-loop#end-early
 - to open the "firebase-game-loop-complete://" URL.

Here is Objective-C snippet of the method I call from my IOS wrapper:

// Your Game Loop test terminates the current loop and executes the next loop. When there are no more loops to run, the test ends.
-(void) finishLoop
{
    NSLog(@"[NativeIOSTestLab] FinishLoop called");
    UIApplication *app = [UIApplication sharedApplication];
    NSLog(@"[NativeIOSTestLab] Calling openURL method");
    [app openURL:[NSURL URLWithString:@"firebase-game-loop-complete://"] options:@{} completionHandler:^(BOOL success) {}];
}

I have also tried to close the app with the exit(0) method, but it still doesn't get marked as completed.This is the result of the finish loop call - it looks like it gets to complete the screen. But the test gets marked as failed after reaching the timeout.

Are there any known solutions, thank you!


问:
Reactjs custom hooks generates jsx and controls events
I'm using React hooks to generate reusable ui and events handling. Is it good to do?</p>

```<code>import React, { useRef, useState } from "react";

const CustomButton = () => {
  const [text, setText] = useState("hello");
  const lower = useRef(false);

  const onClick = () => {
    const newText = lower.current ? text.toUpperCase() : text.toLowerCase();
    lower.current = !lower.current;
    setText(newText);
  };

  const add = () => {
    return <button onClick={onClick}>{text}</button>;
  };

  return { add };
};

export default CustomButton;
</code>```

答:
const { useRef, useState } = React;

const CustomButton = () => {
  const [text, setText] = useState("hello");
  const [isLowercase, setIsLowercase] = useState(false);
  // const lower = useRef(false);

  const onClick = () => {
    // const newText = lower.current ? text.toUpperCase() : text.toLowerCase();
    // lower.current = !lower.current;
    const newText = isLowercase ? text.toUpperCase() : text.toLowerCase();
    setIsLowercase((prev)=>!prev);
    setText(newText);
  };

  const add = () => {
    return <button onClick={onClick}>{text}</button>;
  };
  // return { add }
  return add();
};

const App = () => (<CustomButton />)
ReactDOM.render(<App />, document.getElementById('root'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script>
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root" /></code>```

I don't think you need ref if you want to use it only to change letters.

Body:
I'm using React hooks to generate reusable ui and events handling. Is it good to do?

import React, { useRef, useState } from "react";

const CustomButton = () => {
  const [text, setText] = useState("hello");
  const lower = useRef(false);

  const onClick = () => {
    const newText = lower.current ? text.toUpperCase() : text.toLowerCase();
    lower.current = !lower.current;
    setText(newText);
  };

  const add = () => {
    return <button onClick={onClick}>{text}</button>;
  };

  return { add };
};

export default CustomButton;

Body:
const { useRef, useState } = React;

const CustomButton = () => {
  const [text, setText] = useState("hello");
  const [isLowercase, setIsLowercase] = useState(false);
  // const lower = useRef(false);

  const onClick = () => {
    // const newText = lower.current ? text.toUpperCase() : text.toLowerCase();
    // lower.current = !lower.current;
    const newText = isLowercase ? text.toUpperCase() : text.toLowerCase();
    setIsLowercase((prev)=>!prev);
    setText(newText);
  };

  const add = () => {
    return <button onClick={onClick}>{text}</button>;
  };
  // return { add }
  return add();
};

const App = () => (<CustomButton />)
ReactDOM.render(<App />, document.getElementById('root'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script>
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root" />

I don't think you need ref if you want to use it only to change letters.


问:
Locating a bin in boost histogram
I'm trying out the new boost::histogram library but having trouble with some basic usage.  When adding a new data point to a histogram, I'd like to know the index of the bin it was assigned to.  The method that does the insertion returns void so I'm trying to use STL algorithms to locate the bin but compiler complains.  Here's the code, modified from one of the examples in docs

```<code>#include <iostream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <string>

#include <boost/format.hpp>    // only needed for printing
#include <boost/histogram.hpp> // make_histogram, regular, weight, indexed

namespace bh = boost::histogram;
using namespace std;

int main() {
  vector<double> v = {1.0, 2.0, 3.0, 4.0, 5.0};

  auto h = bh::make_static_histogram(bh::axis::variable<>(v.begin(), v.end()));

  vector<double> data = {-0.5, 1.1, 2.3, 3.7, 3.0, 2.999};
  std::for_each(data.begin(), data.end(), std::ref(h));

  auto it = lower_bound(h.begin(), h.end(), 3.0);
  cout << it.idx(0) << endl;

  return 0;
}
</code>```

The compiler spits out a bunch of errors but I think boils down to the fact that lower_bound can't do the comparison of the objects.  The library docs seem to imply that STL algorithms are supported.
Thanks for your help

答:
You can also directly use the axis to compute a bin. For example (updated for Boost 1.73):

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>

#include <boost/histogram.hpp>

namespace bh = boost::histogram;

int main() {
  std::vector<double> v = {1.0, 2.0, 3.0, 4.0, 5.0};

  auto h = bh::make_histogram(bh::axis::variable<>(v));

  std::vector<double> data = {-0.5, 1.1, 2.3, 3.7, 3.0, 2.999};
  h.fill(data);

  auto bin = h.axis(0).index(3.0);
  std::cout << bin << std::endl;

  return 0;
}
```

Title: Locating a bin in boost histogram

Body:
I'm trying out the new boost::histogram library but having trouble with some basic usage.  When adding a new data point to a histogram, I'd like to know the index of the bin it was assigned to.  The method that does the insertion returns void so I'm trying to use STL algorithms to locate the bin but compiler complains.  Here's the code, modified from one of the examples in docs

#include <iostream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <string>

#include <boost/format.hpp>    // only needed for printing
#include <boost/histogram.hpp> // make_histogram, regular, weight, indexed

namespace bh = boost::histogram;
using namespace std;

int main() {
  vector<double> v = {1.0, 2.0, 3.0, 4.0, 5.0};

  auto h = bh::make_static_histogram(bh::axis::variable<>(v.begin(), v.end()));

  vector<double> data = {-0.5, 1.1, 2.3, 3.7, 3.0, 2.999};
  std::for_each(data.begin(), data.end(), std::ref(h));

  auto it = lower_bound(h.begin(), h.end(), 3.0);
  cout << it.idx(0) << endl;

  return 0;
}

The compiler spits out a bunch of errors but I think boils down to the fact that lower_bound can't do the comparison of the objects.  The library docs seem to imply that STL algorithms are supported.
Thanks for your help


问:
DateTime.Now vs. DateTime.UtcNow
I've been wondering what exactly are the principles of how the two properties work. I know the second one is universal and basically doesn't deal with time zones, but can someone explain in detail how they work and which one should be used in what scenario?</p>

答:
It's really quite simple, so I think it depends what your audience is and where they live.

If you don't use Utc, you must know the timezone of the person you're displaying dates and times to -- otherwise you will tell them something happened at 3 PM in system or server time, when it really happened at 5 PM where they happen to live.

We use DateTime.UtcNow because we have a global web audience, and because I'd prefer not to nag every user to fill out a form indicating what timezone they live in.

We also display relative times (2 hours ago, 1 day ago, etc) until the post ages enough that the time is "the same" no matter where on Earth you live.

OwnerDisplayName: Slavo

Title: DateTime.Now vs. DateTime.UtcNow

LastEditorDisplayName: Jedi Master Spooky

OwnerDisplayName: Jeff Atwood


问:
Converting single column of dictionary like text to multiple columns with key as column name using Pandas
I have the following data to parse,

```<code>                                                                                Data
0    {"key0":"rand_val","key1":"rand_val","key2":"rand_val", ..., "keyn":"rand_val_n"}
1    {"key0":"rand_val","key1":"rand_val","key2":"rand_val", ..., "keyn":"rand_val_n"}
2    {"key0":"rand_val","key1":"rand_val","key2":"rand_val", ..., "keyn":"rand_val_n"}
3    {"key0":"rand_val","key1":"rand_val","key2":"rand_val", ..., "keyn":"rand_val_n"}
4    {"key0":"rand_val","key1":"rand_val","key2":"rand_val", ..., "keyn":"rand_val_n"}
</code>```

Required to be converted to,

```<code>     key0      key1      key2      keyn
0    rand_val  rand_val  rand_val  rand_val
1    rand_val  rand_val  rand_val  rand_val
2    rand_val  rand_val  rand_val  rand_val
3    rand_val  rand_val  rand_val  rand_val
4    rand_val  rand_val  rand_val  rand_val
</code>```

I was able to extract the keys and convert them to column labels the hard way but kind of stuck in getting the final outcome

```<code>attr_data = data.loc[:, ['Data']]
print attr_data.iloc[0]
new_attr1 = pd.DataFrame(attr_data.Data.str.replace('{', ''))
new_attr2 = pd.DataFrame(new_attr1.Data.str.replace('}', ''))
new_attr3 = pd.DataFrame(new_attr2.Data.str.replace('"', ''))
new_attr4 = pd.DataFrame(new_attr3.Data.str.split(','))

print new_attr4.iloc[0]
column_names = []
for label, content in new_attr4.iloc[0].items():
    print label
    for item in content:
        column_names.append(item.split(':')[0])

print column_names
</code>```

答:
Try this:

```<code>df = pd.read_csv('test.csv', sep='|')
dfs = []
for i in range(0, df.shape[0]):
    json_string = df.loc[[i]].iloc[0, 0]
    res = json.loads(json_string)
    d = pd.json_normalize(res)
    dfs.append(d)

df = pd.concat(dfs).reset_index().drop(columns=['index'])
print(df)
</code>```

Output:

```<code>       key0      key1      key2        keyn
0  rand_val  rand_val  rand_val  rand_val_n
1  rand_val  rand_val  rand_val  rand_val_n
2  rand_val  rand_val  rand_val  rand_val_n
3  rand_val  rand_val  rand_val  rand_val_n
4  rand_val  rand_val  rand_val  rand_val_n
</code>```

Body:
I have the following data to parse,

                                                                                Data
0    {"key0":"rand_val","key1":"rand_val","key2":"rand_val", ..., "keyn":"rand_val_n"}
1    {"key0":"rand_val","key1":"rand_val","key2":"rand_val", ..., "keyn":"rand_val_n"}
2    {"key0":"rand_val","key1":"rand_val","key2":"rand_val", ..., "keyn":"rand_val_n"}
3    {"key0":"rand_val","key1":"rand_val","key2":"rand_val", ..., "keyn":"rand_val_n"}
4    {"key0":"rand_val","key1":"rand_val","key2":"rand_val", ..., "keyn":"rand_val_n"}

Required to be converted to,

     key0      key1      key2      keyn
0    rand_val  rand_val  rand_val  rand_val
1    rand_val  rand_val  rand_val  rand_val
2    rand_val  rand_val  rand_val  rand_val
3    rand_val  rand_val  rand_val  rand_val
4    rand_val  rand_val  rand_val  rand_val

I was able to extract the keys and convert them to column labels the hard way but kind of stuck in getting the final outcome

attr_data = data.loc[:, ['Data']]
print attr_data.iloc[0]
new_attr1 = pd.DataFrame(attr_data.Data.str.replace('{', ''))
new_attr2 = pd.DataFrame(new_attr1.Data.str.replace('}', ''))
new_attr3 = pd.DataFrame(new_attr2.Data.str.replace('"', ''))
new_attr4 = pd.DataFrame(new_attr3.Data.str.split(','))

print new_attr4.iloc[0]
column_names = []
for label, content in new_attr4.iloc[0].items():
    print label
    for item in content:
        column_names.append(item.split(':')[0])

print column_names

Body:
Try this:

df = pd.read_csv('test.csv', sep='|')
dfs = []
for i in range(0, df.shape[0]):
    json_string = df.loc[[i]].iloc[0, 0]
    res = json.loads(json_string)
    d = pd.json_normalize(res)
    dfs.append(d)

df = pd.concat(dfs).reset_index().drop(columns=['index'])
print(df)

Output:

       key0      key1      key2        keyn
0  rand_val  rand_val  rand_val  rand_val_n
1  rand_val  rand_val  rand_val  rand_val_n
2  rand_val  rand_val  rand_val  rand_val_n
3  rand_val  rand_val  rand_val  rand_val_n
4  rand_val  rand_val  rand_val  rand_val_n


问:
Working code throwing exception when new lines added. Debugging tips?
I'm working on a proprietary code base, so I have to abstract this.

I'm trying to set the value of DataType_T*** myData in MyApplication. I'm using a shared c++ library (which I denote library A) to set the value. The shared c++ library is just a simple wrapper class around a C API.The C API is included in library A as a shared library (which I denote library B).

So MyApplication calls GetData(myData) in A which calls GetData(myData) in B.

MyApplication has the following code:

```<code>void OnButtonPress(){
    const DataType*** myData;
    GetData(myData);
    DataTypeVal1 val1 = (*myData)[0]->val1; // just grabbing some info.
}
</code>```

GetData(myData): works, and properly sets myData.

Me: types some new code

```<code>void OnButtonPress(){
    const DataType*** myData;
    GetData(myData);
    const void* strData = (*myData)[0]->strData; // just grabbing some info now that we have the pointer.

    //Add lots more new code that does this over and over for each member of myData
    String^ str = gcnew String(static_cast<const char*>(strData));
}
</code>```

GetData(myData): throws a write access violation.

Me: ".   .   .   .   .   .   .what."

Could the exception be getting thrown because of some sort of dll unloading?

Is there a possibility that the linking process changes when I type new code?

I haven't encountered an issue like this before, so I don't really know how to debug this.

Got suggestions?

Thanks.

Solved.
I found my undefined behavior.

答:
I think you want something like this:

```<code>const DataType** myData;
GetData(&myData);
const void* strData = myData[0]->strData;
</code>```

Because in the original code you're just passing a pointer by value; an uninitialized pointer, and then accessing that same uninitialized value.

ed: fixed up the third line

Body:
I'm working on a proprietary code base, so I have to abstract this.

I'm trying to set the value of DataType_T*** myData in MyApplication. I'm using a shared c++ library (which I denote library A) to set the value. The shared c++ library is just a simple wrapper class around a C API.The C API is included in library A as a shared library (which I denote library B).

So MyApplication calls GetData(myData) in A which calls GetData(myData) in B.

MyApplication has the following code:

void OnButtonPress(){
    const DataType*** myData;
    GetData(myData);
    DataTypeVal1 val1 = (*myData)[0]->val1; // just grabbing some info.
}

GetData(myData): works, and properly sets myData.

Me: types some new code

void OnButtonPress(){
    const DataType*** myData;
    GetData(myData);
    const void* strData = (*myData)[0]->strData; // just grabbing some info now that we have the pointer.

    //Add lots more new code that does this over and over for each member of myData
    String^ str = gcnew String(static_cast<const char*>(strData));
}

GetData(myData): throws a write access violation.

Me: ".   .   .   .   .   .   .what."

Could the exception be getting thrown because of some sort of dll unloading?

Is there a possibility that the linking process changes when I type new code?

I haven't encountered an issue like this before, so I don't really know how to debug this.

Got suggestions?

Thanks.

Solved.
I found my undefined behavior.

Body:
I think you want something like this:

const DataType** myData;
GetData(&myData);
const void* strData = myData[0]->strData;

Because in the original code you're just passing a pointer by value; an uninitialized pointer, and then accessing that same uninitialized value.

ed: fixed up the third line


问:
VBA: Content control; filename of a picture
I'm relatively new to VBA & trying to automatize inserting a picture in several Word documents. So in the Word document I made a picture content control. I gave this content control the title "insert_pict". Now in my Macro, how can I add

I have this code so far:

```<code>Sub picturecc()

Dim Word_path As String
Dim Imagelocation As String
Word_path = "template.docm"
Imagelocation = "C:\Users\XXX\Desktop\Picture1.png"
Documents(Word_path).Activate
With ActiveDocument
    .SelectContentControlsByTitle("insert_pict")(1).Range.InlineShape.AddPicture (Imagelocation)
End With

End Sub
</code>```

But I get the error "method or data member not found" in the line .SelectContentControlsByTitle("insert_pict")(1).Range.InlineShape.AddPicture (Imagelocation). What is the right way to add the pricture to the content control? Can anyone help me out to get this work? Very much appreciate it.

答:
Use:</p>

```<code>With ActiveDocument
    .InlineShapes.AddPicture Imagelocation, , , .SelectContentControlsByTitle("insert_pict")(1).Range
End With
</code>```

Body:
I'm relatively new to VBA & trying to automatize inserting a picture in several Word documents. So in the Word document I made a picture content control. I gave this content control the title "insert_pict". Now in my Macro, how can I add

I have this code so far:

Sub picturecc()

Dim Word_path As String
Dim Imagelocation As String
Word_path = "template.docm"
Imagelocation = "C:\Users\XXX\Desktop\Picture1.png"
Documents(Word_path).Activate
With ActiveDocument
    .SelectContentControlsByTitle("insert_pict")(1).Range.InlineShape.AddPicture (Imagelocation)
End With

End Sub

But I get the error "method or data member not found" in the line .SelectContentControlsByTitle("insert_pict")(1).Range.InlineShape.AddPicture (Imagelocation). What is the right way to add the pricture to the content control? Can anyone help me out to get this work? Very much appreciate it.

Body:
Use:

With ActiveDocument
    .InlineShapes.AddPicture Imagelocation, , , .SelectContentControlsByTitle("insert_pict")(1).Range
End With


问:
Xamarin.Forms - getting Control from ImageButtonRenderer
I am trying to create a subclass of ImageButton called TintedImageButton that (surprise) can tint the image.  I am following the basic structure of some TintedImage code I have found.

TintedImageButton has three renderers for iOS, Android and UWP.

The Android version of TintedImageButtonRenderer isn't working because it can't access the "Control" property of its superclass, ImageButtonRenderer. The Control should be the native widget.

I have been unable to locate the class documentation for ImageButtonRenderer but decompiling seems to indicate that the Control property has been made private for Android, but not for iOS.    Does anyone know why this might be?  How can I get the native widget so I can modify it?

答:
The ImageButtonRenderer inherits from AppCompatImageButton, so the class myImageButtonRender itself is a native control which is a subclass of AppCompatImageButton.

```<code>[assembly: ExportRenderer(typeof(TintedImageButton), typeof(myImageButtonRender))]
namespace App261.Droid
{
    class myImageButtonRender : ImageButtonRenderer
    {
        public myImageButtonRender(Context context) : base(context)
        {

        }

        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.ImageButton> e)
        {
            base.OnElementChanged(e);

            this.SetImageResource(Resource.Drawable.sample);

            AppCompatImageButton imagV = this as AppCompatImageButton;

        }
    }
}
</code>```

Body:
The ImageButtonRenderer inherits from AppCompatImageButton, so the class myImageButtonRender itself is a native control which is a subclass of AppCompatImageButton.

[assembly: ExportRenderer(typeof(TintedImageButton), typeof(myImageButtonRender))]
namespace App261.Droid
{
    class myImageButtonRender : ImageButtonRenderer
    {
        public myImageButtonRender(Context context) : base(context)
        {

        }

        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.ImageButton> e)
        {
            base.OnElementChanged(e);

            this.SetImageResource(Resource.Drawable.sample);

            AppCompatImageButton imagV = this as AppCompatImageButton;

        }
    }
}


问:
Python equivalent of the Stata command iebaltab
I need to do a simple balance table between two groups in Python. In Stata, I'd use the command iebaltab, but I couldn't find something similar. Do you know a package that does it?

Thank you in advance!!

答:
This package produces tables of descriptive statistics in Python, which are sometimes referred to as the "Table 1" of a paper.

https://pypi.org/project/tableone/

As a side note, the Stata package table1 has similar functionality to the iebaltab package you referenced.


问:
How to export pandas data to elasticsearch?
It is possible to export a pandas dataframe data to elasticsearch using elasticsearch-py. For example, here is some code:

https://www.analyticsvidhya.com/blog/2017/05/beginners-guide-to-data-exploration-using-elastic-search-and-kibana/

There are a lot of similar methods like to_excel, to_csv, to_sql.

Is there a to_elastic method? If no, where should I request it?

答:
may you can use

pip install es_pandas
pip install progressbar2
```

<p>This package should work on Python3(>=3.4) and ElasticSearch should be version 5.x, 6.x or 7.x.</p>

<pre class="lang-py prettyprint-override"><code>import time
import pandas as pd
from es_pandas import es_pandas

# Information of es cluseter
es_host = 'localhost:9200'
index = 'demo'

# crete es_pandas instance
ep = es_pandas(es_host)

# Example data frame
df = pd.DataFrame({'Alpha': [chr(i) for i in range(97, 128)],
                    'Num': [x for x in range(31)],
                    'Date': pd.date_range(start='2019/01/01', end='2019/01/31')})

# init template if you want
doc_type = 'demo'
ep.init_es_tmpl(df, doc_type)

# Example of write data to es, use the template you create
ep.to_es(df, index, doc_type=doc_type)
# set use_index=True if you want to use DataFrame index as records' _id
ep.to_es(df, index, doc_type=doc_type, use_index=True)
</code>```

here is the document https://pypi.org/project/es-pandas/

if 'es_pandas' cann't solve you problem,you could see other solution : https://towardsdatascience.com/exporting-pandas-data-to-elasticsearch-724aa4dd8f62

Body:
may you can use

pip install es_pandas
pip install progressbar2

This package should work on Python3(>=3.4) and ElasticSearch should be version 5.x, 6.x or 7.x.

import time
import pandas as pd
from es_pandas import es_pandas

# Information of es cluseter
es_host = 'localhost:9200'
index = 'demo'

# crete es_pandas instance
ep = es_pandas(es_host)

# Example data frame
df = pd.DataFrame({'Alpha': [chr(i) for i in range(97, 128)],
                    'Num': [x for x in range(31)],
                    'Date': pd.date_range(start='2019/01/01', end='2019/01/31')})

# init template if you want
doc_type = 'demo'
ep.init_es_tmpl(df, doc_type)

# Example of write data to es, use the template you create
ep.to_es(df, index, doc_type=doc_type)
# set use_index=True if you want to use DataFrame index as records' _id
ep.to_es(df, index, doc_type=doc_type, use_index=True)

here is the document https://pypi.org/project/es-pandas/

if 'es_pandas' cann't solve you problem,you could see other solution : https://towardsdatascience.com/exporting-pandas-data-to-elasticsearch-724aa4dd8f62


问:
plotly dash webpage works on Raspberry Pi BUT can't access it over a LAN
I have started playing with Dash which is EXCELLENT for me as I don't want to be a web coder. the web page is GREAT on host machine  localhost 127.0.0.1:8050

BUT I cannot get at the web page using  192.168.1.216:8050 on the same LAN?

I checked the ports on the raspberry pi and it's listening on 8050
also I am logged in as the same user on both the remote and the hosting machines.

is there something I am missing here?  Here is the print out

```<code>Running on http://192.168.1.202:8050/
Debugger PIN: 086-877-772
 * Serving Flask app "5 26 20  dash datatable drop select csv" (lazy loading)
 * Environment: production
[31m   WARNING: This is a development server. Do not use it in a production deployment.[0m
[2m   Use a production WSGI server instead.[0m
 * Debug mode: on
</code>```

答:
Dash class uses 127.0.0.1 as a default IP address. Did you set the host parameter in the run_server() method?</p>

```<code>if __name__ == '__main__':
    app.run_server(debug=True, host="192.168.1.216", port=8050)
</code>```

Body:
I have started playing with Dash which is EXCELLENT for me as I don't want to be a web coder. the web page is GREAT on host machine  localhost 127.0.0.1:8050

BUT I cannot get at the web page using  192.168.1.216:8050 on the same LAN?

I checked the ports on the raspberry pi and it's listening on 8050
also I am logged in as the same user on both the remote and the hosting machines.

is there something I am missing here?  Here is the print out

Running on http://192.168.1.202:8050/
Debugger PIN: 086-877-772
 * Serving Flask app "5 26 20  dash datatable drop select csv" (lazy loading)
 * Environment: production
[31m   WARNING: This is a development server. Do not use it in a production deployment.[0m
[2m   Use a production WSGI server instead.[0m
 * Debug mode: on

Body:
Dash class uses 127.0.0.1 as a default IP address. Did you set the host parameter in the run_server() method?

if __name__ == '__main__':
    app.run_server(debug=True, host="192.168.1.216", port=8050)


问:
Select between two maps based on values
I have this dataset:

```<code>%{
  "away" => %{
    "id" => "575ec304-wlk3-239n-3032jdns3944",
    "points" => 115
  },
  "home" => %{
    "id" => "583ec7cd-fb46-11e1-82cb-f4ce4684ea4c",
    "points" => 120
  }
}
</code>```

I want to return the map with the most points so that I end up with this.

```<code>%{
  "home" => %{
    "id" => "583ec7cd-fb46-11e1-82cb-f4ce4684ea4c",
    "points" => 120
  }
}
</code>```

I was thinking the enum.find would work for this but I haven't had any luck. Any help would be great.

答:
You want to use Enum.max_by/4 for this because you don't need a specific property of the item you're searching for, but instead you want the item itself with the most points.

```<code>iex> data = %{
  "away" => %{
    "id" => "575ec304-wlk3-239n-3032jdns3944",
    "points" => 115
  },
  "home" => %{
    "id" => "583ec7cd-fb46-11e1-82cb-f4ce4684ea4c",
    "points" => 120
  }
}
iex> Enum.max_by(data, fn {_, value} -> value["points"] end)
{"home", %{"id" => "583ec7cd-fb46-11e1-82cb-f4ce4684ea4c", "points" => 120}}
</code>```

Title: Select between two maps based on values

Body:
I have this dataset:

%{
  "away" => %{
    "id" => "575ec304-wlk3-239n-3032jdns3944",
    "points" => 115
  },
  "home" => %{
    "id" => "583ec7cd-fb46-11e1-82cb-f4ce4684ea4c",
    "points" => 120
  }
}

I want to return the map with the most points so that I end up with this.

%{
  "home" => %{
    "id" => "583ec7cd-fb46-11e1-82cb-f4ce4684ea4c",
    "points" => 120
  }
}

I was thinking the enum.find would work for this but I haven't had any luck. Any help would be great.

Body:
You want to use Enum.max_by/4 for this because you don't need a specific property of the item you're searching for, but instead you want the item itself with the most points.

iex> data = %{
  "away" => %{
    "id" => "575ec304-wlk3-239n-3032jdns3944",
    "points" => 115
  },
  "home" => %{
    "id" => "583ec7cd-fb46-11e1-82cb-f4ce4684ea4c",
    "points" => 120
  }
}
iex> Enum.max_by(data, fn {_, value} -> value["points"] end)
{"home", %{"id" => "583ec7cd-fb46-11e1-82cb-f4ce4684ea4c", "points" => 120}}


问:
jQuery Cycle Effect on Tabs
Hi I have a built this Jquery code.

I want the buttons to auto cycle insted of hovering can anyone help please?

Jquery code is as follows:

```<code>$(function() {
  var $items = $('#vtab>ul>li');
  $items.click(function() {
    $items.removeClass('selected');
    $(this).addClass('selected');
    var index = $items.index($(this));
    $('#vtab>div').hide().eq(index).show();
  }).eq(1).mouseover();
});
</code>```

The Html is as follows:

```<code><div id="vtab">
  <ul>
    <li class="home selected"></li>
    <li class="login"></li>
    <li class="support"></li>
  </ul>
  <div>
    <h4>Home Insurance</h4>
  </div>
  <div>
    <h4>Secure Login</h4>
    <form id="loginForm" action="">
      <fieldset>
        <legend>You need to sign in with your Email & Password to continue.</legend>
        <div>
          <label for="email">Email:</label>
          <input type="text" name="email" id="email" />
        </div>
        <div>
          <label for="password">Password:</label>
          <input type="password" name="password" id="password" />
        </div>
        <div>
          <input id="login" type="submit" value="Fake Login" />
        </div>
      </fieldset>
    </form>
  </div>
  <div>
    <h4>Online Support</h4>
    Maecenas in varius nulla....
  </div>
</div>
</code>```

I want the buttons to cycle through rather than just when you hover

答:
can't see your page.  Can you re-post the url?

I have built one here.  Take a look and see is that what you want:
http://www.castlerockinvestments.ca/dev/index_banner.jsp

If that's what you want, you might need to change the source code yourself because I ch.  The writer of JQuery cycle got sample code for a lot of option there.  I assume you see them all already :  http://jquery.malsup.com/cycle/pager-over.html

Title: jQuery Cycle Effect on Tabs

Body:
Hi I have a built this Jquery code.

I want the buttons to auto cycle insted of hovering can anyone help please?

Jquery code is as follows:

$(function() {
  var $items = $('#vtab>ul>li');
  $items.click(function() {
    $items.removeClass('selected');
    $(this).addClass('selected');
    var index = $items.index($(this));
    $('#vtab>div').hide().eq(index).show();
  }).eq(1).mouseover();
});

The Html is as follows:

Home Insurance

Secure Login

    <form id="loginForm" action="">
      <fieldset>
        <legend>You need to sign in with your Email & Password to continue.</legend>

          Email:
          <input type="text" name="email" id="email" />

          Password:
          <input type="password" name="password" id="password" />

          <input id="login" type="submit" value="Fake Login" />

      </fieldset>
    </form>

Online Support

    Maecenas in varius nulla....

I want the buttons to cycle through rather than just when you hover


问:
Remove any duplicates in a list of lists when order doesn't matter (eg. [1,2,3] and [1,3,2] are duplicate sets)?
I've been deleting all occurrences unintentionally. I would like to keep at least one set of occurrences.

For example, I have [[1,2,3],[1,3,2],[4,5,6],[5,6,4]] and the desired output would be akin to [[1,2,3],[4,5,6]].

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

remove_sets = []
for a in range(0, len(c)):
    for b in permutations(c[a], 3):
        # my idea is that if list(b) != c[a]
        # it should not delete all occurences.
        if list(b) != c[a]:
            if list(b) in c:
                remove_sets.append(list(b))

# delete those occurences.
for cc in range(0, len(remove_sets)):
    if remove_sets[cc] in c:
        del c[c.index(remove_sets[cc])]
</code>```

Unintended Result/Output

```<code>[[1,2,3]]
</code>```

My desired output would be

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

Question

Is there a function for removing these duplicate sets where order is switched around?

答:
groupby works if your duplicate sublists are already adjacent and you need to squeeze them into single units:

```<code>>>> from itertools import groupby
>>> [next(v) for _, v in groupby(c, sorted)]
[[1, 2, 3], [4, 5, 6]]
</code>```

Caling sorted ignores order when grouping, so we can skim the first item from each group to obtain your result.

Otherwise, for the general case, using a dictionary comprehension like

```<code>>>> list({tuple(sorted(x)): x for x in c}.values())
[(1, 2, 3), (4, 6, 5)]
</code>```

works but it only selects the last-seen item in c. If you reverse-iterate c, you'll get the first-seen:

```<code>>>> list({tuple(sorted(x)): x for x in c[::-1]}.values())[::-1]
[(1, 2, 3), (4, 5, 6)]
</code>```

Be aware that sorted is O(n(log(n))), resulting in an overall complexity of

```<code>longest_len = max(map(len, c))
O(n * longest_len * log(longest_len))
</code>```

If you need to scale to large inner lists, consider collections.Counter instead of sorted.

Body:
I've been deleting all occurrences unintentionally. I would like to keep at least one set of occurrences.

For example, I have [[1,2,3],[1,3,2],[4,5,6],[5,6,4]] and the desired output would be akin to [[1,2,3],[4,5,6]].

s = 1,2,3,4,5,6
c = [[1,2,3],[4,5,6],[4,6,5]]

remove_sets = []
for a in range(0, len(c)):
    for b in permutations(c[a], 3):
        # my idea is that if list(b) != c[a]
        # it should not delete all occurences.
        if list(b) != c[a]:
            if list(b) in c:
                remove_sets.append(list(b))

# delete those occurences.
for cc in range(0, len(remove_sets)):
    if remove_sets[cc] in c:
        del c[c.index(remove_sets[cc])]

Unintended Result/Output

[[1,2,3]]

My desired output would be

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

Question

Is there a function for removing these duplicate sets where order is switched around?

Body:
groupby works if your duplicate sublists are already adjacent and you need to squeeze them into single units:

>>> from itertools import groupby
>>> [next(v) for _, v in groupby(c, sorted)]
[[1, 2, 3], [4, 5, 6]]

Caling sorted ignores order when grouping, so we can skim the first item from each group to obtain your result.

Otherwise, for the general case, using a dictionary comprehension like

>>> list({tuple(sorted(x)): x for x in c}.values())
[(1, 2, 3), (4, 6, 5)]

works but it only selects the last-seen item in c. If you reverse-iterate c, you'll get the first-seen:

>>> list({tuple(sorted(x)): x for x in c[::-1]}.values())[::-1]
[(1, 2, 3), (4, 5, 6)]

Be aware that sorted is O(n(log(n))), resulting in an overall complexity of

longest_len = max(map(len, c))
O(n * longest_len * log(longest_len))

If you need to scale to large inner lists, consider collections.Counter instead of sorted.


问:
How do I conditionally render from three different options in React Native?
I want to conditionally render in React Native, but there are three different options: loading screen, the user has no messages, or display all the users messages. I have a variable called conversations which is fetched from my database, but before the fetch completes it is null, so I want to display a loading indicator. After the fetch is complete, I want to display a message if the user has no current chats, or display a table containing all the users chats if the user does have existing chats. My thought was something like this:

return (
  <View>
    {conversations ? conversations.length === 0 ? (
      <Text>You have no messages.</Text>
    ) : (
      <ConversationTable conversations={conversations} />
    ) : (
      <ActivityIndicator />
    )}
  </View>
)
```

Is there a better way to do this?

答:
You can go like this</p>

```<code>{conversations ? (
            {conversations.length===0? (
                <Text>You have no messages.</Text>
            ):(
                <ConversationTable conversations={conversations} />
            )}
        ) :(
            <ActivityIndicator />
        )}
</code>```

Body:
I want to conditionally render in React Native, but there are three different options: loading screen, the user has no messages, or display all the users messages. I have a variable called conversations which is fetched from my database, but before the fetch completes it is null, so I want to display a loading indicator. After the fetch is complete, I want to display a message if the user has no current chats, or display a table containing all the users chats if the user does have existing chats. My thought was something like this:

return (
  <View>
    {conversations ? conversations.length === 0 ? (
      <Text>You have no messages.</Text>
    ) : (
      <ConversationTable conversations={conversations} />
    ) : (
      <ActivityIndicator />
    )}
  </View>
)

Is there a better way to do this?

Body:
You can go like this

{conversations ? (
            {conversations.length===0? (
                <Text>You have no messages.</Text>
            ):(
                <ConversationTable conversations={conversations} />
            )}
        ) :(
            <ActivityIndicator />
        )}


问:
Why doesn't timer treat global variable correctly?
This continuously sends t:

myVar := true

SetTimer, myLoop, 0

myLoop(){
    if (true) {
      Send, {t down}
    }
}

#Persistent
```

<p>But this does nothing:</p>

<pre class="lang-js prettyprint-override"><code>myVar := true

SetTimer, myLoop, 0

myLoop(){
    if (myVar) {
      Send, {t down}
    }
}

#Persistent
</code>```

Why?  myVar and true both evaluate to true so I don't understand why it's different.

答:
myVar := true should be:

global myVar := true
```

Because a global must explicitly be declared as such.

Body:
This continuously sends t:

myVar := true

SetTimer, myLoop, 0

myLoop(){
    if (true) {
      Send, {t down}
    }
}

#Persistent

But this does nothing:

myVar := true

SetTimer, myLoop, 0

myLoop(){
    if (myVar) {
      Send, {t down}
    }
}

#Persistent

Why?  myVar and true both evaluate to true so I don't understand why it's different.

Body:
myVar := true should be:

global myVar := true

Because a global must explicitly be declared as such.