问:
How to use colors and titles inside flutter lists and maps
enter image description here

enter image description here

Help post .... As you can see in the flutter code. I was trying to figure out how to see apps with colors and titles with a map inside a list, but I could see the titles. There was a problem with the colors. How can I fix this? So that I can see my color and title

```<code>import 'package:flutter/material.dart';

class HomePage extends StatelessWidget {
  final myCatagory = [
    {
      'title': 'Samsung',
      'color': Colors.pink[800],
    },
    {
      'title': 'Symphony',
      'color': Colors.tealAccent[800],
    },
    {
      'title': 'MI',
      'color': Colors.amberAccent[800],
    },
    {
      'title': 'Oppo',
      'color': Colors.blue[800],
    },
    {
      'title': 'Vivo',
      'color': Colors.redAccent[800],
    },
    {
      'title': 'Iphone',
      'color': Colors.greenAccent[800],
    },
  ];

  // final catagoryColors = [
  //   Colors.red,
  //   Colors.green,
  //   Colors.black87,
  // ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey,
      appBar: AppBar(
        title: const Text('My Blog'),
        backgroundColor: Colors.redAccent,
      ),
      body: Container(
        height: 150,
        child: ListView.builder(
          itemCount: myCatagory.length,
          shrinkWrap: true,
          primary: false,
          physics: BouncingScrollPhysics(),
          scrollDirection: Axis.horizontal,
          itemBuilder: (BuildContext context, int index) {
            return Container(
              alignment: Alignment.center,
              margin: EdgeInsets.only(
                left: 10,
                top: 10,
              ),
              color: myCatagory[index]['color'], **The problem in this line**
              height: 200,
              width: 100,
              child: Text(
                '${myCatagory[index]['title']}',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 15,
                  fontWeight: FontWeight.w400,
                ),
              ),
            );
          },
        ),
      ),
    );
  }enter image description here

enter code here
</code>```

答:
When you hover over the error the IDE will tell you what's wrong

The compiler can't tell that this is a Color. The solution is to cast it to a Color since you are certain that this is a Color object, like:

```<code>color: myCatagory[index]['color'] as Color,
</code>```

Body:
enter image description here

enter image description here

Help post .... As you can see in the flutter code. I was trying to figure out how to see apps with colors and titles with a map inside a list, but I could see the titles. There was a problem with the colors. How can I fix this? So that I can see my color and title

import 'package:flutter/material.dart';

class HomePage extends StatelessWidget {
  final myCatagory = [
    {
      'title': 'Samsung',
      'color': Colors.pink[800],
    },
    {
      'title': 'Symphony',
      'color': Colors.tealAccent[800],
    },
    {
      'title': 'MI',
      'color': Colors.amberAccent[800],
    },
    {
      'title': 'Oppo',
      'color': Colors.blue[800],
    },
    {
      'title': 'Vivo',
      'color': Colors.redAccent[800],
    },
    {
      'title': 'Iphone',
      'color': Colors.greenAccent[800],
    },
  ];

  // final catagoryColors = [
  //   Colors.red,
  //   Colors.green,
  //   Colors.black87,
  // ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey,
      appBar: AppBar(
        title: const Text('My Blog'),
        backgroundColor: Colors.redAccent,
      ),
      body: Container(
        height: 150,
        child: ListView.builder(
          itemCount: myCatagory.length,
          shrinkWrap: true,
          primary: false,
          physics: BouncingScrollPhysics(),
          scrollDirection: Axis.horizontal,
          itemBuilder: (BuildContext context, int index) {
            return Container(
              alignment: Alignment.center,
              margin: EdgeInsets.only(
                left: 10,
                top: 10,
              ),
              color: myCatagory[index]['color'], **The problem in this line**
              height: 200,
              width: 100,
              child: Text(
                '${myCatagory[index]['title']}',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 15,
                  fontWeight: FontWeight.w400,
                ),
              ),
            );
          },
        ),
      ),
    );
  }enter image description here

enter code here

Body:
When you hover over the error the IDE will tell you what's wrong

The compiler can't tell that this is a Color. The solution is to cast it to a Color since you are certain that this is a Color object, like:

color: myCatagory[index]['color'] as Color,


来源: stackexchange

问:
Error Could not load file or assembly Tesseract on Ubuntu using .Net Core 3.1
I am using Tesseract version 4.1.1 on dotnetcore 3.1 project which works perfectly on windows but when I publish it on ubuntu it throws the following error on this line

```<code>new TesseractEngine(Tessdatapath, LanguageCode, EngineMode.TesseractAndLstm);
</code>```

Could not load file or assembly 'Tesseract, Version=4.1.1.0, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.

I copied the x64 & x86 dlls with the publish files and made sure they are on the same level with tessdata

I tried to install tesseract on ubuntu and copied the .so files inside the x64 & x86 folders but still no luck

答:
As I had to do a lot of trial-and-error even with the great answer from @Lemo I want to post my resulting Docker file as it might save someone a few hours :)</p>
```<code>FROM mcr.microsoft.com/dotnet/aspnet:7.0 AS base
WORKDIR /app
EXPOSE 80

# Install libs for Tesseract
RUN apt-get update
RUN apt-get install -y git cmake build-essential
RUN mkdir leptonica
RUN git clone https://github.com/DanBloomberg/leptonica.git /leptonica

WORKDIR /leptonica
RUN mkdir build
WORKDIR /leptonica/build
RUN cmake ..

RUN apt-get install -y libleptonica-dev libtesseract-dev

FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build
WORKDIR /src
COPY ["ProjectName/ProjectName.csproj", "ProjectName/"]
RUN dotnet restore "ProjectName/ProjectName.csproj"
COPY . .

WORKDIR "/src/ProjectName"
RUN dotnet build "ProjectName.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "ProjectName.csproj" -c Release -o /app/publish

FROM base AS final
# Link libs for Tesseract
WORKDIR /app/x64
RUN ln -s /usr/lib/x86_64-linux-gnu/liblept.so.5 libleptonica-1.80.0.so
RUN ln -s /usr/lib/x86_64-linux-gnu/libtesseract.so.4.0.1 libtesseract41.so
# Entrypoint
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "ProjectName.dll"]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using Tesseract version 4.1.1 on dotnetcore 3.1 project which works perfectly on windows but when I publish it on ubuntu it throws the following error on this line

new TesseractEngine(Tessdatapath, LanguageCode, EngineMode.TesseractAndLstm);

Could not load file or assembly 'Tesseract, Version=4.1.1.0, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.

I copied the x64 & x86 dlls with the publish files and made sure they are on the same level with tessdata

I tried to install tesseract on ubuntu and copied the .so files inside the x64 & x86 folders but still no luck

Body:
As I had to do a lot of trial-and-error even with the great answer from @Lemo I want to post my resulting Docker file as it might save someone a few hours :)

FROM mcr.microsoft.com/dotnet/aspnet:7.0 AS base
WORKDIR /app
EXPOSE 80

# Install libs for Tesseract
RUN apt-get update
RUN apt-get install -y git cmake build-essential
RUN mkdir leptonica
RUN git clone https://github.com/DanBloomberg/leptonica.git /leptonica

WORKDIR /leptonica
RUN mkdir build
WORKDIR /leptonica/build
RUN cmake ..

RUN apt-get install -y libleptonica-dev libtesseract-dev

FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build
WORKDIR /src
COPY ["ProjectName/ProjectName.csproj", "ProjectName/"]
RUN dotnet restore "ProjectName/ProjectName.csproj"
COPY . .

WORKDIR "/src/ProjectName"
RUN dotnet build "ProjectName.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "ProjectName.csproj" -c Release -o /app/publish

FROM base AS final
# Link libs for Tesseract
WORKDIR /app/x64
RUN ln -s /usr/lib/x86_64-linux-gnu/liblept.so.5 libleptonica-1.80.0.so
RUN ln -s /usr/lib/x86_64-linux-gnu/libtesseract.so.4.0.1 libtesseract41.so
# Entrypoint
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "ProjectName.dll"]


问:
Wordpress custom template on every new page (Elementor)
I have wordpress and am using Elementor editor. I have added a page that is meant to be a template for each new pages. I added  a block with breadcrumbs to this page. I want this page with breadcrumbs on evey new page that i create. Copying this page all the time creates problems, e.g. if I wanted to change something in this block so I must do this on every subpage. I do not know how to do it - all i want its one static page with that breadcrumbs that includes to every new page i create, and when im change something in this page, changes will appear on every page.

Help :( Photo below

https://i.stack.imgur.com/G1EyI.png

答: Use the "Template" block in Elementor</p>

Body: Use the "Template" block in Elementor


答:
myCategory is a type of List<Map<String, Object?>>

You need to cast to a Color like so: myCatagory[index]['color'] as Color,

You'll see the warning when you hover over the red line.
Something in the line of

A value of type 'Object?' can't be assigned to a variable of type 'Color'

A nicer way to structure your list would be to use a map

```<code>final Map<String, Color> myCategories = {
 'Samsung': Colors.pink[800],
 'Symphony': Colors.tealAccent[800],
 //the others ...
}
</code>```

And then get the color: myCategories.entries.elementAt(index).value

And the title: myCategories.entries.elementAt(index).key

Title: How to use colors and titles inside flutter lists and maps

Body:
myCategory is a type of List<Map<String, Object?>>

You need to cast to a Color like so: myCatagory[index]['color'] as Color,

You'll see the warning when you hover over the red line.
Something in the line of

A value of type 'Object?' can't be assigned to a variable of type 'Color'

A nicer way to structure your list would be to use a map

final Map<String, Color> myCategories = {
 'Samsung': Colors.pink[800],
 'Symphony': Colors.tealAccent[800],
 //the others ...
}

And then get the color: myCategories.entries.elementAt(index).value

And the title: myCategories.entries.elementAt(index).key


问:
What is CMake equivalent of 'configure --prefix=DIR && make all install '?
I do cmake . && make all install. This works, but installs to /usr/local.

I need to install to a different prefix (for example, to /usr).

What is the cmake and make command line to install to /usr instead of /usr/local?

答:
Starting with CMake 3.21 you can use the --install-prefix option instead of manually setting CMAKE_INSTALL_PREFIX.

The modern equivalent of configure --prefix=DIR && make all install would now be:

cmake -B build --install-prefix=DIR
cmake --build build
cmake --install build
```


问:
Dask returns the same result applying a function to a dataframe
When I apply a function to each dask dataframe in a normal loop:

stats = [run((key, value)) for key, value in tqdm.tqdm(routes_to_process.items())]
stats = {key: value for key, value in stats}

stats_df
```
<p>I get different results for each dataframe:</p>
<pre class="lang-py prettyprint-override"><code>{'/R00_Y2011_0/Data_0001_Wings_H16000_F550.csv': {'total_time': Timedelta('13 days 06:00:00'),
  'wing_adjust_freq_mins': 15.0,
  'TotalTimeInMotion_parallel_mean': 1.2554810767556184,
  'TotalTimeInMotion_parallel_std': 1.938469269213107,
  'TotalTimeInMotion_parallel_95th': 4.919199116216657,
  'TotalTimeInMotion_parallel_max': 24.971773010775486,
  'TotalTimeInMotion_single_mean': 2.070414732378637,
  'TotalTimeInMotion_single_std': 3.110775531046329,
  'TotalTimeInMotion_single_95th': 7.7415319509222,
  'TotalTimeInMotion_single_max': 37.46848468358555},
 '/R00_Y2011_0/Data_0089_Wings_H16000_F550.csv': {'total_time': Timedelta('13 days 05:45:00'),
  'wing_adjust_freq_mins': 15.0,
  'TotalTimeInMotion_parallel_mean': 1.4529180621391111,
  'TotalTimeInMotion_parallel_std': 1.6725803825097267,
  'TotalTimeInMotion_parallel_95th': 4.844115032412909,
  'TotalTimeInMotion_parallel_max': 11.713955279708241,
  'TotalTimeInMotion_single_mean': 2.3589357740318952,
  'TotalTimeInMotion_single_std': 2.6615559537471416,
  'TotalTimeInMotion_single_95th': 7.704699349608058,
  'TotalTimeInMotion_single_max': 20.9864655817048},
 '/R00_Y2011_0/Data_0178_Wings_H16000_F550.csv': {'total_time': Timedelta('13 days 06:00:00'),
  'wing_adjust_freq_mins': 15.0,
  'TotalTimeInMotion_parallel_mean': 1.197378736624615,
  'TotalTimeInMotion_parallel_std': 1.7912324573518639,
  'TotalTimeInMotion_parallel_95th': 3.9983496355992054,
  'TotalTimeInMotion_parallel_max': 29.289081453498962,
  'TotalTimeInMotion_single_mean': 1.993188241820573,
  'TotalTimeInMotion_single_std': 2.885638510182584,
  'TotalTimeInMotion_single_95th': 6.9149671451086965,
  'TotalTimeInMotion_single_max': 46.73164328462062},
 '/R00_Y2011_0/Data_0266_Wings_H16000_F550.csv': {'total_time': Timedelta('13 days 06:15:00'),
  'wing_adjust_freq_mins': 15.0,
  'TotalTimeInMotion_parallel_mean': 0.8902764238240006,
  'TotalTimeInMotion_parallel_std': 1.0558873949196226,
  'TotalTimeInMotion_parallel_95th': 2.8579851928420603,
  'TotalTimeInMotion_parallel_max': 10.951810428266235,
  'TotalTimeInMotion_single_mean': 1.5333169994564122,
  'TotalTimeInMotion_single_std': 1.8294318193945236,
  'TotalTimeInMotion_single_95th': 4.79554414876004,
  'TotalTimeInMotion_single_max': 19.68630214945556},
 '/R00_Y2011_0/Data_0355_Wings_H16000_F550.csv': {'total_time': Timedelta('13 days 05:45:00'),
  'wing_adjust_freq_mins': 15.0,
  'TotalTimeInMotion_parallel_mean': 1.178448380566181,
  'TotalTimeInMotion_parallel_std': 2.3450293462261245,
  'TotalTimeInMotion_parallel_95th': 4.4953148097942774,
  'TotalTimeInMotion_parallel_max': 30.048903002576534,
  'TotalTimeInMotion_single_mean': 1.9654074975262181,
  'TotalTimeInMotion_single_std': 3.7519423792380233,
  'TotalTimeInMotion_single_95th': 6.873441025809852,
  'TotalTimeInMotion_single_max': 43.04718729546469}}
</code>```

When I use dask:

```<code>L = client.map(run, routes_to_process.items())
res = client.gather(L)
</code>```

I get the same result for each:

```<code>[('/R00_Y2011_0/Data_0001_Wings_H16000_F550.csv',
  {'total_time': Timedelta('13 days 06:00:00'),
   'wing_adjust_freq_mins': 15.0,
   'TotalTimeInMotion_parallel_mean': 1.2554810767556184,
   'TotalTimeInMotion_parallel_std': 1.938469269213107,
   'TotalTimeInMotion_parallel_95th': 4.919199116216657,
   'TotalTimeInMotion_parallel_max': 24.971773010775486,
   'TotalTimeInMotion_single_mean': 2.070414732378637,
   'TotalTimeInMotion_single_std': 3.110775531046329,
   'TotalTimeInMotion_single_95th': 7.7415319509222,
   'TotalTimeInMotion_single_max': 37.46848468358555}),
 ('/R00_Y2011_0/Data_0089_Wings_H16000_F550.csv',
  {'total_time': Timedelta('13 days 06:00:00'),
   'wing_adjust_freq_mins': 15.0,
   'TotalTimeInMotion_parallel_mean': 1.2554810767556184,
   'TotalTimeInMotion_parallel_std': 1.938469269213107,
   'TotalTimeInMotion_parallel_95th': 4.919199116216657,
   'TotalTimeInMotion_parallel_max': 24.971773010775486,
   'TotalTimeInMotion_single_mean': 2.070414732378637,
   'TotalTimeInMotion_single_std': 3.110775531046329,
   'TotalTimeInMotion_single_95th': 7.7415319509222,
   'TotalTimeInMotion_single_max': 37.46848468358555}),
 ('/R00_Y2011_0/Data_0178_Wings_H16000_F550.csv',
  {'total_time': Timedelta('13 days 06:00:00'),
   'wing_adjust_freq_mins': 15.0,
   'TotalTimeInMotion_parallel_mean': 1.2554810767556184,
   'TotalTimeInMotion_parallel_std': 1.938469269213107,
   'TotalTimeInMotion_parallel_95th': 4.919199116216657,
   'TotalTimeInMotion_parallel_max': 24.971773010775486,
   'TotalTimeInMotion_single_mean': 2.070414732378637,
   'TotalTimeInMotion_single_std': 3.110775531046329,
   'TotalTimeInMotion_single_95th': 7.7415319509222,
   'TotalTimeInMotion_single_max': 37.46848468358555}),
 ('/R00_Y2011_0/Data_0266_Wings_H16000_F550.csv',
  {'total_time': Timedelta('13 days 06:00:00'),
   'wing_adjust_freq_mins': 15.0,
   'TotalTimeInMotion_parallel_mean': 1.2554810767556184,
   'TotalTimeInMotion_parallel_std': 1.938469269213107,
   'TotalTimeInMotion_parallel_95th': 4.919199116216657,
   'TotalTimeInMotion_parallel_max': 24.971773010775486,
   'TotalTimeInMotion_single_mean': 2.070414732378637,
   'TotalTimeInMotion_single_std': 3.110775531046329,
   'TotalTimeInMotion_single_95th': 7.7415319509222,
   'TotalTimeInMotion_single_max': 37.46848468358555}),
 ('/R00_Y2011_0/Data_0355_Wings_H16000_F550.csv',
  {'total_time': Timedelta('13 days 06:00:00'),
   'wing_adjust_freq_mins': 15.0,
   'TotalTimeInMotion_parallel_mean': 1.2554810767556184,
   'TotalTimeInMotion_parallel_std': 1.938469269213107,
   'TotalTimeInMotion_parallel_95th': 4.919199116216657,
   'TotalTimeInMotion_parallel_max': 24.971773010775486,
   'TotalTimeInMotion_single_mean': 2.070414732378637,
   'TotalTimeInMotion_single_std': 3.110775531046329,
   'TotalTimeInMotion_single_95th': 7.7415319509222,
   'TotalTimeInMotion_single_max': 37.46848468358555})]
</code>```

Despite the file name being different. How can I prevent this?

答:
It's not clear from this information what's inside routes_to_process, but one potential culprit is that the default option for pure in client.map and client.submit is None. This means that the function is expected to return same results for same inputs (which is where content of routes_to_process matters. One thing to try is to add pure=False:

L = client.map(run, routes_to_process.items(), pure=False)
res = client.gather(L)
```

Another potential problem is that in the sequential execution you are calling the function using run((key, value)), and the double brackets suggest that you are passing a tuple to the function, while client.map version will pass two arguments. Depending on how your function is defined, this could lead to a silent failure (because additional inputs are absorbed by **args). If this is the problem, it's probably worth correcting the definition of the function.

Body:
When I apply a function to each dask dataframe in a normal loop:

stats = [run((key, value)) for key, value in tqdm.tqdm(routes_to_process.items())]
stats = {key: value for key, value in stats}

stats_df

I get different results for each dataframe:

{'/R00_Y2011_0/Data_0001_Wings_H16000_F550.csv': {'total_time': Timedelta('13 days 06:00:00'),
  'wing_adjust_freq_mins': 15.0,
  'TotalTimeInMotion_parallel_mean': 1.2554810767556184,
  'TotalTimeInMotion_parallel_std': 1.938469269213107,
  'TotalTimeInMotion_parallel_95th': 4.919199116216657,
  'TotalTimeInMotion_parallel_max': 24.971773010775486,
  'TotalTimeInMotion_single_mean': 2.070414732378637,
  'TotalTimeInMotion_single_std': 3.110775531046329,
  'TotalTimeInMotion_single_95th': 7.7415319509222,
  'TotalTimeInMotion_single_max': 37.46848468358555},
 '/R00_Y2011_0/Data_0089_Wings_H16000_F550.csv': {'total_time': Timedelta('13 days 05:45:00'),
  'wing_adjust_freq_mins': 15.0,
  'TotalTimeInMotion_parallel_mean': 1.4529180621391111,
  'TotalTimeInMotion_parallel_std': 1.6725803825097267,
  'TotalTimeInMotion_parallel_95th': 4.844115032412909,
  'TotalTimeInMotion_parallel_max': 11.713955279708241,
  'TotalTimeInMotion_single_mean': 2.3589357740318952,
  'TotalTimeInMotion_single_std': 2.6615559537471416,
  'TotalTimeInMotion_single_95th': 7.704699349608058,
  'TotalTimeInMotion_single_max': 20.9864655817048},
 '/R00_Y2011_0/Data_0178_Wings_H16000_F550.csv': {'total_time': Timedelta('13 days 06:00:00'),
  'wing_adjust_freq_mins': 15.0,
  'TotalTimeInMotion_parallel_mean': 1.197378736624615,
  'TotalTimeInMotion_parallel_std': 1.7912324573518639,
  'TotalTimeInMotion_parallel_95th': 3.9983496355992054,
  'TotalTimeInMotion_parallel_max': 29.289081453498962,
  'TotalTimeInMotion_single_mean': 1.993188241820573,
  'TotalTimeInMotion_single_std': 2.885638510182584,
  'TotalTimeInMotion_single_95th': 6.9149671451086965,
  'TotalTimeInMotion_single_max': 46.73164328462062},
 '/R00_Y2011_0/Data_0266_Wings_H16000_F550.csv': {'total_time': Timedelta('13 days 06:15:00'),
  'wing_adjust_freq_mins': 15.0,
  'TotalTimeInMotion_parallel_mean': 0.8902764238240006,
  'TotalTimeInMotion_parallel_std': 1.0558873949196226,
  'TotalTimeInMotion_parallel_95th': 2.8579851928420603,
  'TotalTimeInMotion_parallel_max': 10.951810428266235,
  'TotalTimeInMotion_single_mean': 1.5333169994564122,
  'TotalTimeInMotion_single_std': 1.8294318193945236,
  'TotalTimeInMotion_single_95th': 4.79554414876004,
  'TotalTimeInMotion_single_max': 19.68630214945556},
 '/R00_Y2011_0/Data_0355_Wings_H16000_F550.csv': {'total_time': Timedelta('13 days 05:45:00'),
  'wing_adjust_freq_mins': 15.0,
  'TotalTimeInMotion_parallel_mean': 1.178448380566181,
  'TotalTimeInMotion_parallel_std': 2.3450293462261245,
  'TotalTimeInMotion_parallel_95th': 4.4953148097942774,
  'TotalTimeInMotion_parallel_max': 30.048903002576534,
  'TotalTimeInMotion_single_mean': 1.9654074975262181,
  'TotalTimeInMotion_single_std': 3.7519423792380233,
  'TotalTimeInMotion_single_95th': 6.873441025809852,
  'TotalTimeInMotion_single_max': 43.04718729546469}}

When I use dask:

L = client.map(run, routes_to_process.items())
res = client.gather(L)

I get the same result for each:

[('/R00_Y2011_0/Data_0001_Wings_H16000_F550.csv',
  {'total_time': Timedelta('13 days 06:00:00'),
   'wing_adjust_freq_mins': 15.0,
   'TotalTimeInMotion_parallel_mean': 1.2554810767556184,
   'TotalTimeInMotion_parallel_std': 1.938469269213107,
   'TotalTimeInMotion_parallel_95th': 4.919199116216657,
   'TotalTimeInMotion_parallel_max': 24.971773010775486,
   'TotalTimeInMotion_single_mean': 2.070414732378637,
   'TotalTimeInMotion_single_std': 3.110775531046329,
   'TotalTimeInMotion_single_95th': 7.7415319509222,
   'TotalTimeInMotion_single_max': 37.46848468358555}),
 ('/R00_Y2011_0/Data_0089_Wings_H16000_F550.csv',
  {'total_time': Timedelta('13 days 06:00:00'),
   'wing_adjust_freq_mins': 15.0,
   'TotalTimeInMotion_parallel_mean': 1.2554810767556184,
   'TotalTimeInMotion_parallel_std': 1.938469269213107,
   'TotalTimeInMotion_parallel_95th': 4.919199116216657,
   'TotalTimeInMotion_parallel_max': 24.971773010775486,
   'TotalTimeInMotion_single_mean': 2.070414732378637,
   'TotalTimeInMotion_single_std': 3.110775531046329,
   'TotalTimeInMotion_single_95th': 7.7415319509222,
   'TotalTimeInMotion_single_max': 37.46848468358555}),
 ('/R00_Y2011_0/Data_0178_Wings_H16000_F550.csv',
  {'total_time': Timedelta('13 days 06:00:00'),
   'wing_adjust_freq_mins': 15.0,
   'TotalTimeInMotion_parallel_mean': 1.2554810767556184,
   'TotalTimeInMotion_parallel_std': 1.938469269213107,
   'TotalTimeInMotion_parallel_95th': 4.919199116216657,
   'TotalTimeInMotion_parallel_max': 24.971773010775486,
   'TotalTimeInMotion_single_mean': 2.070414732378637,
   'TotalTimeInMotion_single_std': 3.110775531046329,
   'TotalTimeInMotion_single_95th': 7.7415319509222,
   'TotalTimeInMotion_single_max': 37.46848468358555}),
 ('/R00_Y2011_0/Data_0266_Wings_H16000_F550.csv',
  {'total_time': Timedelta('13 days 06:00:00'),
   'wing_adjust_freq_mins': 15.0,
   'TotalTimeInMotion_parallel_mean': 1.2554810767556184,
   'TotalTimeInMotion_parallel_std': 1.938469269213107,
   'TotalTimeInMotion_parallel_95th': 4.919199116216657,
   'TotalTimeInMotion_parallel_max': 24.971773010775486,
   'TotalTimeInMotion_single_mean': 2.070414732378637,
   'TotalTimeInMotion_single_std': 3.110775531046329,
   'TotalTimeInMotion_single_95th': 7.7415319509222,
   'TotalTimeInMotion_single_max': 37.46848468358555}),
 ('/R00_Y2011_0/Data_0355_Wings_H16000_F550.csv',
  {'total_time': Timedelta('13 days 06:00:00'),
   'wing_adjust_freq_mins': 15.0,
   'TotalTimeInMotion_parallel_mean': 1.2554810767556184,
   'TotalTimeInMotion_parallel_std': 1.938469269213107,
   'TotalTimeInMotion_parallel_95th': 4.919199116216657,
   'TotalTimeInMotion_parallel_max': 24.971773010775486,
   'TotalTimeInMotion_single_mean': 2.070414732378637,
   'TotalTimeInMotion_single_std': 3.110775531046329,
   'TotalTimeInMotion_single_95th': 7.7415319509222,
   'TotalTimeInMotion_single_max': 37.46848468358555})]

Despite the file name being different. How can I prevent this?

Body:
It's not clear from this information what's inside routes_to_process, but one potential culprit is that the default option for pure in client.map and client.submit is None. This means that the function is expected to return same results for same inputs (which is where content of routes_to_process matters. One thing to try is to add pure=False:

L = client.map(run, routes_to_process.items(), pure=False)
res = client.gather(L)

Another potential problem is that in the sequential execution you are calling the function using run((key, value)), and the double brackets suggest that you are passing a tuple to the function, while client.map version will pass two arguments. Depending on how your function is defined, this could lead to a silent failure (because additional inputs are absorbed by **args). If this is the problem, it's probably worth correcting the definition of the function.


问:
How to create an array with random numbers and send it to listener without randomizing it again?
So i'm trying to create a program that create an array of 100 random numbers (without changing everytime user reacts to it), and allow users to check the numbers by entering the index of it. However, the array keep randomizing everytime the user pressed the Show Element button.

I also tried to create the array on the main program, but I then faced the error because the listener can't access the array. Please enlighten me as I'm new to this Java GUI Programming. Any help is much appreciated.

```<code>import java.util.Random;
import javax.swing.*;
import java.awt.GridLayout;
import java.awt.*;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.*;

public class P3Q2 extends JFrame {

    private JTextField text1 = new JTextField(10);
    private JTextField text2 = new JTextField(10);
    private int arr[];

    private JButton jbtShow = new JButton("Show Element");

    public P3Q2() {
        JPanel jpTextField = new JPanel();
        jpTextField.setLayout(new GridLayout(3, 2));
        jpTextField.add(new JLabel("Array Index"));
        jpTextField.add(text1);
        jpTextField.add(new JLabel("Array Element"));
        jpTextField.add(text2);
        text2.setEditable(false);

        JPanel jpButtons = new JPanel();
        jpButtons.add(jbtShow);

        add(jpTextField);
        add(jpButtons, BorderLayout.SOUTH);

        jbtShow.addActionListener(new ButtonListener());

        setTitle("Display: Show Bounds Error");
        setSize(400, 150);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

    private class ButtonListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            try {
                Random rd = new Random(); // creating Random object
                int[] arr = new int[100];
                for (int i = 0; i < arr.length; i++) {
                    arr[i] = rd.nextInt(); // storing random integers in an array
                }

                if (e.getSource() == jbtShow) {
                    int num = Integer.parseInt(text1.getText());
                    int result = arr[num];
                    text2.setText("" + result);
                }
            } catch (ArrayIndexOutOfBoundsException ex) {
                text2.setText("Out of bound!");
            }

        }
    }

    public static void main(String[] args) {
        P3Q2 test = new P3Q2();
    }
}
</code>```

答:
Although you are shadowing your arr field you are still creating a new array each time an event is processed which is something you said you didn't want to do.

Doing significant processing in the Event Dispatch Thread is not a good idea.  It can tie up the GUI.  Even though you're only generating 100 random numbers I recommend initializing the array and then just reusing it.

You can do that by having an initialization block in your ButtonListener class.  Then subsequent events will simply use that array without recreating it. The array will be created upon instantiation of your ButtonListener.

```<code>private class ButtonListener implements ActionListener {
    private int arr[] = new int[100];
    {
        Random rd = new Random();
        for (int i = 0; i < arr.length; i++) {
            arr[i] = rd.nextInt(); // storing random integers in an array

        }
    }

    public void actionPerformed(ActionEvent e) {
        try {
            if (e.getSource() == jbtShow) {
                int num = Integer.parseInt(text1.getText());
                int result = arr[num];
                text2.setText("" + result);
            }
        } catch (ArrayIndexOutOfBoundsException ex) {
            text2.setText("Out of bound!");
        }
    }
}
</code>```

If you need to access arr outside of the listener you can use your existing array declaration of private int[] arr; and simply use that in the ButtonListener class.

Another observation.  Catching an exception would be a good idea for parseInt since the value might not be a number.  But if the parsing is acceptable, why not just check to ensure it is between 0 and arr.length-1 inclusive?

Body:
So i'm trying to create a program that create an array of 100 random numbers (without changing everytime user reacts to it), and allow users to check the numbers by entering the index of it. However, the array keep randomizing everytime the user pressed the Show Element button.

I also tried to create the array on the main program, but I then faced the error because the listener can't access the array. Please enlighten me as I'm new to this Java GUI Programming. Any help is much appreciated.

import java.util.Random;
import javax.swing.*;
import java.awt.GridLayout;
import java.awt.*;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.*;

public class P3Q2 extends JFrame {

    private JTextField text1 = new JTextField(10);
    private JTextField text2 = new JTextField(10);
    private int arr[];

    private JButton jbtShow = new JButton("Show Element");

    public P3Q2() {
        JPanel jpTextField = new JPanel();
        jpTextField.setLayout(new GridLayout(3, 2));
        jpTextField.add(new JLabel("Array Index"));
        jpTextField.add(text1);
        jpTextField.add(new JLabel("Array Element"));
        jpTextField.add(text2);
        text2.setEditable(false);

        JPanel jpButtons = new JPanel();
        jpButtons.add(jbtShow);

        add(jpTextField);
        add(jpButtons, BorderLayout.SOUTH);

        jbtShow.addActionListener(new ButtonListener());

        setTitle("Display: Show Bounds Error");
        setSize(400, 150);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

    private class ButtonListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            try {
                Random rd = new Random(); // creating Random object
                int[] arr = new int[100];
                for (int i = 0; i < arr.length; i++) {
                    arr[i] = rd.nextInt(); // storing random integers in an array
                }

                if (e.getSource() == jbtShow) {
                    int num = Integer.parseInt(text1.getText());
                    int result = arr[num];
                    text2.setText("" + result);
                }
            } catch (ArrayIndexOutOfBoundsException ex) {
                text2.setText("Out of bound!");
            }

        }
    }

    public static void main(String[] args) {
        P3Q2 test = new P3Q2();
    }
}

Body:
Although you are shadowing your arr field you are still creating a new array each time an event is processed which is something you said you didn't want to do.

Doing significant processing in the Event Dispatch Thread is not a good idea.  It can tie up the GUI.  Even though you're only generating 100 random numbers I recommend initializing the array and then just reusing it.

You can do that by having an initialization block in your ButtonListener class.  Then subsequent events will simply use that array without recreating it. The array will be created upon instantiation of your ButtonListener.

private class ButtonListener implements ActionListener {
    private int arr[] = new int[100];
    {
        Random rd = new Random();
        for (int i = 0; i < arr.length; i++) {
            arr[i] = rd.nextInt(); // storing random integers in an array

        }
    }

    public void actionPerformed(ActionEvent e) {
        try {
            if (e.getSource() == jbtShow) {
                int num = Integer.parseInt(text1.getText());
                int result = arr[num];
                text2.setText("" + result);
            }
        } catch (ArrayIndexOutOfBoundsException ex) {
            text2.setText("Out of bound!");
        }
    }
}

If you need to access arr outside of the listener you can use your existing array declaration of private int[] arr; and simply use that in the ButtonListener class.

Another observation.  Catching an exception would be a good idea for parseInt since the value might not be a number.  But if the parsing is acceptable, why not just check to ensure it is between 0 and arr.length-1 inclusive?


问:
Change default extensions location for remote development in VS code
I have a visual studio code installed in a desktop. As I don't have any runtime environments installed in it, the source code repository is kept in the remote server where the runtime and other dependencies are available, so SSH connection is established from the VS code to update the source code.

I'm installing few extensions using VS code in the remote server where the source code and runtime are available. It gets installed in my home directory(/home/myname/.vscode-server)by default on the remote server.

As I have very limited disk space in my home directory, I want to change the extension location of vs code. Can you guide me here?. Your insights will be helpful. Thank you !!!

PS: Can't install VS code in the remote server due to limited access rights.

答: It has been well discussed on GitHub under https://github.com/microsoft/vscode-remote-release/issues/472 and remote.SSH.serverInstallPath is the current solution.


问:
Is there a way to compare a lot of files in one directory using the diff command?
I already tried this. (I specified the directory using cd at the beginning of my code)

```<code>    for ((i=0; i<=90; i++))
    do
        if [[ "$(diff -r * *)" -eq 0 ]]
        then
            printf "files dont differ. \n"
        else
            printf "files differ. \n"
        fi
    done
</code>```

This gives me the error "diff: extra operand ''"
The files are all shellscripts with random code in them and I want to compare them all (2 at a time) to find files that are identical.

答:
If you want to compare the files just to find out whether they are identical, you can also use cmp instead of diff.

If you really want to have a line of output for every pair of files, differing as well as identical, you can generate the pairs with two nested loops, e. g.

```<code>set -- *
while [ "$1" ]
do  file1="$1"
    shift
    for file2 in "$@"
    do  if cmp -s "$file1" "$file2"
        then echo $file1 and $file2 don\'t differ.
        else echo $file1 and $file2 differ.
        fi
    done
done
</code>```

(If you wouldn't need output for differing files, a more sophisticated way of selecting files to compare based on their length could be taken.)

Body:
I already tried this. (I specified the directory using cd at the beginning of my code)

    for ((i=0; i<=90; i++))
    do
        if [[ "$(diff -r * *)" -eq 0 ]]
        then
            printf "files dont differ. \n"
        else
            printf "files differ. \n"
        fi
    done

This gives me the error "diff: extra operand ''"
The files are all shellscripts with random code in them and I want to compare them all (2 at a time) to find files that are identical.

Body:
If you want to compare the files just to find out whether they are identical, you can also use cmp instead of diff.

If you really want to have a line of output for every pair of files, differing as well as identical, you can generate the pairs with two nested loops, e. g.

set -- *
while [ "$1" ]
do  file1="$1"
    shift
    for file2 in "$@"
    do  if cmp -s "$file1" "$file2"
        then echo $file1 and $file2 don\'t differ.
        else echo $file1 and $file2 differ.
        fi
    done
done

(If you wouldn't need output for differing files, a more sophisticated way of selecting files to compare based on their length could be taken.)


问:
Testcase returning 401 even with force_autenthicate()
I'm trying to test a view of my project with the following TestCase:

```<code>    def test_jump_story(self):
    c = APIClient()
    user = User.objects.get(username='test1')
    c.login(username=user.username, password='123')
    room_id = PokerRoom.objects.get(name='planning').id
    room_index = PokerRoom.objects.get(name='planning').index
    request = c.post(reverse('jumpstory', kwargs={'pk': room_id, 'index': room_index}))
    c.force_authenticate(user=user)
    self.assertEqual(200,request.status_code)
</code>```

but it returns this <Response status_code=401, "application/json"> even using force_authenticate.

The view that i'm testing:

```<code>class jumpStory(APIView):
permission_classes = [IsAuthenticated]
def post(self, request, pk, index):
    data= self.request.data
    index = self.kwargs['index']
    pk = self.kwargs['pk']
    if PokerRoom.objects.filter(id=pk).exists():
        body = {'index':index}
        message_socket("JUMP_STORY", pk, body)
        return Response({'success':"JUMP_STORY"}, status=200)
    else:
        return Response({'error':'message not sended'}, status=400)
</code>```

What is wrong with my test?

答:
Use APITestCase instead of django TestCase. from rest_framework.test import APITestCase.

```<code>from rest_framework.test import APITestCase
class MyTests(APITestCase)
    def setUp(self):
        user = User.objects.create(username=john)
        user.set_password("1234")
        user.save()
        self.client.force_authenticate(user=user)

    def test_jump_story(self):
         # do your test
</code>```

Body:
I'm trying to test a view of my project with the following TestCase:

    def test_jump_story(self):
    c = APIClient()
    user = User.objects.get(username='test1')
    c.login(username=user.username, password='123')
    room_id = PokerRoom.objects.get(name='planning').id
    room_index = PokerRoom.objects.get(name='planning').index
    request = c.post(reverse('jumpstory', kwargs={'pk': room_id, 'index': room_index}))
    c.force_authenticate(user=user)
    self.assertEqual(200,request.status_code)

but it returns this <Response status_code=401, "application/json"> even using force_authenticate.

The view that i'm testing:

class jumpStory(APIView):
permission_classes = [IsAuthenticated]
def post(self, request, pk, index):
    data= self.request.data
    index = self.kwargs['index']
    pk = self.kwargs['pk']
    if PokerRoom.objects.filter(id=pk).exists():
        body = {'index':index}
        message_socket("JUMP_STORY", pk, body)
        return Response({'success':"JUMP_STORY"}, status=200)
    else:
        return Response({'error':'message not sended'}, status=400)

What is wrong with my test?

Body:
Use APITestCase instead of django TestCase. from rest_framework.test import APITestCase.

from rest_framework.test import APITestCase
class MyTests(APITestCase)
    def setUp(self):
        user = User.objects.create(username=john)
        user.set_password("1234")
        user.save()
        self.client.force_authenticate(user=user)

    def test_jump_story(self):
         # do your test


问:
Import PGP public key by string
I want to import a PGP public key into my keychain in a script, but I don't want it to write the contents to a file. Right now my script does this:

```<code>curl http://example.com/pgp-public-key -o /tmp/pgp && gpg --import /tmp/gpg
</code>```

How could I write this script so I can just call gpg --import and import the public key as a string? Thank you for your help.

答:
We can also achieve this with pgp cmd. For example:

To import PGP public key to keychain(keyring):

```<code>pgp --import "F:\file_path\pgp_public_cert\publickey.asc" --public-keyring "F:\FilePath\keychain\pubchain.gpg"
</code>```

To import PGP private key to keychain(keyring):

```<code>pgp --import "F:\file_path\pgp_private_cert\privatekey.asc" --private-keyring "F:\FilePath\keychain\secchain.gpg"
</code>```

Here,

publickey.asc  ->  my public key

privatekey.asc ->  my private key

pubchain.gpg  ->  my public keyring/keychain where i have stored all my public certificate or public keys.

secchain.gpg  ->  my private keyring/keychain where i have stored all my private certificate or private keys.

Hope this also helps for somebody.

ContentLicense: CC BY-SA 3.0

Title: Import PGP public key by string

Body:
I want to import a PGP public key into my keychain in a script, but I don't want it to write the contents to a file. Right now my script does this:

curl http://example.com/pgp-public-key -o /tmp/pgp && gpg --import /tmp/gpg

How could I write this script so I can just call gpg --import and import the public key as a string? Thank you for your help.

Body:
We can also achieve this with pgp cmd. For example:

To import PGP public key to keychain(keyring):

pgp --import "F:\file_path\pgp_public_cert\publickey.asc" --public-keyring "F:\FilePath\keychain\pubchain.gpg"

To import PGP private key to keychain(keyring):

pgp --import "F:\file_path\pgp_private_cert\privatekey.asc" --private-keyring "F:\FilePath\keychain\secchain.gpg"

Here,

publickey.asc  ->  my public key

privatekey.asc ->  my private key

pubchain.gpg  ->  my public keyring/keychain where i have stored all my public certificate or public keys.

secchain.gpg  ->  my private keyring/keychain where i have stored all my private certificate or private keys.

Hope this also helps for somebody.


问:
Javascript access to other page
Can I have access from javascript on one page to elements on other page the script has created before? Something like this:

```<code>var win=window.open("http://www.ftwars.com/battle",'myWindow');
win.document.getElementById('center').onClick();
</code>```

答:
First page (x.html):

```<code><!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
    var w = window.open('y.html', 'w');
    w.document.getElementById('target').onclick = function () { alert('!'); };
</script>
</body>
</html>
</code>```

Second page (y.html):

```<code><!DOCTYPE html>
<html>
<head>
</head>
<body>
   <button id="target">target</button>
</body>
</html>
</code>```

Title: Javascript access to other page

Body:
Can I have access from javascript on one page to elements on other page the script has created before? Something like this:

var win=window.open("http://www.ftwars.com/battle",'myWindow');
win.document.getElementById('center').onClick();

Body:
First page (x.html):

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
    var w = window.open('y.html', 'w');
    w.document.getElementById('target').onclick = function () { alert('!'); };
</script>
</body>
</html>

Second page (y.html):

<!DOCTYPE html>
<html>
<head>
</head>
<body>
   <button id="target">target</button>
</body>
</html>


问:
Read out tensorboard hparams programatically
after running a hyperparameter search with PyTorch and visualizing the results in Tensorboard, I want to read out the hyperparameters from Tensorboard programatically.

My folder structure is

all_runs

run1

Loss_trainingloss

1634168941.9091413 (or some other timestamp)
events.out.tfevents.1634168941

events.out.tfevents.1634135651

run2

run3

and I can easily read tensorboard time-series like e.g. the loss curve with code like this:

```<code>from tensorboard.backend.event_processing.event_accumulator import EventAccumulator

def read_eventfile(filepath, tag):
    event_accumulator = EventAccumulator(filepath)
        event_accumulator.Reload()

        events = event_accumulator.Scalars(tag)

        y = [x.value for x in events]

        return y

train_loss_curve = read_eventfile(path_to_event_folder, "Loss_trainingloss")
</code>```

However I struggle to find an access to the hparams of each run, which are correctly displayed in tensorboard. Anybody knows how this can be done?

Thanks!

答:
I just finished a tool called tbparse to read the hparams events easily as follows:

```<code>from tbparse import SummaryReader
log_dir = "<PATH_TO_EVENT_FILE_OR_DIRECTORY>"
reader = SummaryReader(log_dir)
hp = reader.hparams
print(hp)
</code>```

See the documentation for more usages.

Body:
after running a hyperparameter search with PyTorch and visualizing the results in Tensorboard, I want to read out the hyperparameters from Tensorboard programatically.

My folder structure is

all_runs

run1

Loss_trainingloss

1634168941.9091413 (or some other timestamp)
events.out.tfevents.1634168941

events.out.tfevents.1634135651

run2

run3

and I can easily read tensorboard time-series like e.g. the loss curve with code like this:

from tensorboard.backend.event_processing.event_accumulator import EventAccumulator

def read_eventfile(filepath, tag):
    event_accumulator = EventAccumulator(filepath)
        event_accumulator.Reload()

        events = event_accumulator.Scalars(tag)

        y = [x.value for x in events]

        return y

train_loss_curve = read_eventfile(path_to_event_folder, "Loss_trainingloss")

However I struggle to find an access to the hparams of each run, which are correctly displayed in tensorboard. Anybody knows how this can be done?

Thanks!

Body:
I just finished a tool called tbparse to read the hparams events easily as follows:

from tbparse import SummaryReader
log_dir = "<PATH_TO_EVENT_FILE_OR_DIRECTORY>"
reader = SummaryReader(log_dir)
hp = reader.hparams
print(hp)

See the documentation for more usages.


问:
How to resize a device local VkBuffer?
Assume a host visible AND also device local VkDeviceMemory that is bound to a VkBuffer, acting as a vertex buffer. The bidirectional access properties of the memory makes it possible to "manipulate" the initial set of associated vertices post-initilization by simply memcpy'ing over the memory - that's fine. I like that.

But I am really confused on what would be "the flow" of practically resizing the vertex buffer? Let's apply it to a chunk of voxel terrain - to give a context: You destroy some terrain, resulting in less vertices than before. So what then?

Do you have to recreate the VkBuffer with a new size? That would screw up the binding in the render pass, wouldn't it? Do you have to re-record the whole command buffer then? Can you still use the same VkDeviceMemory? Do you have to reallocate the memory? It's... idk. I just need some direction of the broader concept.

答:
Do you have to recreate the VkBuffer with a new size?

Vulkan splits resource access from the underlying memory allocation.

In terms of performance, reallocating memory is expensive but creating new buffer/buffer views is really just metadata and expected to be relatively inexpensive. For dynamic resources the usual approach is to over-allocate memory to "a large size" and then just reference the range of memory that is actively used by the current content.

If you must create a new version of a buffer and/or allocation you need to keep the old one "alive" until any pending commands referencing it have completed.

That would screw up the binding in the render pass, wouldn't it?

If you are submitting an existing pre-recorded command buffer, then yes, the bindings are part of the recorded command buffer and will need regenerating.

If you are worried about existing bindings in the command buffer that is currently being recorded, then you need to ensure that the already recorded stay valid if you submit the commands. Allocate a new buffer/memory range for the new buffer, but don't reuse/deallocate the buffer memory that earlier queued commands are referencing. Wait for them to complete first, and then free the existing buffer.

Do you have to re-record the whole command buffer then?

Pre-recorded buffers referring to old bindings will need to be re-recoded.

You don't need to re-record the start of the current command recording, just make sure the "old" buffer and memory stay alive until the queue submit completes.

Title: How to resize a device local VkBuffer?


问:
psycopg2 execute returns datetime instead of a string
```<code>cur.execute("SELECT \
                title, \
                body, \
                date \ # This pgsql type is date
             FROM \
                table \
             WHERE id = '%s';", id)

response = cur.fetchall()

print response
</code>```

As an example this gives me: -

```<code>[('sample title', 'sample body', datetime.date(2012, 8, 5))]
</code>```

Which can't be passed to things like json.dumps so I'm having to do this: -

```<code>processed = []

for row in response:
    processed.append({'title' : row[0],
                      'body' : row[1],
                      'date' : str(row[2])
                     })
</code>```

Which feels like poor form, does anyone know of a better way of handling this?

答:
Instead of adding encoding, you can customise the psycopg2 mapping between SQL and Python data types, as explained here:

https://www.psycopg.org/docs/advanced.html#type-casting-of-sql-types-into-python-objects

The code template is

```<code>date_oid = 1082 # id of date type, see docs how to get it from db
def casting_fn(val,cur):
  # process as you like, e.g. string formatting
# register custom mapping
datetype_casted = psycopg2.extensions.new_type((date_oid,), "date", casting_fn)
psycopg2.extensions.register_type(datetype_casted)
</code>```

Once this is done, instead
[('sample title', 'sample body', datetime.date(2012, 8, 5))]
you will receive
[('sample title', 'sample body', '2012-08-05')]

Body:
cur.execute("SELECT \
                title, \
                body, \
                date \ # This pgsql type is date
             FROM \
                table \
             WHERE id = '%s';", id)

response = cur.fetchall()

print response

As an example this gives me: -

[('sample title', 'sample body', datetime.date(2012, 8, 5))]

Which can't be passed to things like json.dumps so I'm having to do this: -

processed = []

for row in response:
    processed.append({'title' : row[0],
                      'body' : row[1],
                      'date' : str(row[2])
                     })

Which feels like poor form, does anyone know of a better way of handling this?

Body:
Instead of adding encoding, you can customise the psycopg2 mapping between SQL and Python data types, as explained here:

https://www.psycopg.org/docs/advanced.html#type-casting-of-sql-types-into-python-objects

The code template is

date_oid = 1082 # id of date type, see docs how to get it from db
def casting_fn(val,cur):
  # process as you like, e.g. string formatting
# register custom mapping
datetype_casted = psycopg2.extensions.new_type((date_oid,), "date", casting_fn)
psycopg2.extensions.register_type(datetype_casted)

Once this is done, instead
[('sample title', 'sample body', datetime.date(2012, 8, 5))]
you will receive
[('sample title', 'sample body', '2012-08-05')]


问:
Joining three tables in one query
I have three tables:

violation: violation_id,violation_name

violators: violator_id, violation_id

previous_violator: prev_violator_id, violator_id,violation_id

I want to display the violator name and its violation from violators table and previous_violator table.

I tried this code:

```<code>SELECT violation_name
FROM (SELECT violation_name FROM violators
      UNION ALL
      SELECT prev_violator_id
      FROM previous_violator
        LEFT JOIN violators ON violators.violator_id = previous_violator.violator_id) tmp
INNER JOIN violation ON tmp.violation_id = violation.violation_id
</code>```

答:
Try using a CTE to make the query easier, but as mentioned in the comment, there is not reason for prev_violator and violator to be in different tables. so when the data is migrated and corrected, you can replace the CTE with the new table</p>
```<code>with all_violators as (
    select 0 violator, 1 violator_id , null prev_violator_id  -- from violators
    union all
    select 0 violator, 1 violator_id , 1 prev_violator_id -- from prev_violators
)

select violation_name, violator_id from violation v join all_violators a on a.violator_id = v.violation_id
</code>```

Title: Joining three tables in one query

Body:
I have three tables:

violation: violation_id,violation_name

violators: violator_id, violation_id

previous_violator: prev_violator_id, violator_id,violation_id

I want to display the violator name and its violation from violators table and previous_violator table.

I tried this code:

SELECT violation_name
FROM (SELECT violation_name FROM violators
      UNION ALL
      SELECT prev_violator_id
      FROM previous_violator
        LEFT JOIN violators ON violators.violator_id = previous_violator.violator_id) tmp
INNER JOIN violation ON tmp.violation_id = violation.violation_id

Body:
Try using a CTE to make the query easier, but as mentioned in the comment, there is not reason for prev_violator and violator to be in different tables. so when the data is migrated and corrected, you can replace the CTE with the new table

with all_violators as (
    select 0 violator, 1 violator_id , null prev_violator_id  -- from violators
    union all
    select 0 violator, 1 violator_id , 1 prev_violator_id -- from prev_violators
)

select violation_name, violator_id from violation v join all_violators a on a.violator_id = v.violation_id


问:
Why composer.json is modified after "composer install" command?
I am currently working on a Laravel 5.8 project that I have just cloned from our company's Gitlab. I ran composer install and after that when I run git status it lists composer.json as a modified file.

I thought that composer install does not modify composer.json file.

I think that if I commit this file, then the remote server can not merge the new composer file with the old one.

What should I do?

答:
Generally, Composer install will not modify composer.json. But there are some circumstances where it can be changed, although I don't know about any that would happen without user input.

The one I can think of as of now, is the setting config.allow-plugins.

If you clone a project created with Composer < 2.2.0, this option wouldn't exist on the configuration file.

If you now run a version of Composer > 2.2.0, and if this project includes composer plugins (some that come to mind are composer/package-versions-deprecated, symfony/flex, symfony/runtime, and more), you'd get a few prompts asking you to authorize plugins.

Like so:

bamarni/composer-bin-plugin contains a Composer plugin which is currently not in your allow-plugins config. See https://getcomposer.org/allow-plugins
Do you trust "bamarni/composer-bin-plugin" to execute code and wish to enable it now? (writes "allow-plugins" to composer.json) [y,n,d,?]

The different options stand for:

Choosing yes or no, would end up modifying your composer.json adding this configuration.

I think that if I commit this file, then the remote server can not merge the new composer file with the old one.

Git has no problems merging this kind of change.

What should I do?

Talk with someone at your company. Run git diff composer.json to check the changes, and verify with someone if you should push those changes upstream or not. If not, simply run git restore composer.json


问:
nodejs: how to download a zip file from AWS S3 bucket, save as local file in EC2 instance and unzip it?
My EC2 instance is running a nodejs service.
I want to download / save a zip file in S3 bucket to a local location in EC2 instance.

There are a lot of answers about downloading files from s3 bucket, but they are all about how to implement the nodejs api endpoint such that you can download the file from s3 bucket to your local machine:

```<code>s3.getObject(bucketParams).createReadStream().pipe(res);

</code>```

This will create a stream for the file and you just pipe the stream to res, and it will start downloading to your machine.

This is not what I need to do here.

I need to save the file in local in EC2, do some operations such as unzipping it, and then the http response does not return the file. Everything is on the EC2's side.

What should I do? This seems to be so basic and yet I couldn't find much documentations / resources.

答:
Create a read stream for the object and a write stream for the local file and pipe the read stream to the write stream, something like this:</p>
```<code>const AWS = require('aws-sdk');
const path = require('path');
const fs = require('fs');

const s3 = new AWS.S3();

const params = {
  Bucket: 'mybucket',
  Key: 'cats/siberian.png'
};

const rs = s3.getObject(params).createReadStream();
const ws = fs.createWriteStream(path.join('myfolder', 'siberian.png'));

rs.pipe(ws);
</code>```

Body:
My EC2 instance is running a nodejs service.
I want to download / save a zip file in S3 bucket to a local location in EC2 instance.

There are a lot of answers about downloading files from s3 bucket, but they are all about how to implement the nodejs api endpoint such that you can download the file from s3 bucket to your local machine:

s3.getObject(bucketParams).createReadStream().pipe(res);

This will create a stream for the file and you just pipe the stream to res, and it will start downloading to your machine.

This is not what I need to do here.

I need to save the file in local in EC2, do some operations such as unzipping it, and then the http response does not return the file. Everything is on the EC2's side.

What should I do? This seems to be so basic and yet I couldn't find much documentations / resources.

Body:
Create a read stream for the object and a write stream for the local file and pipe the read stream to the write stream, something like this:

const AWS = require('aws-sdk');
const path = require('path');
const fs = require('fs');

const s3 = new AWS.S3();

const params = {
  Bucket: 'mybucket',
  Key: 'cats/siberian.png'
};

const rs = s3.getObject(params).createReadStream();
const ws = fs.createWriteStream(path.join('myfolder', 'siberian.png'));

rs.pipe(ws);


问:
Constant expression required in Java switch statement
I have ths piece of code in Java

```<code> final String workFlowKey = getProcessDefinitionKey();

        switch (workFlowKey) {
            case WorkflowKey.DOG_WORKFLOW.getKey():
                return "A";
                break;
            default: return null;
        }
</code>```

but I have this compilation error: Constant expression required

答:
Imagine a situation, if you could pass a method into case clause. What if the method could return different values depending on some internal factors? The same conforms to field, or variable. It can take different values during application runtime.

```<code>class A {
  String f(){
    if(something) return „string1”;
    else return „string2”
  }
  public static void main(String[] args) {
    A obj = new A();
    String someString = "string1";
    switch(someString){
      case obj.f(): {…} // obj.f can potentially return 2 different results. So as any method.
      …
    }
  }
}
</code>```

Unlike if-else, which checks boolean value of expression, in switch-case a value passed into is compared to cases inside. In compile-time Java compiler create array of jumps to optimize performace, so usually switch-case is more efficient than if-else for big number of alternatives. (Good link explaining jumps, but in assembly code). Hence, in order to perform that, cases' values in switch-case have to be determined in compile-time.

Body:
I have ths piece of code in Java

 final String workFlowKey = getProcessDefinitionKey();

        switch (workFlowKey) {
            case WorkflowKey.DOG_WORKFLOW.getKey():
                return "A";
                break;
            default: return null;
        }

but I have this compilation error: Constant expression required

Body:
Imagine a situation, if you could pass a method into case clause. What if the method could return different values depending on some internal factors? The same conforms to field, or variable. It can take different values during application runtime.

class A {
  String f(){
    if(something) return „string1”;
    else return „string2”
  }
  public static void main(String[] args) {
    A obj = new A();
    String someString = "string1";
    switch(someString){
      case obj.f(): {…} // obj.f can potentially return 2 different results. So as any method.
      …
    }
  }
}

Unlike if-else, which checks boolean value of expression, in switch-case a value passed into is compared to cases inside. In compile-time Java compiler create array of jumps to optimize performace, so usually switch-case is more efficient than if-else for big number of alternatives. (Good link explaining jumps, but in assembly code). Hence, in order to perform that, cases' values in switch-case have to be determined in compile-time.


问:
Force location update
I'm attempting to overcome a sometimes-failure of didUpdateToLocation when checking local data based on current position, closing the app, traveling a bit, and opening the app again. What happens is that the user visits one place, checks the list, goes to another place, and the list is updated but using the old location data.

I would like to make sure I have a fresh newLocation.

What's wrong with this code?

```<code>double aa,bb,cc;

-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    [manager stopUpdatingLocation]; //only stop if new reliable pos fetched.
        //old data? retry.
    aa=[newLocation.timestamp timeIntervalSinceReferenceDate];
    bb=[NSDate timeIntervalSinceReferenceDate];
    cc=bb-aa;   //must be <60 - minute-fresh
    if (cc>60) {
        [manager stopUpdatingLocation]; //only stop if new reliable pos fetched.
        [manager startUpdatingLocation];    //only stop if new reliable pos fetched.
        return;
    }
...handle position
}
</code>```

The symptoms are that cc is about 1200 seconds on app start, then on each retry it increases a few seconds.

I've tried -[newLocation.timestamp timeIntervalSinceNow], and similarly it increases a few seconds at each retry. At one point the interval was ~2400.

I'm using FilterNone and AccuracyBest, if that could influence it.

I'm open to alternative code solutions to make sure you have a fresh position.

答:
The answer was that you need to write the handling the way you want it to behave.

I've read up on this common problem. I should have clarified that "force" means to start unambiguous behavior that gives a reliable position under optimal conditions for the phone. Not to busy-wait until satisfied or to expect an immediate result/error code.

From a common sense viewpoint, what would be desirable by all developers would be at least an extra method to simply ask for a position within parameters, and callback only when it's valid and within accuracy, or canceled, or timed out. If the conditions prevent it you then don't need to test out esoteric behavior to be able to handle it with custom code.

Why I needed to ask about this at all was:

no existence of a method functioning as described above

using code from a book (More Iphone 3 Development)

when writing it from scratch (looking at LocateMe.xproj), discovering that:

simulator behavior differs from phone behavior (not talking about the position itself, which is obviously as good as ip lookup can make it, but the behavior of didUpdateToLocation). Recognizing the limitations of a simulator, the method should at least behave like they do on a device. But currently, correctly written location handling/checking code just times out in the simulator (as in the LocateMe example), while incorrect code (asking once and using newLocation on callback) works.

and a bug causing didUpdateToLocation being called twice after [locationManager stopUpdatingLocation];

If on top of this you (like I) load data based on your position, and the data is required by multiple views in your application, the behavior of Apple's location-fetching methods doesn't make it easy to handle the chain of update-load-calculate-present consistently and problem-free throughout the app. Especially if your stuck between user/boss perception or decision of how it should work (a rock) and how the system works (a hard place).

Here's my current code which works on a device and in a simulator:

```<code>//ask for a position, as fresh as possible.
-(void)updateMeMap {
    lastloc.coordinate=homeloc.coordinate;
    lm.delegate=self;
    ctr=0;
    [self performSelector:@selector(stopUpd) withObject:nil afterDelay:gpstimeout];
    [lm startUpdatingLocation];
}

//called on each position update.
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    ctr++;
    if (ctr<15) {
        NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];
        NSLog(@"%d",ctr);
        if (locationAge<60) {
            NSLog(@"Found");
            ctr=40;
            homeloc.coordinate=newLocation.coordinate;
            [self stopUpd];
            [self reload];
        } else {
            NSLog(@"Lastupd");
            lastloc.coordinate=newLocation.coordinate;
        }
    } else {
            //enough tries, if not canceled choose lastloc.
        if (ctr<40) {
            NSLog(@"Last");
            ctr=40;
            homeloc.coordinate=lastloc.coordinate;
            [self stopUpd];
            [self reload];
        }
    }
}

//force stop updates. ctr prevents extra calls after stopUpdatingLocation.
//called after the timeout delay, if position found, cancel the timeout.
-(void)stopUpd {
    [lm stopUpdatingLocation];
    lm.delegate=nil;
    if (ctr<15) {
        ctr=40; //2 extra calls after stopupda... otherwise, now do nothing.
        NSLog(@"Timeout");
        homeloc.coordinate=lastloc.coordinate;  //@need "copy"?
        [self reload];
    } else {
        ctr=40; //2 extra calls after stopupda... otherwise, now do nothing.
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(stopUpd) object:nil];
    }
}

    // "couldn't get userlocation" handler. I also cancel like this on connectionDidFailWithError.
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"Location failed: %@",[error localizedDescription]);
    ctr=0;
    [self stopUpd];
}
</code>```

Where ctr is there to prevent the 2 extra calls, lastloc is last known reliable position, homeloc is the phone position used for (threaded) loading of location-specific data with [self reload].

The constants 15 and 60 are safe values from real-world testing; gpstimeout is set to 30. If you work a lot in a simulator you may want to set it to something short like 3 seconds, as all you will get is a stale but relatively usable position and no more until the timeout.

Edit: If you can best my code or point out an omission, I'll mark that as answer, I hate marking my own as answer.

Title: Force location update

Body:
I'm attempting to overcome a sometimes-failure of didUpdateToLocation when checking local data based on current position, closing the app, traveling a bit, and opening the app again. What happens is that the user visits one place, checks the list, goes to another place, and the list is updated but using the old location data.

I would like to make sure I have a fresh newLocation.

What's wrong with this code?

double aa,bb,cc;

-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    [manager stopUpdatingLocation]; //only stop if new reliable pos fetched.
        //old data? retry.
    aa=[newLocation.timestamp timeIntervalSinceReferenceDate];
    bb=[NSDate timeIntervalSinceReferenceDate];
    cc=bb-aa;   //must be <60 - minute-fresh
    if (cc>60) {
        [manager stopUpdatingLocation]; //only stop if new reliable pos fetched.
        [manager startUpdatingLocation];    //only stop if new reliable pos fetched.
        return;
    }
...handle position
}

The symptoms are that cc is about 1200 seconds on app start, then on each retry it increases a few seconds.

I've tried -[newLocation.timestamp timeIntervalSinceNow], and similarly it increases a few seconds at each retry. At one point the interval was ~2400.

I'm using FilterNone and AccuracyBest, if that could influence it.

I'm open to alternative code solutions to make sure you have a fresh position.

Body:
The answer was that you need to write the handling the way you want it to behave.

I've read up on this common problem. I should have clarified that "force" means to start unambiguous behavior that gives a reliable position under optimal conditions for the phone. Not to busy-wait until satisfied or to expect an immediate result/error code.

From a common sense viewpoint, what would be desirable by all developers would be at least an extra method to simply ask for a position within parameters, and callback only when it's valid and within accuracy, or canceled, or timed out. If the conditions prevent it you then don't need to test out esoteric behavior to be able to handle it with custom code.

Why I needed to ask about this at all was:

no existence of a method functioning as described above

using code from a book (More Iphone 3 Development)

when writing it from scratch (looking at LocateMe.xproj), discovering that:

simulator behavior differs from phone behavior (not talking about the position itself, which is obviously as good as ip lookup can make it, but the behavior of didUpdateToLocation). Recognizing the limitations of a simulator, the method should at least behave like they do on a device. But currently, correctly written location handling/checking code just times out in the simulator (as in the LocateMe example), while incorrect code (asking once and using newLocation on callback) works.

and a bug causing didUpdateToLocation being called twice after [locationManager stopUpdatingLocation];

If on top of this you (like I) load data based on your position, and the data is required by multiple views in your application, the behavior of Apple's location-fetching methods doesn't make it easy to handle the chain of update-load-calculate-present consistently and problem-free throughout the app. Especially if your stuck between user/boss perception or decision of how it should work (a rock) and how the system works (a hard place).

Here's my current code which works on a device and in a simulator:

//ask for a position, as fresh as possible.
-(void)updateMeMap {
    lastloc.coordinate=homeloc.coordinate;
    lm.delegate=self;
    ctr=0;
    [self performSelector:@selector(stopUpd) withObject:nil afterDelay:gpstimeout];
    [lm startUpdatingLocation];
}

//called on each position update.
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    ctr++;
    if (ctr<15) {
        NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];
        NSLog(@"%d",ctr);
        if (locationAge<60) {
            NSLog(@"Found");
            ctr=40;
            homeloc.coordinate=newLocation.coordinate;
            [self stopUpd];
            [self reload];
        } else {
            NSLog(@"Lastupd");
            lastloc.coordinate=newLocation.coordinate;
        }
    } else {
            //enough tries, if not canceled choose lastloc.
        if (ctr<40) {
            NSLog(@"Last");
            ctr=40;
            homeloc.coordinate=lastloc.coordinate;
            [self stopUpd];
            [self reload];
        }
    }
}

//force stop updates. ctr prevents extra calls after stopUpdatingLocation.
//called after the timeout delay, if position found, cancel the timeout.
-(void)stopUpd {
    [lm stopUpdatingLocation];
    lm.delegate=nil;
    if (ctr<15) {
        ctr=40; //2 extra calls after stopupda... otherwise, now do nothing.
        NSLog(@"Timeout");
        homeloc.coordinate=lastloc.coordinate;  //@need "copy"?
        [self reload];
    } else {
        ctr=40; //2 extra calls after stopupda... otherwise, now do nothing.
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(stopUpd) object:nil];
    }
}

    // "couldn't get userlocation" handler. I also cancel like this on connectionDidFailWithError.
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"Location failed: %@",[error localizedDescription]);
    ctr=0;
    [self stopUpd];
}

Where ctr is there to prevent the 2 extra calls, lastloc is last known reliable position, homeloc is the phone position used for (threaded) loading of location-specific data with [self reload].

The constants 15 and 60 are safe values from real-world testing; gpstimeout is set to 30. If you work a lot in a simulator you may want to set it to something short like 3 seconds, as all you will get is a stale but relatively usable position and no more until the timeout.

Edit: If you can best my code or point out an omission, I'll mark that as answer, I hate marking my own as answer.


问:
Copy All the elements/object of one list N times to new list. Using java 8 stream
Copy all the elements of one list N times in a new list.

I have list of Fruits which i want to iterate to N times and add all the value to new list but the in the list we have less then my iteration so i want to add Empty fruits with incremental id. how to do using java 8 and stream programming.
I have total 7 fruits in my current list but i want to looped in 10 time copied all data to new list and if data is not available in the index then i want to add empty object with incremental ids.
I tried but not getting expected result.

```<code>@Data
@AllArgsConstructor
public class Fruit {
   int id;
   String type;
}

List<Fruit> fruits = new ArrayList<>();
    fruits.add(new Fruit(1, "mango"));
    fruits.add(new Fruit(2, "grapes"));
    fruits.add(new Fruit(3, "apple"));
    fruits.add(new Fruit(4, "banana"));
    fruits.add(new Fruit(5, "papaya"));
    fruits.add(new Fruit(6, "jack fruit"));
    fruits.add(new Fruit(7, "dragon fruit"));
List<Fruit> newFruits = new ArrayList<>();

    fruits.stream().map(value -> {
        IntStream.rangeClosed(1, 10).forEach(index -> {
            if (value.equals(null))
                newFruits.add(new Fruit(index, ""));
            else
                newFruits.add(value);
        });
        return null;
    });
</code>```

Expected OP: for newFruits

```<code>newFruits :
[Fruit(id=1, type=mango),
 Fruit(id=2, type=grapes),
 Fruit(id=3, type=apple),
 Fruit(id=4, type=banana),
 Fruit(id=5, type=papaya),
 Fruit(id=6, type=jack fruit),
 Fruit(id=7, type=dragon fruit),
 Fruit(id=8, type="").
 Fruit(id=9, type=")
 Fruit(id=10, type="")]
</code>```

答:
Streams might not be the right tool for this task. Why not just add all elments from original list to new list and calculate how many new entries to add after finding the largest id? Something like:

```<code>List<Fruit> newFruits =  new ArrayList<>();
newFruits.addAll(fruits);

int N = 10;
int toAdd = N - fruits.size();
int maxId = fruits.stream().mapToInt(Fruit::getId).max().orElse(0);

IntStream.rangeClosed(1,toAdd).forEach(i -> newFruits.add(new Fruit(maxId + i, "")));
</code>```

Or take a look at @Holger's comment.

Body:
Copy all the elements of one list N times in a new list.

I have list of Fruits which i want to iterate to N times and add all the value to new list but the in the list we have less then my iteration so i want to add Empty fruits with incremental id. how to do using java 8 and stream programming.
I have total 7 fruits in my current list but i want to looped in 10 time copied all data to new list and if data is not available in the index then i want to add empty object with incremental ids.
I tried but not getting expected result.

@Data
@AllArgsConstructor
public class Fruit {
   int id;
   String type;
}

List<Fruit> fruits = new ArrayList<>();
    fruits.add(new Fruit(1, "mango"));
    fruits.add(new Fruit(2, "grapes"));
    fruits.add(new Fruit(3, "apple"));
    fruits.add(new Fruit(4, "banana"));
    fruits.add(new Fruit(5, "papaya"));
    fruits.add(new Fruit(6, "jack fruit"));
    fruits.add(new Fruit(7, "dragon fruit"));
List<Fruit> newFruits = new ArrayList<>();

    fruits.stream().map(value -> {
        IntStream.rangeClosed(1, 10).forEach(index -> {
            if (value.equals(null))
                newFruits.add(new Fruit(index, ""));
            else
                newFruits.add(value);
        });
        return null;
    });

Expected OP: for newFruits

newFruits :
[Fruit(id=1, type=mango),
 Fruit(id=2, type=grapes),
 Fruit(id=3, type=apple),
 Fruit(id=4, type=banana),
 Fruit(id=5, type=papaya),
 Fruit(id=6, type=jack fruit),
 Fruit(id=7, type=dragon fruit),
 Fruit(id=8, type="").
 Fruit(id=9, type=")
 Fruit(id=10, type="")]

Body:
Streams might not be the right tool for this task. Why not just add all elments from original list to new list and calculate how many new entries to add after finding the largest id? Something like:

List<Fruit> newFruits =  new ArrayList<>();
newFruits.addAll(fruits);

int N = 10;
int toAdd = N - fruits.size();
int maxId = fruits.stream().mapToInt(Fruit::getId).max().orElse(0);

IntStream.rangeClosed(1,toAdd).forEach(i -> newFruits.add(new Fruit(maxId + i, "")));

Or take a look at @Holger's comment.


问:
Select pandas rows where column is a substring
I'd like to filter my dataframe such that only rows that have a column containing a substring of another string are selected. I know that the opposite can be done like this:

```<code>selection = df[df.str.contains(substring)]
</code>```

But how would I do it such that the substring is in the dataframe and it is compared to another string. What I've tried are

```<code>import pandas
a = pandas.DataFrame({"b":["foo","bar"]})
selection = a[a.b.str in "foot"] # should match first row
selection = a[a.b.str.isin("foot")] # should match first row
selection = a[a.b.str.isin("foobar")] # should match both rows
</code>```

but these won't work

答:
What you could try is make function like so:

```<code>f = lambda substring: substring in string
</code>```

Where string is your target string. Then, apply this function elementwise to the df.

```<code>df.applymap(f)
</code>```

This should return a DataFrame with True where the element is a substring of your target string, and False where it isn't. To find out which rows contain a True, i.e. contain elements that are substrings of your target string, us df.any():

```<code>df.applymap(lambda substring: substring in string).any(axis = 1)
</code>```

If you want to just select these rows use slicing:

```<code>df[df.applymap(lambda substring: substring in string).any(axis = 1)]
</code>```

Body:
I'd like to filter my dataframe such that only rows that have a column containing a substring of another string are selected. I know that the opposite can be done like this:

selection = df[df.str.contains(substring)]

But how would I do it such that the substring is in the dataframe and it is compared to another string. What I've tried are

import pandas
a = pandas.DataFrame({"b":["foo","bar"]})
selection = a[a.b.str in "foot"] # should match first row
selection = a[a.b.str.isin("foot")] # should match first row
selection = a[a.b.str.isin("foobar")] # should match both rows

but these won't work

Body:
What you could try is make function like so:

f = lambda substring: substring in string

Where string is your target string. Then, apply this function elementwise to the df.

df.applymap(f)

This should return a DataFrame with True where the element is a substring of your target string, and False where it isn't. To find out which rows contain a True, i.e. contain elements that are substrings of your target string, us df.any():

df.applymap(lambda substring: substring in string).any(axis = 1)

If you want to just select these rows use slicing:

df[df.applymap(lambda substring: substring in string).any(axis = 1)]


问:
how to generate keypair from secret phrase (mnemonic) SOLANA
I am working with Solana and phantom wallet I have a wallet with a public key and I have it's secret phrase composed of 12 words.
when I generate keypairs from the secret phrase I use:

```<code>const getKeyPair = (mnemomic) => {
  const seed = bip39.mnemonicToSeedSync(mnemomic).slice(0, 32);
  const Keypair = web3.Keypair.fromSeed(seed);
  return Keypair;
};
</code>```

the generated keypair has publicKey and privateKey , but when am checking my balance using the generated public key I find the balance is always 0 even when I try to airdrop Sol using my code it's not getting in the account.

But if I check using my public key from phantom wallet I get the Sol I have and if I want to airdrop sols they also proceed normally.

Why is my generated public key not the same as the one in phantom wallet?

答: solana-keygen recover 'prompt:?key=0/0' -o phantom_wallet.json

Body:
I am working with Solana and phantom wallet I have a wallet with a public key and I have it's secret phrase composed of 12 words.
when I generate keypairs from the secret phrase I use:

const getKeyPair = (mnemomic) => {
  const seed = bip39.mnemonicToSeedSync(mnemomic).slice(0, 32);
  const Keypair = web3.Keypair.fromSeed(seed);
  return Keypair;
};

the generated keypair has publicKey and privateKey , but when am checking my balance using the generated public key I find the balance is always 0 even when I try to airdrop Sol using my code it's not getting in the account.

But if I check using my public key from phantom wallet I get the Sol I have and if I want to airdrop sols they also proceed normally.

Why is my generated public key not the same as the one in phantom wallet?


问:
Need array of specificed key which exists within array of array
So here is the data format in JSON. I need an array which contains all the array within  "data_array".There can be multiple items in "main_array".Is there any way to do this without using any loop.Thank you

```<code>{
    "id" : "60561bbd1be6cb1972254ec4",
    "main_array": [
         {
            "data_array": [
                {
                    "_id": "6054d5c3dbd0af1cca71b857",
                    "qty" : 2000
                }
            ]
         },
         {
            "data_array": [
                {
                    "_id": "6054d5c3dbd0af1cca71b859",
                    "qty" : 78970
                },
                {
                    "_id": "6054d5c3dbd0af1cca71b860",
                    "qty" : 978
                }
            ]
        }
    ]
}
</code>```

This is the expected array

```<code>[
         {
                    "_id": "6054d5c3dbd0af1cca71b857",
                    "qty" : 2000
         },
          {
             "id": "6054d5c3dbd0af1cca71b859",
             "qty" : 78970
          },
          {
             "_id": "6054d5c3dbd0af1cca71b860",
             "qty" : 978
          }

]

</code>```

Currently I'm doing this

```<code>$expectedArray = [];
foreach($inputs['main_array'] as $mainArray){
    $expectedArray =array_merge($expectedArray,$mainArray['data_array']);
}
</code>```

答:
I got the answer to this question from here
https://laracasts.com/discuss/channels/laravel/need-array-of-specificed-key-which-exists-within-array-of-array?page=1&replyId=771482

As I'm already getting converted data in array form.I removed json_decode().

```<code>$collect = collect($inputs['main_array']);
$data = $collect->pluck('data_array');
$flat = collect($data)->flatten(1);
</code>```

Body:
So here is the data format in JSON. I need an array which contains all the array within  "data_array".There can be multiple items in "main_array".Is there any way to do this without using any loop.Thank you

{
    "id" : "60561bbd1be6cb1972254ec4",
    "main_array": [
         {
            "data_array": [
                {
                    "_id": "6054d5c3dbd0af1cca71b857",
                    "qty" : 2000
                }
            ]
         },
         {
            "data_array": [
                {
                    "_id": "6054d5c3dbd0af1cca71b859",
                    "qty" : 78970
                },
                {
                    "_id": "6054d5c3dbd0af1cca71b860",
                    "qty" : 978
                }
            ]
        }
    ]
}

This is the expected array

[
         {
                    "_id": "6054d5c3dbd0af1cca71b857",
                    "qty" : 2000
         },
          {
             "id": "6054d5c3dbd0af1cca71b859",
             "qty" : 78970
          },
          {
             "_id": "6054d5c3dbd0af1cca71b860",
             "qty" : 978
          }

]

Currently I'm doing this

$expectedArray = [];
foreach($inputs['main_array'] as $mainArray){
    $expectedArray =array_merge($expectedArray,$mainArray['data_array']);
}

Body:
I got the answer to this question from here
https://laracasts.com/discuss/channels/laravel/need-array-of-specificed-key-which-exists-within-array-of-array?page=1&replyId=771482

As I'm already getting converted data in array form.I removed json_decode().

$collect = collect($inputs['main_array']);
$data = $collect->pluck('data_array');
$flat = collect($data)->flatten(1);


问:
Detect/Segment hatch-filled rectangles OpenCV

The problem

I need to detect hatch-filled rectangles on a huge image. There are other lines and forms connected to the hatch-filled rectangle. My desired output would be like the black form on the right side of the image. All other forms (not hatch-filled rectangles) are ignored and not in the output.

What I tried:

Build a mask by using a Hough transformation and calculating the angles of the detected lines. Ignore everything that is not about 45°. Use dilation to fill the detected lines into a rectangle. Form a mask and apply it to the gray image. Here I was able to detect the lines for the upper left rectangle, but not for the one in the bottom (lines too short?). Furthermore, this did not work if other lines are attached to the rectangle (as can be seen in the upper left).

Any ideas on how to approach this problem the best way?

答:
For what it is worth:

detect all lines slanted by 45°,

erase all them in the middle,

seed fill from a pixel in the middle.

This will fail for hatches with another angle, for legit 45° lines and for shapes that are not properly closed. Antialiasing along the edges will also cause issues. You may binarize first, but slanted/round edges will turn ugly.

Update:

You can improve the result by applying a morphological closing with a square element, which will respect the rectangular shapes and erase the thin lines. Then AND with the original.


问:
Cannot find 'LeftSegment' & Cannot find 'infer' error in react-router folder in node_modules
I am trying to upgrade my app from react-router v3 to v6 actually I installed react-router-dom v6.2.1 and also the react-router v6.2, I am using Typescript so I installed @types as well. @types/react-router v5.1.18 and @types/react-router-dom v5.3.3 with typescript v3.8.

I am getting these two errors,

Cannot find 'LeftSegment' in node_modules/react-router/index.d.ts

Cannot find 'infer' in node_modules/react-router/index.d.ts

答:
Try to update your typescript version:

```<code>npm i --save-dev typescript@latest
</code>```

Solution by @dolig on previous post.

Body:
Try to update your typescript version:

npm i --save-dev typescript@latest

Solution by @dolig on previous post.


问:
get values from json request
i have this json response

2022-02-08 14:01:56,048 sdc-web-sockets-pp
/moe.com/SMART/logs/srf/srf-web-sockets.log: 2022-02-08 14:01:50,308
srf-web-sockets-pp-1 INFO  [null:-1] (executor-thread-19) Op16 -
Station : id-00003:vdeURRi8v8evU8AZWEnIwtbrucvjdeZyJL42,
MessageId: a8a3e920-88e7-11ec-8f9b-c904565fadef, request message:
{"action":"Boot","messageId":"a8d3r920-88e7-11ec-8f9b-c9074d5fadef","type":"CALL","uniqueId":"a8a3e920-88e7-11ec-8f9b-c9074d5fadef","payload":"{"Vendor":"vendorname","PointModel":"pointname","PointSerialNumber":"123456789","firmwareVersion":"1.1.1.8"}"}

I need to get the specific vars.

ex:

vendname=vendorname

model= pointname

modelsn= 123456789

firmversion=1.1.1.8

Can someone help me get these values from the request?

this is what i have so far

```<code>def getvalboot(e):
        jsrqs = e.widget.get("1.0", "end-1c")
        if "BOOT" in jsrqs.upper():
            j1,j2ff = jsrqs.split(r"payload")
            j2f = j2ff.replace("\\", "")
            j2a = j2f[3:]
            size = len(j2a)
            j2 = j2a[:size - 2]
            stud_obj = json.loads(j2)
            print("1: ",stud_obj['Vendor'])
</code>```

Ok, this works but im pretty sure there is a better way to do this, any idea?

答:
It is harder to help when you don't share a bit of code for context.

Assuming we have a context like this:

```<code>message = some_api_call()
</code>```

I would try this:

```<code>data = message['payload'] #message is a dictionary and we'd like to access the payload/data

vendname = data['Vendor']
model = data['PointModel']
modelsn = data['PointSerialNumber']
firmversion = data['firmwareVersion']
</code>```

I don't like the idea of creating a variable for each info, but since it is a small bit of code and we only have one row of data returned, it might not be relevant to discuss that.

Title: get values from json request

Body:
i have this json response

2022-02-08 14:01:56,048 sdc-web-sockets-pp
/moe.com/SMART/logs/srf/srf-web-sockets.log: 2022-02-08 14:01:50,308
srf-web-sockets-pp-1 INFO  [null:-1] (executor-thread-19) Op16 -
Station : id-00003:vdeURRi8v8evU8AZWEnIwtbrucvjdeZyJL42,
MessageId: a8a3e920-88e7-11ec-8f9b-c904565fadef, request message:
{"action":"Boot","messageId":"a8d3r920-88e7-11ec-8f9b-c9074d5fadef","type":"CALL","uniqueId":"a8a3e920-88e7-11ec-8f9b-c9074d5fadef","payload":"{"Vendor":"vendorname","PointModel":"pointname","PointSerialNumber":"123456789","firmwareVersion":"1.1.1.8"}"}

I need to get the specific vars.

ex:

vendname=vendorname

model= pointname

modelsn= 123456789

firmversion=1.1.1.8

Can someone help me get these values from the request?

this is what i have so far

def getvalboot(e):
        jsrqs = e.widget.get("1.0", "end-1c")
        if "BOOT" in jsrqs.upper():
            j1,j2ff = jsrqs.split(r"payload")
            j2f = j2ff.replace("\\", "")
            j2a = j2f[3:]
            size = len(j2a)
            j2 = j2a[:size - 2]
            stud_obj = json.loads(j2)
            print("1: ",stud_obj['Vendor'])

Ok, this works but im pretty sure there is a better way to do this, any idea?

Body:
It is harder to help when you don't share a bit of code for context.

Assuming we have a context like this:

message = some_api_call()

I would try this:

data = message['payload'] #message is a dictionary and we'd like to access the payload/data

vendname = data['Vendor']
model = data['PointModel']
modelsn = data['PointSerialNumber']
firmversion = data['firmwareVersion']

I don't like the idea of creating a variable for each info, but since it is a small bit of code and we only have one row of data returned, it might not be relevant to discuss that.


问:
Error type 'Null' is not a subtype of type 'Timestamp'
I am setting the current date in firebase and trying to retrieve it to use as a reference. But somehow the results vary. Sometimes I'm having a null value but sometimes it's okay. I tried to add a delay command but it is still behaving the same. Please help. Thanks!

```<code>        //set current date
        await db.collection(Paths.playersPath).doc(uid).set({
          'currDate': FieldValue.serverTimestamp(),
        }, SetOptions(merge: true));

        DocumentSnapshot<Map<String, dynamic>> documentSnapshot =
            await db.collection(Paths.playersPath).doc(uid).get();

        Timestamp currDate = documentSnapshot.data()!['currDate'];

</code>```

Edit: I'm not really sure if it is connected but I have 2 methods that call the same logic. One is under a HookWidget which almost always fail and another in StatefulWidget which never have a problem.

Edit: I don't really know why. But when I move the event which update the current date to a Stateful Widget, it is now working. Hopefully someone can clarify this.

答:
Can you try this:

db.collection(Paths.playersPath).doc(uid).get().then((value) => value.data()!['currDate']);

You can also try to chain then with db.collection(Paths.playersPath).doc(uid).set if still not working

Body:
I am setting the current date in firebase and trying to retrieve it to use as a reference. But somehow the results vary. Sometimes I'm having a null value but sometimes it's okay. I tried to add a delay command but it is still behaving the same. Please help. Thanks!

        //set current date
        await db.collection(Paths.playersPath).doc(uid).set({
          'currDate': FieldValue.serverTimestamp(),
        }, SetOptions(merge: true));

        DocumentSnapshot<Map<String, dynamic>> documentSnapshot =
            await db.collection(Paths.playersPath).doc(uid).get();

        Timestamp currDate = documentSnapshot.data()!['currDate'];

Edit: I'm not really sure if it is connected but I have 2 methods that call the same logic. One is under a HookWidget which almost always fail and another in StatefulWidget which never have a problem.

Edit: I don't really know why. But when I move the event which update the current date to a Stateful Widget, it is now working. Hopefully someone can clarify this.


问:
How can I tell gcc not to inline a function?
Say I have this small function in a source file

```<code>static void foo() {}
</code>```

and I build an optimized version of my binary yet I don't want this function inlined (for optimization purposes). is there a macro I can add in a source code to prevent the inlining?

答:
GCC has a switch called

-fno-inline-small-functions

So use that when invoking gcc. But the side effect is that all other small functions are also non-inlined.

Body:
Say I have this small function in a source file

static void foo() {}

and I build an optimized version of my binary yet I don't want this function inlined (for optimization purposes). is there a macro I can add in a source code to prevent the inlining?


问:
How do you rename the elements of a list when they are nested within another list using R's purrr package?
The NBER dates recessions by their peak and trough.  The json version of the data is here. A simple version looks like this:

```<code>list_old <- list(list(peak = "", trough = "1854-12-01"), list(peak = "1857-06-01", trough = "1858-12-01"))
</code>```

In order for plotBands to be displayed in the highcharter package, the lists must be renamed so that "peak" becomes "start" and "trough" becomes "end".  The resulting list would look like this:

```<code>list_new <- list(list(start = "", end = "1854-12-01"), list(start = "1857-06-01", end = "1858-12-01"))
</code>```

Is there a way to achieve this using the tidyverse in R?  (I've been looking in the purrr package.)

Body:
The NBER dates recessions by their peak and trough.  The json version of the data is here. A simple version looks like this:

list_old <- list(list(peak = "", trough = "1854-12-01"), list(peak = "1857-06-01", trough = "1858-12-01"))

In order for plotBands to be displayed in the highcharter package, the lists must be renamed so that "peak" becomes "start" and "trough" becomes "end".  The resulting list would look like this:

list_new <- list(list(start = "", end = "1854-12-01"), list(start = "1857-06-01", end = "1858-12-01"))

Is there a way to achieve this using the tidyverse in R?  (I've been looking in the purrr package.)

Body:
You can just use lapply to rename each list.

lapply(list_old, \(x) {
  names(x) <- c("start", "end")
  x
  }
)
#> [[1]]
#> [[1]]$start
#> [1] ""
#>
#> [[1]]$end
#> [1] "1854-12-01"
#>
#>
#> [[2]]
#> [[2]]$start
#> [1] "1857-06-01"
#>
#> [[2]]$end
#> [1] "1858-12-01"

You could use purrr::map() if you'd rather a tidy solution. If using purrr, from @Donald Seinen's comment, can also use set_names()

library(purrr)

map(
  list_old,
  set_names,
  c("start", "end")
)
#> [[1]]
#> [[1]]$start
#> [1] ""
#>
#> [[1]]$end
#> [1] "1854-12-01"
#>
#>
#> [[2]]
#> [[2]]$start
#> [1] "1857-06-01"
#>
#> [[2]]$end
#> [1] "1858-12-01"