问:
can't able to get file using id in mongo db python
I have mongoDB database. I'm trying to get file from GridFS collection of mongodb

below is the code

```<code>def get_file(id):
    fs = gridfs.GridFS(user, collection="bb_attachments")
    # print('get file using id')
    file_found = fs.exists(_id=id)
    print('file found {}'.format(file_found))
    if file_found:
        fg = fs.find({"_id": id})
        for f in fg:
            print(f._id)

def get_file_name(name):
    fs = gridfs.GridFS(user, collection="bb_attachments")
    # print('get file using file name')
    file_found = fs.exists({"filename":name})
    print('file found {}'.format(file_found))
    if file_found:
        fg = fs.find({"filename": name})
        for f in fg:
            print(f._id)

print("\n\n get file using name ********* ")
get_file_name('file')
print("\n\n get file using id *********")
get_file('63ac2dc8329de4e0c1d11b8a')
</code>```

here is output

```<code>get file using name *********
file found True
63ac2dc8329de4e0c1d11b8a
</code>```
```<code>get file using id *********
file found False
</code>```

what I am missing here, why I'm not able to get file using id. where as I can get file details using file name

Body:
I have mongoDB database. I'm trying to get file from GridFS collection of mongodb

below is the code

def get_file(id):
    fs = gridfs.GridFS(user, collection="bb_attachments")
    # print('get file using id')
    file_found = fs.exists(_id=id)
    print('file found {}'.format(file_found))
    if file_found:
        fg = fs.find({"_id": id})
        for f in fg:
            print(f._id)

def get_file_name(name):
    fs = gridfs.GridFS(user, collection="bb_attachments")
    # print('get file using file name')
    file_found = fs.exists({"filename":name})
    print('file found {}'.format(file_found))
    if file_found:
        fg = fs.find({"filename": name})
        for f in fg:
            print(f._id)

print("\n\n get file using name ********* ")
get_file_name('file')
print("\n\n get file using id *********")
get_file('63ac2dc8329de4e0c1d11b8a')

here is output

get file using name *********
file found True
63ac2dc8329de4e0c1d11b8a

get file using id *********
file found False

what I am missing here, why I'm not able to get file using id. where as I can get file details using file name


来源: stackexchange

问:
bundled index.html doesnt contains script tag for bundled js file(react + esbuild)
I use react with esbuild for bundling, but after bundling index.html doesnt contain script tag that references to js file(main.js file exists right beside of index.html)

these are my ralated configs:

```<code>//esbuild.conig.js

import { build } from "esbuild";
import process from "process";
import { sassPlugin } from "esbuild-sass-plugin";

const isProd = process.argv[2] === "production";

build({
  inject: ['./config/react-shim.js'],
  entryPoints: ["src/index.js"],
  bundle: true,
  entryNames: '[name]-[hash]',
  outfile: "build/main.js",
  publicPath: "/",
  sourcemap: isProd ? false : "inline",
  minify: isProd ? true : false,
  packages: 'external',
  loader: {
    ".webp": "file",
    ".png": "file",
    ".svg": "text",`your text`
    ".js": "jsx",
  },
  plugins: [
    sassPlugin({
      type: "css-text",
      // for the options availanle look at 'SassPluginOptions' in index.ts
    }),
  ],
}).catch(() => process.exit(1));
</code>```
```<code>

</code>```
```<code>//jsconfig.json
{
    "compilerOptions": {
      "target": "ES2018",
      "lib": [
        "dom",
        "dom.iterable",
        "esnext"
      ],
      "allowJs": true,
      "checkJs": true,
      "skipLibCheck": true,
      "esModuleInterop": true,
      "allowSyntheticDefaultImports": true,
      "strict": true,
      "forceConsistentCasingInFileNames": true,
      "noFallthroughCasesInSwitch": true,
      "module": "esnext",
      "moduleResolution": "node",
      "resolveJsonModule": true,
      "noEmit": true,
      "jsx": "react-jsx",
      "baseUrl": "./src/"
    },
    "include": [
      "src"
    ]
  }
</code>```

and this is my build script in package.json

```<code>"copy:public": "cp -r public/ build/",
    "build:code": "node --es-module-specifier-resolution=node esbuild.config.js",
    "build:public": "npm run copy:public && postbuild -i public/index.html -o build/index.html --css build/ --js build/ ",
    "build": "export NODE_ENV=production && npm run build:code && npm run build:public",
</code>```

Anyone can help me?

ContentLicense: CC BY-SA 4.0

Body:
I use react with esbuild for bundling, but after bundling index.html doesnt contain script tag that references to js file(main.js file exists right beside of index.html)

these are my ralated configs:

//esbuild.conig.js

import { build } from "esbuild";
import process from "process";
import { sassPlugin } from "esbuild-sass-plugin";

const isProd = process.argv[2] === "production";

build({
  inject: ['./config/react-shim.js'],
  entryPoints: ["src/index.js"],
  bundle: true,
  entryNames: '[name]-[hash]',
  outfile: "build/main.js",
  publicPath: "/",
  sourcemap: isProd ? false : "inline",
  minify: isProd ? true : false,
  packages: 'external',
  loader: {
    ".webp": "file",
    ".png": "file",
    ".svg": "text",`your text`
    ".js": "jsx",
  },
  plugins: [
    sassPlugin({
      type: "css-text",
      // for the options availanle look at 'SassPluginOptions' in index.ts
    }),
  ],
}).catch(() => process.exit(1));

//jsconfig.json
{
    "compilerOptions": {
      "target": "ES2018",
      "lib": [
        "dom",
        "dom.iterable",
        "esnext"
      ],
      "allowJs": true,
      "checkJs": true,
      "skipLibCheck": true,
      "esModuleInterop": true,
      "allowSyntheticDefaultImports": true,
      "strict": true,
      "forceConsistentCasingInFileNames": true,
      "noFallthroughCasesInSwitch": true,
      "module": "esnext",
      "moduleResolution": "node",
      "resolveJsonModule": true,
      "noEmit": true,
      "jsx": "react-jsx",
      "baseUrl": "./src/"
    },
    "include": [
      "src"
    ]
  }

and this is my build script in package.json

"copy:public": "cp -r public/ build/",
    "build:code": "node --es-module-specifier-resolution=node esbuild.config.js",
    "build:public": "npm run copy:public && postbuild -i public/index.html -o build/index.html --css build/ --js build/ ",
    "build": "export NODE_ENV=production && npm run build:code && npm run build:public",

Anyone can help me?


问:
How to get data from protected API route
I need to get data from protected API route. I am using Next Auth with google provider.
I have seen some solutions to similar problem but all of them were using JWT token. I don't use JWT. I don't have much experience with auth so I don't know what to pass to axios request.

This is /api/auth/[...nextauth].ts

```<code>import NextAuth, { NextAuthOptions } from 'next-auth'
import GoogleProvider from 'next-auth/providers/google'
import { PrismaAdapter } from '@next-auth/prisma-adapter'
import { prisma } from '../../../server/client'

export const authOptions: NextAuthOptions = {
    adapter: PrismaAdapter(prisma),
    providers: [
        GoogleProvider({
            clientId: process.env.GOOGLE_CLIENT_ID as string,
            clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
        }),
    ],
    session: {
        strategy: 'database',
    },
}

export default NextAuth(authOptions)

</code>```

This is how my route is protected:

```<code>    const session = await getServerAuthSession({ req, res })

    if (!session) {
        return res.status(403).send({
            error: 'You must be signed in to view the protected content on this page.',
        })
    }
</code>```

This is get-server-auth-session.ts file

```<code>// Wrapper for unstable_getServerSession https://next-auth.js.org/configuration/nextjs

import type { GetServerSidePropsContext } from 'next'
import { unstable_getServerSession } from 'next-auth'
import { authOptions as nextAuthOptions } from '../../pages/api/auth/[...nextauth]'

// Next API route example - /pages/api/restricted.ts
export const getServerAuthSession = async (ctx: {
    req: GetServerSidePropsContext['req']
    res: GetServerSidePropsContext['res']
}) => {
    return await unstable_getServerSession(
        ctx.req,
        ctx.res,
        nextAuthOptions
    )
}

</code>```

Body:
I need to get data from protected API route. I am using Next Auth with google provider.
I have seen some solutions to similar problem but all of them were using JWT token. I don't use JWT. I don't have much experience with auth so I don't know what to pass to axios request.

This is /api/auth/[...nextauth].ts

import NextAuth, { NextAuthOptions } from 'next-auth'
import GoogleProvider from 'next-auth/providers/google'
import { PrismaAdapter } from '@next-auth/prisma-adapter'
import { prisma } from '../../../server/client'

export const authOptions: NextAuthOptions = {
    adapter: PrismaAdapter(prisma),
    providers: [
        GoogleProvider({
            clientId: process.env.GOOGLE_CLIENT_ID as string,
            clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
        }),
    ],
    session: {
        strategy: 'database',
    },
}

export default NextAuth(authOptions)

This is how my route is protected:

    const session = await getServerAuthSession({ req, res })

    if (!session) {
        return res.status(403).send({
            error: 'You must be signed in to view the protected content on this page.',
        })
    }

This is get-server-auth-session.ts file

// Wrapper for unstable_getServerSession https://next-auth.js.org/configuration/nextjs

import type { GetServerSidePropsContext } from 'next'
import { unstable_getServerSession } from 'next-auth'
import { authOptions as nextAuthOptions } from '../../pages/api/auth/[...nextauth]'

// Next API route example - /pages/api/restricted.ts
export const getServerAuthSession = async (ctx: {
    req: GetServerSidePropsContext['req']
    res: GetServerSidePropsContext['res']
}) => {
    return await unstable_getServerSession(
        ctx.req,
        ctx.res,
        nextAuthOptions
    )
}


问:
Reading spatial data from mapped network drive
I am working with a shared folder containing multiple datasets. Because this is part of a teamwork and so that we can all use the same scripts without the need to always update the local paths in our personal machines, we mapped the shared folder as a network drive.
Of course tat the content in the shared folder and the network drive is the same. However, when reading spatial data such as a gdb or shp from the mapped drive it returns an empty feature collection or error (see examples below).

I apologize for not providing a reproducible example, but I don't think it’s possible in this instance.

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

#Shared main dir
shared.dir <- 'N:/mapped_path/'

#Data dir
data.dir <- paste0(shared.dir, 'data/')

# Reading gdb file from mapped_path (N:\\)
dsn <- paste0(data.dir, "file.gdb")
dat_raw <- st_read(dsn, layer = 'annual')

#################################
# Returns empty feature collection
Reading layer `annual' from data source
  `N:\mapped_path\data\file.gdb'
  using driver `OpenFileGDB'
Simple feature collection with 0 features and 0 fields
Bounding box:  xmin: NA ymin: NA xmax: NA ymax: NA
Geodetic CRS:  WGS 84
Warning message:
In CPL_read_ogr(dsn, layer, query, as.character(options), quiet,  :
  GDAL Error 4: Cannot open N:\mapped_path\data\file.gdb\a00000009.gdbtable (layer annual): No error
#####################################

# Reading shp file from mapped_path (N:\\)
dat_sf <- st_read(paste0(data.dir, “file.shp”))
#####################################
Error: Cannot open "N:\mapped_path\data\file.shp"; The source could be corrupt or not supported. See `st_drivers()` for a list of supported formats.
In addition: Warning message:
In CPL_read_ogr(dsn, layer, query, as.character(options), quiet,  :
  GDAL Message 4: Failed to open .
#####################################
</code>```

I can easily read csv files from mapped_path

```<code># Reading csv file from mapped_path
pa_dat <- read_delim(paste0(data.dir, "file.csv"),
name_repair = 'universal')

head(pa_dat)
# A tibble: 6 × 4
  Country.Name                Country.Code Indicator.Name                                     PA_coverage
  <chr>                       <chr>        <chr>                                                    <dbl>
1 Aruba                       ABW          Terrestrial protected areas (% of total land area)       18.9
2 Africa Eastern and Southern AFE          Terrestrial protected areas (% of total land area)       16.9
3 Afghanistan                 AFG          Terrestrial protected areas (% of total land area)        3.64
4 Africa Western and Central  AFW          Terrestrial protected areas (% of total land area)       15.7
5 Angola                      AGO          Terrestrial protected areas (% of total land area)        6.97
</code>```

And if I use the local path (pointing to the same files as before) I can read the spatial data without any problem:

```<code># Reading gdb file from local_path (C:\\)
dsn <- "C:\\local_path\\file.gdb"
dat_raw <- st_read(dsn, layer = 'annual')

#####################################
# Returns feature collection with 68506
Reading layer `annual' from data source
  `C:\local_path\file.gdb'
  using driver `OpenFileGDB'
replacing null geometries with empty geometries
Simple feature collection with 68506 features and 262 fields (with 12 geometries empty)
Geometry type: MULTIPOLYGON
Dimension:     XY
Bounding box:  xmin: -180 ymin: -89.99999 xmax: 180.0006 ymax: 83.65833
Geodetic CRS:  WGS 84
Warning message:
In CPL_read_ogr(dsn, layer, query, as.character(options), quiet,  :
  GDAL Message 1: organizePolygons() received a polygon with more than 100 parts. The processing may be really slow.  You can skip the processing by setting METHOD=SKIP, or only make it analyze counter-clock wise parts by setting METHOD=ONLY_CCW if you can assume that the outline of holes is counter-clock wise defined
#####################################

# Reading shp file from local_path (C:\\)
dat_sf <- st_read("C:\\local_path\\file.shp")
#####################################
Reading layer `file' from data source
  `C:\local_path\file.shp'
  using driver `ESRI Shapefile'
Simple feature collection with 6933 features and 6 fields
Geometry type: MULTIPOLYGON
Dimension:     XY
Bounding box:  xmin: -171.7608 ymin: -54.77436 xmax: 179.4398 ymax: 81.35914
Geodetic CRS:  WGS 84
#####################################
</code>```

Interestingly my colleague can read these files using the exact same approach. Any clue on what the problem (and solution) might be when reading spatial data from the mapped network would be very much appreciated.

Body:
I am working with a shared folder containing multiple datasets. Because this is part of a teamwork and so that we can all use the same scripts without the need to always update the local paths in our personal machines, we mapped the shared folder as a network drive.
Of course tat the content in the shared folder and the network drive is the same. However, when reading spatial data such as a gdb or shp from the mapped drive it returns an empty feature collection or error (see examples below).

I apologize for not providing a reproducible example, but I don't think it’s possible in this instance.

library(sf)
library(tidyverse)

#Shared main dir
shared.dir <- 'N:/mapped_path/'

#Data dir
data.dir <- paste0(shared.dir, 'data/')

# Reading gdb file from mapped_path (N:\\)
dsn <- paste0(data.dir, "file.gdb")
dat_raw <- st_read(dsn, layer = 'annual')

#################################
# Returns empty feature collection
Reading layer `annual' from data source
  `N:\mapped_path\data\file.gdb'
  using driver `OpenFileGDB'
Simple feature collection with 0 features and 0 fields
Bounding box:  xmin: NA ymin: NA xmax: NA ymax: NA
Geodetic CRS:  WGS 84
Warning message:
In CPL_read_ogr(dsn, layer, query, as.character(options), quiet,  :
  GDAL Error 4: Cannot open N:\mapped_path\data\file.gdb\a00000009.gdbtable (layer annual): No error
#####################################

# Reading shp file from mapped_path (N:\\)
dat_sf <- st_read(paste0(data.dir, “file.shp”))
#####################################
Error: Cannot open "N:\mapped_path\data\file.shp"; The source could be corrupt or not supported. See `st_drivers()` for a list of supported formats.
In addition: Warning message:
In CPL_read_ogr(dsn, layer, query, as.character(options), quiet,  :
  GDAL Message 4: Failed to open .
#####################################

I can easily read csv files from mapped_path

# Reading csv file from mapped_path
pa_dat <- read_delim(paste0(data.dir, "file.csv"),
name_repair = 'universal')

head(pa_dat)
# A tibble: 6 × 4
  Country.Name                Country.Code Indicator.Name                                     PA_coverage
  <chr>                       <chr>        <chr>                                                    <dbl>
1 Aruba                       ABW          Terrestrial protected areas (% of total land area)       18.9
2 Africa Eastern and Southern AFE          Terrestrial protected areas (% of total land area)       16.9
3 Afghanistan                 AFG          Terrestrial protected areas (% of total land area)        3.64
4 Africa Western and Central  AFW          Terrestrial protected areas (% of total land area)       15.7
5 Angola                      AGO          Terrestrial protected areas (% of total land area)        6.97

And if I use the local path (pointing to the same files as before) I can read the spatial data without any problem:

# Reading gdb file from local_path (C:\\)
dsn <- "C:\\local_path\\file.gdb"
dat_raw <- st_read(dsn, layer = 'annual')

#####################################
# Returns feature collection with 68506
Reading layer `annual' from data source
  `C:\local_path\file.gdb'
  using driver `OpenFileGDB'
replacing null geometries with empty geometries
Simple feature collection with 68506 features and 262 fields (with 12 geometries empty)
Geometry type: MULTIPOLYGON
Dimension:     XY
Bounding box:  xmin: -180 ymin: -89.99999 xmax: 180.0006 ymax: 83.65833
Geodetic CRS:  WGS 84
Warning message:
In CPL_read_ogr(dsn, layer, query, as.character(options), quiet,  :
  GDAL Message 1: organizePolygons() received a polygon with more than 100 parts. The processing may be really slow.  You can skip the processing by setting METHOD=SKIP, or only make it analyze counter-clock wise parts by setting METHOD=ONLY_CCW if you can assume that the outline of holes is counter-clock wise defined
#####################################

# Reading shp file from local_path (C:\\)
dat_sf <- st_read("C:\\local_path\\file.shp")
#####################################
Reading layer `file' from data source
  `C:\local_path\file.shp'
  using driver `ESRI Shapefile'
Simple feature collection with 6933 features and 6 fields
Geometry type: MULTIPOLYGON
Dimension:     XY
Bounding box:  xmin: -171.7608 ymin: -54.77436 xmax: 179.4398 ymax: 81.35914
Geodetic CRS:  WGS 84
#####################################

Interestingly my colleague can read these files using the exact same approach. Any clue on what the problem (and solution) might be when reading spatial data from the mapped network would be very much appreciated.


问:
How to hide a field on a condition of selection of another field in javascript?
I have a mainpage.html where I have 2 fields Testtitle and testtype.
 In testtype we have 2 options Offline and Online.
 And through I frame I have called a seperate html page in that I have 2 f sepearte fields which has the fields Name and productname.

My problem is I am not able to hide the productname field on a condition where if the testtype is offline.The producttype field should not be visible on if testtype is selcted as offline.
Can Anyone help on this?

```<code>Mainpage.html
</code>```
```<code><tr>
                    <td>
                        <label class="detailsLabelClass">Title</label>
                    </td>
                    <td>
                        <label id="TestTitle"></label>
                    </td>
                    <td>
                        <label>Type</label>
                    </td>
                    <td>
                        <label id="TestType"></label>
                    </td>
                </tr>
</code>```

```
Testpage.html
```

                     Name

                    <input type="text" id="txt1" />

                    Product Name<

                    <input type="text" id="txt2" />

```
<p>Mainpage.js</p>
```function LoadProtocolMainPage() {
var MasterModel = new Object();

MasterModel.Testtitle = document.getElementById("Testtitle").innerHTML;
$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    dataType: 'json',
    data: JSON.stringify(MasterModel),
    url: "https://localhost:44/api/MainPage/MasterGet",

    success: function (responses, textStatus, XMLHttpRequest) {
        if (responses == "Unable to fetch information") {
            alert(responses);
        }
        else {
            obj = JSON.parse(responses);
            if (obj.testtype == "true") {
                document.getElementById("testType").innerHTML = "Offline";
            }
            else
            {
                document.getElementById("testType").innerHTML = "Online";
            }
            var TestpageIFramee = document.getElementById("iframeTestpage");
            var TestPageDoc = TestpageIFramee.contentDocument
                || TestpageIFramee.contentWindow.document;

            TestPageDoc.getElementById("Name").value = obj.Name;
            TestPageDoc.getElementById("ProductName").value = obj.ProductName;
```

Body:
I have a mainpage.html where I have 2 fields Testtitle and testtype.
 In testtype we have 2 options Offline and Online.
 And through I frame I have called a seperate html page in that I have 2 f sepearte fields which has the fields Name and productname.

My problem is I am not able to hide the productname field on a condition where if the testtype is offline.The producttype field should not be visible on if testtype is selcted as offline.
Can Anyone help on this?

Mainpage.html

                        Title

                        Type

```
Testpage.html

                     Name

                    <input type="text" id="txt1" />

                    Product Name<

                    <input type="text" id="txt2" />

Mainpage.js

function LoadProtocolMainPage() {
var MasterModel = new Object();

MasterModel.Testtitle = document.getElementById("Testtitle").innerHTML;
$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    dataType: 'json',
    data: JSON.stringify(MasterModel),
    url: "https://localhost:44/api/MainPage/MasterGet",

    success: function (responses, textStatus, XMLHttpRequest) {
        if (responses == "Unable to fetch information") {
            alert(responses);
        }
        else {
            obj = JSON.parse(responses);
            if (obj.testtype == "true") {
                document.getElementById("testType").innerHTML = "Offline";
            }
            else
            {
                document.getElementById("testType").innerHTML = "Online";
            }
            var TestpageIFramee = document.getElementById("iframeTestpage");
            var TestPageDoc = TestpageIFramee.contentDocument
                || TestpageIFramee.contentWindow.document;

            TestPageDoc.getElementById("Name").value = obj.Name;
            TestPageDoc.getElementById("ProductName").value = obj.ProductName;


问:
laravel - model as pivot also needs withPivot to return it's fillable fields
On laravel docs I found a guide to use a Model as Pivot on many-tomany relation.
https://laravel.com/docs/5.6/eloquent-relationships#many-to-many
(scroll to section "Defining Custom Intermediate Table Models")

So I'm trying it and it is working.

Models

```<code>Channel        => title
Company        => id
</code>```

Tables

```<code>channels         => id, title
companies        => id
company_channel  => channel_id, company_id, SCORE
</code>```

Pivot model

```<code>class CompanyChannel extends Pivot
{
  protected $table = 'company_channels';
  public $timestamps = false;

  protected $fillable = [
    'score',   <<<<<========= PIVOT FIELD I NEED
  ];
</code>```

The problem is the serialized json doesn't include pivot-model fields.

```<code>public function channels() { return $this->belongsToMany('\App\Channel')->using('App\CompanyChannel'); }

{
  "id": 1,
  "channels": [
    {
      "id": 1,
      "pivot": {
        "empresa_id": 1,
        "channel_id": 1
                      <<<<<====== NOT INCLUDE PIVOT FIELD
      }
    }
  ]
}
</code>```

When I add withPivot to Company model relation, then it returns the field in JSON.

```<code>public function channels() { return $this->belongsToMany('\App\Channel')->using('App\CompanyChannel')->withPivot('score'); }

{
  "id": 1,
  "channels": [
    {
      "id": 1,
      "pivot": {
        "empresa_id": 1,
        "channel_id": 1,
        "score": 50  <<<<<====== NOW IT WORKS
      }
    }
  ]
}
</code>```

So, is there any way to return pivot-model fields automatically? Or do I have to set all fields manually on withPivot?

Body:
On laravel docs I found a guide to use a Model as Pivot on many-tomany relation.
https://laravel.com/docs/5.6/eloquent-relationships#many-to-many
(scroll to section "Defining Custom Intermediate Table Models")

So I'm trying it and it is working.

Models

Channel        => title
Company        => id

Tables

channels         => id, title
companies        => id
company_channel  => channel_id, company_id, SCORE

Pivot model

class CompanyChannel extends Pivot
{
  protected $table = 'company_channels';
  public $timestamps = false;

  protected $fillable = [
    'score',   <<<<<========= PIVOT FIELD I NEED
  ];

The problem is the serialized json doesn't include pivot-model fields.

public function channels() { return $this->belongsToMany('\App\Channel')->using('App\CompanyChannel'); }

{
  "id": 1,
  "channels": [
    {
      "id": 1,
      "pivot": {
        "empresa_id": 1,
        "channel_id": 1
                      <<<<<====== NOT INCLUDE PIVOT FIELD
      }
    }
  ]
}

When I add withPivot to Company model relation, then it returns the field in JSON.

public function channels() { return $this->belongsToMany('\App\Channel')->using('App\CompanyChannel')->withPivot('score'); }

{
  "id": 1,
  "channels": [
    {
      "id": 1,
      "pivot": {
        "empresa_id": 1,
        "channel_id": 1,
        "score": 50  <<<<<====== NOW IT WORKS
      }
    }
  ]
}

So, is there any way to return pivot-model fields automatically? Or do I have to set all fields manually on withPivot?


问:
mainloop() getting stuck on GUI on pyamaze library
I have a code made with pyamaze library which I perform 4 different types of search on maze and I want to display it with GUI (to make the user choose the type of search they want)
but the problem when I run the code the GUI gets stuck

```<code>from pyamaze import maze, COLOR, agent,textLabel
#Depth first search
def DFS(m1):
    start=(m1.rows,m1.cols)
    explored=[start]
    frontier=[start]
    dfsPath={}
    while len(frontier)>0:
        currCell=frontier.pop()
        if currCell==(1,1):
            break
        for d in 'ESNW':
            if m1.maze_map[currCell][d]==True:
                if d=='E':
                    childCell=(currCell[0],currCell[1]+1)
                elif d=='W':
                    childCell=(currCell[0],currCell[1]-1)
                elif d=='S':
                    childCell=(currCell[0]+1,currCell[1])
                elif d=='N':
                    childCell=(currCell[0]-1,currCell[1])
                if childCell in explored:
                    continue
                explored.append(childCell)
                frontier.append(childCell)
                dfsPath[childCell]=currCell
    fwdPath={}
    cell=(1,1)
    while cell!=start:
        fwdPath[dfsPath[cell]]=cell
        cell=dfsPath[cell]
    return fwdPath

#Breadth first search
def BFS(m2):
    start=(m2.rows,m2.cols)
    frontier=[start]
    explored=[start]
    bfsPath={}
    while len(frontier)>0:
        currCell=frontier.pop(0)
        if currCell==(1,1):
            break
        for d in 'ESNW':
            if m2.maze_map[currCell][d]==True:
                if d=='E':
                    childCell=(currCell[0],currCell[1]+1)
                elif d=='W':
                    childCell=(currCell[0],currCell[1]-1)
                elif d=='N':
                    childCell=(currCell[0]-1,currCell[1])
                elif d=='S':
                    childCell=(currCell[0]+1,currCell[1])
                if childCell in explored:
                    continue
                frontier.append(childCell)
                explored.append(childCell)
                bfsPath[childCell]=currCell
    fwdPath={}
    cell=(1,1)
    while cell!=start:
        fwdPath[bfsPath[cell]]=cell
        cell=bfsPath[cell]
    return fwdPath

# A-star search
from queue import PriorityQueue
def h(cell1,cell2):
    x1,y1=cell1
    x2,y2=cell2
    return abs(x1-x2)+abs(y1-y2)
def aStar(m3):
    start=(m3.rows,m3.cols)
    g_score={cell:float('inf') for cell in m3.grid}
    g_score[start]=0
    f_score={cell:float('inf') for cell in m3.grid}
    f_score[start]=h(start,(1,1))
    open=PriorityQueue()
    open.put((h(start,(1,1)),h(start,(1,1)),start))
    aPath={}
    while not open.empty():
        currCell=open.get()[2]
        if currCell==(1,1):
            break
        for d in 'ESNW':
           if m3.maze_map[currCell][d]==True:
             if d=='E':
                childCell=(currCell[0],currCell[1]+1)
             if d=='W':
                childCell=(currCell[0],currCell[1]-1)
             if d=='N':
                childCell=(currCell[0]-1,currCell[1])
             if d=='S':
                childCell=(currCell[0]+1,currCell[1])
             temp_g_score=g_score[currCell]+1
             temp_f_score=temp_g_score+h(childCell,(1,1))
             if temp_f_score < f_score[childCell]:
                g_score[childCell]=temp_g_score
                f_score[childCell]=temp_f_score
                open.put((temp_f_score,h(childCell,(1,1)),childCell))
                aPath[childCell]=currCell
    fwdPath={}
    cell=(1,1)
    while cell!=start:
        fwdPath[aPath[cell]]=cell
        cell=aPath[cell]
    return fwdPath

#uniform cost search.
def UCS(m,*h,start=None):
    if start is None:
        start=(m.rows,m.cols)

    hurdles=[(i.position,i.cost) for i in h]

    unvisited={n:float('inf') for n in m.grid}
    unvisited[start]=0
    visited={}
    revPath={}
    while unvisited:
        currCell=min(unvisited,key=unvisited.get)
        visited[currCell]=unvisited[currCell]
        if currCell==m._goal:
            break
        for d in 'EWNS':
            if m.maze_map[currCell][d]==True:
                if d=='E':
                    childCell=(currCell[0],currCell[1]+1)
                elif d=='W':
                    childCell=(currCell[0],currCell[1]-1)
                elif d=='S':
                    childCell=(currCell[0]+1,currCell[1])
                elif d=='N':
                    childCell=(currCell[0]-1,currCell[1])
                if childCell in visited:
                    continue
                tempDist= unvisited[currCell]+1
                for hurdle in hurdles:
                    if hurdle[0]==currCell:
                        tempDist+=hurdle[1]

                if tempDist < unvisited[childCell]:
                    unvisited[childCell]=tempDist
                    revPath[childCell]=currCell
        unvisited.pop(currCell)

    fwdPath={}
    cell=m._goal
    while cell!=start:
        fwdPath[revPath[cell]]=cell
        cell=revPath[cell]

    return fwdPath,visited[m._goal]

from timeit import timeit
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
import tkinter as tk
class MazeGUI:
    def __init__(self, master):
        self.master = master
        self.master.title("Maze GUI")
        self.master.geometry("700x500")
        self.master.resizable(True, True)
        self.master.configure(background='white')
        self.create_widgets()
        self.master.mainloop()

    def create_widgets(self):
        self.frame = tk.Frame(self.master, bg='black')
        self.frame.pack(fill=tk.BOTH, expand=True)
        self.frame.grid_rowconfigure(0, weight=1)
        self.frame.grid_columnconfigure(0, weight=1)
        self.frame.grid_propagate(False)
        self.button1 = tk.Button(self.frame, text="BFS", command=self.bfs)
        self.button1.grid(row=1, column=1, sticky="nsew", padx=10, pady=10)
        self.button1.place(x=50,y=50)
        self.button2 = tk.Button(self.frame, text="A*", command=self.aStar)
        self.button2.grid(row=2, column=1, sticky="nsew", padx=10, pady=10)
        self.button3 = tk.Button(self.frame, text="UCS", command=self.UCS)
        self.button3.grid(row=3, column=1, sticky="nsew", padx=10, pady=10)
        self.button4 = tk.Button(self.frame, text="DFS", command=self.dfs)
        self.button4.grid(row=4, column=1, sticky="nsew", padx=10, pady=10)
        self.button5 = tk.Button(self.frame, text="Exit", command=self.exit)
        self.button5.grid(row=5, column=1, sticky="nsew", padx=10, pady=10)

    def bfs(self):
        m2=maze()
        m2.CreateMaze()
        path=BFS(m2)
        b=agent(m2,footprints=True,filled=True)
        m2.tracePath({b:path})
        l2=textLabel(m2,'Length of Shortest Path',len(path)+1)
        m2.mainloop()
    def aStar(self):
        m3=maze()
        m3.CreateMaze()
        path=aStar(m3)
        c=agent(m3,footprints=True)
        m3.tracePath({c:path})
        l3=textLabel(m3,"A Star Path Length",len(path)+1)
        m3.mainloop()
    def UCS(self):
       m4=maze(10,10)
       m4.CreateMaze()
       path,c=UCS(m4)
       textLabel(m4,'Total Cost',c)
       a=agent(m4,color=COLOR.cyan,filled=True,footprints=True,)

       m4.tracePath({a:path},delay=100)
       t1=timeit(stmt='UCS(m4)',number=100,globals=globals())
       textLabel(m4,'UCS Time',t1)

       m4.run()
       m4.mainloop()
    def dfs(self):
        m1=maze()
        m1.CreateMaze()
        path=DFS(m1)
        a=agent(m1,footprints=True)
        m1.tracePath({a:path})
        l1=textLabel(m1,'Length of Shortest Path',len(path)+1)
        m1.mainloop()
    def exit(self):
        self.master.destroy()

if __name__ == '__main__':
    root = tk.Tk()
    app = MazeGUI(root)

</code>```

I want to be displayed correctly and As it meant to be so if a press a button the search starts and agent moves.

Body:
I have a code made with pyamaze library which I perform 4 different types of search on maze and I want to display it with GUI (to make the user choose the type of search they want)
but the problem when I run the code the GUI gets stuck

from pyamaze import maze, COLOR, agent,textLabel
#Depth first search
def DFS(m1):
    start=(m1.rows,m1.cols)
    explored=[start]
    frontier=[start]
    dfsPath={}
    while len(frontier)>0:
        currCell=frontier.pop()
        if currCell==(1,1):
            break
        for d in 'ESNW':
            if m1.maze_map[currCell][d]==True:
                if d=='E':
                    childCell=(currCell[0],currCell[1]+1)
                elif d=='W':
                    childCell=(currCell[0],currCell[1]-1)
                elif d=='S':
                    childCell=(currCell[0]+1,currCell[1])
                elif d=='N':
                    childCell=(currCell[0]-1,currCell[1])
                if childCell in explored:
                    continue
                explored.append(childCell)
                frontier.append(childCell)
                dfsPath[childCell]=currCell
    fwdPath={}
    cell=(1,1)
    while cell!=start:
        fwdPath[dfsPath[cell]]=cell
        cell=dfsPath[cell]
    return fwdPath

#Breadth first search
def BFS(m2):
    start=(m2.rows,m2.cols)
    frontier=[start]
    explored=[start]
    bfsPath={}
    while len(frontier)>0:
        currCell=frontier.pop(0)
        if currCell==(1,1):
            break
        for d in 'ESNW':
            if m2.maze_map[currCell][d]==True:
                if d=='E':
                    childCell=(currCell[0],currCell[1]+1)
                elif d=='W':
                    childCell=(currCell[0],currCell[1]-1)
                elif d=='N':
                    childCell=(currCell[0]-1,currCell[1])
                elif d=='S':
                    childCell=(currCell[0]+1,currCell[1])
                if childCell in explored:
                    continue
                frontier.append(childCell)
                explored.append(childCell)
                bfsPath[childCell]=currCell
    fwdPath={}
    cell=(1,1)
    while cell!=start:
        fwdPath[bfsPath[cell]]=cell
        cell=bfsPath[cell]
    return fwdPath

# A-star search
from queue import PriorityQueue
def h(cell1,cell2):
    x1,y1=cell1
    x2,y2=cell2
    return abs(x1-x2)+abs(y1-y2)
def aStar(m3):
    start=(m3.rows,m3.cols)
    g_score={cell:float('inf') for cell in m3.grid}
    g_score[start]=0
    f_score={cell:float('inf') for cell in m3.grid}
    f_score[start]=h(start,(1,1))
    open=PriorityQueue()
    open.put((h(start,(1,1)),h(start,(1,1)),start))
    aPath={}
    while not open.empty():
        currCell=open.get()[2]
        if currCell==(1,1):
            break
        for d in 'ESNW':
           if m3.maze_map[currCell][d]==True:
             if d=='E':
                childCell=(currCell[0],currCell[1]+1)
             if d=='W':
                childCell=(currCell[0],currCell[1]-1)
             if d=='N':
                childCell=(currCell[0]-1,currCell[1])
             if d=='S':
                childCell=(currCell[0]+1,currCell[1])
             temp_g_score=g_score[currCell]+1
             temp_f_score=temp_g_score+h(childCell,(1,1))
             if temp_f_score < f_score[childCell]:
                g_score[childCell]=temp_g_score
                f_score[childCell]=temp_f_score
                open.put((temp_f_score,h(childCell,(1,1)),childCell))
                aPath[childCell]=currCell
    fwdPath={}
    cell=(1,1)
    while cell!=start:
        fwdPath[aPath[cell]]=cell
        cell=aPath[cell]
    return fwdPath

#uniform cost search.
def UCS(m,*h,start=None):
    if start is None:
        start=(m.rows,m.cols)

    hurdles=[(i.position,i.cost) for i in h]

    unvisited={n:float('inf') for n in m.grid}
    unvisited[start]=0
    visited={}
    revPath={}
    while unvisited:
        currCell=min(unvisited,key=unvisited.get)
        visited[currCell]=unvisited[currCell]
        if currCell==m._goal:
            break
        for d in 'EWNS':
            if m.maze_map[currCell][d]==True:
                if d=='E':
                    childCell=(currCell[0],currCell[1]+1)
                elif d=='W':
                    childCell=(currCell[0],currCell[1]-1)
                elif d=='S':
                    childCell=(currCell[0]+1,currCell[1])
                elif d=='N':
                    childCell=(currCell[0]-1,currCell[1])
                if childCell in visited:
                    continue
                tempDist= unvisited[currCell]+1
                for hurdle in hurdles:
                    if hurdle[0]==currCell:
                        tempDist+=hurdle[1]

                if tempDist < unvisited[childCell]:
                    unvisited[childCell]=tempDist
                    revPath[childCell]=currCell
        unvisited.pop(currCell)

    fwdPath={}
    cell=m._goal
    while cell!=start:
        fwdPath[revPath[cell]]=cell
        cell=revPath[cell]

    return fwdPath,visited[m._goal]

from timeit import timeit
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
import tkinter as tk
class MazeGUI:
    def __init__(self, master):
        self.master = master
        self.master.title("Maze GUI")
        self.master.geometry("700x500")
        self.master.resizable(True, True)
        self.master.configure(background='white')
        self.create_widgets()
        self.master.mainloop()

    def create_widgets(self):
        self.frame = tk.Frame(self.master, bg='black')
        self.frame.pack(fill=tk.BOTH, expand=True)
        self.frame.grid_rowconfigure(0, weight=1)
        self.frame.grid_columnconfigure(0, weight=1)
        self.frame.grid_propagate(False)
        self.button1 = tk.Button(self.frame, text="BFS", command=self.bfs)
        self.button1.grid(row=1, column=1, sticky="nsew", padx=10, pady=10)
        self.button1.place(x=50,y=50)
        self.button2 = tk.Button(self.frame, text="A*", command=self.aStar)
        self.button2.grid(row=2, column=1, sticky="nsew", padx=10, pady=10)
        self.button3 = tk.Button(self.frame, text="UCS", command=self.UCS)
        self.button3.grid(row=3, column=1, sticky="nsew", padx=10, pady=10)
        self.button4 = tk.Button(self.frame, text="DFS", command=self.dfs)
        self.button4.grid(row=4, column=1, sticky="nsew", padx=10, pady=10)
        self.button5 = tk.Button(self.frame, text="Exit", command=self.exit)
        self.button5.grid(row=5, column=1, sticky="nsew", padx=10, pady=10)

    def bfs(self):
        m2=maze()
        m2.CreateMaze()
        path=BFS(m2)
        b=agent(m2,footprints=True,filled=True)
        m2.tracePath({b:path})
        l2=textLabel(m2,'Length of Shortest Path',len(path)+1)
        m2.mainloop()
    def aStar(self):
        m3=maze()
        m3.CreateMaze()
        path=aStar(m3)
        c=agent(m3,footprints=True)
        m3.tracePath({c:path})
        l3=textLabel(m3,"A Star Path Length",len(path)+1)
        m3.mainloop()
    def UCS(self):
       m4=maze(10,10)
       m4.CreateMaze()
       path,c=UCS(m4)
       textLabel(m4,'Total Cost',c)
       a=agent(m4,color=COLOR.cyan,filled=True,footprints=True,)

       m4.tracePath({a:path},delay=100)
       t1=timeit(stmt='UCS(m4)',number=100,globals=globals())
       textLabel(m4,'UCS Time',t1)

       m4.run()
       m4.mainloop()
    def dfs(self):
        m1=maze()
        m1.CreateMaze()
        path=DFS(m1)
        a=agent(m1,footprints=True)
        m1.tracePath({a:path})
        l1=textLabel(m1,'Length of Shortest Path',len(path)+1)
        m1.mainloop()
    def exit(self):
        self.master.destroy()

if __name__ == '__main__':
    root = tk.Tk()
    app = MazeGUI(root)

I want to be displayed correctly and As it meant to be so if a press a button the search starts and agent moves.


问:
How to apply a gradient color throughout an SVG Path
I am trying to apply a gradient color along an SVG which consists of multiple <path> tags. I want SVG paths to start with a color and end up with another color and do this through the entirety of the collection of paths. What I currently have is the following code, which outputs the following image:

<svg width="300" height="300" viewBox="0 0 300 300">
    <defs>
        <linearGradient id="gradient1" x1="0%" y1="0%" x2="0%" y2="100%" >
            <stop offset="0%" stop-color="#f5f242" />
            <stop offset="100%" stop-color="#5430e6" />
        </linearGradient>
    </defs>

    <g fill="url(#gradient1)">
        <path d="M 10 10 h 90 v 6 h -90" />
        <path d="M 100 10 v 90 h 6 v -90" />
        <path d="M 10 94 h 90 v 6 h -90" />
    </g>
</svg>```

I want the gradient to start with yellow at top left and as you move along the lines, I want it to end at the purple at the bottom left. Is this possible with SVG? How can I achieve this?

Body:
I am trying to apply a gradient color along an SVG which consists of multiple <path> tags. I want SVG paths to start with a color and end up with another color and do this through the entirety of the collection of paths. What I currently have is the following code, which outputs the following image:

<svg width="300" height="300" viewBox="0 0 300 300">
    <defs>
        <linearGradient id="gradient1" x1="0%" y1="0%" x2="0%" y2="100%" >
            <stop offset="0%" stop-color="#f5f242" />
            <stop offset="100%" stop-color="#5430e6" />
        </linearGradient>
    </defs>

    <g fill="url(#gradient1)">
        <path d="M 10 10 h 90 v 6 h -90" />
        <path d="M 100 10 v 90 h 6 v -90" />
        <path d="M 10 94 h 90 v 6 h -90" />
    </g>
</svg>

I want the gradient to start with yellow at top left and as you move along the lines, I want it to end at the purple at the bottom left. Is this possible with SVG? How can I achieve this?


问:
laravel - do I have to set withPivot fields on both models?
I need some fields (SCORE, HEALTH) in many-to-many relation.

Models

```<code>Channel => title
Company => id
</code>```

Tables

```<code>channels         => id, title
companies        => id
company_channel  => channel_id, company_id, SCORE, HEALTH
</code>```

The question is: do I have to set withPivot fields on both models?

```<code>// channel model
public function companies() { return $this->belongsToMany('\App\Company')->withPivot(['score', 'health']); }

// company model
public function channels() { return $this->belongsToMany('\App\Channel')->withPivot(['score', 'health']); }
</code>```

Body:
I need some fields (SCORE, HEALTH) in many-to-many relation.

Models

Channel => title
Company => id

Tables

channels         => id, title
companies        => id
company_channel  => channel_id, company_id, SCORE, HEALTH

The question is: do I have to set withPivot fields on both models?

// channel model
public function companies() { return $this->belongsToMany('\App\Company')->withPivot(['score', 'health']); }

// company model
public function channels() { return $this->belongsToMany('\App\Channel')->withPivot(['score', 'health']); }


问:
Facing issue with django_admin_hstore_widget in production
```<code>  Uncaught ReferenceError: initDjangoHStoreWidget is not defined
        at HTMLDocument.<anonymous> ((index):3024:36)
        at j (jquery.min.js:2:26911)
        at Object.fireWith [as resolveWith] (jquery.min.js:2:27724)
        at Function.ready (jquery.min.js:2:29518)
        at HTMLDocument.I (jquery.min.js:2:29709)
</code>```

This works fine in local server.

Body:
  Uncaught ReferenceError: initDjangoHStoreWidget is not defined
        at HTMLDocument.<anonymous> ((index):3024:36)
        at j (jquery.min.js:2:26911)
        at Object.fireWith [as resolveWith] (jquery.min.js:2:27724)
        at Function.ready (jquery.min.js:2:29518)
        at HTMLDocument.I (jquery.min.js:2:29709)

This works fine in local server.


问:
Google Cloud Run - One container handling multiple similar requests with queue for each user
I have a SERVICE that gets a request from a Webhook and this is currently deployed across seperate Cloud Run containers. These seperate containers are the exact same (image), however, each instance processes data seperately for each particular account.

This is due to a ~ 3-5 min processing of the request and if the user sends in more requests, it needs to wait for the existing process to be completed for that particular user before processing the next one to avoid racing conditions. The container can still receive webhooks though, however, the actual processing of the data itself needs to be done one by one for each account.

Is there no way to reduce the container count, as such for example, to use one container to process all the requests, while still ensuring it processes one task for each user at a time and waits for that to complete for that user, before processing the next request from the same user.

To explain it better, i.e.

Multiple tasks can be run across all the users

However, per user 1 task at a time processed; Once that is completed, the next task for that user can be processed

I was thinking of monitoring the tasks through a Redis Cache, however, with Cloud Run being stateless, I am not sure that is the right way to go.

Or seperating the requests and the actual work - Master / Worker - And having the worker report back to the master once a task is completed for the user across 2 images (Using the concurrency to process multiple tasks across the users), however that might mean that I would have to increase the timeout time for Cloud Run.

Good to hear any other suggestions.

Apologies if this doesn't seem clear, feel free to ask for more information.


问:
Catch all requests and proxy a subset to a different server
I would like to proxy all requests matching a certain criteria to my backend server. Is there any way to catch all requests and let a subset through the proxy based on things like headers and request paths?

vite.config.ts

```<code>server: {
    proxy: {
      '^.*': {
        target: 'https://backend.com',
        secure: false,
        changeOrigin: true,
        ws: true,
        configure: proxy => {
          // only proxy if request has header "accept: application/json"
          // or if it's an image request
        }
      }
    }
  }
</code>```

This seems to catch all requests, but I want my "static" files like index.html, app.js etc. to be served from the devserver, not the proxy.

Body:
I would like to proxy all requests matching a certain criteria to my backend server. Is there any way to catch all requests and let a subset through the proxy based on things like headers and request paths?

vite.config.ts

server: {
    proxy: {
      '^.*': {
        target: 'https://backend.com',
        secure: false,
        changeOrigin: true,
        ws: true,
        configure: proxy => {
          // only proxy if request has header "accept: application/json"
          // or if it's an image request
        }
      }
    }
  }

This seems to catch all requests, but I want my "static" files like index.html, app.js etc. to be served from the devserver, not the proxy.


问:
i am using tomcat v10 i am getting an error unable to compile class for jsp
org.apache.jasper.JasperException: Unable to compile class for JSP:

An error occurred at line: [6] in the jsp file: [/table/create_table.jsp]
ConnectionProvider cannot be resolved

Stacktrace:
org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:102)
org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:213)
org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:509)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:397)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:367)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:351)
org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:603)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:399)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:380)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:328)
jakarta.servlet.http.HttpServlet.service(HttpServlet.java:777)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Note The full stack trace of the root cause is available in the server logs.`


问:
ASP.NET MVC : post the text inside the table header cell
I have a table and I want to call an action method when the text inside the table header is clicked. Inside this action method, I want to be able to write LINQ queries according to text clicked.

Pseudo code:

```<code>public IActionResult Select(string text)
{
    var viewModel = (from c in _context.Companies
                     join co in _context.Component on c.id equals co.company_id
                     where c.id.Equals(co.company_id)
                     select new Joincco { Companies = c,
                                          Component = co}
                    ) where co.text=="Y"
    return View(viewModel);
}
</code>```

Is it possible or is there a better way? I don't want to create different view pages for each table header.

Body:
I have a table and I want to call an action method when the text inside the table header is clicked. Inside this action method, I want to be able to write LINQ queries according to text clicked.

Pseudo code:

public IActionResult Select(string text)
{
    var viewModel = (from c in _context.Companies
                     join co in _context.Component on c.id equals co.company_id
                     where c.id.Equals(co.company_id)
                     select new Joincco { Companies = c,
                                          Component = co}
                    ) where co.text=="Y"
    return View(viewModel);
}

Is it possible or is there a better way? I don't want to create different view pages for each table header.


问:
create blog in react and store in backend mongodb
enter image description here

I want to create a blog like this image, I mean first text then image with own css the and then add heading with some css and then another and then table

some people say write like this

loreme523

loreme523

heading 1

heading 6

 >

but I do not need like this I want, I just type heading text in my dash bord and my code automaticaly edit this and save in backend and when I call it my backend send this file and just type{ blog.file} and it work

please give some idea


问:
Retrieving Error messages from SWI-Prolog using java and jpl
When I use JPL (from JavaSE 1.8), Prolog (SWI-Prolog version 8.2.4) it return an error message . E.g. when using consult and the file has errors:

```<code>ERROR: c:/program files/swipl/library/jpl.pl:5428:
ERROR:    '$open_shared_object'/3: The specified module could not be found.

ERROR: c:/program files/swipl/library/jpl.pl:5428:
ERROR:    c:/program files/swipl/library/jpl.pl:5428: Initialization goal raised exception:
ERROR:    jpl:jpl_get_default_jvm_opts/1: Unknown procedure: jpl:jni_get_default_jvm_opts/1
ERROR: c:/users/kt356/onedrive/desktop/system/medical expert system.pl:4:
ERROR:    Exported procedure jpl:jpl_c_lib_version/1 is not defined
</code>```

What can I do so that to resolve this error?

Body:
When I use JPL (from JavaSE 1.8), Prolog (SWI-Prolog version 8.2.4) it return an error message . E.g. when using consult and the file has errors:

ERROR: c:/program files/swipl/library/jpl.pl:5428:
ERROR:    '$open_shared_object'/3: The specified module could not be found.

ERROR: c:/program files/swipl/library/jpl.pl:5428:
ERROR:    c:/program files/swipl/library/jpl.pl:5428: Initialization goal raised exception:
ERROR:    jpl:jpl_get_default_jvm_opts/1: Unknown procedure: jpl:jni_get_default_jvm_opts/1
ERROR: c:/users/kt356/onedrive/desktop/system/medical expert system.pl:4:
ERROR:    Exported procedure jpl:jpl_c_lib_version/1 is not defined

What can I do so that to resolve this error?


问:
Why is my carousel making page extra wide?
I am creating my portfolio website and i just implemented this carousel. All seems to work nice but when it gets scrolled to right it makes my page wide and adds a scrollbar at the bottom.

I would like the slides to just hide after screen edge on both sides.

Extra request: im also trying to figure out how to make it loop the images so they wont stop at the ends, so if you have any suggestions about that please let me know.

preview: https://htmlpreview.github.io/?https://raw.githubusercontent.com/DBvagabond/dbogdanski/main/work.html
(js not working on my github but works locally, dont know why yet)

const track = document.getElementById("image-track");

const handleOnDown = e => track.dataset.mouseDownAt = e.clientX;

const handleOnUp = () => {
  track.dataset.mouseDownAt = "0";
  track.dataset.prevPercentage = track.dataset.percentage;
}

const handleOnMove = e => {
  if (track.dataset.mouseDownAt === "0") return;

  const mouseDelta = parseFloat(track.dataset.mouseDownAt) - e.clientX,
    maxDelta = window.innerWidth / 2;

  const percentage = (mouseDelta / maxDelta) * -100,
    nextPercentageUnconstrained = parseFloat(track.dataset.prevPercentage) + percentage,
    nextPercentage = Math.max(Math.min(nextPercentageUnconstrained, 0), -100);

  track.dataset.percentage = nextPercentage;

  track.animate({
    transform: `translate(${nextPercentage}%, -50%)`
  }, {
    duration: 1200,
    fill: "forwards"
  });

  for (const image of track.getElementsByClassName("image")) {
    image.animate({
      objectPosition: `${100 + nextPercentage}% center`
    }, {
      duration: 1200,
      fill: "forwards"
    });
  }
}

window.onmousedown = e => handleOnDown(e);

window.ontouchstart = e => handleOnDown(e.touches[0]);

window.onmouseup = e => handleOnUp(e);

window.ontouchend = e => handleOnUp(e.touches[0]);

window.onmousemove = e => handleOnMove(e);

window.ontouchmove = e => handleOnMove(e.touches[0]);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#image-track {
  display: flex;
  gap: 4vmin;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(0%, -50%);
  user-select: none;
}

#image-track .image {
  width: 40vmin;
  height: 56vmin;
  object-fit: cover;
  object-position: 100% center;
}</code>```

```

Body:
I am creating my portfolio website and i just implemented this carousel. All seems to work nice but when it gets scrolled to right it makes my page wide and adds a scrollbar at the bottom.

I would like the slides to just hide after screen edge on both sides.

Extra request: im also trying to figure out how to make it loop the images so they wont stop at the ends, so if you have any suggestions about that please let me know.

preview: https://htmlpreview.github.io/?https://raw.githubusercontent.com/DBvagabond/dbogdanski/main/work.html
(js not working on my github but works locally, dont know why yet)

const track = document.getElementById("image-track");

const handleOnDown = e => track.dataset.mouseDownAt = e.clientX;

const handleOnUp = () => {
  track.dataset.mouseDownAt = "0";
  track.dataset.prevPercentage = track.dataset.percentage;
}

const handleOnMove = e => {
  if (track.dataset.mouseDownAt === "0") return;

  const mouseDelta = parseFloat(track.dataset.mouseDownAt) - e.clientX,
    maxDelta = window.innerWidth / 2;

  const percentage = (mouseDelta / maxDelta) * -100,
    nextPercentageUnconstrained = parseFloat(track.dataset.prevPercentage) + percentage,
    nextPercentage = Math.max(Math.min(nextPercentageUnconstrained, 0), -100);

  track.dataset.percentage = nextPercentage;

  track.animate({
    transform: `translate(${nextPercentage}%, -50%)`
  }, {
    duration: 1200,
    fill: "forwards"
  });

  for (const image of track.getElementsByClassName("image")) {
    image.animate({
      objectPosition: `${100 + nextPercentage}% center`
    }, {
      duration: 1200,
      fill: "forwards"
    });
  }
}

window.onmousedown = e => handleOnDown(e);

window.ontouchstart = e => handleOnDown(e.touches[0]);

window.onmouseup = e => handleOnUp(e);

window.ontouchend = e => handleOnUp(e.touches[0]);

window.onmousemove = e => handleOnMove(e);

window.ontouchmove = e => handleOnMove(e.touches[0]);

#image-track {
  display: flex;
  gap: 4vmin;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(0%, -50%);
  user-select: none;
}

#image-track .image {
  width: 40vmin;
  height: 56vmin;
  object-fit: cover;
  object-position: 100% center;
}


问:
How to add slide in animation when navigating from tab to stack screen
ive got a react navigation structure like so

Home

--RestaurantList

--RestaurantDetails

My Queues

Home and My Queues are within a Tab navigator. RestaurantList and RestaurantDetails are within Home's Stack navigator.

Navigating from RestaurantList to RestaurantDetails gives a slide-in animation because it is navigating from a stack to another stack screen as seen.

https://youtube.com/shorts/VdFyNCwm1yw

I want that same slide in animation for navigating from my My Queues to RestaurantDetails, from a tab screen to a stack screen. It is currently just instant with no animation as seen.

https://youtube.com/shorts/nOZLP9seI14

This is the attached snack used in the videos

https://snack.expo.dev/@meg_hidey/ashamed-celery?platform=web

How can I achieve the same slide-in animation when navigating from MyQueues to RestaurantDetails?


问:
Android Studio Emulator apk install error
I've started the android emulator (android 5.1), wanted to install an apk through drag and drop, but I get this error message:

```<code>pm install-create -r -t --user current --full -S 203239352' returns error 'Unknown failure: Error: java.lang.NumberFormatException: Invalid int: "current"'
</code>```

I've tried on an m1 mac and a windows pc. On the mac I tried arm and arm64, on windows tried it with x86. Got apk files with matching architectures for all of them with chrome version (95.0.4638.x) compatible with android 5.1. I get the same error message for all of them.

Body:
I've started the android emulator (android 5.1), wanted to install an apk through drag and drop, but I get this error message:

pm install-create -r -t --user current --full -S 203239352' returns error 'Unknown failure: Error: java.lang.NumberFormatException: Invalid int: "current"'

I've tried on an m1 mac and a windows pc. On the mac I tried arm and arm64, on windows tried it with x86. Got apk files with matching architectures for all of them with chrome version (95.0.4638.x) compatible with android 5.1. I get the same error message for all of them.


问:
Connection reset by peer (rabbitmq)
```<code>client side py

import pika, sys, os,ssl

def main():

    context =ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
    context.verify_mode = ssl.CERT_REQUIRED
    context.load_verify_locations("/home/dev/Desktop/files_from_ssh/ca_certificate.pem")

    credentials = pika.PlainCredentials(username='xxx', password='xxxx')
    conn_params = pika.ConnectionParameters(host="***",port=5672,heartbeat=60,ssl_options=pika.SSLOptions(context),
                                            virtual_host="test_environment",credentials=credentials)
    connection = pika.BlockingConnection(conn_params)
    channel = connection.channel()
    channel.queue_declare(queue='ssl_test')

    def callback(ch, method, properties, body):
        print(" [x] Received %r" % body)

    channel.basic_consume(queue='ssl_test', on_message_callback=callback, auto_ack=True)
    print(' [*] Waiting for messages. To exit press CTRL+C')

    channel.start_consuming()

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print("Interrupted")
        try:
            sys.exit(0)
        except SystemExit:
            pass
</code>```

on the server side tls is enabled

```<code>Interface: [::], port: 25672, protocol: clustering, purpose: inter-node and CLI tool communication
Interface: [::], port: 5672, protocol: amqp/ssl, purpose: AMQP 0-9-1 and AMQP 1.0 over TLS
Interface: [::], port: 15672, protocol: http, purpose: HTTP API
</code>```
```<code>rabbitmq.conf

listeners.ssl.default               = 5672
ssl_options.cacertfile              = /home/dev/testca/ca_certificate.pem
ssl_options.certfile                = /home/dev/server/server_certificate.pem
ssl_options.keyfile                 = /home/dev/server/private_key.pem
ssl_options.verify                  = verify_peer
ssl_options.fail_if_no_peer_cert    = true
listeners.tcp = none
</code>```

refered from this site:https://pika.readthedocs.io/en/stable/examples/tls_server_authentication.html
unable to connect to the server would someone help me out kinda new to rabbitmq
this is the error im getting
ConnectionResetError: [Errno 104] Connection reset by peer

Title: Connection reset by peer (rabbitmq)

Body:
client side py

import pika, sys, os,ssl

def main():

    context =ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
    context.verify_mode = ssl.CERT_REQUIRED
    context.load_verify_locations("/home/dev/Desktop/files_from_ssh/ca_certificate.pem")

    credentials = pika.PlainCredentials(username='xxx', password='xxxx')
    conn_params = pika.ConnectionParameters(host="***",port=5672,heartbeat=60,ssl_options=pika.SSLOptions(context),
                                            virtual_host="test_environment",credentials=credentials)
    connection = pika.BlockingConnection(conn_params)
    channel = connection.channel()
    channel.queue_declare(queue='ssl_test')

    def callback(ch, method, properties, body):
        print(" [x] Received %r" % body)

    channel.basic_consume(queue='ssl_test', on_message_callback=callback, auto_ack=True)
    print(' [*] Waiting for messages. To exit press CTRL+C')

    channel.start_consuming()

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print("Interrupted")
        try:
            sys.exit(0)
        except SystemExit:
            pass

on the server side tls is enabled

Interface: [::], port: 25672, protocol: clustering, purpose: inter-node and CLI tool communication
Interface: [::], port: 5672, protocol: amqp/ssl, purpose: AMQP 0-9-1 and AMQP 1.0 over TLS
Interface: [::], port: 15672, protocol: http, purpose: HTTP API

rabbitmq.conf

listeners.ssl.default               = 5672
ssl_options.cacertfile              = /home/dev/testca/ca_certificate.pem
ssl_options.certfile                = /home/dev/server/server_certificate.pem
ssl_options.keyfile                 = /home/dev/server/private_key.pem
ssl_options.verify                  = verify_peer
ssl_options.fail_if_no_peer_cert    = true
listeners.tcp = none

refered from this site:https://pika.readthedocs.io/en/stable/examples/tls_server_authentication.html
unable to connect to the server would someone help me out kinda new to rabbitmq
this is the error im getting
ConnectionResetError: [Errno 104] Connection reset by peer


问:
PostgreSQL: Raise a message in a function in case when there is no required output
I have a function which helps to find a word in a movie title. For example: find '%story%' in a movie title.

But what if we do not have this word in the movie list? I want to raise a message like "There is no movie with the required word". How to do that with my function? What is the syntax in my case?

Here is the structure of my code:

```<code>CREATE FUNCTION movies_to_find (IN i_title varchar(20))
RETURNS TABLE ( rows
) AS $$

    statements

$$
LANGUAGE SQL;
</code>```

Thank you!

Body:
I have a function which helps to find a word in a movie title. For example: find '%story%' in a movie title.

But what if we do not have this word in the movie list? I want to raise a message like "There is no movie with the required word". How to do that with my function? What is the syntax in my case?

Here is the structure of my code:

CREATE FUNCTION movies_to_find (IN i_title varchar(20))
RETURNS TABLE ( rows
) AS $$

    statements

$$
LANGUAGE SQL;

Thank you!


问:
How do I disable user authentication log in on certain pages on laravel web project?
I have a website built on laravel. I'd love to enable guests view some pages without having to log in or sign up. Currently, that pages requires user authentication. I'd love to disable it so everyone can see it.

How do I go about this??

Tried checking App\Http\Controllers\Auth\


问:
How can I only display the first and last three generations of my GA using deap
I am writing a GA to calculate maximums in a function. Whith the attribute verbose it will display every single generation but I want to only show the fist and last three generations so they can be compared for analysis easierly.

Does anyone know how to do this?

currently using verbose=1 will display all the generations


问:
Can anybody tell me how to use mask argument in LSTM cell?
I have a X_train padded sequence of shape (1400, 17640) and separate mask array of shape (1400, 17640) of type boolean what I want to create

```<code>layer1 = Input(shape=(X_train.shape[1], 1))

layer2 = Dense(64, name='layer2', mask=[need to provide mask here])(layer1)

output = Dense(10, activation='softmax', name='output')(layer2)
</code>```

can you tell me how to do that if I already have pre-computed padded sequence and mask Boolean array of same size? there is not much enough document regarding mask argument in LSTM cell in tensorflow documents.

Body:
I have a X_train padded sequence of shape (1400, 17640) and separate mask array of shape (1400, 17640) of type boolean what I want to create

layer1 = Input(shape=(X_train.shape[1], 1))

layer2 = Dense(64, name='layer2', mask=[need to provide mask here])(layer1)

output = Dense(10, activation='softmax', name='output')(layer2)

can you tell me how to do that if I already have pre-computed padded sequence and mask Boolean array of same size? there is not much enough document regarding mask argument in LSTM cell in tensorflow documents.


问:
How to change mapping type on a very large ElasticSearch index?
I tried to this solution from here, but it didn't worked for me.

I needed to convert the nested text fields like one.second.third to ip type. So I added mapping like

```<code>PUT .the-index-2022.12.20-0000025/_mapping
{
  "properties": {
    "one": {
      "type": "object",
      "properties": {
        "second": {
          "type":"object",
          "properties": {
            "ip_address1": {
              "type": "ip"
            },
            "ip_address2": {
              "type": "ip"
            }
          }
        }
      }
    }
  }
}
</code>```

Then I used

```<code>POST .the-index-2022.12.20-0000025/_update_by_query?wait_for_completion=false&slices=auto
</code>```

It executed successfully but still didnt change the fields type to ip.

What can I do else or what is the problem here?

Thanks in advance

Also tried like:

```<code>PUT .the-index-2022.12.20-0000025/_mapping
{
  "properties": {
    "one": {
      "properties": {
        "second": {
          "properties": {
            "ip_address1": {
              "type": "ip"
            },
            "ip_address2": {
              "type": "ip"
            }
          }
        }
      }
    }
  }
}
</code>```

Could you please help?

I've added 3 new fields in ip type:

```<code>{
  ".the-index-2022.12.20-0000025" : {
    "mappings" : {
      "one.sec.ip1" : {
        "full_name" : "one.sec.ip1",
        "mapping" : {
          "ip1" : {
            "type" : "ip"
          }
        }
      },
      "one.sec.ip2" : {
        "full_name" : "one.sec.ip2",
        "mapping" : {
          "ip2" : {
            "type" : "ip"
          }
        }
      },
      "one.sec.ip3" : {
        "full_name" : "one.sec.ip3",
        "mapping" : {
          "ip3" : {
            "type" : "ip"
          }
        }
      }
    }
  }
}

</code>```

Body:
I tried to this solution from here, but it didn't worked for me.

I needed to convert the nested text fields like one.second.third to ip type. So I added mapping like

PUT .the-index-2022.12.20-0000025/_mapping
{
  "properties": {
    "one": {
      "type": "object",
      "properties": {
        "second": {
          "type":"object",
          "properties": {
            "ip_address1": {
              "type": "ip"
            },
            "ip_address2": {
              "type": "ip"
            }
          }
        }
      }
    }
  }
}

Then I used

POST .the-index-2022.12.20-0000025/_update_by_query?wait_for_completion=false&slices=auto

It executed successfully but still didnt change the fields type to ip.

What can I do else or what is the problem here?

Thanks in advance

Also tried like:

PUT .the-index-2022.12.20-0000025/_mapping
{
  "properties": {
    "one": {
      "properties": {
        "second": {
          "properties": {
            "ip_address1": {
              "type": "ip"
            },
            "ip_address2": {
              "type": "ip"
            }
          }
        }
      }
    }
  }
}

Could you please help?

I've added 3 new fields in ip type:

{
  ".the-index-2022.12.20-0000025" : {
    "mappings" : {
      "one.sec.ip1" : {
        "full_name" : "one.sec.ip1",
        "mapping" : {
          "ip1" : {
            "type" : "ip"
          }
        }
      },
      "one.sec.ip2" : {
        "full_name" : "one.sec.ip2",
        "mapping" : {
          "ip2" : {
            "type" : "ip"
          }
        }
      },
      "one.sec.ip3" : {
        "full_name" : "one.sec.ip3",
        "mapping" : {
          "ip3" : {
            "type" : "ip"
          }
        }
      }
    }
  }
}


问:
compare Excel value and get the row to nearest or same value from other worksheet
I have 02 worksheets, Worksheet one contain table where user will enter the data. Worksheet 2 contain all the data.
When user click on "Estimate" button then it should compare that value of Worksheet 1 with Worksheet 2 and provide the nearest/same value with entire row from worksheet 02.

I have attached 02 images,

and (2 -image contain the data worksheet 2)

(1 - images contain expected result and place where end user can enter the data)

```<code>
Sub compare2()

Dim compId As Range
Range("I6").ClearContents
Set compId = Worksheets(2).Range("G11:G83").Find(what:=Worksheets(1).Range("c6").Value)

If Not compId Is Nothing Then
    Range("I6").Value = compId.Row()
Else
    MsgBox "Value does not match"
End If

End Sub
</code>```

I tried above code but it does not provide the nearest/same value and does not provide the entire row

Body:
I have 02 worksheets, Worksheet one contain table where user will enter the data. Worksheet 2 contain all the data.
When user click on "Estimate" button then it should compare that value of Worksheet 1 with Worksheet 2 and provide the nearest/same value with entire row from worksheet 02.

I have attached 02 images,

and (2 -image contain the data worksheet 2)

(1 - images contain expected result and place where end user can enter the data)

Sub compare2()

Dim compId As Range
Range("I6").ClearContents
Set compId = Worksheets(2).Range("G11:G83").Find(what:=Worksheets(1).Range("c6").Value)

If Not compId Is Nothing Then
    Range("I6").Value = compId.Row()
Else
    MsgBox "Value does not match"
End If

End Sub

I tried above code but it does not provide the nearest/same value and does not provide the entire row


问:
Old android https issue (ERR_CERT_AUTHORITY_INVALID)
I have a host where I use nginx and "let's encryt" for https certification. I have a test phone with android 6.0 and chrome 106 and I get the error of "ERR_CERT_AUTHORITY_INVALID". In every browser and device I tried it on (except for old android emulators, where I couldn't get chrome installed yet, but built in browser shows a blank page for this site), it works perfectly and says that the certificate is valid.

https://codenames.stemadev.com


问:
how to load images from server to react
React.js Node.js Multer Axios MongoDb

Hi im trying to load an image i uploaded to to server in my React.js project.
ive made a route to my public folder in the server
app.use("/uploads", express.static("public/uploads/images/"));

and when i enter the http://localhost:8080/uploads/ + file name.png i can see the uploaded img, but in my React project when i enter it as the img src it does not appear.

ive tried it through userInfo?.avatar data i get from MongoDB and server and through hard coding the full domain.

```<code>{!token ? (

 <HiOutlineUserCircle
     className="fs-1 pointer"
     data-bs-toggle="dropdown"
     aria-expanded="false"  />
                ) : (
  <img
     src="http://localhost:8080/uploads/buzi.PNG"
     // src={`http://localhost:8080/uploads/${userInfo?.avatar}`}
     alt={userInfo?.avatar} />
)}

</code>```

creating auto login hook

```<code>const useAutoLogin = () => {
  const dispatch = useDispatch();
  const autoLoginFunction = async (token) => {
    try {
      let dataFromToken = jwt_decode(token);
      let { data } = await autoLogin();
      if (data) {
        dispatch(authActions.login(dataFromToken.id));
        dispatch(authActions.updateUserInfo(data));
        return true;
      }
    } catch (err) {
      return false;
    }
  };
  return autoLoginFunction;
};
export default useAutoLogin;
</code>```

Auto login function from useAutoLogin hook

```<code>import axios from "axios";
const autoLogin = () => {
  return axios.get("/auth/getUserById");
};
export default autoLogin;
</code>```

assigning user info the info of the user from login

```<code>const userInfo = useSelector((state) => state.auth.userInfo);
</code>```

Redux state mangment for login and user info

```<code>import { createSlice } from "@reduxjs/toolkit";

//create variable that we want redux to store for us
//this object configure the redux "state"
const initialAuthState = {
  loggedIn: false,
  isAdmin: false,
  userData: null,
  userInfo: null,
  stay: false,
};

const authSlice = createSlice({
  name: "auth",
  initialState: initialAuthState,

  reducers: {
    login(state, action) {
      state.loggedIn = true;
      state.userData = action.payload;
      state.isAdmin = action.payload.isAdmin;
    },

    logout: (state) => initialAuthState,

    updateUserInfo(state, action) {
      state.userInfo = action.payload;
    },

    stayLoggedIn: (state, action) => {
      state.stay = action.payload;
    },
  },
});

export const authActions = authSlice.actions;

export default authSlice.reducer;
</code>```

Title: how to load images from server to react

Body:
React.js Node.js Multer Axios MongoDb

Hi im trying to load an image i uploaded to to server in my React.js project.
ive made a route to my public folder in the server
app.use("/uploads", express.static("public/uploads/images/"));

and when i enter the http://localhost:8080/uploads/ + file name.png i can see the uploaded img, but in my React project when i enter it as the img src it does not appear.

ive tried it through userInfo?.avatar data i get from MongoDB and server and through hard coding the full domain.

{!token ? (

 <HiOutlineUserCircle
     className="fs-1 pointer"
     data-bs-toggle="dropdown"
     aria-expanded="false"  />
                ) : (
  <img
     src="http://localhost:8080/uploads/buzi.PNG"
     // src={`http://localhost:8080/uploads/${userInfo?.avatar}`}
     alt={userInfo?.avatar} />
)}

creating auto login hook

const useAutoLogin = () => {
  const dispatch = useDispatch();
  const autoLoginFunction = async (token) => {
    try {
      let dataFromToken = jwt_decode(token);
      let { data } = await autoLogin();
      if (data) {
        dispatch(authActions.login(dataFromToken.id));
        dispatch(authActions.updateUserInfo(data));
        return true;
      }
    } catch (err) {
      return false;
    }
  };
  return autoLoginFunction;
};
export default useAutoLogin;

Auto login function from useAutoLogin hook

import axios from "axios";
const autoLogin = () => {
  return axios.get("/auth/getUserById");
};
export default autoLogin;

assigning user info the info of the user from login

const userInfo = useSelector((state) => state.auth.userInfo);

Redux state mangment for login and user info

import { createSlice } from "@reduxjs/toolkit";

//create variable that we want redux to store for us
//this object configure the redux "state"
const initialAuthState = {
  loggedIn: false,
  isAdmin: false,
  userData: null,
  userInfo: null,
  stay: false,
};

const authSlice = createSlice({
  name: "auth",
  initialState: initialAuthState,

  reducers: {
    login(state, action) {
      state.loggedIn = true;
      state.userData = action.payload;
      state.isAdmin = action.payload.isAdmin;
    },

    logout: (state) => initialAuthState,

    updateUserInfo(state, action) {
      state.userInfo = action.payload;
    },

    stayLoggedIn: (state, action) => {
      state.stay = action.payload;
    },
  },
});

export const authActions = authSlice.actions;

export default authSlice.reducer;


问:
Invoke multiple subnet id's into ec2 instance resource creation in terraform
I was trying to create two subnets, after that need to invoke these subnets for ec2 instance creation, but getting below error.

```<code>resource "aws_subnet" "mysubnet" {
  count             = length(var.subnet_cidr)
  vpc_id            = aws_vpc.myvpc.id
  cidr_block        = element(var.subnet_cidr, count.index)
  availability_zone = element(var.availability_zone, count.index)
}
</code>```
```<code>resource "aws_instance" "myinstance" {
  count             = 2
  subnet_id         = "element(aws_subnet.mysubnet.*id, count.index)"
  availability_zone = "element(aws_subnet.mysubnet.*id, count.index)"
  instance_type     = "t2.micro"
  ami               = element(var.ami_id, count.index)
}
</code>```
```<code>│ Error: creating EC2 Instance: InvalidSubnetID.NotFound: The subnet ID 'element(aws_subnet.mysubnet.*id, count.index)' does not exist
│       status code: 400, request id: e23c77ea-cfd1-4592-8d88-4017cad6fae4
│
│   with aws_instance.myinstance[1],
│   on multi.tf line 36, in resource "aws_instance" "myinstance":
│   36: resource "aws_instance" "myinstance" {
│
╵
╷
│ Error: creating EC2 Instance: InvalidSubnetID.NotFound: The subnet ID 'element(aws_subnet.mysubnet.*id, count.index)' does not exist
│       status code: 400, request id: 609ab349-e859-4192-aa4d-ee29e345c283
│
│   with aws_instance.myinstance[0],
│   on multi.tf line 36, in resource "aws_instance" "myinstance":
│   36: resource "aws_instance" "myinstance" {

</code>```

how we can use the syntax to invoke the multiple subnets for creating multiple ec2 instances.

Variables.tf.

```<code>variable "subnet_cidr" {
  type = list(any)

}
variable "availability_zone" {
  type = list(any)

}

</code>```

tfvars file ---->

```<code>subnet_cidr       = ["10.0.0.0/28", "10.0.0.16/28"]
availability_zone = ["us-east-1a", "us-east-1b"]
</code>```

Body:
I was trying to create two subnets, after that need to invoke these subnets for ec2 instance creation, but getting below error.

resource "aws_subnet" "mysubnet" {
  count             = length(var.subnet_cidr)
  vpc_id            = aws_vpc.myvpc.id
  cidr_block        = element(var.subnet_cidr, count.index)
  availability_zone = element(var.availability_zone, count.index)
}

resource "aws_instance" "myinstance" {
  count             = 2
  subnet_id         = "element(aws_subnet.mysubnet.*id, count.index)"
  availability_zone = "element(aws_subnet.mysubnet.*id, count.index)"
  instance_type     = "t2.micro"
  ami               = element(var.ami_id, count.index)
}

│ Error: creating EC2 Instance: InvalidSubnetID.NotFound: The subnet ID 'element(aws_subnet.mysubnet.*id, count.index)' does not exist
│       status code: 400, request id: e23c77ea-cfd1-4592-8d88-4017cad6fae4
│
│   with aws_instance.myinstance[1],
│   on multi.tf line 36, in resource "aws_instance" "myinstance":
│   36: resource "aws_instance" "myinstance" {
│
╵
╷
│ Error: creating EC2 Instance: InvalidSubnetID.NotFound: The subnet ID 'element(aws_subnet.mysubnet.*id, count.index)' does not exist
│       status code: 400, request id: 609ab349-e859-4192-aa4d-ee29e345c283
│
│   with aws_instance.myinstance[0],
│   on multi.tf line 36, in resource "aws_instance" "myinstance":
│   36: resource "aws_instance" "myinstance" {

how we can use the syntax to invoke the multiple subnets for creating multiple ec2 instances.

Variables.tf.

variable "subnet_cidr" {
  type = list(any)

}
variable "availability_zone" {
  type = list(any)

}

tfvars file ---->

subnet_cidr       = ["10.0.0.0/28", "10.0.0.16/28"]
availability_zone = ["us-east-1a", "us-east-1b"]


问:
FFMPEG image2pipe & No JPEG data found in image
I'm trying to create a video programmatically from a stream of base64/jpeg images in nodeJs

Current setup is as following:
Stream of base64 data comes in, it gets converted to a buffer and appended to a list.

N times *

this.framebuffer.push(Buffer.from(data, 'base64'))
```
<p>After that I spin up a ffmpeg instance with the image2pipe arg</p>
<pre class="lang-js prettyprint-override"><code>this.frames = new stream.PassThrough()
</code>```

this.ffmpeg = exec(`/opt/ffmpeg -y -framerate ${framerate} -f image2pipe -s 1024x1024 -i pipe: -pix_fmt yuv420p -vcodec libx264 -profile main -qp 1 -shortest -movflags +faststart -tune animation ${this.file_path}`)
```
<p>After this I pipe the the passthrough stream to the running ffmpeg process and write all collected frames to the passthrough stream.</p>
<pre class="lang-js prettyprint-override"><code>this.frames.pipe(this.ffmpeg.stdin)
this.framebuffer.forEach(frame => {
  this.frames.write(frame)
})
</code>```

This all works perfectly fine on my local machine with ffmpeg 4.4.1 (Mac OS) but when attempting to run in on AWS Lambda with 4.4.1 statically compiled downloaded from https://johnvansickle.com/ffmpeg/ it does not work and gives the following error n times:

```<code>No JPEG data found in image00:00:00.00 bitrate=N/A speed=   0x
Error while decoding stream #0:0: Invalid data found when processing input
</code>```

and ffmpeg outputs an empty file. I've tried different ffmpeg versions but they all seem to have a similar issue given the environment and use case. Other than that I checked whether the base64 string corresponds to an actual image and it does. The frames stored in the frame buffer are all valid images. I'm not really sure what could be causing this and how to solve it.

Body:
I'm trying to create a video programmatically from a stream of base64/jpeg images in nodeJs

Current setup is as following:
Stream of base64 data comes in, it gets converted to a buffer and appended to a list.

N times *

this.framebuffer.push(Buffer.from(data, 'base64'))

After that I spin up a ffmpeg instance with the image2pipe arg

this.frames = new stream.PassThrough()

this.ffmpeg = exec(`/opt/ffmpeg -y -framerate ${framerate} -f image2pipe -s 1024x1024 -i pipe: -pix_fmt yuv420p -vcodec libx264 -profile main -qp 1 -shortest -movflags +faststart -tune animation ${this.file_path}`)

After this I pipe the the passthrough stream to the running ffmpeg process and write all collected frames to the passthrough stream.

this.frames.pipe(this.ffmpeg.stdin)
this.framebuffer.forEach(frame => {
  this.frames.write(frame)
})

This all works perfectly fine on my local machine with ffmpeg 4.4.1 (Mac OS) but when attempting to run in on AWS Lambda with 4.4.1 statically compiled downloaded from https://johnvansickle.com/ffmpeg/ it does not work and gives the following error n times:

No JPEG data found in image00:00:00.00 bitrate=N/A speed=   0x
Error while decoding stream #0:0: Invalid data found when processing input

and ffmpeg outputs an empty file. I've tried different ffmpeg versions but they all seem to have a similar issue given the environment and use case. Other than that I checked whether the base64 string corresponds to an actual image and it does. The frames stored in the frame buffer are all valid images. I'm not really sure what could be causing this and how to solve it.


问:
How to keep last half parentheses line by line after fomating in flutter code?
I'm using intellij idea.My flutter code after formating:

```

    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
            home: Scaffold(
                backgroundColor: Colors.purple[50],
                appBar: AppBar(
                  title: Text('I AM RICH'),
                  backgroundColor: Colors.purple,
                ),
                body: Center(
                    child: Image(
                  image: NetworkImage(
                      'https://df2sm3urulav.cloudfront.net/tenants/gr/uploads/content/4wmnqlctgu0f3c9a.jpg'),
                ))));
      }
    }

```

But what i want is...

```

    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
            home: Scaffold(
                backgroundColor: Colors.purple[50],
                appBar: AppBar(
                  title: Text('I AM RICH'),
                  backgroundColor: Colors.purple,
                ),
                body:  Center(
                   child: Image(
                      image: NetworkImage(
                          'https://df2sm3urulav.cloudfront.net/tenants/gr/uploads/content/4wmnqlctgu0f3c9a.jpg'),
                    )
                )
            )
        );
      }
    }

```

The parentheses at the end stacks,i want them to be line by line.

Body:
I'm using intellij idea.My flutter code after formating:

    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
            home: Scaffold(
                backgroundColor: Colors.purple[50],
                appBar: AppBar(
                  title: Text('I AM RICH'),
                  backgroundColor: Colors.purple,
                ),
                body: Center(
                    child: Image(
                  image: NetworkImage(
                      'https://df2sm3urulav.cloudfront.net/tenants/gr/uploads/content/4wmnqlctgu0f3c9a.jpg'),
                ))));
      }
    }

But what i want is...

    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
            home: Scaffold(
                backgroundColor: Colors.purple[50],
                appBar: AppBar(
                  title: Text('I AM RICH'),
                  backgroundColor: Colors.purple,
                ),
                body:  Center(
                   child: Image(
                      image: NetworkImage(
                          'https://df2sm3urulav.cloudfront.net/tenants/gr/uploads/content/4wmnqlctgu0f3c9a.jpg'),
                    )
                )
            )
        );
      }
    }

The parentheses at the end stacks,i want them to be line by line.


问:
Trying to add a column to my data set in R that calculates the % of 2 other columns
Basically, I am using a dataset looking at the 2017 UK election data and I am trying to add a new column for votes cast for right wing parties, so UKIP and Conservatives. the dataset is for each constituency and gives numerical values for all the votes cast. but i am having difficulty adding a new column.

```<code># % Right wing ====

ew_ele$Right2017 <- ((ew_ele$"17CON"+ew_ele$"17UKIP") /
                      rowSums(ew_ele[,8, 11, drop=TRUE]))*100
</code>```

ew_ele is the name of the dataset, and 17CON and 17UKIP are the names of the columns which contain the number of votes, they are in the 8th and 11th column respectively

Body:
Basically, I am using a dataset looking at the 2017 UK election data and I am trying to add a new column for votes cast for right wing parties, so UKIP and Conservatives. the dataset is for each constituency and gives numerical values for all the votes cast. but i am having difficulty adding a new column.

# % Right wing ====

ew_ele$Right2017 <- ((ew_ele$"17CON"+ew_ele$"17UKIP") /
                      rowSums(ew_ele[,8, 11, drop=TRUE]))*100

ew_ele is the name of the dataset, and 17CON and 17UKIP are the names of the columns which contain the number of votes, they are in the 8th and 11th column respectively


问:
Spring bearer Jwt Token Validation: Erorr java.lang.IllegalArgumentException: Key bytes can only be specified for HMAC signatures
I created bearer token using keycloak, The token is formed straight.
I am trying to validate using filter, but When I try to validate token, I get an error.

Token Validation class

```<code>@Component
public class TokenFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        final String token = request.getHeader("Authorization").substring(7);
        String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAj71smzim/iRbR0ggkQmhAVp" +
                "LTeIi5lNCCNymj+Qafl5sxWklEG5vnI64566vtfufv9HWT+HQvDQetHBKgwIDAQAB";

        Claims claims = Jwts.parserBuilder().setSigningKey(publicKey).build().parseClaimsJws(token).getBody();
        String tokens = claims.getSubject();
    }
}
</code>```

pom.xml

```<code><dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-oauth2-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-api</artifactId>
            <version>0.11.5</version>
        </dependency>
</dependencies>
</code>```

Error

```<code>java.lang.IllegalArgumentException: Key bytes can only be specified for HMAC signatures. Please specify a PublicKey or PrivateKey instance.
    at io.jsonwebtoken.lang.Assert.isTrue(Assert.java:35) ~[jjwt-api-0.11.5.jar:0.11.5]
    at io.jsonwebtoken.impl.DefaultJwtParser.parse(DefaultJwtParser.java:363) ~[jjwt-impl-0.11.5.jar:0.11.5]
    at io.jsonwebtoken.impl.DefaultJwtParser.parse(DefaultJwtParser.java:529) ~[jjwt-impl-0.11.5.jar:0.11.5]
    at io.jsonwebtoken.impl.DefaultJwtParser.parseClaimsJws(DefaultJwtParser.java:589) ~[jjwt-impl-0.11.5.jar:0.11.5]
    at com.framework.security.util.TokenFilter.doFilterInternal(TokenFilter.java:52) ~[security-0.0.1-SNAPSHOT.jar:?]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.23.jar:5.3.23]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) ~[spring-security-web-5.7.3.jar:5.7.3]
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:103) ~[spring-security-web-5.7.3.jar:5.7.3]
</code>```

It gives the error as follows.

```<code>Claims claims = Jwts.parserBuilder().setSigningKey(publicKey).build().parseClaimsJws(token).getBody();
</code>```

I couldnt found the problem
How can i Solve?

Body:
I created bearer token using keycloak, The token is formed straight.
I am trying to validate using filter, but When I try to validate token, I get an error.

Token Validation class

@Component
public class TokenFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        final String token = request.getHeader("Authorization").substring(7);
        String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAj71smzim/iRbR0ggkQmhAVp" +
                "LTeIi5lNCCNymj+Qafl5sxWklEG5vnI64566vtfufv9HWT+HQvDQetHBKgwIDAQAB";

        Claims claims = Jwts.parserBuilder().setSigningKey(publicKey).build().parseClaimsJws(token).getBody();
        String tokens = claims.getSubject();
    }
}

pom.xml

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-oauth2-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-api</artifactId>
            <version>0.11.5</version>
        </dependency>
</dependencies>

Error

java.lang.IllegalArgumentException: Key bytes can only be specified for HMAC signatures. Please specify a PublicKey or PrivateKey instance.
    at io.jsonwebtoken.lang.Assert.isTrue(Assert.java:35) ~[jjwt-api-0.11.5.jar:0.11.5]
    at io.jsonwebtoken.impl.DefaultJwtParser.parse(DefaultJwtParser.java:363) ~[jjwt-impl-0.11.5.jar:0.11.5]
    at io.jsonwebtoken.impl.DefaultJwtParser.parse(DefaultJwtParser.java:529) ~[jjwt-impl-0.11.5.jar:0.11.5]
    at io.jsonwebtoken.impl.DefaultJwtParser.parseClaimsJws(DefaultJwtParser.java:589) ~[jjwt-impl-0.11.5.jar:0.11.5]
    at com.framework.security.util.TokenFilter.doFilterInternal(TokenFilter.java:52) ~[security-0.0.1-SNAPSHOT.jar:?]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.23.jar:5.3.23]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) ~[spring-security-web-5.7.3.jar:5.7.3]
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:103) ~[spring-security-web-5.7.3.jar:5.7.3]

It gives the error as follows.

Claims claims = Jwts.parserBuilder().setSigningKey(publicKey).build().parseClaimsJws(token).getBody();

I couldnt found the problem
How can i Solve?


问:
Error while getting Values from SSM using Fargate
While creating Task Definition for fargate I have specified Environment variables to get value from SSM parameter store, but when the task is getting started I'm getting below error

RequestError: send request failed caused by: Post "https://ssm.us-west-2.amazonaws.com/": x509: certificate signed by unknown authority

Taskexecution role have SSM full access policy as well as AmazonECSTaskExecutionRolePolicy policy.
Not sure what I'm missing. Please let me know if I did something wrong.

Thanks in advance!

Tried adding certs to dockerfile, but as its failing before even task starts I don't think issue is with image that was created.