问:
Enable to connect through 465 port
I am trying to send an email. Everything works fine on localhost but not on production:

Connection could not be established with host
"ssl://smtp.gmail.com:465": stream_socket_client(): Unable to connect
to ssl://smtp.gmail.com:465 (Network is unreachable)

```<code>$dsn = Transport::fromDsn('gmail+smtp://mygmail@gmail.com:myapppassword@default');
$mailer = new Mailer($dsn);
$mailer->send($email);
</code>```

From the documentation about emails, I saw that the problem might be the missing verify_peer parameter in the end. So I tried with both 0 and 1 like:

```<code>$dsn = Transport::fromDsn('gmail+smtp://mygmail@gmail.com:myapppassword@default?verify_peer=0');
</code>```

and

```<code> $dsn = Transport::fromDsn('gmail+smtp://mygmail@gmail.com:myapppassword@default?verify_peer=1');
</code>```

Don't see where can I pass the tls port actually.

Title: Enable to connect through 465 port

Body:
I am trying to send an email. Everything works fine on localhost but not on production:

Connection could not be established with host
"ssl://smtp.gmail.com:465": stream_socket_client(): Unable to connect
to ssl://smtp.gmail.com:465 (Network is unreachable)

$dsn = Transport::fromDsn('gmail+smtp://mygmail@gmail.com:myapppassword@default');
$mailer = new Mailer($dsn);
$mailer->send($email);

From the documentation about emails, I saw that the problem might be the missing verify_peer parameter in the end. So I tried with both 0 and 1 like:

$dsn = Transport::fromDsn('gmail+smtp://mygmail@gmail.com:myapppassword@default?verify_peer=0');

and

 $dsn = Transport::fromDsn('gmail+smtp://mygmail@gmail.com:myapppassword@default?verify_peer=1');

Don't see where can I pass the tls port actually.


来源: stackexchange

问:
I want to give the user a 5 second time to give an input. How do I do that?
So I wan't the user to enter an input. But if they don't do it within a certain amount of time, The code ends. How do i Achieve that?

I tried using a stopwatch, but that would obviously not work since the stopwatch would start after user gives input.

ContentLicense: CC BY-SA 4.0


问:
MongoMemoryServer: Instance closed unexpectedly in supertest for express app
I am trying to use Mongo Memory Server in supertest to test my API, but I get the following error:

```<code>    Starting the MongoMemoryServer Instance failed, enable debug log for more information. Error:
 UnexpectedCloseError: Instance closed unexpectedly with code "1" and signal "null"
    at MongoInstance.closeHandler (/home/jonathanpotter/code/express-apps/rest-api-tutorial/node_modules/mongodb-memory-server-core/src/util/MongoInstance.ts:543:52)
    at ChildProcess.emit (node:events:513:28)
    at ChildProcess.emit (node:domain:489:12)
    at maybeClose (node:internal/child_process:1091:16)
    at Socket.<anonymous> (node:internal/child_process:449:11)
    at Socket.emit (node:events:513:28)
    at Socket.emit (node:domain:489:12)
    at Pipe.<anonymous> (node:net:313:12)
</code>```

My test is as follows:

```<code>import supertest from "supertest";
import createServer from "../utils/server";
import { MongoMemoryServer } from "mongodb-memory-server";
import mongoose from "mongoose";

const app = createServer();

describe("product", () => {

  beforeAll(async () => {
    const mongoServer = await MongoMemoryServer.create();
    await mongoose.connect(mongoServer.getUri());
  });

  afterAll(async () => {
    await mongoose.disconnect();
    await mongoose.connection.close();
  });

  describe("get product", () => {
    describe("given the product does not exist", () => {
      it("should return a 404", async () => {
        const productId = "product123";
        await supertest(app).get(`/api/products/${productId}`);
      });
    });
  });
});
</code>```

My testing dependencies are:

```<code>"jest": "^29.3.1",
"mongodb-memory-server": "^8.10.2",
"supertest": "^6.3.3",
"ts-jest": "^29.0.3",
"ts-node-dev": "^2.0.0",
</code>```

...and I my operating system is Pop!_OS 22.04 LTS.

edit: This all works fine on my Mac, but not on my Linux machine. Does anyone know of a fix for Linux (Pop!OS)?

Body:
I am trying to use Mongo Memory Server in supertest to test my API, but I get the following error:

    Starting the MongoMemoryServer Instance failed, enable debug log for more information. Error:
 UnexpectedCloseError: Instance closed unexpectedly with code "1" and signal "null"
    at MongoInstance.closeHandler (/home/jonathanpotter/code/express-apps/rest-api-tutorial/node_modules/mongodb-memory-server-core/src/util/MongoInstance.ts:543:52)
    at ChildProcess.emit (node:events:513:28)
    at ChildProcess.emit (node:domain:489:12)
    at maybeClose (node:internal/child_process:1091:16)
    at Socket.<anonymous> (node:internal/child_process:449:11)
    at Socket.emit (node:events:513:28)
    at Socket.emit (node:domain:489:12)
    at Pipe.<anonymous> (node:net:313:12)

My test is as follows:

import supertest from "supertest";
import createServer from "../utils/server";
import { MongoMemoryServer } from "mongodb-memory-server";
import mongoose from "mongoose";

const app = createServer();

describe("product", () => {

  beforeAll(async () => {
    const mongoServer = await MongoMemoryServer.create();
    await mongoose.connect(mongoServer.getUri());
  });

  afterAll(async () => {
    await mongoose.disconnect();
    await mongoose.connection.close();
  });

  describe("get product", () => {
    describe("given the product does not exist", () => {
      it("should return a 404", async () => {
        const productId = "product123";
        await supertest(app).get(`/api/products/${productId}`);
      });
    });
  });
});

My testing dependencies are:

"jest": "^29.3.1",
"mongodb-memory-server": "^8.10.2",
"supertest": "^6.3.3",
"ts-jest": "^29.0.3",
"ts-node-dev": "^2.0.0",

...and I my operating system is Pop!_OS 22.04 LTS.

edit: This all works fine on my Mac, but not on my Linux machine. Does anyone know of a fix for Linux (Pop!OS)?


问:
Electron 22.0/23.0 alpha not playing mkv file h265 on other machines
I made a simple media player app with electronjs to play video files and display subtitles.

When in dev or packaged mode on my PC, it plays the video fine.

When I use the same packaged app on a laptop, PC or even inside a VM (both Windows 10 or 11), the video plays but only sound and subtitles, no image.

How do I go to debug/figure what's the issue? I read that Chromium 108 is meant to support H265. And it's working fine on my machine. Would there be a codec available on my machine which am unaware of? Or is electron-builder not including the latest version of Chromium?

below is my current package.json

```<code>"scripts": {
    "dev": "vite",
    "build": "vite build && electron-builder",
    "lint": "eslint --ext .js,.vue --ignore-path .gitignore --fix src",
    "format": "prettier .  --write",
    "release": "node release.mjs"
  },
  "dependencies": {
    "electron-log": "^4.4.8",
    "electron-updater": "^5.3.0",
    "ffmpeg": "^0.0.4",
    "fs-extra": "^11.1.0",
    "mime-types": "^2.1.35",
    "mkv-subtitle-extractor": "^1.1.1",
    "srt-to-vtt": "^1.1.3"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^3.2.0",
    "autoprefixer": "^10.4.13",
    "chalk": "^5.2.0",
    "cross-env": "^7.0.3",
    "electron": "^23.0.0-alpha.3",
    "electron-builder": "^23.5.1",
    "eslint": "^8.29.0",
    "eslint-config-prettier": "^8.5.0",
    "eslint-config-standard": "^17.0.0",
    "eslint-plugin-import": "^2.26.0",
    "eslint-plugin-json": "^3.1.0",
    "eslint-plugin-n": "^15.6.0",
    "eslint-plugin-promise": "^6.1.1",
    "eslint-plugin-vue": "^9.8.0",
    "inquirer": "^9.1.4",
    "postcss": "^8.4.20",
    "prettier": "^2.8.0",
    "tailwindcss": "^3.2.4",
    "vite": "^3.2.3",
    "vite-plugin-electron": "^0.10.4",
    "vite-plugin-eslint": "^1.8.1",
    "vue": "^3.2.41"
  }
</code>```

Body:
I made a simple media player app with electronjs to play video files and display subtitles.

When in dev or packaged mode on my PC, it plays the video fine.

When I use the same packaged app on a laptop, PC or even inside a VM (both Windows 10 or 11), the video plays but only sound and subtitles, no image.

How do I go to debug/figure what's the issue? I read that Chromium 108 is meant to support H265. And it's working fine on my machine. Would there be a codec available on my machine which am unaware of? Or is electron-builder not including the latest version of Chromium?

below is my current package.json

"scripts": {
    "dev": "vite",
    "build": "vite build && electron-builder",
    "lint": "eslint --ext .js,.vue --ignore-path .gitignore --fix src",
    "format": "prettier .  --write",
    "release": "node release.mjs"
  },
  "dependencies": {
    "electron-log": "^4.4.8",
    "electron-updater": "^5.3.0",
    "ffmpeg": "^0.0.4",
    "fs-extra": "^11.1.0",
    "mime-types": "^2.1.35",
    "mkv-subtitle-extractor": "^1.1.1",
    "srt-to-vtt": "^1.1.3"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^3.2.0",
    "autoprefixer": "^10.4.13",
    "chalk": "^5.2.0",
    "cross-env": "^7.0.3",
    "electron": "^23.0.0-alpha.3",
    "electron-builder": "^23.5.1",
    "eslint": "^8.29.0",
    "eslint-config-prettier": "^8.5.0",
    "eslint-config-standard": "^17.0.0",
    "eslint-plugin-import": "^2.26.0",
    "eslint-plugin-json": "^3.1.0",
    "eslint-plugin-n": "^15.6.0",
    "eslint-plugin-promise": "^6.1.1",
    "eslint-plugin-vue": "^9.8.0",
    "inquirer": "^9.1.4",
    "postcss": "^8.4.20",
    "prettier": "^2.8.0",
    "tailwindcss": "^3.2.4",
    "vite": "^3.2.3",
    "vite-plugin-electron": "^0.10.4",
    "vite-plugin-eslint": "^1.8.1",
    "vue": "^3.2.41"
  }


问:
What if I preload a lazily loaded image?
I have a mobile-only image. The problem is that with the default loading strategy (eager) the image is getting loaded even on desktops or larger screens. But the image is important for mobile devices only, and at the same time, it should be available as soon as possible. So, it's not possible to lazy load the image, either.

But what if I conditionally preload (using media query) the image and lazy load it at the same time?

<link rel="preload" media="(max-width: 768px)" href="/path/to/image" as="image/type">

```

It solves both of the problems: the image doesn't load on desktops, and it's available as soon as possible on mobile devices. But is there any other issue with this approach that I have missed?

Body:
I have a mobile-only image. The problem is that with the default loading strategy (eager) the image is getting loaded even on desktops or larger screens. But the image is important for mobile devices only, and at the same time, it should be available as soon as possible. So, it's not possible to lazy load the image, either.

But what if I conditionally preload (using media query) the image and lazy load it at the same time?

<link rel="preload" media="(max-width: 768px)" href="/path/to/image" as="image/type">

It solves both of the problems: the image doesn't load on desktops, and it's available as soon as possible on mobile devices. But is there any other issue with this approach that I have missed?


问:
mips assembly octal to decimal
i have a task where i need to turn octal numbers in the data to their right decimal counterpart.
the numbers in the data are in octal and i need to turn then to decimal.enter image description here.

i tried to make loop that suppurate the 10' bit like 3 in 35.

for example for the number 35 i need that in the end ,in the register will be 29d.
also can i do it in byte or i need to change it to ascii ?

Title: mips assembly octal to decimal


问:
Image view not changing/Shared prefs not updating (android)
My app utilizes a Image view that changes daily. It runs a receiver every 24 hours which should send a notification and change the shared preferences value (this being the image to display). The notification runs fine at the correct time so I know the receiver works correctly. When you launch the activity the image that needs to be changed is located, the app gets the shared preferences value and then sets the imageView to display that image. The default value is set to 0, and if the value is 0 it sets the image to a "something went wrong" style of image. How come the notification works but my image view doesn't change? It stays as the "something went wrong image"?

My code:

The Reciever:

```<code>    val quotes = arrayOf(R.drawable.i1, R.drawable.i2, R.drawable.i3, R.drawable.i5, R.drawable.i6, R.drawable.i7, R.drawable.i8, R.drawable.i9, R.drawable.i10, R.drawable.i11, R.drawable.i12, R.drawable.i13, R.drawable.i14, R.drawable.i15, R.drawable.i16, R.drawable.i17, R.drawable.i18, R.drawable.i19, R.drawable.i20, R.drawable.i21, R.drawable.i22, R.drawable.i23, R.drawable.i24, R.drawable.i25)
    val quote = quotes.random()

    val prefquotes = context.getSharedPreferences("save", AppCompatActivity.MODE_PRIVATE).edit()
    prefquotes.putInt("Quotes", quote)
    prefquotes.apply()
</code>```

Qinsperation:

```<code>        val quote = sharedPreferences.getInt("Quote", 0)

        setContentView(R.layout.qinsperational)

        val imageView = findViewById<ImageView>(R.id.daily_image)

       if (quote == 0) {
           imageView.setImageResource(R.drawable.oh_no)
       }else{
           Log.d("Quote", "good")
           imageView.setImageResource(quote)
       }
</code>```

There is no crashes or anything in the logs. All help is much appreciated as I can't figure this one out

Body:
My app utilizes a Image view that changes daily. It runs a receiver every 24 hours which should send a notification and change the shared preferences value (this being the image to display). The notification runs fine at the correct time so I know the receiver works correctly. When you launch the activity the image that needs to be changed is located, the app gets the shared preferences value and then sets the imageView to display that image. The default value is set to 0, and if the value is 0 it sets the image to a "something went wrong" style of image. How come the notification works but my image view doesn't change? It stays as the "something went wrong image"?

My code:

The Reciever:

    val quotes = arrayOf(R.drawable.i1, R.drawable.i2, R.drawable.i3, R.drawable.i5, R.drawable.i6, R.drawable.i7, R.drawable.i8, R.drawable.i9, R.drawable.i10, R.drawable.i11, R.drawable.i12, R.drawable.i13, R.drawable.i14, R.drawable.i15, R.drawable.i16, R.drawable.i17, R.drawable.i18, R.drawable.i19, R.drawable.i20, R.drawable.i21, R.drawable.i22, R.drawable.i23, R.drawable.i24, R.drawable.i25)
    val quote = quotes.random()

    val prefquotes = context.getSharedPreferences("save", AppCompatActivity.MODE_PRIVATE).edit()
    prefquotes.putInt("Quotes", quote)
    prefquotes.apply()

Qinsperation:

        val quote = sharedPreferences.getInt("Quote", 0)

        setContentView(R.layout.qinsperational)

        val imageView = findViewById<ImageView>(R.id.daily_image)

       if (quote == 0) {
           imageView.setImageResource(R.drawable.oh_no)
       }else{
           Log.d("Quote", "good")
           imageView.setImageResource(quote)
       }

There is no crashes or anything in the logs. All help is much appreciated as I can't figure this one out


问:
Mediawiki Page Forms Javascript error when adding a new field
I use:

MediaWiki v1.39

Extension Page Forms 5.5.1

Extension Cargo 3.3.1

PHP 7.4 or PHP 8.0.26

When I open page Special:CreateClass, fill in a field and then click "Add field" I get a javascript error.

```<code>Uncaught TypeError: Cannot read properties of undefined (reading 'replace')
    at pf.ComboBoxInput.apply (<anonymous>:86:73)
    at jQuery.fn.createTemplateAddField (<anonymous>:79:26)
    at HTMLSpanElement.<anonymous> (<anonymous>:84:116)
    at HTMLSpanElement.dispatch (load.php?lang=nl&modules=ext.pageforms.select2%7Cjquery%2Cmoment%2Coojs-ui-core%2Coojs-ui-widgets&skin=vector&version=8i8qb:206:260)
    at elemData.handle (load.php?lang=nl&modules=ext.pageforms.select2%7Cjquery%2Cmoment%2Coojs-ui-core%2Coojs-ui-widgets&skin=vector&version=8i8qb:202:877)
</code>```

I also have installed the Cargo 3.3.1 extension, but get the same error whether I uncheck or check the box "Use the Cargo extension..."

When using Firefox I get the error:

```<code>    apply jQuery
load.php:234:45
    jQuery 23
</code>```

Tried it in Chrome and Edge too but doesn't work in those either.

UPDATE 18-dec-2022:

I installed Mediawiki 1.35.8 and PageForms 5.5.1 and get the javascript error.

Solution / Workaround:

After installing PageForms 5.5 it is working in 1.39

Body:
I use:

MediaWiki v1.39

Extension Page Forms 5.5.1

Extension Cargo 3.3.1

PHP 7.4 or PHP 8.0.26

When I open page Special:CreateClass, fill in a field and then click "Add field" I get a javascript error.

Uncaught TypeError: Cannot read properties of undefined (reading 'replace')
    at pf.ComboBoxInput.apply (<anonymous>:86:73)
    at jQuery.fn.createTemplateAddField (<anonymous>:79:26)
    at HTMLSpanElement.<anonymous> (<anonymous>:84:116)
    at HTMLSpanElement.dispatch (load.php?lang=nl&modules=ext.pageforms.select2%7Cjquery%2Cmoment%2Coojs-ui-core%2Coojs-ui-widgets&skin=vector&version=8i8qb:206:260)
    at elemData.handle (load.php?lang=nl&modules=ext.pageforms.select2%7Cjquery%2Cmoment%2Coojs-ui-core%2Coojs-ui-widgets&skin=vector&version=8i8qb:202:877)

I also have installed the Cargo 3.3.1 extension, but get the same error whether I uncheck or check the box "Use the Cargo extension..."

When using Firefox I get the error:

    apply jQuery
load.php:234:45
    jQuery 23

Tried it in Chrome and Edge too but doesn't work in those either.

UPDATE 18-dec-2022:

I installed Mediawiki 1.35.8 and PageForms 5.5.1 and get the javascript error.

Solution / Workaround:

After installing PageForms 5.5 it is working in 1.39


问:
Nuxt 3.0.0 transition/animations not working
I tried to use all animations and transitions technics, but it doesn't work in today's latest version of Nuxt 3.0.0 and Nitro 1.0.0.

But when I use older projects where is Nuxt 3.0.0-rc.12 it's working.

Is there any package that is removed from the latest version of Nuxt?

If I use older versions everything is working fine but Nuxt /3.0.0-rc.13/3.0.0-rc.14/ 3.0.0 does not work...

In Chrome inspect element switching between routes there are no toggling CSS classes like enter, leave, etc like in rc.12.


问:
Playsound() breaks my ASCII animation in Python
I have this code, it's for an ASCII animation that loops 100 times (just to put a number) with 4 frames

```<code>import os,time,random
from playsound import playsound

os.system('cls') # linus - 'clear'
filenames = ["milton1.txt","milton2.txt","milton3.txt","milton2.txt"]
frames = []

for name in filenames:
    with open(name,"r",encoding="utf8") as f:
        frames.append(f.readlines())

for i in range(100):
    eye_opened=True
    for frame in frames:
        print("".join(frame))
        if eye_opened:
            playsound("Beep.wav")
            time.sleep(random. randint(1,5))
            eye_opened=False
        else:
            time.sleep(0.075)
        os.system('cls')
</code>```

The problem is that after the first loop, when it's time to go back to the first frame (milton1.txt) the program closes, but it gets fixed when I delete the playsound("Beep.wav") part, I have no idea what to do or why this happens

Also, kinda unrelated, when I add playsound("Beep.wav", block=False) it just crashes without doing anything, I have understood that block=False makes it so the animation doesn't have to wait for the sound to finish playing before continuing, but it doesn't work

Body:
I have this code, it's for an ASCII animation that loops 100 times (just to put a number) with 4 frames

import os,time,random
from playsound import playsound

os.system('cls') # linus - 'clear'
filenames = ["milton1.txt","milton2.txt","milton3.txt","milton2.txt"]
frames = []

for name in filenames:
    with open(name,"r",encoding="utf8") as f:
        frames.append(f.readlines())

for i in range(100):
    eye_opened=True
    for frame in frames:
        print("".join(frame))
        if eye_opened:
            playsound("Beep.wav")
            time.sleep(random. randint(1,5))
            eye_opened=False
        else:
            time.sleep(0.075)
        os.system('cls')

The problem is that after the first loop, when it's time to go back to the first frame (milton1.txt) the program closes, but it gets fixed when I delete the playsound("Beep.wav") part, I have no idea what to do or why this happens

Also, kinda unrelated, when I add playsound("Beep.wav", block=False) it just crashes without doing anything, I have understood that block=False makes it so the animation doesn't have to wait for the sound to finish playing before continuing, but it doesn't work


问:
Uncaught (in promise) TypeError: Cannot read properties of null (reading 'value') in react
Im new to react, i want to get input and store the input to the smartcontract. but i keep getting this error, can someone help me ?

this is the file (https://github.com/fahmifakhir/voting-dapp/blob/main/CreateVoting.js


问:
Filtration of the Rows based on the Year and product_id
I have a dataset with columns customer_id, ordered_year, product_id.
I need to drop some of the rows based on a filter - If a product is ordered in 2020 and not ordered in 2021 & 2022.I need to drop these rows.
Any suggestion how to proceed ?

Tried with If conditions but did not got the expected result.


问:
Use node ssh into Runcloud gives a different version to what is actually installed/used by NVM on the server
I have a server on Runcloud on which I've used NVM and installed the version 16.14.2.

If I ssh via any SSH client and run node -v, I effectively get 16.14.2

Though when I wrote a script to ssh into the server and run the same command, I get 10.0

I was previously advised to create an alias, I tried to follow some steps I came across for that but it did not fix my issue. Further more, referencing the path to the desired version of npm inside nvm gives me an error that this version npm cannot run with node 10.0
npm does not support Node.js v10.0.0\n

Below is my code

```<code>import { NodeSSH } from 'node-ssh'

const ssh = new NodeSSH()

const { environment } = await inquirer.prompt([
  {
    name: 'environment',
    message: `Environment?`,
    type: 'input',
    default: 'development'
  }
])

if (build) {
  const sshConfig = sshConfigs[environment]

  console.log(chalk.yellow(`Connecting to ${sshConfig.host}...`))

  await ssh.connect(sshConfig)

  console.log(chalk.green('Connected'))

  console.log(chalk.yellow('Executing release...'))

  const nodePath = '~/.nvm/versions/node/v16.14.2/bin/node'

  const npmPath = '~/.nvm/versions/node/v16.14.2/bin/npm'

  console.log(await ssh.execCommand(`${npmPath} -v`))

  ssh.dispose()

  console.log(chalk.green('Release completed'))
}

</code>```

Body:
I have a server on Runcloud on which I've used NVM and installed the version 16.14.2.

If I ssh via any SSH client and run node -v, I effectively get 16.14.2

Though when I wrote a script to ssh into the server and run the same command, I get 10.0

I was previously advised to create an alias, I tried to follow some steps I came across for that but it did not fix my issue. Further more, referencing the path to the desired version of npm inside nvm gives me an error that this version npm cannot run with node 10.0
npm does not support Node.js v10.0.0\n

Below is my code

import { NodeSSH } from 'node-ssh'

const ssh = new NodeSSH()

const { environment } = await inquirer.prompt([
  {
    name: 'environment',
    message: `Environment?`,
    type: 'input',
    default: 'development'
  }
])

if (build) {
  const sshConfig = sshConfigs[environment]

  console.log(chalk.yellow(`Connecting to ${sshConfig.host}...`))

  await ssh.connect(sshConfig)

  console.log(chalk.green('Connected'))

  console.log(chalk.yellow('Executing release...'))

  const nodePath = '~/.nvm/versions/node/v16.14.2/bin/node'

  const npmPath = '~/.nvm/versions/node/v16.14.2/bin/npm'

  console.log(await ssh.execCommand(`${npmPath} -v`))

  ssh.dispose()

  console.log(chalk.green('Release completed'))
}


问:
refetchQueries not updating UI on Delete Note Item Action
I'm learn from projects Javascript Everywhere book. I have a problem when i'm doing delete (mutation) action. in the Backend, Delete Mutation works normally. But in the front end. let's say i'm have 2 pages that querying notes. Home and MyNotes.

Home page

My Notes Page

When i'm clicking delete note. it direct to '/mynotes' page, and delete the note. UI update normaly when i'm deleting inside mynotes page, but when i'm going to home page, notes that has been delete before is still showing.

here's my code
DeleteNote.js

```<code>import React from 'react';
import { useMutation } from '@apollo/client';
import { withRouter } from 'react-router-dom';

import ButtonAsLink from './ButtonAsLink';
import { DELETE_NOTE } from '../gql/mutation';
import { GET_MY_NOTES, GET_NOTES } from '../gql/query';

const DeleteNote = props => {
  const [deleteNote] = useMutation(DELETE_NOTE, {
    variables: {
      id: props.noteId
    },
    // refetch the note list queries to update the cache
    refetchQueries: [{ query: GET_MY_NOTES, GET_NOTES }],
    onCompleted: data => {
      // redirect the user to the "my notes" page
      props.history.push('/mynotes');
    },
    options: {
        fetchPolicy: 'cache-first',
        errorPolicy: 'ignore'
    }
  });

  return <ButtonAsLink onClick={deleteNote}>Delete Note</ButtonAsLink>;
};

export default withRouter(DeleteNote)
</code>```

;

delete mutation

```<code>const DELETE_NOTE = gql`
    mutation deleteNote($id: ID!) {
        deleteNote(id: $id)
    }
`;
</code>```

i want to delete note in homepage with realtime results. i don't have any idea , i'm beginner in graphQL. any help will be appreciated, thank you.

Body:
I'm learn from projects Javascript Everywhere book. I have a problem when i'm doing delete (mutation) action. in the Backend, Delete Mutation works normally. But in the front end. let's say i'm have 2 pages that querying notes. Home and MyNotes.

Home page

My Notes Page

When i'm clicking delete note. it direct to '/mynotes' page, and delete the note. UI update normaly when i'm deleting inside mynotes page, but when i'm going to home page, notes that has been delete before is still showing.

here's my code
DeleteNote.js

import React from 'react';
import { useMutation } from '@apollo/client';
import { withRouter } from 'react-router-dom';

import ButtonAsLink from './ButtonAsLink';
import { DELETE_NOTE } from '../gql/mutation';
import { GET_MY_NOTES, GET_NOTES } from '../gql/query';

const DeleteNote = props => {
  const [deleteNote] = useMutation(DELETE_NOTE, {
    variables: {
      id: props.noteId
    },
    // refetch the note list queries to update the cache
    refetchQueries: [{ query: GET_MY_NOTES, GET_NOTES }],
    onCompleted: data => {
      // redirect the user to the "my notes" page
      props.history.push('/mynotes');
    },
    options: {
        fetchPolicy: 'cache-first',
        errorPolicy: 'ignore'
    }
  });

  return <ButtonAsLink onClick={deleteNote}>Delete Note</ButtonAsLink>;
};

export default withRouter(DeleteNote)

;

delete mutation

const DELETE_NOTE = gql`
    mutation deleteNote($id: ID!) {
        deleteNote(id: $id)
    }
`;

i want to delete note in homepage with realtime results. i don't have any idea , i'm beginner in graphQL. any help will be appreciated, thank you.


问:
how to alter table to add two or more foreign keys
I tried using the code below to add two foreign keys to the table products but it wont add foreign keys if i run the two on one run, they work individualy but not if i code it the way below:

```<code> ALTER TABLE products
   ADD FOREIGN KEY (CategoryI)  REFERENCES categories (CategoryID),
   ADD FOREIGN KEY (SupplierID) REFERENCES suppliers (SupplierID);
</code>```

two alter table to make two foreign keys from separate tables

Body:
I tried using the code below to add two foreign keys to the table products but it wont add foreign keys if i run the two on one run, they work individualy but not if i code it the way below:

 ALTER TABLE products
   ADD FOREIGN KEY (CategoryI)  REFERENCES categories (CategoryID),
   ADD FOREIGN KEY (SupplierID) REFERENCES suppliers (SupplierID);

two alter table to make two foreign keys from separate tables


问:
How to create tab-completion for custom language in VSCode?
I am pressing tab with a "term" in scope (in the file), but tab does nothing in my custom language.

How can I turn on tab completion so it finds tokens/terms/keywords (things separated by spaces even) and autocompletes them? Do I need to create a full-on language server to do this? Or is there an extension config variable somewhere I simply need to turn on?


问:
Storage reuse Undefined behaviour
Reading in the cppreference for lifetime, there is the following statement for storage reuse

A program is not required to call the destructor of an object to end
its lifetime if the object is trivially-destructible or if the program
does not rely on the side effects of the destructor. However, if a
program ends the lifetime of an non-trivially destructible object that
is a variable explicitly, it must ensure that a new object of the same
type is constructed in-place (e.g. via placement new) before the
destructor may be called implicitly, i.e. due to scope exit or
exception for automatic objects, due to thread exit for thread-local
objects, or due to program exit for static objects; otherwise the
behavior is undefined.

There is the following example

```<code>class T {}; // trivial

struct B
{
    ~B() {} // non-trivial
};

void x()
{
    long long n; // automatic, trivial
    new (&n) double(3.14); // reuse with a different type okay
} // okay

void h()
{
    B b; // automatic non-trivially destructible
    b.~B(); // end lifetime (not required, since no side-effects)
    new (&b) T; // wrong type: okay until the destructor is called
} // destructor is called: undefined behavior
</code>```

Why when the destructor of T is called is undefined behavior?

In the above example, if std::launder is used , is the UB issue solved? Look at the following demo

Title: Storage reuse Undefined behaviour

Body:
Reading in the cppreference for lifetime, there is the following statement for storage reuse

A program is not required to call the destructor of an object to end
its lifetime if the object is trivially-destructible or if the program
does not rely on the side effects of the destructor. However, if a
program ends the lifetime of an non-trivially destructible object that
is a variable explicitly, it must ensure that a new object of the same
type is constructed in-place (e.g. via placement new) before the
destructor may be called implicitly, i.e. due to scope exit or
exception for automatic objects, due to thread exit for thread-local
objects, or due to program exit for static objects; otherwise the
behavior is undefined.

There is the following example

class T {}; // trivial

struct B
{
    ~B() {} // non-trivial
};

void x()
{
    long long n; // automatic, trivial
    new (&n) double(3.14); // reuse with a different type okay
} // okay

void h()
{
    B b; // automatic non-trivially destructible
    b.~B(); // end lifetime (not required, since no side-effects)
    new (&b) T; // wrong type: okay until the destructor is called
} // destructor is called: undefined behavior

Why when the destructor of T is called is undefined behavior?

In the above example, if std::launder is used , is the UB issue solved? Look at the following demo


问:
Not a single-group group function in TDengine
I'm writing a sql with partition by in TDengine database.

My statement is:

```<code>select app_id, task_name, sum(allocated) as allocated
from (
    select tbname as app_id,
           task_name,
           apercentile(allocated, 90) as allocated
    from yarn
     where ts > now -5m
       and tenant_name = 'xxxx'
 partition by tbname,
              task_name
   ) t
partition by task_name;
</code>```

It reports an error:

DB error: Not a single-group group function

Why is it working correctly?

Body:
I'm writing a sql with partition by in TDengine database.

My statement is:

select app_id, task_name, sum(allocated) as allocated
from (
    select tbname as app_id,
           task_name,
           apercentile(allocated, 90) as allocated
    from yarn
     where ts > now -5m
       and tenant_name = 'xxxx'
 partition by tbname,
              task_name
   ) t
partition by task_name;

It reports an error:

DB error: Not a single-group group function

Why is it working correctly?


问:
How can I retrive data from a mongodb database and show in an ejs file?
I am trying to create a calendar using Nodejs, EJS and Mongodb wherein one can write events for a particular day. The events get stored in a collection called Names in a mongodb database called Sample Database.

This is the code in app.js file.

```<code>const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const { MongoClient } = require("mongodb");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));

const uri =
"mongodb+srv://netTheCoder:welcome@cluster0.ra2eh5p.mongodb.net/?retryWrites=true&w=majority";
const client = new MongoClient(uri);
var eventItems = [];
var eventsObj={};
var events_arr = [];
var inputEvent,inputDate;
var added;
</code>```

```<code> app.get("/calendar",function(req,res){
console.log(events_arr);
   res.render('calendar',{newListItem: eventItems, added : added, eventsArr : events_arr});    })
app.post("/calendar",function(req,res){
   inputEvent = req.body.eventInput   inputDate = req.body.eventDate;
   eventsObj= {
   date:inputDate,
 description: inputEvent
 }
events_arr.push(eventsObj)
console.log(eventsObj);
   // obj={

  //   user :"user1",
//   events: events_arr   // }
AddEvents().catch(console.dir);
  eventItems.push(inputEvent);
added = true;
res.redirect("/calendar");
})
async function AddEvents() {
try {
const database = client.db('SampleDatabase');
const names = database.collection('n');
//Adding events to calendar
const addedItem = await names.insertOne(eventsObj);
console.log("Item added successfully")
console.log(addedItem);
// Query for a movie that has the title 'Back to the Future'
}         finally {
   } }

async function getEvents() {
 try {
const database = client.db('SampleDatabase');
const names = database.collection('Names');
//Adding events to calendar
const addedItem = await names.find();
 console.log("Item added successfully")
console.log(addedItem);

 // const query = { date: "16-12-22"};
// const event = await names.find(query);    }

finally {   //
// Ensures that the client will close when you finish/error   //   await client.close();   } }

server.listen(3000,function(req,res){   console.log("The server is running at port 3000"); })
</code>```

The calendar.js file

```<code> const currentDate = $(".current-date"),
    daysTag = $(".days"),
    prevNextIcons = document.querySelectorAll(".calender-icons span");

//getting the present date, year and month
let date = new Date(),
    currentYear = date.getFullYear(),
    currentMonth = date.getMonth();
console.log(currentMonth)
const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

const renderCalendar = () => {

    const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

    let firstDayofMonth = new Date(currentYear, currentMonth, 1).getDay();
    let lastDateofMonth = new Date(currentYear, currentMonth + 1, 0).getDate();
    let lastDayofMonth = new Date(currentYear, currentMonth, lastDateofMonth ).getDay()
    let lastDateofLastMonth = new Date(currentYear, currentMonth, 0).getDate();

    let liTag = "";

    for (let i = firstDayofMonth ; i > 0; i--) {
        liTag += `<li class="day inactive">${lastDateofLastMonth-i +1}</li>`

    }

    for (let i = 1; i <= lastDateofMonth; i++) {
        let isToday = i ===  date.getDate() && currentMonth === new Date().getMonth()
                      && currentYear === new Date().getFullYear() ? "active" :"";
        liTag += `<li class="day ${isToday}">${i}</li>`
    }
   for(let i =lastDayofMonth; i<6 ;i++){
    liTag += `<li class="day inactive">${i-lastDayofMonth +1}</li>`
   }

    currentDate.text(`${months[currentMonth]} ${currentYear}`);
    daysTag.html(liTag)
}
renderCalendar();

prevNextIcons.forEach(icon => {
    icon.addEventListener("click", () => {
        if (icon.id === "prev") {

            if (currentMonth === 0) {
                currentMonth = 11;
                currentYear = currentYear - 1;
            } else {
                currentMonth = currentMonth - 1;
            }

            console.log(currentMonth);
            renderCalendar();
            dateClicked();
        } else {

            if (currentMonth === 11) {
                currentMonth = 0;
                currentYear = currentYear + 1;
            } else {
                currentMonth = currentMonth + 1;
            }
            console.log(currentMonth);

            renderCalendar();
            dateClicked();
        }

    })
})

let dateObj = new Date();
let today = String(dateObj.getDate()).padStart(2, '0');
$(".event-date").text(today +" " + months[currentMonth]);

let eventLi ="";
var eventAddedDay;
dateClicked();
function dateClicked(){
    selectedDate = document.querySelectorAll(".day")
    selectedDate.forEach(day=>{
        day.addEventListener("click",()=>{
        var clickedDate = day.textContent;
        $(".event-date").text(clickedDate + " " + months[currentMonth]);
        let clickedMonth = currentMonth+1;
        let output = currentYear + '-' + clickedMonth + '-' + clickedDate;
       console.log("clicked");
        $(".events-date").attr('value' ,output );
        })
    })
}

</code>```

The code for calendar in calendar.ejs file. This file is linked to calendar.js file.

```<code><div class="calendar">
        <ul class="weeks">
            <li>Sun</li>
            <li>Mon</li>
            <li>Tues</li>
            <li>Wed</li>
            <li>Thurs</li>
            <li>Fri</li>
            <li>Sat</li>
        </ul>
        <ul class="days"></ul>
    </div>
  </div>
</div>
<div id = "events">
    <h3 class="event-date"></h3>
    <ul type="disc" class="events">

        <% for(let i = 0; i<newListItem.length; i++){ %>
        <li> <%= newListItem[i] %></li>
        <% } %>

    </ul>
    <p class="retured-date" hidden>

    </p>
    <form method="post" action="/calendar">
    <input class="events-date" type="date" name="eventDate" placeholder="Date">
    <input class="event-input" type="text" name="eventInput" placeholder="Your event">
    <button type="submit" class="btn btn-outline-dark">Add</button>
</form>
</div>
</code>```

I was trying to send this data through ejs to my HTML calendar page. So when I click on a  day in the calendar the events stored in the database for that particular day should be displayed in the events section . I don't know why but I have tried all possible ways to tackle this but none of them seem to work.

Body:
I am trying to create a calendar using Nodejs, EJS and Mongodb wherein one can write events for a particular day. The events get stored in a collection called Names in a mongodb database called Sample Database.

This is the code in app.js file.

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const { MongoClient } = require("mongodb");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));

const uri =
"mongodb+srv://netTheCoder:welcome@cluster0.ra2eh5p.mongodb.net/?retryWrites=true&w=majority";
const client = new MongoClient(uri);
var eventItems = [];
var eventsObj={};
var events_arr = [];
var inputEvent,inputDate;
var added;

 app.get("/calendar",function(req,res){
console.log(events_arr);
   res.render('calendar',{newListItem: eventItems, added : added, eventsArr : events_arr});    })
app.post("/calendar",function(req,res){
   inputEvent = req.body.eventInput   inputDate = req.body.eventDate;
   eventsObj= {
   date:inputDate,
 description: inputEvent
 }
events_arr.push(eventsObj)
console.log(eventsObj);
   // obj={

  //   user :"user1",
//   events: events_arr   // }
AddEvents().catch(console.dir);
  eventItems.push(inputEvent);
added = true;
res.redirect("/calendar");
})
async function AddEvents() {
try {
const database = client.db('SampleDatabase');
const names = database.collection('n');
//Adding events to calendar
const addedItem = await names.insertOne(eventsObj);
console.log("Item added successfully")
console.log(addedItem);
// Query for a movie that has the title 'Back to the Future'
}         finally {
   } }

async function getEvents() {
 try {
const database = client.db('SampleDatabase');
const names = database.collection('Names');
//Adding events to calendar
const addedItem = await names.find();
 console.log("Item added successfully")
console.log(addedItem);

 // const query = { date: "16-12-22"};
// const event = await names.find(query);    }

finally {   //
// Ensures that the client will close when you finish/error   //   await client.close();   } }

server.listen(3000,function(req,res){   console.log("The server is running at port 3000"); })

The calendar.js file

 const currentDate = $(".current-date"),
    daysTag = $(".days"),
    prevNextIcons = document.querySelectorAll(".calender-icons span");

//getting the present date, year and month
let date = new Date(),
    currentYear = date.getFullYear(),
    currentMonth = date.getMonth();
console.log(currentMonth)
const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

const renderCalendar = () => {

    const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

    let firstDayofMonth = new Date(currentYear, currentMonth, 1).getDay();
    let lastDateofMonth = new Date(currentYear, currentMonth + 1, 0).getDate();
    let lastDayofMonth = new Date(currentYear, currentMonth, lastDateofMonth ).getDay()
    let lastDateofLastMonth = new Date(currentYear, currentMonth, 0).getDate();

    let liTag = "";

    for (let i = firstDayofMonth ; i > 0; i--) {
        liTag += `<li class="day inactive">${lastDateofLastMonth-i +1}</li>`

    }

    for (let i = 1; i <= lastDateofMonth; i++) {
        let isToday = i ===  date.getDate() && currentMonth === new Date().getMonth()
                      && currentYear === new Date().getFullYear() ? "active" :"";
        liTag += `<li class="day ${isToday}">${i}</li>`
    }
   for(let i =lastDayofMonth; i<6 ;i++){
    liTag += `<li class="day inactive">${i-lastDayofMonth +1}</li>`
   }

    currentDate.text(`${months[currentMonth]} ${currentYear}`);
    daysTag.html(liTag)
}
renderCalendar();

prevNextIcons.forEach(icon => {
    icon.addEventListener("click", () => {
        if (icon.id === "prev") {

            if (currentMonth === 0) {
                currentMonth = 11;
                currentYear = currentYear - 1;
            } else {
                currentMonth = currentMonth - 1;
            }

            console.log(currentMonth);
            renderCalendar();
            dateClicked();
        } else {

            if (currentMonth === 11) {
                currentMonth = 0;
                currentYear = currentYear + 1;
            } else {
                currentMonth = currentMonth + 1;
            }
            console.log(currentMonth);

            renderCalendar();
            dateClicked();
        }

    })
})

let dateObj = new Date();
let today = String(dateObj.getDate()).padStart(2, '0');
$(".event-date").text(today +" " + months[currentMonth]);

let eventLi ="";
var eventAddedDay;
dateClicked();
function dateClicked(){
    selectedDate = document.querySelectorAll(".day")
    selectedDate.forEach(day=>{
        day.addEventListener("click",()=>{
        var clickedDate = day.textContent;
        $(".event-date").text(clickedDate + " " + months[currentMonth]);
        let clickedMonth = currentMonth+1;
        let output = currentYear + '-' + clickedMonth + '-' + clickedDate;
       console.log("clicked");
        $(".events-date").attr('value' ,output );
        })
    })
}

The code for calendar in calendar.ejs file. This file is linked to calendar.js file.

Sun

Mon

Tues

Wed

Thurs

Fri

Sat

        <% for(let i = 0; i<newListItem.length; i++){ %>

 <%= newListItem[i] %>

        <% } %>

    <form method="post" action="/calendar">
    <input class="events-date" type="date" name="eventDate" placeholder="Date">
    <input class="event-input" type="text" name="eventInput" placeholder="Your event">
    <button type="submit" class="btn btn-outline-dark">Add</button>
</form>

I was trying to send this data through ejs to my HTML calendar page. So when I click on a  day in the calendar the events stored in the database for that particular day should be displayed in the events section . I don't know why but I have tried all possible ways to tackle this but none of them seem to work.


问:
A small problem with stm32f103c8t6 using DMA to transmit data
guys. I need some help. I am a novice, I am learning to use stm32, just when I was learning DMA data transmission, I found a strange place, so I looked up some materials, but limited by the knowledge reserve, I could not understand. If you know the reason, can you explain it to me?

```<code>uint8_t block[18] = {0};
HAL_UART_Receive_DMA(&huart1, block, 18);
while (1) {
    if (block[0] == '0') {
        HAL_GPIO_WritePin(GPIOA, GPIO_PIN_1, GPIO_PIN_SET);

        for (uint8_t i = 0; i < 18; i++) {
            block[i] = 0;
        }
    }
    if (block[0] == '1') {
        HAL_GPIO_WritePin(GPIOA, GPIO_PIN_1, GPIO_PIN_RESET);

        for (uint8_t i = 0; i < 18; i++) {
            block[i] = '3';
            count++;
        }
    }
</code>```

I'm using the hal library, I've configured DMA to transfer my data using cubemx, you can see I wanted to control the LED by string, it worked, but I found that block[0] meant that I had to send 1's over and over again 18 times before I could control it again, so I used a loop to make the array all zeros after controlling the LED, But unexpectedly, it failed. It becomes 3111 1111 1111 1111 11 in the block array, so I add a counter to count OK, and I find it loops 12 times, and when I send 1111 1111 1111 1111 1111, it loops 24 times, and again I find it loops 36 times.

I was very strange, I guess it was sending some kind of interrupt.

I know what I'm describing isn't clear, but I can't help it. I'm using machine translation, and I don't have a camera.

I would appreciate it if you would help me. If you leave a comment here, thank you. I may not be able to reply your message in time, I hope you can forgive me.

Body:
guys. I need some help. I am a novice, I am learning to use stm32, just when I was learning DMA data transmission, I found a strange place, so I looked up some materials, but limited by the knowledge reserve, I could not understand. If you know the reason, can you explain it to me?

uint8_t block[18] = {0};
HAL_UART_Receive_DMA(&huart1, block, 18);
while (1) {
    if (block[0] == '0') {
        HAL_GPIO_WritePin(GPIOA, GPIO_PIN_1, GPIO_PIN_SET);

        for (uint8_t i = 0; i < 18; i++) {
            block[i] = 0;
        }
    }
    if (block[0] == '1') {
        HAL_GPIO_WritePin(GPIOA, GPIO_PIN_1, GPIO_PIN_RESET);

        for (uint8_t i = 0; i < 18; i++) {
            block[i] = '3';
            count++;
        }
    }

I'm using the hal library, I've configured DMA to transfer my data using cubemx, you can see I wanted to control the LED by string, it worked, but I found that block[0] meant that I had to send 1's over and over again 18 times before I could control it again, so I used a loop to make the array all zeros after controlling the LED, But unexpectedly, it failed. It becomes 3111 1111 1111 1111 11 in the block array, so I add a counter to count OK, and I find it loops 12 times, and when I send 1111 1111 1111 1111 1111, it loops 24 times, and again I find it loops 36 times.

I was very strange, I guess it was sending some kind of interrupt.

I know what I'm describing isn't clear, but I can't help it. I'm using machine translation, and I don't have a camera.

I would appreciate it if you would help me. If you leave a comment here, thank you. I may not be able to reply your message in time, I hope you can forgive me.


问:
Printf gives SegFault when single element in stack
I have encountered a problem with printf spitting out segfaults whenever there is only one element in the stack. Here, what I want the script to do is print 5, only then do the add operation, but segmentation fault happens.

Interestingly, if I push 6 right after I push 5 and then print, it works. Thus, I suppose the problem occurs when there is only one element in the stack.

Any ideas?

Thank you in advance!

```<code>.fmt:
    .asciz "%d\n"
.text

.globl _start

_start:
    push $5

    pop %rdx
    mov %rdx, %rsi
    push %rdx
    mov $.fmt, %rdi
    call printf
    xor %rax, %rax

    push $6

    pop %rdx
    pop %rcx
    add %rdx, %rcx
    push %rcx

    mov $60, %rax
    pop %rdi
    syscall
</code>```

Body:
I have encountered a problem with printf spitting out segfaults whenever there is only one element in the stack. Here, what I want the script to do is print 5, only then do the add operation, but segmentation fault happens.

Interestingly, if I push 6 right after I push 5 and then print, it works. Thus, I suppose the problem occurs when there is only one element in the stack.

Any ideas?

Thank you in advance!

.fmt:
    .asciz "%d\n"
.text

.globl _start

_start:
    push $5

    pop %rdx
    mov %rdx, %rsi
    push %rdx
    mov $.fmt, %rdi
    call printf
    xor %rax, %rax

    push $6

    pop %rdx
    pop %rcx
    add %rdx, %rcx
    push %rcx

    mov $60, %rax
    pop %rdi
    syscall


问:
Set line height in the
 tag - JSX element
I know the standard HTML for how to set line-height
 in the
 tag, but in the react JSX elements, I am not sure how to set it.

Below is the code I've tried, but it doesn't increase the height. I want actual results that can increase the height of the element.

```<code><>
<br style={{lineHeight: 60}} />
</>
</code>```

Hope someone can guide me on how to solve it. Thank you.

Title: Set line height in the <br> tag - JSX element

Body:
I know the standard HTML for how to set line-height
 in the
 tag, but in the react JSX elements, I am not sure how to set it.

Below is the code I've tried, but it doesn't increase the height. I want actual results that can increase the height of the element.

<>

</>

Hope someone can guide me on how to solve it. Thank you.


问:
ERROR: cannot update table "book_max" because it does not have a replica identity and publishes updates
I am trying to perform an update on a table using temp table.

Error updating database.  Cause: org.postgresql.util.PSQLException: ERROR: cannot update table "book_max" because it does not have a replica identity and publishes updates
Hint: To enable updating the table, set REPLICA IDENTITY using ALTER TABLE.

However, I do have a primary key on my temp table.
Below is my query :

```<code>CREATE TEMP TABLE IF NOT EXISTS bookTemp
                (
                bookId                varchar(50),
                authorId              varchar(50),
                subject             varchar(50),
                index                integer,
                index_id                integer,
                buyer            varchar(50),
                buyerId        varchar(50)

                PRIMARY KEY (bookId, authorId, subject, index, buyer)
                )

  INSERT INTO bookTemp(,,,,,,,)

  update book
  set bookId = b.bookId,
  authorId = b.authorId,
  subject = b.subject,
  index = b.index,
  index_id = b.index_id,
  buyer = b.buyer,
  buyerId = b.buyerId
  from bookTemp b
  where ....;
</code>```

I am not sure why it is giving me this error despite the primary key.

Body:
I am trying to perform an update on a table using temp table.

Error updating database.  Cause: org.postgresql.util.PSQLException: ERROR: cannot update table "book_max" because it does not have a replica identity and publishes updates
Hint: To enable updating the table, set REPLICA IDENTITY using ALTER TABLE.

However, I do have a primary key on my temp table.
Below is my query :

CREATE TEMP TABLE IF NOT EXISTS bookTemp
                (
                bookId                varchar(50),
                authorId              varchar(50),
                subject             varchar(50),
                index                integer,
                index_id                integer,
                buyer            varchar(50),
                buyerId        varchar(50)

                PRIMARY KEY (bookId, authorId, subject, index, buyer)
                )

  INSERT INTO bookTemp(,,,,,,,)

  update book
  set bookId = b.bookId,
  authorId = b.authorId,
  subject = b.subject,
  index = b.index,
  index_id = b.index_id,
  buyer = b.buyer,
  buyerId = b.buyerId
  from bookTemp b
  where ....;

I am not sure why it is giving me this error despite the primary key.


问:
webp generator via .htaccess
I am working with WordPress and I would like to have support for webp, but without installing an additional plugin. I thought it could be solved with a few .htaccess rules and a PHP script, but I don't have enough experience to create such a rule. Because different plugins and different themes may have different files, I thought that the wp-content/uploads/ directory would be a good place for webp files: wp-content/uploads/webp/.

I want the rule to detect at the start whether the request has webp support:
RewriteCond %{HTTP_ACCEPT} image/webp

The next condition that must be met is that the request must only be for files with the jpg, png extension, excluding webp.

If a file with the .webp suffix is found in the wp-content/uploads/webp/ directory -> return the webp file.

If the file does not exist, it should go to the webp.php file - there I have a script that generates the appropriate webp file on the fly and saves it in the appropriate place.

For example:

Request to https://example.com/wp-content/uploads/test.webp will return the webp file - the rule was not fulfilled because the file extension is webp. If the file does not exist, WordPress will return 404.

Request to https://example.com/wp-content/uploads/test.jpg - the rule checks whether a file exists in the wp-content/uploads/webp/wp-content/uploads/test.jpg.webp directory -> if it exists, it will return the webp file, otherwise the webp.php script will run.

Example code, but it was my trying:

```<code><IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP_ACCEPT} image/webp
    RewriteCond app/uploads/webp/$1.webp -f
    RewriteRule (.*).(png|jpg)$ app/uploads/webp/$1.$2.webp [NC,L]
    RewriteRule (.*).(png|jpg)$ webp.php [NC,L]
</IfModule>
</code>```

Title: webp generator via .htaccess

Body:
I am working with WordPress and I would like to have support for webp, but without installing an additional plugin. I thought it could be solved with a few .htaccess rules and a PHP script, but I don't have enough experience to create such a rule. Because different plugins and different themes may have different files, I thought that the wp-content/uploads/ directory would be a good place for webp files: wp-content/uploads/webp/.

I want the rule to detect at the start whether the request has webp support:
RewriteCond %{HTTP_ACCEPT} image/webp

The next condition that must be met is that the request must only be for files with the jpg, png extension, excluding webp.

If a file with the .webp suffix is found in the wp-content/uploads/webp/ directory -> return the webp file.

If the file does not exist, it should go to the webp.php file - there I have a script that generates the appropriate webp file on the fly and saves it in the appropriate place.

For example:

Request to https://example.com/wp-content/uploads/test.webp will return the webp file - the rule was not fulfilled because the file extension is webp. If the file does not exist, WordPress will return 404.

Request to https://example.com/wp-content/uploads/test.jpg - the rule checks whether a file exists in the wp-content/uploads/webp/wp-content/uploads/test.jpg.webp directory -> if it exists, it will return the webp file, otherwise the webp.php script will run.

Example code, but it was my trying:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP_ACCEPT} image/webp
    RewriteCond app/uploads/webp/$1.webp -f
    RewriteRule (.*).(png|jpg)$ app/uploads/webp/$1.$2.webp [NC,L]
    RewriteRule (.*).(png|jpg)$ webp.php [NC,L]
</IfModule>


问:
How do you effectively solve node module issues when google isn't providing many answers?
I received this issue and google isn't providing many case-specific examples to work from. Can anyone decode this? I am not really sure what the main issue is.

I have followed the file path of the first issue to cjs.js file but there isn't much there

```<code>"use strict";

const loader = require("./index");

module.exports = loader.default;
</code>```

And the file path of the second issue leads me to this

```<code>var correctedContent = params.removeCR && (os.EOL !== '\\r') ?
sourceContent.replace(ORPHAN_CR_REGEX, ' $1') :
sourceContent;
</code>```

Github link for context.

Body:
I received this issue and google isn't providing many case-specific examples to work from. Can anyone decode this? I am not really sure what the main issue is.

I have followed the file path of the first issue to cjs.js file but there isn't much there

"use strict";

const loader = require("./index");

module.exports = loader.default;

And the file path of the second issue leads me to this

var correctedContent = params.removeCR && (os.EOL !== '\\r') ?
sourceContent.replace(ORPHAN_CR_REGEX, ' $1') :
sourceContent;

Github link for context.


问:
How to plot learning curve for my gan in python
I want to plot the learning curve (loss & accuracy plot) for my gan? I try different solution but still can't plot the learning curve for my gan. I tried to use fit and history function but I get error and can't plot loss & accuracy curve. If anyone can help?

I run my code in google colab. Since I only train the discriminator I tried to use fit & history function in the definition of discriminator & gan but still get error

```<code>from tensorflow.keras.layers import Dense, Conv2DTranspose, LeakyReLU, Reshape, BatchNormalization, Activation, Conv2D
from tensorflow.keras.models import Model, Sequential
import matplotlib.pyplot as plt
import numpy as np
from tensorflow.keras.layers import Conv2D, Flatten, Dropout
from tensorflow.keras import optimizers
import tensorflow as tf

def image_generator():

    generator = Sequential()

    generator.add(Dense(256*4*4, input_shape = (100,)))
    #generator.add(BatchNormalization())
    generator.add(LeakyReLU())
    generator.add(Reshape((4,4,256)))

    generator.add(Conv2DTranspose(128,kernel_size=3, strides=2, padding = "same"))
    #generator.add(BatchNormalization())
    generator.add(LeakyReLU(alpha=0.2))

    generator.add(Conv2DTranspose(128,kernel_size=3, strides=2, padding = "same"))
    #generator.add(BatchNormalization())
    generator.add(LeakyReLU(alpha=0.2))

    generator.add(Conv2DTranspose(128,kernel_size=3, strides=2, padding = "same"))
    #generator.add(BatchNormalization())
    generator.add(LeakyReLU(alpha=0.2))

    generator.add(Conv2D(3,kernel_size=3, padding = "same", activation='tanh'))

    return(generator)

model_generator = image_generator()

model_generator.summary()

# Define input data
def generate_data_entry(n_samples):
  X = np.random.randn(100 * n_samples)
  X = X.reshape(n_samples, 100)
  return X

def create_data_fake(model_generator, n_samples):
  input = generate_data_entry(n_samples)
  X = model_generator.predict(input)
  y = np.zeros((n_samples, 1))
  return X,y

number_samples = 4
X,_ = create_data_fake(model_generator, number_samples)

# Visualize results
for i in range(number_samples):
    plt.subplot(2, 2, 1 + i)
    plt.axis('off')
    plt.imshow(X[i])

def images_discriminator():

    discriminator = Sequential()
    discriminator.add(Conv2D(64, kernel_size=3, padding = "same", input_shape = (32,32,3)))
    discriminator.add(LeakyReLU(alpha=0.2))
    #discriminator.add(Dropout(0.2))

    discriminator.add(Conv2D(128, kernel_size=3,strides=(2,2), padding = "same"))
    discriminator.add(LeakyReLU(alpha=0.2))
    #discriminator.add(Dropout(0.2))

    discriminator.add(Conv2D(128, kernel_size=3,strides=(2,2), padding = "same"))
    discriminator.add(LeakyReLU(alpha=0.2))
    #discriminator.add(Dropout(0.2))

    discriminator.add(Conv2D(256, kernel_size=3, strides=(2,2), padding = "same"))
    discriminator.add(LeakyReLU(alpha=0.2))
    #discriminator.add(Dropout(0.2))

    discriminator.add(Flatten())
    discriminator.add(Dropout(0.4))
    discriminator.add(Dense(1, activation='sigmoid'))

    opt = tf.keras.optimizers.Adam(learning_rate=0.0002 ,beta_1=0.5)
    discriminator.compile(loss='binary_crossentropy', optimizer= opt , metrics = ['accuracy'])

    return(discriminator)

model_discriminator = images_discriminator()
model_discriminator.summary()

from tensorflow.keras.datasets import cifar10
import random
import tensorflow as tf
import numpy as np
from tensorflow.keras import backend
import pandas as pd
import matplotlib.pyplot as plt
import keras
%matplotlib inline

(Xtrain, Ytrain), (testx, testy) = cifar10.load_data()

def load_images():
    (Xtrain, Ytrain), (testx, testy) = cifar10.load_data()
    # we stayed with the dogs
    indice = np.where(Ytrain == 0)
    indice = indice[0]
    Xtrain = Xtrain[indice, :,:,:]

    # Normalize the data
    X = Xtrain.astype('float32')
    X = (X - 127.5) / 127.5

    return X

print(load_images().shape)

def load_data_reales(dataset, n_samples):
  ix = np.random.randint(0, dataset.shape[0], n_samples)
  X = dataset[ix]
  y = np.ones((n_samples, 1))
  return X,y

def load_data_fake(n_samples):
  X = np.random.rand(32 * 32 * 3 * n_samples)
  X = -1 + X * 2
  X = X.reshape((n_samples, 32,32,3))
  y = np.zeros((n_samples, 1))
  return X,y

def train_discriminator(model, dataset, n_iterations=20, batch = 128):
  medium_batch = int(batch/2)

  for i in range(n_iterations):
    X_real, y_real = load_data_reales(dataset, medium_batch)
    los_real, acc_real = model.train_on_batch(X_real, y_real)

    X_fake, y_fake = load_data_fake(medium_batch)
    los_fake, acc_fake = model.train_on_batch(X_fake, y_fake)

    print(str(i+1) + ' Real:' + str(acc_real*100) + ', Fake:' + str(acc_fake*100))

dataset = load_images()
train_discriminator(model_discriminator, dataset)

def my_loss_function(x_real,x_fake):

  la=tf.keras.losses.BinaryCrossentropy()
  my_loss_function = la(x_real, x_fake)

  return my_loss_function

def create_gan(discriminator, generator):
    discriminator.trainable=False
    gan = Sequential()
    gan.add(generator)
    gan.add(discriminator)

    opt = tf.keras.optimizers.Adam(learning_rate=0.0002,beta_1=0.5)

    return gan

gan = create_gan(model_discriminator,model_generator)
gan.summary()

def show_images_generated(data_fake, epoch):

  now = datetime.now()
  now = now.strftime("%Y%m%d_%H%M%S")

  # we make the data go from 0 to 1
  data_fake = (data_fake + 1) / 2.0

  for i in range(10):
    plt.imshow(data_fake[i])
    plt.axis('off')
    name = str(epoch) + '_generated_image_' + str(i) + '.png'
    plt.savefig(name, bbox_inches='tight')
    plt.close()

def evaluate_and_save(model_generator, epoch, medium_dataset):

  # We save the model
  now = datetime.now()
  now = now.strftime("%Y%m%d_%H%M%S")
  name = str(epoch) + '_' + str(now)+"_model_generator_" + '.h5'
  model_generator.save(name)

  # We generate new data
  X_real,Y_real = load_data_reales(dataset, medium_dataset)
  X_fake, Y_fake =  create_data_fake(model_generator,medium_dataset)

  # We evaluate the model
  _, acc_real = model_discriminator.evaluate(X_real, Y_real)
  _, acc_fake = model_discriminator.evaluate(X_fake, Y_fake)

  print('Acc Real:' + str(acc_real*100) + '% Acc Fake:' + str(acc_fake*100)+'%')

def training(data, model_generator, model_discriminator, epochs, n_batch, beginning = 0):
  dimension_batch = int(data.shape[0]/n_batch)
  medium_dataset = int(n_batch/2)

  # We iterate over the epochs
  for epoch in range(beginning, beginning + epochs):
    # We iterate over all batches
    for batch in range(n_batch):

      # We load all the real data
      X_real,Y_real = load_data_reales(dataset, medium_dataset)

      # We train the discriminator withEnrenamos discriminator with data reales
      cost_discriminator_real, _ = model_discriminator.train_on_batch(X_real, Y_real)
      X_fake, Y_fake =  create_data_fake(model_generator,medium_dataset)

      cost_discriminator_fake, _ = model_discriminator.train_on_batch(X_fake, Y_fake)

      # We generate input images for the GAN
      X_gan = generate_data_entry(medium_dataset)
      Y_gan = np.ones((medium_dataset, 1))

      # We train the GAN with fake data
      cost_gan = gan.train_on_batch(X_gan, Y_gan)

    # Every 10 epochs we show the results and cost
    if (epoch+1) % 10 == 0:
      evaluate_and_save(model_generator,epoch = epoch, medium_dataset= medium_dataset)
      show_images_generated(X_fake, epoch = epoch)

training(dataset, model_generator, model_discriminator, epochs = 10, n_batch=128, beginning = 0)

X_fake, _ = create_data_fake(n_samples=49, model_generator=model_generator)
X_fake = (X_fake+1)/2

for i in range(49):
  plt.subplot(7,7,i+1)
  plt.axis('off')
  plt.imshow(X_fake[i])

# We generate new data
X_real1,Y_real1 = load_data_reales(dataset, int(15))
X_fake1, Y_fake1 =  create_data_fake(model_generator,int(15))
# We evaluate the model
_, acc_real = model_discriminator.evaluate(X_real1, Y_real1)
_, acc_fake = model_discriminator.evaluate(X_fake1, Y_fake1)
print('Acc Real:' + str(acc_real*100) + '% Acc Fake:' + str(acc_fake*100)+'%')
</code>```

Body:
I want to plot the learning curve (loss & accuracy plot) for my gan? I try different solution but still can't plot the learning curve for my gan. I tried to use fit and history function but I get error and can't plot loss & accuracy curve. If anyone can help?

I run my code in google colab. Since I only train the discriminator I tried to use fit & history function in the definition of discriminator & gan but still get error

from tensorflow.keras.layers import Dense, Conv2DTranspose, LeakyReLU, Reshape, BatchNormalization, Activation, Conv2D
from tensorflow.keras.models import Model, Sequential
import matplotlib.pyplot as plt
import numpy as np
from tensorflow.keras.layers import Conv2D, Flatten, Dropout
from tensorflow.keras import optimizers
import tensorflow as tf

def image_generator():

    generator = Sequential()

    generator.add(Dense(256*4*4, input_shape = (100,)))
    #generator.add(BatchNormalization())
    generator.add(LeakyReLU())
    generator.add(Reshape((4,4,256)))

    generator.add(Conv2DTranspose(128,kernel_size=3, strides=2, padding = "same"))
    #generator.add(BatchNormalization())
    generator.add(LeakyReLU(alpha=0.2))

    generator.add(Conv2DTranspose(128,kernel_size=3, strides=2, padding = "same"))
    #generator.add(BatchNormalization())
    generator.add(LeakyReLU(alpha=0.2))

    generator.add(Conv2DTranspose(128,kernel_size=3, strides=2, padding = "same"))
    #generator.add(BatchNormalization())
    generator.add(LeakyReLU(alpha=0.2))

    generator.add(Conv2D(3,kernel_size=3, padding = "same", activation='tanh'))

    return(generator)

model_generator = image_generator()

model_generator.summary()

# Define input data
def generate_data_entry(n_samples):
  X = np.random.randn(100 * n_samples)
  X = X.reshape(n_samples, 100)
  return X

def create_data_fake(model_generator, n_samples):
  input = generate_data_entry(n_samples)
  X = model_generator.predict(input)
  y = np.zeros((n_samples, 1))
  return X,y

number_samples = 4
X,_ = create_data_fake(model_generator, number_samples)

# Visualize results
for i in range(number_samples):
    plt.subplot(2, 2, 1 + i)
    plt.axis('off')
    plt.imshow(X[i])

def images_discriminator():

    discriminator = Sequential()
    discriminator.add(Conv2D(64, kernel_size=3, padding = "same", input_shape = (32,32,3)))
    discriminator.add(LeakyReLU(alpha=0.2))
    #discriminator.add(Dropout(0.2))

    discriminator.add(Conv2D(128, kernel_size=3,strides=(2,2), padding = "same"))
    discriminator.add(LeakyReLU(alpha=0.2))
    #discriminator.add(Dropout(0.2))

    discriminator.add(Conv2D(128, kernel_size=3,strides=(2,2), padding = "same"))
    discriminator.add(LeakyReLU(alpha=0.2))
    #discriminator.add(Dropout(0.2))

    discriminator.add(Conv2D(256, kernel_size=3, strides=(2,2), padding = "same"))
    discriminator.add(LeakyReLU(alpha=0.2))
    #discriminator.add(Dropout(0.2))

    discriminator.add(Flatten())
    discriminator.add(Dropout(0.4))
    discriminator.add(Dense(1, activation='sigmoid'))

    opt = tf.keras.optimizers.Adam(learning_rate=0.0002 ,beta_1=0.5)
    discriminator.compile(loss='binary_crossentropy', optimizer= opt , metrics = ['accuracy'])

    return(discriminator)

model_discriminator = images_discriminator()
model_discriminator.summary()

from tensorflow.keras.datasets import cifar10
import random
import tensorflow as tf
import numpy as np
from tensorflow.keras import backend
import pandas as pd
import matplotlib.pyplot as plt
import keras
%matplotlib inline

(Xtrain, Ytrain), (testx, testy) = cifar10.load_data()

def load_images():
    (Xtrain, Ytrain), (testx, testy) = cifar10.load_data()
    # we stayed with the dogs
    indice = np.where(Ytrain == 0)
    indice = indice[0]
    Xtrain = Xtrain[indice, :,:,:]

    # Normalize the data
    X = Xtrain.astype('float32')
    X = (X - 127.5) / 127.5

    return X

print(load_images().shape)

def load_data_reales(dataset, n_samples):
  ix = np.random.randint(0, dataset.shape[0], n_samples)
  X = dataset[ix]
  y = np.ones((n_samples, 1))
  return X,y

def load_data_fake(n_samples):
  X = np.random.rand(32 * 32 * 3 * n_samples)
  X = -1 + X * 2
  X = X.reshape((n_samples, 32,32,3))
  y = np.zeros((n_samples, 1))
  return X,y

def train_discriminator(model, dataset, n_iterations=20, batch = 128):
  medium_batch = int(batch/2)

  for i in range(n_iterations):
    X_real, y_real = load_data_reales(dataset, medium_batch)
    los_real, acc_real = model.train_on_batch(X_real, y_real)

    X_fake, y_fake = load_data_fake(medium_batch)
    los_fake, acc_fake = model.train_on_batch(X_fake, y_fake)

    print(str(i+1) + ' Real:' + str(acc_real*100) + ', Fake:' + str(acc_fake*100))

dataset = load_images()
train_discriminator(model_discriminator, dataset)

def my_loss_function(x_real,x_fake):

  la=tf.keras.losses.BinaryCrossentropy()
  my_loss_function = la(x_real, x_fake)

  return my_loss_function

def create_gan(discriminator, generator):
    discriminator.trainable=False
    gan = Sequential()
    gan.add(generator)
    gan.add(discriminator)

    opt = tf.keras.optimizers.Adam(learning_rate=0.0002,beta_1=0.5)

    return gan

gan = create_gan(model_discriminator,model_generator)
gan.summary()

def show_images_generated(data_fake, epoch):

  now = datetime.now()
  now = now.strftime("%Y%m%d_%H%M%S")

  # we make the data go from 0 to 1
  data_fake = (data_fake + 1) / 2.0

  for i in range(10):
    plt.imshow(data_fake[i])
    plt.axis('off')
    name = str(epoch) + '_generated_image_' + str(i) + '.png'
    plt.savefig(name, bbox_inches='tight')
    plt.close()

def evaluate_and_save(model_generator, epoch, medium_dataset):

  # We save the model
  now = datetime.now()
  now = now.strftime("%Y%m%d_%H%M%S")
  name = str(epoch) + '_' + str(now)+"_model_generator_" + '.h5'
  model_generator.save(name)

  # We generate new data
  X_real,Y_real = load_data_reales(dataset, medium_dataset)
  X_fake, Y_fake =  create_data_fake(model_generator,medium_dataset)

  # We evaluate the model
  _, acc_real = model_discriminator.evaluate(X_real, Y_real)
  _, acc_fake = model_discriminator.evaluate(X_fake, Y_fake)

  print('Acc Real:' + str(acc_real*100) + '% Acc Fake:' + str(acc_fake*100)+'%')

def training(data, model_generator, model_discriminator, epochs, n_batch, beginning = 0):
  dimension_batch = int(data.shape[0]/n_batch)
  medium_dataset = int(n_batch/2)

  # We iterate over the epochs
  for epoch in range(beginning, beginning + epochs):
    # We iterate over all batches
    for batch in range(n_batch):

      # We load all the real data
      X_real,Y_real = load_data_reales(dataset, medium_dataset)

      # We train the discriminator withEnrenamos discriminator with data reales
      cost_discriminator_real, _ = model_discriminator.train_on_batch(X_real, Y_real)
      X_fake, Y_fake =  create_data_fake(model_generator,medium_dataset)

      cost_discriminator_fake, _ = model_discriminator.train_on_batch(X_fake, Y_fake)

      # We generate input images for the GAN
      X_gan = generate_data_entry(medium_dataset)
      Y_gan = np.ones((medium_dataset, 1))

      # We train the GAN with fake data
      cost_gan = gan.train_on_batch(X_gan, Y_gan)

    # Every 10 epochs we show the results and cost
    if (epoch+1) % 10 == 0:
      evaluate_and_save(model_generator,epoch = epoch, medium_dataset= medium_dataset)
      show_images_generated(X_fake, epoch = epoch)

training(dataset, model_generator, model_discriminator, epochs = 10, n_batch=128, beginning = 0)

X_fake, _ = create_data_fake(n_samples=49, model_generator=model_generator)
X_fake = (X_fake+1)/2

for i in range(49):
  plt.subplot(7,7,i+1)
  plt.axis('off')
  plt.imshow(X_fake[i])

# We generate new data
X_real1,Y_real1 = load_data_reales(dataset, int(15))
X_fake1, Y_fake1 =  create_data_fake(model_generator,int(15))
# We evaluate the model
_, acc_real = model_discriminator.evaluate(X_real1, Y_real1)
_, acc_fake = model_discriminator.evaluate(X_fake1, Y_fake1)
print('Acc Real:' + str(acc_real*100) + '% Acc Fake:' + str(acc_fake*100)+'%')


问:
How can i replace Add to cart with vendors phone number dokan plugin in wordpress
I want to get rid of Add to cart button entirely and replace it with the “contact seller” buttons that shows the seller info directly to the buyer. instead of this?</p>


问:
React NavLink activeClassName not Working
I create basic a component and use react-router-dom for routing and use activeClassName property but it's not working

anyone has solution for it please help me

here is the working codesandlink: https://codesandbox.io/s/happy-payne-xjcjx8?file=/src/App.js:0-565

here is the code

```<code>import "./styles.css";
import { NavLink, Route, Routes } from "react-router-dom";
import { About } from "./About";
import { Contact } from "./Contact";

export default function App() {
  return (
    <div className="App">
      <NavLink to="/" exact activeClassName="active">
        About
      </NavLink>
      <NavLink to="/contact" exact activeClassName="active">
        Contact
      </NavLink>

      <Routes>
        <Route path="/" element={<About />}></Route>
        <Route path="contact" element={<Contact />}></Route>
      </Routes>
    </div>
  );
}

</code>```

Body:
I create basic a component and use react-router-dom for routing and use activeClassName property but it's not working

anyone has solution for it please help me

here is the working codesandlink: https://codesandbox.io/s/happy-payne-xjcjx8?file=/src/App.js:0-565

here is the code

import "./styles.css";
import { NavLink, Route, Routes } from "react-router-dom";
import { About } from "./About";
import { Contact } from "./Contact";

export default function App() {
  return (

      <NavLink to="/" exact activeClassName="active">
        About
      </NavLink>
      <NavLink to="/contact" exact activeClassName="active">
        Contact
      </NavLink>

      <Routes>
        <Route path="/" element={<About />}></Route>
        <Route path="contact" element={<Contact />}></Route>
      </Routes>

  );
}


问:
Python script is not properly filtering a JSON file
The script has to:

1. Filter the json file (if there are multiple json blocks with the same "Plugin ID" and "Host" then filter it so there is only one)

2. Translate blocks to Slovenian language using SLO-ID.json (The script collects the remaining blocks's "Plugin ID's" and checks if there are any blocks in the "SLO-byID.json" file with these "Plugin IDs". For every block that has its "PluginID" in the "SLO-ID", it takes this block from "SLO-ID" and replaces the block in the original json file.)

```<code>import json

input_file_name = "before.json"                         #Enter file name
output_file_name = "after.json"                 #Enter result name
language = "SLO-byID.json"                      #Language to translate to (in this case Slovenian)

new = []
new_translated = []

with open(input_file_name) as f:
    data = json.load(f)
with open(language) as l:
    translate= json.load(l)

for section in range(0, len(data)):
    found = False
    sec = data[section]
    for compare in new:
        if (sec["Plugin ID"] == compare["Plugin ID"] and sec["Host"] == compare["Host"]):
            print(sec["Host"])
            print(compare["Host"])
            found = True
            break
    if found == False:
        new.append(sec)
        translate_block = sec
        for translate_section in translate:
            if (translate_section["Plugin ID"] == sec["Plugin ID"]):
                translate_block = translate_section
                translate_block["Host"] = sec["Host"]
                #translate_block["Protocol"] = sec["Protocol"]
                #translate_block["Port"] = sec["Port"]
                break
        new_translated.append(translate_block)
with open(output_file_name, "w") as r:
    json.dump(new_translated, r, indent=2, ensure_ascii=False)
</code>```

Example of file not working: (In after they both have the same "host" for some reason)

Before:

```<code>[
  {
    "Plugin ID": 51972,
    "Risk": "Medium",
    "Host": "subdomain-1.domain.com",
    "Protocol": "tcp",
    "Port": 443,
    "Name": "CGI Generic XSS (Parameters Names)",
    "Description": "The remote web server hosts CGI scripts that fail to adequately\nsanitize parameters name of malicious JavaScript.  By leveraging this\nissue, an attacker may be able to cause arbitrary HTML and script code\nto be executed in a user's browser within the security context of the\naffected site.",
    "Solution": "Contact the vendor for a patch or upgrade."
  },
  {
    "Plugin ID": 51972,
    "Risk": "Medium",
    "Host": "subdomain-2.domain.com",
    "Protocol": "tcp",
    "Port": 443,
    "Name": "CGI Generic XSS (Parameters Names)",
    "Description": "The remote web server hosts CGI scripts that fail to adequately\nsanitize parameters name of malicious JavaScript.  By leveraging this\nissue, an attacker may be able to cause arbitrary HTML and script code\nto be executed in a user's browser within the security context of the\naffected site.",
    "Solution": "Contact the vendor for a patch or upgrade."
  }
]
</code>```

After:

```<code>[
  {
    "Plugin ID": 51972,
    "Risk": "Srednja ranljivost",
    "Host": "subdomain-2.domain.com",
    "Protocol": "tcp",
    "Port": 443,
    "Name": "Stran omogoči napadalcu, da sproži nevaren HTML in javascript",
    "Description": "Stran je ranljiva na XSS napad. To pomeni, da lahko napadalec sproži nevarno HTML in javascript kodo v brskalniku žrtve. To lahko privede do kraje zasebnih podatkov. Več o XSS na: https://www.synopsys.com/glossary/what-is-cross-site-scripting.html",
    "Solution": "Odpravljanje XSS ranljivosti ni enostavno. Če uporabljate zunanji program ga posodobite. V primeru, da to ni možno ali pa da ste kodo napisali sami, pa morate dodati kodo, ki sanitira vnos uporabnika."
  },
  {
    "Plugin ID": 51972,
    "Risk": "Srednja ranljivost",
    "Host": "subdomain-2.domain.com",
    "Protocol": "tcp",
    "Port": 443,
    "Name": "Stran omogoči napadalcu, da sproži nevaren HTML in javascript",
    "Description": "Stran je ranljiva na XSS napad. To pomeni, da lahko napadalec sproži nevarno HTML in javascript kodo v brskalniku žrtve. To lahko privede do kraje zasebnih podatkov. Več o XSS na: https://www.synopsys.com/glossary/what-is-cross-site-scripting.html",
    "Solution": "Odpravljanje XSS ranljivosti ni enostavno. Če uporabljate zunanji program ga posodobite. V primeru, da to ni možno ali pa da ste kodo napisali sami, pa morate dodati kodo, ki sanitira vnos uporabnika."
  }
]
</code>```

What "after" file should look like: (host difference)

```<code>[
  {
    "Plugin ID": 51972,
    "Risk": "Srednja ranljivost",
    "Host": "subdomain-1.domain.com",
    "Protocol": "tcp",
    "Port": 443,
    "Name": "Stran omogoči napadalcu, da sproži nevaren HTML in javascript",
    "Description": "Stran je ranljiva na XSS napad. To pomeni, da lahko napadalec sproži nevarno HTML in javascript kodo v brskalniku žrtve. To lahko privede do kraje zasebnih podatkov. Več o XSS na: https://www.synopsys.com/glossary/what-is-cross-site-scripting.html",
    "Solution": "Odpravljanje XSS ranljivosti ni enostavno. Če uporabljate zunanji program ga posodobite. V primeru, da to ni možno ali pa da ste kodo napisali sami, pa morate dodati kodo, ki sanitira vnos uporabnika."
  },
  {
    "Plugin ID": 51972,
    "Risk": "Srednja ranljivost",
    "Host": "subdomain-2.domain.com",
    "Protocol": "tcp",
    "Port": 443,
    "Name": "Stran omogoči napadalcu, da sproži nevaren HTML in javascript",
    "Description": "Stran je ranljiva na XSS napad. To pomeni, da lahko napadalec sproži nevarno HTML in javascript kodo v brskalniku žrtve. To lahko privede do kraje zasebnih podatkov. Več o XSS na: https://www.synopsys.com/glossary/what-is-cross-site-scripting.html",
    "Solution": "Odpravljanje XSS ranljivosti ni enostavno. Če uporabljate zunanji program ga posodobite. V primeru, da to ni možno ali pa da ste kodo napisali sami, pa morate dodati kodo, ki sanitira vnos uporabnika."
  }
]
</code>```

Body:
The script has to:

1. Filter the json file (if there are multiple json blocks with the same "Plugin ID" and "Host" then filter it so there is only one)

2. Translate blocks to Slovenian language using SLO-ID.json (The script collects the remaining blocks's "Plugin ID's" and checks if there are any blocks in the "SLO-byID.json" file with these "Plugin IDs". For every block that has its "PluginID" in the "SLO-ID", it takes this block from "SLO-ID" and replaces the block in the original json file.)

import json

input_file_name = "before.json"                         #Enter file name
output_file_name = "after.json"                 #Enter result name
language = "SLO-byID.json"                      #Language to translate to (in this case Slovenian)

new = []
new_translated = []

with open(input_file_name) as f:
    data = json.load(f)
with open(language) as l:
    translate= json.load(l)

for section in range(0, len(data)):
    found = False
    sec = data[section]
    for compare in new:
        if (sec["Plugin ID"] == compare["Plugin ID"] and sec["Host"] == compare["Host"]):
            print(sec["Host"])
            print(compare["Host"])
            found = True
            break
    if found == False:
        new.append(sec)
        translate_block = sec
        for translate_section in translate:
            if (translate_section["Plugin ID"] == sec["Plugin ID"]):
                translate_block = translate_section
                translate_block["Host"] = sec["Host"]
                #translate_block["Protocol"] = sec["Protocol"]
                #translate_block["Port"] = sec["Port"]
                break
        new_translated.append(translate_block)
with open(output_file_name, "w") as r:
    json.dump(new_translated, r, indent=2, ensure_ascii=False)

Example of file not working: (In after they both have the same "host" for some reason)

Before:

[
  {
    "Plugin ID": 51972,
    "Risk": "Medium",
    "Host": "subdomain-1.domain.com",
    "Protocol": "tcp",
    "Port": 443,
    "Name": "CGI Generic XSS (Parameters Names)",
    "Description": "The remote web server hosts CGI scripts that fail to adequately\nsanitize parameters name of malicious JavaScript.  By leveraging this\nissue, an attacker may be able to cause arbitrary HTML and script code\nto be executed in a user's browser within the security context of the\naffected site.",
    "Solution": "Contact the vendor for a patch or upgrade."
  },
  {
    "Plugin ID": 51972,
    "Risk": "Medium",
    "Host": "subdomain-2.domain.com",
    "Protocol": "tcp",
    "Port": 443,
    "Name": "CGI Generic XSS (Parameters Names)",
    "Description": "The remote web server hosts CGI scripts that fail to adequately\nsanitize parameters name of malicious JavaScript.  By leveraging this\nissue, an attacker may be able to cause arbitrary HTML and script code\nto be executed in a user's browser within the security context of the\naffected site.",
    "Solution": "Contact the vendor for a patch or upgrade."
  }
]

After:

[
  {
    "Plugin ID": 51972,
    "Risk": "Srednja ranljivost",
    "Host": "subdomain-2.domain.com",
    "Protocol": "tcp",
    "Port": 443,
    "Name": "Stran omogoči napadalcu, da sproži nevaren HTML in javascript",
    "Description": "Stran je ranljiva na XSS napad. To pomeni, da lahko napadalec sproži nevarno HTML in javascript kodo v brskalniku žrtve. To lahko privede do kraje zasebnih podatkov. Več o XSS na: https://www.synopsys.com/glossary/what-is-cross-site-scripting.html",
    "Solution": "Odpravljanje XSS ranljivosti ni enostavno. Če uporabljate zunanji program ga posodobite. V primeru, da to ni možno ali pa da ste kodo napisali sami, pa morate dodati kodo, ki sanitira vnos uporabnika."
  },
  {
    "Plugin ID": 51972,
    "Risk": "Srednja ranljivost",
    "Host": "subdomain-2.domain.com",
    "Protocol": "tcp",
    "Port": 443,
    "Name": "Stran omogoči napadalcu, da sproži nevaren HTML in javascript",
    "Description": "Stran je ranljiva na XSS napad. To pomeni, da lahko napadalec sproži nevarno HTML in javascript kodo v brskalniku žrtve. To lahko privede do kraje zasebnih podatkov. Več o XSS na: https://www.synopsys.com/glossary/what-is-cross-site-scripting.html",
    "Solution": "Odpravljanje XSS ranljivosti ni enostavno. Če uporabljate zunanji program ga posodobite. V primeru, da to ni možno ali pa da ste kodo napisali sami, pa morate dodati kodo, ki sanitira vnos uporabnika."
  }
]

What "after" file should look like: (host difference)

[
  {
    "Plugin ID": 51972,
    "Risk": "Srednja ranljivost",
    "Host": "subdomain-1.domain.com",
    "Protocol": "tcp",
    "Port": 443,
    "Name": "Stran omogoči napadalcu, da sproži nevaren HTML in javascript",
    "Description": "Stran je ranljiva na XSS napad. To pomeni, da lahko napadalec sproži nevarno HTML in javascript kodo v brskalniku žrtve. To lahko privede do kraje zasebnih podatkov. Več o XSS na: https://www.synopsys.com/glossary/what-is-cross-site-scripting.html",
    "Solution": "Odpravljanje XSS ranljivosti ni enostavno. Če uporabljate zunanji program ga posodobite. V primeru, da to ni možno ali pa da ste kodo napisali sami, pa morate dodati kodo, ki sanitira vnos uporabnika."
  },
  {
    "Plugin ID": 51972,
    "Risk": "Srednja ranljivost",
    "Host": "subdomain-2.domain.com",
    "Protocol": "tcp",
    "Port": 443,
    "Name": "Stran omogoči napadalcu, da sproži nevaren HTML in javascript",
    "Description": "Stran je ranljiva na XSS napad. To pomeni, da lahko napadalec sproži nevarno HTML in javascript kodo v brskalniku žrtve. To lahko privede do kraje zasebnih podatkov. Več o XSS na: https://www.synopsys.com/glossary/what-is-cross-site-scripting.html",
    "Solution": "Odpravljanje XSS ranljivosti ni enostavno. Če uporabljate zunanji program ga posodobite. V primeru, da to ni možno ali pa da ste kodo napisali sami, pa morate dodati kodo, ki sanitira vnos uporabnika."
  }
]


问:
Performance Counter for Memory Mapped Files
When using memory mapped files I'm getting in situations where Windows stalls since new memory is allocated and processed faster than it can be written to disk using memory mappedfiles.

The only solution I see is to throttle my processing while the MiMappedPageWriter and the KeBalanceSetManager are doing their jobs. I would be completely fine if the application is running slower instead of a complete OS freeze.

It already helped to use SetWorkingSetSizeEx using a hard limit, because the MiMappedPageWriter is starting earlier to page-out to disk, but still on some drives the data is allocated faster. For example an SSD with 250MB/s does not manage it, but with 500MB/s it is getting better. But I have to support a wide range of hardware and cannot rely on fast drives.

I found that there once was a performance counter, for example: Memory\Mapped File Bytes Written/sec, that I could use not monitor periodically (see: https://docs.microsoft.com/en-us/windows-server/management/windows-performance-monitor/memory-performance-counter-mapped-file-bytes-written-sec) but it seems that all the links have gone.

I have searched on many places, but couldn't find the performance counters for this.

Is there still a source for this?


问:
ERROR: pq: invalid input syntax for type json
I have an orders table with a column named description which stores additional information such as promotional code and a few other things in a JSON format.

I want to query all the orders which are made using a particular promotional code say WELCOME100 and wrote a query as shown below.

```<code>select o.id
from orders o
where o.description is not null and (o.description::jsonb) ->> 'promotionCode' = 'WELCOME100'
</code>```

This is throwing the below error

ERROR: pq: invalid input syntax for type json

Can someone help me with what went wrong in the above query?

Body:
I have an orders table with a column named description which stores additional information such as promotional code and a few other things in a JSON format.

I want to query all the orders which are made using a particular promotional code say WELCOME100 and wrote a query as shown below.

select o.id
from orders o
where o.description is not null and (o.description::jsonb) ->> 'promotionCode' = 'WELCOME100'

This is throwing the below error

ERROR: pq: invalid input syntax for type json

Can someone help me with what went wrong in the above query?


问:
Using a URL to log a user out of a developer web app and redirect to another URL
I have an app that all works fine for authentication and it uses Oauth2 (Google).

Now, I am struggling with the logout URL for this app. It works, but I am under the impression that it is possible to logout of it and remain logged into my gmail account please? Currently, ALL accounts are logged out of so the two gmail accounts need to go through login each time the app is used and log out is pressed.

I have read that this is possible but this is the URL that I am using to Log out

```<code>https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=http://news.bbc.co.uk
</code>```

I am sure it can be done because I did it in a former role but do not have the code!

Body:
I have an app that all works fine for authentication and it uses Oauth2 (Google).

Now, I am struggling with the logout URL for this app. It works, but I am under the impression that it is possible to logout of it and remain logged into my gmail account please? Currently, ALL accounts are logged out of so the two gmail accounts need to go through login each time the app is used and log out is pressed.

I have read that this is possible but this is the URL that I am using to Log out

https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=http://news.bbc.co.uk

I am sure it can be done because I did it in a former role but do not have the code!