问:
React App: Why I get an error when I try to run npm start script?
I installed all required packages and trying to run npm start script which gives me the error below:

```<code>TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received undefined
    at validateString (internal/validators.js:118:11)
    at Object.join (path.js:375:7)
    at noopServiceWorkerMiddleware (C:\Alex\Practise\React website\front-end\node_modules\react-dev-utils\noopServiceWorkerMiddleware.js:14:26)
    at Layer.handle [as handle_request] (C:\Alex\Practise\React website\front-end\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (C:\Alex\Practise\React website\front-end\node_modules\express\lib\router\index.js:317:13)
    at C:\Alex\Practise\React website\front-end\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (C:\Alex\Practise\React website\front-end\node_modules\express\lib\router\index.js:335:12)
    at next (C:\Alex\Practise\React website\front-end\node_modules\express\lib\router\index.js:275:10)
    at launchEditorMiddleware (C:\Alex\Practise\React website\front-end\node_modules\react-dev-utils\errorOverlayMiddleware.js:20:7)
    at Layer.handle [as handle_request] (C:\Alex\Practise\React website\front-end\node_modules\express\lib\router\layer.js:95:5)

</code>```

Here's copy of my package.json:

```<code>{
  "name": "front-end",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.3.2",
    "@testing-library/user-event": "^7.1.2",
    "node-sass": "^4.13.1",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-scripts": "3.3.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

</code>```

I tried to delete and reinstall the whole project, reinstall node and packages with no luck.
Any help is very appreciated!

答:
Upgrade your react-scripts to 3.4.0. I've just installed modules provided from your package.json and upgraded react-scripts to the newest version and everything works fine.

More details on github issue.

Body:
I installed all required packages and trying to run npm start script which gives me the error below:

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received undefined
    at validateString (internal/validators.js:118:11)
    at Object.join (path.js:375:7)
    at noopServiceWorkerMiddleware (C:\Alex\Practise\React website\front-end\node_modules\react-dev-utils\noopServiceWorkerMiddleware.js:14:26)
    at Layer.handle [as handle_request] (C:\Alex\Practise\React website\front-end\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (C:\Alex\Practise\React website\front-end\node_modules\express\lib\router\index.js:317:13)
    at C:\Alex\Practise\React website\front-end\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (C:\Alex\Practise\React website\front-end\node_modules\express\lib\router\index.js:335:12)
    at next (C:\Alex\Practise\React website\front-end\node_modules\express\lib\router\index.js:275:10)
    at launchEditorMiddleware (C:\Alex\Practise\React website\front-end\node_modules\react-dev-utils\errorOverlayMiddleware.js:20:7)
    at Layer.handle [as handle_request] (C:\Alex\Practise\React website\front-end\node_modules\express\lib\router\layer.js:95:5)

Here's copy of my package.json:

{
  "name": "front-end",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.3.2",
    "@testing-library/user-event": "^7.1.2",
    "node-sass": "^4.13.1",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-scripts": "3.3.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

I tried to delete and reinstall the whole project, reinstall node and packages with no luck.
Any help is very appreciated!


来源: stackexchange

问:
How to return an array of char pointers? What is wrong in my code?
I have seen similar posts related to my question but I could not find any answer to understand the bug in this code.

So, I have a function whose return type can't be changed (for case 1). For case 2, I would like to know how to return char *a[];

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char **myfunc(int n) {
    char **a = malloc(n * sizeof(char *));
    int i, j = 1;
    for (i = 0; i < n; i++)
        a[i] = malloc(9 * sizeof(char));
    for (i = 0; i < n; i++) {
        snprintf(a[i], 5, "%d", i);
        return a;
    }

int main() {
    int num = 10, i;
    char **ar = myfunc(num);
    for (i = 0; i < num; i++)
        printf("%s\n", ar[i]);

    return 0;
}
</code>```

1) In the myfunc(), how should I return a correctly? My compiler is throwing me a warning that return from incompatible pointer type.

2) In case, if I change my above myfunc() as follows, how should I return the modified buffer?

```<code>char ???myfunc(int n) {
    char *a[n];
    for (i = 0; i < n; i++)
        a[i] = malloc(10 * sizeof(char));

   return ?
}
</code>```

3) In both cases, how should I handle the return inside the main() function?

Case 2:

```<code>char *myfunc(int n) {
    static char *a[n];
    int i;

    for (i = 0; i < n; i++)
        a[i] = malloc(9 * sizeof(char));

    for (i = 0; i < n; i++)
        snprintf(a[i], 5, "%d", i);

    return a;
}

int main() {
    int num = 10, i;
    char *ar = myfunc(num);
    for (i = 0; i < num; i++)
        printf("%s\n", ar[i]);

    return 0;
}
</code>```

答:
Your code was mis-indented, which makes it hard to read and hides silly mistakes such as the extra brace after the second for.

Once corrected for this mistake, the code compiles and runs fine:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char **myfunc(int n) {
    char **a = malloc(n * sizeof(char *));
    int i;
    for (i = 0; i < n; i++)
        a[i] = malloc(9 * sizeof(char));
    for (i = 0; i < n; i++)
        snprintf(a[i], 9, "%d", i);
    return a;
}

int main() {
    int num = 10, i;
    char **ar = myfunc(num);
    for (i = 0; i < num; i++)
        printf("%s\n", ar[i]);

    return 0;
}
```

If you change myfunc() to define a as char *a[n];, you have a major problem when returning a from myfunc() as the array is defined only inside the scope of myfunc(). Returning its address, which is simply return a; will cause undefined behavior in main() because the space it points to might have been reused for other stuff, such as printf() local variables.

The third option where you define a as static char *a[n]; does not compile because the size of static objects must be known at compile time. Using local static objects is not advisable as it makes the program harder to understand and non-reentrant, with hidden internal state, etc. One such function is strtok() from <string.h>.

ContentLicense: CC BY-SA 4.0

Body:
I have seen similar posts related to my question but I could not find any answer to understand the bug in this code.

So, I have a function whose return type can't be changed (for case 1). For case 2, I would like to know how to return char *a[];

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char **myfunc(int n) {
    char **a = malloc(n * sizeof(char *));
    int i, j = 1;
    for (i = 0; i < n; i++)
        a[i] = malloc(9 * sizeof(char));
    for (i = 0; i < n; i++) {
        snprintf(a[i], 5, "%d", i);
        return a;
    }

int main() {
    int num = 10, i;
    char **ar = myfunc(num);
    for (i = 0; i < num; i++)
        printf("%s\n", ar[i]);

    return 0;
}

1) In the myfunc(), how should I return a correctly? My compiler is throwing me a warning that return from incompatible pointer type.

2) In case, if I change my above myfunc() as follows, how should I return the modified buffer?

char ???myfunc(int n) {
    char *a[n];
    for (i = 0; i < n; i++)
        a[i] = malloc(10 * sizeof(char));

   return ?
}

3) In both cases, how should I handle the return inside the main() function?

Case 2:

char *myfunc(int n) {
    static char *a[n];
    int i;

    for (i = 0; i < n; i++)
        a[i] = malloc(9 * sizeof(char));

    for (i = 0; i < n; i++)
        snprintf(a[i], 5, "%d", i);

    return a;
}

int main() {
    int num = 10, i;
    char *ar = myfunc(num);
    for (i = 0; i < num; i++)
        printf("%s\n", ar[i]);

    return 0;
}

Body:
Your code was mis-indented, which makes it hard to read and hides silly mistakes such as the extra brace after the second for.

Once corrected for this mistake, the code compiles and runs fine:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char **myfunc(int n) {
    char **a = malloc(n * sizeof(char *));
    int i;
    for (i = 0; i < n; i++)
        a[i] = malloc(9 * sizeof(char));
    for (i = 0; i < n; i++)
        snprintf(a[i], 9, "%d", i);
    return a;
}

int main() {
    int num = 10, i;
    char **ar = myfunc(num);
    for (i = 0; i < num; i++)
        printf("%s\n", ar[i]);

    return 0;
}

If you change myfunc() to define a as char *a[n];, you have a major problem when returning a from myfunc() as the array is defined only inside the scope of myfunc(). Returning its address, which is simply return a; will cause undefined behavior in main() because the space it points to might have been reused for other stuff, such as printf() local variables.

The third option where you define a as static char *a[n]; does not compile because the size of static objects must be known at compile time. Using local static objects is not advisable as it makes the program harder to understand and non-reentrant, with hidden internal state, etc. One such function is strtok() from <string.h>.


问:
If I create a project to react native how to make it support on several Android platforms for example (Android 6 and later)
I'm new in the world of APP(mobile applications). I want to create a APP using react native. But it is necessary that it works out in several versions of android (6 onwards).

Now I am working on no expo way and on windows 10 too. So,  I installed react native that now it works with android 9 (PIE) API LVL 28 AVD. If I finish my project with this API, would the apk work on different old versions of Android? or only in phones which have API 9. Give me advices pleases.

if i development my project with react native 0.61.5 version (the last i think 18/02/2020), would i run old APIs of android (6 onwards i want)?. Or, do i need to put my react native version on an old version to development an APP on android 6 to run on several versions?. Or the only thing that i need to do is write a sentence in my code that cover some plataforms.

PD: I'm new in this web page too.

答: If I understand your question @abdiaslabrador, you want your app to be available to users still on android version 5.1 to 8.1 and to do that you have to select an Android API level lower than level 29 which targets only android phones running Android10. For your case, that'd be android API level 22 which enables you target android version 5.1 (lollipop) and above. Check out the official android build numbers page for more clarification </p>


问:
Re-grouping data based on report run time
I have a folder which serves as a container for a standardized report from a system. This report is run on a daily basis. However, the report may require re-run for a certain date or range of dates depending on user preferences and asks. Thus file content may change significantly.

I would like to create a script that would group the unique dates together in one dataframe based on the latest run time, and another dataframe for the dates that are being revised.

Here is a simplified version of the table:

```<code>structure(list(Source = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L,
2L, 3L, 3L, 3L, 3L), Date = structure(c(1L, 1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L), .Label = c("11-Feb-20", "12-Feb-20"
), class = "factor"), FarmType = structure(c(3L, 4L, 5L, 1L,
2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L), .Label = c("AJSKJA",
"ASKJKA", "GHDGH", "KLKIUK", "KLSAKJ"), class = "factor"), FarmName = structure(c(1L,
2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L), .Label = c("",
"JJHGH", "JKJKK", "JUISO", "SDLLS"), class = "factor"), Perform = c(13.04144378,
1.230474165, 1.230474165, 13.9407486, 13.9407486, 13.04144378,
1.230474165, 1.230474165, 13.9407486, 13.9407486, 13.04144378,
15.26566, 1.230474165, 13.9407486), RunDate = structure(c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L), .Label = c("02/14/2020",
"02/15/2020"), class = "factor")), class = "data.frame", row.names = c(NA,
-14L))
</code>```

Please note that the number of columns does not change, however, after each re-run the number of rows may increase/decrease.

The idea is -- the first group of data that is based on the most recent run would represent the up-to-date information (corrections, revisions, etc.), while the second group essentially looks at what is being revised and how the numbers and data are changing.

Expected output for the first group:

```<code>structure(list(Source = c(3L, 3L, 3L, 3L, 2L, 2L, 2L, 2L, 2L),
    Date = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L), .Label = c("11-Feb-20",
    "12-Feb-20"), class = "factor"), FarmType = structure(c(3L,
    4L, 5L, 1L, 3L, 4L, 5L, 1L, 2L), .Label = c("AJSKJA", "ASKJKA",
    "GHDGH", "KLKIUK", "KLSAKJ"), class = "factor"), FarmName = structure(c(1L,
    2L, 3L, 4L, 1L, 2L, 3L, 4L, 5L), .Label = c("", "JJHGH",
    "JKJKK", "JUISO", "SDLLS"), class = "factor"), Perform = c(13.04144378,
    15.26566, 1.230474165, 13.9407486, 13.04144378, 1.230474165,
    1.230474165, 13.9407486, 13.9407486), RunDate = structure(c(2L,
    2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L), .Label = c("02/14/2020",
    "02/15/2020"), class = "factor")), class = "data.frame", row.names = c(NA,
-9L))
</code>```

Expected output for the second group:

```<code>structure(list(Source = c(1L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 3L),
    Date = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "11-Feb-20", class = "factor"),
    FarmType = structure(c(3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L
    ), .Label = c("AJSKJA", "ASKJKA", "GHDGH", "KLKIUK", "KLSAKJ"
    ), class = "factor"), FarmName = structure(c(1L, 2L, 3L,
    4L, 5L, 1L, 2L, 3L, 4L), .Label = c("", "JJHGH", "JKJKK",
    "JUISO", "SDLLS"), class = "factor"), Perform = c(13.04144378,
    1.230474165, 1.230474165, 13.9407486, 13.9407486, 13.04144378,
    15.26566, 1.230474165, 13.9407486), RunDate = structure(c(1L,
    1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L), .Label = c("02/14/2020",
    "02/15/2020"), class = "factor")), class = "data.frame", row.names = c(NA,
-9L))
</code>```

Thank you for your time. Please let me know if you have questions.

答:
We could group by 'Date' and filter those groups where the 'RunDate' is the latest after converting to Date class

```<code>library(lubridate)
library(dplyr)
new1 <- df1 %>%
            group_by(Date) %>%
            filter(mdy(RunDate) == max(mdy(RunDate)))
</code>```

and for the second set, we can check if the number of distinct elements of 'RunDate' is more than 1

```<code>new2 <- df1 %>%
            group_by(Date) %>%
            filter(n_distinct(RunDate) > 1)
</code>```

Body:
I have a folder which serves as a container for a standardized report from a system. This report is run on a daily basis. However, the report may require re-run for a certain date or range of dates depending on user preferences and asks. Thus file content may change significantly.

I would like to create a script that would group the unique dates together in one dataframe based on the latest run time, and another dataframe for the dates that are being revised.

Here is a simplified version of the table:

structure(list(Source = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L,
2L, 3L, 3L, 3L, 3L), Date = structure(c(1L, 1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L), .Label = c("11-Feb-20", "12-Feb-20"
), class = "factor"), FarmType = structure(c(3L, 4L, 5L, 1L,
2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L), .Label = c("AJSKJA",
"ASKJKA", "GHDGH", "KLKIUK", "KLSAKJ"), class = "factor"), FarmName = structure(c(1L,
2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L), .Label = c("",
"JJHGH", "JKJKK", "JUISO", "SDLLS"), class = "factor"), Perform = c(13.04144378,
1.230474165, 1.230474165, 13.9407486, 13.9407486, 13.04144378,
1.230474165, 1.230474165, 13.9407486, 13.9407486, 13.04144378,
15.26566, 1.230474165, 13.9407486), RunDate = structure(c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L), .Label = c("02/14/2020",
"02/15/2020"), class = "factor")), class = "data.frame", row.names = c(NA,
-14L))

Please note that the number of columns does not change, however, after each re-run the number of rows may increase/decrease.

The idea is -- the first group of data that is based on the most recent run would represent the up-to-date information (corrections, revisions, etc.), while the second group essentially looks at what is being revised and how the numbers and data are changing.

Expected output for the first group:

structure(list(Source = c(3L, 3L, 3L, 3L, 2L, 2L, 2L, 2L, 2L),
    Date = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L), .Label = c("11-Feb-20",
    "12-Feb-20"), class = "factor"), FarmType = structure(c(3L,
    4L, 5L, 1L, 3L, 4L, 5L, 1L, 2L), .Label = c("AJSKJA", "ASKJKA",
    "GHDGH", "KLKIUK", "KLSAKJ"), class = "factor"), FarmName = structure(c(1L,
    2L, 3L, 4L, 1L, 2L, 3L, 4L, 5L), .Label = c("", "JJHGH",
    "JKJKK", "JUISO", "SDLLS"), class = "factor"), Perform = c(13.04144378,
    15.26566, 1.230474165, 13.9407486, 13.04144378, 1.230474165,
    1.230474165, 13.9407486, 13.9407486), RunDate = structure(c(2L,
    2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L), .Label = c("02/14/2020",
    "02/15/2020"), class = "factor")), class = "data.frame", row.names = c(NA,
-9L))

Expected output for the second group:

structure(list(Source = c(1L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 3L),
    Date = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "11-Feb-20", class = "factor"),
    FarmType = structure(c(3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L
    ), .Label = c("AJSKJA", "ASKJKA", "GHDGH", "KLKIUK", "KLSAKJ"
    ), class = "factor"), FarmName = structure(c(1L, 2L, 3L,
    4L, 5L, 1L, 2L, 3L, 4L), .Label = c("", "JJHGH", "JKJKK",
    "JUISO", "SDLLS"), class = "factor"), Perform = c(13.04144378,
    1.230474165, 1.230474165, 13.9407486, 13.9407486, 13.04144378,
    15.26566, 1.230474165, 13.9407486), RunDate = structure(c(1L,
    1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L), .Label = c("02/14/2020",
    "02/15/2020"), class = "factor")), class = "data.frame", row.names = c(NA,
-9L))

Thank you for your time. Please let me know if you have questions.

Body:
We could group by 'Date' and filter those groups where the 'RunDate' is the latest after converting to Date class

library(lubridate)
library(dplyr)
new1 <- df1 %>%
            group_by(Date) %>%
            filter(mdy(RunDate) == max(mdy(RunDate)))

and for the second set, we can check if the number of distinct elements of 'RunDate' is more than 1

new2 <- df1 %>%
            group_by(Date) %>%
            filter(n_distinct(RunDate) > 1)


问:
Problem with nodejs static route and files
In my project I have a report hat is reachable with index.html
But this is private and I want to protect / limit access  with my node app. for this I use

app.use('/allure', express.static(path.join(__alluredir , 'allure-report/')));

Then I use for bugging purpose

```<code>app.all('/allure/*', function(req, res, next) {

console.log("catched allure query");
next(); // allow the next route to run

});
</code>```

But the index.html is still reachable with localhost:8080/allure/index.hmtl and also just with localhost:8080/allure/ without an console output. This confuse a lot. Anybody has an idea how to hinder access the index.html without logged in? (Is use passport)

my whole app.js file is:

```<code>const express = require('express');
const app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
const expressLayouts = require('express-ejs-layouts');
const mongoose = require('mongoose');
const passport = require('passport');
const flash = require('connect-flash');
const session = require('express-session');
var bodyParser = require('body-parser');
const fs = require('fs');
const path = require('path');
var favicon = require('serve-favicon')
const { allureGenerator } = require('./ops/copyalluredata');

app.set('socketio', io);
//app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json({ type: 'application/json' }));
app.use(bodyParser.urlencoded({
    parameterLimit: 100000,
    limit: '50mb',
    extended: true
}));

var appDir = path.dirname(require.main.filename);
global.__basedir = appDir;
global.__alluredir = process.env.REPORT_DIR_ENV;

fs.readFile(path.join(appDir, '/config.xml'), (err, data) => {
    if (err) throw err;
    myConfigData = JSON.parse(data);

    process.env.BROWSERSTACK_USERNAME = myConfigData.browserstackid;
    process.env.BROWSERSTACK_ACCESS_KEY = myConfigData.browserstackkey;
    process.env.BROWSERSTACK_DISPLAY_RESOLUTION="1600x1200";

    console.log('config gelesen');

});

//Diese Funktion schreibt die benötigten Dateien in den allure Modul Ordner damit das Logo verwendet wird.
allureGenerator();

// Passport Config
require(path.join(appDir, '/config/passport'))(passport);
// DB Config
var db = '';
if (process.env.NODE_ENV == 'home') {
    db = require(path.join(appDir, '/config/keys')).mongoURI;
    console.log('keys');
}else{
    db = require(path.join(appDir, '/config/keys_local')).mongoURI;
    console.log('keys_local');
}

// Connect to MongoDB
mongoose
    .connect(
        db,
        { useNewUrlParser: true }
    )
    .then(() => console.log('MongoDB Connected'))
    .catch(err => console.log(err));

app.use('/allure', express.static(path.join(__alluredir , 'allure-report/')));
app.use(express.static(appDir));

// EJS
app.use(expressLayouts);
app.set('view engine', 'ejs');
app.set('views', path.join(appDir, '/views'));

app.use(
    session({
        secret: 'secret',
        resave: true,
        saveUninitialized: true
    })
);

app.use(favicon(path.join(__dirname, 'css', 'fvicon.ico')))

app.use(passport.initialize());
app.use(passport.session());

// Connect flash
app.use(flash());

// Global variables
app.use(function(req, res, next) {
    res.locals.success_msg = req.flash('success_msg');
    res.locals.error_msg = req.flash('error_msg');
    res.locals.error = req.flash('error');
    next();
});

// Routes
app.use('/', require('./routes/index.js'));
app.use('/users', require('./routes/users.js'));
app.use('/cases', require('./routes/cases.js'));
app.use('/tcafe', require('./routes/tcafe.js'));
app.use('/imgtest', require('./routes/imgtest.js'));
app.use('/rapitest', require('./routes/restapitest.js'));

io.on('connection', function(socket){
    console.log('a user connected');
});

app.all('/allure/*', function(req, res, next) {

console.log("catched allure query");
next(); // allow the next route to run

});

app.use((req, res, next) => {
    next({
        status: 404,
        message: 'Not Found',
    });
});

app.use((err, req, res, next) => {
    if (err.status === 404) {
        return res.status(400).render('404',{ layout: 'system.ejs' });
    }

    if (err.status === 500) {
        return res.status(500).render('500');
    }

    next();
});

const PORT = process.env.PORT || 8080;

http.listen(PORT, console.log(`Server started on port ${PORT}`));

</code>```

答:
You can use something like this Or just use somemiddleware-

```<code>app.use('/allure', function(req,res,next){
   if(<authenticate check>){ // some kind of authenticate check
     return express.static(path.join(__dirname, 'allure'));
   } else {
      <Any error you want to show>
   }
});
</code>```

OR

```<code>app.use('/allure',<Auth Middlewarae> , express.static(path.join(__dirname, 'allure')));
</code>```

Body:
In my project I have a report hat is reachable with index.html
But this is private and I want to protect / limit access  with my node app. for this I use

app.use('/allure', express.static(path.join(__alluredir , 'allure-report/')));

Then I use for bugging purpose

app.all('/allure/*', function(req, res, next) {

console.log("catched allure query");
next(); // allow the next route to run

});

But the index.html is still reachable with localhost:8080/allure/index.hmtl and also just with localhost:8080/allure/ without an console output. This confuse a lot. Anybody has an idea how to hinder access the index.html without logged in? (Is use passport)

my whole app.js file is:

const express = require('express');
const app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
const expressLayouts = require('express-ejs-layouts');
const mongoose = require('mongoose');
const passport = require('passport');
const flash = require('connect-flash');
const session = require('express-session');
var bodyParser = require('body-parser');
const fs = require('fs');
const path = require('path');
var favicon = require('serve-favicon')
const { allureGenerator } = require('./ops/copyalluredata');

app.set('socketio', io);
//app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json({ type: 'application/json' }));
app.use(bodyParser.urlencoded({
    parameterLimit: 100000,
    limit: '50mb',
    extended: true
}));

var appDir = path.dirname(require.main.filename);
global.__basedir = appDir;
global.__alluredir = process.env.REPORT_DIR_ENV;

fs.readFile(path.join(appDir, '/config.xml'), (err, data) => {
    if (err) throw err;
    myConfigData = JSON.parse(data);

    process.env.BROWSERSTACK_USERNAME = myConfigData.browserstackid;
    process.env.BROWSERSTACK_ACCESS_KEY = myConfigData.browserstackkey;
    process.env.BROWSERSTACK_DISPLAY_RESOLUTION="1600x1200";

    console.log('config gelesen');

});

//Diese Funktion schreibt die benötigten Dateien in den allure Modul Ordner damit das Logo verwendet wird.
allureGenerator();

// Passport Config
require(path.join(appDir, '/config/passport'))(passport);
// DB Config
var db = '';
if (process.env.NODE_ENV == 'home') {
    db = require(path.join(appDir, '/config/keys')).mongoURI;
    console.log('keys');
}else{
    db = require(path.join(appDir, '/config/keys_local')).mongoURI;
    console.log('keys_local');
}

// Connect to MongoDB
mongoose
    .connect(
        db,
        { useNewUrlParser: true }
    )
    .then(() => console.log('MongoDB Connected'))
    .catch(err => console.log(err));

app.use('/allure', express.static(path.join(__alluredir , 'allure-report/')));
app.use(express.static(appDir));

// EJS
app.use(expressLayouts);
app.set('view engine', 'ejs');
app.set('views', path.join(appDir, '/views'));

app.use(
    session({
        secret: 'secret',
        resave: true,
        saveUninitialized: true
    })
);

app.use(favicon(path.join(__dirname, 'css', 'fvicon.ico')))

app.use(passport.initialize());
app.use(passport.session());

// Connect flash
app.use(flash());

// Global variables
app.use(function(req, res, next) {
    res.locals.success_msg = req.flash('success_msg');
    res.locals.error_msg = req.flash('error_msg');
    res.locals.error = req.flash('error');
    next();
});

// Routes
app.use('/', require('./routes/index.js'));
app.use('/users', require('./routes/users.js'));
app.use('/cases', require('./routes/cases.js'));
app.use('/tcafe', require('./routes/tcafe.js'));
app.use('/imgtest', require('./routes/imgtest.js'));
app.use('/rapitest', require('./routes/restapitest.js'));

io.on('connection', function(socket){
    console.log('a user connected');
});

app.all('/allure/*', function(req, res, next) {

console.log("catched allure query");
next(); // allow the next route to run

});

app.use((req, res, next) => {
    next({
        status: 404,
        message: 'Not Found',
    });
});

app.use((err, req, res, next) => {
    if (err.status === 404) {
        return res.status(400).render('404',{ layout: 'system.ejs' });
    }

    if (err.status === 500) {
        return res.status(500).render('500');
    }

    next();
});

const PORT = process.env.PORT || 8080;

http.listen(PORT, console.log(`Server started on port ${PORT}`));

Body:
You can use something like this Or just use somemiddleware-

app.use('/allure', function(req,res,next){
   if(<authenticate check>){ // some kind of authenticate check
     return express.static(path.join(__dirname, 'allure'));
   } else {
      <Any error you want to show>
   }
});

OR

app.use('/allure',<Auth Middlewarae> , express.static(path.join(__dirname, 'allure')));


问:
How to compre DateTime with generic times in ruby
I'm working on a ruby on rails app that can automatically schedule events. Every event has a start_time datetime and an end_time datetime.

Here is the problem:

In general, events shouldn't be scheduled before 9:00am or after 10:30pm. This is true for edge cases as well. I.e, even if an event ends after 9:00am, it shouldn't start before it. Similarly, if an event starts before 10:30pm, it should not go on passed 10:30pm.

How can I go about making sure that every event fits this criteria, when some of these events are on different dates?

The problem i'm having is that, yes, a DateTime object has a date and a time associated with it. But so does a Time object.

This means that if I have an event with a start and end datetime between 9am and 10:30pm, my comparison will always return false if I'm comparing a time object with a datetime object of a different date.

Here is what I had in mind:

```<code>def event_out_of_bounds?(event_start_time, event_end_time, min_start_time, max_end_time)

if event_start_time.hour > max_end_time.hour then
  return true
end

if event_end_time.hour > max_end_time.hour then
  return true
end

if event_start_time.hour < min_start_time.hour then
  return true
end

if event_end_time.hour < min_start_time.hour then
  return true
end

return false

end
</code>```

Problems with this code:

It doesn't take into account minutes. I.e., if I ever change min_start_time to 9:30 am, then this method won't work anymore.

There are different dates involved. event_start_time and event_end_time, which are DateTimes, obviously have the same date. However, min_start_time and max_end_time, Which are created using Time.new have a different date (I just default it 2020-01-01). This wouldn't be a big problem if I knew beforehand what the dates would be for the events, however I won't in this case.

Any ideas for an algorithm to make this check elegantly?

答:
Approach

It's curious that the question is framed in terms of DateTime objects, considering that the underlying problem seems to be just determining whether the scheduled time of a sporting match falls within a given window of time. Using DateTime objects is but one way of addressing the problem, but is not the only way. In that sense the question may fall under the heading of X-Y problem.

In fact, I find the use of DateTime objects complicates the problem unnecessarily. It's easier to express each time as simply a two-element array that contains the hour and minute. For example, the time-window that extends from 12:30 (24-hour clock) to 22:00 that evening could be expressed as the range:1

```<code>window = [12, 30]..[22, 0]
</code>```

Event times could be defined similarly:2

```<code>event_time = [15, 45]..[19, 30]
</code>```

For convenience, I will refer to the two-element arrays that are the endpoints of these ranges as simply "times".

An important consideration is that the start and end time of a sporting event does not necessarily fall on the same day. An example would be a tournament at which matches must fall within a window between 12:30 (24 hour clock) and 1:00 (AM) the following day. This is not unusual. This time-window would be expressed:

```<code>window = [12, 30]..[1, 0]
</code>```

I assume:

end times are less than 24 hours after their corresponding start times; and

the time-window is the same every day.

Adjustments could of course be made to the code below if either assumption does not hold.

Code

Let's construct a method valid? that returns true (else false) if a given event falls within a given time-window:

```<code>def valid?(event_time, window)
  e = time_to_mins(event_time.begin)..time_to_mins(event_time.end)
  w = time_to_mins(window.begin)..time_to_mins(window.end)
  if w.begin <= w.end
    w.cover?(e)
  else
    (w.begin <= e.begin || e.begin <= w.end) &&
    (w.begin <= e.end   || e.end   <= w.end)
  end
end
</code>```

```<code>def time_to_mins(time_arr)
  60 * time_arr.first + time_arr.last
end
</code>```

Examples

```<code>time_to_mins [ 0, 10]              #=> 10
time_to_mins [22, 30]              #=> 1350
</code>```

```<code>window = [ 9, 30]..[22, 30]

valid?([13, 45]..[16, 30], window) #=> true
valid?([ 8, 45]..[11, 30], window) #=> false
valid?([22, 15]..[ 0, 15], window) #=> false
</code>```

```<code>window = [12, 30]..[1, 0]

valid?([16, 15]..[19, 30], window) #=> true
valid?([22, 45]..[ 0, 30], window) #=> true
valid?([ 0, 15]..[ 0, 45], window) #=> true
valid?([22, 45]..[ 1, 30], window) #=> false
valid?([ 0, 15]..[ 1, 45], window) #=> false
</code>```

1. If desired, one might alternatively express times as hashes, such as { hour: 12, min: 30, sec: 0 }.

2. Information for each event might be held in a larger data structure, such as event = { start_date: [2020, 2, 7], time_block: [[22, 45, 0]..[ 0, 30, 0]], player_1: 'R. Federer', player_2: 'R. Nadal' }, using only event[:time_block] in the above calculation.

Body:
I'm working on a ruby on rails app that can automatically schedule events. Every event has a start_time datetime and an end_time datetime.

Here is the problem:

In general, events shouldn't be scheduled before 9:00am or after 10:30pm. This is true for edge cases as well. I.e, even if an event ends after 9:00am, it shouldn't start before it. Similarly, if an event starts before 10:30pm, it should not go on passed 10:30pm.

How can I go about making sure that every event fits this criteria, when some of these events are on different dates?

The problem i'm having is that, yes, a DateTime object has a date and a time associated with it. But so does a Time object.

This means that if I have an event with a start and end datetime between 9am and 10:30pm, my comparison will always return false if I'm comparing a time object with a datetime object of a different date.

Here is what I had in mind:

def event_out_of_bounds?(event_start_time, event_end_time, min_start_time, max_end_time)

if event_start_time.hour > max_end_time.hour then
  return true
end

if event_end_time.hour > max_end_time.hour then
  return true
end

if event_start_time.hour < min_start_time.hour then
  return true
end

if event_end_time.hour < min_start_time.hour then
  return true
end

return false

end

Problems with this code:

It doesn't take into account minutes. I.e., if I ever change min_start_time to 9:30 am, then this method won't work anymore.

There are different dates involved. event_start_time and event_end_time, which are DateTimes, obviously have the same date. However, min_start_time and max_end_time, Which are created using Time.new have a different date (I just default it 2020-01-01). This wouldn't be a big problem if I knew beforehand what the dates would be for the events, however I won't in this case.

Any ideas for an algorithm to make this check elegantly?

Body:
Approach

It's curious that the question is framed in terms of DateTime objects, considering that the underlying problem seems to be just determining whether the scheduled time of a sporting match falls within a given window of time. Using DateTime objects is but one way of addressing the problem, but is not the only way. In that sense the question may fall under the heading of X-Y problem.

In fact, I find the use of DateTime objects complicates the problem unnecessarily. It's easier to express each time as simply a two-element array that contains the hour and minute. For example, the time-window that extends from 12:30 (24-hour clock) to 22:00 that evening could be expressed as the range:1

window = [12, 30]..[22, 0]

Event times could be defined similarly:2

event_time = [15, 45]..[19, 30]

For convenience, I will refer to the two-element arrays that are the endpoints of these ranges as simply "times".

An important consideration is that the start and end time of a sporting event does not necessarily fall on the same day. An example would be a tournament at which matches must fall within a window between 12:30 (24 hour clock) and 1:00 (AM) the following day. This is not unusual. This time-window would be expressed:

window = [12, 30]..[1, 0]

I assume:

end times are less than 24 hours after their corresponding start times; and

the time-window is the same every day.

Adjustments could of course be made to the code below if either assumption does not hold.

Code

Let's construct a method valid? that returns true (else false) if a given event falls within a given time-window:

def valid?(event_time, window)
  e = time_to_mins(event_time.begin)..time_to_mins(event_time.end)
  w = time_to_mins(window.begin)..time_to_mins(window.end)
  if w.begin <= w.end
    w.cover?(e)
  else
    (w.begin <= e.begin || e.begin <= w.end) &&
    (w.begin <= e.end   || e.end   <= w.end)
  end
end

def time_to_mins(time_arr)
  60 * time_arr.first + time_arr.last
end

Examples

time_to_mins [ 0, 10]              #=> 10
time_to_mins [22, 30]              #=> 1350

window = [ 9, 30]..[22, 30]

valid?([13, 45]..[16, 30], window) #=> true
valid?([ 8, 45]..[11, 30], window) #=> false
valid?([22, 15]..[ 0, 15], window) #=> false

window = [12, 30]..[1, 0]

valid?([16, 15]..[19, 30], window) #=> true
valid?([22, 45]..[ 0, 30], window) #=> true
valid?([ 0, 15]..[ 0, 45], window) #=> true
valid?([22, 45]..[ 1, 30], window) #=> false
valid?([ 0, 15]..[ 1, 45], window) #=> false

1. If desired, one might alternatively express times as hashes, such as { hour: 12, min: 30, sec: 0 }.

2. Information for each event might be held in a larger data structure, such as event = { start_date: [2020, 2, 7], time_block: [[22, 45, 0]..[ 0, 30, 0]], player_1: 'R. Federer', player_2: 'R. Nadal' }, using only event[:time_block] in the above calculation.


问:
How to groupBy one column and count another column with condition in Laravel?
I have a table for students with column remarks which is equal to pass or fail and a column class to determine their group.

Now I want to get a collection using eloquent that goes like:

```<code>Select count(remarks) where 'remarks' equal to pass and
count(remarks) where 'remarks' equal to fail
GROUP BY class
</code>```

What I have tried so far:

```<code>Student::where('remarks', 'pass')
        ->selectRaw('count(remarks) as passRemark')
        ->where('remarks', 'fail')
        ->selectRaw('count(remarks) as failRemark')
        ->groupBy('class')->get();
</code>```

The above code doesn't seem to work and it returns nothing, it does work when using 1 where clause which is not what I intend to do and I tried adding another where, the query breaks.

Can anyone suggest the best approach for this?

答:
I guess you should try this query, using DB::raw(), just to see whether it works or not, then you can rewrite using the built in methods from the ORM.

SELECT SUM((CASE WHEN remarks = 'pass' THEN 1 ELSE 0 END)) AS passRemark,
       SUM((CASE WHEN remarks = 'fail' THEN 1 ELSE 0 END)) AS failRemark
GROUP BY class
```

Body:
I have a table for students with column remarks which is equal to pass or fail and a column class to determine their group.

Now I want to get a collection using eloquent that goes like:

Select count(remarks) where 'remarks' equal to pass and
count(remarks) where 'remarks' equal to fail
GROUP BY class

What I have tried so far:

Student::where('remarks', 'pass')
        ->selectRaw('count(remarks) as passRemark')
        ->where('remarks', 'fail')
        ->selectRaw('count(remarks) as failRemark')
        ->groupBy('class')->get();

The above code doesn't seem to work and it returns nothing, it does work when using 1 where clause which is not what I intend to do and I tried adding another where, the query breaks.

Can anyone suggest the best approach for this?


问:
FileNotFoundException for a valid file using FileInputStream
When I write an FileInputStream, while I have the valid file, it throws a FileNotFoundException.
I used this:

```<code>package io;
import java.io.*;
public class implementIo {
    public static int i;
    public static FileOutputStream output;
    public static FileInputStream input;
    public static void main(String args[]) {
    try {
                output = new FileOutputStream("writeModification.txt");
            input = new FileInputStream("modification.txt");
            do {
        i = input.read();
        if(i != -1) output.write(i);
        }while(i != -1);
    } catch (Exception e) {
        System.out.println("Exception caught " + e);
    } finally {
        try {
            if(output == null) input.close();
        }catch(IOException e) {
            System.out.println("IOException caught: " + e);
        }
    }
}
</code>```

}

While I had a two separate files named "modification.txt" and "printModification.txt" in the same package folder, yet the system threw a FileNotFoundException. Please help!

答:
This is because the FileInputStream doesn't provide the file creation during initialization like new FileOutputStream() does. So if these have been said, we can see one interesting thing to keep in mind: the modification.txt will be created every time when you initialize the FileOutputStream (and won't be overwritten) and this is why most probably your code breaks at the new FileInputStream() line.

How can you handle your exception?
You either create your file before executing the code( manually with New -> Text Document etc. ) or modify your code and make use of File class :

```<code>File file = new File("modification.txt");
    try {
        file.createNewFile();
        input = new FileInputStream(file);
        //your code here - output etc.
</code>```

Your code still doesn't work even if you have the files created in the same package folder? It's because the default path that your streams are looking for your files is the current working directory. Here is an example :

```<code>myproject
   |___src
   |    |___main
   |          |___java
   |                |___io
   |                     |___implementIo
   |___writeModification.txt
   |___modification.txt
</code>```

This is the correct structure if you want to use the streams like you did (with just a simple file name in stream constructor argument). But if your files are not there, you have to specify the absolute path. Here is an example :

```<code> myproject
   |___src
        |___main
              |___java
                    |___io
                         |___implementIo
                         |___writeModification.txt
                         |___modification.txt
</code>```

And the correct way to access the files is this:

```<code>FileInputStream input = new FileInputStream("C://myproject//src//main//java//io//modification.txt");
</code>```

Same for the output stream. (Please modify the path with your correct file location)

Body:
When I write an FileInputStream, while I have the valid file, it throws a FileNotFoundException.
I used this:

package io;
import java.io.*;
public class implementIo {
    public static int i;
    public static FileOutputStream output;
    public static FileInputStream input;
    public static void main(String args[]) {
    try {
                output = new FileOutputStream("writeModification.txt");
            input = new FileInputStream("modification.txt");
            do {
        i = input.read();
        if(i != -1) output.write(i);
        }while(i != -1);
    } catch (Exception e) {
        System.out.println("Exception caught " + e);
    } finally {
        try {
            if(output == null) input.close();
        }catch(IOException e) {
            System.out.println("IOException caught: " + e);
        }
    }
}

}

While I had a two separate files named "modification.txt" and "printModification.txt" in the same package folder, yet the system threw a FileNotFoundException. Please help!

Body:
This is because the FileInputStream doesn't provide the file creation during initialization like new FileOutputStream() does. So if these have been said, we can see one interesting thing to keep in mind: the modification.txt will be created every time when you initialize the FileOutputStream (and won't be overwritten) and this is why most probably your code breaks at the new FileInputStream() line.

How can you handle your exception?
You either create your file before executing the code( manually with New -> Text Document etc. ) or modify your code and make use of File class :

File file = new File("modification.txt");
    try {
        file.createNewFile();
        input = new FileInputStream(file);
        //your code here - output etc.

Your code still doesn't work even if you have the files created in the same package folder? It's because the default path that your streams are looking for your files is the current working directory. Here is an example :

myproject
   |___src
   |    |___main
   |          |___java
   |                |___io
   |                     |___implementIo
   |___writeModification.txt
   |___modification.txt

This is the correct structure if you want to use the streams like you did (with just a simple file name in stream constructor argument). But if your files are not there, you have to specify the absolute path. Here is an example :

 myproject
   |___src
        |___main
              |___java
                    |___io
                         |___implementIo
                         |___writeModification.txt
                         |___modification.txt

And the correct way to access the files is this:

FileInputStream input = new FileInputStream("C://myproject//src//main//java//io//modification.txt");

Same for the output stream. (Please modify the path with your correct file location)


问:
Thread-safe uniform random number generator
I have some parallel Fortran90 code in which each thread needs to generate the same sequence of random numbers.

I have a random number generator that seems to be thread-unsafe, since, for a given seed, I'm completely unable to repeat the same results each time I run the program.

I surfed unsuccessfully (almost) the entire web looking for some code of a thread-safe RNG. Could anyone provide me with (the link to) the code of one?

Thanks in advance!

答: A good Pseudorandom number generator for Fortran90 can be found in the Intel Math Kernel Vector Statistical Library.  They are thread safe.  Also, why does it need to be threadsafe?  If you want each thread to get the same list, instantiate a new PRNG for each thread with the same seed.</p>

OwnerDisplayName: Bellman

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Eric P

OwnerDisplayName: John Ellinwood


问:
Efficient traversal of a directed acyclic graph
Input:

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

Resulting Tree:

Output:

```<code>total_time = sum of all individual wait_time //without overlap
</code>```

Rules:

Input code will always result a directed acyclic graph

Each node has some wait_time value

A complete graph traversal should calculate the total wait_time of whole graph

All independent nodes must be traversed in parallel (or at least time calculation should be in this way)

If overlapping of wait_time of two different nodes occur then maximum value will be considered and traversal of a node with lesser time will move to the next independent node

All single and paired nodes will have exactly 1 and 2 in-coming and out-going edges except roots and leaves (there can be multiple roots and leaves)

Problem 1: How to convert given input-code into the graph so it can be traversed? (pseudo-code or any kind of guidance might help)

Problem 2: How to achieve the successful traversal based on mentioned rules?

Previous Effort:

I was able to sort the nodes in a linear way using Topological
sort, but I am not sure how can I achieve these specific goals.

I drew this graph based on my intuition from code.

Digits on the edges are just to clarify what number is causing the
dependency.

I am using python 3

My previous code does not seem to make any sense in relevance to
these problems so I did not include that.

答:
Creating the graph

Let a, b, c three nodes which have a 0 property/depandancy in common (to node 0). If a is discovered before b, and b discovered before c, edge should be a->b and b->c.

To address above rule, consider a cache for every discovered digit.
If a node includes 0, then you cache it as cache[0].
Later on if an other node b includes 0, you must make an edge from cache[0] to b, and update that cache so that subsequent node including 0 get an edge from b.

```<code>foreach input as node
  forall dependancy of node
    if discovered[dependancy]
      make_edge(discovered[dependancy], node)
    fi
    discovered[dependancy] = node // apply dependancy "transitivity"
</code>```

Now to build the graph as "layers" you can start from the leaves (layer 0), here [1,4],[0,2],[0,3] only.
Then take the nodes whose output edge link to any of the leaves, here only [1,4]. (because [1,3] while linking to [3] which is a leaf, also links to [1,4] which is not. So excluded). You then have built the layer 1.

While building layer n, you can only add nodes having deps to layer 0 to n-1

A more compact way of saying this is for a node, to compute its eccentricity (the longest path (here to the leaves)).

To print the graph as you did, notice you can just plot the nodes by eccentricity which would show the "level" of dependancy (how far they are from the leaves/end, see plotByLayers in code below).

Computing the total time

We don't need to go to the hassle of building layers as above.

A node can start only when all of its ancestors end.

The ancestors have already been determined when we made the graph.

The recursion is thus

```<code>n.endAt = max(n.endAt for n in n.ancestors) + n.wait
</code>```

Initialization being for the root nodes (which have no dependancy) and where we can just keep the wait time.

```<code>nroot.endAt = nroot.wait
</code>```

Regarding the node.id notation i)x,y. i is the ith node as read in input. (its true id somehow. x,y is just garbage to help us visualize).

const input = `
nd[0];
nd[1, 2];
nd[3, 4];
nd[0, 1];
nd[2, 3];
nd[0, 4];
nd[1, 3];
nd[0, 2];
nd[1, 4];
nd[3];
nd[1, 4];`
function makeGraph(input) {
  const nodes = input.trim().split('\n').map((x,i) => {
    const deps = x.match(/\[(.+)\]/)[1]
    return { id: i+')'+deps, v: deps.split(',').map(x => x.trim()) }
  })
  const edges = {}
  const discovered = {}
  nodes.forEach((node, i) => {
    node.v.forEach(digit => {
      if (discovered[digit]) {
        // there is an edge
        edges[discovered[digit].id] = edges[discovered[digit].id] || []
        edges[discovered[digit].id].push(node)
      }
      // apply transitivity a->b->c
      discovered[digit] = node
    })
  })
  return {nodes, edges}
}

function computeEccentricity(n, edges) {
  if (typeof(n.eccentricity) !== 'undefined') {
    return n.eccentricity
  }
  if (!edges[n.id]) {// a leaf has no outgoing edges
    n.eccentricity = 0
    return 0
  }
  const distances = Object.values(edges[n.id]).map(n => computeEccentricity(n, edges))
  const min = Math.max(...distances)
  n.eccentricity = 1 + min
  return n.eccentricity
}

function plotByLayers(nodes) {
  const lvls = []
  let m = 0;
  nodes.forEach(n => {
    const i = n.eccentricity
    lvls[i] = lvls[i] || []
    lvls[i].push(n)
    m = i > m ? i: m
  })
  for(let i = m; i >=0 ; --i) {
    console.log(lvls[i].map(x => x.id))
  }
  return lvls
}
const { nodes, edges } = makeGraph(input)
nodes.forEach(n => computeEccentricity(n, edges))
plotByLayers(nodes)

// for any node, compute its ancestors.
nodes.forEach((n, i) => {
  if (edges[n.id]) {
    edges[n.id].forEach(v => {
      v.ancestors = v.ancestors || []
      v.ancestors.push(n)
    })
  }
  n.wait = 2**i // say arbitrarily that i node waits 2^i some time
})
function computeEndAt(node) {
  if (typeof(node.endAt) !== 'undefined') {
    return node.endAt
  }
  if (!node.ancestors) {
    node.endAt = 0 + node.wait
    return node.endAt
  }
  const maxEnd = Math.max(...node.ancestors.map(computeEndAt))
  node.endAt = maxEnd + node.wait
  return node.endAt
}
nodes.forEach(computeEndAt)
const longest = nodes.sort((a,b)=>b.endAt - a.endAt)[0]
console.log('awaited: ', longest.endAt, longest.id)```

Body:
Input:

nd[0];
nd[1, 2];
nd[3, 4];
nd[0, 1];
nd[2, 3];
nd[0, 4];
nd[1, 3];
nd[0, 2];
nd[1, 4];
nd[3];
nd[1, 4];

Resulting Tree:

Output:

total_time = sum of all individual wait_time //without overlap

Rules:

Input code will always result a directed acyclic graph

Each node has some wait_time value

A complete graph traversal should calculate the total wait_time of whole graph

All independent nodes must be traversed in parallel (or at least time calculation should be in this way)

If overlapping of wait_time of two different nodes occur then maximum value will be considered and traversal of a node with lesser time will move to the next independent node

All single and paired nodes will have exactly 1 and 2 in-coming and out-going edges except roots and leaves (there can be multiple roots and leaves)

Problem 1: How to convert given input-code into the graph so it can be traversed? (pseudo-code or any kind of guidance might help)

Problem 2: How to achieve the successful traversal based on mentioned rules?

Previous Effort:

I was able to sort the nodes in a linear way using Topological
sort, but I am not sure how can I achieve these specific goals.

I drew this graph based on my intuition from code.

Digits on the edges are just to clarify what number is causing the
dependency.

I am using python 3

My previous code does not seem to make any sense in relevance to
these problems so I did not include that.

Body:
Creating the graph

Let a, b, c three nodes which have a 0 property/depandancy in common (to node 0). If a is discovered before b, and b discovered before c, edge should be a->b and b->c.

To address above rule, consider a cache for every discovered digit.
If a node includes 0, then you cache it as cache[0].
Later on if an other node b includes 0, you must make an edge from cache[0] to b, and update that cache so that subsequent node including 0 get an edge from b.

foreach input as node
  forall dependancy of node
    if discovered[dependancy]
      make_edge(discovered[dependancy], node)
    fi
    discovered[dependancy] = node // apply dependancy "transitivity"

Now to build the graph as "layers" you can start from the leaves (layer 0), here [1,4],[0,2],[0,3] only.
Then take the nodes whose output edge link to any of the leaves, here only [1,4]. (because [1,3] while linking to [3] which is a leaf, also links to [1,4] which is not. So excluded). You then have built the layer 1.

While building layer n, you can only add nodes having deps to layer 0 to n-1

A more compact way of saying this is for a node, to compute its eccentricity (the longest path (here to the leaves)).

To print the graph as you did, notice you can just plot the nodes by eccentricity which would show the "level" of dependancy (how far they are from the leaves/end, see plotByLayers in code below).

Computing the total time

We don't need to go to the hassle of building layers as above.

A node can start only when all of its ancestors end.

The ancestors have already been determined when we made the graph.

The recursion is thus

n.endAt = max(n.endAt for n in n.ancestors) + n.wait

Initialization being for the root nodes (which have no dependancy) and where we can just keep the wait time.

nroot.endAt = nroot.wait

Regarding the node.id notation i)x,y. i is the ith node as read in input. (its true id somehow. x,y is just garbage to help us visualize).

const input = `
nd[0];
nd[1, 2];
nd[3, 4];
nd[0, 1];
nd[2, 3];
nd[0, 4];
nd[1, 3];
nd[0, 2];
nd[1, 4];
nd[3];
nd[1, 4];`
function makeGraph(input) {
  const nodes = input.trim().split('\n').map((x,i) => {
    const deps = x.match(/\[(.+)\]/)[1]
    return { id: i+')'+deps, v: deps.split(',').map(x => x.trim()) }
  })
  const edges = {}
  const discovered = {}
  nodes.forEach((node, i) => {
    node.v.forEach(digit => {
      if (discovered[digit]) {
        // there is an edge
        edges[discovered[digit].id] = edges[discovered[digit].id] || []
        edges[discovered[digit].id].push(node)
      }
      // apply transitivity a->b->c
      discovered[digit] = node
    })
  })
  return {nodes, edges}
}

function computeEccentricity(n, edges) {
  if (typeof(n.eccentricity) !== 'undefined') {
    return n.eccentricity
  }
  if (!edges[n.id]) {// a leaf has no outgoing edges
    n.eccentricity = 0
    return 0
  }
  const distances = Object.values(edges[n.id]).map(n => computeEccentricity(n, edges))
  const min = Math.max(...distances)
  n.eccentricity = 1 + min
  return n.eccentricity
}

function plotByLayers(nodes) {
  const lvls = []
  let m = 0;
  nodes.forEach(n => {
    const i = n.eccentricity
    lvls[i] = lvls[i] || []
    lvls[i].push(n)
    m = i > m ? i: m
  })
  for(let i = m; i >=0 ; --i) {
    console.log(lvls[i].map(x => x.id))
  }
  return lvls
}
const { nodes, edges } = makeGraph(input)
nodes.forEach(n => computeEccentricity(n, edges))
plotByLayers(nodes)

// for any node, compute its ancestors.
nodes.forEach((n, i) => {
  if (edges[n.id]) {
    edges[n.id].forEach(v => {
      v.ancestors = v.ancestors || []
      v.ancestors.push(n)
    })
  }
  n.wait = 2**i // say arbitrarily that i node waits 2^i some time
})
function computeEndAt(node) {
  if (typeof(node.endAt) !== 'undefined') {
    return node.endAt
  }
  if (!node.ancestors) {
    node.endAt = 0 + node.wait
    return node.endAt
  }
  const maxEnd = Math.max(...node.ancestors.map(computeEndAt))
  node.endAt = maxEnd + node.wait
  return node.endAt
}
nodes.forEach(computeEndAt)
const longest = nodes.sort((a,b)=>b.endAt - a.endAt)[0]
console.log('awaited: ', longest.endAt, longest.id)


问:
How to transform position from one object to the current player position?
So i have this little particlesystem attached on my player so if he dies he explodes. But i cant simply attach the particlesystem under the player because if i destroy my player the childs of the gameobjects get destroyed as well. The animation runs if he dies but not on his current spot so some ideas for that? Maybe to transform the position to the current position of the player while he dies?
Here my code:</p>

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class playerdeath : MonoBehaviour
{

    public ParticleSystem death_explosion;

    // Start is called before the first frame update
    void Start()
    {

        death_explosion.Stop();
    }

    // Update is called once per frame
    void Update()
    {

    }

    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "deathcube")
            Destroy(gameObject);
        Debug.Log("collision detected");
        death_explosion.Play();
    }
}
</code>```

答:
What you could do is create a prefab of the particle object and reference it inside your script like so:

```<code>public ParticleSystem death_explosion_Prefab;
</code>```

And instead of attaching it to the Player as a child, instantiate it on collision:

```<code>void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "deathcube")
        {
            Debug.Log("collision detected");
            Instantiate(death_explosion_Prefab, gameObject.transform.position, Quaternion.identity);
            Destroy(gameObject);
        }
    }
</code>```

Body:
So i have this little particlesystem attached on my player so if he dies he explodes. But i cant simply attach the particlesystem under the player because if i destroy my player the childs of the gameobjects get destroyed as well. The animation runs if he dies but not on his current spot so some ideas for that? Maybe to transform the position to the current position of the player while he dies?
Here my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class playerdeath : MonoBehaviour
{

    public ParticleSystem death_explosion;

    // Start is called before the first frame update
    void Start()
    {

        death_explosion.Stop();
    }

    // Update is called once per frame
    void Update()
    {

    }

    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "deathcube")
            Destroy(gameObject);
        Debug.Log("collision detected");
        death_explosion.Play();
    }
}

Body:
What you could do is create a prefab of the particle object and reference it inside your script like so:

public ParticleSystem death_explosion_Prefab;

And instead of attaching it to the Player as a child, instantiate it on collision:

void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "deathcube")
        {
            Debug.Log("collision detected");
            Instantiate(death_explosion_Prefab, gameObject.transform.position, Quaternion.identity);
            Destroy(gameObject);
        }
    }


问:
Action when tap on tableViewCell (swift)
I want execute a code when user tap on tableViewCell, this is the code:

```<code>import UIKit
import MediaPlayer

class ViewController: UIViewController, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return titolo.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellReuseIdentifier")!
    let text1 = titolo[indexPath.row]
    let text2 = genere[indexPath.row]
    cell.textLabel?.text = text1
    cell.detailTextLabel?.text = text2
    return cell
}

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    print("test tap cell")
}

@IBOutlet weak var tableView: UITableView!

let mediaItems = MPMediaQuery.songs().items
let musicPlayer = MPMusicPlayerApplicationController.applicationQueuePlayer

...
</code>```

This function not work:

```<code>func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    print("test tap cell")
}
</code>```

"test tap cell" does not appear in the console.

答:
You need to set delegate and dataSource and implement  didSelectRowAt correctly

```<code>class ViewController: UIViewController , UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.tableView.delegate = self
        self.tableView.dataSource = self

    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return titolo.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellReuseIdentifier")!
        cell.textLabel?.text = text1
        cell.detailTextLabel?.text = text2
        return cell
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
         print("test tap cell")
    }
}
</code>```

Body:
I want execute a code when user tap on tableViewCell, this is the code:

import UIKit
import MediaPlayer

class ViewController: UIViewController, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return titolo.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellReuseIdentifier")!
    let text1 = titolo[indexPath.row]
    let text2 = genere[indexPath.row]
    cell.textLabel?.text = text1
    cell.detailTextLabel?.text = text2
    return cell
}

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    print("test tap cell")
}

@IBOutlet weak var tableView: UITableView!

let mediaItems = MPMediaQuery.songs().items
let musicPlayer = MPMusicPlayerApplicationController.applicationQueuePlayer

...

This function not work:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    print("test tap cell")
}

"test tap cell" does not appear in the console.

Body:
You need to set delegate and dataSource and implement  didSelectRowAt correctly

class ViewController: UIViewController , UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.tableView.delegate = self
        self.tableView.dataSource = self

    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return titolo.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellReuseIdentifier")!
        cell.textLabel?.text = text1
        cell.detailTextLabel?.text = text2
        return cell
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
         print("test tap cell")
    }
}


问:
Can't convert time strings from csv to datetime
I have a csv file with 2 timestamps per row consisting of date, time and a value:

```<code>02.04.2019 00:30:30;02.04.2019 00:36:05;6354
02.04.2019 02:36:05;02.04.2019 03:41:40;3453
02.04.2019 03:41:40;02.04.2019 04:47:15;5456
</code>```

When I try to convert date and time string to datetime:

```<code>with open("file.csv", "rt", encoding='utf-8-sig') as source:
    reader = csv.reader(source)
    for row in csv.reader(source, delimiter=";"):
        dateTimeBegin = row[0]
        dateTimeEnd = row[1]
        begin_intervall = datetime.datetime.strptime("%d.%m.%Y %I:%M:%S", dateTimeBegin)
        end_intervall = datetime.datetime.strptime("%d.%m.%Y %I:%M:%S", dateTimeEnd)
</code>```

I got:

```<code>Traceback (most recent call last):
  File ".\compare.py", line 48, in <module>
    begin_intervall = datetime.datetime.strptime("%d.%m.%Y %I:%M:%S", dateTimeBegin)
  File "C:\Users\foobar\AppData\Local\Programs\Python\Python38-32\lib\_strptime.py", line 568, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "C:\Users\foobar\AppData\Local\Programs\Python\Python38-32\lib\_strptime.py", line 349, in _strptime
    raise ValueError("time data %r does not match format %r" %
ValueError: time data '%d.%m.%Y %I:%M:%S' does not match format '02.04.2019 00:30:30'
</code>```

Why is that? When I try something like

```<code>date_time_str ="08.04.2018 05:35:38"
date_time_obj = datetime.datetime.strptime(date_time_str, '%d.%m.%Y %I:%M:%S')
</code>```

it works fine.

EDIT:
I swapped format and time string and used some other data:

```<code>02.04.2019 01:30:30;02.04.2019 02:36:05;6354 #works
02.04.2019 02:36:05;02.04.2019 03:41:40;3453 #works
02.04.2019 03:41:40;02.04.2019 04:47:15;5456 #works
03.04.2019 00:25:03;03.04.2019 01:30:12;5997 #ERROR
03.04.2019 01:30:12;03.04.2019 02:35:21;5993
03.04.2019 02:35:21;03.04.2019 03:40:30;5994
</code>```

Error is still:

```<code>Traceback (most recent call last):
  File ".\new.py", line 12, in <module>
    begin_intervall = datetime.datetime.strptime(dateTimeBegin, "%d.%m.%Y %I:%M:%S")
  File "C:\Users\foobar\AppData\Local\Programs\Python\Python38-32\lib\_strptime.py", line 568, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "C:\Users\foobar\AppData\Local\Programs\Python\Python38-32\lib\_strptime.py", line 349, in _strptime
    raise ValueError("time data %r does not match format %r" %
ValueError: time data '03.04.2019 00:25:03' does not match format '%d.%m.%Y %I:%M:%S'
</code>```

Seems to be the 00:25:03. But %I is the 24hour format.

答:
As per the datetime docs

the functions is defined as  datetime.strptime(date_string, format)

This means the first parameter will be Date string (02.04.2019 01:30:30) or the variable dateTimeBegin and Second will be the format String ('%d.%m.%Y %I:%M:%S').

Body:
I have a csv file with 2 timestamps per row consisting of date, time and a value:

02.04.2019 00:30:30;02.04.2019 00:36:05;6354
02.04.2019 02:36:05;02.04.2019 03:41:40;3453
02.04.2019 03:41:40;02.04.2019 04:47:15;5456

When I try to convert date and time string to datetime:

with open("file.csv", "rt", encoding='utf-8-sig') as source:
    reader = csv.reader(source)
    for row in csv.reader(source, delimiter=";"):
        dateTimeBegin = row[0]
        dateTimeEnd = row[1]
        begin_intervall = datetime.datetime.strptime("%d.%m.%Y %I:%M:%S", dateTimeBegin)
        end_intervall = datetime.datetime.strptime("%d.%m.%Y %I:%M:%S", dateTimeEnd)

I got:

Traceback (most recent call last):
  File ".\compare.py", line 48, in <module>
    begin_intervall = datetime.datetime.strptime("%d.%m.%Y %I:%M:%S", dateTimeBegin)
  File "C:\Users\foobar\AppData\Local\Programs\Python\Python38-32\lib\_strptime.py", line 568, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "C:\Users\foobar\AppData\Local\Programs\Python\Python38-32\lib\_strptime.py", line 349, in _strptime
    raise ValueError("time data %r does not match format %r" %
ValueError: time data '%d.%m.%Y %I:%M:%S' does not match format '02.04.2019 00:30:30'

Why is that? When I try something like

date_time_str ="08.04.2018 05:35:38"
date_time_obj = datetime.datetime.strptime(date_time_str, '%d.%m.%Y %I:%M:%S')

it works fine.

EDIT:
I swapped format and time string and used some other data:

02.04.2019 01:30:30;02.04.2019 02:36:05;6354 #works
02.04.2019 02:36:05;02.04.2019 03:41:40;3453 #works
02.04.2019 03:41:40;02.04.2019 04:47:15;5456 #works
03.04.2019 00:25:03;03.04.2019 01:30:12;5997 #ERROR
03.04.2019 01:30:12;03.04.2019 02:35:21;5993
03.04.2019 02:35:21;03.04.2019 03:40:30;5994

Error is still:

Traceback (most recent call last):
  File ".\new.py", line 12, in <module>
    begin_intervall = datetime.datetime.strptime(dateTimeBegin, "%d.%m.%Y %I:%M:%S")
  File "C:\Users\foobar\AppData\Local\Programs\Python\Python38-32\lib\_strptime.py", line 568, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "C:\Users\foobar\AppData\Local\Programs\Python\Python38-32\lib\_strptime.py", line 349, in _strptime
    raise ValueError("time data %r does not match format %r" %
ValueError: time data '03.04.2019 00:25:03' does not match format '%d.%m.%Y %I:%M:%S'

Seems to be the 00:25:03. But %I is the 24hour format.


问:
jQuery mouseleave on nested ul
I'm putting together a simple drop down that contains nested ul's. I want it to animate to a visible state when hovering over the top level li. And, then animate to a hidden state when the mouse leaves the entire navigation area.

It works fine when animating to a visible state. My problem is the hiding part. It seems to fire the mouseleave whenever the mouse leaves the top level li. I though that mouseleave shouldn't do that for child elements unless I'm thinking wrong.

Below is the code. Any help or insight is appreciated.

```<code>$(document).ready(function() {

        //When mouse rolls over
        $('#mainNavBar li').mouseenter(function(){
            $('.menuDrop').stop().animate({height:'163px'},{ queue:false, duration:300, easing: 'easeInQuart'})
        });

        //When mouse is removed
        $('#mainNavBar li').mouseleave(function(){
            $('.menuDrop').stop().animate({height:'0px'},{ queue:false, duration:300, easing: 'easeOutQuart'})
        });

    });
</code>```

And the HTML

```<code><ul id="mainNavBar">
                <li id="pos1"><a href="#"><span class="accesslinks">TOP 1</span></a>
                    <div class="menuDrop">
                        <ul class="products">
                            <li class="active">Product 1</li>
                            <li>Product 2</li>
                            <li>Product 3</li>
                            <li>Product 4</li>
                        </ul>
                        <ul class="tabs">
                            <li class="selected"><a href="#">Tab 1</a></li>
                            <li><a href="#">Tab 2</a></li>
                            <li><a href="#">Tab 3</a></li>
                            <li><a href="#">Tab 4</a></li>
                        </ul>
                    </div>
                </li>
                <li id="pos2"><a href="#"><span class="accesslinks">TOP 2</span></a>
                    <div class="menuDrop">
                        <ul class="products">
                            <li class="active">Product 5</li>
                            <li>Product 6</li>
                            <li>Product 7</li>
                            <li>product 8</li>
                        </ul>
                        <ul class="tabs">
                            <li class="selected"><a href="#">Tab 1</a></li>
                            <li><a href="#">Tab 2</a></li>
                            <li><a href="#">Tab 3</a></li>
                            <li><a href="#">Tab 4</a></li>
                        </ul>
                    </div>
                </li>
            </ul>
</code>```

答:
The problem is that #mainNavBar li matches all li elements within #mainNavBar at any level.  That means that it matches the inner li elements as well.  If you want it to only happen on the direct children change your selector to #mainNavBar > li.

Also, I'm thinking you probably want $(this).find('.menuDrop') instead of just $('.menuDrop'), otherwise you will affect all .menuDrop elements and not just the ones that are within your hovered li.

You may also want to try hover to simplify your code.

http://api.jquery.com/hover/

ContentLicense: CC BY-SA 3.0

Title: jQuery mouseleave on nested ul

Body:
I'm putting together a simple drop down that contains nested ul's. I want it to animate to a visible state when hovering over the top level li. And, then animate to a hidden state when the mouse leaves the entire navigation area.

It works fine when animating to a visible state. My problem is the hiding part. It seems to fire the mouseleave whenever the mouse leaves the top level li. I though that mouseleave shouldn't do that for child elements unless I'm thinking wrong.

Below is the code. Any help or insight is appreciated.

$(document).ready(function() {

        //When mouse rolls over
        $('#mainNavBar li').mouseenter(function(){
            $('.menuDrop').stop().animate({height:'163px'},{ queue:false, duration:300, easing: 'easeInQuart'})
        });

        //When mouse is removed
        $('#mainNavBar li').mouseleave(function(){
            $('.menuDrop').stop().animate({height:'0px'},{ queue:false, duration:300, easing: 'easeOutQuart'})
        });

    });

And the HTML

TOP 1

Product 1

Product 2

Product 3

Product 4

Tab 1

Tab 2

Tab 3

Tab 4

TOP 2

Product 5

Product 6

Product 7

product 8

Tab 1

Tab 2

Tab 3

Tab 4


问:
Partial overlapping of image with color
I am trying to accomplish this section of a webpage and am having a difficult time finding a good way to overlap the yellow from the 1st column partially over the 2nd column image. I have set up the columns and have tried using negative properties but that didn't work. I tried adding it to the image in Photoshop but that was a BIG fail. I obviously can't do a border hack with opacity.

Am I missing something? I just can't think of a good way to do this. Any help is appreciated.

答:
I would approach this using absolutely positioned pseudo content within a relatively positioned parent. The following example is missing many details, of course (media queries, better spacing, font treatment, etc.), but is one way to accomplish what you're trying to do.

.container {
  display: flex;
}

.leaf {
  background-color: yellow;
  flex: 1;
  position: relative;
  margin: 2.5em 0;
}

.leaf-content {
  padding: 1em 3em 1em 1em;
}

.leaf::after {
  content: '';
  background-color: yellow;
  right: -150px;
  top: 0;
  bottom: 0;
  width: 150px;
  opacity: .35;
  position: absolute;
}

.container img {
  width: 500px;
  height: auto;
}

body {
  font-family: sans-serif;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="leaf">
    <div class="leaf-content">
      <h1>BIKE</h1>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sed est, ipsa minus repellendus, rerum officia eaque, quia pariatur voluptatibus asperiores inventore illum laudantium soluta itaque sit nobis officiis deserunt vero!</p>
    </div>

  </div>
  <div class="img-container">
    <img src="https://images.unsplash.com/photo-1517054612019-1bf855127c43?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=e4814eb541ddb4ef86140974f1bee831&fit=crop&w=1000&h=1000&q=80" alt="">
  </div>
</div></code>```

jsFiddle

Title: Partial overlapping of image with color

Body:
I would approach this using absolutely positioned pseudo content within a relatively positioned parent. The following example is missing many details, of course (media queries, better spacing, font treatment, etc.), but is one way to accomplish what you're trying to do.

.container {
  display: flex;
}

.leaf {
  background-color: yellow;
  flex: 1;
  position: relative;
  margin: 2.5em 0;
}

.leaf-content {
  padding: 1em 3em 1em 1em;
}

.leaf::after {
  content: '';
  background-color: yellow;
  right: -150px;
  top: 0;
  bottom: 0;
  width: 150px;
  opacity: .35;
  position: absolute;
}

.container img {
  width: 500px;
  height: auto;
}

body {
  font-family: sans-serif;
}

<div class="container">
  <div class="leaf">
    <div class="leaf-content">
      <h1>BIKE</h1>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sed est, ipsa minus repellendus, rerum officia eaque, quia pariatur voluptatibus asperiores inventore illum laudantium soluta itaque sit nobis officiis deserunt vero!</p>
    </div>

  </div>
  <div class="img-container">
    <img src="https://images.unsplash.com/photo-1517054612019-1bf855127c43?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=e4814eb541ddb4ef86140974f1bee831&fit=crop&w=1000&h=1000&q=80" alt="">
  </div>
</div>

jsFiddle


问:
Replacement in a loop using find and sed
Please help me with advice

I need to go through the files in this $tmp directory and make substitutions in the lines according to the rule described in sed

I trained on one file and this sed worked it out normally.
But when I perform a replacement in for , I get some nonsense on the output

```<code>for file in $tmp/*.txt; do
    find $tmp/ -type f -name "*.txt" -exec sed -i -e 's/, /\n''/g; s/"//g; s/$/\x0A/; s/:[ ]/;/g;  s/\n''/;\n''/g; s/^[ t]*//' {} \;
done
</code>```

How can I fix it?
Thanks…

UP

I did it.

find - It was really unnecessary

@Rob Sweet Thanks!

答:
When you don't need to edit files in a subdir of /tmp, than give sed all files in once.

```<code>sed -i your_command *.txt
</code>```

Off topic:

I don't understand your sed command. Why two single quotes? When you want to replace a newline, consider option -z.

Body:
Please help me with advice

I need to go through the files in this $tmp directory and make substitutions in the lines according to the rule described in sed

I trained on one file and this sed worked it out normally.
But when I perform a replacement in for , I get some nonsense on the output

for file in $tmp/*.txt; do
    find $tmp/ -type f -name "*.txt" -exec sed -i -e 's/, /\n''/g; s/"//g; s/$/\x0A/; s/:[ ]/;/g;  s/\n''/;\n''/g; s/^[ t]*//' {} \;
done

How can I fix it?
Thanks…

UP

I did it.

find - It was really unnecessary

@Rob Sweet Thanks!

Body:
When you don't need to edit files in a subdir of /tmp, than give sed all files in once.

sed -i your_command *.txt

Off topic:

I don't understand your sed command. Why two single quotes? When you want to replace a newline, consider option -z.


问:
What is the purpose of the key pairs (public and private) available in aws ec2?
In the AWS EC2 console/service, you are able to view several key pairs - what exactly is the purpose of these key pairs? Are they relevant to the ec2 instances or the rds?</p>

答:
Keypairs are not actually related to AWS or Amazon EC2. They are related to Linux.

When using Linux utilities like ssh and scp, keypairs are used to authenticate users. For example, if you use this command:

```<code>ssh -i key.pem ec2-user@IP-ADDRESS
</code>```

The receiving Linux operating system will look in the /home/ec2-user/.ssh/authorized_keys file. It will check whether the private keypair supplied in key.pem matches a public keypair in that file. If they match, then the connection is permitted.

To make this process simpler, there is some software installed in Amazon Linux that will accept a nominated keypair and install the public half in the the authorized_keys file. This makes it easy to initially login to the instance.

You are then welcome to modify the contents of the authorized_keys file to add/remove any keypairs you wish. You can also create new users on the operating system and add appropriate keypairs to their authorized_keys file.

Common corporate security practices involve each staff member generating their own keypair (so only they have the private keypair), then providing the public half of the keypair to the IT department. Whenever access is requested to a particular Linux computer, the IT people can add their public keypair in the appropriate location. This then grants the staff member access to the computer.

The Amazon EC2 service provides an easy way to generate keys and it will also keep the public half of the keypair, which can be used to add keys when an instance is launched. However, you do not need to keep these keypairs! If you prefer to manage the keypairs yourself (as suggested above), then you do not need to keep these in AWS beyond the initial launch of the instance.

Amazon RDS does not allow users to connect via SSH, so keypairs are not used with Amazon RDS.

Bottom line: Keypairs are used by Linux computers to authenticate users.

Body:
Keypairs are not actually related to AWS or Amazon EC2. They are related to Linux.

When using Linux utilities like ssh and scp, keypairs are used to authenticate users. For example, if you use this command:

ssh -i key.pem ec2-user@IP-ADDRESS

The receiving Linux operating system will look in the /home/ec2-user/.ssh/authorized_keys file. It will check whether the private keypair supplied in key.pem matches a public keypair in that file. If they match, then the connection is permitted.

To make this process simpler, there is some software installed in Amazon Linux that will accept a nominated keypair and install the public half in the the authorized_keys file. This makes it easy to initially login to the instance.

You are then welcome to modify the contents of the authorized_keys file to add/remove any keypairs you wish. You can also create new users on the operating system and add appropriate keypairs to their authorized_keys file.

Common corporate security practices involve each staff member generating their own keypair (so only they have the private keypair), then providing the public half of the keypair to the IT department. Whenever access is requested to a particular Linux computer, the IT people can add their public keypair in the appropriate location. This then grants the staff member access to the computer.

The Amazon EC2 service provides an easy way to generate keys and it will also keep the public half of the keypair, which can be used to add keys when an instance is launched. However, you do not need to keep these keypairs! If you prefer to manage the keypairs yourself (as suggested above), then you do not need to keep these in AWS beyond the initial launch of the instance.

Amazon RDS does not allow users to connect via SSH, so keypairs are not used with Amazon RDS.

Bottom line: Keypairs are used by Linux computers to authenticate users.


问:
Filtering a mongodb query result based on the position of a field in an array
Apologies for the confusing title, I am not sure how to summarize this.

Suppose I have the following list of documents in a collection:

{ "name": "Lorem", "source": "A" }
{ "name": "Lorem", "source": "B" }
{ "name": "Ipsum", "source": "A" }
{ "name": "Ipsum", "source": "B" }
{ "name": "Ipsum", "source": "C" }
{ "name": "Foo",   "source": "B" }
```

<p>as well an ordered list of accepted sources, where lower indexes signify higher priority</p>

<pre class="lang-py prettyprint-override"><code>sources = ["A", "B"]
</code>```

My query should:

Take a list of available sources and a list of wanted names

Return a maximum of one document per name.

In case of multiple matches, the document with the most prioritized source should be chosen.

Example:

wanted_names = ['Lorem', 'Ipsum', 'Foo', 'NotThere']
```

<p>Result: </p>

<pre class="lang-py prettyprint-override"><code>{ "name": "Lorem", "source": "A" }
{ "name": "Ipsum", "source": "A" }
{ "name": "Foo",   "source": "B" }
</code>```

The results don't necessarily have to be ordered.

Is it possible to do this with a Mongo query alone? If so could someone point me towards a resource detailing how to accomplish it?

My current solution doesn't support a list of names, and instead relies on a Python script to execute multiple queries:

```<code>db.collection.aggregate([
    {$match: {
        "name": "Lorem",
        "source": {
            $in: sources
    }}},
    {$addFields: {
        "order": {
            $indexOfArray: [sources, "$source"]
    }}},
    {$sort: {
        "order": 1
    }},
    {$limit: 1}
]);
</code>```

Note: _id fields are omitted in this question for the sake of brevity

答:
How about this: With $group we have $min operator which takes lower source

Note: If you prioritize as ['B', 'A'], use $max then

```<code>db.collection.aggregate([
  {
    $match: {
      "name": {
        $in: [
          "Lorem",
          "Ipsum",
          "Foo",
          "NotThere"
        ]
      },
      "source": {
        $in: [
          "A",
          "B"
        ]
      }
    }
  },
  {
    $group: {
      _id: "$name",
      source: {
        $min: "$source"
      }
    }
  },
  {
    $project: {
      _id: 0,
      name: "$_id",
      source: 1
    }
  }
])
</code>```

MongoPlayground

Body:
Apologies for the confusing title, I am not sure how to summarize this.

Suppose I have the following list of documents in a collection:

{ "name": "Lorem", "source": "A" }
{ "name": "Lorem", "source": "B" }
{ "name": "Ipsum", "source": "A" }
{ "name": "Ipsum", "source": "B" }
{ "name": "Ipsum", "source": "C" }
{ "name": "Foo",   "source": "B" }

as well an ordered list of accepted sources, where lower indexes signify higher priority

sources = ["A", "B"]

My query should:

Take a list of available sources and a list of wanted names

Return a maximum of one document per name.

In case of multiple matches, the document with the most prioritized source should be chosen.

Example:

wanted_names = ['Lorem', 'Ipsum', 'Foo', 'NotThere']

Result:

{ "name": "Lorem", "source": "A" }
{ "name": "Ipsum", "source": "A" }
{ "name": "Foo",   "source": "B" }

The results don't necessarily have to be ordered.

Is it possible to do this with a Mongo query alone? If so could someone point me towards a resource detailing how to accomplish it?

My current solution doesn't support a list of names, and instead relies on a Python script to execute multiple queries:

db.collection.aggregate([
    {$match: {
        "name": "Lorem",
        "source": {
            $in: sources
    }}},
    {$addFields: {
        "order": {
            $indexOfArray: [sources, "$source"]
    }}},
    {$sort: {
        "order": 1
    }},
    {$limit: 1}
]);

Note: _id fields are omitted in this question for the sake of brevity

Body:
How about this: With $group we have $min operator which takes lower source

Note: If you prioritize as ['B', 'A'], use $max then

db.collection.aggregate([
  {
    $match: {
      "name": {
        $in: [
          "Lorem",
          "Ipsum",
          "Foo",
          "NotThere"
        ]
      },
      "source": {
        $in: [
          "A",
          "B"
        ]
      }
    }
  },
  {
    $group: {
      _id: "$name",
      source: {
        $min: "$source"
      }
    }
  },
  {
    $project: {
      _id: 0,
      name: "$_id",
      source: 1
    }
  }
])

MongoPlayground


问:
How can I execute a python script directly (without prefixing by the python command) from bash?
I am just starting to use terminal for my programming needs. In a lot of Django tutorials I see people say, for example, I should type this in terminal:

```<code>manage.py runserver
</code>```

However when I do this it says:

```<code>bash: manage.py: command not found
</code>```

I get it to work when I do: python manage.py runserver, however I would like to understand why this works and the other method doesn't. I guess these are some very basic things but I thought I'd ask here.

答:
bash(1) will search your PATH environment variable to find programs to execute. PATH does not normally contain your "current working directory" (.) because that opens people up to trivial security problems:

```<code>cd /home/unsavory_character/
ls
</code>```

If unsavory_character places an executable in /home/unsavory_character/ls that adds his or her ssh(1) key to your ~/.ssh/authorized_keys file, you'd be in for a surprise -- he or she could log in as you without a password.

So systems these days don't add the current working directory to the PATH, because it is too unsafe.

The workaround:

```<code>./manage.py runserver
</code>```

Of course, that assumes your current working directory is whichever directory contains the manage.py script. That might be a safe assumption. If you'd like to be able to execute it from anywhere in the filesystem, you can add the directory to your PATH by editing your ~/.profile or ~/.bash_profile or ~/.bashrc file. (If one of them already exists, pick that one. I seem to recall others with PATH problems on OS X found one or the the other file worked well, and the other one never got executed.)

(In my case, I have a bunch of self-written utilities in ~/bin/, but yours might be elsewhere. Change the paths as appropriate.)

```<code>if [ -d "$HOME/bin" ] ; then
    PATH="$HOME/bin:$PATH"
fi
</code>```

Body:
I am just starting to use terminal for my programming needs. In a lot of Django tutorials I see people say, for example, I should type this in terminal:

manage.py runserver

However when I do this it says:

bash: manage.py: command not found

I get it to work when I do: python manage.py runserver, however I would like to understand why this works and the other method doesn't. I guess these are some very basic things but I thought I'd ask here.

Body:
bash(1) will search your PATH environment variable to find programs to execute. PATH does not normally contain your "current working directory" (.) because that opens people up to trivial security problems:

cd /home/unsavory_character/
ls

If unsavory_character places an executable in /home/unsavory_character/ls that adds his or her ssh(1) key to your ~/.ssh/authorized_keys file, you'd be in for a surprise -- he or she could log in as you without a password.

So systems these days don't add the current working directory to the PATH, because it is too unsafe.

The workaround:

./manage.py runserver

Of course, that assumes your current working directory is whichever directory contains the manage.py script. That might be a safe assumption. If you'd like to be able to execute it from anywhere in the filesystem, you can add the directory to your PATH by editing your ~/.profile or ~/.bash_profile or ~/.bashrc file. (If one of them already exists, pick that one. I seem to recall others with PATH problems on OS X found one or the the other file worked well, and the other one never got executed.)

(In my case, I have a bunch of self-written utilities in ~/bin/, but yours might be elsewhere. Change the paths as appropriate.)

if [ -d "$HOME/bin" ] ; then
    PATH="$HOME/bin:$PATH"
fi


问:
Angular setTimeout() with external lambda with parameter
I want to solve two problems simultaneously: 1) use setTimeout( #action#, timeMillis) with #action# as lambda 2) supply lambda with a parameter.

A popular approach with setTimeout( ()=>{ #callback# }, timeMillis) works perfectly when I extract ()=>{ #callback# } to lambda (and this case lambda has no parameters).
 But if I try to pass a lambda with parameter to setTimeout - this function stops working properly - callback fires immediately.

Here  is my code:

```<code>let lambda = (text: string) : TimerHandler => {
    alert(text)
    return ""
}

 .  .  .  .

lambda('text1')                     // value passes to lambda (show 'text1')         - OK  |  no delay - X
setTimeout(lambda, 3000);           // value don't pass to lambda (show 'undefined') - X   |  delay    - OK
setTimeout(lambda('text3'), 3000);  // value passes to lambda (show 'text1')         - OK  |  no delay - X
</code>```

Note: Accordingly to setTimeout docs, first #action# parameter is of type TimerHandler, and this type is extension of string. Thats why I have to return "empty_string" inside lambda's body.

Maybe this behaviour occurs because of an empty string in return statement? But I don't know what to set there

答:
You can use setTimeout function properly this way:

```<code>const lambda = (text: string) : TimerHandler => {
  console.info(text);
  return '';
}

setTimeout(lambda, 3000, "hola");
</code>```

Output after 3 secs

```<code>"hola"
</code>```

setTimeout receive args after the third prop.

The syntax is:

```<code>let timerId = setTimeout(func|code, [delay], [arg1], [arg2], ...)
</code>```

Body:
I want to solve two problems simultaneously: 1) use setTimeout( #action#, timeMillis) with #action# as lambda 2) supply lambda with a parameter.

A popular approach with setTimeout( ()=>{ #callback# }, timeMillis) works perfectly when I extract ()=>{ #callback# } to lambda (and this case lambda has no parameters).
 But if I try to pass a lambda with parameter to setTimeout - this function stops working properly - callback fires immediately.

Here  is my code:

let lambda = (text: string) : TimerHandler => {
    alert(text)
    return ""
}

 .  .  .  .

lambda('text1')                     // value passes to lambda (show 'text1')         - OK  |  no delay - X
setTimeout(lambda, 3000);           // value don't pass to lambda (show 'undefined') - X   |  delay    - OK
setTimeout(lambda('text3'), 3000);  // value passes to lambda (show 'text1')         - OK  |  no delay - X

Note: Accordingly to setTimeout docs, first #action# parameter is of type TimerHandler, and this type is extension of string. Thats why I have to return "empty_string" inside lambda's body.

Maybe this behaviour occurs because of an empty string in return statement? But I don't know what to set there

Body:
You can use setTimeout function properly this way:

const lambda = (text: string) : TimerHandler => {
  console.info(text);
  return '';
}

setTimeout(lambda, 3000, "hola");

Output after 3 secs

"hola"

setTimeout receive args after the third prop.

The syntax is:

let timerId = setTimeout(func|code, [delay], [arg1], [arg2], ...)