问:
Automatic Label Placement for GIS maps in R
I'm making GIS maps in R using the sf package (and related packages) to read in shapefiles, and ggplot2 (and friends) for plotting. This works fine, but I can find no way to (automatically/programmatically) create label placements for features such as rivers and roads. These features are typically linestrings, with irregular shapes. See image attached for example from wikimedia.

The ggrepel package works well for labeling points in an automated way, but this doesn't make much sense for other geographic features that aren't discrete Lat/Long points.

I could imagine doing this by placing individual text labels on each feature individually, but I'm looking for something more automated, if possible. I realize such automation isn't a trivial problem, but it's been solved before (ArcGIS apparently has a way of doing this with an extension called maplex, but I don't have access to the software, and I'd like to stay in R if possible).

Does anyone know of a way of doing this?

MWE here:

```<code>#MWE Linestring labeling

library(tidyverse)
library(sf)
library(ggrepel)
set.seed(120)

#pick a county from the built-in North Carolina dataset
BuncombeCounty <- st_read(system.file("shapes/", package="maptools"), "sids") %>%
  filter(NAME == "Buncombe")

#pick 4 random points in that county
pts_sf <- data.frame(
  x = seq(-82.3, -82.7, by=-0.1) %>%
    sample(4),
  y = seq(35.5, 35.7, by=0.05) %>%
    sample(4),
  placenames = c("A", "B", "C", "D")
) %>%
  st_as_sf(coords = c("x","y"))

#link those points into a linestring
linestring_sf <- pts_sf %>%
  st_coordinates() %>%
  st_linestring()
  st_cast("LINESTRING")

#plot them with labels, using geom_text_repel() from the `ggrepel` package
ggplot() +
  geom_sf(data = BuncombeCounty) +
  geom_sf(data = linestring_sf) +
  geom_label_repel(data = pts_sf,
                  stat = "sf_coordinates",
                  aes(geometry = geometry,
                      label = placenames),
                  nudge_y = 0.05,
                  label.r = 0, #don't round corners of label boxes
                  min.segment.length = 0,
                  segment.size = 0.4,
                  segment.color = "dodgerblue")
</code>```

答:
I think I have something that might work for you. I've taken the liberty of changing your example to something a bit more realistic: a couple of random "rivers" made with smoothed random walks, each 100 points long:

```<code>library(tidyverse)
library(sf)
library(ggrepel)

BuncombeCounty <- st_read(system.file("shapes/", package = "maptools"), "sids") %>%
                  filter(NAME == "Buncombe")
set.seed(120)

x1 <- seq(-82.795, -82.285, length.out = 100)
y1 <- cumsum(runif(100, -.01, .01))
y1 <- predict(loess(y1 ~ x1, span = 0.1)) + 35.6

x2 <- x1 + 0.02
y2 <- cumsum(runif(100, -.01, .01))
y2 <- predict(loess(y2 ~ x2, span = 0.1)) + 35.57

river_1 <- data.frame(x = x1, y = y1)     %>%
           st_as_sf(coords = c("x", "y")) %>%
           st_coordinates()               %>%
           st_linestring()                %>%
           st_cast("LINESTRING")

river_2 <- data.frame(x = x2, y = y2)     %>%
           st_as_sf(coords = c("x", "y")) %>%
           st_coordinates()               %>%
           st_linestring()                %>%
           st_cast("LINESTRING")
</code>```

We can plot them as per your example:

riverplot  <- ggplot() +
              geom_sf(data = BuncombeCounty) +
              geom_sf(data = river_1, colour = "blue", size = 2) +
              geom_sf(data = river_2, colour = "blue", size = 2)

riverplot
```

<p><img src="https://i.stack.imgur.com/nnmMO.png" alt="enter image description here"></p>

<p>My solution is basically to extract points from the linestrings and label them. Like the picture at the top of your question, you might want multiple copies of each label along the length of the linestring, so if you want <em>n</em> labels you just extract <em>n</em> equally-spaced points. </p>

<p>Of course, you want to be able to label both rivers at once without the labels clashing, so you'll need to be able to pass multiple geographical features as a named list. </p>

<p>Here is a function that does all that:</p>

<pre class="lang-r prettyprint-override"><code>linestring_labels <- function(linestrings, n)
{
  do.call(rbind, mapply(function(linestring, label)
  {
  n_points <- length(linestring)/2
  distance <- round(n_points / (n + 1))
  data.frame(x = linestring[1:n * distance],
             y = linestring[1:n * distance + n_points],
             label = rep(label, n))
  }, linestrings, names(linestrings), SIMPLIFY = FALSE)) %>%
  st_as_sf(coords = c("x","y"))
}
</code>```

So if we put the objects we want to label in a named list like this:

```<code>river_list <- list("River 1" = river_1, "River 2" = river_2)
</code>```

Then we can do this:

```<code>riverplot +
   geom_label_repel(data = linestring_labels(river_list, 3),
                    stat = "sf_coordinates",
                    aes(geometry = geometry, label = label),
                    nudge_y = 0.05,
                    label.r = 0, #don't round corners of label boxes
                    min.segment.length = 0,
                    segment.size = 0.4,
                    segment.color = "dodgerblue")
</code>```

Body:
I'm making GIS maps in R using the sf package (and related packages) to read in shapefiles, and ggplot2 (and friends) for plotting. This works fine, but I can find no way to (automatically/programmatically) create label placements for features such as rivers and roads. These features are typically linestrings, with irregular shapes. See image attached for example from wikimedia.

The ggrepel package works well for labeling points in an automated way, but this doesn't make much sense for other geographic features that aren't discrete Lat/Long points.

I could imagine doing this by placing individual text labels on each feature individually, but I'm looking for something more automated, if possible. I realize such automation isn't a trivial problem, but it's been solved before (ArcGIS apparently has a way of doing this with an extension called maplex, but I don't have access to the software, and I'd like to stay in R if possible).

Does anyone know of a way of doing this?

MWE here:

#MWE Linestring labeling

library(tidyverse)
library(sf)
library(ggrepel)
set.seed(120)

#pick a county from the built-in North Carolina dataset
BuncombeCounty <- st_read(system.file("shapes/", package="maptools"), "sids") %>%
  filter(NAME == "Buncombe")

#pick 4 random points in that county
pts_sf <- data.frame(
  x = seq(-82.3, -82.7, by=-0.1) %>%
    sample(4),
  y = seq(35.5, 35.7, by=0.05) %>%
    sample(4),
  placenames = c("A", "B", "C", "D")
) %>%
  st_as_sf(coords = c("x","y"))

#link those points into a linestring
linestring_sf <- pts_sf %>%
  st_coordinates() %>%
  st_linestring()
  st_cast("LINESTRING")

#plot them with labels, using geom_text_repel() from the `ggrepel` package
ggplot() +
  geom_sf(data = BuncombeCounty) +
  geom_sf(data = linestring_sf) +
  geom_label_repel(data = pts_sf,
                  stat = "sf_coordinates",
                  aes(geometry = geometry,
                      label = placenames),
                  nudge_y = 0.05,
                  label.r = 0, #don't round corners of label boxes
                  min.segment.length = 0,
                  segment.size = 0.4,
                  segment.color = "dodgerblue")

Body:
I think I have something that might work for you. I've taken the liberty of changing your example to something a bit more realistic: a couple of random "rivers" made with smoothed random walks, each 100 points long:

library(tidyverse)
library(sf)
library(ggrepel)

BuncombeCounty <- st_read(system.file("shapes/", package = "maptools"), "sids") %>%
                  filter(NAME == "Buncombe")
set.seed(120)

x1 <- seq(-82.795, -82.285, length.out = 100)
y1 <- cumsum(runif(100, -.01, .01))
y1 <- predict(loess(y1 ~ x1, span = 0.1)) + 35.6

x2 <- x1 + 0.02
y2 <- cumsum(runif(100, -.01, .01))
y2 <- predict(loess(y2 ~ x2, span = 0.1)) + 35.57

river_1 <- data.frame(x = x1, y = y1)     %>%
           st_as_sf(coords = c("x", "y")) %>%
           st_coordinates()               %>%
           st_linestring()                %>%
           st_cast("LINESTRING")

river_2 <- data.frame(x = x2, y = y2)     %>%
           st_as_sf(coords = c("x", "y")) %>%
           st_coordinates()               %>%
           st_linestring()                %>%
           st_cast("LINESTRING")

We can plot them as per your example:

riverplot  <- ggplot() +
              geom_sf(data = BuncombeCounty) +
              geom_sf(data = river_1, colour = "blue", size = 2) +
              geom_sf(data = river_2, colour = "blue", size = 2)

riverplot

My solution is basically to extract points from the linestrings and label them. Like the picture at the top of your question, you might want multiple copies of each label along the length of the linestring, so if you want n labels you just extract n equally-spaced points.

Of course, you want to be able to label both rivers at once without the labels clashing, so you'll need to be able to pass multiple geographical features as a named list.

Here is a function that does all that:

linestring_labels <- function(linestrings, n)
{
  do.call(rbind, mapply(function(linestring, label)
  {
  n_points <- length(linestring)/2
  distance <- round(n_points / (n + 1))
  data.frame(x = linestring[1:n * distance],
             y = linestring[1:n * distance + n_points],
             label = rep(label, n))
  }, linestrings, names(linestrings), SIMPLIFY = FALSE)) %>%
  st_as_sf(coords = c("x","y"))
}

So if we put the objects we want to label in a named list like this:

river_list <- list("River 1" = river_1, "River 2" = river_2)

Then we can do this:

riverplot +
   geom_label_repel(data = linestring_labels(river_list, 3),
                    stat = "sf_coordinates",
                    aes(geometry = geometry, label = label),
                    nudge_y = 0.05,
                    label.r = 0, #don't round corners of label boxes
                    min.segment.length = 0,
                    segment.size = 0.4,
                    segment.color = "dodgerblue")


来源: stackexchange

问:
Trying to lookup a value from a pandas dataframe within a range of two rows in the index dataframe
I have two dataframes - "grower_moo" and "pricing" in a Python notebook to analyze harvested crops and price payments to the growers.

pricing is the index dataframe, and grower_moo has various unique load tickets with information about each load.

I need to pull the price per ton from the pricing index to a new column in the load data if the Fat of that load is not greater than the next Wet Fat.

Below is a .head() sample of each dataframe and the code I tried. I received a ValueError: Can only compare identically-labeled Series objects error.

```<code>
pricing
    Price_Per_Ton   Wet_Fat
0       306            10
1       339            11
2       382            12
3       430            13
4       481            14
5       532            15
6       580            16
7       625            17
8       665            18
9       700            19
10      728            20
11      750            21
12      766            22
13      778            23
14      788            24
15      797            25

grower_moo
    Load Ticket     Net Fruit Weight  Net MOO  Percent_MOO  Fat
0   L2019000011817     56660           833     1.448872    21.92
1   L2019000011816     53680           1409    2.557679    21.12
2   L2019000011815     53560           1001    1.834644    21.36
3   L2019000011161     62320           2737    4.207080    21.41
4   L2019000011160     57940           1129    1.911324    20.06
</code>```

grower_moo['price_per_ton'] = max(pricing[pricing['Wet_Fat'] < grower_moo['Fat']]['Price_Per_Ton'])

Example output - grower_moo['Fat'] of 13.60 is less than 14 Fat, therefore gets a price per ton of $430

```<code>grower_moo_with_price
    Load Ticket     Net Fruit Weight  Net MOO  Percent_MOO  Fat    price_per_ton
0   L2019000011817     56660           833     1.448872    21.92      750
1   L2019000011816     53680           1409    2.557679    21.12      750
2   L2019000011815     53560           1001    1.834644    21.36      750
3   L2019000011161     62320           2737    4.207080    21.41      750
4   L2019000011160     57940           1129    1.911324    20.06      728
</code>```

答:
This looks like a job for an "as of" merge, pd.merge_asof (documentation):

This is similar to a left-join except that we match on nearest key
  rather than equal keys. Both DataFrames must be sorted by the key.

For each row in the left DataFrame:

A "backward" search [the default]
  selects the last row in the right DataFrame whose ‘on’ key is less
  than or equal to the left’s key.

In the following code, I use your example inputs, but with column names using underscores _ instead of spaces .

```<code># Required by merge_asof: sort keys in left DataFrame
grower_moo = grower_moo.sort_values('Fat')

# Required by merge_asof: key column data types must match
pricing['Wet_Fat'] = pricing['Wet_Fat'].astype('float')

# Perform the asof merge
res = pd.merge_asof(grower_moo, pricing, left_on='Fat', right_on='Wet_Fat')

# Print result
res
      Load_Ticket  Net_Fruit_Weight  Net_MOO  Percent_MOO    Fat  Price_Per_Ton  Wet_Fat
0  L2019000011160             57940     1129     1.911324  20.06            728     20.0
1  L2019000011816             53680     1409     2.557679  21.12            750     21.0
2  L2019000011815             53560     1001     1.834644  21.36            750     21.0
3  L2019000011161             62320     2737     4.207080  21.41            750     21.0
4  L2019000011817             56660      833     1.448872  21.92            750     21.0

# Optional: drop the key column from the right DataFrame
res.drop(columns='Wet_Fat')
      Load_Ticket  Net_Fruit_Weight  Net_MOO  Percent_MOO    Fat  Price_Per_Ton
0  L2019000011160             57940     1129     1.911324  20.06            728
1  L2019000011816             53680     1409     2.557679  21.12            750
2  L2019000011815             53560     1001     1.834644  21.36            750
3  L2019000011161             62320     2737     4.207080  21.41            750
4  L2019000011817             56660      833     1.448872  21.92            750
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have two dataframes - "grower_moo" and "pricing" in a Python notebook to analyze harvested crops and price payments to the growers.

pricing is the index dataframe, and grower_moo has various unique load tickets with information about each load.

I need to pull the price per ton from the pricing index to a new column in the load data if the Fat of that load is not greater than the next Wet Fat.

Below is a .head() sample of each dataframe and the code I tried. I received a ValueError: Can only compare identically-labeled Series objects error.

pricing
    Price_Per_Ton   Wet_Fat
0       306            10
1       339            11
2       382            12
3       430            13
4       481            14
5       532            15
6       580            16
7       625            17
8       665            18
9       700            19
10      728            20
11      750            21
12      766            22
13      778            23
14      788            24
15      797            25

grower_moo
    Load Ticket     Net Fruit Weight  Net MOO  Percent_MOO  Fat
0   L2019000011817     56660           833     1.448872    21.92
1   L2019000011816     53680           1409    2.557679    21.12
2   L2019000011815     53560           1001    1.834644    21.36
3   L2019000011161     62320           2737    4.207080    21.41
4   L2019000011160     57940           1129    1.911324    20.06

grower_moo['price_per_ton'] = max(pricing[pricing['Wet_Fat'] < grower_moo['Fat']]['Price_Per_Ton'])

Example output - grower_moo['Fat'] of 13.60 is less than 14 Fat, therefore gets a price per ton of $430

grower_moo_with_price
    Load Ticket     Net Fruit Weight  Net MOO  Percent_MOO  Fat    price_per_ton
0   L2019000011817     56660           833     1.448872    21.92      750
1   L2019000011816     53680           1409    2.557679    21.12      750
2   L2019000011815     53560           1001    1.834644    21.36      750
3   L2019000011161     62320           2737    4.207080    21.41      750
4   L2019000011160     57940           1129    1.911324    20.06      728

Body:
This looks like a job for an "as of" merge, pd.merge_asof (documentation):

This is similar to a left-join except that we match on nearest key
  rather than equal keys. Both DataFrames must be sorted by the key.

For each row in the left DataFrame:

A "backward" search [the default]
  selects the last row in the right DataFrame whose ‘on’ key is less
  than or equal to the left’s key.

In the following code, I use your example inputs, but with column names using underscores _ instead of spaces .

# Required by merge_asof: sort keys in left DataFrame
grower_moo = grower_moo.sort_values('Fat')

# Required by merge_asof: key column data types must match
pricing['Wet_Fat'] = pricing['Wet_Fat'].astype('float')

# Perform the asof merge
res = pd.merge_asof(grower_moo, pricing, left_on='Fat', right_on='Wet_Fat')

# Print result
res
      Load_Ticket  Net_Fruit_Weight  Net_MOO  Percent_MOO    Fat  Price_Per_Ton  Wet_Fat
0  L2019000011160             57940     1129     1.911324  20.06            728     20.0
1  L2019000011816             53680     1409     2.557679  21.12            750     21.0
2  L2019000011815             53560     1001     1.834644  21.36            750     21.0
3  L2019000011161             62320     2737     4.207080  21.41            750     21.0
4  L2019000011817             56660      833     1.448872  21.92            750     21.0

# Optional: drop the key column from the right DataFrame
res.drop(columns='Wet_Fat')
      Load_Ticket  Net_Fruit_Weight  Net_MOO  Percent_MOO    Fat  Price_Per_Ton
0  L2019000011160             57940     1129     1.911324  20.06            728
1  L2019000011816             53680     1409     2.557679  21.12            750
2  L2019000011815             53560     1001     1.834644  21.36            750
3  L2019000011161             62320     2737     4.207080  21.41            750
4  L2019000011817             56660      833     1.448872  21.92            750


问:
Can i copy my Heroku deployment and its commit history to a new github repository?
I'm wondering if it's possible to copy my Heroku deployment, along with its commit history to a new repository in github. I want to upload the code to my account and include all its history rather than having just one commit. Is this possible?</p>

答:
I'm wondering if it's possible to copy my Heroku deployment, along with its commit history to a new repository in github. I want to [preserve] all its history ..

Yes.

Use something like git remote -v to find the URL of your repository at heroku. It might look like this:

```<code>origin  git@github.com:myorg/myproject.git (push)
prd     https://git.heroku.com/myapp.git (fetch)
</code>```

If you can't use git remote you can guess the URL using the name of your app.

Then git clone https://git.heroku.com/myapp.git.

Now you can push your local copy to git with the usual github routine.

Body:
I'm wondering if it's possible to copy my Heroku deployment, along with its commit history to a new repository in github. I want to [preserve] all its history ..

Yes.

Use something like git remote -v to find the URL of your repository at heroku. It might look like this:

origin  git@github.com:myorg/myproject.git (push)
prd     https://git.heroku.com/myapp.git (fetch)

If you can't use git remote you can guess the URL using the name of your app.

Then git clone https://git.heroku.com/myapp.git.

Now you can push your local copy to git with the usual github routine.


问:
Set headers twice and/or not correctly handling a callback - resulting in Error [ERR_HTTP_HEADERS_SENT]
I'm getting the expected image with this code but it does not display in my pug template, instead it displays in the browser devtools console (i hope that makes sense), and it appears that I'm trying to set headers twice. My code produces [ERR_HTTP_HEADERS_SENT] as shown below.

I've read through numerous StackOverflow questions on this, including this thorough breakdown of the issue:

Error: Can't set headers after they are sent to the client

and I think what is actually happening is that I'm not correctly handling a callback, but I'm not sure.

I've really struggled with this and could use a little help pointing out where I'm going wrong.

route.js:

```<code>router.get('/issue/filedisplay/:id', issue_controller.file_display);
</code>```

controller.js:

```<code>// controller.js
    exports.file_display = function(req, res) {
      gfs.files.findOne(
        { _id: mongoose.Types.ObjectId(req.params.id) },
        (err, file) => {
          //res.contentType(file.contentType);
          // Check if file
          if (!file || file.length === 0) {
            return res.status(404).json({
              err: 'No file exists',
            });
          }
          const readstream = gfs.createReadStream(file._id);
          readstream.pipe(res);
          readstream.on('close', () => {
            res.render('filedisplay', {
              title: 'Display Image',
              file: file._id,
            });
          });
          //return res.json(file);
          //return res;
        }
      );
    };
</code>```

Pug Template:

```<code>//-filedisplay.pug
extends layout

block content
  h1= title
    p Display Image
    div
      img.image(src="/list/issue/filedisplay/" + file alt="")
</code>```

The error:

```<code>Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:482:11)
    at ServerResponse.header (/home/don/dev/sandbox/fileupload-ex/file-upload-gridfs/node_modules/express/lib/response.js:771:10)
    at ServerResponse.send (/home/don/dev/sandbox/fileupload-ex/file-upload-gridfs/node_modules/express/lib/response.js:170:12)
    at done (/home/don/dev/sandbox/fileupload-ex/file-upload-gridfs/node_modules/express/lib/response.js:1008:10)
    at Object.exports.renderFile (/home/don/dev/sandbox/fileupload-ex/file-upload-gridfs/node_modules/pug/lib/index.js:421:12)
    at View.exports.__express [as engine] (/home/don/dev/sandbox/fileupload-ex/file-upload-gridfs/node_modules/pug/lib/index.js:464:11)
    at View.render (/home/don/dev/sandbox/fileupload-ex/file-upload-gridfs/node_modules/express/lib/view.js:135:8)
    at tryRender (/home/don/dev/sandbox/fileupload-ex/file-upload-gridfs/node_modules/express/lib/application.js:640:10)
    at Function.render (/home/don/dev/sandbox/fileupload-ex/file-upload-gridfs/node_modules/express/lib/application.js:592:3)
    at ServerResponse.render (/home/don/dev/sandbox/fileupload-ex/file-upload-gridfs/node_modules/express/lib/response.js:1012:7)
    at /home/don/dev/sandbox/fileupload-ex/file-upload-gridfs/app.js:82:7
    at Layer.handle_error (/home/don/dev/sandbox/fileupload-ex/file-upload-gridfs/node_modules/express/lib/router/layer.js:71:5)
    at trim_prefix (/home/don/dev/sandbox/fileupload-ex/file-upload-gridfs/node_modules/express/lib/router/index.js:315:13)
    at /home/don/dev/sandbox/fileupload-ex/file-upload-gridfs/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/home/don/dev/sandbox/fileupload-ex/file-upload-gridfs/node_modules/express/lib/router/index.js:335:12)
    at next (/home/don/dev/sandbox/fileupload-ex/file-upload-gridfs/node_modules/express/lib/router/index.js:275:10)
</code>```

答:
This issue is closed. It is not resolved and the code is still broken. Of the above controller code, all I really needed was everything down to:

```<code>readstream.pipe(res);
</code>```

That works because I added target="_blank" to the referring link causing the rendered image to open in a new browser window, which was what I was actually going for. So rendering the image in a new pug template was an unnecessary step, and it is that rendering code inside the "on" method that was causing the problem.

Body:
I'm getting the expected image with this code but it does not display in my pug template, instead it displays in the browser devtools console (i hope that makes sense), and it appears that I'm trying to set headers twice. My code produces [ERR_HTTP_HEADERS_SENT] as shown below.

I've read through numerous StackOverflow questions on this, including this thorough breakdown of the issue:

Error: Can't set headers after they are sent to the client

and I think what is actually happening is that I'm not correctly handling a callback, but I'm not sure.

I've really struggled with this and could use a little help pointing out where I'm going wrong.

route.js:

router.get('/issue/filedisplay/:id', issue_controller.file_display);

controller.js:

// controller.js
    exports.file_display = function(req, res) {
      gfs.files.findOne(
        { _id: mongoose.Types.ObjectId(req.params.id) },
        (err, file) => {
          //res.contentType(file.contentType);
          // Check if file
          if (!file || file.length === 0) {
            return res.status(404).json({
              err: 'No file exists',
            });
          }
          const readstream = gfs.createReadStream(file._id);
          readstream.pipe(res);
          readstream.on('close', () => {
            res.render('filedisplay', {
              title: 'Display Image',
              file: file._id,
            });
          });
          //return res.json(file);
          //return res;
        }
      );
    };

Pug Template:

//-filedisplay.pug
extends layout

block content
  h1= title
    p Display Image
    div
      img.image(src="/list/issue/filedisplay/" + file alt="")

The error:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:482:11)
    at ServerResponse.header (/home/don/dev/sandbox/fileupload-ex/file-upload-gridfs/node_modules/express/lib/response.js:771:10)
    at ServerResponse.send (/home/don/dev/sandbox/fileupload-ex/file-upload-gridfs/node_modules/express/lib/response.js:170:12)
    at done (/home/don/dev/sandbox/fileupload-ex/file-upload-gridfs/node_modules/express/lib/response.js:1008:10)
    at Object.exports.renderFile (/home/don/dev/sandbox/fileupload-ex/file-upload-gridfs/node_modules/pug/lib/index.js:421:12)
    at View.exports.__express [as engine] (/home/don/dev/sandbox/fileupload-ex/file-upload-gridfs/node_modules/pug/lib/index.js:464:11)
    at View.render (/home/don/dev/sandbox/fileupload-ex/file-upload-gridfs/node_modules/express/lib/view.js:135:8)
    at tryRender (/home/don/dev/sandbox/fileupload-ex/file-upload-gridfs/node_modules/express/lib/application.js:640:10)
    at Function.render (/home/don/dev/sandbox/fileupload-ex/file-upload-gridfs/node_modules/express/lib/application.js:592:3)
    at ServerResponse.render (/home/don/dev/sandbox/fileupload-ex/file-upload-gridfs/node_modules/express/lib/response.js:1012:7)
    at /home/don/dev/sandbox/fileupload-ex/file-upload-gridfs/app.js:82:7
    at Layer.handle_error (/home/don/dev/sandbox/fileupload-ex/file-upload-gridfs/node_modules/express/lib/router/layer.js:71:5)
    at trim_prefix (/home/don/dev/sandbox/fileupload-ex/file-upload-gridfs/node_modules/express/lib/router/index.js:315:13)
    at /home/don/dev/sandbox/fileupload-ex/file-upload-gridfs/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/home/don/dev/sandbox/fileupload-ex/file-upload-gridfs/node_modules/express/lib/router/index.js:335:12)
    at next (/home/don/dev/sandbox/fileupload-ex/file-upload-gridfs/node_modules/express/lib/router/index.js:275:10)

Body:
This issue is closed. It is not resolved and the code is still broken. Of the above controller code, all I really needed was everything down to:

readstream.pipe(res);

That works because I added target="_blank" to the referring link causing the rendered image to open in a new browser window, which was what I was actually going for. So rendering the image in a new pug template was an unnecessary step, and it is that rendering code inside the "on" method that was causing the problem.


问:
correct way to use the constructor with props?
When I print to console, it says that the auth isn't loaded and thus there is no auth.uid. Why?</p>

```<code>    constructor(props) {
        super(props);
        this.state = {
            auth : props,
            links : props.auth.uid ? <SignedInLinks /> : <SignedOutLinks />
        };
    }

...

const mapStateToProps = (state) => {
    return {
        auth: state.firebase.auth
    }
}
export default connect(mapStateToProps)(Navbar);

</code>```

答:
In your this.state, don't you mean?

auth : props.auth
```

<p>Maybe simpler to define state outside of constructor:</p>

<pre class="lang-js prettyprint-override"><code>// Inside your component but not inside the constructor:

state = {
  auth : this.props.auth,
  links : this.props.auth.uid ? <SignedInLinks /> : <SignedOutLinks />
};

</code>```

But even so, you're simply inserting your redux state props into your component state.  Why?  Why not just read directly from redux state, like so?

class MyComponent extends React.Component{

  render(){
    return this.props.auth.uid ? <SignedInLinks /> : <SignedOutLinks />
  }

}

const mapStateToProps = (state) => {
    return {
        auth: state.firebase.auth
    }
}
export default connect(mapStateToProps)(Navbar);
```

Body:
When I print to console, it says that the auth isn't loaded and thus there is no auth.uid. Why?

    constructor(props) {
        super(props);
        this.state = {
            auth : props,
            links : props.auth.uid ? <SignedInLinks /> : <SignedOutLinks />
        };
    }

...

const mapStateToProps = (state) => {
    return {
        auth: state.firebase.auth
    }
}
export default connect(mapStateToProps)(Navbar);

Body:
In your this.state, don't you mean?

auth : props.auth

Maybe simpler to define state outside of constructor:

// Inside your component but not inside the constructor:

state = {
  auth : this.props.auth,
  links : this.props.auth.uid ? <SignedInLinks /> : <SignedOutLinks />
};

But even so, you're simply inserting your redux state props into your component state.  Why?  Why not just read directly from redux state, like so?

class MyComponent extends React.Component{

  render(){
    return this.props.auth.uid ? <SignedInLinks /> : <SignedOutLinks />
  }

}

const mapStateToProps = (state) => {
    return {
        auth: state.firebase.auth
    }
}
export default connect(mapStateToProps)(Navbar);


问:
how to use unix command in src in ansible
File is opened if I run the following command from shell:

ls -l /tmp/uname -n ---file1

I am trying to run it with fetch:

```<code>- name: COPY file from remote machine to local

  fetch:

    src: /tmp/`uname -n`---mem-swap.out

    dest: /tmp
</code>```

But it gives me the error:

file not found: /tmp/uname -n---mem-swap.out

Is it possible to execute it in   "src"

Thank you.

答:
It's possible to register the result and concatenate the src string. For example

```<code>   - commnad: "uname -n"
     register: result
   - fetch:
        src: "/tmp/{{ result.stdout }}---mem-swap.out"
        dest: "/tmp"
</code>```

Body:
File is opened if I run the following command from shell:

ls -l /tmp/uname -n ---file1

I am trying to run it with fetch:

- name: COPY file from remote machine to local

  fetch:

    src: /tmp/`uname -n`---mem-swap.out

    dest: /tmp

But it gives me the error:

file not found: /tmp/uname -n---mem-swap.out

Is it possible to execute it in   "src"

Thank you.

Body:
It's possible to register the result and concatenate the src string. For example

   - commnad: "uname -n"
     register: result
   - fetch:
        src: "/tmp/{{ result.stdout }}---mem-swap.out"
        dest: "/tmp"


问:
How to click and hold using the webdriverio
I am trying to figure out how to click and hold using webdriverio. In selenium it is like this:

```<code>WebElement elementToInteractWith = driver.findElement(By.id("myElement"));

Actions holdClick = new Actions(driver);

holdClick.clickAndHold(elementToInteractWith).perform();

//wait for however long you need to hold

holdClick.release().perform();
</code>```

However i am not sure how to do that in webdriver io but cannot find anything on the documentation

答:
You can test it with buttonDown on w3school page.

```<code>browser.url("https://www.w3schools.com/css/css3_buttons.asp");
browser.buttonDown("//button[text()='Default Button']");
browser.pause(5000);
browser.buttonUp("//button[text()='Default Button']");
</code>```

However, this is for webdriverio v4.  It says this is deprecated soon, but maybe V5 has the same api.

Body:
I am trying to figure out how to click and hold using webdriverio. In selenium it is like this:

WebElement elementToInteractWith = driver.findElement(By.id("myElement"));

Actions holdClick = new Actions(driver);

holdClick.clickAndHold(elementToInteractWith).perform();

//wait for however long you need to hold

holdClick.release().perform();

However i am not sure how to do that in webdriver io but cannot find anything on the documentation

Body:
You can test it with buttonDown on w3school page.

browser.url("https://www.w3schools.com/css/css3_buttons.asp");
browser.buttonDown("//button[text()='Default Button']");
browser.pause(5000);
browser.buttonUp("//button[text()='Default Button']");

However, this is for webdriverio v4.  It says this is deprecated soon, but maybe V5 has the same api.


问:
Order of promise array in Promise.allSettled and order in which database transactions are created?
In the following code,

```<code>Promise.allSettled( [ entry_save(), save_state(), get_HTML() ] ).then( ... );
</code>```

promises entry_save and save_state are both readwrite database transactions and get_HTML is readonly. The two readwrite transactions could be combined together but that complicates the undo/redo chain that is maintained and it ties the success and rollback of the two together which is undesired.

The entry_save transaction needs to write before the save_state transaction.  Before moving entry_save into the Promise.allSettled that is how it worked because the entry_save transaction was created prior to those of the others.  This MDN article explains how the order in which  requests are performed is based upon when the transactions are created independently of the order in which the requests are made.

My question is does the synchronous code of each promise process in the order in which it is placed in the array, such that placing entry_save first will always result in its transaction being created first and guaranteeing its database requests will be performed first?

Although it works and is quick enough, I'd prefer to not do this:

```<code>entry_save().then( () => { Promise.allSettled( [ save_state(), get_HTML() ] ) } ).then( ... );
</code>```

If it matters, that's not the exactly the way it is written, it's more consistent with:

entry_save().then( intermediate ); where intermediate invokes the Promise.allSettled.

Thank you.

To clarify a bit, below is the example given in the above cited MDN document.

```<code>var trans1 = db.transaction("foo", "readwrite");
var trans2 = db.transaction("foo", "readwrite");
var objectStore2 = trans2.objectStore("foo")
var objectStore1 = trans1.objectStore("foo")
objectStore2.put("2", "key");
objectStore1.put("1", "key");
</code>```

After the code is executed the object store should contain the value "2", since trans2 should run after trans1.

If entry_save creates trans1 and save_state create trans2, and all in the synchronous code of the functions, meaning not within an onsuccess or onerror handler of a database request or something similar, will the MDN example not hold?

Thus, where @jfriend00 writes,

The functions are called in the order they are placed in the array,
  but that only determines the order in which the asynchronous are
  started.

will this order the timing of the write requests by that of the creation of the transactions, since the transactions are created in the synchronous code before the asynchronous can commence?

I'd like to test it but I'm not sure how.  If two nearly identical promises are used in a Promise.allSettled, how can the write request of the first created transaction be delayed such that it takes place after the write request of the second created transaction, to test if it will be written first? A setTimeout should terminate the transaction. Perhaps a long-running synchronous loop placed before the request.

The code at the very end of this question may better illustrate more precisely what I have attempted to ask. It takes the MDN example in the article cited above and spreads it across two promises placed in a Promise.allSettled, both of which attempt to write to the same object store from within the onsuccess event of a get request.

The question was will the same principle in the article of the first transaction created writing before the second transaction created, regardless of the order the requests are made, still hold in this set up. Since the synchronous portions of the promises will process in the order the promises are placed in the array, the transaction in promise p_1 will be created before that of p_2.  However, the put request in the onsuccess event of the get request in p_1 is delayed by the loop building a large string. The question is will p_1 still write before p_2?

In experimenting with this, I cannot get p_2 to write before p_1. Thus, it appears that the MDN example applies even in this type of set up.  However, I cannot be sure of why because I don't understand how the JS code is really interpreted/processed.

For example, why can the req.onsuccess function be defined after the request is made? I asked that question sometime ago but still don't know enough to be sure that it doesn't affect the way I attempted to add in a delay here. I know that it won't work the other way around; but my point is I'm not sure how the browser handles that synchronous loop before the put request is made in p_1 to really know for sure that this example demonstrates that the MDN article ALWAYS holds in this set up.  However, I can observe that it takes longer for the requests to complete as the number of loop iterations is increased; and, in all cases I have observed, p_1 always writes before p_2. The only way p_2 writes before p_1 is if p_1 doesn't write at all because of the string taking up to much memory causing the transaction in p_1 to be aborted.

That being said, and returning to the fuller set up of my question concerning three promises in the array of the Promise.allSettled compared to requiring entry_save to complete before commencing a Promise.allSettled on the two remaining promises, in the full code of my project, for reasons I am not sure of, the latter is quicker than the former, that is, waiting for entry_save to complete is quicker than including it in the Promise.allSettled.

I was expecting it to be the other way around.  The only reason I can think of at this point is that, since entry_save and save_state are both writing to the same object store, perhaps whatever the browser does equivalent to locking the object store until the first transaction, which is that in entry_save, completes and removing the lock takes longer than requiring that entry_save complete before the Promise.allSettled commences and not involving a lock. I thought that everything would be ready "in advance" just waiting for the two put requests to take place in transaction order. They took place in order but more slowly or at least not as quick as using:

```<code>entry_save().then( () => { Promise.allSettled( [ save_state(), get_HTML() ] ) } ).then( ... );
</code>```

instead of:

```<code> Promise.allSettled( [ entry_save(), save_state(), get_HTML() ] ).then( ... );
</code>```

```<code>function p_all() { Promise.allSettled( [ p_1(), p_2() ] ); }

function p_1()
  {
    return new Promise( ( resolve, reject ) =>
      {
        let T = DB.transaction( [ 'os_1', 'os_2' ], 'readwrite' ),
            q = T.objectStore( 'os_1' ),
            u = T.objectStore( 'os_2' ),
            req, i, t ='', x = '';

     req = q.get( 1 );

     req.onsuccess = () =>
       {
         let i, t, r = req.result;
         for ( i = 1; i < 10000000; i++ ) t = t + 'This is a string';
         r.n = 'p1';
         u.put( r );
         console.log( r );
       };
    }); }

function p_2()
  {
    return new Promise( ( resolve, reject ) =>
      {
       let T = DB.transaction( [ 'os_1', 'os_2' ], 'readwrite' ),
           q = T.objectStore( 'os_1' ),
           u = T.objectStore( 'os_2' ),
           req;

        req = q.get( 1 );

        req.onsuccess = () =>
          {
            let r = req.result;
            r.n = 'p2';
            u.put( r );
            console.log( r );
          };
    }); }
</code>```

答:
When you do this:

```<code>Promise.allSettled( [ entry_save(), save_state(), get_HTML() ] ).then(...)
</code>```

It's equivalent to this:

```<code>const p1 = entry_save();
const p2 = save_state();
const p3 = get_HTML();

Promise.allSettled([p1, p2, p3]).then(...);
</code>```

So, the individual function calls you issue such as save_state() are STARTED in the order specified.  But, each of those calls are asynchronous so the internal order of what happens before something else really depends upon what they do inside as they can all be in flight at the same time and parts of their execution can be interleaved in an indeterminate order.

Imagine that entry_save() actually consists of multiple asynchronous pieces such as first reading some data from disk, then modifying the data, then writing it to the database.  It would call the first asynchronous operation to read some data from disk and then immediately return a promise.  Then, save_state() would get to start executing.  If save_state() just immediately issued a write to the database, then it very well may write to the database before entry_save() writes to the database.  In fact, the sequencing of the two database writes is indeterminate and racy.

If you need entry_save() to complete before save_state(), then the above is NOT the way to code it at all.  Your code is not guaranteeing that all of entry_save() is done before any of save_state() runs.

Instead, you SHOULD do what you seem to already know:

```<code>entry_save().then( () => { Promise.allSettled( [ save_state(), get_HTML() ] ) } ).then( ... );
</code>```

Only that guarantees that entry_save() will complete before save_state() gets to run.  And, this assumes that you're perfectly OK with save_state() and get_HTML() running concurrently and in an unpredictable order.

My question is does the synchronous code of each promise process in the order in which it is placed in the array, such that placing entry_save first will always result in its transaction being created first and guaranteeing its database requests will be performed first?

The functions are called in the order they are placed in the array, but that only determines the order in which the asynchronous are started.  After that, they are all in-flight at the same time and the internal timing between them depends upon how long their individual asynchronous operations take and what those asynchronous operations do.  If order matters, you can't just put them all in an indeterminate race.  That's call a "race condition".  Instead, you would need to structure your code to guarantee that the desired operation goes first before the ones that need to execute after it.

Body:
In the following code,

Promise.allSettled( [ entry_save(), save_state(), get_HTML() ] ).then( ... );

promises entry_save and save_state are both readwrite database transactions and get_HTML is readonly. The two readwrite transactions could be combined together but that complicates the undo/redo chain that is maintained and it ties the success and rollback of the two together which is undesired.

The entry_save transaction needs to write before the save_state transaction.  Before moving entry_save into the Promise.allSettled that is how it worked because the entry_save transaction was created prior to those of the others.  This MDN article explains how the order in which  requests are performed is based upon when the transactions are created independently of the order in which the requests are made.

My question is does the synchronous code of each promise process in the order in which it is placed in the array, such that placing entry_save first will always result in its transaction being created first and guaranteeing its database requests will be performed first?

Although it works and is quick enough, I'd prefer to not do this:

entry_save().then( () => { Promise.allSettled( [ save_state(), get_HTML() ] ) } ).then( ... );

If it matters, that's not the exactly the way it is written, it's more consistent with:

entry_save().then( intermediate ); where intermediate invokes the Promise.allSettled.

Thank you.

To clarify a bit, below is the example given in the above cited MDN document.

var trans1 = db.transaction("foo", "readwrite");
var trans2 = db.transaction("foo", "readwrite");
var objectStore2 = trans2.objectStore("foo")
var objectStore1 = trans1.objectStore("foo")
objectStore2.put("2", "key");
objectStore1.put("1", "key");

After the code is executed the object store should contain the value "2", since trans2 should run after trans1.

If entry_save creates trans1 and save_state create trans2, and all in the synchronous code of the functions, meaning not within an onsuccess or onerror handler of a database request or something similar, will the MDN example not hold?

Thus, where @jfriend00 writes,

The functions are called in the order they are placed in the array,
  but that only determines the order in which the asynchronous are
  started.

will this order the timing of the write requests by that of the creation of the transactions, since the transactions are created in the synchronous code before the asynchronous can commence?

I'd like to test it but I'm not sure how.  If two nearly identical promises are used in a Promise.allSettled, how can the write request of the first created transaction be delayed such that it takes place after the write request of the second created transaction, to test if it will be written first? A setTimeout should terminate the transaction. Perhaps a long-running synchronous loop placed before the request.

The code at the very end of this question may better illustrate more precisely what I have attempted to ask. It takes the MDN example in the article cited above and spreads it across two promises placed in a Promise.allSettled, both of which attempt to write to the same object store from within the onsuccess event of a get request.

The question was will the same principle in the article of the first transaction created writing before the second transaction created, regardless of the order the requests are made, still hold in this set up. Since the synchronous portions of the promises will process in the order the promises are placed in the array, the transaction in promise p_1 will be created before that of p_2.  However, the put request in the onsuccess event of the get request in p_1 is delayed by the loop building a large string. The question is will p_1 still write before p_2?

In experimenting with this, I cannot get p_2 to write before p_1. Thus, it appears that the MDN example applies even in this type of set up.  However, I cannot be sure of why because I don't understand how the JS code is really interpreted/processed.

For example, why can the req.onsuccess function be defined after the request is made? I asked that question sometime ago but still don't know enough to be sure that it doesn't affect the way I attempted to add in a delay here. I know that it won't work the other way around; but my point is I'm not sure how the browser handles that synchronous loop before the put request is made in p_1 to really know for sure that this example demonstrates that the MDN article ALWAYS holds in this set up.  However, I can observe that it takes longer for the requests to complete as the number of loop iterations is increased; and, in all cases I have observed, p_1 always writes before p_2. The only way p_2 writes before p_1 is if p_1 doesn't write at all because of the string taking up to much memory causing the transaction in p_1 to be aborted.

That being said, and returning to the fuller set up of my question concerning three promises in the array of the Promise.allSettled compared to requiring entry_save to complete before commencing a Promise.allSettled on the two remaining promises, in the full code of my project, for reasons I am not sure of, the latter is quicker than the former, that is, waiting for entry_save to complete is quicker than including it in the Promise.allSettled.

I was expecting it to be the other way around.  The only reason I can think of at this point is that, since entry_save and save_state are both writing to the same object store, perhaps whatever the browser does equivalent to locking the object store until the first transaction, which is that in entry_save, completes and removing the lock takes longer than requiring that entry_save complete before the Promise.allSettled commences and not involving a lock. I thought that everything would be ready "in advance" just waiting for the two put requests to take place in transaction order. They took place in order but more slowly or at least not as quick as using:

entry_save().then( () => { Promise.allSettled( [ save_state(), get_HTML() ] ) } ).then( ... );

instead of:

 Promise.allSettled( [ entry_save(), save_state(), get_HTML() ] ).then( ... );

function p_all() { Promise.allSettled( [ p_1(), p_2() ] ); }

function p_1()
  {
    return new Promise( ( resolve, reject ) =>
      {
        let T = DB.transaction( [ 'os_1', 'os_2' ], 'readwrite' ),
            q = T.objectStore( 'os_1' ),
            u = T.objectStore( 'os_2' ),
            req, i, t ='', x = '';

     req = q.get( 1 );

     req.onsuccess = () =>
       {
         let i, t, r = req.result;
         for ( i = 1; i < 10000000; i++ ) t = t + 'This is a string';
         r.n = 'p1';
         u.put( r );
         console.log( r );
       };
    }); }

function p_2()
  {
    return new Promise( ( resolve, reject ) =>
      {
       let T = DB.transaction( [ 'os_1', 'os_2' ], 'readwrite' ),
           q = T.objectStore( 'os_1' ),
           u = T.objectStore( 'os_2' ),
           req;

        req = q.get( 1 );

        req.onsuccess = () =>
          {
            let r = req.result;
            r.n = 'p2';
            u.put( r );
            console.log( r );
          };
    }); }

Body:
When you do this:

Promise.allSettled( [ entry_save(), save_state(), get_HTML() ] ).then(...)

It's equivalent to this:

const p1 = entry_save();
const p2 = save_state();
const p3 = get_HTML();

Promise.allSettled([p1, p2, p3]).then(...);

So, the individual function calls you issue such as save_state() are STARTED in the order specified.  But, each of those calls are asynchronous so the internal order of what happens before something else really depends upon what they do inside as they can all be in flight at the same time and parts of their execution can be interleaved in an indeterminate order.

Imagine that entry_save() actually consists of multiple asynchronous pieces such as first reading some data from disk, then modifying the data, then writing it to the database.  It would call the first asynchronous operation to read some data from disk and then immediately return a promise.  Then, save_state() would get to start executing.  If save_state() just immediately issued a write to the database, then it very well may write to the database before entry_save() writes to the database.  In fact, the sequencing of the two database writes is indeterminate and racy.

If you need entry_save() to complete before save_state(), then the above is NOT the way to code it at all.  Your code is not guaranteeing that all of entry_save() is done before any of save_state() runs.

Instead, you SHOULD do what you seem to already know:

entry_save().then( () => { Promise.allSettled( [ save_state(), get_HTML() ] ) } ).then( ... );

Only that guarantees that entry_save() will complete before save_state() gets to run.  And, this assumes that you're perfectly OK with save_state() and get_HTML() running concurrently and in an unpredictable order.

My question is does the synchronous code of each promise process in the order in which it is placed in the array, such that placing entry_save first will always result in its transaction being created first and guaranteeing its database requests will be performed first?

The functions are called in the order they are placed in the array, but that only determines the order in which the asynchronous are started.  After that, they are all in-flight at the same time and the internal timing between them depends upon how long their individual asynchronous operations take and what those asynchronous operations do.  If order matters, you can't just put them all in an indeterminate race.  That's call a "race condition".  Instead, you would need to structure your code to guarantee that the desired operation goes first before the ones that need to execute after it.


问:
Error with Confluent Schema REST proxy when trying to set an Avro schema
I am trying to update an avro schema using the rest proxy API in Confluent.  I can do a GET with the following, and get a valid response:

http://mykafkahost.com:8081/subjects/avro-schema-for-value/versions/1

But when I try this:
http://mykafkahost.com:8081/subjects/my-avro-schema-for-value/1

using either POST, PUT, or PATCH, I consistently get

{"error_code":404,"message":"HTTP 404 Not Found"}

Also tried
http://mykafkahost.com:8081/subjects/my-avro-schema-for-value/versions/1
but it yields:

{"error_code":405,"message":"HTTP 405 Method Not Allowed"}

I've asked the operations team, and they don't believe specific verbs are enabled/disabled, but it's looking possible to me. If I need to enable the POST, what config file is this done through?

答:
using the rest proxy API in Confluent

This is the Schema Registry, not the REST Proxy.

But when I try this: :8081/subjects/my-avro-schema-for-value/1

using either POST, PUT, or PATCH, I consistently get

{"error_code":404,"message":"HTTP 404 Not Found"}

Typo? You put /my-avro-schema, not /avro-schema

That address doesn't respond to those methods. Only DELETE works at /subjects/<name>-value/versions/<version>

what config file is this done through?

There is only one config file for the Schema Registry.


问:
How to keep data between intervals with Workmanager/PeriodicWorkRequest
I need a variable in the IntervalWork class keeping it's data throughout the different calls or intervals. Making the variable static or global within the class doesn't work. How to?

IntervalWork('keep' always loses it's value):

```<code>  public class IntervalWork{
    static int keep;
    public result doWork(){
       keep++;
     }
  }
</code>```

MainActivity:

```<code>        Constraints IntervalWorkerCS = new Constraints.Builder()
            .setRequiresBatteryNotLow(true)
            .build();
    //W/WM-WorkSpec: Interval duration lesser than minimum allowed value; Changed to 900000(15 minutes)
    PeriodicWorkRequest periodicWork = new PeriodicWorkRequest.Builder(IntervalWork.class, 15, TimeUnit.MINUTES)
            .setConstraints(IntervalWorkerCS)
            .setInitialDelay(delay,TimeUnit.MINUTES)
            .addTag("MyID")
            .build();
        WorkManager.getInstance(this).cancelAllWork();
        WorkManager.getInstance(this).enqueueUniquePeriodicWork("MyID", ExistingPeriodicWorkPolicy.KEEP, periodicWork);
</code>```

答: Your process may be terminated in between work items. So, if you have data that you wish to hold onto, save it in a file (database, SharedPreferences, etc.) or on a server.

Body:
I need a variable in the IntervalWork class keeping it's data throughout the different calls or intervals. Making the variable static or global within the class doesn't work. How to?

IntervalWork('keep' always loses it's value):

  public class IntervalWork{
    static int keep;
    public result doWork(){
       keep++;
     }
  }

MainActivity:

        Constraints IntervalWorkerCS = new Constraints.Builder()
            .setRequiresBatteryNotLow(true)
            .build();
    //W/WM-WorkSpec: Interval duration lesser than minimum allowed value; Changed to 900000(15 minutes)
    PeriodicWorkRequest periodicWork = new PeriodicWorkRequest.Builder(IntervalWork.class, 15, TimeUnit.MINUTES)
            .setConstraints(IntervalWorkerCS)
            .setInitialDelay(delay,TimeUnit.MINUTES)
            .addTag("MyID")
            .build();
        WorkManager.getInstance(this).cancelAllWork();
        WorkManager.getInstance(this).enqueueUniquePeriodicWork("MyID", ExistingPeriodicWorkPolicy.KEEP, periodicWork);


问:
How can I set and get cookies (server side) in Meteor?
How can I set and get cookies (server side) in Meteor?</p>

答:
It looks like we got a solution: ostrio/cookies which work both on the server side and on the client side: https://atmospherejs.com/ostrio/cookies</p>

```<code>import { Cookies } from 'meteor/ostrio:cookies';

const cookies = new Cookies();

const oldValue = cookies.get("key");
cookies.set("key", "newValue");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
It looks like we got a solution: ostrio/cookies which work both on the server side and on the client side: https://atmospherejs.com/ostrio/cookies

import { Cookies } from 'meteor/ostrio:cookies';

const cookies = new Cookies();

const oldValue = cookies.get("key");
cookies.set("key", "newValue");


问:
Error: APK content must be streamed
I am trying to install the apk in the device but I am seeing "Error: APK content must be streamed" error. Please help me to resolve this issue.</p>

```<code>$ adb install –r test.apk
Failed to install test.apk: Error: APK content must be streamed
</code>```

答:
I have found this error typically when I make a typo in the file pathing or the file name itself.

One thing that helps me in these incidences is this:

```<code>abd install -r StartOfFileName*.apk
</code>```

This is useful when you update your apk as well as to alleviate typo errors. The asterix suggests all or any entries after. Therefore, if you have a file named MyAwesomeAPKFileV7.apk

You could use:

```<code>abd install -r MyAwesome*.apk
</code>```

With less characters typed, less room for error. Furthermore, when version 8 comes out [MyAwesomeAPKFileV8.apk] you don't need a new command or to rewrite your scripts, just replace the old APK and run the script again.

Title: Error: APK content must be streamed

Body:
I am trying to install the apk in the device but I am seeing "Error: APK content must be streamed" error. Please help me to resolve this issue.

$ adb install –r test.apk
Failed to install test.apk: Error: APK content must be streamed

Body:
I have found this error typically when I make a typo in the file pathing or the file name itself.

One thing that helps me in these incidences is this:

abd install -r StartOfFileName*.apk

This is useful when you update your apk as well as to alleviate typo errors. The asterix suggests all or any entries after. Therefore, if you have a file named MyAwesomeAPKFileV7.apk

You could use:

abd install -r MyAwesome*.apk

With less characters typed, less room for error. Furthermore, when version 8 comes out [MyAwesomeAPKFileV8.apk] you don't need a new command or to rewrite your scripts, just replace the old APK and run the script again.


问:
pandas compare certain colum entries by date and value
my problem:

```<code> df1 = [{'Day': '2019-12-01', 'Issue Date': '2019-12-01', 'Price': '50'},
 {'Day': '2019-12-02', 'Issue Date': '2019-12-01', 'Price': '45'},
 {'Day': '2019-12-03', 'Issue Date': '2019-12-01', 'Price': '40'},
       {'Day': '2019-12-02', 'Issue Date': '2019-12-02', 'Price': '50'},
 {'Day': '2019-12-03', 'Issue Date': '2019-12-02', 'Price': '42'},
 {'Day': '2019-12-04', 'Issue Date': '2019-12-02', 'Price': '41'},
      {'Day': '2019-12-03', 'Issue Date': '2019-12-03', 'Price': '60'},
 {'Day': '2019-12-04', 'Issue Date': '2019-12-03', 'Price': '50'},
 {'Day': '2019-12-05', 'Issue Date': '2019-12-03', 'Price': '48'}

]
</code>```

Now I'd like to automatically compare the Price of the Issue date, with the price for the same date the day before.

To find out, how much the price rose from yesterday to today and create a new column with this value.

For Example: I'd like to compare the price of the 02nd of December in 'Issue Date: 2019-12-02 (Price = 45),
to the Price of the 2nd of December in 'Issue Date: 2019-12-01' (Price = 50). The Result should be Plus 10 %.

And so on.
How do I do that?

Body:
my problem:

 df1 = [{'Day': '2019-12-01', 'Issue Date': '2019-12-01', 'Price': '50'},
 {'Day': '2019-12-02', 'Issue Date': '2019-12-01', 'Price': '45'},
 {'Day': '2019-12-03', 'Issue Date': '2019-12-01', 'Price': '40'},
       {'Day': '2019-12-02', 'Issue Date': '2019-12-02', 'Price': '50'},
 {'Day': '2019-12-03', 'Issue Date': '2019-12-02', 'Price': '42'},
 {'Day': '2019-12-04', 'Issue Date': '2019-12-02', 'Price': '41'},
      {'Day': '2019-12-03', 'Issue Date': '2019-12-03', 'Price': '60'},
 {'Day': '2019-12-04', 'Issue Date': '2019-12-03', 'Price': '50'},
 {'Day': '2019-12-05', 'Issue Date': '2019-12-03', 'Price': '48'}

]

Now I'd like to automatically compare the Price of the Issue date, with the price for the same date the day before.

To find out, how much the price rose from yesterday to today and create a new column with this value.

For Example: I'd like to compare the price of the 02nd of December in 'Issue Date: 2019-12-02 (Price = 45),
to the Price of the 2nd of December in 'Issue Date: 2019-12-01' (Price = 50). The Result should be Plus 10 %.

And so on.
How do I do that?

Body:
Okay, if I understand your problem correctly, try this:

df1 = [{'Day': '2019-12-01', 'Issue Date': '2019-12-01', 'Price': '50'},
 {'Day': '2019-12-02', 'Issue Date': '2019-12-01', 'Price': '45'},
 {'Day': '2019-12-03', 'Issue Date': '2019-12-01', 'Price': '40'},
       {'Day': '2019-12-02', 'Issue Date': '2019-12-02', 'Price': '50'},
 {'Day': '2019-12-03', 'Issue Date': '2019-12-02', 'Price': '42'},
 {'Day': '2019-12-04', 'Issue Date': '2019-12-02', 'Price': '41'},
      {'Day': '2019-12-03', 'Issue Date': '2019-12-03', 'Price': '60'},
 {'Day': '2019-12-04', 'Issue Date': '2019-12-03', 'Price': '50'},
 {'Day': '2019-12-05', 'Issue Date': '2019-12-03', 'Price': '48'}

]

df = pd.DataFrame(df1)

df['Price'] = df['Price'].astype(int)

df['Issue Price'] = df.loc[df['Day'] == df['Issue Date'], 'Price']

df['Issue Price'] = df['Issue Price'].ffill()

df['Pct Change'] = (df['Issue Price'] - df['Price']) / df['Issue Price']
df

Output:

          Day  Issue Date  Price  Issue Price  Pct Change
0  2019-12-01  2019-12-01     50         50.0    0.000000
1  2019-12-02  2019-12-01     45         50.0    0.100000
2  2019-12-03  2019-12-01     40         50.0    0.200000
3  2019-12-02  2019-12-02     50         50.0    0.000000
4  2019-12-03  2019-12-02     42         50.0    0.160000
5  2019-12-04  2019-12-02     41         50.0    0.180000
6  2019-12-03  2019-12-03     60         60.0    0.000000
7  2019-12-04  2019-12-03     50         60.0    0.166667
8  2019-12-05  2019-12-03     48         60.0    0.200000


问:
UIActionSheet on iPad is not showing cancel button
I am trying to show cancel button in UIActionSheet but it's not showing, is that an acceptable behavior? please advice.

```<code>UIActionSheet *actionSheet = [[UIActionSheet alloc]
          initWithTitle:@"Are you sure you want to clear the cache?"
          delegate:self
          cancelButtonTitle:@"No"
          destructiveButtonTitle:@"Yes"
          otherButtonTitles:nil];

[actionSheet showInView:self.view];

[actionSheet release];
</code>```

答:
iPads have some special rules about action sheets and their cancel buttons, depending on where you are displaying it from:

You can present an action sheet from a toolbar, tab bar, button bar item, or from a view. This class takes the starting view and current platform into account when determining how to present the action sheet. For applications running on iPhone and iPod touch devices, the action sheet typically slides up from the bottom of the window that owns the view. For applications running on iPad devices, the action sheet is typically displayed in a popover that is anchored to the starting view in an appropriate way. Taps outside of the popover automatically dismiss the action sheet, as do taps within any custom buttons. You can also dismiss it programmatically.

When presenting an action sheet on an iPad, there are times when you should not include a cancel button. If you are presenting just the action sheet, the system displays the action sheet inside a popover without using an animation. Because taps outside the popover dismiss the action sheet without selecting an item, this results in a default way to cancel the sheet. Including a cancel button would therefore only cause confusion. However, if you have an existing popover and are displaying an action sheet on top of other content using an animation, a cancel button is still appropriate. For more information see iPad Human Interface Guidelines.

Here's a link with more explanation: http://crazyviraj.blogspot.com/2010/05/showing-cancel-button-in.html

Body:
I am trying to show cancel button in UIActionSheet but it's not showing, is that an acceptable behavior? please advice.

UIActionSheet *actionSheet = [[UIActionSheet alloc]
          initWithTitle:@"Are you sure you want to clear the cache?"
          delegate:self
          cancelButtonTitle:@"No"
          destructiveButtonTitle:@"Yes"
          otherButtonTitles:nil];

[actionSheet showInView:self.view];

[actionSheet release];


答:
This is not possible. A lookup would help if your were running the playbook on a local system, but unfortunately lookups don't run on remotely managed nodes.

As per the other answer, you can run a task first.

But if you are collecting facts first, why not use an Ansible variable?

```<code>- name: COPY file from remote machine to local
  fetch:
    src: /tmp/{{ ansible_nodename }}---mem-swap.out
    dest: /tmp
</code>```

Title: how to use unix command in src in ansible

Body:
This is not possible. A lookup would help if your were running the playbook on a local system, but unfortunately lookups don't run on remotely managed nodes.

As per the other answer, you can run a task first.

But if you are collecting facts first, why not use an Ansible variable?

- name: COPY file from remote machine to local
  fetch:
    src: /tmp/{{ ansible_nodename }}---mem-swap.out
    dest: /tmp


问:
Calculating second page of results from a union
I've got a SQLServer problem.

I'm trying to work out how to show a second page of results. The first page of results are pulled using the query below.

```<code>SELECT TOP 10 * FROM (
    SELECT c.id, c.name, c.inserteddate, c.cityname, ftblstates.name AS statename, clc.name AS catname, '' AS listingimagelogo, '' AS orgname, relocateyn, '' AS employerclassified
    FROM tblclassifieds c
    LEFT JOIN tblclassifiedscategories clc ON c.categoryid = clc.id
    LEFT JOIN ftblstates ON c.stateid = ftblstates.id
    WHERE c.expirydate != '' AND c.expirydate >= '5/17/2011'
    UNION ALL
    SELECT ce.id, ce.name, ce.inserteddate, suburb AS cityname, ftblstates.name AS statename, ce.jobtype AS catname, ce.listingimagelogo, ce.orgname, '' AS relocateyn, '1' AS employerclassified
    FROM tblclassifiedemployers ce
    LEFT JOIN ftblstates ON ce.stateid = ftblstates.id
    WHERE ce.expirydate != '' AND ce.expirydate >= '5/17/2011'
) a
ORDER BY inserteddate desc;
</code>```

Is the answer similar to the following?

```<code>SELECT TOP 10 * FROM (
    SELECT c.id, c.name, c.inserteddate, c.cityname, ftblstates.name AS statename, clc.name AS catname, '' AS listingimagelogo, '' AS orgname, relocateyn, '' AS employerclassified
    FROM tblclassifieds c
    LEFT JOIN tblclassifiedscategories clc ON c.categoryid = clc.id
    LEFT JOIN ftblstates ON c.stateid = ftblstates.id
    WHERE c.expirydate != '' AND c.expirydate >= '5/17/2011'
    UNION ALL
    SELECT ce.id, ce.name, ce.inserteddate, suburb AS cityname, ftblstates.name AS statename, ce.jobtype AS catname, ce.listingimagelogo, ce.orgname, '' AS relocateyn, '1' AS employerclassified
    FROM tblclassifiedemployers ce
    LEFT JOIN ftblstates ON ce.stateid = ftblstates.id
    WHERE ce.expirydate != '' AND ce.expirydate >= '5/17/2011'
) a

WHERE NOT a.id IN (SELECT TOP 10 tblclassifieds.id ...

ORDER BY inserteddate desc;
</code>```

Can someone please help me out completing the query?

答:
A simple way of doing it:

```<code>declare @page int = 2
declare @take int = 10

select * from (
    SELECT *, ROW_NUMBER() OVER(ORDER BY inserteddate desc) as rowno FROM (
        SELECT c.id, c.name, c.inserteddate, c.cityname, ftblstates.name AS statename, clc.name AS catname, '' AS listingimagelogo, '' AS orgname, relocateyn, '' AS employerclassified
        FROM tblclassifieds c
        LEFT JOIN tblclassifiedscategories clc ON c.categoryid = clc.id
        LEFT JOIN ftblstates ON c.stateid = ftblstates.id
        WHERE c.expirydate != '' AND c.expirydate >= '5/17/2011'
        UNION ALL
        SELECT ce.id, ce.name, ce.inserteddate, suburb AS cityname, ftblstates.name AS statename, ce.jobtype AS catname, ce.listingimagelogo, ce.orgname, '' AS relocateyn, '1' AS employerclassified
        FROM tblclassifiedemployers ce
        LEFT JOIN ftblstates ON ce.stateid = ftblstates.id
        WHERE ce.expirydate != '' AND ce.expirydate >= '5/17/2011'
    ) a
) b
where   rowno > (@page - 1) * @take
    AND rowno <= @page * @take
order by rowno
</code>```

I didnt alter your internal query.

Edit: Added parenteses in where clause

Body:
I've got a SQLServer problem.

I'm trying to work out how to show a second page of results. The first page of results are pulled using the query below.

SELECT TOP 10 * FROM (
    SELECT c.id, c.name, c.inserteddate, c.cityname, ftblstates.name AS statename, clc.name AS catname, '' AS listingimagelogo, '' AS orgname, relocateyn, '' AS employerclassified
    FROM tblclassifieds c
    LEFT JOIN tblclassifiedscategories clc ON c.categoryid = clc.id
    LEFT JOIN ftblstates ON c.stateid = ftblstates.id
    WHERE c.expirydate != '' AND c.expirydate >= '5/17/2011'
    UNION ALL
    SELECT ce.id, ce.name, ce.inserteddate, suburb AS cityname, ftblstates.name AS statename, ce.jobtype AS catname, ce.listingimagelogo, ce.orgname, '' AS relocateyn, '1' AS employerclassified
    FROM tblclassifiedemployers ce
    LEFT JOIN ftblstates ON ce.stateid = ftblstates.id
    WHERE ce.expirydate != '' AND ce.expirydate >= '5/17/2011'
) a
ORDER BY inserteddate desc;

Is the answer similar to the following?

SELECT TOP 10 * FROM (
    SELECT c.id, c.name, c.inserteddate, c.cityname, ftblstates.name AS statename, clc.name AS catname, '' AS listingimagelogo, '' AS orgname, relocateyn, '' AS employerclassified
    FROM tblclassifieds c
    LEFT JOIN tblclassifiedscategories clc ON c.categoryid = clc.id
    LEFT JOIN ftblstates ON c.stateid = ftblstates.id
    WHERE c.expirydate != '' AND c.expirydate >= '5/17/2011'
    UNION ALL
    SELECT ce.id, ce.name, ce.inserteddate, suburb AS cityname, ftblstates.name AS statename, ce.jobtype AS catname, ce.listingimagelogo, ce.orgname, '' AS relocateyn, '1' AS employerclassified
    FROM tblclassifiedemployers ce
    LEFT JOIN ftblstates ON ce.stateid = ftblstates.id
    WHERE ce.expirydate != '' AND ce.expirydate >= '5/17/2011'
) a

WHERE NOT a.id IN (SELECT TOP 10 tblclassifieds.id ...

ORDER BY inserteddate desc;

Can someone please help me out completing the query?

Body:
A simple way of doing it:

declare @page int = 2
declare @take int = 10

select * from (
    SELECT *, ROW_NUMBER() OVER(ORDER BY inserteddate desc) as rowno FROM (
        SELECT c.id, c.name, c.inserteddate, c.cityname, ftblstates.name AS statename, clc.name AS catname, '' AS listingimagelogo, '' AS orgname, relocateyn, '' AS employerclassified
        FROM tblclassifieds c
        LEFT JOIN tblclassifiedscategories clc ON c.categoryid = clc.id
        LEFT JOIN ftblstates ON c.stateid = ftblstates.id
        WHERE c.expirydate != '' AND c.expirydate >= '5/17/2011'
        UNION ALL
        SELECT ce.id, ce.name, ce.inserteddate, suburb AS cityname, ftblstates.name AS statename, ce.jobtype AS catname, ce.listingimagelogo, ce.orgname, '' AS relocateyn, '1' AS employerclassified
        FROM tblclassifiedemployers ce
        LEFT JOIN ftblstates ON ce.stateid = ftblstates.id
        WHERE ce.expirydate != '' AND ce.expirydate >= '5/17/2011'
    ) a
) b
where   rowno > (@page - 1) * @take
    AND rowno <= @page * @take
order by rowno

I didnt alter your internal query.

Edit: Added parenteses in where clause


问:
Installation of tensor flow on windows
When I installed tensor flow, after type following command
pip3 install --upgrade tensor flow
following issue rose up

Could not find a version that satisfies the requirement tensor flow
  (from versions: ) No matching distribution found for tensor flow

any solutions??

答:
Install

```<code>pip install tensorflow
</code>```

Verify the installation

```<code>python3 -c "import tensorflow as tf;
print(tf.reduce_sum(tf.random.normal([1000, 1000])))"
</code>```

your mistake is that you're writing it separately.  pip3 install --upgrade tensor flow

Title: Installation of tensor flow on windows

Body:
Install

pip install tensorflow

Verify the installation

python3 -c "import tensorflow as tf;
print(tf.reduce_sum(tf.random.normal([1000, 1000])))"

your mistake is that you're writing it separately.  pip3 install --upgrade tensor flow


问:
Creating a dataframe from list of lists: Column Data Repeating for Each Record
I have a list of lists that I'm trying to convert into a dataframe. As the title suggests, each record contains the column name and the value. Here's a modified example of what my list looks like:

```<code>    sample_list =
        [['record',''],
        ['fname','John'],
        ['lname','Smith'],
        ['bdate','1985-06-15'],
        ['record',''],
        ['fname','Mary'],
        ['lname','Smith'],
        ['bdate','1990-03-12'],
                          ...]
</code>```

I'm coming from the VBA world and I'd probably handle something like this with a loop. However, I've been warned to not do that for really large datasets (happens to be case where this conversion is needed). What method should I use to give me the following result:

```<code>fname | lname | bdate
John  | Smith | 1985-06-15
Mary  | Smith | 1990-03-12
...
</code>```

Any help or pointing in the right direction is very appreciated.

答:
It probably be best to just iterate over the data, but this is a pandas solution with pivot:

```<code>(pd.DataFrame(lst)
   .assign(group=lambda x: x[0].eq('record').cumsum())
   .pivot(index='group', columns=0, values=1)
   .drop('record', axis=1)
)
</code>```

output:

```<code>0           bdate fname  lname
group
1      1985-06-15  John  Smith
2      1990-03-12  Mary  Smith
</code>```

Body:
I have a list of lists that I'm trying to convert into a dataframe. As the title suggests, each record contains the column name and the value. Here's a modified example of what my list looks like:

    sample_list =
        [['record',''],
        ['fname','John'],
        ['lname','Smith'],
        ['bdate','1985-06-15'],
        ['record',''],
        ['fname','Mary'],
        ['lname','Smith'],
        ['bdate','1990-03-12'],
                          ...]

I'm coming from the VBA world and I'd probably handle something like this with a loop. However, I've been warned to not do that for really large datasets (happens to be case where this conversion is needed). What method should I use to give me the following result:

fname | lname | bdate
John  | Smith | 1985-06-15
Mary  | Smith | 1990-03-12
...

Any help or pointing in the right direction is very appreciated.

Body:
It probably be best to just iterate over the data, but this is a pandas solution with pivot:

(pd.DataFrame(lst)
   .assign(group=lambda x: x[0].eq('record').cumsum())
   .pivot(index='group', columns=0, values=1)
   .drop('record', axis=1)
)

output:

0           bdate fname  lname
group
1      1985-06-15  John  Smith
2      1990-03-12  Mary  Smith


问:
Testing a Redux connected component with enzyme and jest
I am unit testing my React app with jest and enzyme and all is good until I happened to test a class component connected with Redux. I went ahead and tested it by wrapping the component with a  and then shallow mounting it. However I am not able to run assertions after updating the props of component, nor I am able to spy on the class methods being called or not.

Below is my sample code:

```<code>const wrapper = shallow(
    <Provider store={store}>
        <TestComponent {...props}  />
    </Provider>
).dive();
</code>```

Now when I try t set the props of the wrapper and run assertions, it fails:

```<code>wrapper.setProps({
  showHeader:  true
})
expect(wrapper.find('h1')).toHaveLength(1);
</code>```

Interesting part is, if I export the unconnected component as also suggested in redux docs, the assertions work well. Is it fine to export the unconnected component just for the purpose of testing? I can't spy on instance methods/lifecycle methods if I try to test the connected component.

答:
You can mock the connect function from react-redux to return the original component

```<code>jest.mock('react-redux', () => ({
   connect: () => Component => Component
}))

</code>```

Body:
I am unit testing my React app with jest and enzyme and all is good until I happened to test a class component connected with Redux. I went ahead and tested it by wrapping the component with a  and then shallow mounting it. However I am not able to run assertions after updating the props of component, nor I am able to spy on the class methods being called or not.

Below is my sample code:

const wrapper = shallow(
    <Provider store={store}>
        <TestComponent {...props}  />
    </Provider>
).dive();

Now when I try t set the props of the wrapper and run assertions, it fails:

wrapper.setProps({
  showHeader:  true
})
expect(wrapper.find('h1')).toHaveLength(1);

Interesting part is, if I export the unconnected component as also suggested in redux docs, the assertions work well. Is it fine to export the unconnected component just for the purpose of testing? I can't spy on instance methods/lifecycle methods if I try to test the connected component.

Body:
You can mock the connect function from react-redux to return the original component

jest.mock('react-redux', () => ({
   connect: () => Component => Component
}))


问:
Convert list of dictionaries to a pandas DataFrame
How can I convert a list of dictionaries into a DataFrame? Given:

```<code>[{'points': 50, 'time': '5:00', 'year': 2010},
 {'points': 25, 'time': '6:00', 'month': "february"},
 {'points':90, 'time': '9:00', 'month': 'january'},
 {'points_h1':20, 'month': 'june'}]
</code>```

I want to turn the above into a DataFrame:

```<code>      month  points  points_h1  time  year
0       NaN      50        NaN  5:00  2010
1  february      25        NaN  6:00   NaN
2   january      90        NaN  9:00   NaN
3      june     NaN         20   NaN   NaN
</code>```

Note: Order of the columns does not matter.

答:
Pyhton3:
Most of the solutions listed previously work. However, there are instances when row_number of the dataframe is not required and the each row (record) has to be written individually.

The following method is useful in that case.

```<code>import csv

my file= 'C:\Users\John\Desktop\export_dataframe.csv'

records_to_save = data2 #used as in the thread.

colnames = list[records_to_save[0].keys()]
# remember colnames is a list of all keys. All values are written corresponding
# to the keys and "None" is specified in case of missing value

with open(myfile, 'w', newline="",encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerow(colnames)
    for d in records_to_save:
        writer.writerow([d.get(r, "None") for r in colnames])
</code>```

Body:
How can I convert a list of dictionaries into a DataFrame? Given:

[{'points': 50, 'time': '5:00', 'year': 2010},
 {'points': 25, 'time': '6:00', 'month': "february"},
 {'points':90, 'time': '9:00', 'month': 'january'},
 {'points_h1':20, 'month': 'june'}]

I want to turn the above into a DataFrame:

      month  points  points_h1  time  year
0       NaN      50        NaN  5:00  2010
1  february      25        NaN  6:00   NaN
2   january      90        NaN  9:00   NaN
3      june     NaN         20   NaN   NaN

Note: Order of the columns does not matter.

Body:
Pyhton3:
Most of the solutions listed previously work. However, there are instances when row_number of the dataframe is not required and the each row (record) has to be written individually.

The following method is useful in that case.

import csv

my file= 'C:\Users\John\Desktop\export_dataframe.csv'

records_to_save = data2 #used as in the thread.

colnames = list[records_to_save[0].keys()]
# remember colnames is a list of all keys. All values are written corresponding
# to the keys and "None" is specified in case of missing value

with open(myfile, 'w', newline="",encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerow(colnames)
    for d in records_to_save:
        writer.writerow([d.get(r, "None") for r in colnames])


问:
Visual studio with mvvm-light toolkit crash
I am building a Silverlight 4 application using Mvvm Light(latest version), and VS 2010 crashes every 5 minutes even less. So it is impossible to work.

I believe it is because I am doing or there is something wrong with my MVVM implementation.

I get this error on the designer sometimes.

An unhandled exception has occurred:

An unhandled exception has occurred:  [Xml_CannotFindFileInXapPackage] Arguments: ServiceReferences.ClientConfig Debugging resource strings are unavailable. Often the key and arguments provide sufficient information to diagnose the problem. See http://go.microsoft.com/fwlink/?linkid=106663&Version=4.0.60129.0&File=System.Xml.dll&Key=Xml_CannotFindFileInXapPackage    at System.Xml.XmlXapResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn)    at System.Xml.XmlReaderSettings.CreateReader(String inputUri, XmlParserContext inputContext)    at System.Xml.XmlReader.Create(String inputUri, XmlReaderSettings settings, XmlParserContext inputContext)    at System.ServiceModel.Configuration.ServiceModelSectionGroup.GetSectionGroup() I don't know if this is related with the crash.   ..And I found this error in the event viewer: Application: devenv.exe Framework Version: v4.0.30319 Description: The process was terminated due to an unhandled exception. Exception Info: System.ObjectDisposedException Stack:    at System.Windows.Threading.Dispatcher.FastInvoke(System.Windows.Threading.DispatcherPriority, System.Delegate, System.Object[])    at System.Net.Browser.AsyncHelper.CheckUseLowLatencyNetworking()    at System.Net.Browser.AsyncHelper.BeginOnUI(System.Threading.SendOrPostCallback, System.Object)    at System.Net.Browser.BrowserHttpWebRequest.Abort()    at System.ServiceModel.Channels.HttpOutput+WebRequestHttpOutput.Abort(System.ServiceModel.Channels.HttpAbortReason)    at System.ServiceModel.Channels.HttpChannelFactory+HttpRequestChannel+HttpChannelAsyncRequest.AbortSend()    at System.ServiceModel.Channels.HttpChannelFactory+HttpRequestChannel+HttpChannelAsyncRequest.OnSendTimeout(System.Object)    at System.Threading._TimerCallback.TimerCallback_Context(System.Object)    at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)    at System.Threading._TimerCallback.PerformTimerCallback(System.Object)

Any help will be appreciated, thanks in advance.

答:
Most of the times the reason why Visual Studio crashes in WPF and Silverlight applications is that it has difficulty in loading Xaml in design view. It is usually because of an error in XAML.

To prevent this issue from occuring:

Go to Tools / Options

Text Editor -> XAML -> Miscellaneous

Check the option "Always open documents in full XAML view".

Resolve the error in xaml

Uncheck the option mentioned in point#3 to see XAML in design view.

ContentLicense: CC BY-SA 2.5


问:
Xcode doesn't write anything to output console
I am working on an iPhone/iPad app. All of a sudden output console stopped displaying ANY messages AT ALL. I tried to open older project - works just fine. So I thought that local project's repository got corrupted somehow, so I tried to create a new project - no messages at all are getting written to console output. Did I do something with Xcode settings accidentally? I am at a complete loss and frustrated.

Please help if you have any ideas.

Thanks.

答:
I had OS_ACTIVITY_MODE checked to disabled.
once i removed this the console was showing debug info again.


问:
C++ Program skipping second fuction call
I have a problem in my C++, I call a first funtion (verif) which runs very well and then when I try to run an other one (dateIncrement), she just dont run and it skips to the next if, I saw it with the debugger, here is my code :

```<code>#include <iostream>
using namespace std;

bool verif(int day, int month, int year) {
    bool verifStatus;
    bool month31;
    bool month30;
    bool anneeBis;
    bool feb29;
    bool feb;
    month31 = ((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && day > 0 && day < 32);
    month30 = ((month == 4 || month == 6 || month == 9 || month == 11) && day > 0 && day < 31);
    anneeBis = (year % 4 == 0 && year % 100 != 0);
    feb = (month == 2 && day > 0 && day < 29);
    feb29 = ((month == 2 && day == 29) && anneeBis);
    verifStatus = (month31 || month30 || feb || feb29);
    return verifStatus;
}

int dateIncrement(int day, int month, int year) {
    bool month31;
    bool month30;
    bool anneeBis;
    bool feb29;
    bool feb;
    bool dec;
    bool dec31;
    month31 = ((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10) && day > 0 && day < 32);
    month30 = ((month == 4 || month == 6 || month == 9 || month == 11) && day > 0 && day < 31);
    anneeBis = (year % 4 == 0 && year % 100 != 0);
    feb = (month == 2 && day > 0 && day < 29);
    feb29 = ((month == 2 && day == 29) && anneeBis);
    dec = (month == 12 && day > 0 && day < 31);
    dec31 = (month == 12 && day == 31);

    if (month31) {
        if (day == 31) {
            day = 1;
            month++;
        }

        if (day < 31) day++;
    }

    if (month30) {
        if (day == 30) {
            day = 1;
            month++;
        }

        if (day < 30) day += 1;
    }

    if(feb) day += 1;
    if (feb29) {
        day = 1;
        month++;
    }

    if (dec31) {
        day = 1;
        month = 1;
        year++;
    }
    if (dec) day++;
    return day, month, year;
}

int main()
{
    int day, month, year;

    do {
        day = 0;
        month = 0; // Mise et remise à 0 des variables à chaque essai
        year = 0;

        cout << "Entrez jour (666 pour quitter le programme) : " << endl;
        cin >> day;
        cout << "Entrez Mois :" << endl;
        cin >> month;
        cout << "Entrez ann\202e : " << endl;
        cin >> year;
        if (verif(day, month, year)) { // First function call works
            cout << "Le " << day << "/" << month << "/" << year << " est une date valide ! " << endl;
        }
        dateIncrement(day, month, year); // This is skipped
        if (verif(day, month, year)) { // It goes there without calling dateIncrement...
            cout << "Le " << day << "/" << month << "/" << year << " est aussi une date valide ! " << endl;
        }

        else {
            cout << "Le " << day << "/" << month << "/" << year << " n'est pas une date valide ! " << endl;
        }
    } while (day != 666);
    return 0;
}
</code>```

I also know that if I add a system("pause"); or a _getch(); between the first and second call, it works well, but I dont want the user to make anything after putting his date (and I also dont want to add batch in my C++).
I hope one of you can tell me why and how to solve it, thanks.

PS : I tried to say hello but this text editor wont :(

答:
Your function is not being skipped. Rather, is behaving counter intuitively to what you expect. According to dateIncrement's function signature

```<code>int dateIncrement(int day, int month, int year) {
    ...
    return day, month, year;
}
</code>```

The function takes three ints by value. By "takes three ints by value" I mean it copies their value from main into the stack space of dateIncrement, where they are now new, local variables of dateIncrement. Any changes you make to these values in dateIncrement are only valid for the length of the function execution.

Your return statement return day, month, year; uses the comma operator. According to https://en.cppreference.com/w/cpp/language/operator_other,

In a comma expression E1, E2, the expression E1 is evaluated, its result is discarded (although if it has class type, it won't be destroyed until the end of the containing full expression), and its side effects are completed before evaluation of the expression E2 begins

That means that day and month do nothing, and your function returns the value of year. This would have some effect if you were assigning the value of of dateIncrement to anything in main (e.g. year = dateIncrement(day, month, year);) but alas you are discarding this result.

If you want a function to be able to modify parameters that you send to it (and have those changes be visible to the function that called this function), you can either pass pointers to your variables (not recommended), or pass the variables by reference.

Change your function signature to

```<code>void dateIncrement(int& day, int& month, int& year) {
    ...
    // this is a void function so remove your return statement
}
</code>```

Body:
I have a problem in my C++, I call a first funtion (verif) which runs very well and then when I try to run an other one (dateIncrement), she just dont run and it skips to the next if, I saw it with the debugger, here is my code :

#include <iostream>
using namespace std;

bool verif(int day, int month, int year) {
    bool verifStatus;
    bool month31;
    bool month30;
    bool anneeBis;
    bool feb29;
    bool feb;
    month31 = ((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && day > 0 && day < 32);
    month30 = ((month == 4 || month == 6 || month == 9 || month == 11) && day > 0 && day < 31);
    anneeBis = (year % 4 == 0 && year % 100 != 0);
    feb = (month == 2 && day > 0 && day < 29);
    feb29 = ((month == 2 && day == 29) && anneeBis);
    verifStatus = (month31 || month30 || feb || feb29);
    return verifStatus;
}

int dateIncrement(int day, int month, int year) {
    bool month31;
    bool month30;
    bool anneeBis;
    bool feb29;
    bool feb;
    bool dec;
    bool dec31;
    month31 = ((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10) && day > 0 && day < 32);
    month30 = ((month == 4 || month == 6 || month == 9 || month == 11) && day > 0 && day < 31);
    anneeBis = (year % 4 == 0 && year % 100 != 0);
    feb = (month == 2 && day > 0 && day < 29);
    feb29 = ((month == 2 && day == 29) && anneeBis);
    dec = (month == 12 && day > 0 && day < 31);
    dec31 = (month == 12 && day == 31);

    if (month31) {
        if (day == 31) {
            day = 1;
            month++;
        }

        if (day < 31) day++;
    }

    if (month30) {
        if (day == 30) {
            day = 1;
            month++;
        }

        if (day < 30) day += 1;
    }

    if(feb) day += 1;
    if (feb29) {
        day = 1;
        month++;
    }

    if (dec31) {
        day = 1;
        month = 1;
        year++;
    }
    if (dec) day++;
    return day, month, year;
}

int main()
{
    int day, month, year;

    do {
        day = 0;
        month = 0; // Mise et remise à 0 des variables à chaque essai
        year = 0;

        cout << "Entrez jour (666 pour quitter le programme) : " << endl;
        cin >> day;
        cout << "Entrez Mois :" << endl;
        cin >> month;
        cout << "Entrez ann\202e : " << endl;
        cin >> year;
        if (verif(day, month, year)) { // First function call works
            cout << "Le " << day << "/" << month << "/" << year << " est une date valide ! " << endl;
        }
        dateIncrement(day, month, year); // This is skipped
        if (verif(day, month, year)) { // It goes there without calling dateIncrement...
            cout << "Le " << day << "/" << month << "/" << year << " est aussi une date valide ! " << endl;
        }

        else {
            cout << "Le " << day << "/" << month << "/" << year << " n'est pas une date valide ! " << endl;
        }
    } while (day != 666);
    return 0;
}

I also know that if I add a system("pause"); or a _getch(); between the first and second call, it works well, but I dont want the user to make anything after putting his date (and I also dont want to add batch in my C++).
I hope one of you can tell me why and how to solve it, thanks.

PS : I tried to say hello but this text editor wont :(

Body:
Your function is not being skipped. Rather, is behaving counter intuitively to what you expect. According to dateIncrement's function signature

int dateIncrement(int day, int month, int year) {
    ...
    return day, month, year;
}

The function takes three ints by value. By "takes three ints by value" I mean it copies their value from main into the stack space of dateIncrement, where they are now new, local variables of dateIncrement. Any changes you make to these values in dateIncrement are only valid for the length of the function execution.

Your return statement return day, month, year; uses the comma operator. According to https://en.cppreference.com/w/cpp/language/operator_other,

In a comma expression E1, E2, the expression E1 is evaluated, its result is discarded (although if it has class type, it won't be destroyed until the end of the containing full expression), and its side effects are completed before evaluation of the expression E2 begins

That means that day and month do nothing, and your function returns the value of year. This would have some effect if you were assigning the value of of dateIncrement to anything in main (e.g. year = dateIncrement(day, month, year);) but alas you are discarding this result.

If you want a function to be able to modify parameters that you send to it (and have those changes be visible to the function that called this function), you can either pass pointers to your variables (not recommended), or pass the variables by reference.

Change your function signature to

void dateIncrement(int& day, int& month, int& year) {
    ...
    // this is a void function so remove your return statement
}