问:
No route to host with Gitea and Drone.io using Traefik
I'm trying to get self hosted Gitea instance and a self hosted drone.io (version 2) instance to work together.

Gitea is running. I added a drone.io OAuth application in Gitea settings with "https://drone.mydomain/login" as url.

When I open drone.io url (https://drone.mydomain) in my browser I get a welcome page. Clicking the "Continue" button I get a message after a few seconds:

Post "https://gitea.mydomain/login/oauth/access_token": dial tcp 192.168.82.146:443: connect: no route to host

Logs in gitea look normal to me:

router: completed GET /login/oauth/authorize?client_id=f999e784-f351-43db-a491-d0a90d8a2c57&redirect_uri=https%3A%2F%2Fdrone.mydomain%2Flogin&response_type=code&state=b80704bb7b4d7c03 for 192.168.82.40:0, 303 See Other in 20.2ms @ auth/oauth.go:361(auth.AuthorizeOAuth)

Logs in dronio container look as expected:

```<code>{
  "level": "error",
  "msg": "oauth: cannot exchange code: gta_cgbk727fe32plbnahnok4u3543ql2xv4q3fvnfgaxwtkknafb5gq: Post \"https://gitea.mydomain/login/oauth/access_token\": dial tcp 192.168.82.146:443: connect: no route to host",
  "time": "2022-12-31T01:39:18+01:00"
}
</code>```

To me it looks like "https://gitea.mydomain/login/oauth/access_token" was resolved via DNS and the IP was inserted for the domain but some header informations are missing so that Traefik does not know to which service to forward the request.

I added dns information (gitea, local DNS) to drone service which did not help.

Here is my docker-compose file:

```<code>

version: '3.3'
services:
  gitea-db:
    # Left out to shorten this file

  gitea:
    image: gitea/gitea:latest
    container_name: gitea
    restart: always
    depends_on:
      gitea-db:
        condition: service_started
      gitea-cache:
        condition: service_healthy
    secrets:
      - mysql_user
      - mysql_user_password
    volumes:
      - /share/Container/gitea/data:/data
    environment:
      - APP_NAME=Gitea
      - USER_UID=1000
      - USER_GID=1000
      - USER=git
      - HTTP_PORT=3000
      - DOMAIN=`${GITEA_URL}`
      - SSH_DOMAIN=`${GITEA_URL}`
      - SSH_PORT=222
      - SSH_LISTEN_PORT=22
      - DB_TYPE=mysql
      - DB_HOST=gitea-db:3306
      - DB_NAME=${MYSQL_DATABASE}
      - DB_USER_FILE=/run/secrets/mysql_user
      - DB_PASSWD_FILE=/run/secrets/mysql_user_password
      - TZ=Europe/Berlin
      - RUN_MODE=prod
      - APP_NAME=My Gitea
      - REQUIRE_SIGNIN_VIEW=true
      - ROOT_URL=`https://${GITEA_URL}`
      - GITEA__cache__ENABLED=true
      - GITEA__cache__ADAPTER=redis
      - GITEA__cache__HOST=redis://gitea-cache:6379/0?pool_size=100&idle_timeout=180s
      - GITEA__cache__ITEM_TTL=24h
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.gitea.entrypoints=web-secure"
      - "traefik.http.routers.gitea.rule=Host(`${GITEA_URL}`)"
      - "traefik.http.routers.gitea.tls=true"
      - "traefik.http.routers.gitea.service=gitea-service"
      - "traefik.http.services.gitea-service.loadbalancer.server.port=3000"
      - "traefik.tcp.routers.gitea-ssh.rule=HostSNI(`*`)"
      - "traefik.tcp.routers.gitea-ssh.entrypoints=ssh"
      - "traefik.tcp.routers.gitea-ssh.service=gitea-ssh-svc"
      - "traefik.tcp.services.gitea-ssh-svc.loadbalancer.server.port=22"
    networks:
      - traefik_proxy
      - default

  gitea-cache:
    # Left out to shorten this file

  droneio:
    image: drone/drone:2
    container_name: droneio
    restart: unless-stopped
    dns: # trying to fix my issue by adding this section
      - 192.168.82.153 # local DNS
      - gitea
    volumes:
      - /etc/localtime:/etc/localtime:ro
      - /etc/timezone:/etc/timezone:ro
      - /share/Container/drone/data:/data
      - /var/run/docker.sock:/var/run/docker.sock
    environment:
      - DRONE_SERVER_HOST=${DRONE_URL}
      - DRONE_SERVER_PROTO=https
      - DRONE_RPC_SECRET=${PRC_SECRET}
      - DRONE_GITEA_SERVER=https://${GITEA_URL}/
      - DRONE_GITEA_CLIENT_ID=${GITEA_CLIENT_ID} # need to change to docker secret
      - DRONE_GITEA_CLIENT_SECRET=${GITEA_CLIENT_SECRET} # need to change to docker secret
      - DRONE_LOGS_PRETTY=true
      - DRONE_LOGS_COLOR=true
      - DRONE_DEBUG=true
      - DRONE_TRACE=true
    labels:
      - traefik.enable=true
      - traefik.http.routers.drone-http.entrypoints=web
      - traefik.http.routers.drone-http.rule=Host(`${DRONE_URL}`)
      - traefik.http.routers.drone.entrypoints=web-secure
      - traefik.http.routers.drone.rule=Host(`${DRONE_URL}`)
      - traefik.http.routers.drone.tls=true
    networks:
      - traefik_proxy
      - default
    depends_on:
      - gitea

  drone-runner:
    image: drone/drone-runner-docker:1
    container_name: drone-runner
    restart: unless-stopped
    volumes:
      - /etc/localtime:/etc/localtime:ro
      - /etc/timezone:/etc/timezone:ro
      - /var/run/docker.sock:/var/run/docker.sock
    environment:
      - DRONE_RPC_PROTO=https
      - DRONE_RPC_HOST=${DRONE_URL}
      - DRONE_RPC_SECRET=${PRC_SECRET}
      - DRONE_RUNNER_CAPACITY=1
      - DRONE_RUNNER_NAME=drone-runner-1
    ports:
      - 3000:3000
    depends_on:
      - droneio
    networks:
      - default

secrets:
  mysql_root_password:
    file: ./secrets/mysql_root_pw.txt
  mysql_user:
    file: ./secrets/mysql_user.txt
  mysql_user_password:
    file: ./secrets/mysql_user_pw.txt

networks:
  traefik_proxy:
    external:
      name: traefik_proxy
  default:
    driver: bridge
</code>```

I'd be grateful if somebody has a hint. Thank you in advance.

Body:
I'm trying to get self hosted Gitea instance and a self hosted drone.io (version 2) instance to work together.

Gitea is running. I added a drone.io OAuth application in Gitea settings with "https://drone.mydomain/login" as url.

When I open drone.io url (https://drone.mydomain) in my browser I get a welcome page. Clicking the "Continue" button I get a message after a few seconds:

Post "https://gitea.mydomain/login/oauth/access_token": dial tcp 192.168.82.146:443: connect: no route to host

Logs in gitea look normal to me:

router: completed GET /login/oauth/authorize?client_id=f999e784-f351-43db-a491-d0a90d8a2c57&redirect_uri=https%3A%2F%2Fdrone.mydomain%2Flogin&response_type=code&state=b80704bb7b4d7c03 for 192.168.82.40:0, 303 See Other in 20.2ms @ auth/oauth.go:361(auth.AuthorizeOAuth)

Logs in dronio container look as expected:

{
  "level": "error",
  "msg": "oauth: cannot exchange code: gta_cgbk727fe32plbnahnok4u3543ql2xv4q3fvnfgaxwtkknafb5gq: Post \"https://gitea.mydomain/login/oauth/access_token\": dial tcp 192.168.82.146:443: connect: no route to host",
  "time": "2022-12-31T01:39:18+01:00"
}

To me it looks like "https://gitea.mydomain/login/oauth/access_token" was resolved via DNS and the IP was inserted for the domain but some header informations are missing so that Traefik does not know to which service to forward the request.

I added dns information (gitea, local DNS) to drone service which did not help.

Here is my docker-compose file:

version: '3.3'
services:
  gitea-db:
    # Left out to shorten this file

  gitea:
    image: gitea/gitea:latest
    container_name: gitea
    restart: always
    depends_on:
      gitea-db:
        condition: service_started
      gitea-cache:
        condition: service_healthy
    secrets:
      - mysql_user
      - mysql_user_password
    volumes:
      - /share/Container/gitea/data:/data
    environment:
      - APP_NAME=Gitea
      - USER_UID=1000
      - USER_GID=1000
      - USER=git
      - HTTP_PORT=3000
      - DOMAIN=`${GITEA_URL}`
      - SSH_DOMAIN=`${GITEA_URL}`
      - SSH_PORT=222
      - SSH_LISTEN_PORT=22
      - DB_TYPE=mysql
      - DB_HOST=gitea-db:3306
      - DB_NAME=${MYSQL_DATABASE}
      - DB_USER_FILE=/run/secrets/mysql_user
      - DB_PASSWD_FILE=/run/secrets/mysql_user_password
      - TZ=Europe/Berlin
      - RUN_MODE=prod
      - APP_NAME=My Gitea
      - REQUIRE_SIGNIN_VIEW=true
      - ROOT_URL=`https://${GITEA_URL}`
      - GITEA__cache__ENABLED=true
      - GITEA__cache__ADAPTER=redis
      - GITEA__cache__HOST=redis://gitea-cache:6379/0?pool_size=100&idle_timeout=180s
      - GITEA__cache__ITEM_TTL=24h
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.gitea.entrypoints=web-secure"
      - "traefik.http.routers.gitea.rule=Host(`${GITEA_URL}`)"
      - "traefik.http.routers.gitea.tls=true"
      - "traefik.http.routers.gitea.service=gitea-service"
      - "traefik.http.services.gitea-service.loadbalancer.server.port=3000"
      - "traefik.tcp.routers.gitea-ssh.rule=HostSNI(`*`)"
      - "traefik.tcp.routers.gitea-ssh.entrypoints=ssh"
      - "traefik.tcp.routers.gitea-ssh.service=gitea-ssh-svc"
      - "traefik.tcp.services.gitea-ssh-svc.loadbalancer.server.port=22"
    networks:
      - traefik_proxy
      - default

  gitea-cache:
    # Left out to shorten this file

  droneio:
    image: drone/drone:2
    container_name: droneio
    restart: unless-stopped
    dns: # trying to fix my issue by adding this section
      - 192.168.82.153 # local DNS
      - gitea
    volumes:
      - /etc/localtime:/etc/localtime:ro
      - /etc/timezone:/etc/timezone:ro
      - /share/Container/drone/data:/data
      - /var/run/docker.sock:/var/run/docker.sock
    environment:
      - DRONE_SERVER_HOST=${DRONE_URL}
      - DRONE_SERVER_PROTO=https
      - DRONE_RPC_SECRET=${PRC_SECRET}
      - DRONE_GITEA_SERVER=https://${GITEA_URL}/
      - DRONE_GITEA_CLIENT_ID=${GITEA_CLIENT_ID} # need to change to docker secret
      - DRONE_GITEA_CLIENT_SECRET=${GITEA_CLIENT_SECRET} # need to change to docker secret
      - DRONE_LOGS_PRETTY=true
      - DRONE_LOGS_COLOR=true
      - DRONE_DEBUG=true
      - DRONE_TRACE=true
    labels:
      - traefik.enable=true
      - traefik.http.routers.drone-http.entrypoints=web
      - traefik.http.routers.drone-http.rule=Host(`${DRONE_URL}`)
      - traefik.http.routers.drone.entrypoints=web-secure
      - traefik.http.routers.drone.rule=Host(`${DRONE_URL}`)
      - traefik.http.routers.drone.tls=true
    networks:
      - traefik_proxy
      - default
    depends_on:
      - gitea

  drone-runner:
    image: drone/drone-runner-docker:1
    container_name: drone-runner
    restart: unless-stopped
    volumes:
      - /etc/localtime:/etc/localtime:ro
      - /etc/timezone:/etc/timezone:ro
      - /var/run/docker.sock:/var/run/docker.sock
    environment:
      - DRONE_RPC_PROTO=https
      - DRONE_RPC_HOST=${DRONE_URL}
      - DRONE_RPC_SECRET=${PRC_SECRET}
      - DRONE_RUNNER_CAPACITY=1
      - DRONE_RUNNER_NAME=drone-runner-1
    ports:
      - 3000:3000
    depends_on:
      - droneio
    networks:
      - default

secrets:
  mysql_root_password:
    file: ./secrets/mysql_root_pw.txt
  mysql_user:
    file: ./secrets/mysql_user.txt
  mysql_user_password:
    file: ./secrets/mysql_user_pw.txt

networks:
  traefik_proxy:
    external:
      name: traefik_proxy
  default:
    driver: bridge

I'd be grateful if somebody has a hint. Thank you in advance.


来源: stackexchange

问:
Python and SQL Server - _pymssql.ProgrammingError: (208, b"Invalid object name X. DB-Lib error message 20018, severity 16 ..)
I want to fetch data from a MSSQL Server (Microsoft SQL Server 2017) via Python (3.8.6) and the pymssql library (2.2.7).

The tables are in the dbo Schema of database A, the default database of the user is master.

By using the following code, I am able to fetch data from most of the tables:

import pymssql

# Connect to the database - dont mind the fake server, pw and other creds, database='A'
conn = pymssql.connect(
  server='localhost',
  user='sa',
  password='1234',
  database='A',
  port=8888
)

# Create a cursor
cursor = conn.cursor()

# Execute a SELECT statement++++
c = cursor.execute("SELECT TOP 10 * FROM dbo.KHKBookings")

results = cursor.fetchall()

# Iterate over the results and print each row
for row in results:
    print(row)

# Close the cursor and connection
cursor.close()
conn.close()
```
<p>While it works for the example table <strong>KHKBookings</strong>, it does not for another one called <strong>icZGBookings</strong>, which is in the same database and also in dbo schema. I get the following error:</p>
<blockquote>
<p>Traceback (most recent call last):   File "src\pymssql_pymssql.pyx",
line 459, in pymssql._pymssql.Cursor.execute   File
"src\pymssql_mssql.pyx", line 1087, in
pymssql._mssql.MSSQLConnection.execute_query   File
"src\pymssql_mssql.pyx", line 1118, in
pymssql._mssql.MSSQLConnection.execute_query   File
"src\pymssql_mssql.pyx", line 1251, in
pymssql._mssql.MSSQLConnection.format_and_run_query   File
"src\pymssql_mssql.pyx", line 1789, in
pymssql._mssql.check_cancel_and_raise   File "src\pymssql_mssql.pyx",
line 1835, in pymssql._mssql.raise_MSSQLDatabaseException
pymssql._mssql.MSSQLDatabaseException: (208, b"Invalid object name
'dbo.icZGBookings'.DB-Lib error message 20018, severity 16:\nGeneral
SQL Server error: Check messages from the SQL Server\n")</p>
<p>During handling of the above exception, another exception occurred:</p>
<p>Traceback (most recent call last):   File "", line 1, in
   File "src\pymssql_pymssql.pyx", line 476, in
pymssql._pymssql.Cursor.execute pymssql._pymssql.ProgrammingError:
(208, b"Invalid object name 'dbo.icZGBookings'.DB-Lib error message
20018, severity 16:\nGeneral SQL Server error: Check messages from the
SQL Server\n")</p>
</blockquote>
<p>So we are not finding the table, I can also make up a table and get the same error.</p>
<p>Adding the Database to the query didnt help either:
<code>SELECT TOP 10 * FROM A.dbo.icZGBookings</code></p>
<p>But why is that so? I cant figure it out, because the table <strong>icZGBookings</strong> exists.
I can see and query it with the same user <strong>sa</strong> in MSSQL Server Management Studio in the database <strong>A</strong> and schema <strong>dbo</strong>.</p>
<p>I even altered the default database for that user from <strong>master</strong> to <strong>A</strong>, but that didnt help either.
We should not need to do that anyway because we specify the database we connect to in the beginning.
The <strong>master</strong> database <strong>dbo</strong> schema is empty anyway and should have not worked for the other tables too.</p>
<p>So, why cant I query it via Python?</p>
<p>I compared the values of the two tables with the following query:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT *
FROM sys.tables AS t
INNER JOIN sys.partitions AS p
ON t.object_id = p.object_id
WHERE t.name in ('KHKBookings', 'icZGBookings')
</code>```

The values are not different besides the object_ids, index_ids, and dates of course.

Any idea?

Thank you in advance!

ContentLicense: CC BY-SA 4.0

Body:
I want to fetch data from a MSSQL Server (Microsoft SQL Server 2017) via Python (3.8.6) and the pymssql library (2.2.7).

The tables are in the dbo Schema of database A, the default database of the user is master.

By using the following code, I am able to fetch data from most of the tables:

import pymssql

# Connect to the database - dont mind the fake server, pw and other creds, database='A'
conn = pymssql.connect(
  server='localhost',
  user='sa',
  password='1234',
  database='A',
  port=8888
)

# Create a cursor
cursor = conn.cursor()

# Execute a SELECT statement++++
c = cursor.execute("SELECT TOP 10 * FROM dbo.KHKBookings")

results = cursor.fetchall()

# Iterate over the results and print each row
for row in results:
    print(row)

# Close the cursor and connection
cursor.close()
conn.close()

While it works for the example table KHKBookings, it does not for another one called icZGBookings, which is in the same database and also in dbo schema. I get the following error:

Traceback (most recent call last):   File "src\pymssql_pymssql.pyx",
line 459, in pymssql._pymssql.Cursor.execute   File
"src\pymssql_mssql.pyx", line 1087, in
pymssql._mssql.MSSQLConnection.execute_query   File
"src\pymssql_mssql.pyx", line 1118, in
pymssql._mssql.MSSQLConnection.execute_query   File
"src\pymssql_mssql.pyx", line 1251, in
pymssql._mssql.MSSQLConnection.format_and_run_query   File
"src\pymssql_mssql.pyx", line 1789, in
pymssql._mssql.check_cancel_and_raise   File "src\pymssql_mssql.pyx",
line 1835, in pymssql._mssql.raise_MSSQLDatabaseException
pymssql._mssql.MSSQLDatabaseException: (208, b"Invalid object name
'dbo.icZGBookings'.DB-Lib error message 20018, severity 16:\nGeneral
SQL Server error: Check messages from the SQL Server\n")

During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File "", line 1, in
   File "src\pymssql_pymssql.pyx", line 476, in
pymssql._pymssql.Cursor.execute pymssql._pymssql.ProgrammingError:
(208, b"Invalid object name 'dbo.icZGBookings'.DB-Lib error message
20018, severity 16:\nGeneral SQL Server error: Check messages from the
SQL Server\n")

So we are not finding the table, I can also make up a table and get the same error.

Adding the Database to the query didnt help either:
SELECT TOP 10 * FROM A.dbo.icZGBookings

But why is that so? I cant figure it out, because the table icZGBookings exists.
I can see and query it with the same user sa in MSSQL Server Management Studio in the database A and schema dbo.

I even altered the default database for that user from master to A, but that didnt help either.
We should not need to do that anyway because we specify the database we connect to in the beginning.
The master database dbo schema is empty anyway and should have not worked for the other tables too.

So, why cant I query it via Python?

I compared the values of the two tables with the following query:

SELECT *
FROM sys.tables AS t
INNER JOIN sys.partitions AS p
ON t.object_id = p.object_id
WHERE t.name in ('KHKBookings', 'icZGBookings')

The values are not different besides the object_ids, index_ids, and dates of course.

Any idea?

Thank you in advance!


问:
Writting messages to shared log file from different MPI processes independently
I have a parallel MPI program in which I would like to collect log messages for debugging to a single log text file. The length, number and timing of messages varies for each process and I cannot use the collective write_shared function. Is there a way to check if a process is currently writing to the shared file and hold the others until that action has been completed to prevent messages from being written over on another? I'm imagining functionality like a mutex pr a lock.</p>


问:
Horizontal UICollectionViewCompositionalLayout with next cell hint
I'm experimenting with UICollectionViewCompositionalLayout and trying to achieve a similar effect to the Apple Music app, especially to the "hint" indicating there are more cells to scroll:

So far, I have managed to make a similar grid, but I can't make the "visual hint" appear among all screen widths.

This is what I tried:

```<code>func createBasicListLayout() -> UICollectionViewLayout {
    let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .fractionalHeight(1.0))
    let item = NSCollectionLayoutItem(layoutSize: itemSize)

    // we will be working with this part
    let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalHeight(1.0), heightDimension: .fractionalHeight(1))
    let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item])
    group.edgeSpacing = .init(leading: .fixed(10), top: nil, trailing: .fixed(10), bottom: nil)

    let section = NSCollectionLayoutSection(group: group)
    section.orthogonalScrollingBehavior = .continuous
    section.interGroupSpacing = 0
    section.contentInsets = .init(top: 0, leading: 20, bottom: 0, trailing: 20)

    let layout = UICollectionViewCompositionalLayout(section: section)
    layout.configuration.scrollDirection = .horizontal

    return layout
}

Which results in:
</code>```

How can I make the layout show a hint on a third cell? Thanks in advance!

Body:
I'm experimenting with UICollectionViewCompositionalLayout and trying to achieve a similar effect to the Apple Music app, especially to the "hint" indicating there are more cells to scroll:

So far, I have managed to make a similar grid, but I can't make the "visual hint" appear among all screen widths.

This is what I tried:

func createBasicListLayout() -> UICollectionViewLayout {
    let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .fractionalHeight(1.0))
    let item = NSCollectionLayoutItem(layoutSize: itemSize)

    // we will be working with this part
    let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalHeight(1.0), heightDimension: .fractionalHeight(1))
    let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item])
    group.edgeSpacing = .init(leading: .fixed(10), top: nil, trailing: .fixed(10), bottom: nil)

    let section = NSCollectionLayoutSection(group: group)
    section.orthogonalScrollingBehavior = .continuous
    section.interGroupSpacing = 0
    section.contentInsets = .init(top: 0, leading: 20, bottom: 0, trailing: 20)

    let layout = UICollectionViewCompositionalLayout(section: section)
    layout.configuration.scrollDirection = .horizontal

    return layout
}

Which results in:

How can I make the layout show a hint on a third cell? Thanks in advance!


问:
blank images when logging in one account through vscode ssh-remote
If I log in one user account through vscode ssh-remote and open any image, it can be loaded but become blank\

However, if I log in another account and open any image at the same time, both the images can be loaded and viewed correctly.\

No special extension, no special ssh configuration。

hope to vdiew images through ssh normally


问:
Image frames from GIF not working properly
I want to try and save all the frames from a GIF but it either doesn't write the image or if I try another method, it gives an error.

I have

public static void encryptionGIF () throws IOException {
    ImageReader GIFReader = (ImageReader)ImageIO.getImageReadersByFormatName("gif").next();
    File input = new File("Test.gif");
    ImageInputStream Stream = ImageIO.createImageInputStream(input);
    GIFReader.setInput(Stream);
    int frames = GIFReader.getNumImages(true);
    for (int i = 0; i < frames; i++) {
        BufferedImage frame = GIFReader.getRawImageType(i).createBufferedImage(GIFReader.getWidth(i), GIFReader.getHeight(i));
        File output = new File ("Test" + i + ".png");
        ImageIO.write(frame, ".png", output);
    }
}
```
<p>I have also tried replacing</p>
<pre class="lang-java prettyprint-override"><code>BufferedImage frame = GIFReader.getRawImageType(i).createBufferedImage(GIFReader.getWidth(i), GIFReader.getHeight(i));
</code>```

with

BufferedImage frame = GIFReader.read(i);
```
<p>and get the error:</p>
<pre class="lang-none prettyprint-override"><code>Exception in thread "main" javax.imageio.IIOException: I/O error reading image!
    at java.desktop/com.sun.imageio.plugins.gif.GIFImageReader.read(GIFImageReader.java:1046)
    at ReadAndWrite.encryptionGIF(ReadAndWrite.java:102)
    at ReadAndWrite.main(ReadAndWrite.java:109)
Caused by: javax.imageio.IIOException: Code buffer limit reached, no End of Image tag present, possibly data is corrupted.
    at java.desktop/com.sun.imageio.plugins.gif.GIFImageReader.read(GIFImageReader.java:1011)
    ... 2 more
</code>```

Body:
I want to try and save all the frames from a GIF but it either doesn't write the image or if I try another method, it gives an error.

I have

public static void encryptionGIF () throws IOException {
    ImageReader GIFReader = (ImageReader)ImageIO.getImageReadersByFormatName("gif").next();
    File input = new File("Test.gif");
    ImageInputStream Stream = ImageIO.createImageInputStream(input);
    GIFReader.setInput(Stream);
    int frames = GIFReader.getNumImages(true);
    for (int i = 0; i < frames; i++) {
        BufferedImage frame = GIFReader.getRawImageType(i).createBufferedImage(GIFReader.getWidth(i), GIFReader.getHeight(i));
        File output = new File ("Test" + i + ".png");
        ImageIO.write(frame, ".png", output);
    }
}

I have also tried replacing

BufferedImage frame = GIFReader.getRawImageType(i).createBufferedImage(GIFReader.getWidth(i), GIFReader.getHeight(i));

with

BufferedImage frame = GIFReader.read(i);

and get the error:

Exception in thread "main" javax.imageio.IIOException: I/O error reading image!
    at java.desktop/com.sun.imageio.plugins.gif.GIFImageReader.read(GIFImageReader.java:1046)
    at ReadAndWrite.encryptionGIF(ReadAndWrite.java:102)
    at ReadAndWrite.main(ReadAndWrite.java:109)
Caused by: javax.imageio.IIOException: Code buffer limit reached, no End of Image tag present, possibly data is corrupted.
    at java.desktop/com.sun.imageio.plugins.gif.GIFImageReader.read(GIFImageReader.java:1011)
    ... 2 more


问:
Not able to send and recive data from clinet to mysql table
First I am not able to send the data from the input field after submitting the form and Unable to get the data back and show it on the page. I Checked the pathway but couldn't find any thing wrong.

When i click on the submit button i get an error ---Uncaught TypeError: AddProjects.projectList is undefined  and Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3060/addProjects.

```<code>import React,{useState , useRef} from "react";
import "./AddProjects.css"
import axios from "axios";
import Projects from "../Projects/Projects";

export default function AddProjects() {
    const [AddProjects,setAddProjects] = useState({
        ProjectName:"",
        Discription:"",
        git:"",
        Img:"",
        projectList:[]
    })
    const inputFile = useRef(null)
    function handleChange(e) {
        const {name , value} = e.target;
        setAddProjects(newProjects => ({
            ...newProjects,[name]:value
        }))

    }
    function imgChange(e) {
        setAddProjects({ ...AddProjects, Img: URL.createObjectURL(e.target.files[0]) });
    }
    function getProjectList() {
        axios.get(`http://localhost:3060/projects`)
        .then((response) => response.data)
        .then(response2 => {
            setAddProjects({projectList : response2})
        })
    }

    function onSubmitHandler(e) {
        axios.post(`http://localhost:3060/addProjects`,{
                ProjectName: AddProjects.ProjectName,
                Discription:AddProjects.Discription,
                git:AddProjects.git,
                Img:AddProjects.Img
        })
        setAddProjects({
            ProjectName:"",
            Discription:"",
            git:"",
            Img:""
        })
        getProjectList()

        // alert("Project is added")
        // e.preventDefault()

    }
    console.log(AddProjects);
    return(
        <>
            <div className="AddProjects">
                <form onSubmit={onSubmitHandler}>
                    <h2>Add New Project</h2>
                    <input  type="text" placeholder="Project Name..."  value={AddProjects.ProjectName}    name="ProjectName" onChange={handleChange}/>
                    <input  type="text"   placeholder="Project Discription..."  value={AddProjects.Discription}  name="Discription" onChange={handleChange}/>
                    <input  type="text"   placeholder="Git Repository/Code..."  value={AddProjects.git}   name="git" onChange={handleChange}/>
                    <input type="file"  accept="image/jpg,image/jpeg" name="Img" onChange={imgChange} ref={inputFile} />
                    <button type="button"onClick={() => inputFile.current.click()}>Add New Image</button>
                    <button type="submit" >Submit Project</button>
                </form>
            </div>
            {AddProjects.projectList.map((project) =>
                        <Projects   name={project.ProjectName}
                        Discription={project.Discription}
                        git={project.git}
                        Img={project.Img}
                            />
            )

            }
                </>
    )

};
</code>```

This is my Server.js file Please tell me whats wrong and any way to improve the quality of my code

```<code>const express = require('express');
const cors = require('cors')
const PORT = 3060;
const db  = require('./Database')

const bodyParser = require('body-parser');
const { response } = require('express');

const app = express();

app.use(cors());
app.use(bodyParser.json());

app.get('/projects', (req,res) => {
    const TASK_QUERY = `SELECT * FROM  addprojects.newProjects`;
    db.query(TASK_QUERY , (err, response) => {
        if(err) res.status(404).send('somthings wrong')
        else res.send(response)
    })
});

app.post('/addProjects', (req,res) => {
    const ADD_QUERY = `INSERT INTO addprojects.newProjects(ProjectName, Discription, git, Img) VALUES('${req.body.task}')`;
    db.query(ADD_QUERY, (err) => {
        if (err) console.log(err)
        else res.send('Query added sucsessfully')
    })

} );

// app.delete('/deleteprojects/:ProjectId', (req,res) => {
//     console.log(req.params.ProjectId)
//     const DELETE_TASK = `DELETE FROM addprojects.newProjects WHERE task_id = ${req.params.ProjectId}`
//     db.query(DELETE_TASK, (err,res) => {
//         if (err) console.log(err)
//     })
// })

app.listen(PORT, () => {
    console.log('app is listning to port 3000')
})
</code>```

Body:
First I am not able to send the data from the input field after submitting the form and Unable to get the data back and show it on the page. I Checked the pathway but couldn't find any thing wrong.

When i click on the submit button i get an error ---Uncaught TypeError: AddProjects.projectList is undefined  and Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3060/addProjects.

import React,{useState , useRef} from "react";
import "./AddProjects.css"
import axios from "axios";
import Projects from "../Projects/Projects";

export default function AddProjects() {
    const [AddProjects,setAddProjects] = useState({
        ProjectName:"",
        Discription:"",
        git:"",
        Img:"",
        projectList:[]
    })
    const inputFile = useRef(null)
    function handleChange(e) {
        const {name , value} = e.target;
        setAddProjects(newProjects => ({
            ...newProjects,[name]:value
        }))

    }
    function imgChange(e) {
        setAddProjects({ ...AddProjects, Img: URL.createObjectURL(e.target.files[0]) });
    }
    function getProjectList() {
        axios.get(`http://localhost:3060/projects`)
        .then((response) => response.data)
        .then(response2 => {
            setAddProjects({projectList : response2})
        })
    }

    function onSubmitHandler(e) {
        axios.post(`http://localhost:3060/addProjects`,{
                ProjectName: AddProjects.ProjectName,
                Discription:AddProjects.Discription,
                git:AddProjects.git,
                Img:AddProjects.Img
        })
        setAddProjects({
            ProjectName:"",
            Discription:"",
            git:"",
            Img:""
        })
        getProjectList()

        // alert("Project is added")
        // e.preventDefault()

    }
    console.log(AddProjects);
    return(
        <>

                <form onSubmit={onSubmitHandler}>

Add New Project

                    <input  type="text" placeholder="Project Name..."  value={AddProjects.ProjectName}    name="ProjectName" onChange={handleChange}/>
                    <input  type="text"   placeholder="Project Discription..."  value={AddProjects.Discription}  name="Discription" onChange={handleChange}/>
                    <input  type="text"   placeholder="Git Repository/Code..."  value={AddProjects.git}   name="git" onChange={handleChange}/>
                    <input type="file"  accept="image/jpg,image/jpeg" name="Img" onChange={imgChange} ref={inputFile} />
                    <button type="button"onClick={() => inputFile.current.click()}>Add New Image</button>
                    <button type="submit" >Submit Project</button>
                </form>

            {AddProjects.projectList.map((project) =>
                        <Projects   name={project.ProjectName}
                        Discription={project.Discription}
                        git={project.git}
                        Img={project.Img}
                            />
            )

            }
                </>
    )

};

This is my Server.js file Please tell me whats wrong and any way to improve the quality of my code

const express = require('express');
const cors = require('cors')
const PORT = 3060;
const db  = require('./Database')

const bodyParser = require('body-parser');
const { response } = require('express');

const app = express();

app.use(cors());
app.use(bodyParser.json());

app.get('/projects', (req,res) => {
    const TASK_QUERY = `SELECT * FROM  addprojects.newProjects`;
    db.query(TASK_QUERY , (err, response) => {
        if(err) res.status(404).send('somthings wrong')
        else res.send(response)
    })
});

app.post('/addProjects', (req,res) => {
    const ADD_QUERY = `INSERT INTO addprojects.newProjects(ProjectName, Discription, git, Img) VALUES('${req.body.task}')`;
    db.query(ADD_QUERY, (err) => {
        if (err) console.log(err)
        else res.send('Query added sucsessfully')
    })

} );

// app.delete('/deleteprojects/:ProjectId', (req,res) => {
//     console.log(req.params.ProjectId)
//     const DELETE_TASK = `DELETE FROM addprojects.newProjects WHERE task_id = ${req.params.ProjectId}`
//     db.query(DELETE_TASK, (err,res) => {
//         if (err) console.log(err)
//     })
// })

app.listen(PORT, () => {
    console.log('app is listning to port 3000')
})


问:
How to train Sentence Recognizer in Spacy?
I am trying to detect and extract sentences from legal cases. Each paragraph in these cases starts with a number:

23 The main issue for determination therefore....

7 The Appellant’s factual witness...

Right now, Spacy's Sentence Recognizer extracts the above as sentences. I would like to train it such that it 'ignores' the leading digits and detects the sentences as starting after the digits.

The code I have thus far is:

```<code>import spacy
from spacy.training import Example

nlp = spacy.load('en_core_web_sm')
senter = nlp.add_pipe("senter", name="my_senter")

doc = nlp("32 It should be noted that each step")
tokens_ref = ["32", "It", "should", "be", "noted", "that", "each", "step"]
sents_ref = [False, True, False, False, False, False, False, False]
examples = Example.from_dict(doc, {"words": tokens_ref, "sent_starts": sents_ref})
split_examples = examples.split_sents()
senter.initialize(lambda: split_examples, nlp=nlp)
</code>```

I am not sure whether the above code is accurate and works. I'm also unsure how I can:

Pass multiple training examples at one go

Save the trained sentence recognizer and use it again

I would appreciate any help in this regard. I'm fairly new to using Spacy and could not find much resources on training the Sentence Recognizer.

I am aware that I can use other methods to remove the leading digits in each line. Nonetheless, I would still like to know how to train Spacy to try and do the same.

Body:
I am trying to detect and extract sentences from legal cases. Each paragraph in these cases starts with a number:

23 The main issue for determination therefore....

7 The Appellant’s factual witness...

Right now, Spacy's Sentence Recognizer extracts the above as sentences. I would like to train it such that it 'ignores' the leading digits and detects the sentences as starting after the digits.

The code I have thus far is:

import spacy
from spacy.training import Example

nlp = spacy.load('en_core_web_sm')
senter = nlp.add_pipe("senter", name="my_senter")

doc = nlp("32 It should be noted that each step")
tokens_ref = ["32", "It", "should", "be", "noted", "that", "each", "step"]
sents_ref = [False, True, False, False, False, False, False, False]
examples = Example.from_dict(doc, {"words": tokens_ref, "sent_starts": sents_ref})
split_examples = examples.split_sents()
senter.initialize(lambda: split_examples, nlp=nlp)

I am not sure whether the above code is accurate and works. I'm also unsure how I can:

Pass multiple training examples at one go

Save the trained sentence recognizer and use it again

I would appreciate any help in this regard. I'm fairly new to using Spacy and could not find much resources on training the Sentence Recognizer.

I am aware that I can use other methods to remove the leading digits in each line. Nonetheless, I would still like to know how to train Spacy to try and do the same.


问:
How to implement transformation of vector of objects?
I want to implement template function which will transform vector to vector by calling method A::fun() which returns type B.

I implemented it this way:

```<code>#include <algorithm>
#include <iostream>
#include <vector>

struct Point {
  float x;
  float y;
};

template<typename T, typename U>
std::vector<T> getVectorOfValues(const std::vector<U> &objects,
                                 T(*functor)(const U&)) {
    std::vector<T> result;
    std::transform(std::begin(objects), std::end(objects), std::back_inserter(result), functor);
    return result;
}

int main()
{
    std::vector<Point> a = { {1,2},{3,4},{5,6},{7,8},{9,10} };

    auto y = getVectorOfValues(a, +[](const Point& l){return l.y;});

    for(auto a : y) { std::cout << a << " "; }
    std::cout << std::endl;
}
</code>```

It works well untill I need to capture variables by lambda and I have to put + before lambda.
Why does the + sign helps there?

Also I tried to use std::function but it couldn't deduce return type of functor without explicit declaration.
How can I implement this idea in the way where return type of the functor is deduced automaticaly?

Body:
I want to implement template function which will transform vector to vector by calling method A::fun() which returns type B.

I implemented it this way:

#include <algorithm>
#include <iostream>
#include <vector>

struct Point {
  float x;
  float y;
};

template<typename T, typename U>
std::vector<T> getVectorOfValues(const std::vector &objects,
                                 T(*functor)(const U&)) {
    std::vector<T> result;
    std::transform(std::begin(objects), std::end(objects), std::back_inserter(result), functor);
    return result;
}

int main()
{
    std::vector<Point> a = { {1,2},{3,4},{5,6},{7,8},{9,10} };

    auto y = getVectorOfValues(a, +[](const Point& l){return l.y;});

    for(auto a : y) { std::cout << a << " "; }
    std::cout << std::endl;
}

It works well untill I need to capture variables by lambda and I have to put + before lambda.
Why does the + sign helps there?

Also I tried to use std::function but it couldn't deduce return type of functor without explicit declaration.
How can I implement this idea in the way where return type of the functor is deduced automaticaly?


问:
AJAX Data Request For PHP File Loading Entire File, Not Just the Echo
I have some experience in SQL/basic web programming and wanted to branch out. After some help from other users on this site I decided to use JQuery to grab data from a PHP file and echo it to an AJAX request. (Right now I know it seems redundant to use AJAX for this, but my goal is to connect a database to the PHP file once I can hash out this issue).

I can connect to the file no problem, but instead of just loading in the echo I send out from the PHP file, AJAX loads the ENTIRE PHP file, which makes some weird HTML. Any advice on how to fix this? I've tried some tutorials and they all seem to have similar syntax.

PHP File Code:

```<code><?php
echo "<p> HELLO HOW ARE YOU? </p>";
?>
</code>```

JS/JQuery Code:

```<code>function incrementerJavascript() {
            $.ajax({
                url: "increment-counter.php",
                success: function(result)
                {
                    $("#counter").append(result);
                }
            });
        };
</code>```

Relevant screenshot from debugger:

Body:
I have some experience in SQL/basic web programming and wanted to branch out. After some help from other users on this site I decided to use JQuery to grab data from a PHP file and echo it to an AJAX request. (Right now I know it seems redundant to use AJAX for this, but my goal is to connect a database to the PHP file once I can hash out this issue).

I can connect to the file no problem, but instead of just loading in the echo I send out from the PHP file, AJAX loads the ENTIRE PHP file, which makes some weird HTML. Any advice on how to fix this? I've tried some tutorials and they all seem to have similar syntax.

PHP File Code:

<?php
echo "
 HELLO HOW ARE YOU?
";
?>

JS/JQuery Code:

function incrementerJavascript() {
            $.ajax({
                url: "increment-counter.php",
                success: function(result)
                {
                    $("#counter").append(result);
                }
            });
        };

Relevant screenshot from debugger:


问:
Questions about SwiftUI Layout
I tried to place a Button inside a TextField

```<code>List {
    Section(header: Text("ADD WORD")) {
        HStack {
            TextField("input word", text: $dictionaryVM.inputText)
                .autocapitalization(.none)
                .disableAutocorrection(true)

            Button(action: {
                showDetailView = true
            }, label: {
                Image(systemName:"plus")
            })
                .frame(width: 40, height: 40)
                .background(Color.blue.opacity(0.1))
                .cornerRadius(10)
                .padding(.trailing, -10)
            }
     }
}
</code>```

I draw a red border on the screenshot 1 image, when I click outside that red border, it'll trigger the button action

and When I click the button, like the screenshot 2 showed, the whole TextField turned gray, I don't know what I did is wrong, please help me out.

Title: Questions about SwiftUI Layout

Body:
I tried to place a Button inside a TextField

List {
    Section(header: Text("ADD WORD")) {
        HStack {
            TextField("input word", text: $dictionaryVM.inputText)
                .autocapitalization(.none)
                .disableAutocorrection(true)

            Button(action: {
                showDetailView = true
            }, label: {
                Image(systemName:"plus")
            })
                .frame(width: 40, height: 40)
                .background(Color.blue.opacity(0.1))
                .cornerRadius(10)
                .padding(.trailing, -10)
            }
     }
}

I draw a red border on the screenshot 1 image, when I click outside that red border, it'll trigger the button action

and When I click the button, like the screenshot 2 showed, the whole TextField turned gray, I don't know what I did is wrong, please help me out.


问:
Numba Vectorize FakeOverload
This program gives an error when it gets to the "@vectorize(['float32(float32)'], target='cuda')" function with the error:

```<code>File "/home/idf/anaconda3/envs/gpu/lib/python3.9/site-packages/numba/cuda/vectorizers.py", line 206, in _compile_core
    return cudevfn, cudevfn.overloads[sig.args].signature.return_type
AttributeError: 'FakeOverload' object has no attribute 'signature'
</code>```

Notice that I am not even calling the function. It seems to be an error at the interpreter stage:

```<code>import math
import numpy as np
from numba import vectorize,guvectorize,cuda

import timeit

def numpy_sqrt_x(x):
    return np.sqrt(x)

def math_sqrt_x(x):
    return [math.sqrt(xx) for xx in x]

@vectorize
def cpu_sqrt(x):
  return math.sqrt(x)

@vectorize(['float32(float32)'], target='cuda')
def gpu_sqrt(x):
    return math.sqrt(x)

if __name__ == '__main__':
    x = np.arange(10)
    print(x**2)

    #print(np.exp(x))
    #x = np.arange(int(1e2))
    #print(timeit.timeit("numpy_sqrt_x(x)", globals=globals()))
    #print(timeit.timeit("math_sqrt_x(x)", globals=globals()))

    #print(gpu_sqrt(x))
</code>```

Not sure what I am doing wrong?

Title: Numba Vectorize FakeOverload

Body:
This program gives an error when it gets to the "@vectorize(['float32(float32)'], target='cuda')" function with the error:

File "/home/idf/anaconda3/envs/gpu/lib/python3.9/site-packages/numba/cuda/vectorizers.py", line 206, in _compile_core
    return cudevfn, cudevfn.overloads[sig.args].signature.return_type
AttributeError: 'FakeOverload' object has no attribute 'signature'

Notice that I am not even calling the function. It seems to be an error at the interpreter stage:

import math
import numpy as np
from numba import vectorize,guvectorize,cuda

import timeit

def numpy_sqrt_x(x):
    return np.sqrt(x)

def math_sqrt_x(x):
    return [math.sqrt(xx) for xx in x]

@vectorize
def cpu_sqrt(x):
  return math.sqrt(x)

@vectorize(['float32(float32)'], target='cuda')
def gpu_sqrt(x):
    return math.sqrt(x)

if __name__ == '__main__':
    x = np.arange(10)
    print(x**2)

    #print(np.exp(x))
    #x = np.arange(int(1e2))
    #print(timeit.timeit("numpy_sqrt_x(x)", globals=globals()))
    #print(timeit.timeit("math_sqrt_x(x)", globals=globals()))

    #print(gpu_sqrt(x))

Not sure what I am doing wrong?


问:
iframe src from form input
any ideas how to have say a set url for iframe like mysite.com/ and then this input form would add the input field to the end like mysite.com/txtsrc?

```<code><html>
<head>
    <title>Blah.</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript">
        function SetSrc()
        {
            document.getElementById("myIfreme").src = document.getElementById("txtSRC").value;
        }
    </script>
</head>
<body>
    <form>
    Enter URL:
    <input type="text" id="txtSRC" />
    <input type="button" value="GO" onclick="SetSrc()" />
    </form>
    <iframe id="myIfreme" src="" frameborder="0" marginwidth="0" scrolling="yes"></iframe>
</body>
</html>
</code>```

so rather than user inputting the full src i want mysite.com/then the form input after that but so user would not have to put mysite.com/

thanks in advance

i have tried but failed anyone able to help?

Title: iframe src from form input

Body:
any ideas how to have say a set url for iframe like mysite.com/ and then this input form would add the input field to the end like mysite.com/txtsrc?

    <title>Blah.</title>
    <link href="style.css" rel="stylesheet" type="text/css" />

    <form>
    Enter URL:
    <input type="text" id="txtSRC" />
    <input type="button" value="GO" onclick="SetSrc()" />
    </form>

so rather than user inputting the full src i want mysite.com/then the form input after that but so user would not have to put mysite.com/

thanks in advance

i have tried but failed anyone able to help?


问:
Pause Screen in PyQt5
I am trying to pause my screen for 2 seconds using PyQt5 i ran a for loop and tried QThread.sleep(2)
but that makes my screen white for 2 seconds and then continues the loop

I need my screen to show me different results every 2 seconds

Title: Pause Screen in PyQt5


问:
Very long MediaExtractor delay/latency for online audio stream
I'm writing a small (personal use) app that plays an audio stream from the internet. The stream is an AAC audio stream. I can play that stream just fine on linux through mpv and it plays immediately with no perceivable latency.

On Android, I'm first creating a MediaExtractor to extract the data to decode, like this:

```<code>    // tested URLs:
    // https://r.dcs.redcdn.pl/sc/o2/Eurozet/live/audio.livx
    // https://rs101-krk.rmfstream.pl/RMFFM48
    String streamSource = ...;
    MediaExtractor extractor = new MediaExtractor();
    extractor.setDataSource(streamSource);
    extractor.selectTrack(0);
    // it takes ~5 seconds to get there
    this.format = extractor.getTrackFormat(0);
</code>```

And for some reason there is a few seconds of delay from beginning downloading data to actually being able to get any information (like even track count, or select a track) from MediaExtractor. This is both when I construct it with a URL and when I create my own StreamMediaSource, and in this case it actually outputs any information after first reading about 130-150kiB of data, which at 64kbps is 16+ seconds of audio.

Is there any way to replicate the instant playback I can get on a PC? Why does it have to read that much data to proceed?

Body:
I'm writing a small (personal use) app that plays an audio stream from the internet. The stream is an AAC audio stream. I can play that stream just fine on linux through mpv and it plays immediately with no perceivable latency.

On Android, I'm first creating a MediaExtractor to extract the data to decode, like this:

    // tested URLs:
    // https://r.dcs.redcdn.pl/sc/o2/Eurozet/live/audio.livx
    // https://rs101-krk.rmfstream.pl/RMFFM48
    String streamSource = ...;
    MediaExtractor extractor = new MediaExtractor();
    extractor.setDataSource(streamSource);
    extractor.selectTrack(0);
    // it takes ~5 seconds to get there
    this.format = extractor.getTrackFormat(0);

And for some reason there is a few seconds of delay from beginning downloading data to actually being able to get any information (like even track count, or select a track) from MediaExtractor. This is both when I construct it with a URL and when I create my own StreamMediaSource, and in this case it actually outputs any information after first reading about 130-150kiB of data, which at 64kbps is 16+ seconds of audio.

Is there any way to replicate the instant playback I can get on a PC? Why does it have to read that much data to proceed?


问:
How to display listboxes options into different frames Python
I have the following code:

```<code>import tkinter as tk
from tkinter import *
root = Tk()
root.title('N/A')
root.iconbitmap() #None for now, specifying directory on computer
root.geometry("1000x500")

#Create the Frame and menubar
menubar = Menu(root)
root.config(menu=menubar)

#Create the menu widgets
Networks = Menu(menubar, tearoff=False)

Menu_Choices = [Networks]
# Add menu widgets to the menubar
menubar.add_cascade(menu=Networks, label="Networks")

#---------------------------------------------------------------------

# Create the frame
frame = tk.Frame(root, width=1000, height=1000)

# Create the list box
listbox1 = tk.Listbox(frame)
listbox2 = tk.Listbox(frame)
listbox3 = tk.Listbox(frame)
listbox4 = tk.Listbox(frame)
listbox5 = tk.Listbox(frame)

# Pack the list box into the frame
listbox1.pack(side=tk.LEFT)
listbox2.pack(side=tk.LEFT)
listbox3.pack(side=tk.LEFT)
listbox4.pack(side=tk.LEFT)
listbox5.pack(side=tk.LEFT)

# Pack the frame into the main window
frame.pack()

# Add some items to the list box
#listbox.insert(tk.END, "*Please Select Network")

def select_network_1():
    # Clear the list box
    listbox1.delete(0, tk.END)
    listbox2.delete(0, tk.END)
    listbox3.delete(0, tk.END)
    listbox4.delete(0, tk.END)
    listbox5.delete(0, tk.END)

    # Add new items to the list box
    listbox1.insert(tk.END, "1")
    listbox1.insert(tk.END, "2")
    listbox1.insert(tk.END, "3")

    listbox2.insert(tk.END, "1")
    listbox2.insert(tk.END, "2")
    listbox2.insert(tk.END, "3")

    listbox3.insert(tk.END, "1")
    listbox3.insert(tk.END, "2")
    listbox3.insert(tk.END, "3")

    listbox4.insert(tk.END, "1")
    listbox4.insert(tk.END, "2")
    listbox4.insert(tk.END, "3")

    listbox5.insert(tk.END, "1")
    listbox5.insert(tk.END, "2")
    listbox5.insert(tk.END, "3")

def select_network_2():
    # Clear the list box
    listbox1.delete(0, tk.END)
    listbox2.delete(0, tk.END)
    listbox3.delete(0, tk.END)
    listbox4.delete(0, tk.END)
    listbox5.delete(0, tk.END)

    # Add new items to the list box
    listbox1.insert(tk.END, "4")
    listbox1.insert(tk.END, "5")
    listbox1.insert(tk.END, "6")

    listbox2.insert(tk.END, "4")
    listbox2.insert(tk.END, "5")
    listbox2.insert(tk.END, "6")

    listbox3.insert(tk.END, "4")
    listbox3.insert(tk.END, "5")
    listbox3.insert(tk.END, "6")

    listbox4.insert(tk.END, "4")
    listbox4.insert(tk.END, "5")
    listbox4.insert(tk.END, "6")

    listbox5.insert(tk.END, "4")
    listbox5.insert(tk.END, "5")
    listbox5.insert(tk.END, "6")

# Add a command to the "Network 1" menu item that calls the select_network_1 function
Networks.add_command(label="Network 1", command=select_network_1)

Networks.add_command(label="Network 2", command=select_network_2)

root.mainloop()
</code>```

I am trying to add a frame that when a user clicks on the listbox from any of the 5 lists, it will display it in a frame corresponding with the listbox itself.

So, listbox1 when an option is clicked, will display that option in a separate frame correlated to listbox1. So there should be 5 frames, given listbox1, listbox2, listbox3, listbox4, and listbox5.

I have tried using the following code:

```<code>label = tk.Label(root, text="")

# Define the function to be called when an item is selected
def select1(event):
    selection = listbox1.curselection()
    value = listbox1.get(selection)
    label.config(text=value)

listbox1.bind("<<ListboxSelect>>", select1)
</code>```

I tried this to experiment with the first box, but I was unable to display anything when clicking on the options.

Body:
I have the following code:

import tkinter as tk
from tkinter import *
root = Tk()
root.title('N/A')
root.iconbitmap() #None for now, specifying directory on computer
root.geometry("1000x500")

#Create the Frame and menubar
menubar = Menu(root)
root.config(menu=menubar)

#Create the menu widgets
Networks = Menu(menubar, tearoff=False)

Menu_Choices = [Networks]
# Add menu widgets to the menubar
menubar.add_cascade(menu=Networks, label="Networks")

#---------------------------------------------------------------------

# Create the frame
frame = tk.Frame(root, width=1000, height=1000)

# Create the list box
listbox1 = tk.Listbox(frame)
listbox2 = tk.Listbox(frame)
listbox3 = tk.Listbox(frame)
listbox4 = tk.Listbox(frame)
listbox5 = tk.Listbox(frame)

# Pack the list box into the frame
listbox1.pack(side=tk.LEFT)
listbox2.pack(side=tk.LEFT)
listbox3.pack(side=tk.LEFT)
listbox4.pack(side=tk.LEFT)
listbox5.pack(side=tk.LEFT)

# Pack the frame into the main window
frame.pack()

# Add some items to the list box
#listbox.insert(tk.END, "*Please Select Network")

def select_network_1():
    # Clear the list box
    listbox1.delete(0, tk.END)
    listbox2.delete(0, tk.END)
    listbox3.delete(0, tk.END)
    listbox4.delete(0, tk.END)
    listbox5.delete(0, tk.END)

    # Add new items to the list box
    listbox1.insert(tk.END, "1")
    listbox1.insert(tk.END, "2")
    listbox1.insert(tk.END, "3")

    listbox2.insert(tk.END, "1")
    listbox2.insert(tk.END, "2")
    listbox2.insert(tk.END, "3")

    listbox3.insert(tk.END, "1")
    listbox3.insert(tk.END, "2")
    listbox3.insert(tk.END, "3")

    listbox4.insert(tk.END, "1")
    listbox4.insert(tk.END, "2")
    listbox4.insert(tk.END, "3")

    listbox5.insert(tk.END, "1")
    listbox5.insert(tk.END, "2")
    listbox5.insert(tk.END, "3")

def select_network_2():
    # Clear the list box
    listbox1.delete(0, tk.END)
    listbox2.delete(0, tk.END)
    listbox3.delete(0, tk.END)
    listbox4.delete(0, tk.END)
    listbox5.delete(0, tk.END)

    # Add new items to the list box
    listbox1.insert(tk.END, "4")
    listbox1.insert(tk.END, "5")
    listbox1.insert(tk.END, "6")

    listbox2.insert(tk.END, "4")
    listbox2.insert(tk.END, "5")
    listbox2.insert(tk.END, "6")

    listbox3.insert(tk.END, "4")
    listbox3.insert(tk.END, "5")
    listbox3.insert(tk.END, "6")

    listbox4.insert(tk.END, "4")
    listbox4.insert(tk.END, "5")
    listbox4.insert(tk.END, "6")

    listbox5.insert(tk.END, "4")
    listbox5.insert(tk.END, "5")
    listbox5.insert(tk.END, "6")

# Add a command to the "Network 1" menu item that calls the select_network_1 function
Networks.add_command(label="Network 1", command=select_network_1)

Networks.add_command(label="Network 2", command=select_network_2)

root.mainloop()

I am trying to add a frame that when a user clicks on the listbox from any of the 5 lists, it will display it in a frame corresponding with the listbox itself.

So, listbox1 when an option is clicked, will display that option in a separate frame correlated to listbox1. So there should be 5 frames, given listbox1, listbox2, listbox3, listbox4, and listbox5.

I have tried using the following code:

label = tk.Label(root, text="")

# Define the function to be called when an item is selected
def select1(event):
    selection = listbox1.curselection()
    value = listbox1.get(selection)
    label.config(text=value)

listbox1.bind("<<ListboxSelect>>", select1)

I tried this to experiment with the first box, but I was unable to display anything when clicking on the options.


问:
How to avoid function overlaps while using Array (Bounce game)?
I'm writing a collision function to help the object stop moving in a certain direction when facing a block/wall. But it seems that the function has been overlapped because I have called this function multiple times in the draw function of the javascript. How do I prevent this from happening if I want to draw an entire level for the game? For reference, I'm recreating the Bounce game on Nokia.

let cX = 150, cY = 250, size = 50;  // circle
let velY = 0;
let gravity = 0.3;

let blockX = new Array (999);
let blockY = new Array (999);

function draw() {
  background(230);

  velY += gravity;  // ball falls faster with time
  cY += velY;

  if (cX - size/2 < 0)  // ball touches left wall
    {
      cX = 0 + size/2;
    }
  if (cX + size/2 > width)  // ball touches right wall
    {
      cX = width - size/2;
    }

  // creates object
  for (i = 0; i < 13; i++)
    {
      blockX[i] = size * i;
      blockY[i] = size * 7;
      square(blockX[i], blockY[i], size);
      collision();
    }
  for (i = 0; i < 4; i++)
    {
      blockX[i] = size * 7;
      blockY[i] = size * (i+3);
      square(blockX[i], blockY[i], size);
      collision();
    }
  for (i = 0; i < 6; i++)
    {
      blockX[i] = 0;
      blockY[i] = size * (i+1);
      square(blockX[i], blockY[i], size);
      collision();
    }

  if (keyIsDown(LEFT_ARROW))    // move left
    {
      cX += -3;
    }
  if (keyIsDown(RIGHT_ARROW))   // move right
    {
      cX += 3;
    }
  if (keyIsDown(UP_ARROW) && cY + size/2 == blockY[i])  // ball touches ground
    {
      velY = -12;
    }
}

function collision()
{
  if (cY + size/2 > blockY[i] && cY < blockY[i] && blockX[i]-5 <= cX && cX <= blockX[i]+5 + size)  // ball touches top of block
    {
      cY = blockY[i] - size/2;
      velY = -0.4 * velY;
    }
  if (cX - size/2 < blockX[i] + size && cX - size/2 > blockX[i] + size/2 && blockY[i] <= cY && cY <= blockY[i] + size)  // ball touches right of block
    {
      cX = blockX[i] + size * 3/2;
    }
  if (cY - size/2 < blockY[i] + size && cY > blockY[i] + size/2 && blockX[i]-5 <= cX && cX <= blockX[i]+5 + size)  // ball touches bottom of block
    {
      cY = blockY[i] + size * 3/2;
    }
  if (cX + size/2 > blockX[i] && cX + size/2 < blockX[i] + size/2 && blockY[i] <= cY && cY <= blockY[i] + size)  // ball touches left of block
    {
      cX = blockX[i] - size/2;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.5.0/p5.min.js"></script></code>```

The occurring problem is that the ball can't jump if it's standing on a higher block than the floor.

Body:
I'm writing a collision function to help the object stop moving in a certain direction when facing a block/wall. But it seems that the function has been overlapped because I have called this function multiple times in the draw function of the javascript. How do I prevent this from happening if I want to draw an entire level for the game? For reference, I'm recreating the Bounce game on Nokia.

let cX = 150, cY = 250, size = 50;  // circle
let velY = 0;
let gravity = 0.3;

let blockX = new Array (999);
let blockY = new Array (999);

function draw() {
  background(230);

  velY += gravity;  // ball falls faster with time
  cY += velY;

  if (cX - size/2 < 0)  // ball touches left wall
    {
      cX = 0 + size/2;
    }
  if (cX + size/2 > width)  // ball touches right wall
    {
      cX = width - size/2;
    }

  // creates object
  for (i = 0; i < 13; i++)
    {
      blockX[i] = size * i;
      blockY[i] = size * 7;
      square(blockX[i], blockY[i], size);
      collision();
    }
  for (i = 0; i < 4; i++)
    {
      blockX[i] = size * 7;
      blockY[i] = size * (i+3);
      square(blockX[i], blockY[i], size);
      collision();
    }
  for (i = 0; i < 6; i++)
    {
      blockX[i] = 0;
      blockY[i] = size * (i+1);
      square(blockX[i], blockY[i], size);
      collision();
    }

  if (keyIsDown(LEFT_ARROW))    // move left
    {
      cX += -3;
    }
  if (keyIsDown(RIGHT_ARROW))   // move right
    {
      cX += 3;
    }
  if (keyIsDown(UP_ARROW) && cY + size/2 == blockY[i])  // ball touches ground
    {
      velY = -12;
    }
}

function collision()
{
  if (cY + size/2 > blockY[i] && cY < blockY[i] && blockX[i]-5 <= cX && cX <= blockX[i]+5 + size)  // ball touches top of block
    {
      cY = blockY[i] - size/2;
      velY = -0.4 * velY;
    }
  if (cX - size/2 < blockX[i] + size && cX - size/2 > blockX[i] + size/2 && blockY[i] <= cY && cY <= blockY[i] + size)  // ball touches right of block
    {
      cX = blockX[i] + size * 3/2;
    }
  if (cY - size/2 < blockY[i] + size && cY > blockY[i] + size/2 && blockX[i]-5 <= cX && cX <= blockX[i]+5 + size)  // ball touches bottom of block
    {
      cY = blockY[i] + size * 3/2;
    }
  if (cX + size/2 > blockX[i] && cX + size/2 < blockX[i] + size/2 && blockY[i] <= cY && cY <= blockY[i] + size)  // ball touches left of block
    {
      cX = blockX[i] - size/2;
    }
}

The occurring problem is that the ball can't jump if it's standing on a higher block than the floor.


问:
Failure to connect to postgres docker container running locally

Solution

The problem was that my VPN wasn't allowing any internal networking connections, I didn't realise that was possible.

What I'm trying to do

On my Ubuntu system run postgres within a docker container, then from the Ubuntu system connect to the container using psql. Note - I don't want to enter the container then run psql, I want to be able to connect to the running container from the OS using psql.

What I've tried

When I run the following command:

docker run --rm -d \
        -e POSTGRES_PASSWORD=password \
        -e POSTGRES_DB=example \
        -e POSTGRES_USER=user \
        -p 5432:5432 postgres:14.6-bullseye

```
<p>I have the output:</p>
```> docker ps
CONTAINER ID   IMAGE                    COMMAND                  CREATED         STATUS        PORTS                                       NAMES
bd655ef0830a   postgres:14.6-bullseye   "docker-entrypoint.s…"   3 seconds ago   Up 1 second   0.0.0.0:5432->5432/tcp, :::5432->5432/tcp   tender_ardinghelli
```
<p>When I try connecting to this using the following psql command (this is run from my OS, not from within the container):</p>
```psql -h localhost --port 5432 --dbname example -U user
```
<p>I get the error:</p>
```psql: error: connection to server at "localhost" (::1), port 5432 failed: server closed the connection unexpectedly
        This probably means the server terminated abnormally
        before or while processing the request.
```
<p>I don't understand why this is happening - as I have explicitly stated which port I want to connect to, and I have set the ports (i think) correctly in the <code>docker run</code> command.</p>
<h1>Updates</h1>
<h2>Try using a different port in <code>docker run</code></h2>
<blockquote>
<p><em>"If you have a postgres running on the host OS, try to avoid issues by forwarding and connecting to a different port than 5432</em>"</p>
</blockquote>
<p>I tried altering the docker run command to:</p>
```docker run --name example \
    --rm -d \
    -e POSTGRES_PASSWORD=password \
    -e POSTGRES_DB=db -e POSTGRES_USER=user \
    -p 5499:5432 \
    postgres:14.6-bullseye

```
<p>Where I've changed the host port from <code>5432</code> to <code>5499</code> in case there's a conflict with <code>postgres</code> already running on the host system.</p>
<p>After running the <code>docker run</code> command above I have <code>docker ps</code> output of:</p>
```$ docker ps
CONTAINER ID   IMAGE                    COMMAND                  CREATED         STATUS        PORTS                                       NAMES
4172d2d12bb8   postgres:14.6-bullseye   "docker-entrypoint.s…"   2 seconds ago   Up 1 second   0.0.0.0:5499->5432/tcp, :::5499->5432/tcp   example
```
<p>Trying to connect from the host using <code>psql</code> i have:</p>
```$ psql -h localhost --port 5499 --dbname db -U user
psql: error: connection to server at "localhost" (::1), port 5499 failed: server closed the connection unexpectedly
        This probably means the server terminated abnormally
        before or while processing the request.

```
<p>Which is the same error :S</p>
<h2>Try changing <code>listen_addresses</code> in <code>postgres.conf</code></h2>
<p>I have updated <code>/etc/postgresql/14/main/postgresql.conf</code> to have the following line:</p>
```listen_addresses = '*'      # what IP address(es) to listen on;
                    # comma-separated list of addresses;
                    # defaults to 'localhost'; use '*' for all
                    # (change requires restart)
```
<p>And restarted postgres using:</p>
```sudo systemctl restart postgresql
```
<p>But I have the same error as above.</p>
<h1>system info</h1>
<p>Ubuntu system:</p>
```No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 22.04.1 LTS
Release:        22.04
Codename:       jammy
```
<p>Docker version:</p>
```Docker version 20.10.22, build 3a2c30b
```
<p>host <code>psql</code> version</p>
```$ psql --version
psql (PostgreSQL) 14.5 (Ubuntu 14.5-0ubuntu0.22.04.1)

```
<p>Run from the host: <code>systemctl status postgresql</code></p>
```● postgresql.service - PostgreSQL RDBMS
     Loaded: loaded (/lib/systemd/system/postgresql.service; enabled; vendor preset: enabled)
     Active: active (exited) since Sat 2022-12-31 02:18:33 GMT; 1min 0s ago
    Process: 17727 ExecStart=/bin/true (code=exited, status=0/SUCCESS)
   Main PID: 17727 (code=exited, status=0/SUCCESS)
        CPU: 1ms

```
<p>What directories contain <code>post</code>, run from <code>/etc</code>:</p>
```$ /etc> find . -maxdepth 1 -type d | sort | grep post
./postgresql
./postgresql-common
```

Body:
Solution

The problem was that my VPN wasn't allowing any internal networking connections, I didn't realise that was possible.

What I'm trying to do

On my Ubuntu system run postgres within a docker container, then from the Ubuntu system connect to the container using psql. Note - I don't want to enter the container then run psql, I want to be able to connect to the running container from the OS using psql.

What I've tried

When I run the following command:

docker run --rm -d \
        -e POSTGRES_PASSWORD=password \
        -e POSTGRES_DB=example \
        -e POSTGRES_USER=user \
        -p 5432:5432 postgres:14.6-bullseye

I have the output:

> docker ps
CONTAINER ID   IMAGE                    COMMAND                  CREATED         STATUS        PORTS                                       NAMES
bd655ef0830a   postgres:14.6-bullseye   "docker-entrypoint.s…"   3 seconds ago   Up 1 second   0.0.0.0:5432->5432/tcp, :::5432->5432/tcp   tender_ardinghelli

When I try connecting to this using the following psql command (this is run from my OS, not from within the container):

psql -h localhost --port 5432 --dbname example -U user

I get the error:

psql: error: connection to server at "localhost" (::1), port 5432 failed: server closed the connection unexpectedly
        This probably means the server terminated abnormally
        before or while processing the request.

I don't understand why this is happening - as I have explicitly stated which port I want to connect to, and I have set the ports (i think) correctly in the docker run command.

Updates

Try using a different port in docker run

"If you have a postgres running on the host OS, try to avoid issues by forwarding and connecting to a different port than 5432"

I tried altering the docker run command to:

docker run --name example \
    --rm -d \
    -e POSTGRES_PASSWORD=password \
    -e POSTGRES_DB=db -e POSTGRES_USER=user \
    -p 5499:5432 \
    postgres:14.6-bullseye

Where I've changed the host port from 5432 to 5499 in case there's a conflict with postgres already running on the host system.

After running the docker run command above I have docker ps output of:

$ docker ps
CONTAINER ID   IMAGE                    COMMAND                  CREATED         STATUS        PORTS                                       NAMES
4172d2d12bb8   postgres:14.6-bullseye   "docker-entrypoint.s…"   2 seconds ago   Up 1 second   0.0.0.0:5499->5432/tcp, :::5499->5432/tcp   example

Trying to connect from the host using psql i have:

$ psql -h localhost --port 5499 --dbname db -U user
psql: error: connection to server at "localhost" (::1), port 5499 failed: server closed the connection unexpectedly
        This probably means the server terminated abnormally
        before or while processing the request.

Which is the same error :S

Try changing listen_addresses in postgres.conf

I have updated /etc/postgresql/14/main/postgresql.conf to have the following line:

listen_addresses = '*'      # what IP address(es) to listen on;
                    # comma-separated list of addresses;
                    # defaults to 'localhost'; use '*' for all
                    # (change requires restart)

And restarted postgres using:

sudo systemctl restart postgresql

But I have the same error as above.

system info

Ubuntu system:

No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 22.04.1 LTS
Release:        22.04
Codename:       jammy

Docker version:

Docker version 20.10.22, build 3a2c30b

host psql version

$ psql --version
psql (PostgreSQL) 14.5 (Ubuntu 14.5-0ubuntu0.22.04.1)

Run from the host: systemctl status postgresql

● postgresql.service - PostgreSQL RDBMS
     Loaded: loaded (/lib/systemd/system/postgresql.service; enabled; vendor preset: enabled)
     Active: active (exited) since Sat 2022-12-31 02:18:33 GMT; 1min 0s ago
    Process: 17727 ExecStart=/bin/true (code=exited, status=0/SUCCESS)
   Main PID: 17727 (code=exited, status=0/SUCCESS)
        CPU: 1ms

What directories contain post, run from /etc:

$ /etc> find . -maxdepth 1 -type d | sort | grep post
./postgresql
./postgresql-common


问:
Cannot send logs to Kibana via ELK Stack
Hello Stackoverflow community,

I have AWS EKS and I would like to install the ELK stack (v8.5.0) in order to leverage logging for my containers.

I am using HelmChart for it, and for Elasticsearch I am also using value.yaml

After installation, I see that the pods are running.

```<code>
zhajili$ kubectl get pods -n monitoring
NAME                            READY   STATUS    RESTARTS       AGE
elasticsearch-master-0          1/1     Running   0              4h42m
elasticsearch-master-1          1/1     Running   0              4h42m
elasticsearch-master-2          1/1     Running   0              4h42m
fluentd-0                       1/1     Running   0              136m
fluentd-nsbz5                   1/1     Running   4 (135m ago)   136m
fluentd-pccpd                   1/1     Running   1 (2m ago)     4m30s
fluentd-qcrvv                   1/1     Running   4 (135m ago)   136m
fluentd-w8cwl                   1/1     Running   4 (135m ago)   136m
java-app-6ddf744575-4k2cv       1/1     Running   0              4h2m
java-app-6ddf744575-4wdw2       1/1     Running   0              4h2m
java-app-6ddf744575-6xsz7       1/1     Running   0              4h2m
java-app-6ddf744575-7nmql       1/1     Running   0              4h2m
java-app-6ddf744575-8mn7q       1/1     Running   0              4h2m
java-app-6ddf744575-bvlmf       1/1     Running   0              4h2m
java-app-6ddf744575-tgzb7       1/1     Running   0              4h2m
kibana-kibana-fc8cbfc5d-4jkdt   1/1     Running   0              4h36m
node-app-96b85dc67-8rmng        1/1     Running   0              4h3m
node-app-96b85dc67-nhh8w        1/1     Running   0              4h3m
node-app-96b85dc67-pm2lx        1/1     Running   0              4h3m
node-app-96b85dc67-xvtf8        1/1     Running   0              4h3m

</code>```

My next action is configure ConfigMap for Fluentd. I am deleting current configmap for fluentd and applying new one ,my yaml file is like below

```<code>kind: ConfigMap
apiVersion: v1
metadata:
  name: fluentd-forwarder-cm
  namespace: monitoring
  labels:
    app.kubernetes.io/component: forwarder
    app.kubernetes.io/instance: fluentd
    app.kubernetes.io/managed-by: Helm
    app.kubernetes.io/name: fluentd
    helm.sh/chart: fluentd-1.3.0
  annotations:
    meta.helm.sh/release-name: fluentd
    meta.helm.sh/release-namespace: default
data:
  fluentd.conf: |

    # Ignore fluentd own events
    <match fluent.**>
        @type null
    </match>

    # HTTP input for the liveness and readiness probes
    <source>
        @type http
        port 9880
    </source>

    # Throw the healthcheck to the standard output instead of forwarding it
    <match fluentd.healthcheck>
        @type null
    </match>

    # Get the logs from the containers running in the node
    <source>
      @type tail
      path /var/log/containers/*-app*.log
      pos_file /opt/bitnami/fluentd/logs/buffers/fluentd-docker.pos
      tag kubernetes.*
      read_from_head true
      format json
      time_format %Y-%m-%dT%H:%M:%S.%NZ
    </source>

    <filter **>
      @type parser
      key_name log
      <parse>
        @type multi_format
        <pattern>
          format json
          time_key time
          keep_time_key true
        </pattern>
      </parse>
    </filter>

    # enrich with kubernetes metadata
    <filter kubernetes.**>
        @type kubernetes_metadata
    </filter>

    <match kubernetes.var.log.containers.**java-app**.log>
      @type elasticsearch
      include_tag_key true
      host "elasticsearch-master.default.svc.cluster.local"
      port "9200"
      index_name "java-app-logs"
      <buffer>
        @type file
        path /opt/bitnami/fluentd/logs/buffers/java-logs.buffer
        flush_thread_count 2
        flush_interval 5s
      </buffer>
    </match>

    <match kubernetes.var.log.containers.**node-app**.log>
      @type elasticsearch
      include_tag_key true
      host "elasticsearch-master.default.svc.cluster.local"
      port "9200"
      index_name "node-app-logs"
      <buffer>
        @type file
        path /opt/bitnami/fluentd/logs/buffers/node-logs.buffer
        flush_thread_count 2
        flush_interval 5s
      </buffer>
    </match>
</code>```

After applying yaml and I am restarting Fluentd deamonSet with following command

```<code> kubectl rollout restart daemonset/fluentd -n monitoring
</code>```

after that ,some pods are not coming up and they are giving following warning

```<code>                             node.kubernetes.io/unreachable:NoExecute
                             node.kubernetes.io/unschedulable:NoSchedule
Events:
  Type     Reason     Age                     From                                  Message
  ----     ------     ----                    ----                                  -------
  Normal   Scheduled  9m4s                    default-scheduler                     Successfully assigned monitoring/fluentd-pccpd to ip-10-0-27-188.ec2.internal
  Normal   Pulled     9m4s                    kubelet, ip-10-0-27-188.ec2.internal  Container image "docker.io/bitnami/fluentd:1.15.3-debian-11-r11" already present on machine
  Normal   Created    9m3s                    kubelet, ip-10-0-27-188.ec2.internal  Created container fluentd
  Normal   Started    9m3s                    kubelet, ip-10-0-27-188.ec2.internal  Started container fluentd
  Warning  Unhealthy  7m4s (x6 over 7m54s)    kubelet, ip-10-0-27-188.ec2.internal  Liveness probe failed: Get "http://10.0.3.255:9880/fluentd.healthcheck?json=%7B%22ping%22%3A+%22pong%22%7D": dial tcp 10.0.3.255:9880: connect: connection refused
  Normal   Killing    7m4s                    kubelet, ip-10-0-27-188.ec2.internal  Container fluentd failed liveness probe, will be restarted
  Warning  Unhealthy  3m54s (x35 over 8m54s)  kubelet, ip-10-0-27-188.ec2.internal  Readiness probe failed: Get "http://10.0.3.255:9880/fluentd.healthcheck?json=%7B%22ping%22%3A+%22pong%22%7D": dial tcp 10.0.3.255:9880: connect: connection refused
</code>```

Even though rest of FluentD PODs are up and running ,I see following WARNING in other Pods

```<code>Events:
  Type     Reason       Age                 From                                 Message
  ----     ------       ----                ----                                 -------
  Warning  FailedMount  20m (x10 over 24m)  kubelet, ip-10-0-3-179.ec2.internal  MountVolume.SetUp failed for volume "fluentd-config" : configmap "fluentd-forwarder-cm" not found
</code>```

But I can confirm that I have mentioned CM deployed already.

```<code>zhajili$ kubectl get cm -n monitoring
NAME                    DATA   AGE
fluentd-aggregator-cm   4      144m
fluentd-forwarder-cm    1      21m
kube-root-ca.crt        1      4h50m

</code>```

I also see that following pods are using mentioned configmap with following command ,I am very confused now

```<code>kube-root-ca.crt        1      4h54m
zhajili$ kubectl get pods --namespace=monitoring -o custom-columns=NAME:.metadata.name,CONFIGMAP:.spec.volumes[*].configMap.name | grep fluentd-forwarder-cm

fluentd-nsbz5                   fluentd-forwarder-cm
fluentd-pccpd                   fluentd-forwarder-cm
fluentd-qcrvv                   fluentd-forwarder-cm
fluentd-w8cwl                   fluentd-forwarder-cm
zhajili$
zhajili$ kubectl get pods -n monitoring
NAME                            READY   STATUS             RESTARTS       AGE
elasticsearch-master-0          1/1     Running            0              4h55m
elasticsearch-master-1          1/1     Running            0              4h55m
elasticsearch-master-2          1/1     Running            0              4h55m
fluentd-0                       1/1     Running            0              149m
fluentd-nsbz5                   1/1     Running            4 (148m ago)   149m
fluentd-pccpd                   0/1     CrashLoopBackOff   6 (70s ago)    17m
fluentd-qcrvv                   1/1     Running            4 (148m ago)   149m
fluentd-w8cwl                   1/1     Running            4 (148m ago)   149m
java-app-6ddf744575-4k2cv       1/1     Running            0              4h16m
java-app-6ddf744575-4wdw2       1/1     Running            0              4h16m
java-app-6ddf744575-6xsz7       1/1     Running            0              4h16m
java-app-6ddf744575-7nmql       1/1     Running            0              4h16m
java-app-6ddf744575-8mn7q       1/1     Running            0              4h16m
java-app-6ddf744575-bvlmf       1/1     Running            0              4h16m
java-app-6ddf744575-tgzb7       1/1     Running            0              4h16m
kibana-kibana-fc8cbfc5d-4jkdt   1/1     Running            0              4h50m
node-app-96b85dc67-8rmng        1/1     Running            0              4h16m
node-app-96b85dc67-nhh8w        1/1     Running            0              4h16m
node-app-96b85dc67-pm2lx        1/1     Running            0              4h16m
node-app-96b85dc67-xvtf8        1/1     Running            0              4h16m
</code>```

And due that issue ,I assume that No Indices are created in Kibana.

Could you pleas help me?

Body:
Hello Stackoverflow community,

I have AWS EKS and I would like to install the ELK stack (v8.5.0) in order to leverage logging for my containers.

I am using HelmChart for it, and for Elasticsearch I am also using value.yaml

After installation, I see that the pods are running.

zhajili$ kubectl get pods -n monitoring
NAME                            READY   STATUS    RESTARTS       AGE
elasticsearch-master-0          1/1     Running   0              4h42m
elasticsearch-master-1          1/1     Running   0              4h42m
elasticsearch-master-2          1/1     Running   0              4h42m
fluentd-0                       1/1     Running   0              136m
fluentd-nsbz5                   1/1     Running   4 (135m ago)   136m
fluentd-pccpd                   1/1     Running   1 (2m ago)     4m30s
fluentd-qcrvv                   1/1     Running   4 (135m ago)   136m
fluentd-w8cwl                   1/1     Running   4 (135m ago)   136m
java-app-6ddf744575-4k2cv       1/1     Running   0              4h2m
java-app-6ddf744575-4wdw2       1/1     Running   0              4h2m
java-app-6ddf744575-6xsz7       1/1     Running   0              4h2m
java-app-6ddf744575-7nmql       1/1     Running   0              4h2m
java-app-6ddf744575-8mn7q       1/1     Running   0              4h2m
java-app-6ddf744575-bvlmf       1/1     Running   0              4h2m
java-app-6ddf744575-tgzb7       1/1     Running   0              4h2m
kibana-kibana-fc8cbfc5d-4jkdt   1/1     Running   0              4h36m
node-app-96b85dc67-8rmng        1/1     Running   0              4h3m
node-app-96b85dc67-nhh8w        1/1     Running   0              4h3m
node-app-96b85dc67-pm2lx        1/1     Running   0              4h3m
node-app-96b85dc67-xvtf8        1/1     Running   0              4h3m

My next action is configure ConfigMap for Fluentd. I am deleting current configmap for fluentd and applying new one ,my yaml file is like below

kind: ConfigMap
apiVersion: v1
metadata:
  name: fluentd-forwarder-cm
  namespace: monitoring
  labels:
    app.kubernetes.io/component: forwarder
    app.kubernetes.io/instance: fluentd
    app.kubernetes.io/managed-by: Helm
    app.kubernetes.io/name: fluentd
    helm.sh/chart: fluentd-1.3.0
  annotations:
    meta.helm.sh/release-name: fluentd
    meta.helm.sh/release-namespace: default
data:
  fluentd.conf: |

    # Ignore fluentd own events
    <match fluent.**>
        @type null
    </match>

    # HTTP input for the liveness and readiness probes
    <source>
        @type http
        port 9880
    </source>

    # Throw the healthcheck to the standard output instead of forwarding it
    <match fluentd.healthcheck>
        @type null
    </match>

    # Get the logs from the containers running in the node
    <source>
      @type tail
      path /var/log/containers/*-app*.log
      pos_file /opt/bitnami/fluentd/logs/buffers/fluentd-docker.pos
      tag kubernetes.*
      read_from_head true
      format json
      time_format %Y-%m-%dT%H:%M:%S.%NZ
    </source>

    <filter **>
      @type parser
      key_name log
      <parse>
        @type multi_format
        <pattern>
          format json
          time_key time
          keep_time_key true
        </pattern>
      </parse>
    </filter>

    # enrich with kubernetes metadata
    <filter kubernetes.**>
        @type kubernetes_metadata
    </filter>

    <match kubernetes.var.log.containers.**java-app**.log>
      @type elasticsearch
      include_tag_key true
      host "elasticsearch-master.default.svc.cluster.local"
      port "9200"
      index_name "java-app-logs"
      <buffer>
        @type file
        path /opt/bitnami/fluentd/logs/buffers/java-logs.buffer
        flush_thread_count 2
        flush_interval 5s
      </buffer>
    </match>

    <match kubernetes.var.log.containers.**node-app**.log>
      @type elasticsearch
      include_tag_key true
      host "elasticsearch-master.default.svc.cluster.local"
      port "9200"
      index_name "node-app-logs"
      <buffer>
        @type file
        path /opt/bitnami/fluentd/logs/buffers/node-logs.buffer
        flush_thread_count 2
        flush_interval 5s
      </buffer>
    </match>

After applying yaml and I am restarting Fluentd deamonSet with following command

 kubectl rollout restart daemonset/fluentd -n monitoring

after that ,some pods are not coming up and they are giving following warning

                             node.kubernetes.io/unreachable:NoExecute
                             node.kubernetes.io/unschedulable:NoSchedule
Events:
  Type     Reason     Age                     From                                  Message
  ----     ------     ----                    ----                                  -------
  Normal   Scheduled  9m4s                    default-scheduler                     Successfully assigned monitoring/fluentd-pccpd to ip-10-0-27-188.ec2.internal
  Normal   Pulled     9m4s                    kubelet, ip-10-0-27-188.ec2.internal  Container image "docker.io/bitnami/fluentd:1.15.3-debian-11-r11" already present on machine
  Normal   Created    9m3s                    kubelet, ip-10-0-27-188.ec2.internal  Created container fluentd
  Normal   Started    9m3s                    kubelet, ip-10-0-27-188.ec2.internal  Started container fluentd
  Warning  Unhealthy  7m4s (x6 over 7m54s)    kubelet, ip-10-0-27-188.ec2.internal  Liveness probe failed: Get "http://10.0.3.255:9880/fluentd.healthcheck?json=%7B%22ping%22%3A+%22pong%22%7D": dial tcp 10.0.3.255:9880: connect: connection refused
  Normal   Killing    7m4s                    kubelet, ip-10-0-27-188.ec2.internal  Container fluentd failed liveness probe, will be restarted
  Warning  Unhealthy  3m54s (x35 over 8m54s)  kubelet, ip-10-0-27-188.ec2.internal  Readiness probe failed: Get "http://10.0.3.255:9880/fluentd.healthcheck?json=%7B%22ping%22%3A+%22pong%22%7D": dial tcp 10.0.3.255:9880: connect: connection refused

Even though rest of FluentD PODs are up and running ,I see following WARNING in other Pods

Events:
  Type     Reason       Age                 From                                 Message
  ----     ------       ----                ----                                 -------
  Warning  FailedMount  20m (x10 over 24m)  kubelet, ip-10-0-3-179.ec2.internal  MountVolume.SetUp failed for volume "fluentd-config" : configmap "fluentd-forwarder-cm" not found

But I can confirm that I have mentioned CM deployed already.

zhajili$ kubectl get cm -n monitoring
NAME                    DATA   AGE
fluentd-aggregator-cm   4      144m
fluentd-forwarder-cm    1      21m
kube-root-ca.crt        1      4h50m

I also see that following pods are using mentioned configmap with following command ,I am very confused now

kube-root-ca.crt        1      4h54m
zhajili$ kubectl get pods --namespace=monitoring -o custom-columns=NAME:.metadata.name,CONFIGMAP:.spec.volumes[*].configMap.name | grep fluentd-forwarder-cm

fluentd-nsbz5                   fluentd-forwarder-cm
fluentd-pccpd                   fluentd-forwarder-cm
fluentd-qcrvv                   fluentd-forwarder-cm
fluentd-w8cwl                   fluentd-forwarder-cm
zhajili$
zhajili$ kubectl get pods -n monitoring
NAME                            READY   STATUS             RESTARTS       AGE
elasticsearch-master-0          1/1     Running            0              4h55m
elasticsearch-master-1          1/1     Running            0              4h55m
elasticsearch-master-2          1/1     Running            0              4h55m
fluentd-0                       1/1     Running            0              149m
fluentd-nsbz5                   1/1     Running            4 (148m ago)   149m
fluentd-pccpd                   0/1     CrashLoopBackOff   6 (70s ago)    17m
fluentd-qcrvv                   1/1     Running            4 (148m ago)   149m
fluentd-w8cwl                   1/1     Running            4 (148m ago)   149m
java-app-6ddf744575-4k2cv       1/1     Running            0              4h16m
java-app-6ddf744575-4wdw2       1/1     Running            0              4h16m
java-app-6ddf744575-6xsz7       1/1     Running            0              4h16m
java-app-6ddf744575-7nmql       1/1     Running            0              4h16m
java-app-6ddf744575-8mn7q       1/1     Running            0              4h16m
java-app-6ddf744575-bvlmf       1/1     Running            0              4h16m
java-app-6ddf744575-tgzb7       1/1     Running            0              4h16m
kibana-kibana-fc8cbfc5d-4jkdt   1/1     Running            0              4h50m
node-app-96b85dc67-8rmng        1/1     Running            0              4h16m
node-app-96b85dc67-nhh8w        1/1     Running            0              4h16m
node-app-96b85dc67-pm2lx        1/1     Running            0              4h16m
node-app-96b85dc67-xvtf8        1/1     Running            0              4h16m

And due that issue ,I assume that No Indices are created in Kibana.

Could you pleas help me?


问:
Build and install libsocketcan for x86_64
I have downloaded the the libsocketcan project and built and installed it successfully (no errors) using:

```<code>./autogen.sh
./configure
make
make install
</code>```

and the configure step outputs:

```<code>checking build system type... x86_64-pc-linux-gnu
</code>```

By my program still complains about the missing libsocketcan file:

```<code>qt.canbus.plugins.socketcan: Cannot load library socketcan: (socketcan: cannot open shared object file: No such file or directory)
qt.canbus.plugins.socketcan: Cannot load library libsocketcan, some functionality will not be available.
Cannot load library socketcan: (socketcan: cannot open shared object file: No such file or directory)
</code>```

I notice that libsocketcan.* can be found in /usr/local/lib, but not in /usr/local/lib64.  I think thats the problem.  Why are the above steps not building and installing the 64-bit versions of the library?  I tried symlinking the .so file into the /usr/local/lib64 but it had no effect.  I also tried adding the path to the /usr/local/lib/libsocketcan.so in the ld.config.conf file but also no effect (and I ran ldconfig).

I'm working in Fedora 34 x86_64.

Body:
I have downloaded the the libsocketcan project and built and installed it successfully (no errors) using:

./autogen.sh
./configure
make
make install

and the configure step outputs:

checking build system type... x86_64-pc-linux-gnu

By my program still complains about the missing libsocketcan file:

qt.canbus.plugins.socketcan: Cannot load library socketcan: (socketcan: cannot open shared object file: No such file or directory)
qt.canbus.plugins.socketcan: Cannot load library libsocketcan, some functionality will not be available.
Cannot load library socketcan: (socketcan: cannot open shared object file: No such file or directory)

I notice that libsocketcan.* can be found in /usr/local/lib, but not in /usr/local/lib64.  I think thats the problem.  Why are the above steps not building and installing the 64-bit versions of the library?  I tried symlinking the .so file into the /usr/local/lib64 but it had no effect.  I also tried adding the path to the /usr/local/lib/libsocketcan.so in the ld.config.conf file but also no effect (and I ran ldconfig).

I'm working in Fedora 34 x86_64.


问:
Linked drop-down menu with xml
When the user completes the selection to display the city information of the State, city, or county, the corresponding city name will be displayed in the second selection field, and finally, after the city name is selected, the city will be displayed in the third selection field Township Information for .

my trying:
`

```<code>function ChangeText(Target, Destin, Value)
{
  var CityList,City,Index;
  CreateXMLHttpRequest("xml example.xml", function()
    {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
      {
        xmlDoc=xmlhttp.responseXML;
        CityList="<option value=0>Please Select</option><br>";
        City=xmlDoc.getElementsByTagName(Target);
        if (Value < 0)
        {
          for (Index=1; Index<=City.length; Index++)
          {

            CityList=CityList + "<option value=" + Index + ">" + City[Index-1].attributes['name'].value + "</option><br>";

          }
        }
        else if (Value > 0)
        {
          //CityList="<h1>City: "+City[Value-1].attributes['name'].value+"</h1><br>";
          CityList="<h1>City: "+City[Value-1].childNodes[0].nodeValue+"</h1><br>";
        }
        document.getElementById(Destin).innerHTML=CityList;
      }
    }
  );
}
</code>```

xml example:

```<code><country>
    <State name="California">
        <CITY name="Los Angeles">
            <DISTRICT name="Orange County"/>
            <DISTRICT name="Riverside County"/>
        </CITY>

    </State>
    <State name="Florida">
        <CITY name="Jacksonville"></CITY>
    </State>
</country>
</code>```

`

Title: Linked drop-down menu with xml

Body:
When the user completes the selection to display the city information of the State, city, or county, the corresponding city name will be displayed in the second selection field, and finally, after the city name is selected, the city will be displayed in the third selection field Township Information for .

my trying:
`

function ChangeText(Target, Destin, Value)
{
  var CityList,City,Index;
  CreateXMLHttpRequest("xml example.xml", function()
    {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
      {
        xmlDoc=xmlhttp.responseXML;
        CityList="<option value=0>Please Select</option>
";
        City=xmlDoc.getElementsByTagName(Target);
        if (Value < 0)
        {
          for (Index=1; Index<=City.length; Index++)
          {

            CityList=CityList + "<option value=" + Index + ">" + City[Index-1].attributes['name'].value + "</option>
";

          }
        }
        else if (Value > 0)
        {
          //CityList="
City: "+City[Value-1].attributes['name'].value+"

";
          CityList="
City: "+City[Value-1].childNodes[0].nodeValue+"

";
        }
        document.getElementById(Destin).innerHTML=CityList;
      }
    }
  );
}

xml example:

<country>
    <State name="California">
        <CITY name="Los Angeles">
            <DISTRICT name="Orange County"/>
            <DISTRICT name="Riverside County"/>
        </CITY>

    </State>
    <State name="Florida">
        <CITY name="Jacksonville"></CITY>
    </State>
</country>

`


问:
fast access management for CDN
I am looking for a quick/cheap way to implement the access management of a CDN containing images.

Please check the diagram

context

A user usually requests a high number of small images (latency should be below 200ms), and a user requests images one by one.

access management

A user updates the permission of an image in the DB

A permission hook is triggered and updates the permission file of the image (add user id in the file)

Upload/update the S3 bucket with the new permission file

invalidate CLOUDFRONT cache for this specific file

image request

A user sends an HTTP request to collect an image
METHOD: GET
URL: URL/image-id.png
HEADER: Authorisation (containing user id)

The edge lambda intercepts the request, validates the token, uses the image id to retrieve the permission file of the image, and finally verifies if the file contains the user id.

If any steps in point 2 fail, then the lambda returns an error message; otherwise forward the request to CDN.

What do you guys think? Is it a terrible idea?

Title: fast access management for CDN


问:
do the sin and cos from the columns of a data set
I have data of size (999,100)

I am trying to plot the sin and cos for each column and plot it as 999 lines in a 3d plot

I have written the code

```<code>    plt.figure(figsize=(4.3,4))
    ax = plt.axes(projection='3d')
    tgrid = np.arange(0,999)

    ax.plot3D(tgrid,np.cos(data[:,:100]), np.sin(data[:,:100]), '-',color='black',linewidth=1.5,label='True')

    ax.set_xlabel(r'$t$')
    ax.set_ylabel(r'$\cos(\theta)$')
    ax.set_zlabel(r'$\sin(\theta)$')
    plt.legend(loc='best',prop={'size':12})
</code>```

I am getting the following error:

```<code>    ax.plot3D(tgrid,np.cos(data[:,:100]), np.sin(data[:,:100]), '-',color='black',linewidth=1.5,label='True')
  File "/home/linot/anaconda3/lib/python3.7/site-packages/mpl_toolkits/mplot3d/axes3d.py", line 1538, in plot
    zs = np.broadcast_to(zs, len(xs))
  File "<__array_function__ internals>", line 6, in broadcast_to
  File "/home/linot/anaconda3/lib/python3.7/site-packages/numpy/lib/stride_tricks.py", line 182, in broadcast_to
    return _broadcast_to(array, shape, subok=subok, readonly=True)
  File "/home/linot/anaconda3/lib/python3.7/site-packages/numpy/lib/stride_tricks.py", line 127, in _broadcast_to
    op_flags=['readonly'], itershape=shape, order='C')
ValueError: input operand has more dimensions than allowed by the axis remapping
</code>```

I have also tried the following, but it is not saving the figures

```<code>    data_x=np.cos(data[:,:])
    data_y=np.sin(data[:,:])

    tgrid = np.arange(0,999)

    plt.figure(figsize=(4.3,4))
    for jj in range(100):
        ax = plt.axes(projection='3d')
        ax.plot3D(tgrid,data_x[jj,:], data_y[jj,:])

    plt.savefig('data.pdf')

</code>```

Body:
I have data of size (999,100)

I am trying to plot the sin and cos for each column and plot it as 999 lines in a 3d plot

I have written the code

    plt.figure(figsize=(4.3,4))
    ax = plt.axes(projection='3d')
    tgrid = np.arange(0,999)

    ax.plot3D(tgrid,np.cos(data[:,:100]), np.sin(data[:,:100]), '-',color='black',linewidth=1.5,label='True')

    ax.set_xlabel(r'$t$')
    ax.set_ylabel(r'$\cos(\theta)$')
    ax.set_zlabel(r'$\sin(\theta)$')
    plt.legend(loc='best',prop={'size':12})

I am getting the following error:

    ax.plot3D(tgrid,np.cos(data[:,:100]), np.sin(data[:,:100]), '-',color='black',linewidth=1.5,label='True')
  File "/home/linot/anaconda3/lib/python3.7/site-packages/mpl_toolkits/mplot3d/axes3d.py", line 1538, in plot
    zs = np.broadcast_to(zs, len(xs))
  File "<__array_function__ internals>", line 6, in broadcast_to
  File "/home/linot/anaconda3/lib/python3.7/site-packages/numpy/lib/stride_tricks.py", line 182, in broadcast_to
    return _broadcast_to(array, shape, subok=subok, readonly=True)
  File "/home/linot/anaconda3/lib/python3.7/site-packages/numpy/lib/stride_tricks.py", line 127, in _broadcast_to
    op_flags=['readonly'], itershape=shape, order='C')
ValueError: input operand has more dimensions than allowed by the axis remapping

I have also tried the following, but it is not saving the figures

    data_x=np.cos(data[:,:])
    data_y=np.sin(data[:,:])

    tgrid = np.arange(0,999)

    plt.figure(figsize=(4.3,4))
    for jj in range(100):
        ax = plt.axes(projection='3d')
        ax.plot3D(tgrid,data_x[jj,:], data_y[jj,:])

    plt.savefig('data.pdf')