问:
Socket.io client sending but not receiving. How to debug?
I have a Node.js server that serves a game that uses socket.io for communciation.

The server has socket.io as a Websocket Server.
The client is a Vue project that is built with Vite.

All this is deployed on Heroku.

The problem is that the client has a succesful WS connection and sends data to the server which the server sees. However, the server appears to be unable to send data back the client.

Developer Tools > Network tab (WS)
active ws connection

Locally, of course, this works fine.

I've enabled http-session-affinity and DEBUG=socket* dist/index.js

```<code>socket.io:server incoming connection with id pp-tr6sHkUhv0XQmAAAA
socket.io-parser decoded 0 as {"type":0,"nsp":"/"}
socket.io:client connecting to namespace /
socket.io:namespace adding socket to nsp /
socket.io:socket socket connected - writing packet
socket.io:socket join room cKL5uTe1EsFYQVpfAAAB
socket.io-parser encoding packet {"type":0,"data":{"sid":"cKL5uTe1EsFYQVpfAAAB"},"nsp":"/"}
socket.io-parser encoded {"type":0,"data":{"sid":"cKL5uTe1EsFYQVpfAAAB"},"nsp":"/"} as 0{"sid":"cKL5uTe1EsFYQVpfAAAB"}
socket.io-parser decoded 2["join-room","prelobby"] as {"type":2,"nsp":"/","data":["join-room","prelobby"]}
socket.io:socket got packet {"type":2,"nsp":"/","data":["join-room","prelobby"]}
socket.io:socket emitting event ["join-room","prelobby"]
socket.io:socket dispatching an event ["join-room","prelobby"]
heroku/router at=info method=GET path="/socket.io/?EIO=4&transport=polling&t=OMRi4mx&sid=pp-tr6sHkUhv0XQmAAAA" host=xxx.herokuapp.com request_id=a93e01fd-f3ce-4d66-9f8f-4421a2e04d5d fwd="88.159.232.55" dyno=web.1 connect=0ms service=146ms status=200 bytes=168 protocol=https
socket.io-parser decoded 2["create-lobby",{"id":"bf791395-2316-4a8c-bffc-ca8b8b600385","teamName":"TEAM NAME HERE","players":[],"maxPlayers":4,"started":false,"takenSlots":[]}] as {"type":2,"nsp":"/","data":["create-lobby",{"id":"bf791395-2316-4a8c-bffc-ca8b8b600385","teamName":"TEAM NAME HERE","players":[],"maxPlayers":4,"started":false,"takenSlots":[]}]}
socket got packet {"type":2,"nsp":"/","data":["create-lobby",{"id":"bf791395-2316-4a8c-bffc-ca8b8b600385","teamName":"TEAM NAME HERE","players":[],"maxPlayers":4,"started":false,"takenSlots":[]}]}
socket.io:socket emitting event ["create-lobby",{"id":"bf791395-2316-4a8c-bffc-ca8b8b600385","teamName":"TEAM NAME HERE","players":[],"maxPlayers":4,"started":false,"takenSlots":[]}]
socket.io:socket dispatching an event ["create-lobby",{"id":"bf791395-2316-4a8c-bffc-ca8b8b600385","teamName":"TEAM NAME HERE","players":[],"maxPlayers":4,"started":false,"takenSlots":[]}]
socket.io-parser decoded 2["create-lobby",{"id":"d881d972-a341-487d-9831-90d0769e21ee","teamName":"TEAM NAME HERE","players":[],"maxPlayers":4,"started":false,"takenSlots":[]}] as {"type":2,"nsp":"/","data":["create-lobby",{"id":"d881d972-a341-487d-9831-90d0769e21ee","teamName":"TEAM NAME HERE","players":[],"maxPlayers":4,"started":false,"takenSlots":[]}]}
socket.io:socket got packet {"type":2,"nsp":"/","data":["create-lobby",{"id":"d881d972-a341-487d-9831-90d0769e21ee","teamName":"TEAM NAME HERE","players":[],"maxPlayers":4,"started":false,"takenSlots":[]}]}
socket.io:socket emitting event ["create-lobby",{"id":"d881d972-a341-487d-9831-90d0769e21ee","teamName":"TEAM NAME HERE","players":[],"maxPlayers":4,"started":false,"takenSlots":[]}]
socket.io:socket dispatching an event ["create-lobby",{"id":"d881d972-a341-487d-9831-90d0769e21ee","teamName":"TEAM NAME HERE","players":[],"maxPlayers":4,"started":false,"takenSlots":[]}]
</code>```

Server:

```<code>const server = new Server(server, {
    cors: {
        origin: "*",
        methods: ["GET", "POST"],
    },
    transports: ["polling", "websocket"],
    allowEIO3: true,
    allowUpgrades: true,
});
const server: http.Server = httpServer.initialise();
server.listen(env.PORT, () => {
   console.log(`Server listening on port ${env.PORT}`);
});
const io = sockets.start(server);
</code>```

Client:

```<code>this.socket = io();
this.socket.emit(SocketEvents.JOIN_ROOM, "prelobby");
this.socket.on(SocketEvents.LOBBY_CREATED, (lobbyData) => {
      console.log("received lobby data", lobbyData);
      LobbyData.data = lobbyData;
      this.cameras.main.fadeOut(1000);
      this.socket.emit(SocketEvents.LEAVE_ROOM, "prelobby");
});
</code>```

vite.config.js

```<code>export default defineConfig({
  plugins: [vue({
    template: {
      transformAssetUrls: {
        includeAbsolute: false,
      }
    }
  })],
  server: {
    proxy: {
      '/api': {
        target: `http://localhost:4000`,
        changeOrigin: true,
      },
      '/socket.io': {
        target: `ws://localhost:4000`,
        ws: true,
        changeOrigin: true,
      }
    },
  },
  build: {
    rollupOptions: {
      external: [],
    }
  }
})
</code>```

Body:
I have a Node.js server that serves a game that uses socket.io for communciation.

The server has socket.io as a Websocket Server.
The client is a Vue project that is built with Vite.

All this is deployed on Heroku.

The problem is that the client has a succesful WS connection and sends data to the server which the server sees. However, the server appears to be unable to send data back the client.

Developer Tools > Network tab (WS)
active ws connection

Locally, of course, this works fine.

I've enabled http-session-affinity and DEBUG=socket* dist/index.js

socket.io:server incoming connection with id pp-tr6sHkUhv0XQmAAAA
socket.io-parser decoded 0 as {"type":0,"nsp":"/"}
socket.io:client connecting to namespace /
socket.io:namespace adding socket to nsp /
socket.io:socket socket connected - writing packet
socket.io:socket join room cKL5uTe1EsFYQVpfAAAB
socket.io-parser encoding packet {"type":0,"data":{"sid":"cKL5uTe1EsFYQVpfAAAB"},"nsp":"/"}
socket.io-parser encoded {"type":0,"data":{"sid":"cKL5uTe1EsFYQVpfAAAB"},"nsp":"/"} as 0{"sid":"cKL5uTe1EsFYQVpfAAAB"}
socket.io-parser decoded 2["join-room","prelobby"] as {"type":2,"nsp":"/","data":["join-room","prelobby"]}
socket.io:socket got packet {"type":2,"nsp":"/","data":["join-room","prelobby"]}
socket.io:socket emitting event ["join-room","prelobby"]
socket.io:socket dispatching an event ["join-room","prelobby"]
heroku/router at=info method=GET path="/socket.io/?EIO=4&transport=polling&t=OMRi4mx&sid=pp-tr6sHkUhv0XQmAAAA" host=xxx.herokuapp.com request_id=a93e01fd-f3ce-4d66-9f8f-4421a2e04d5d fwd="88.159.232.55" dyno=web.1 connect=0ms service=146ms status=200 bytes=168 protocol=https
socket.io-parser decoded 2["create-lobby",{"id":"bf791395-2316-4a8c-bffc-ca8b8b600385","teamName":"TEAM NAME HERE","players":[],"maxPlayers":4,"started":false,"takenSlots":[]}] as {"type":2,"nsp":"/","data":["create-lobby",{"id":"bf791395-2316-4a8c-bffc-ca8b8b600385","teamName":"TEAM NAME HERE","players":[],"maxPlayers":4,"started":false,"takenSlots":[]}]}
socket got packet {"type":2,"nsp":"/","data":["create-lobby",{"id":"bf791395-2316-4a8c-bffc-ca8b8b600385","teamName":"TEAM NAME HERE","players":[],"maxPlayers":4,"started":false,"takenSlots":[]}]}
socket.io:socket emitting event ["create-lobby",{"id":"bf791395-2316-4a8c-bffc-ca8b8b600385","teamName":"TEAM NAME HERE","players":[],"maxPlayers":4,"started":false,"takenSlots":[]}]
socket.io:socket dispatching an event ["create-lobby",{"id":"bf791395-2316-4a8c-bffc-ca8b8b600385","teamName":"TEAM NAME HERE","players":[],"maxPlayers":4,"started":false,"takenSlots":[]}]
socket.io-parser decoded 2["create-lobby",{"id":"d881d972-a341-487d-9831-90d0769e21ee","teamName":"TEAM NAME HERE","players":[],"maxPlayers":4,"started":false,"takenSlots":[]}] as {"type":2,"nsp":"/","data":["create-lobby",{"id":"d881d972-a341-487d-9831-90d0769e21ee","teamName":"TEAM NAME HERE","players":[],"maxPlayers":4,"started":false,"takenSlots":[]}]}
socket.io:socket got packet {"type":2,"nsp":"/","data":["create-lobby",{"id":"d881d972-a341-487d-9831-90d0769e21ee","teamName":"TEAM NAME HERE","players":[],"maxPlayers":4,"started":false,"takenSlots":[]}]}
socket.io:socket emitting event ["create-lobby",{"id":"d881d972-a341-487d-9831-90d0769e21ee","teamName":"TEAM NAME HERE","players":[],"maxPlayers":4,"started":false,"takenSlots":[]}]
socket.io:socket dispatching an event ["create-lobby",{"id":"d881d972-a341-487d-9831-90d0769e21ee","teamName":"TEAM NAME HERE","players":[],"maxPlayers":4,"started":false,"takenSlots":[]}]

Server:

const server = new Server(server, {
    cors: {
        origin: "*",
        methods: ["GET", "POST"],
    },
    transports: ["polling", "websocket"],
    allowEIO3: true,
    allowUpgrades: true,
});
const server: http.Server = httpServer.initialise();
server.listen(env.PORT, () => {
   console.log(`Server listening on port ${env.PORT}`);
});
const io = sockets.start(server);

Client:

this.socket = io();
this.socket.emit(SocketEvents.JOIN_ROOM, "prelobby");
this.socket.on(SocketEvents.LOBBY_CREATED, (lobbyData) => {
      console.log("received lobby data", lobbyData);
      LobbyData.data = lobbyData;
      this.cameras.main.fadeOut(1000);
      this.socket.emit(SocketEvents.LEAVE_ROOM, "prelobby");
});

vite.config.js

export default defineConfig({
  plugins: [vue({
    template: {
      transformAssetUrls: {
        includeAbsolute: false,
      }
    }
  })],
  server: {
    proxy: {
      '/api': {
        target: `http://localhost:4000`,
        changeOrigin: true,
      },
      '/socket.io': {
        target: `ws://localhost:4000`,
        ws: true,
        changeOrigin: true,
      }
    },
  },
  build: {
    rollupOptions: {
      external: [],
    }
  }
})


来源: stackexchange

问:
Linking a local vue.js to my html: two links; both can reach the file, but only one can read the Vue
```<code><script src="./lib/vue.js"></script>
<script src="../day01/lib/vue.js"></script>
</code>```

You can see two links, both can head to the file in my computer, but the first can read Vue, the other can not.

second one will show bugs like the picture below

First one can show the result normally.
what's the difference between them?

ContentLicense: CC BY-SA 4.0


问:
how to save the output image in browser cache and display it from cache on similar subsequent requests instead of reprocessing it everytime
I have a local server with express in node js that takes a url with query data image name, width and height and resize that image with sharp according to the query data from the request url and respond with the resized image now i want this to store the image into the browser cache and upon subsequent requests if the request already made before with the same params it displays the image from the cache without reprocessing it again

here is my code: this is the img route module

```<code>import express from "express";
import resizeImage from "./imgProcessing";
const img = express.Router();

img.get("/", (req, res) => {
  const queryData = req.query;
  resizeImage(
    queryData.filename as string,
    Number(queryData.width) as number,
    Number(queryData.height) as number
  ).then(err => {
    if (err) {
      res.send("the image not found please enter a valid image name");
      return;
    }
    res.sendFile(`${queryData.filename}-${queryData.width}x${queryData.height}.jpg`, {
      root: "imgs/thumbs",
    });

  });
});
export default img;
</code>```

this is the img processing module

```<code>import sharp from "sharp";

const resizeImage = async function (
    filename: string,
    width: number,
    height: number
  ): Promise<unknown> {
    try {
      const path = `./imgs/${filename}.jpg`;
        await sharp(path)
        .resize({
          width: width,
          height: height,
          fit: "fill",
        })
        .toFile(`./imgs/thumbs/${filename}-${width}x${height}.jpg`);

    } catch (err) {
        console.log(err);
      return err;
    }
};

export default resizeImage;

</code>```

I tried to use express.static() method and set the max-age option to 86400 * 30 but still in the network tap in the developers tool cache-control, max-age=0, I also want to access this cache after to compare it with the req url to prevent unnecessary reprocessing

Body:
I have a local server with express in node js that takes a url with query data image name, width and height and resize that image with sharp according to the query data from the request url and respond with the resized image now i want this to store the image into the browser cache and upon subsequent requests if the request already made before with the same params it displays the image from the cache without reprocessing it again

here is my code: this is the img route module

import express from "express";
import resizeImage from "./imgProcessing";
const img = express.Router();

img.get("/", (req, res) => {
  const queryData = req.query;
  resizeImage(
    queryData.filename as string,
    Number(queryData.width) as number,
    Number(queryData.height) as number
  ).then(err => {
    if (err) {
      res.send("the image not found please enter a valid image name");
      return;
    }
    res.sendFile(`${queryData.filename}-${queryData.width}x${queryData.height}.jpg`, {
      root: "imgs/thumbs",
    });

  });
});
export default img;

this is the img processing module

import sharp from "sharp";

const resizeImage = async function (
    filename: string,
    width: number,
    height: number
  ): Promise<unknown> {
    try {
      const path = `./imgs/${filename}.jpg`;
        await sharp(path)
        .resize({
          width: width,
          height: height,
          fit: "fill",
        })
        .toFile(`./imgs/thumbs/${filename}-${width}x${height}.jpg`);

    } catch (err) {
        console.log(err);
      return err;
    }
};

export default resizeImage;

I tried to use express.static() method and set the max-age option to 86400 * 30 but still in the network tap in the developers tool cache-control, max-age=0, I also want to access this cache after to compare it with the req url to prevent unnecessary reprocessing


问:
Pandoc powerpoint with template : title slide is blank
I'm using pandoc to write a slideshow as Markdown and then export it as Powerpoint file with a .potx template, through the --reference-doc as mentionned in Pandoc's documentation.

Everything is working fine, except that the title slide is blank in the result. It correclty uses the "Title Slide" master slide from the template, but the title, presenter name and dates, which are specified in the pandoc metadata are not inserted.

If I remove the master slide from my template, the data is rendered correctly but using the "Standard Slide" master slide.

Any clue about this ?


问:
My firebase writes & reads are exploding without any indications, any ideas?
My app has stopped working and my console is giving errors stating that I've reached my quota. I have checked my dashboard on firebase and seen that in the last couple of days (without explanation) my reads and writes have exploded. No more users, no more content.

Below is a one day difference between normal expected behaviour and a complete overload.

Before:

After:

Any ideas?

I tried reviewing my code but I haven't made any changes that would affect the database...

Most likely culprit:

```<code>class FeedViewModel: ObservableObject {
    @Published var posts = [Post]()
    @Published var stories = [Story]()

    let service = PostService()
    let userService = UserService()

    init() {
        fetchPosts()
        fetchStories()
    }

    func fetchPosts() {
        service.fetchPosts { posts in
            self.posts = posts

            for i in 0 ..< posts.count {
                let uid = posts[i].uid

                self.userService.fetchUser(withUid: uid) { user in
                    self.posts[i].user = user

                }
            }
        }
    }

    func fetchStories() {
        service.fetchStories { stories in
            self.stories = stories

            for i in 0 ..< stories.count {
                let uid = stories[i].uid

                self.userService.fetchUser(withUid: uid) { user in
                    self.stories[i].user = user

                }
            }
        }
    }
    }
</code>```

I added a print statement and it was sent to the console 40 or so times.

Body:
My app has stopped working and my console is giving errors stating that I've reached my quota. I have checked my dashboard on firebase and seen that in the last couple of days (without explanation) my reads and writes have exploded. No more users, no more content.

Below is a one day difference between normal expected behaviour and a complete overload.

Before:

After:

Any ideas?

I tried reviewing my code but I haven't made any changes that would affect the database...

Most likely culprit:

class FeedViewModel: ObservableObject {
    @Published var posts = [Post]()
    @Published var stories = [Story]()

    let service = PostService()
    let userService = UserService()

    init() {
        fetchPosts()
        fetchStories()
    }

    func fetchPosts() {
        service.fetchPosts { posts in
            self.posts = posts

            for i in 0 ..< posts.count {
                let uid = posts[i].uid

                self.userService.fetchUser(withUid: uid) { user in
                    self.posts[i].user = user

                }
            }
        }
    }

    func fetchStories() {
        service.fetchStories { stories in
            self.stories = stories

            for i in 0 ..< stories.count {
                let uid = stories[i].uid

                self.userService.fetchUser(withUid: uid) { user in
                    self.stories[i].user = user

                }
            }
        }
    }
    }

I added a print statement and it was sent to the console 40 or so times.


问:
Angular web app 13 ngx-barcode-scanner doesn't work on mobile version
Hello I have a problem with ngx-barcode-scanner.

I install ngx-barcode-scanner no matter what version of angular (currently 13). After installing and creating a simple desktop application (chrome) everything works fine. Unfortunately, opening a web application on a mobile phone the library does not work properly.
The browser does not even ask for permissions to use the camera.
On this demo it works correctly on my phone and on me it doesn't anymore:
https://julienboulay.github.io/ngx-barcode-scanner/livestream

Will someone tell me if it is at all feasible to create a web app with abrcode/qrcode scanning capability using mobile without creating a native app? Maybe I am doing something wrong please help and regards.

app.module.ts

```<code>import { QuaggaJSResultObject } from '@ericblade/quagga2';
import { BarcodeScannerLivestreamComponent } from "ngx-barcode-scanner";

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
@ViewChild(BarcodeScannerLivestreamComponent)
barcodeScanner!: BarcodeScannerLivestreamComponent;
barcodeValue: any
name = 'Angular';
torch = false;
wasFound = true
availableDevices!: MediaDeviceInfo[];
deviceCurrent!: MediaDeviceInfo;

@Input() deviceId!: string;
ngAfterViewInit() {
 this.barcodeScanner.start();
}

onValueChanges(result: QuaggaJSResultObject) {
 this.barcodeValue = result.codeResult.code;
 if (result.codeResult.code) {
   this.wasFound = false;
 }
}

}
</code>```

app.module.html

```<code><barcode-scanner-livestream [deviceId]="deviceId" [type]="['code_128', 'code_39', 'ean_8']"
  [errorFilter]="{ median: 0.08, threshold: 0.1 }" (valueChanges)="onValueChanges($event)"
  [torch]="torch"></barcode-scanner-livestream>
<div [hidden]="!barcodeValue">
  {{ barcodeValue }}
</div>
<video autoplay="true" id="videoElement">
</video>```

I would like ngx-barcode-scanner to work for me using the webcam and using the phone's camera.
```

Body:
Hello I have a problem with ngx-barcode-scanner.

I install ngx-barcode-scanner no matter what version of angular (currently 13). After installing and creating a simple desktop application (chrome) everything works fine. Unfortunately, opening a web application on a mobile phone the library does not work properly.
The browser does not even ask for permissions to use the camera.
On this demo it works correctly on my phone and on me it doesn't anymore:
https://julienboulay.github.io/ngx-barcode-scanner/livestream

Will someone tell me if it is at all feasible to create a web app with abrcode/qrcode scanning capability using mobile without creating a native app? Maybe I am doing something wrong please help and regards.

app.module.ts

import { QuaggaJSResultObject } from '@ericblade/quagga2';
import { BarcodeScannerLivestreamComponent } from "ngx-barcode-scanner";

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
@ViewChild(BarcodeScannerLivestreamComponent)
barcodeScanner!: BarcodeScannerLivestreamComponent;
barcodeValue: any
name = 'Angular';
torch = false;
wasFound = true
availableDevices!: MediaDeviceInfo[];
deviceCurrent!: MediaDeviceInfo;

@Input() deviceId!: string;
ngAfterViewInit() {
 this.barcodeScanner.start();
}

onValueChanges(result: QuaggaJSResultObject) {
 this.barcodeValue = result.codeResult.code;
 if (result.codeResult.code) {
   this.wasFound = false;
 }
}

}

app.module.html

<barcode-scanner-livestream [deviceId]="deviceId" [type]="['code_128', 'code_39', 'ean_8']"
  [errorFilter]="{ median: 0.08, threshold: 0.1 }" (valueChanges)="onValueChanges($event)"
  [torch]="torch"></barcode-scanner-livestream>

  {{ barcodeValue }}

<video autoplay="true" id="videoElement">
</video>```

I would like ngx-barcode-scanner to work for me using the webcam and using the phone's camera.


问:
How can I sort dictionary
I have an array of names of months. I need to create dictionary with key of type Int and value of type String. With the help of for loop I have to set value to be an element of month’s array and key to be an index. I’ve done that, but I need to sort dictionary. So I created sortWithKeys function, but it sort incorrect.

```<code>var month = ["January", "February", "March", "April", "May", "June", "July", "August" ,"September" ,"October", "November", "December"]

var monthDict: [Int:String] = [:]

    for j in 0..<12 {
        monthDict[j + 1] = month[j]
    }

func sortWithKeys(_ dict: [Int: String]) -> [Int: String] {
    let sorted = dict.sorted(by: { $0.key < $1.key })
    var newDict: [Int: String] = [:]
    for sortedDict in sorted {
        newDict[sortedDict.key] = sortedDict.value
    }
    return newDict
}

print(sortWithKeys(monthDict))
</code>```

Title: How can I sort dictionary

Body:
I have an array of names of months. I need to create dictionary with key of type Int and value of type String. With the help of for loop I have to set value to be an element of month’s array and key to be an index. I’ve done that, but I need to sort dictionary. So I created sortWithKeys function, but it sort incorrect.

var month = ["January", "February", "March", "April", "May", "June", "July", "August" ,"September" ,"October", "November", "December"]

var monthDict: [Int:String] = [:]

    for j in 0..<12 {
        monthDict[j + 1] = month[j]
    }

func sortWithKeys(_ dict: [Int: String]) -> [Int: String] {
    let sorted = dict.sorted(by: { $0.key < $1.key })
    var newDict: [Int: String] = [:]
    for sortedDict in sorted {
        newDict[sortedDict.key] = sortedDict.value
    }
    return newDict
}

print(sortWithKeys(monthDict))


问:
Wait for directLine.activity$ to complete before going to next step
I'm using the following code to listen to activities sent from the bot:

```<code>/* Listen to activities sent from the bot */
directline.activity$
  .filter(activity => activity.type === 'message' && activity.from.id === botId)
  .subscribe(message => {
    if (message) {
      console.log("Reply", message)
    twiml.message(message);
    }
});
</code>```

It works but my code is proceeded to send the response (see below) before the activity listener completes:

```<code>context.res = {

       headers: { 'Content-Type': 'application/xml' },
       body: twiml.toString()
    };
</code>```

The "twiml.message" part is assigning the response syntax to confirm with Twilio.

I tried "let x = await directline.activity$" but it did not work.

Can anyone point me in the right direction about waiting for the process to finish before going to the next step in the code?

This is my full implementation:

```<code>async function step2() {
/* Listen to activities sent from the bot */
directline.activity$
  .filter(activity => activity.type === 'message' && activity.from.id === botId)
  .subscribe(message => {
    if (message) {
      console.log("Reply", message)
    twiml.message(message);
    }
});

}

return step2().then(function(response) {

    context.res = {

       headers: { 'Content-Type': 'application/xml' },
       body: twiml.toString()
    };

}) //end return step2
</code>```

I thought by using return step2 and "async function step2" it should wait for everything to complete before sending the response.

Body:
I'm using the following code to listen to activities sent from the bot:

/* Listen to activities sent from the bot */
directline.activity$
  .filter(activity => activity.type === 'message' && activity.from.id === botId)
  .subscribe(message => {
    if (message) {
      console.log("Reply", message)
    twiml.message(message);
    }
});

It works but my code is proceeded to send the response (see below) before the activity listener completes:

context.res = {

       headers: { 'Content-Type': 'application/xml' },
       body: twiml.toString()
    };

The "twiml.message" part is assigning the response syntax to confirm with Twilio.

I tried "let x = await directline.activity$" but it did not work.

Can anyone point me in the right direction about waiting for the process to finish before going to the next step in the code?

This is my full implementation:

async function step2() {
/* Listen to activities sent from the bot */
directline.activity$
  .filter(activity => activity.type === 'message' && activity.from.id === botId)
  .subscribe(message => {
    if (message) {
      console.log("Reply", message)
    twiml.message(message);
    }
});

}

return step2().then(function(response) {

    context.res = {

       headers: { 'Content-Type': 'application/xml' },
       body: twiml.toString()
    };

}) //end return step2

I thought by using return step2 and "async function step2" it should wait for everything to complete before sending the response.


问:
Can't receive video on webrtc when I toggle camera
I'm trying to write a method to toggle camera for turn on/off the camera.

Call Peer

```<code>const callPeer = (myPeer, peerId, myVideoStream, addToCalls = true) => {
    const call = myPeer.call(peerId, myVideoStream);
    if (addToCalls) {
        let existingCall = myPeer.calls.find((existingCall) => existingCall.peer == peerId);
        if (existingCall)
            myPeer.calls.splice(myPeer.calls.indexOf(existingCall), 1);
        myPeer.calls.push(call);
        call.on('stream', peerVideoStream => {
            let userVideoElement = $("video[data-peer='" + peerId + "']")[0];
            userVideoElement.srcObject = peerVideoStream;
        });
    }
}
</code>```

Answer Call

```<code>const answerCall = (call, addToCalls = true) => {
    call.answer(myVideoStream);
    if (addToCalls) {
        let existingCall = myPeer.calls.find((existingCall) => existingCall.peer == call.peer);
        if (existingCall)
            myPeer.calls.splice(myPeer.calls.indexOf(existingCall), 1);
        myPeer.calls.push(call);
    }
    call.on('stream', userVideoStream => {
        let userVideoElement = $("video[data-peer='" + call.peer + "']")[0];
        userVideoElement.srcObject = userVideoStream;
    });
}
</code>```

Toggle Camera

```<code>const toggleCamera = async (isOpened, peerId, isMuted) => {
    let oldStream = myVideoStream;
    myVideoStream = await navigator.mediaDevices.getUserMedia({
        video: !isOpened,
        audio: true
    });
    myPeer.calls.forEach((call) => {
        call.peerConnection.removeStream(oldStream);
        call.peerConnection.addStream(myVideoStream);
    });
    oldStream.getTracks().forEach((track) => {
        track.stop();
    });
    let myVideoElement = document.querySelector("video[data-peer='" + peerId + "']");
    myVideoElement.srcObject = myVideoStream;
    myVideoElement.muted = true;
    if (isOpened)
        $("#video").removeClass("bg-primary").attr("data-video", "closed");
    else
        $("#video").addClass("bg-primary").attr("data-video", "opened");
    ws.send(JSON.stringify({
        type: isOpened ? "video-off" : "video-on"
    }));
    if (isMuted)
        myVideoStream.getAudioTracks()[0].enabled = false;
};
</code>```

When I print the localstream at peer connection, it seems like localstream is switched but when I print the remote stream from other client, Its not changing. So stream event is not runnig.

I also tried to write a event for onaddstream but it also didn't work.

Body:
I'm trying to write a method to toggle camera for turn on/off the camera.

Call Peer

const callPeer = (myPeer, peerId, myVideoStream, addToCalls = true) => {
    const call = myPeer.call(peerId, myVideoStream);
    if (addToCalls) {
        let existingCall = myPeer.calls.find((existingCall) => existingCall.peer == peerId);
        if (existingCall)
            myPeer.calls.splice(myPeer.calls.indexOf(existingCall), 1);
        myPeer.calls.push(call);
        call.on('stream', peerVideoStream => {
            let userVideoElement = $("video[data-peer='" + peerId + "']")[0];
            userVideoElement.srcObject = peerVideoStream;
        });
    }
}

Answer Call

const answerCall = (call, addToCalls = true) => {
    call.answer(myVideoStream);
    if (addToCalls) {
        let existingCall = myPeer.calls.find((existingCall) => existingCall.peer == call.peer);
        if (existingCall)
            myPeer.calls.splice(myPeer.calls.indexOf(existingCall), 1);
        myPeer.calls.push(call);
    }
    call.on('stream', userVideoStream => {
        let userVideoElement = $("video[data-peer='" + call.peer + "']")[0];
        userVideoElement.srcObject = userVideoStream;
    });
}

Toggle Camera

const toggleCamera = async (isOpened, peerId, isMuted) => {
    let oldStream = myVideoStream;
    myVideoStream = await navigator.mediaDevices.getUserMedia({
        video: !isOpened,
        audio: true
    });
    myPeer.calls.forEach((call) => {
        call.peerConnection.removeStream(oldStream);
        call.peerConnection.addStream(myVideoStream);
    });
    oldStream.getTracks().forEach((track) => {
        track.stop();
    });
    let myVideoElement = document.querySelector("video[data-peer='" + peerId + "']");
    myVideoElement.srcObject = myVideoStream;
    myVideoElement.muted = true;
    if (isOpened)
        $("#video").removeClass("bg-primary").attr("data-video", "closed");
    else
        $("#video").addClass("bg-primary").attr("data-video", "opened");
    ws.send(JSON.stringify({
        type: isOpened ? "video-off" : "video-on"
    }));
    if (isMuted)
        myVideoStream.getAudioTracks()[0].enabled = false;
};

When I print the localstream at peer connection, it seems like localstream is switched but when I print the remote stream from other client, Its not changing. So stream event is not runnig.

I also tried to write a event for onaddstream but it also didn't work.


问:
Does ReadyAPI support RAML specification import?
I am trying to explore if the ReadyAPI product by SmartBear supports the import of API definitions written in the RAML specification.

After installing ReadyAPI v. 3.42.2 locally, there is no option to import RAML API definitions. If I select the "determine automatically" dropdown option during import (as shows on the image below), it results in an error.

I found some posts in the SmartBear community indicating that RAML import is possible with help of some plugins, but the post is quite old and the URLs mentioned are giving 404 now.


问:
Why is mockk executing a method when I'm checking for not invoked scenario?
I have a scenario like

```<code>fun someMethod() {
   try {
       val response = callApi.method()
       val output = processResponse(response)
   } catch (throwable: Throwable) {
   }
}
</code>```

Now I'm testing for the scenario when callApi.method() throws an exception and the method processResponse() is not invoked. It is working as expected but mockk is failing

```<code>verify(exactly = 0) { processResponse(any()) }
verify { processResponse(any()) wasNot Called }
</code>```

with this error:

```<code>java.lang.NullPointerException: Parameter specified as non-null is null
</code>```

My question is that why mockk is trying to execute the processResponse() method with a null response from any() when I'm just verifying that the method is not invoked? Are there any other ways to avoid this error? Thanks

Body:
I have a scenario like

fun someMethod() {
   try {
       val response = callApi.method()
       val output = processResponse(response)
   } catch (throwable: Throwable) {
   }
}

Now I'm testing for the scenario when callApi.method() throws an exception and the method processResponse() is not invoked. It is working as expected but mockk is failing

verify(exactly = 0) { processResponse(any()) }
verify { processResponse(any()) wasNot Called }

with this error:

java.lang.NullPointerException: Parameter specified as non-null is null

My question is that why mockk is trying to execute the processResponse() method with a null response from any() when I'm just verifying that the method is not invoked? Are there any other ways to avoid this error? Thanks


问:
Depends_on in Docker Swarm
Is it not possible to be using depends_on in docker swarm?

How can I be performing?

nominatim_db
ports:

${NOMINATIM_DB_PUBLIC_PORT:-5432}:5432
volumes:

nominatim_db_conf:/bitnami/postgresql/conf/conf.d

nominatim_db_data:/bitnami/postgresql
deploy:
placement:
constraints:

node.hostname == ${NOMINATIM_DB_DEPLOY_HOSTNAME}
healthcheck:
test:

/bin/sh

-ç
-exec pg_isready -U "postgres" -h 127.0.0.1 -p 5432
interval: 10s
timeout: 5s
retries: 6
start_period: 30s
depends_on:
generate_nominatim_db_conf:
condition: service_completed_successfully

I have already checked in some searches that it is not used, but how could I be doing

Title: Depends_on in Docker Swarm


问:
How to pass a value to my api page(backend) in Next.js so that it can be used by puppeteer
I am building an app that aggregates the main articles from a few game websites. I initially scrape the main page and get back the article titles and the associated href. These are then mapped so each article is displayed with the title and a button. I don't want to go to the website when I click on my articles. Instead, I would like the articles' body text to be displayed on my page by performing another scrape with the href connected to a specific article.

The "handler" button runs getArticleBody which connects to the api/puppeteer/rockpapershotgun.tsx.

The puppeteer logic in api/puppeteer/rockpapershotgun.tsx works – I get the text I want back from the page when I use the hardcoded test variable "href".

However I would like the string'href'to be dynamic. How do I pass the "a.url" from my index.js file where the "handler" button is into the api page so that puppeteer can use that value in the following line of  code below?

```<code> await page.goto(`${href}`)
</code>```

Here is my puppeteer logic in  api/puppeteer/rockpapershotgun

```<code>import { url } from "node:inspector";
import { it } from "node:test";
import puppeteer, { MouseButton } from "puppeteer";
import { useState } from "react";

// TEST Variables - this is where I want to use a.url instead
const href =
  "https://www.rockpapershotgun.com/forspokens-cinematic-trailer-shows-a-world-the-demo-suggests-it-might-not-live-up-to";

async function start() {
  const browser = await puppeteer.launch({ headless: false });
  const page = await browser.newPage();

  // I want this href to be the "a.url" from my pages/index.js file
  await page.goto(`${href}`);

  const bodyText = await page.evaluate(() => {
    return Array.from(document.querySelectorAll(".article_body_content")).map((x) => x.textContent);
  });

  console.log(bodyText);
  await browser.close();
  console.log("finished");
}

start();

export default start;
</code>```

This is my pages/index.js

```<code>import Head from "next/head";
import Image from "next/image";
import { Inter } from "@next/font/google";
import styles from "../styles/Home.module.css";
import Article from "../components/ArticleComponent";
import { useState, useEffect, use } from "react";
import { slice } from "cheerio/lib/api/traversing";
import cheerio, { load } from "cheerio";
import { NextApiRequest, NextApiResponse } from "next/dist/shared/lib/utils";
import Link from "next/link";

const inter = Inter({ subsets: ["latin"] });

export default function Home() {
  const [retrievedArticles, setRetrievedArticles] = useState<Object>([]);
  const [finalArticles, setFinalArticles] = useState<Object>([]);
  const [fetched, setFetched] = useState(false);
  const [href, setHref] = useState("");
  const [post, setPost] = useState("");
  const [loading, setLoading] = useState(false);

  const getUrl = async (url: string) => {
    const res = await fetch(`/api/${url}`);
    const { articles } = await res.json();
    setRetrievedArticles(articles);
    setFetched((fetched) => !fetched);
  };

  const urls: any[] = [];
  const url = Array.isArray(retrievedArticles) ? retrievedArticles.forEach((a: any) => urls.push(a.url)) : [];

  const handler = function (e: { target: any }) {
    const href = e.target.getAttribute("data-href");
    setHref(href);
  };

  const getArticleBody = async (url: string) => {
    const res = await fetch(`/api/puppeteer/rockpapershotgun`);
  };

  useEffect(() => {
    const toComponent =
      Array.isArray(retrievedArticles) &&
      retrievedArticles.map((a, i) => {
        if (i <= 10) {
          return (
            <div className="" key={a.title.slice(5) + i}>
              <div className="bg-orange-200 auto-cols-min h-70 justify-center items-center  rounded-xl m-5">
                <Article title={a.title} url={a.url} sitename={a.sitename} details={a.details} id={i} img={a.img} />
                <Link
                  className="bg-orange-300 text-slate-800 text-xl  p-3 rounded flex justify-center hover:bg-orange-400"
                  href={a.url}
                >
                  Read
                </Link>

                <button
                  className="bg-orange-500 rounded flex  p-4"
                  data-key={i}
                  data-href={a.url}
                  onClick={() => {
                    getArticleBody(a.url);
                  }}
                >
                  Handler
                </button>
              </div>
            </div>
          );
        }
        if (i > 10) return;
      });

    setFinalArticles(toComponent);
  }, [fetched, retrievedArticles]);

  return (
    <>
      <div className="bg-slate-900  justify-center items-center p-20 flex flex-col">
        <h1 className="sm:text-4xl md:text-6xl xl:text-6-xl text-4xl pb-10 text-slate-100">Gaming News</h1>
        <div className="  flex-col flex gap-6 justify-center items-center pb-10">
          <div className="grid grid-cols-1 sm:grid-cols-3  grid-rows-2 gap-4">
            <button
              onClick={() => {
                getUrl("giantbomb");
              }}
              className="rounded-xl p-5 col-span-2 bg-red-400 hover:bg-slate-600"
            >
              GiantBomb
            </button>
            <button
              onClick={() => {
                getUrl("rockpapershotgun");
              }}
              className="bg-blue-400 col-span-2  sm:col-span-1 rounded-xl  p-5  hover:bg-slate-600"
            >
              Rock Paper Shotgun
            </button>
            <button
              onClick={() => {
                getUrl("destructoid");
              }}
              className="rounded-xl p-5  col-span-2  sm:col-span-1  bg-slate-800 hover:bg-slate-600"
            >
              IGN(not)
            </button>
            <button
              onClick={() => {
                getUrl("destructoid");
              }}
              className="rounded-xl p-5 col-span-2  bg-green-400 hover:bg-slate-600"
            >
              Destructoid
            </button>
            <button
              onClick={() => {
                getUrl("escapist");
              }}
              className="rounded-xl p-5 col-span-2 bg-yellow-400  hover:bg-slate-600"
            >
              The Escapist
            </button>
          </div>
        </div>
        <div className="grid grid-cols-1  sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-4">
          <> {finalArticles}</>
        </div>
      </div>
    </>
  );
}
</code>```

This is my ArticleComponent which mapped and display on my pages/index.js

```<code>import Link from "next/link";
import { ReactElement, JSXElementConstructor, ReactFragment, ReactPortal } from "react";
import { UrlObject } from "url";
import cheerio, { load } from "cheerio";

export default function ArticleComponent(props: {
  url: string;
  title: string;
  sitename: string;
  details: string;
  id: number;
  img: string;
}) {
  const handleClick = async function (url: any) {
    // const response = await fetch(`http://localhost:3000/api/article/${url}`);
    console.log(url);
  };

  return (
    <div className="flex justify-center items-center p-4 ">
      <div className="cursor-pointer text-slate-50 pointer-cursor  bg-slate-900 p-5 g-2 text-2sm flex-col flex justify-center items-center w-56 h-64 rounded-xl">
        <h2 className="text-grey-100 ">{props.title}</h2>

        {/* <h4>{props.id}</h4> */}
        {/* <button onClick={() => handleClick(props.url)} className="bg-orange-400 p-2 rounded-xl">
            Read
          </button> */}
      </div>
    </div>
  );
}
</code>```

Body:
I am building an app that aggregates the main articles from a few game websites. I initially scrape the main page and get back the article titles and the associated href. These are then mapped so each article is displayed with the title and a button. I don't want to go to the website when I click on my articles. Instead, I would like the articles' body text to be displayed on my page by performing another scrape with the href connected to a specific article.

The "handler" button runs getArticleBody which connects to the api/puppeteer/rockpapershotgun.tsx.

The puppeteer logic in api/puppeteer/rockpapershotgun.tsx works – I get the text I want back from the page when I use the hardcoded test variable "href".

However I would like the string'href'to be dynamic. How do I pass the "a.url" from my index.js file where the "handler" button is into the api page so that puppeteer can use that value in the following line of  code below?

 await page.goto(`${href}`)

Here is my puppeteer logic in  api/puppeteer/rockpapershotgun

import { url } from "node:inspector";
import { it } from "node:test";
import puppeteer, { MouseButton } from "puppeteer";
import { useState } from "react";

// TEST Variables - this is where I want to use a.url instead
const href =
  "https://www.rockpapershotgun.com/forspokens-cinematic-trailer-shows-a-world-the-demo-suggests-it-might-not-live-up-to";

async function start() {
  const browser = await puppeteer.launch({ headless: false });
  const page = await browser.newPage();

  // I want this href to be the "a.url" from my pages/index.js file
  await page.goto(`${href}`);

  const bodyText = await page.evaluate(() => {
    return Array.from(document.querySelectorAll(".article_body_content")).map((x) => x.textContent);
  });

  console.log(bodyText);
  await browser.close();
  console.log("finished");
}

start();

export default start;

This is my pages/index.js

import Head from "next/head";
import Image from "next/image";
import { Inter } from "@next/font/google";
import styles from "../styles/Home.module.css";
import Article from "../components/ArticleComponent";
import { useState, useEffect, use } from "react";
import { slice } from "cheerio/lib/api/traversing";
import cheerio, { load } from "cheerio";
import { NextApiRequest, NextApiResponse } from "next/dist/shared/lib/utils";
import Link from "next/link";

const inter = Inter({ subsets: ["latin"] });

export default function Home() {
  const [retrievedArticles, setRetrievedArticles] = useState<Object>([]);
  const [finalArticles, setFinalArticles] = useState<Object>([]);
  const [fetched, setFetched] = useState(false);
  const [href, setHref] = useState("");
  const [post, setPost] = useState("");
  const [loading, setLoading] = useState(false);

  const getUrl = async (url: string) => {
    const res = await fetch(`/api/${url}`);
    const { articles } = await res.json();
    setRetrievedArticles(articles);
    setFetched((fetched) => !fetched);
  };

  const urls: any[] = [];
  const url = Array.isArray(retrievedArticles) ? retrievedArticles.forEach((a: any) => urls.push(a.url)) : [];

  const handler = function (e: { target: any }) {
    const href = e.target.getAttribute("data-href");
    setHref(href);
  };

  const getArticleBody = async (url: string) => {
    const res = await fetch(`/api/puppeteer/rockpapershotgun`);
  };

  useEffect(() => {
    const toComponent =
      Array.isArray(retrievedArticles) &&
      retrievedArticles.map((a, i) => {
        if (i <= 10) {
          return (

                <Link
                  className="bg-orange-300 text-slate-800 text-xl  p-3 rounded flex justify-center hover:bg-orange-400"
                  href={a.url}
                >
                  Read
                </Link>

                <button
                  className="bg-orange-500 rounded flex  p-4"
                  data-key={i}
                  data-href={a.url}
                  onClick={() => {
                    getArticleBody(a.url);
                  }}
                >
                  Handler
                </button>

          );
        }
        if (i > 10) return;
      });

    setFinalArticles(toComponent);
  }, [fetched, retrievedArticles]);

  return (
    <>

Gaming News

            <button
              onClick={() => {
                getUrl("giantbomb");
              }}
              className="rounded-xl p-5 col-span-2 bg-red-400 hover:bg-slate-600"
            >
              GiantBomb
            </button>
            <button
              onClick={() => {
                getUrl("rockpapershotgun");
              }}
              className="bg-blue-400 col-span-2  sm:col-span-1 rounded-xl  p-5  hover:bg-slate-600"
            >
              Rock Paper Shotgun
            </button>
            <button
              onClick={() => {
                getUrl("destructoid");
              }}
              className="rounded-xl p-5  col-span-2  sm:col-span-1  bg-slate-800 hover:bg-slate-600"
            >
              IGN(not)
            </button>
            <button
              onClick={() => {
                getUrl("destructoid");
              }}
              className="rounded-xl p-5 col-span-2  bg-green-400 hover:bg-slate-600"
            >
              Destructoid
            </button>
            <button
              onClick={() => {
                getUrl("escapist");
              }}
              className="rounded-xl p-5 col-span-2 bg-yellow-400  hover:bg-slate-600"
            >
              The Escapist
            </button>

          <> {finalArticles}</>

    </>
  );
}

This is my ArticleComponent which mapped and display on my pages/index.js

import Link from "next/link";
import { ReactElement, JSXElementConstructor, ReactFragment, ReactPortal } from "react";
import { UrlObject } from "url";
import cheerio, { load } from "cheerio";

export default function ArticleComponent(props: {
  url: string;
  title: string;
  sitename: string;
  details: string;
  id: number;
  img: string;
}) {
  const handleClick = async function (url: any) {
    // const response = await fetch(`http://localhost:3000/api/article/${url}`);
    console.log(url);
  };

  return (

{props.title}

        {/*
{props.id}
 */}
        {/* <button onClick={() => handleClick(props.url)} className="bg-orange-400 p-2 rounded-xl">
            Read
          </button> */}

  );
}


问:
File uploader doesn't allow me to upload the same named image twice in a row
I am using FileBase64 react component for uploading files (images), but I have a problem. When I try to upload the same named image twice in a row the file uploader doesn't even trigger. I also tried to upload an image and then change the name of it and try again and then it worked. So I am guessing that the problem is with the file uploader which is not triggered when you try to upload the same NAMED file more times in a row. I have also the function addImageToBase which is just calling an endpoint to send images to the server. I tried to print something on the first line of that function so I can be sure that the problem is not with the function, and the function wasn't triggered at all, so it is a one hundred percent problem with the file uploader.

```<code><FileBase64
  type="file"
  name='image'
  id="file-upload"
  multiple={false}
  accept="image/*"
  onDone={(e) => { setFieldValue("image", e); addImageToBase(e) }}
/>
</code>```

I don't think that this code is important, but if it will help, here you go. Can anyone tell me how to fix this problem?

Body:
I am using FileBase64 react component for uploading files (images), but I have a problem. When I try to upload the same named image twice in a row the file uploader doesn't even trigger. I also tried to upload an image and then change the name of it and try again and then it worked. So I am guessing that the problem is with the file uploader which is not triggered when you try to upload the same NAMED file more times in a row. I have also the function addImageToBase which is just calling an endpoint to send images to the server. I tried to print something on the first line of that function so I can be sure that the problem is not with the function, and the function wasn't triggered at all, so it is a one hundred percent problem with the file uploader.

<FileBase64
  type="file"
  name='image'
  id="file-upload"
  multiple={false}
  accept="image/*"
  onDone={(e) => { setFieldValue("image", e); addImageToBase(e) }}
/>

I don't think that this code is important, but if it will help, here you go. Can anyone tell me how to fix this problem?


问:
Jetpack Compose TextField - Cursor behind placeholder
Quick question here:

Is this a bug inside jetpack compose TextField or am I missing something:

```<code>@Composable
fun TextFieldWithPlaceholder() {
    val text = rememberSaveable {
        mutableStateOf("")
    }
    Box(modifier = Modifier
        .fillMaxSize()
        .background(MaterialTheme.colors.background)) {

        TextField(
            modifier = Modifier
                .background(Color.Blue)
                .size(width = 300.dp, height = 50.dp),
            value = text.value,
            onValueChange = { value ->
                text.value = value
            },
            singleLine = true,
            colors = TextFieldDefaults.textFieldColors(
                backgroundColor = Color.Transparent,
                focusedIndicatorColor = Color.Transparent,
                unfocusedIndicatorColor = Color.Transparent,
                focusedLabelColor = Color.Transparent,
                unfocusedLabelColor = Color.Transparent,
                placeholderColor = Color.Red,
                cursorColor = Color.White
            ),
            placeholder = {
                Text(
                    modifier = Modifier.fillMaxWidth(),
                    textAlign = TextAlign.Center,
                    text = "Placeholder"
                )
            },
            textStyle = MaterialTheme.typography.body2.copy(textAlign = TextAlign.Center)
        )
    }
}
</code>```

If you build the project with this composable, and tap inside the input field, you'll notice that the cursor is behind the placeholder text (talking about the Z axis). Parts of the cursor are not visible due to "Placeholder" text being on top of it.

Is there a way to force it to be on top of placeholder?

Thanks in advance

Body:
Quick question here:

Is this a bug inside jetpack compose TextField or am I missing something:

@Composable
fun TextFieldWithPlaceholder() {
    val text = rememberSaveable {
        mutableStateOf("")
    }
    Box(modifier = Modifier
        .fillMaxSize()
        .background(MaterialTheme.colors.background)) {

        TextField(
            modifier = Modifier
                .background(Color.Blue)
                .size(width = 300.dp, height = 50.dp),
            value = text.value,
            onValueChange = { value ->
                text.value = value
            },
            singleLine = true,
            colors = TextFieldDefaults.textFieldColors(
                backgroundColor = Color.Transparent,
                focusedIndicatorColor = Color.Transparent,
                unfocusedIndicatorColor = Color.Transparent,
                focusedLabelColor = Color.Transparent,
                unfocusedLabelColor = Color.Transparent,
                placeholderColor = Color.Red,
                cursorColor = Color.White
            ),
            placeholder = {
                Text(
                    modifier = Modifier.fillMaxWidth(),
                    textAlign = TextAlign.Center,
                    text = "Placeholder"
                )
            },
            textStyle = MaterialTheme.typography.body2.copy(textAlign = TextAlign.Center)
        )
    }
}

If you build the project with this composable, and tap inside the input field, you'll notice that the cursor is behind the placeholder text (talking about the Z axis). Parts of the cursor are not visible due to "Placeholder" text being on top of it.

Is there a way to force it to be on top of placeholder?

Thanks in advance


问:
Map php web socket server inside container to the host
I have a docker-compose.yml file that looks like below

```<code>
version: "3.9"

services:
  php-env:
    build: .
    volumes:
      # This is where php files outside will be located inside the container
      - ./src:/var/www/html
    ports:
      - 9000:80

  # mysql_db is also the server name when entering username and password to login to php my admin
  mysql_db:
    image: mysql:latest
    # NOTE: use of "mysql_native_password" is not recommended: https://dev.mysql.com/doc/refman/8.0/en/upgrading-from-previous-series.html#upgrade-caching-sha2-password
    # (this is just an example, not intended to be a production configuration)
    command: --default-authentication-plugin=mysql_native_password
    restart: always
    environment:
      # Mysql root password change below
      MYSQL_ROOT_PASSWORD: root
      # MYSQL_DATABASE: myDb
      # MYSQL_USER: user

  # mysql_db container name above is also the server name when entering username and password to login to php my admin
  # default username is root
  phpmyadmin:
    image: phpmyadmin:latest
    restart: always
    ports:
      # This is the local host port example: http://localhost:9001/
      - 9001:80
    environment:
      - PMA_ARBITRARY=1

</code>```

Below is my Docker file

```<code>FROM php:8.0-apache
# Simple libmaridb install
# RUN apt-get update -y && apt-get install -y libmariadb-dev
RUN apt-get update && \
    apt-get install \
    #libzip is for installing packages
    libzip-dev \
    wget \
    grep \
    curl \
    git \
    unzip \
    libmariadb-dev \
    -y --no-install-recommends

#Install php sockets
RUN docker-php-ext-install sockets

# Install mysqli
# RUN docker-php-ext-install mysqli
# Install pdo mysql
RUN docker-php-ext-install zip pdo_mysql

# copy composer dependency manager installer shell script
COPY ./install-composer.sh ./

# Copy php.ini file
COPY ./php.ini /usr/local/etc/php

# Composer, Git.... will all be installed in php-env container

# Clean up packages and install composer
RUN apt-get purge -y g++ \
    && apt-get autoremove -y \
    && rm -r /var/lib/apt/lists/* \
    && rm -rf /tmp/* \
    && sh ./install-composer.sh \
    && rm ./install-composer.sh

# Change the current working directory
# WORKDIR /var/www/
WORKDIR /var/www/html

</code>```

What i am trying to create is a web socket server and a client where the websocket server writes the time and the client displays the time

Below is my websocket.php server file

```<code><?php

$address = '0.0.0.0';
$port = 12345;

// Create WebSocket.
$server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($server, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($server, $address, $port);
socket_listen($server);
$client = socket_accept($server);

// Send WebSocket handshake headers.
$request = socket_read($client, 5000);
preg_match('#Sec-WebSocket-Key: (.*)\r\n#', $request, $matches);
$key = base64_encode(pack(
    'H*',
    sha1($matches[1] . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')
));
$headers = "HTTP/1.1 101 Switching Protocols\r\n";
$headers .= "Upgrade: websocket\r\n";
$headers .= "Connection: Upgrade\r\n";
$headers .= "Sec-WebSocket-Version: 13\r\n";
$headers .= "Sec-WebSocket-Accept: $key\r\n\r\n";
socket_write($client, $headers, strlen($headers));

// Send messages into WebSocket in a loop.
while (true) {
    sleep(1);
    $content = 'Now: ' . time();
    $response = chr(129) . chr(strlen($content)) . $content;
    socket_write($client, $response);
}

?>

</code>```

Below is my wesocket.html client file

```<code>
<html>
<body>
    <div id="root"></div>
    <script>
        var host = 'ws://0.0.0.0:12345/websocket.php';
        var socket = new WebSocket(host);
        socket.onmessage = function(e) {
            document.getElementById('root').innerHTML = e.data;
        };
    </script>
</body>
</html>

</code>```

Below is how i started my php server where i access the container via docker exec then i start the server

Below is how i am accessing my container

```<code>
docker exec -it dockercomposefiles-php-env-1 bash

</code>```

Below is how i am starting my server

```<code>
php -q websocket.php

</code>```

Below is how i am starting my client server

```<code>
php -S 0.0.0.0:8000 websocket.html

</code>```

Normally if i am using Xamp i should be able to access the client via  http://0.0.0.0:8000/ but if i try to that in a browser its not working because its in the container and not in the host system how can i be able to Map this from the container to the host system so that i can be able to access via the host's system browser

Body:
I have a docker-compose.yml file that looks like below

version: "3.9"

services:
  php-env:
    build: .
    volumes:
      # This is where php files outside will be located inside the container
      - ./src:/var/www/html
    ports:
      - 9000:80

  # mysql_db is also the server name when entering username and password to login to php my admin
  mysql_db:
    image: mysql:latest
    # NOTE: use of "mysql_native_password" is not recommended: https://dev.mysql.com/doc/refman/8.0/en/upgrading-from-previous-series.html#upgrade-caching-sha2-password
    # (this is just an example, not intended to be a production configuration)
    command: --default-authentication-plugin=mysql_native_password
    restart: always
    environment:
      # Mysql root password change below
      MYSQL_ROOT_PASSWORD: root
      # MYSQL_DATABASE: myDb
      # MYSQL_USER: user

  # mysql_db container name above is also the server name when entering username and password to login to php my admin
  # default username is root
  phpmyadmin:
    image: phpmyadmin:latest
    restart: always
    ports:
      # This is the local host port example: http://localhost:9001/
      - 9001:80
    environment:
      - PMA_ARBITRARY=1

Below is my Docker file

FROM php:8.0-apache
# Simple libmaridb install
# RUN apt-get update -y && apt-get install -y libmariadb-dev
RUN apt-get update && \
    apt-get install \
    #libzip is for installing packages
    libzip-dev \
    wget \
    grep \
    curl \
    git \
    unzip \
    libmariadb-dev \
    -y --no-install-recommends

#Install php sockets
RUN docker-php-ext-install sockets

# Install mysqli
# RUN docker-php-ext-install mysqli
# Install pdo mysql
RUN docker-php-ext-install zip pdo_mysql

# copy composer dependency manager installer shell script
COPY ./install-composer.sh ./

# Copy php.ini file
COPY ./php.ini /usr/local/etc/php

# Composer, Git.... will all be installed in php-env container

# Clean up packages and install composer
RUN apt-get purge -y g++ \
    && apt-get autoremove -y \
    && rm -r /var/lib/apt/lists/* \
    && rm -rf /tmp/* \
    && sh ./install-composer.sh \
    && rm ./install-composer.sh

# Change the current working directory
# WORKDIR /var/www/
WORKDIR /var/www/html

What i am trying to create is a web socket server and a client where the websocket server writes the time and the client displays the time

Below is my websocket.php server file

<?php

$address = '0.0.0.0';
$port = 12345;

// Create WebSocket.
$server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($server, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($server, $address, $port);
socket_listen($server);
$client = socket_accept($server);

// Send WebSocket handshake headers.
$request = socket_read($client, 5000);
preg_match('#Sec-WebSocket-Key: (.*)\r\n#', $request, $matches);
$key = base64_encode(pack(
    'H*',
    sha1($matches[1] . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')
));
$headers = "HTTP/1.1 101 Switching Protocols\r\n";
$headers .= "Upgrade: websocket\r\n";
$headers .= "Connection: Upgrade\r\n";
$headers .= "Sec-WebSocket-Version: 13\r\n";
$headers .= "Sec-WebSocket-Accept: $key\r\n\r\n";
socket_write($client, $headers, strlen($headers));

// Send messages into WebSocket in a loop.
while (true) {
    sleep(1);
    $content = 'Now: ' . time();
    $response = chr(129) . chr(strlen($content)) . $content;
    socket_write($client, $response);
}

?>

Below is my wesocket.html client file

Below is how i started my php server where i access the container via docker exec then i start the server

Below is how i am accessing my container

docker exec -it dockercomposefiles-php-env-1 bash

Below is how i am starting my server

php -q websocket.php

Below is how i am starting my client server

php -S 0.0.0.0:8000 websocket.html

Normally if i am using Xamp i should be able to access the client via  http://0.0.0.0:8000/ but if i try to that in a browser its not working because its in the container and not in the host system how can i be able to Map this from the container to the host system so that i can be able to access via the host's system browser


问:
Skip gradle dependency if not found
I am looking for a solution to add optional dependency.
It is possible to add dependency based on property:

```<code>    if (project.hasProperty("isLocal")) {
        implementation("com.example.gradle:dependency1")
    }
</code>```

But I wonder if there isn't something like if dependency exists than use dependency. By default in the absence of dependency I will receive build failed. I would like succeed build for specific libraries which may be missing.

Title: Skip gradle dependency if not found

Body:
I am looking for a solution to add optional dependency.
It is possible to add dependency based on property:

    if (project.hasProperty("isLocal")) {
        implementation("com.example.gradle:dependency1")
    }

But I wonder if there isn't something like if dependency exists than use dependency. By default in the absence of dependency I will receive build failed. I would like succeed build for specific libraries which may be missing.


问:
Is it correct to obtain the 'z-buffer' in computer graphics from the camera coordinate system?
want to do : make function that draw depthmap for 3D object

Problem : Calculate 'Z-buffer' myself

Questions :

Q1. Do I need to transform both the camera and the object to the view(camera) coordinate system to calculate the 'z-buffer' ?

Q2. Since the direction coming out of the monitor by the right-handed coordinate system is the +z direction, the near and far values of the clipping plane are positive value in theory, but is it correct to calculate them as negative value (-far ,-near) in actual calculation?


问:
Azure Data Factory Truncate prescript taking too long as data size increases
I am using Azure Data Factory to load data from the Azure SQL server into a snowflake data warehouse. I am using the truncate table script in the pre-script section of sink data to completely remove the data from the destination and insert all of the data that's in the source table. It's fast when the data size is small but once the data size gets really big the entire copy activity takes hours to complete the sync. What other alternatives can I use to copy data from my source to the destination?

I thought about using Upsert instead of truncating and inserting but since it's going to check each record I assumed that it will be slower.


问:
How to apply label to strip based on symbol present in two parallel array
I have data strips of length 3600. This data strip has two values.

symbols

aux_note
it looks like this - https://extendsclass.com/csv-editor.html#031e1f1

If the aux note is empty, it means consider the previous aux note value.

Above data frame is of length 100000+, I want to create strip(window) of 3600 lengths.

I apply set on each strip to get the unique symbols and aux_note for each strip. 1st array contains symbols, another array contains aux_note.

Symbol value we get every time, but the aux_note value we get only if there is some event. If the aux_note value is empty that means it considers previous aux_note values ( previous event state )

Two array looks like this. When we apply set operation on each strip, it give symbol and aux_note as below.

```<code>sym_list = set(strip['symbol'])
aux_note_list = set(strip['aux_note'])
print(sym_list, cur_aux_note)

{'+', 'V', 'N'} {'', '(N\x00'}
{'N'} {''}
{'N'} {''}
{'N'} {''}
{'N'} {''}
{'N'} {''}
{'N'} {''}
{'V', 'N'} {''}
{'V', 'N'} {''}
{'N'} {''}
{'N'} {''}
{'V', 'N'} {''}
{'N'} {''}
{'A', 'N'} {''}
{'V', 'N'} {''}
{'V', 'N'} {''}
{'N'} {''}
{'N'} {''}
{'N'} {''}
{'N'} {''}
{'V', 'N'} {''}
{'V', 'N'} {''}
{'|', 'V', 'N'} {''}
{'N'} {''}
{'A', 'a', 'N'} {''}
{'V', 'A', 'a', 'N'} {''}
{'A', 'N'} {''}
{'|', 'N'} {''}
{'N', 'A'} {''}
{'N'} {''}
{'N'} {''}
{'N'} {''}
{'N'} {''}
{'N'} {''}
{'N'} {''}
{'N'} {''}
{'N'} {''}
{'A', 'a', 'N'} {''}
{'+', 'A', 'a', 'N'} {'', '(AFIB\x00', '(N\x00'}
{'+', 'A', 'a', 'N'} {'', '(AFIB\x00'}
{'N'} {''}
{'N'} {''}
{'V', 'N'} {''}
{'+', 'F', 'A', 'N'} {'', '(AFIB\x00', '(N\x00'}
{'a', 'N'} {''}
{'N'} {''}
{'N'} {''}
{'N'} {''}
{'N'} {''}
{'N'} {''}
{'+', 'N'} {'', '(AFL'}
{'N'} {''}
{'+', 'V', 'N'} {'', '(AFIB'}
{'N'} {''}
{'N'} {''}
{'N'} {''}
{'a', 'N'} {''}
{'N'} {''}
{'N'} {''}
{'N'} {''}
</code>```

I want to give a label to each strip based on the value present in the strip symbol and aux_note. Aux_note is the decision maker here.

If aux note and symbol are the same, give the strip's label as aux_note. eg { N } { N } then label = N

If Aux note is value other than N, and that value present in symbols, then give aux note values as label. eg. {A,N}{A} then label = A

Give highest priority to A, eg. {A,V,N}{A} then label = A

My attempt

```<code>for i in range(num_strips):
    strp = {}
    strp['signal'] = df_data[i * len_ecg_strip : (i+1)*len_ecg_strip]['MLII']

    temp = df_descr[df_descr['sample'] >= i * len_ecg_strip]
    temp = temp[df_descr['sample'] <= (i+1)*len_ecg_strip]

    strp['sample'] = temp['sample']
    strp['symbol'] = temp['symbol']
    strp['aux_note'] = temp['aux_note']
    prev_aux_note = strip_validate(strp, prev_aux_note)

def strip_validate(strip, pre_aux):
    sym_list = set(strip['symbol'])
    aux_note_list = list(set(strip['aux_note']))
    aux_note_list = list(filter(None,aux_note_list))
    pdb.set_trace()
    if len(aux_note_list)==0:
        cur_aux_note = pre_aux
        label = cur_aux_note
    elif len(aux_note_list) == 1:
        cur_aux_note = aux_note_list[0]
        label = cur_aux_note
    elif 'AFIB' in aux_note_list:
        cur_aux_note = 'AFIB'
        label = cur_aux_note
    else:
        cur_aux_note = aux_note_list[1]
        label = cur_aux_note

    print(sym_list, cur_aux_note)
    return cur_aux_note, label
</code>```

Body:
I have data strips of length 3600. This data strip has two values.

symbols

aux_note
it looks like this - https://extendsclass.com/csv-editor.html#031e1f1

If the aux note is empty, it means consider the previous aux note value.

Above data frame is of length 100000+, I want to create strip(window) of 3600 lengths.

I apply set on each strip to get the unique symbols and aux_note for each strip. 1st array contains symbols, another array contains aux_note.

Symbol value we get every time, but the aux_note value we get only if there is some event. If the aux_note value is empty that means it considers previous aux_note values ( previous event state )

Two array looks like this. When we apply set operation on each strip, it give symbol and aux_note as below.

sym_list = set(strip['symbol'])
aux_note_list = set(strip['aux_note'])
print(sym_list, cur_aux_note)

{'+', 'V', 'N'} {'', '(N\x00'}
{'N'} {''}
{'N'} {''}
{'N'} {''}
{'N'} {''}
{'N'} {''}
{'N'} {''}
{'V', 'N'} {''}
{'V', 'N'} {''}
{'N'} {''}
{'N'} {''}
{'V', 'N'} {''}
{'N'} {''}
{'A', 'N'} {''}
{'V', 'N'} {''}
{'V', 'N'} {''}
{'N'} {''}
{'N'} {''}
{'N'} {''}
{'N'} {''}
{'V', 'N'} {''}
{'V', 'N'} {''}
{'|', 'V', 'N'} {''}
{'N'} {''}
{'A', 'a', 'N'} {''}
{'V', 'A', 'a', 'N'} {''}
{'A', 'N'} {''}
{'|', 'N'} {''}
{'N', 'A'} {''}
{'N'} {''}
{'N'} {''}
{'N'} {''}
{'N'} {''}
{'N'} {''}
{'N'} {''}
{'N'} {''}
{'N'} {''}
{'A', 'a', 'N'} {''}
{'+', 'A', 'a', 'N'} {'', '(AFIB\x00', '(N\x00'}
{'+', 'A', 'a', 'N'} {'', '(AFIB\x00'}
{'N'} {''}
{'N'} {''}
{'V', 'N'} {''}
{'+', 'F', 'A', 'N'} {'', '(AFIB\x00', '(N\x00'}
{'a', 'N'} {''}
{'N'} {''}
{'N'} {''}
{'N'} {''}
{'N'} {''}
{'N'} {''}
{'+', 'N'} {'', '(AFL'}
{'N'} {''}
{'+', 'V', 'N'} {'', '(AFIB'}
{'N'} {''}
{'N'} {''}
{'N'} {''}
{'a', 'N'} {''}
{'N'} {''}
{'N'} {''}
{'N'} {''}

I want to give a label to each strip based on the value present in the strip symbol and aux_note. Aux_note is the decision maker here.

If aux note and symbol are the same, give the strip's label as aux_note. eg { N } { N } then label = N

If Aux note is value other than N, and that value present in symbols, then give aux note values as label. eg. {A,N}{A} then label = A

Give highest priority to A, eg. {A,V,N}{A} then label = A

My attempt

for i in range(num_strips):
    strp = {}
    strp['signal'] = df_data[i * len_ecg_strip : (i+1)*len_ecg_strip]['MLII']

    temp = df_descr[df_descr['sample'] >= i * len_ecg_strip]
    temp = temp[df_descr['sample'] <= (i+1)*len_ecg_strip]

    strp['sample'] = temp['sample']
    strp['symbol'] = temp['symbol']
    strp['aux_note'] = temp['aux_note']
    prev_aux_note = strip_validate(strp, prev_aux_note)

def strip_validate(strip, pre_aux):
    sym_list = set(strip['symbol'])
    aux_note_list = list(set(strip['aux_note']))
    aux_note_list = list(filter(None,aux_note_list))
    pdb.set_trace()
    if len(aux_note_list)==0:
        cur_aux_note = pre_aux
        label = cur_aux_note
    elif len(aux_note_list) == 1:
        cur_aux_note = aux_note_list[0]
        label = cur_aux_note
    elif 'AFIB' in aux_note_list:
        cur_aux_note = 'AFIB'
        label = cur_aux_note
    else:
        cur_aux_note = aux_note_list[1]
        label = cur_aux_note

    print(sym_list, cur_aux_note)
    return cur_aux_note, label


问:
Django - Prefill admin creation form with inline forms
I'm trying to create a form in Django admin, that, when you create a new entry, will take the latest entry, and fill the new entry with that data.
E.g. (Book and Author are just examples)

```<code>class Book(models.Model):
    id = models.Autofield(primary_key=True)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    name = models.Charfield(max_length=200)

class Author(models.Model):
    id = models.Autofield(primary_key=True)
    name = models.Charfield(max_length=200)
</code>```

I then added this to the admin page:

```<code>class BookInline(StackedInline):
    model = Book
    extra = 0

class AuthorAdmin(ModelAdmin):
    inlines = [BookInline]

admin.site.register(Author, AuthorAdmin)
</code>```

Now when I create a new Author, I want the form to be filled in with the last created author and his books
So if said author had 5 books, it would now fill this form with the name of that author, and also add the 5 books.

I was able to fill the author form by adding this to the AuthorAdmin class:

```<code>def get_changeform_initial_data(self, request):
    return model_to_dict(Author.objects.all().get())#Temp
</code>```

But the books are not filled this way. Is it somehow possible, to pass the books into the inline forms?

(Running Django 3.2 and Python 3.9)

Body:
I'm trying to create a form in Django admin, that, when you create a new entry, will take the latest entry, and fill the new entry with that data.
E.g. (Book and Author are just examples)

class Book(models.Model):
    id = models.Autofield(primary_key=True)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    name = models.Charfield(max_length=200)

class Author(models.Model):
    id = models.Autofield(primary_key=True)
    name = models.Charfield(max_length=200)

I then added this to the admin page:

class BookInline(StackedInline):
    model = Book
    extra = 0

class AuthorAdmin(ModelAdmin):
    inlines = [BookInline]

admin.site.register(Author, AuthorAdmin)

Now when I create a new Author, I want the form to be filled in with the last created author and his books
So if said author had 5 books, it would now fill this form with the name of that author, and also add the 5 books.

I was able to fill the author form by adding this to the AuthorAdmin class:

def get_changeform_initial_data(self, request):
    return model_to_dict(Author.objects.all().get())#Temp

But the books are not filled this way. Is it somehow possible, to pass the books into the inline forms?

(Running Django 3.2 and Python 3.9)


问:
What is the best way to include templates inside a plugin and render them for a wordpress shortcode?
I'm trying to build a custom plugin for my website. I like to learn new things about coding and programming so I practice.

I have a plugin which contains two files, this is the structure:

• templates folder > login-form.php

• custom-login.php

Inside login-form.php I'm going to build the login form.
While inside custom-login.php I will insert the functions that the plugin will have to execute.

The first step is to include the login-form.php template inside custom-login.php. Then render the template content to be visible with a shortcode. So below I post the code of what I did, it works. Being new to this I'm not sure if it's the right way. Does anyone have any suggestions for me? I would like to improve this practice with a more practical, safe and efficient way if there is. How is this usually done?

```<code>// Shortcodes
add_shortcode('login_form', 'render_login_form');

/* Render login-form temlate for shortcode */
function render_login_form(){
   $template = require( plugin_dir_path( __FILE__ ) . 'templates/login-form.php' );
   if ( ! empty( $template ) ) {
      include $template;
   }
}
</code>```

Body:
I'm trying to build a custom plugin for my website. I like to learn new things about coding and programming so I practice.

I have a plugin which contains two files, this is the structure:

• templates folder > login-form.php

• custom-login.php

Inside login-form.php I'm going to build the login form.
While inside custom-login.php I will insert the functions that the plugin will have to execute.

The first step is to include the login-form.php template inside custom-login.php. Then render the template content to be visible with a shortcode. So below I post the code of what I did, it works. Being new to this I'm not sure if it's the right way. Does anyone have any suggestions for me? I would like to improve this practice with a more practical, safe and efficient way if there is. How is this usually done?

// Shortcodes
add_shortcode('login_form', 'render_login_form');

/* Render login-form temlate for shortcode */
function render_login_form(){
   $template = require( plugin_dir_path( __FILE__ ) . 'templates/login-form.php' );
   if ( ! empty( $template ) ) {
      include $template;
   }
}


问:
How to properly display a Polars dataframe in VSCode Jupyter Notebook variables inspector
Edit:
This has been filed as bug in the Polars repository:
https://github.com/pola-rs/polars/issues/6152

And the VSCode Jupyter repo:
https://github.com/microsoft/vscode-jupyter/issues/12519

I am testing Python-Polars inside a Jupyter notebook in VSCode.

When I open a data frame from the variable view, it is not formatted correctly.

It shows like this:

Columns and Rows are swapped and the column names are missing.

I would've expected a display similar to pandas data frames like so:

How can I make the Polars dataframe display correctly?


问:
AttributeError: 'NoneType' object has no attribute 'read' raises while using AudioSegment get_file() command
I am currently working on a speech to text project. I tried the code in the following video
"https://www.youtube.com/watch?v=B5A1bMi4dJI", and received :

```<code> Line 29, in <module>
    clip = AudioSegment().from_file(data)

  File "C:\Users\efeba\anaconda3\lib\site-packages\pydub\audio_segment.py", line 213, in __init__
    data = data if isinstance(data, (basestring, bytes)) else data.read()

AttributeError: 'NoneType' object has no attribute 'read'
</code>```

Here is my whole code :

```<code>
import torch
from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
import speech_recognition as sr
from pydub import AudioSegment
import io

r = sr.Recognizer()

tokenizer = Wav2Vec2Processor.from_pretrained("cahya/wav2vec2-base-turkish")
model = Wav2Vec2ForCTC.from_pretrained("cahya/wav2vec2-base-turkish")

with sr.Microphone(sample_rate=16000) as source:
    print("You can start speaking now")
    while True:
        audio = r.listen(source)
        data = io.BytesIO(audio.get_wav_data())

        clip = AudioSegment().from_file(data)
        x    = torch.FloatTensor(clip.get_array_of_samples())

        inputs = tokenizer(x, sampling_rate = 16000, return_tensors = 'pt', padding = 'longest' ).input_values
        logits = model(inputs).logits
        tokens = torch.argmax(logits, dim = -1)
        text   = tokenizer.batch_decode(tokens)

        print(str(text).lower())
</code>```

Error occurs right after I start to talk. I could not understand what causes this error, so i couldn't solve.
Any help is appreciated

Body:
I am currently working on a speech to text project. I tried the code in the following video
"https://www.youtube.com/watch?v=B5A1bMi4dJI", and received :

 Line 29, in <module>
    clip = AudioSegment().from_file(data)

  File "C:\Users\efeba\anaconda3\lib\site-packages\pydub\audio_segment.py", line 213, in __init__
    data = data if isinstance(data, (basestring, bytes)) else data.read()

AttributeError: 'NoneType' object has no attribute 'read'

Here is my whole code :

import torch
from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
import speech_recognition as sr
from pydub import AudioSegment
import io

r = sr.Recognizer()

tokenizer = Wav2Vec2Processor.from_pretrained("cahya/wav2vec2-base-turkish")
model = Wav2Vec2ForCTC.from_pretrained("cahya/wav2vec2-base-turkish")

with sr.Microphone(sample_rate=16000) as source:
    print("You can start speaking now")
    while True:
        audio = r.listen(source)
        data = io.BytesIO(audio.get_wav_data())

        clip = AudioSegment().from_file(data)
        x    = torch.FloatTensor(clip.get_array_of_samples())

        inputs = tokenizer(x, sampling_rate = 16000, return_tensors = 'pt', padding = 'longest' ).input_values
        logits = model(inputs).logits
        tokens = torch.argmax(logits, dim = -1)
        text   = tokenizer.batch_decode(tokens)

        print(str(text).lower())

Error occurs right after I start to talk. I could not understand what causes this error, so i couldn't solve.
Any help is appreciated


问:
How to get SSID for Android 12 API level 31
I am developing app in Xamarin Forms using Visual Studio 2022 for Mac.

For Android 12 API level 31, I am getting SSID as <unknown ssid>

I have added below location permissions in manifest file:

```<code><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
</code>```

I have written below code to get SSID.

```<code>public string GetWifiDetails()
    {
        var wifiManager = (WifiManager)Application.Context
                                .GetSystemService(Context.WifiService);
        return wifiManager.ConnectionInfo.SSID;
    }
</code>```

At runtime it is asking user for both Precise and Approximate location.

I have to select Precise because even if I select Approximate it is asking to select Precise location. So I select Precise location and While using the app option.

With above code, on Android OS which are before Android 12, it is working fine but for Android 12 API level 31 it is showing <unknown ssid>

Somewhere I read that wifiManager.ConnectionInfo is deprecated so I have tried using below code:

```<code>public string GetWifiDetails()
    {
   ConnectivityManager cm = Android.App.Application.Context.GetSystemService(Context.ConnectivityService) as ConnectivityManager;
        Network n = cm.ActiveNetwork;
       // NetworkCapabilities netCaps = cm.GetNetworkCapabilities(n);
        WifiInfo wifiInfo = (WifiInfo)cm.GetNetworkCapabilities(n).TransportInfo;
        return wifiInfo.SSID;
}
</code>```

In this WifiInfo is null but in TransportInfo as well it is showing <unknown ssid>

I think even if wifiManager.ConnectionInfo is deprecated we can use it.

I am not getting what is exactly missing while going through above codes or is any other code or permissions need to add to get SSID for Android 12 API level 31?

Body:
I am developing app in Xamarin Forms using Visual Studio 2022 for Mac.

For Android 12 API level 31, I am getting SSID as <unknown ssid>

I have added below location permissions in manifest file:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

I have written below code to get SSID.

public string GetWifiDetails()
    {
        var wifiManager = (WifiManager)Application.Context
                                .GetSystemService(Context.WifiService);
        return wifiManager.ConnectionInfo.SSID;
    }

At runtime it is asking user for both Precise and Approximate location.

I have to select Precise because even if I select Approximate it is asking to select Precise location. So I select Precise location and While using the app option.

With above code, on Android OS which are before Android 12, it is working fine but for Android 12 API level 31 it is showing <unknown ssid>

Somewhere I read that wifiManager.ConnectionInfo is deprecated so I have tried using below code:

public string GetWifiDetails()
    {
   ConnectivityManager cm = Android.App.Application.Context.GetSystemService(Context.ConnectivityService) as ConnectivityManager;
        Network n = cm.ActiveNetwork;
       // NetworkCapabilities netCaps = cm.GetNetworkCapabilities(n);
        WifiInfo wifiInfo = (WifiInfo)cm.GetNetworkCapabilities(n).TransportInfo;
        return wifiInfo.SSID;
}

In this WifiInfo is null but in TransportInfo as well it is showing <unknown ssid>

I think even if wifiManager.ConnectionInfo is deprecated we can use it.

I am not getting what is exactly missing while going through above codes or is any other code or permissions need to add to get SSID for Android 12 API level 31?


问:
AWS EFS files gone without delete and efs still shows size
I have a multizone EFS which shows that it stores 180mb data in the AWS console.

When Accessing this efs from my beanstalk environment it is just empty desptite it had files in the past and redeploys were also working.

Now suddenly the files dont show but it still says 180mb storage is used.
I was following this guide on how to setup efs: https://github.com/awsdocs/elastic-beanstalk-samples/blob/main/configuration-files/aws-provided/instance-configuration/storage-efs-mountfilesystem.config

Now my efs is just empty and i dont know how.

It is not publicly available.

EDIT

```<code>
$ df -H
Filesystem      Size  Used Avail Use% Mounted on
devtmpfs        507M     0  507M   0% /dev
tmpfs           515M     0  515M   0% /dev/shm
tmpfs           515M   59M  457M  12% /run
tmpfs           515M     0  515M   0% /sys/fs/cgroup
/dev/xvda1      8.6G  3.9G  4.8G  45% /
127.0.0.1:/     9.3E     0  9.3E   0% /efs <- (AWS shows that EFS is 500mb in size)
tmpfs           103M     0  103M   0% /run/user/1000

</code>```

I have tried to restore multiple backups but each backup is only increasing the EFS size but the files are still missing.

EDIT2

```<code>mount | grep nfs
sunrpc on /var/lib/nfs/rpc_pipefs type rpc_pipefs (rw,relatime)
127.0.0.1:/ on /efs type nfs4 (rw,relatime,vers=4.1,rsize=1048576,wsize=1048576,namlen=255,hard,noresvport,proto=tcp,port=20644,timeo=600,retrans=2,sec=sys,clientaddr=127.0.0.1,local_lock=none,addr=127.0.0.1)

</code>```

Body:
I have a multizone EFS which shows that it stores 180mb data in the AWS console.

When Accessing this efs from my beanstalk environment it is just empty desptite it had files in the past and redeploys were also working.

Now suddenly the files dont show but it still says 180mb storage is used.
I was following this guide on how to setup efs: https://github.com/awsdocs/elastic-beanstalk-samples/blob/main/configuration-files/aws-provided/instance-configuration/storage-efs-mountfilesystem.config

Now my efs is just empty and i dont know how.

It is not publicly available.

EDIT

$ df -H
Filesystem      Size  Used Avail Use% Mounted on
devtmpfs        507M     0  507M   0% /dev
tmpfs           515M     0  515M   0% /dev/shm
tmpfs           515M   59M  457M  12% /run
tmpfs           515M     0  515M   0% /sys/fs/cgroup
/dev/xvda1      8.6G  3.9G  4.8G  45% /
127.0.0.1:/     9.3E     0  9.3E   0% /efs <- (AWS shows that EFS is 500mb in size)
tmpfs           103M     0  103M   0% /run/user/1000

I have tried to restore multiple backups but each backup is only increasing the EFS size but the files are still missing.

EDIT2

mount | grep nfs
sunrpc on /var/lib/nfs/rpc_pipefs type rpc_pipefs (rw,relatime)
127.0.0.1:/ on /efs type nfs4 (rw,relatime,vers=4.1,rsize=1048576,wsize=1048576,namlen=255,hard,noresvport,proto=tcp,port=20644,timeo=600,retrans=2,sec=sys,clientaddr=127.0.0.1,local_lock=none,addr=127.0.0.1)


问:
How to force initiate a mongo replica when other replicas are not yet available
I'm trying to set up a simple mongo replication: One primary (mongo-01) and one secondary (mongo-02), both of which is running inside docker.

I bring up mongo-01 which I want as primary and within it, I run the below command as part of a shell script.

```<code>rs.initiate({
 _id: "replica-01",
 members: [
   {_id: 0, host: "mongo-01:27017"},
   {_id: 1, host: "mongo-02:27017"}
 ]
})"
</code>```

I know for a fact that mongo-02 is not yet available (since i've not brought up the docker instance). The above command fails stating that "mongo-02" name or service unknown.

How do I force configure the mongo-01 instance to account for there beinga mongo-02 instance that is currently down/not reachable, and hence mark itself as PRIMARY and move on. Until at some point in time, mongo-02 comes up.

Body:
I'm trying to set up a simple mongo replication: One primary (mongo-01) and one secondary (mongo-02), both of which is running inside docker.

I bring up mongo-01 which I want as primary and within it, I run the below command as part of a shell script.

rs.initiate({
 _id: "replica-01",
 members: [
   {_id: 0, host: "mongo-01:27017"},
   {_id: 1, host: "mongo-02:27017"}
 ]
})"

I know for a fact that mongo-02 is not yet available (since i've not brought up the docker instance). The above command fails stating that "mongo-02" name or service unknown.

How do I force configure the mongo-01 instance to account for there beinga mongo-02 instance that is currently down/not reachable, and hence mark itself as PRIMARY and move on. Until at some point in time, mongo-02 comes up.


问:
XML Namespace for Experimental Features
We've hard forked the XML schema AIXM 4.5 to properly add our up-to-then informal extensions as OFMX. This is finished now and we'll release 1.0 of OFMX soonish.

From here on forward, we'd like to implement future extensions in a separate namespace and (after an extension has proven useful) move it to the main schema as a new release.

Unfortunately, AIXM (and OFMX for that matter) is imposing a strict order on the nodes which seems to complicate things. Here's an example:

<?xml version="1.0" encoding="UTF-8"?>
<OFMX-Snapshot xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://schema.openflightmaps.org/0.1/OFMX-Snapshot.xsd" version="0.1" origin="example" namespace="00000000-0000-0000-0000-000000000000" regions="LF" created="2018-01-01T12:09:15Z" effective="2018-01-04T00:00:00Z" expiration="2018-02-01T00:00:00Z">
  <Ser source="LF|AD|1.6|2018-01-04|1846">
    <SerUid mid="6a3ceb1b-5bbf-1fe4-8926-6fddd6bd1169">
      <UniUid region="LF" mid="d105b6b6-e020-2a73-5ec9-5eb3d5d86499">
        <txtName>STRASBOURG</txtName>
        <codeType>APP</codeType>
      </UniUid>
      <codeType>APP</codeType>
      <noSeq>1</noSeq>
    </SerUid>
    <Stt>
      <codeWorkHr>TIMSH</codeWorkHr>
      <Timsh>
        <codeTimeRef>UTCW</codeTimeRef>
        <dateValidWef>01-01</dateValidWef>
        <dateYearValidWef>2019</dateYearValidWef>
        <dateValidTil>31-12</dateValidTil>
        <dateYearValidTil>2020</dateYearValidTil>
        <codeDay>MON</codeDay>
        <codeDayTil>FRI</codeDayTil>
        <timeWef>08:00</timeWef>
        <codeEventWef>SR</codeEventWef>
        <timeRelEventWef>-30</timeRelEventWef>
        <codeCombWef>L</codeCombWef>
        <timeTil>20:00</timeTil>
        <codeEventTil>SS</codeEventTil>
        <timeRelEventTil>30</timeRelEventTil>
        <codeCombTil>E</codeCombTil>
      </Timsh>
      <txtRmkWorkHr>Consult NOTAM</txtRmkWorkHr>
    </Stt>
    <txtRmk>aka STRASBOURG approche</txtRmk>
  </Ser>
</OFMX-Snapshot>
```
<p>My probably naïve idea is to add a <code>pre</code> namespace like so:</p>
<pre class="lang-xml prettyprint-override"><code><OFMX-Snapshot
  xmlns:pre="http://schema.openflightmaps.org/1.0-pre/OFMX-Experimental.xsd"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:noNamespaceSchemaLocation="http://schema.openflightmaps.org/0.1/OFMX-Snapshot.xsd"
  (...)
>
</code>```

And then add experimental features like so:

<Stt>

bar

  <codeWorkHr>TIMSH</codeWorkHr>
  (...)
</Stt>
```

Validating this results in:

element foo: Schemas validity error : Element '{http://schema.openflightmaps.org/1.0-pre/OFMX-Experimental.xsd}foo': This element is not expected. Expected is ( codeWorkHr ).

Is such a namespace approach for experimental features feasible at all given the way AIXM (and by extension OFMX) is built?

Thanks for your hints!

Title: XML Namespace for Experimental Features

Body:
We've hard forked the XML schema AIXM 4.5 to properly add our up-to-then informal extensions as OFMX. This is finished now and we'll release 1.0 of OFMX soonish.

From here on forward, we'd like to implement future extensions in a separate namespace and (after an extension has proven useful) move it to the main schema as a new release.

Unfortunately, AIXM (and OFMX for that matter) is imposing a strict order on the nodes which seems to complicate things. Here's an example:

<?xml version="1.0" encoding="UTF-8"?>
<OFMX-Snapshot xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://schema.openflightmaps.org/0.1/OFMX-Snapshot.xsd" version="0.1" origin="example" namespace="00000000-0000-0000-0000-000000000000" regions="LF" created="2018-01-01T12:09:15Z" effective="2018-01-04T00:00:00Z" expiration="2018-02-01T00:00:00Z">
  <Ser source="LF|AD|1.6|2018-01-04|1846">
    <SerUid mid="6a3ceb1b-5bbf-1fe4-8926-6fddd6bd1169">
      <UniUid region="LF" mid="d105b6b6-e020-2a73-5ec9-5eb3d5d86499">
        <txtName>STRASBOURG</txtName>
        <codeType>APP</codeType>
      </UniUid>
      <codeType>APP</codeType>
      <noSeq>1</noSeq>
    </SerUid>
    <Stt>
      <codeWorkHr>TIMSH</codeWorkHr>
      <Timsh>
        <codeTimeRef>UTCW</codeTimeRef>
        <dateValidWef>01-01</dateValidWef>
        <dateYearValidWef>2019</dateYearValidWef>
        <dateValidTil>31-12</dateValidTil>
        <dateYearValidTil>2020</dateYearValidTil>
        <codeDay>MON</codeDay>
        <codeDayTil>FRI</codeDayTil>
        <timeWef>08:00</timeWef>
        <codeEventWef>SR</codeEventWef>
        <timeRelEventWef>-30</timeRelEventWef>
        <codeCombWef>L</codeCombWef>
        <timeTil>20:00</timeTil>
        <codeEventTil>SS</codeEventTil>
        <timeRelEventTil>30</timeRelEventTil>
        <codeCombTil>E</codeCombTil>
      </Timsh>
      <txtRmkWorkHr>Consult NOTAM</txtRmkWorkHr>
    </Stt>
    <txtRmk>aka STRASBOURG approche</txtRmk>
  </Ser>
</OFMX-Snapshot>

My probably naïve idea is to add a pre namespace like so:

<OFMX-Snapshot
  xmlns:pre="http://schema.openflightmaps.org/1.0-pre/OFMX-Experimental.xsd"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:noNamespaceSchemaLocation="http://schema.openflightmaps.org/0.1/OFMX-Snapshot.xsd"
  (...)
>

And then add experimental features like so:

<Stt>

bar

  <codeWorkHr>TIMSH</codeWorkHr>
  (...)
</Stt>

Validating this results in:

element foo: Schemas validity error : Element '{http://schema.openflightmaps.org/1.0-pre/OFMX-Experimental.xsd}foo': This element is not expected. Expected is ( codeWorkHr ).

Is such a namespace approach for experimental features feasible at all given the way AIXM (and by extension OFMX) is built?

Thanks for your hints!


问:
How to use MUI Datagrid custom footer component at top instead of bottom
How to move this custom footer to top?

For example: Need grid to look in this order

Header

Footer

Rows