问:
Adding extra description between argparse optional arguments
I'd like to add an extra description between optional argument groups in argaparse in a following style:</p>
```<code>script --help
usage: script [options] <COMMAND>

A script

optional arguments:
  -h, --help            show this help message and exit
  -f FOO, --foo FOO     show FOO
following commands modify FOO output:
  -lower                show FOO in lowercase
  -upper                show FOO in CAPS
following commands redirect FOO:
  -to-file              write FOO to file

</code>```

答:
Well, I guess you've already made something as you mentioned argparse in your question title and your output sample looks quite similar to something which have been generated using ArgumentParser. If you want just a code sample, you could take it from comment I've left, but I've decided to add some explanation.

Basically the solution of your problem is creating separate groups using ArgumentParser.add_argument_group(). Text you pass to description argument will be printed before help for arguments added to this group (exactly how you wanted besides some extra newlines).

Now some tips regarding implementation for this particular case.

Since --lower and --upper arguments should just store a boolean value, I'd recommend to set same destination for both arguments (e.g. is_lower) and use store_true/store_false action. Also as logically only one of these arguments could be used at the same time it'd be a good idea to add both into a mutually exclusive group using ArgumentParser.add_mutually_exclusive_group(). Code:

from argparse import ArgumentParser

...

parser = ArgumentParser(description="A script")

...

modify_group = parser.add_argument_group(
    description="following commands modify FOO output:"
)
modify_exclusive_group = modify_group.add_mutually_exclusive_group()
modify_exclusive_group.add_argument(
    "--lower",
    action="store_true",
    dest="is_lower",
    default=True,
    help="show FOO in lowercase"
)
modify_exclusive_group.add_argument(
    "--upper",
    action="store_false",
    dest="is_lower",
    help="show FOO in CAPS"
)
```
<p>With <code>--to-file</code> argument situation is quite different. First of all, I'd not add it at all, as output redirection could be done in console <em>(<code>python script.py > out.txt</code>)</em>. But if you still want to implement it, you might use special file type <code>argparse.FileType</code> which let parser to open file handle in certain mode. Depending on your code you might use opened file in any of possible way, I'd show common way to redirect all output into a file by replacing <code>sys.stdout</code> with opened file object. Code:</p>
<pre class="lang-py prettyprint-override"><code>import sys
from argparse import FileType

...

redirect_group = parser.add_argument_group(
    description="following commands redirect FOO:"
)
redirect_group.add_argument(
    "--to-file",
    type=FileType("w"),
    dest="stdout",
    default=sys.stdout,
    help="write FOO to file",
    metavar=""  # set name here to add variable in help message
)

...

args = parser.parse_args()
sys.stdout = args.stdout
</code>```

Combining all together and adding some simple task to print random strings you will get next code:

import sys
from argparse import ArgumentParser, FileType
from random import randrange, choices
from string import ascii_letters

parser = ArgumentParser(description="A script")
parser.add_argument("-f", "--foo", help="show FOO")
modify_group = parser.add_argument_group(
    description="following commands modify FOO output:"
)
modify_exclusive_group = modify_group.add_mutually_exclusive_group()
modify_exclusive_group.add_argument(
    "--lower",
    action="store_true",
    dest="is_lower",
    default=True,
    help="show FOO in lowercase"
)
modify_exclusive_group.add_argument(
    "--upper",
    action="store_false",
    dest="is_lower",
    help="show FOO in CAPS"
)
redirect_group = parser.add_argument_group(
    description="following commands redirect FOO:"
)
redirect_group.add_argument(
    "--to-file",
    type=FileType("w"),
    dest="stdout",
    default=sys.stdout,
    help="write FOO to file",
    metavar=""
)

args = parser.parse_args()
sys.stdout = args.stdout
modify_method = str.lower if args.is_lower else str.upper

for _ in range(randrange(5, 10)):
    random_string = "".join(choices(ascii_letters, k=randrange(10, 20)))
    print(modify_method(random_string))
```
<p>Help message:</p>
<pre class="lang-none prettyprint-override"><code>usage: script.py [-h] [-f FOO] [--lower | --upper] [--to-file]

A script

optional arguments:
  -h, --help         show this help message and exit
  -f FOO, --foo FOO  show FOO

  following commands modify FOO output:

  --lower            show FOO in lowercase
  --upper            show FOO in CAPS

  following commands redirect FOO:

  --to-file          write FOO to file
</code>```

Body:
I'd like to add an extra description between optional argument groups in argaparse in a following style:

script --help
usage: script [options] <COMMAND>

A script

optional arguments:
  -h, --help            show this help message and exit
  -f FOO, --foo FOO     show FOO
following commands modify FOO output:
  -lower                show FOO in lowercase
  -upper                show FOO in CAPS
following commands redirect FOO:
  -to-file              write FOO to file

Body:
Well, I guess you've already made something as you mentioned argparse in your question title and your output sample looks quite similar to something which have been generated using ArgumentParser. If you want just a code sample, you could take it from comment I've left, but I've decided to add some explanation.

Basically the solution of your problem is creating separate groups using ArgumentParser.add_argument_group(). Text you pass to description argument will be printed before help for arguments added to this group (exactly how you wanted besides some extra newlines).

Now some tips regarding implementation for this particular case.

Since --lower and --upper arguments should just store a boolean value, I'd recommend to set same destination for both arguments (e.g. is_lower) and use store_true/store_false action. Also as logically only one of these arguments could be used at the same time it'd be a good idea to add both into a mutually exclusive group using ArgumentParser.add_mutually_exclusive_group(). Code:

from argparse import ArgumentParser

...

parser = ArgumentParser(description="A script")

...

modify_group = parser.add_argument_group(
    description="following commands modify FOO output:"
)
modify_exclusive_group = modify_group.add_mutually_exclusive_group()
modify_exclusive_group.add_argument(
    "--lower",
    action="store_true",
    dest="is_lower",
    default=True,
    help="show FOO in lowercase"
)
modify_exclusive_group.add_argument(
    "--upper",
    action="store_false",
    dest="is_lower",
    help="show FOO in CAPS"
)

With --to-file argument situation is quite different. First of all, I'd not add it at all, as output redirection could be done in console (python script.py > out.txt). But if you still want to implement it, you might use special file type argparse.FileType which let parser to open file handle in certain mode. Depending on your code you might use opened file in any of possible way, I'd show common way to redirect all output into a file by replacing sys.stdout with opened file object. Code:

import sys
from argparse import FileType

...

redirect_group = parser.add_argument_group(
    description="following commands redirect FOO:"
)
redirect_group.add_argument(
    "--to-file",
    type=FileType("w"),
    dest="stdout",
    default=sys.stdout,
    help="write FOO to file",
    metavar=""  # set name here to add variable in help message
)

...

args = parser.parse_args()
sys.stdout = args.stdout

Combining all together and adding some simple task to print random strings you will get next code:

import sys
from argparse import ArgumentParser, FileType
from random import randrange, choices
from string import ascii_letters

parser = ArgumentParser(description="A script")
parser.add_argument("-f", "--foo", help="show FOO")
modify_group = parser.add_argument_group(
    description="following commands modify FOO output:"
)
modify_exclusive_group = modify_group.add_mutually_exclusive_group()
modify_exclusive_group.add_argument(
    "--lower",
    action="store_true",
    dest="is_lower",
    default=True,
    help="show FOO in lowercase"
)
modify_exclusive_group.add_argument(
    "--upper",
    action="store_false",
    dest="is_lower",
    help="show FOO in CAPS"
)
redirect_group = parser.add_argument_group(
    description="following commands redirect FOO:"
)
redirect_group.add_argument(
    "--to-file",
    type=FileType("w"),
    dest="stdout",
    default=sys.stdout,
    help="write FOO to file",
    metavar=""
)

args = parser.parse_args()
sys.stdout = args.stdout
modify_method = str.lower if args.is_lower else str.upper

for _ in range(randrange(5, 10)):
    random_string = "".join(choices(ascii_letters, k=randrange(10, 20)))
    print(modify_method(random_string))

Help message:

usage: script.py [-h] [-f FOO] [--lower | --upper] [--to-file]

A script

optional arguments:
  -h, --help         show this help message and exit
  -f FOO, --foo FOO  show FOO

  following commands modify FOO output:

  --lower            show FOO in lowercase
  --upper            show FOO in CAPS

  following commands redirect FOO:

  --to-file          write FOO to file


来源: stackexchange

问:
Error crs when reading a shapefile with geopandas in jupyter
I´m trying to read a shapefile with geopandas

```<code>Quito_full =gpd.read_file('./shapefiles/administraciones_zonales.shp')
</code>```

Simple as that but I keep getting the following error

```<code>CRSError: Invalid projection: epsg:32717: (Internal Proj Error: proj_create: SQLite error on SELECT name, coordinate_system_auth_name, coordinate_system_code, geodetic_crs_auth_name, geodetic_crs_code, conversion_auth_name, conversion_code, area_of_use_auth_name, area_of_use_code, text_definition, deprecated FROM projected_crs WHERE auth_name = ? AND code = ?: no such column: area_of_use_auth_name)
</code>```

This are my versions

```<code>print(sys.version)
3.8.12 (default, Oct 12 2021, 03:01:40) [MSC v.1916 64 bit (AMD64)]
import pyproj
print(pyproj.__version__)
2.6.1.post1
import geopandas
print(geopandas.__version__)
0.9.0
</code>```

Is there anyway to fix this error, I have been trying everything!.

答:
have downloaded shape file from here https://hub.arcgis.com/datasets/esrimarketing::administraciones-zonales/explore?location=-0.167571%2C-78.559309%2C10.38

it is epsg:4326,  but then projected to epsg:32717.  No issues

your pyproj and geopandas versions are a bit outdated.  Your error primarily points to an issue with pyproj

```<code>from pathlib import Path
import geopandas as gpd

gdf = gpd.read_file(list(Path.home().joinpath("Downloads").glob("**/Administraciones_Zonales.shp"))[0])
gdf.to_crs("epsg:32717").explore()
</code>```

versions

```<code>import pyproj, sys
print(gpd.__version__, pyproj.__version__, sys.version)
</code>```
```<code>0.10.2 3.3.0 3.9.10 (main, Jan 15 2022, 11:48:00)
[Clang 13.0.0 (clang-1300.0.29.3)]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I´m trying to read a shapefile with geopandas

Quito_full =gpd.read_file('./shapefiles/administraciones_zonales.shp')

Simple as that but I keep getting the following error

CRSError: Invalid projection: epsg:32717: (Internal Proj Error: proj_create: SQLite error on SELECT name, coordinate_system_auth_name, coordinate_system_code, geodetic_crs_auth_name, geodetic_crs_code, conversion_auth_name, conversion_code, area_of_use_auth_name, area_of_use_code, text_definition, deprecated FROM projected_crs WHERE auth_name = ? AND code = ?: no such column: area_of_use_auth_name)

This are my versions

print(sys.version)
3.8.12 (default, Oct 12 2021, 03:01:40) [MSC v.1916 64 bit (AMD64)]
import pyproj
print(pyproj.__version__)
2.6.1.post1
import geopandas
print(geopandas.__version__)
0.9.0

Is there anyway to fix this error, I have been trying everything!.

Body:
have downloaded shape file from here https://hub.arcgis.com/datasets/esrimarketing::administraciones-zonales/explore?location=-0.167571%2C-78.559309%2C10.38

it is epsg:4326,  but then projected to epsg:32717.  No issues

your pyproj and geopandas versions are a bit outdated.  Your error primarily points to an issue with pyproj

from pathlib import Path
import geopandas as gpd

gdf = gpd.read_file(list(Path.home().joinpath("Downloads").glob("**/Administraciones_Zonales.shp"))[0])
gdf.to_crs("epsg:32717").explore()

versions

import pyproj, sys
print(gpd.__version__, pyproj.__version__, sys.version)

0.10.2 3.3.0 3.9.10 (main, Jan 15 2022, 11:48:00)
[Clang 13.0.0 (clang-1300.0.29.3)]


问:
How to close shiny modal box after clicking on downloadButton
I have an actionButton that, when clicked, opens a modal dialog box that offers a small message, and gives user an opportunity to download data or cancel. When clicking on the download button, the downloadHandler is appropriately triggered, and data downloads successfully. However, I don't know where/how to include removeModal().  I want the pop up modal dialog box to automatically close when the downloadButton is clicked.

```<code>library(shiny)
library(data.table)

data = data.frame(x=rnorm(10),y=rnorm(10))

get_download_handler <- function(fname, data) {
  downloadHandler(
    filename = function() paste0(fname, '.csv'),
    content = function(con) data.table::fwrite(data, con)
  )
}

ui <- fluidPage(
  actionButton(inputId = "dwnld",label = "Download Data")
)

server <- function(input, output, session) {
  observeEvent(input$dwnld, {
    showModal(modalDialog(
      title="Download",
      "<Disclaimer Text>",
      footer = tagList(
        downloadButton(outputId = "dwnld_data","Download Data"),
        modalButton("Cancel")
      ),easyClose = TRUE
    ))
  })

  output$dwnld_data <-get_download_handler(fname="data",data)
}

shinyApp(ui, server)
</code>```

答:
You can do like this:</p>
```<code>library(shiny)
library(data.table)

data = data.frame(x = rnorm(10), y = rnorm(10))

ui <- fluidPage(
  actionButton(inputId = "dwnld", label = "Download Data")
)

server <- function(input, output, session) {
  observeEvent(input$dwnld, {
    showModal(modalDialog(
      title = "Download",
      "<Disclaimer Text>",
      footer = tagList(
        downloadButton(outputId = "dwnld_data", "Download Data"),
        modalButton("Cancel")
      ),
      easyClose = TRUE
    ))
  })

  output$dwnld_data <- downloadHandler(
    filename = "data.csv",
    content = function(con){
      on.exit(removeModal())
      data.table::fwrite(data, con)
    }
  )
}

shinyApp(ui, server)
</code>```

Body:
I have an actionButton that, when clicked, opens a modal dialog box that offers a small message, and gives user an opportunity to download data or cancel. When clicking on the download button, the downloadHandler is appropriately triggered, and data downloads successfully. However, I don't know where/how to include removeModal().  I want the pop up modal dialog box to automatically close when the downloadButton is clicked.

library(shiny)
library(data.table)

data = data.frame(x=rnorm(10),y=rnorm(10))

get_download_handler <- function(fname, data) {
  downloadHandler(
    filename = function() paste0(fname, '.csv'),
    content = function(con) data.table::fwrite(data, con)
  )
}

ui <- fluidPage(
  actionButton(inputId = "dwnld",label = "Download Data")
)

server <- function(input, output, session) {
  observeEvent(input$dwnld, {
    showModal(modalDialog(
      title="Download",
      "<Disclaimer Text>",
      footer = tagList(
        downloadButton(outputId = "dwnld_data","Download Data"),
        modalButton("Cancel")
      ),easyClose = TRUE
    ))
  })

  output$dwnld_data <-get_download_handler(fname="data",data)
}

shinyApp(ui, server)

Body:
You can do like this:

library(shiny)
library(data.table)

data = data.frame(x = rnorm(10), y = rnorm(10))

ui <- fluidPage(
  actionButton(inputId = "dwnld", label = "Download Data")
)

server <- function(input, output, session) {
  observeEvent(input$dwnld, {
    showModal(modalDialog(
      title = "Download",
      "<Disclaimer Text>",
      footer = tagList(
        downloadButton(outputId = "dwnld_data", "Download Data"),
        modalButton("Cancel")
      ),
      easyClose = TRUE
    ))
  })

  output$dwnld_data <- downloadHandler(
    filename = "data.csv",
    content = function(con){
      on.exit(removeModal())
      data.table::fwrite(data, con)
    }
  )
}

shinyApp(ui, server)


问:
How to read and merge only the second sheet from a number of excel files (xlsm) in R?
I have a working directory with a large number of xlsm files (600ish). I need to merge all of these files into one dataframe, but ONLY the second sheet of the excel file. Since there are a lot of files, ideally I would use a loop, but I'm struggling with how to do this. Right now I have this code, which is obviously not working. Any thoughts on how to best do this would be greatly appreciated.

```<code>library(readxl)
library(tidyverse)

data.files = list.files(pattern = "*.xlsm")

data_to_merge <- lapply(data.files, read_excel(x, sheet = 2))

combined_df <- bind_rows(data_to_merge)
</code>```

Not sure how to include examples of the data so it's easily reproducible since my question is dealing with excel sheets, not data that's already in r, but if this is useful, all of the 2nd sheets have the same simple structure that looks something like this:

```<code>data1 <- data.frame(id = 1:6,
                    x1 = c(5, 1, 4, 9, 1, 2),
                    x2 = c("A", "Y", "G", "F", "G", "Y"))

data2 <- data.frame(id = 4:9,
                    y1 = c(3, 3, 4, 1, 2, 9),
                    y2 = c("a", "x", "a", "x", "a", "x"))
</code>```

答:
You were close. You just need to slightly alter your lapply statement, so that the function and parameter are separated by a column.

```<code>library(readxl)
library(tidyverse)

data.files = list.files(pattern = "*.xlsm")

data_to_merge <- lapply(data.files, read_excel, sheet = 2)

combined_df <- bind_rows(data_to_merge)
</code>```

Or a more tidyverse approach:

```<code>combined_df <- list.files(pattern = "*.xlsm") %>%
  map(., ~ read_excel(.x, sheet = 2)) %>%
  bind_rows()
</code>```

Body:
I have a working directory with a large number of xlsm files (600ish). I need to merge all of these files into one dataframe, but ONLY the second sheet of the excel file. Since there are a lot of files, ideally I would use a loop, but I'm struggling with how to do this. Right now I have this code, which is obviously not working. Any thoughts on how to best do this would be greatly appreciated.

library(readxl)
library(tidyverse)

data.files = list.files(pattern = "*.xlsm")

data_to_merge <- lapply(data.files, read_excel(x, sheet = 2))

combined_df <- bind_rows(data_to_merge)

Not sure how to include examples of the data so it's easily reproducible since my question is dealing with excel sheets, not data that's already in r, but if this is useful, all of the 2nd sheets have the same simple structure that looks something like this:

data1 <- data.frame(id = 1:6,
                    x1 = c(5, 1, 4, 9, 1, 2),
                    x2 = c("A", "Y", "G", "F", "G", "Y"))

data2 <- data.frame(id = 4:9,
                    y1 = c(3, 3, 4, 1, 2, 9),
                    y2 = c("a", "x", "a", "x", "a", "x"))

Body:
You were close. You just need to slightly alter your lapply statement, so that the function and parameter are separated by a column.

library(readxl)
library(tidyverse)

data.files = list.files(pattern = "*.xlsm")

data_to_merge <- lapply(data.files, read_excel, sheet = 2)

combined_df <- bind_rows(data_to_merge)

Or a more tidyverse approach:

combined_df <- list.files(pattern = "*.xlsm") %>%
  map(., ~ read_excel(.x, sheet = 2)) %>%
  bind_rows()


问:
AS3 Dynamic class that only accepts a given type
Is it possible to make a dynamic class in AS3 only accept dynamically created properties if they're a given type?

For example, I may only want Sprites to be allowed. So take this quick example class:

```<code>public dynamic class Test extends Object{}
</code>```

-------

And a few quick lines to get an idea of what I mean:

```<code>var test:Test = new Test();

test.something = 32; // error
test.something = "party hats"; // error
test.something = new Sprte(); // works
</code>```

Maybe using the proxy class/namespsace there's a way to manipulate whatever is run when creating variables dynamically?

答:
The Test class:

```<code>package classes {
    import flash.display.Sprite;
    import flash.utils.Proxy;
    import flash.utils.flash_proxy;

    public dynamic class Test extends Proxy {
        private var _properties : Object;

        public function Test() {
            _properties = new Object();
        }

        override flash_proxy function getProperty(name : *) : * {
            return _properties[name];
        }

        override flash_proxy function setProperty(name:*, value:*):void {
            if (!(value is Sprite)) throw new Error("No Sprite given: " + value);
            _properties[name] = value;
        }
    }
}
</code>```

The App:

```<code>package classes {
    import flash.display.Sprite;

    public class TestTest extends Sprite {
        public function TestTest() {
            var test:Test = new Test();

            try {
                test.something = 32; // error
            } catch (e : Error) {
                trace (e);
            }

            try {
                test.something = new Sprite(); // works
            } catch (e : Error) {
                trace (e);
            }

            trace (test.something);
        }
    }
}
</code>```

The output:

```<code>Error: No Sprite given: 32
[object Sprite]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Is it possible to make a dynamic class in AS3 only accept dynamically created properties if they're a given type?

For example, I may only want Sprites to be allowed. So take this quick example class:

public dynamic class Test extends Object{}

-------

And a few quick lines to get an idea of what I mean:

var test:Test = new Test();

test.something = 32; // error
test.something = "party hats"; // error
test.something = new Sprte(); // works

Maybe using the proxy class/namespsace there's a way to manipulate whatever is run when creating variables dynamically?

Body:
The Test class:

package classes {
    import flash.display.Sprite;
    import flash.utils.Proxy;
    import flash.utils.flash_proxy;

    public dynamic class Test extends Proxy {
        private var _properties : Object;

        public function Test() {
            _properties = new Object();
        }

        override flash_proxy function getProperty(name : *) : * {
            return _properties[name];
        }

        override flash_proxy function setProperty(name:*, value:*):void {
            if (!(value is Sprite)) throw new Error("No Sprite given: " + value);
            _properties[name] = value;
        }
    }
}

The App:

package classes {
    import flash.display.Sprite;

    public class TestTest extends Sprite {
        public function TestTest() {
            var test:Test = new Test();

            try {
                test.something = 32; // error
            } catch (e : Error) {
                trace (e);
            }

            try {
                test.something = new Sprite(); // works
            } catch (e : Error) {
                trace (e);
            }

            trace (test.something);
        }
    }
}

The output:

Error: No Sprite given: 32
[object Sprite]


问:
how to get the mac Address , user , through an end-point request
I have a controller that when accessing it I need to get the ip, user, macAdress information that are accessing this new end-point. I have the code below and I would like to get this other information I need. Can you help me?</p>
```<code>@RequestMapping(value = "/account", method = RequestMethod.GET)
public String getIp(HttpServletRequest request) {

    String ipAddress = request.getHeader("X-FORWARDED-FOR");
    if (ipAddress == null) {
        ipAddress = request.getRemoteAddr();
    }

    return "page";
}
</code>```

答:
As you can see from the image below, a Network Layer packet does not contain fields for transporting the information you are asking about.

However, nothing stops you from putting this information on the payload. You could, for instance, establish a format for messages exchanged between applications where the sender's MAC address and the signed-in username is stored. The receiver could then extract this information from the payload.

I think you should be able to do something like this:

```<code>{
  "metadata":
  {
    "username" : "hector",
    "mac" : "00:00:00:00:00:00"
  },
  "payload" : {-WHATEVER YOU'RE SENDING HERE-}
}
</code>```

In XML

```<code><?xml version="1.0" encoding="UTF-8" ?>
<metadata>
    <username>hector</username>
    <mac>00:00:00:00:00:00</mac>
</metadata>
<payload>...</payload>
</code>```

Body:
I have a controller that when accessing it I need to get the ip, user, macAdress information that are accessing this new end-point. I have the code below and I would like to get this other information I need. Can you help me?

@RequestMapping(value = "/account", method = RequestMethod.GET)
public String getIp(HttpServletRequest request) {

    String ipAddress = request.getHeader("X-FORWARDED-FOR");
    if (ipAddress == null) {
        ipAddress = request.getRemoteAddr();
    }

    return "page";
}

Body:
As you can see from the image below, a Network Layer packet does not contain fields for transporting the information you are asking about.

However, nothing stops you from putting this information on the payload. You could, for instance, establish a format for messages exchanged between applications where the sender's MAC address and the signed-in username is stored. The receiver could then extract this information from the payload.

I think you should be able to do something like this:

{
  "metadata":
  {
    "username" : "hector",
    "mac" : "00:00:00:00:00:00"
  },
  "payload" : {-WHATEVER YOU'RE SENDING HERE-}
}

In XML

<?xml version="1.0" encoding="UTF-8" ?>
<metadata>
    <username>hector</username>
    <mac>00:00:00:00:00:00</mac>
</metadata>
<payload>...</payload>


问:
Getting unresolved external symbol errors for libcurl_a.lib in VC++
I have a project in VC++ where I am using libcurl library. Even after adding the library in Additional Dependencies I am facing around 150 unresolved external errors, all majorly for libcurl_a.lib file.</p>
```<code>Error -
1>OLDNAMES.lib(open.obi): warning LNK4049: locally defined symbol open imported

1>libcurl_a.lib(mime.obj): error LNK2019: unresolved external symbol imp__feof referenced
1>libcurl_a.lib(mime.obj): error LNK2019: unresolved external symbol imp_access referenced in function Curl_mime_duppart in function _read_part content
1>OLDNAMES.lib(access.obi): error LNK2001: unresolved external symbol imp access
1>libcurl_a.lib(mime.obj): error LNK2019: unresolved external symbolimp_ stat64 referenced in function Curl_nine duppart 1>libcurl_a.lib(strerror.obj): error LNK2019: unresolved external symbolimp_strerror referenced in function Curl strerror
1>libcurl_a.lib(url.obj): error LNK2001: unresolved external symbol imp_strerror
1>1ibcurl_a.lib(telnet.obj): error LNK2001: unresolved external symbol imp_strncpy
1>1ibcurl_a.lib(ftp.obj): error LNK2001: unresolved external symbolimp_strncpy
1>libcurl_alib(curl_sspi.obj): error LNK2001: unresolved external symbolimp_strncpy
1>1ibcurl_s.lib(strerror.obj): error LNK2001: unresolved external symbolimp_strncpy
1>1ibcurl_a.lib(vtis.obj): error LNK2001: unresolved external symbol imp_strncpy 1>1ibcurl_.1ib(url.obj): error LNK2001: unresolved external symbolimp_strncpy
1>libcurl_a.lib(schannel.obj) error LNK 2001: unresolved external symbol_imp_strncpy
1>libcuri_a.lip(strerror.obj) : error LNK2019: unresolved external symbol imp sys_nerr referenced in function Curi strerror
1>libcurl_a.lib(warnless.obj): error LNK2019: unresolved external symbol 1 OLDNAMES1ib(read.obi): error LNK2001: unresolved external symbolimp_read imp_read referenced in function curl_read
111bcurt a.lib/warmless.obj) error LNK2019: unresolved external symbol_imp_write referenced in function curl, weite

1 OLDNAMES-110(write.obi): error LNK2001: unresolved external symbolimp_write
</code>```

答: I have solved this problem by building the library with RTLIBCFG=static option.

Body:
I have a project in VC++ where I am using libcurl library. Even after adding the library in Additional Dependencies I am facing around 150 unresolved external errors, all majorly for libcurl_a.lib file.

Error -
1>OLDNAMES.lib(open.obi): warning LNK4049: locally defined symbol open imported

1>libcurl_a.lib(mime.obj): error LNK2019: unresolved external symbol imp__feof referenced
1>libcurl_a.lib(mime.obj): error LNK2019: unresolved external symbol imp_access referenced in function Curl_mime_duppart in function _read_part content
1>OLDNAMES.lib(access.obi): error LNK2001: unresolved external symbol imp access
1>libcurl_a.lib(mime.obj): error LNK2019: unresolved external symbolimp_ stat64 referenced in function Curl_nine duppart 1>libcurl_a.lib(strerror.obj): error LNK2019: unresolved external symbolimp_strerror referenced in function Curl strerror
1>libcurl_a.lib(url.obj): error LNK2001: unresolved external symbol imp_strerror
1>1ibcurl_a.lib(telnet.obj): error LNK2001: unresolved external symbol imp_strncpy
1>1ibcurl_a.lib(ftp.obj): error LNK2001: unresolved external symbolimp_strncpy
1>libcurl_alib(curl_sspi.obj): error LNK2001: unresolved external symbolimp_strncpy
1>1ibcurl_s.lib(strerror.obj): error LNK2001: unresolved external symbolimp_strncpy
1>1ibcurl_a.lib(vtis.obj): error LNK2001: unresolved external symbol imp_strncpy 1>1ibcurl_.1ib(url.obj): error LNK2001: unresolved external symbolimp_strncpy
1>libcurl_a.lib(schannel.obj) error LNK 2001: unresolved external symbol_imp_strncpy
1>libcuri_a.lip(strerror.obj) : error LNK2019: unresolved external symbol imp sys_nerr referenced in function Curi strerror
1>libcurl_a.lib(warnless.obj): error LNK2019: unresolved external symbol 1 OLDNAMES1ib(read.obi): error LNK2001: unresolved external symbolimp_read imp_read referenced in function curl_read
111bcurt a.lib/warmless.obj) error LNK2019: unresolved external symbol_imp_write referenced in function curl, weite

1 OLDNAMES-110(write.obi): error LNK2001: unresolved external symbolimp_write


问:
kustomize and kubectl not finding CRDs
I'm using kustomize to pipe a manifest to kubectl on a new k8s cluster (v1.17.2). This includes CRDs, but other objects are unable to find them. For example:

```<code>unable to recognize "STDIN": no matches for kind "Certificate" in version "cert-manager.io/v1alpha2"
unable to recognize "STDIN": no matches for kind "IngressRoute" in version "traefik.containo.us/v1alpha1"
</code>```

The CRDs are defined in the resources section of my kubectl, they show in the output which I'm piping to kubectl, and I'm sure this approach of putting everything in one file worked last time I did it.

If I apply the CRDs first, then apply the main manifest separately, it all goes through without a problem. Can I do them all at the same time? If so, what am I doing wrong; if not, why did it work before?

Can anyone point me at where the problem may lie?

Sample CRD definition:

```<code>apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
  name: ingressroutetcps.traefik.containo.us
spec:
  group: traefik.containo.us
  names:
    kind: IngressRouteTCP
    plural: ingressroutetcps
    singular: ingressroutetcp
  scope: Namespaced
  version: v1alpha1
</code>```

答:
I solved this problem by using Skaffold and deploying all my CRDs with kubectl:

deploy:
  kubectl:
    manifests:
    - custom_resources.yaml
  kustomize:
    paths:
    - kustomize_directory
```

Title: kustomize and kubectl not finding CRDs

Body:
I'm using kustomize to pipe a manifest to kubectl on a new k8s cluster (v1.17.2). This includes CRDs, but other objects are unable to find them. For example:

unable to recognize "STDIN": no matches for kind "Certificate" in version "cert-manager.io/v1alpha2"
unable to recognize "STDIN": no matches for kind "IngressRoute" in version "traefik.containo.us/v1alpha1"

The CRDs are defined in the resources section of my kubectl, they show in the output which I'm piping to kubectl, and I'm sure this approach of putting everything in one file worked last time I did it.

If I apply the CRDs first, then apply the main manifest separately, it all goes through without a problem. Can I do them all at the same time? If so, what am I doing wrong; if not, why did it work before?

Can anyone point me at where the problem may lie?

Sample CRD definition:

apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
  name: ingressroutetcps.traefik.containo.us
spec:
  group: traefik.containo.us
  names:
    kind: IngressRouteTCP
    plural: ingressroutetcps
    singular: ingressroutetcp
  scope: Namespaced
  version: v1alpha1


问:
Select with different conditions on multiple different fields of a single table
hello i want something like the fallowing (without using sub queries):

```<code>select planName where period=1 as 1stPlan
select planName where period=2 as 2ndPlan
select planName where period=3 as 3ndPlan
...
FROM plan inner join project ON Project.Id=Plan.ProjectId
</code>```

thank you

答:
```<code>select
  plan1.planName,
  plan2.planName,
  plan3.planName
FROM project
  left join plan plan1 ON Project.Id=Plan1.ProjectId and Plan1.period=1
  left join plan plan2 ON Project.Id=Plan2.ProjectId and Plan2.period=2
  left join plan plan3 ON Project.Id=Plan3.ProjectId and Plan3.period=3
</code>```

Body:
hello i want something like the fallowing (without using sub queries):

select planName where period=1 as 1stPlan
select planName where period=2 as 2ndPlan
select planName where period=3 as 3ndPlan
...
FROM plan inner join project ON Project.Id=Plan.ProjectId

thank you


问:
Manipulating file content in rails application
I'm not a security expert. I'm working on a rails application where the user needs to upload a txt file to the app. The app doesn't store the file but reads its content and saves some of it in the database. Is it safe or not? If not is there a way to secure this like preventing the users from uploading txt files with malicious content?</p>

答:
You're rightly concerned about the possibility of a so-called injection attack.

The Rails Guide "Securing Rails Applications" is very thorough and has a section specifically on preventing various types of injection attacks.


问:
Print Value from Key and Value in one list in a new empty list based on matching elements
Logic Behind Problem:
When building a route you need two steps in order to perform a direction. For example if you go from Step1 to Step2 that is right. But Step1 to Step3 is left. The steps need to be in pairs in order to determine direction.

Issue:
I have a function that produces a 'Direction' based on a pair of elements in 'StepName'. If a routes 'StepName' pair is already defined with 'Direction' it should be able to produce the same 'Direction' in another route dictionary if it contains the same pair of elements in a sequence of pairs. Doesn't matter at what index the pair is located in the list

For example:

104-1 to 104-2 produces 'Left' in 'Direction'

104-2 to 105-A produces 'Right' in 'Direction'

105-A to 105-D produces 'Right' in 'Direction'

Code:

```<code>route1 = {
    'RouteID': 1,
    'StepID': [1, 2, 3, 4],
    'StepName': ['104-1', '104-2', '105-A', '105-D'],
    'Direction': ['Left', 'Right', 'Right']}

route2 = {
    'RouteID': 2,
    'StepID': [1, 2, 3, 4],
    'StepName': ['104-2', '105-A', '105-C', '105-B'],
    'Direction': []}

def routeMapper(longRoute, subRoute):
    for i, v in enumerate(subRoute['StepName']):
        found = False
        for j, b in enumerate(longRoute['StepName']):
            if v == b:
                found = True
                subRoute['Direction'].append(longRoute['Direction'][j])
        if not found:
            subRoute['Direction'].append(False)

routeMapper(route1, route2)
print(route2)
</code>```

Output:

```<code>{'RouteID': 2, 'StepID': [1, 2, 3, 4], 'StepName': ['104-2', '105-A', '105-C', '105-B'], 'Direction': ['Right', 'Right', False, False]}
</code>```

As you can see it is comparing what each index element direction it is assigned to. I want it to be seen in pairs instead of single.

Desired Output: (for 'Direction')

```<code>{'RouteID': 2, 'StepID': [1, 2, 3, 4], 'StepName': ['104-2', '105-A', '105-C', '105-B'], 'Direction': ['Right', False, False, False]}
</code>```

The reason this output makes sense is because in route1 104-2 to 105-A produces 'Right' even though it is 1 and 2 in the index as a pair compared to it being at the 0 and 1 index in route2. As long as the pair is found in the list it should be able to produce the direction.

答:
I first created a list named pair1 that will keep hold of i & i+1 elements from the subRoute's StepName in the first loop. I've also done the same to the longRoute in the second loop. Then if the first element of each pair and both of the pairs match, the function will append the direction of that pair's. If not, it will append False.  (I had to restructure the loops to make this work)

def routeMapper(longRoute, subRoute):
    for i in range(len(subRoute['StepName']) - 1):
        found = False
        pair1 = [subRoute['StepName'][i], subRoute['StepName'][i+1]]
        for j in range(len(longRoute['StepName']) - 1):
            pair2 = [longRoute['StepName'][j], longRoute['StepName'][j+1]]
            if pair1[0]==pair2[0] and pair1 == pair2:
                found = True
                subRoute['Direction'].append(longRoute['Direction'][j])
        if not found:
                subRoute['Direction'].append(False)

    #Output: {'RouteID': 2, 'StepID': [1, 2, 3, 4], 'StepName': ['104-2', '105-A', '105-C', '105-B'], 'Direction': ['Right', False, False]}
```

Body:
Logic Behind Problem:
When building a route you need two steps in order to perform a direction. For example if you go from Step1 to Step2 that is right. But Step1 to Step3 is left. The steps need to be in pairs in order to determine direction.

Issue:
I have a function that produces a 'Direction' based on a pair of elements in 'StepName'. If a routes 'StepName' pair is already defined with 'Direction' it should be able to produce the same 'Direction' in another route dictionary if it contains the same pair of elements in a sequence of pairs. Doesn't matter at what index the pair is located in the list

For example:

104-1 to 104-2 produces 'Left' in 'Direction'

104-2 to 105-A produces 'Right' in 'Direction'

105-A to 105-D produces 'Right' in 'Direction'

Code:

route1 = {
    'RouteID': 1,
    'StepID': [1, 2, 3, 4],
    'StepName': ['104-1', '104-2', '105-A', '105-D'],
    'Direction': ['Left', 'Right', 'Right']}

route2 = {
    'RouteID': 2,
    'StepID': [1, 2, 3, 4],
    'StepName': ['104-2', '105-A', '105-C', '105-B'],
    'Direction': []}

def routeMapper(longRoute, subRoute):
    for i, v in enumerate(subRoute['StepName']):
        found = False
        for j, b in enumerate(longRoute['StepName']):
            if v == b:
                found = True
                subRoute['Direction'].append(longRoute['Direction'][j])
        if not found:
            subRoute['Direction'].append(False)

routeMapper(route1, route2)
print(route2)

Output:

{'RouteID': 2, 'StepID': [1, 2, 3, 4], 'StepName': ['104-2', '105-A', '105-C', '105-B'], 'Direction': ['Right', 'Right', False, False]}

As you can see it is comparing what each index element direction it is assigned to. I want it to be seen in pairs instead of single.

Desired Output: (for 'Direction')

{'RouteID': 2, 'StepID': [1, 2, 3, 4], 'StepName': ['104-2', '105-A', '105-C', '105-B'], 'Direction': ['Right', False, False, False]}

The reason this output makes sense is because in route1 104-2 to 105-A produces 'Right' even though it is 1 and 2 in the index as a pair compared to it being at the 0 and 1 index in route2. As long as the pair is found in the list it should be able to produce the direction.


问:
what is onChange={(e) => setName(e.target.value)}? in React mean
I am new to React;I am learning about React Form. I understand the code but I do not really understand the concept behind and why we use this line "  onChange={(e) => setName(e.target.value)}".

Thank you for your help.

They used this example:

```<code>import ReactDOM from 'react-dom';

function MyForm() {
  const [name, setName] = useState("");

  const handleSubmit = (event) => {
    event.preventDefault();
    alert(`The name you entered was: ${name}`)
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>Enter your name:
        <input
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
        />
      </label>
      <input type="submit" />
    </form>
  )
}

ReactDOM.render(<MyForm />, document.getElementById('root'));
</code>```

答:
You have two different things happening here.

Event (e)

First you have e which is short for event. To understand what it does change onChange={(e) => setName(e.target.value)} to onChange={(e) => console.log(e)}. Inspect the log and you'll find a list of events in which one of them is target. Open target (if not already opened) and within target, you'll find value. In short, this is the target value that's being typed in your input, it's what the user is typing.

useState

Your using state to track the value in your input. So [name] is the getter and [setName] is the setter. If you notice in your alert you have alert(The name you entered was: ${name}). The variable name is the getter which means it holds the current value of the state. On the other hand setName will set that value. It's able to do so because you're setting and tracking the value here on change onChange={(e) => setName(e.target.value)}.

Body:
I am new to React;I am learning about React Form. I understand the code but I do not really understand the concept behind and why we use this line "  onChange={(e) => setName(e.target.value)}".

Thank you for your help.

They used this example:

import ReactDOM from 'react-dom';

function MyForm() {
  const [name, setName] = useState("");

  const handleSubmit = (event) => {
    event.preventDefault();
    alert(`The name you entered was: ${name}`)
  }

  return (
    <form onSubmit={handleSubmit}>
      Enter your name:
        <input
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
        />

      <input type="submit" />
    </form>
  )
}

ReactDOM.render(<MyForm />, document.getElementById('root'));


问:
The argument type 'void Function(int)' can't be assigned to the parameter type 'void Function(int?)?'
Hello for all I have problem so I want to best solution for this code
enter image description here

It shows The argument type

'void Function(int)' can't be assigned to the parameter type 'void Function(int?)?'.

答:
This is null safety error

define color variable like this:

```<code>int? color;
</code>```

also change the following lines to this:

```<code>int? newColor;
saveColor(newColor!);
</code>```

for more info about null safety:
https://dart.dev/null-safety

Body:
This is null safety error

define color variable like this:

int? color;

also change the following lines to this:

int? newColor;
saveColor(newColor!);

for more info about null safety:
https://dart.dev/null-safety


问:
Web components and shared styles
This is one of those "what should we do about this"-questions. As you know, web components are supposed to be small, contained applications for websites. However, sometimes these needs to be styled depending on the site they're embedded on.

Example: "Sign up to our newsletter"-component. This component would have a few key items:

An input box

A button

Maybe recaptcha

A method that talks to your service once the button is pressed (passing in the email)

We're going to use Google and YouTube as examples. Google's color scheme is blue (let's imagine that) and YouTube's color scheme is red. The component would then be something like <newsletter-signup></newsletter-signup> on the page you're embedding it in. Both Google and YouTube have this.

The problem comes in, when the component needs to inherit the styles from Google and YouTube. A few deprecated CSS selectors would be great for this, because Google and YouTube's style sheets could simply enable colors for the Shadow DOM, so we wouldn't have to copy/paste the styles. The component should theoretically not know anything about the styles from the host, because we want it to inherit from the host (Google and YouTube).

At the moment, I'm creating a web component using Angular 6, which has a lot of styles, because it has a lot of elements. I'm copy/pasting styles, Bootstrap, icons, and so on from the host site, then styling them based on <newsletter-signup brand="google"></newsletter-signup>. So if the brand is Google, the colors should be red, for example.

This is really bad, because of a few reasons:

Styles have to be updated on both the web component and on the host

Duplicated code is never a good idea

If all the styles are copied 1:1, the amount of bytes required for styles is doubled

How would I, as a developer, take this into account? How do I make styles on the host, then apply them on my web component (call it inheritance)? I'm sure someone has had the exact same problem with Shadow DOM as I am experiencing. Thanks for reading.

答:
This question is a few years old and the situation has changed. The way to share styles with web components is now to use link tags to a shared stylesheet.

Inside each component:

```<code><link rel="stylesheet" href="https://my-host.com/styles/core.css">
</code>```

Reference:
https://github.com/WICG/webcomponents/issues/628

Title: Web components and shared styles

Body:
This question is a few years old and the situation has changed. The way to share styles with web components is now to use link tags to a shared stylesheet.

Inside each component:

<link rel="stylesheet" href="https://my-host.com/styles/core.css">

Reference:
https://github.com/WICG/webcomponents/issues/628


问:
Extract inline CSS from HTML and purify pages
I have a large set (over 300) of C# ASP.NET pages *.aspx and controls *.ascx, which are littered with inline CSS styles. My task is to extract those style into a CSS file.

So I'm looking for a tool to simplify the task of manually extracting this inline styles and replacing them with class="" statements.

Now I know this is not the ideal solution of doing things, but any tool which could ease the task would be helpful.

答: You can use this tool, it will look for inline style=... definitions replace them with class definitions and generate a style sheet. Hope this is helpful. </p>

ContentLicense: CC BY-SA 2.5


问:
flutter for loop return first id only how to fix
dart file

```<code> List<Widget> getplans() {
    List<Widget> plans = planController.plansList
        .map((e) {
          var index = e.selectSubCategory.length;
          for (int i = 0; i < index; i++) {
            var subcategorName = e.selectSubCategory[i].subcategorName;
            var details = e.selectSubCategory[i].details;

            return Stack(
              alignment: Alignment.center,
              children: [
                Container(
                  child: Text(subcategorName),
                  padding: EdgeInsets.all(16),
                  decoration: BoxDecoration(
                    color: Colors.red,
                    borderRadius: BorderRadius.circular(20),
                  ),
                  width: 350,
                  height: 200,
                ),
                Positioned(
                  bottom: 10,
                  right: 20,
                  left: 20,
                  child: Container(
                    height: 140,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(20),
                    ),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        Text(details),
                        InkWell(
                          onTap: () {},
                          child: Container(
                            decoration: BoxDecoration(
                              color: Colors.red,
                              borderRadius: BorderRadius.circular(10),
                            ),
                            alignment: Alignment.center,
                            width: 150,
                            margin: EdgeInsets.only(bottom: 10),
                            padding: EdgeInsets.symmetric(vertical: 10),
                            child: GestureDetector(
                              onTap: () {
                                Get.to(() => FormsScreen(), arguments: e.id);
                              },
                              child: const Text(
                                'SELECT',
                                style: TextStyle(
                                    fontSize: 16,
                                    fontWeight: FontWeight.bold,
                                    color: Colors.white),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            );
          }
        })
        .cast<Widget>()
        .toList();

    return plans;
  }
}

</code>```

api response

```<code>[
    {
        "id": 1,
        "title": "Category 1",
        "select_sub_category": [
            {
                "id": 1,
                "subcategor_name": "Sucategory 1",
                "details": "Sucategory 1"
            },
            {
                "id": 3,
                "subcategor_name": "Sucategory 1.1",
                "details": "Sucategory 1.1"
            }
        ]
    }
]
</code>```

here select_sub_category contain 2 data

```<code> {
                "id": 1,
                "subcategor_name": "Sucategory 1",
                "details": "Sucategory 1"
            },
            {
                "id": 3,
                "subcategor_name": "Sucategory 1.1",
                "details": "Sucategory 1.1"
            }
</code>```

but the output return only

```<code>{
               "id": 1,
               "subcategor_name": "Sucategory 1",
               "details": "Sucategory 1"
           }
</code>```

**details only but i want to get all data how to fix this **

**here select_sub_category contain 2 data id:1,id:3 but the out put return only id:1 details ony but i want to get all data how to fix this ****here select_sub_category contain 2 data id:1,id:3 but the out put return only id:1 details ony but i want to get all data how to fix this **

答:
If you use the 'return' statement, the loop is broken. That's why you can't get to the ones after the first statement. I made an example for you, it should work correctly.

List<Widget> getplans() {
  List<Widget> result = [];

  for (final plan in planController.plansList) {
    for (final category in plan.selectSubCategory) {
      final subCategoryName = category.subcategorName;
      final details = category.details;

      result.add(
        Stack(
          alignment: Alignment.center,
          children: [
            Container(
              child: Text(subCategoryName),
              padding: EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.red,
                borderRadius: BorderRadius.circular(20),
              ),
              width: 350,
              height: 200,
            ),
            Positioned(
              bottom: 10,
              right: 20,
              left: 20,
              child: Container(
                height: 140,
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(20),
                ),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Text(details),
                    InkWell(
                      onTap: () {},
                      child: Container(
                        decoration: BoxDecoration(
                          color: Colors.red,
                          borderRadius: BorderRadius.circular(10),
                        ),
                        alignment: Alignment.center,
                        width: 150,
                        margin: EdgeInsets.only(bottom: 10),
                        padding: EdgeInsets.symmetric(vertical: 10),
                        child: GestureDetector(
                          onTap: () {
                            Get.to(() => FormsScreen(), arguments: e.id);
                          },
                          child: const Text(
                            'SELECT',
                            style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: Colors.white),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      );
    }
  }

  return result;
}
```

Body:
dart file

 List<Widget> getplans() {
    List<Widget> plans = planController.plansList
        .map((e) {
          var index = e.selectSubCategory.length;
          for (int i = 0; i < index; i++) {
            var subcategorName = e.selectSubCategory[i].subcategorName;
            var details = e.selectSubCategory[i].details;

            return Stack(
              alignment: Alignment.center,
              children: [
                Container(
                  child: Text(subcategorName),
                  padding: EdgeInsets.all(16),
                  decoration: BoxDecoration(
                    color: Colors.red,
                    borderRadius: BorderRadius.circular(20),
                  ),
                  width: 350,
                  height: 200,
                ),
                Positioned(
                  bottom: 10,
                  right: 20,
                  left: 20,
                  child: Container(
                    height: 140,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(20),
                    ),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        Text(details),
                        InkWell(
                          onTap: () {},
                          child: Container(
                            decoration: BoxDecoration(
                              color: Colors.red,
                              borderRadius: BorderRadius.circular(10),
                            ),
                            alignment: Alignment.center,
                            width: 150,
                            margin: EdgeInsets.only(bottom: 10),
                            padding: EdgeInsets.symmetric(vertical: 10),
                            child: GestureDetector(
                              onTap: () {
                                Get.to(() => FormsScreen(), arguments: e.id);
                              },
                              child: const Text(
                                'SELECT',
                                style: TextStyle(
                                    fontSize: 16,
                                    fontWeight: FontWeight.bold,
                                    color: Colors.white),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            );
          }
        })
        .cast<Widget>()
        .toList();

    return plans;
  }
}

api response

[
    {
        "id": 1,
        "title": "Category 1",
        "select_sub_category": [
            {
                "id": 1,
                "subcategor_name": "Sucategory 1",
                "details": "Sucategory 1"
            },
            {
                "id": 3,
                "subcategor_name": "Sucategory 1.1",
                "details": "Sucategory 1.1"
            }
        ]
    }
]

here select_sub_category contain 2 data

 {
                "id": 1,
                "subcategor_name": "Sucategory 1",
                "details": "Sucategory 1"
            },
            {
                "id": 3,
                "subcategor_name": "Sucategory 1.1",
                "details": "Sucategory 1.1"
            }

but the output return only

{
               "id": 1,
               "subcategor_name": "Sucategory 1",
               "details": "Sucategory 1"
           }

**details only but i want to get all data how to fix this **

**here select_sub_category contain 2 data id:1,id:3 but the out put return only id:1 details ony but i want to get all data how to fix this ****here select_sub_category contain 2 data id:1,id:3 but the out put return only id:1 details ony but i want to get all data how to fix this **


问:
Can I use a FormRequest inside another?
Can I use a FormRequest inside another?
Something like:

```<code>class StoreRestaurantRequest extends FormRequest
{
    ....

    public function rules()
    {
        return [
            'name' => 'required',
            'description' => 'required',
            'opening_hours' => new OpeningHoursRequest // -> other FormRequest
        ];
    }
}
</code>```
```<code>class OpeningHoursRequest extends FormRequest
{
    .....

    public function rules()
    {
        return [
            "day" => ['required','integer'],
            "opening_hour" => ['integer',],
            "opening_minute" => ['integer'],
            "closing_hour" => ['integer'],
            "closing_minute" => ['integer'],
        ];
    }
}
</code>```

I am not getting any errors but validation doesn't seem to work.
How can I keep thoose rules seperated?

答: Nope, you shouldn't do like that. I'd use traits for your case</p>

Title: Can I use a FormRequest inside another?

Body:
Can I use a FormRequest inside another?
Something like:

class StoreRestaurantRequest extends FormRequest
{
    ....

    public function rules()
    {
        return [
            'name' => 'required',
            'description' => 'required',
            'opening_hours' => new OpeningHoursRequest // -> other FormRequest
        ];
    }
}

class OpeningHoursRequest extends FormRequest
{
    .....

    public function rules()
    {
        return [
            "day" => ['required','integer'],
            "opening_hour" => ['integer',],
            "opening_minute" => ['integer'],
            "closing_hour" => ['integer'],
            "closing_minute" => ['integer'],
        ];
    }
}

I am not getting any errors but validation doesn't seem to work.
How can I keep thoose rules seperated?


问:
Prometheus Query for 24 hour snapshots
is there a way to query prometheus and return 24hour snapshots of a metric over the course of a week?

Details about the metric:

Name: foo

Type: Gauge

Value: 1

The metric is scraped every minute and the value will vary like so

I want to turn this into something that looks like

Which is taking a rollup of all the values within a 24hour period and creating a single sum'd value for each day.

Is this possible?

Thanks!

答:
This is possible with Prometheus subqueries. For example, the following query should return per-day averages for the metric:

```<code>last_over_time(
  avg_over_time(metric[1d])[1d:1d]
)
</code>```

Note that the returned results will be shifted 1 day forward because Prometheus performs calculations over lookbehind windows in square brackets. This can be fixed by adding offset -1d inside the query:

```<code>last_over_time(
  avg_over_time(metric[1d] offset -1d)[1d:1d]
)
</code>```

Unfortunately the given query with negative offset doesn't work in Prometheus older than v2.33.0. But this query works perfectly in all the versions of VictoriaMetrics - the Prometheus-like monitoring system I work on.

Title: Prometheus Query for 24 hour snapshots

Body:
This is possible with Prometheus subqueries. For example, the following query should return per-day averages for the metric:

last_over_time(
  avg_over_time(metric[1d])[1d:1d]
)

Note that the returned results will be shifted 1 day forward because Prometheus performs calculations over lookbehind windows in square brackets. This can be fixed by adding offset -1d inside the query:

last_over_time(
  avg_over_time(metric[1d] offset -1d)[1d:1d]
)

Unfortunately the given query with negative offset doesn't work in Prometheus older than v2.33.0. But this query works perfectly in all the versions of VictoriaMetrics - the Prometheus-like monitoring system I work on.


问:
Issue to convert the ssl certificates from pfx to peem with openssl
when i try to convert the .pfx certifates to .pem to import to ACM, i get this error

Error outputting keys and certificates
8C2B0000:error:0308010C:digital envelope routines:inner_evp_generic_fetch:unsupported:crypto\evp\evp_fetch.c:346:Global default library context, Algorithm (RC2-40-CBC : 0), Properties ()

the command i run

openssl pkcs12 -in filename.pfx -out filename.pem

答:
If the command used to work in previous OpenSSL versions, try the following:

Ensure you have the legacy library (file named legacy*.<os_lib_ext>, e.g. legacy-x64.dll). Instead of configuring environment variables it may be easier to just copy the library as legacy.<os_lib_ext> (e.g. legacy.dll) in both the libraries path and the path containing openssl executable.

Then add -legacy -provider-path "/path/to/legacy_library/dir" -provider default:

```<code>openssl pkcs12 -in filename.pfx -out filename.pem -legacy -provider-path "/path/to/legacy_library/dir" -provider default
</code>```

Body:
If the command used to work in previous OpenSSL versions, try the following:

Ensure you have the legacy library (file named legacy*.<os_lib_ext>, e.g. legacy-x64.dll). Instead of configuring environment variables it may be easier to just copy the library as legacy.<os_lib_ext> (e.g. legacy.dll) in both the libraries path and the path containing openssl executable.

Then add -legacy -provider-path "/path/to/legacy_library/dir" -provider default:

openssl pkcs12 -in filename.pfx -out filename.pem -legacy -provider-path "/path/to/legacy_library/dir" -provider default


问:
using GD library drawing in php?
the system is window xp.now, i  using  GD library to draw a chart set the font path as this:

```<code>    putenv('GDFONTPATH=c:\windows\Fonts');
    $fontname='arial';
   $bbox=imagettfbbox($font_size,0,$fontname,$button_text);
</code>```

the programme gave me a tip: can't find the font? but in my window xp system, there is a font named arial in the Fonts file. why ?

test code:

```<code> putenv('GDFONTPATH=C:\\WINDOWS\\Fonts');
 $fontname='arial';
$char="test";
$size=20;
$bbox=imagettfbbox($size,0,$fontname,$char);
</code>```

it show invalidate font filename,

答:
On Windows you have to use double backslashes, like so:
putenv('GDFONTPATH=c:\\windows\\Fonts');

Title: using GD library drawing in php?

Body:
the system is window xp.now, i  using  GD library to draw a chart set the font path as this:

    putenv('GDFONTPATH=c:\windows\Fonts');
    $fontname='arial';
   $bbox=imagettfbbox($font_size,0,$fontname,$button_text);

the programme gave me a tip: can't find the font? but in my window xp system, there is a font named arial in the Fonts file. why ?

test code:

 putenv('GDFONTPATH=C:\\WINDOWS\\Fonts');
 $fontname='arial';
$char="test";
$size=20;
$bbox=imagettfbbox($size,0,$fontname,$char);

it show invalidate font filename,


问:
Why can't I vectorize Python's datetime.utcfromtimestamp()?
I have an array of Unix timestamps.  I can run datetime.utcfromtimestamp on each entry individually, but I cannot run them all from a numpy array.  Why does that happen?

MWE

import numpy as np
from datetime import datetime

times = np.array((1524967210, 1524967211, 1524967212))

# Works
for i in times:
    print(datetime.utcfromtimestamp(times[i]))

# Does not work
print(datetime.utcfromtimestamp(times[:]))
```

The second example issues: TypeError: only integer scalar arrays can be converted to a scalar index rather than an array of times.  A Unix timestamp conversion seems straightforward to implement as a vectorized operation (see source code here), so why does it not work here?  Is there something I can do to alter this which will enable vectorized operation?

答:
times is a Numpy array of the numpy module and datetime.utcfromtimestamp is a function of the datetime module. datetime does not support Numpy array and it does not actually have any dependency with Numpy. In fact, because datetime is a [built-in module] of Python 3, having a dependency with Numpy would result in Numpy being a built-in module too! Numpy is an independent module developped by different people and there is no plan to add it in built-in modules yet. While np.vectorize could be used, it does not truly vectorise a function (it inefficiently calls the CPython function using a loop internally). It is provided for convenience and not speed.

The standard way to manipulate date/time in Numpy is using the datetime64 type.

Body:
I have an array of Unix timestamps.  I can run datetime.utcfromtimestamp on each entry individually, but I cannot run them all from a numpy array.  Why does that happen?

MWE

import numpy as np
from datetime import datetime

times = np.array((1524967210, 1524967211, 1524967212))

# Works
for i in times:
    print(datetime.utcfromtimestamp(times[i]))

# Does not work
print(datetime.utcfromtimestamp(times[:]))

The second example issues: TypeError: only integer scalar arrays can be converted to a scalar index rather than an array of times.  A Unix timestamp conversion seems straightforward to implement as a vectorized operation (see source code here), so why does it not work here?  Is there something I can do to alter this which will enable vectorized operation?