问:
issue while sharing a rabbitmq connection between goroutines with prefork true
I have a go-fiber app that tries to publish messages to RabbitMQ.
And here is the simplified version of the app:

```<code>// main.go
type custom_handler struct {
    RMQConn *rabbitmq.Connection
}

func newHandler(conn *rabbitmq.Connection) custom_handler {
    return custom_handler{
        RMQConn: conn,
    }
}

func main() {
    var hndlr custom_handler
    if !fiber.IsChild() {
        messageq.ConnectMQ()
        hndlr = newHandler(messageq.RMQConn)
        log.Println(messageq.RMQConn) // not nil
    }

    engine := html.New("./static", ".html")
    app := fiber.New(fiber.Config{
        Views:     engine,
        Prefork:   true,  // ATTENTION!!!
    })

    app.Use(cors.New())
    app.Get("/", func(c *fiber.Ctx) error {
        return c.Render("index", fiber.Map{})
    })

    app.Post("/", hndlr.handleFileupload)

    log.Fatal(app.Listen(":8080"))
}

func (hndlr custom_handler) handleFileupload(c *fiber.Ctx) error {
    log.Println(hndlr.RMQConn) // nil
    RMQChan, err := hndlr.RMQConn.Channel()
    if err != nil {
        return err
    }
    defer RMQChan.Close()
}
</code>```

And messageq package looks like this:

```<code>// messageq.go
var RMQConn *rabbitmq.Connection

func ConnectMQ() {
    var err error
    amqpServerURL := os.Getenv("RABBITMQ_SERVER_URL")
    RMQConn, err = rabbitmq.Dial(amqpServerURL)
    if err != nil {
        panic(err)
    }
}
</code>```

afaik, RabbitMQ Connections can be shared between goroutines.
But when I run the app, I get this segmentation violation error:

```<code>producer_1  | panic: runtime error: invalid memory address or nil pointer dereference
producer_1  | [signal SIGSEGV: segmentation violation code=0x1 addr=0x14 pc=0x8ef6db]
imgress-producer_1  |
producer_1  | goroutine 7 [running]:
producer_1  | github.com/rabbitmq/amqp091-go.(*Connection).allocateChannel(0x0)
producer_1  |   /go/pkg/mod/github.com/rabbitmq/amqp091-go@v1.5.0/connection.go:679 +0x5b
producer_1  | github.com/rabbitmq/amqp091-go.(*Connection).openChannel(0x4f46c8?)
producer_1  |   /go/pkg/mod/github.com/rabbitmq/amqp091-go@v1.5.0/connection.go:709 +0x25
producer_1  | github.com/rabbitmq/amqp091-go.(*Connection).Channel(...)
producer_1  |   /go/pkg/mod/github.com/rabbitmq/amqp091-go@v1.5.0/connection.go:736
producer_1  | main.ValidateAndPublish({0xc0000120c8, 0x1, 0xb7aeff?}, 0x1?, {0xc0000e7f38, 0x8}, 0xffffffffffffffff?)
producer_1  |   /app/validate.go:14 +0x8a
producer_1  | main.custom_handler.handleFileupload({0x0?, 0x0?}, 0xc00015f080?)
producer_1  |   /app/main.go:94 +0x4bb
producer_1  | github.com/gofiber/fiber/v2.(*App).next(0xc000221b80, 0xc00009e000)
producer_1  |   /go/pkg/mod/github.com/gofiber/fiber/v2@v2.39.0/router.go:132 +0x1c2
producer_1  | github.com/gofiber/fiber/v2.(*Ctx).Next(0xc0001bcf18?)
producer_1  |   /go/pkg/mod/github.com/gofiber/fiber/v2@v2.39.0/ctx.go:945 +0x53
producer_1  | github.com/gofiber/fiber/v2/middleware/cors.New.func1(0xc00009e000)
producer_1  |   /go/pkg/mod/github.com/gofiber/fiber/v2@v2.39.0/middleware/cors/cors.go:141 +0x286
producer_1  | github.com/gofiber/fiber/v2.(*App).next(0xc000221b80, 0xc00009e000)
producer_1  |   /go/pkg/mod/github.com/gofiber/fiber/v2@v2.39.0/router.go:132 +0x1c2
producer_1  | github.com/gofiber/fiber/v2.(*App).handler(0xc000221b80, 0x485df7?)
producer_1  |   /go/pkg/mod/github.com/gofiber/fiber/v2@v2.39.0/router.go:159 +0x45
producer_1  | github.com/valyala/fasthttp.(*Server).serveConn(0xc0001478c0, {0xc8dd90?, 0xc000012070})
producer_1  |   /go/pkg/mod/github.com/valyala/fasthttp@v1.40.0/server.go:2311 +0x1268
producer_1  | github.com/valyala/fasthttp.(*workerPool).workerFunc(0xc0000000a0, 0xc0000400a0)
producer_1  |   /go/pkg/mod/github.com/valyala/fasthttp@v1.40.0/workerpool.go:224 +0xa9
producer_1  | github.com/valyala/fasthttp.(*workerPool).getCh.func1()
producer_1  |   /go/pkg/mod/github.com/valyala/fasthttp@v1.40.0/workerpool.go:196 +0x38
producer_1  | created by github.com/valyala/fasthttp.(*workerPool).getCh
producer_1  |   /go/pkg/mod/github.com/valyala/fasthttp@v1.40.0/workerpool.go:195 +0x1b0
</code>```

I am assuming because I do Prefork: true while creating the app, every request will be handled in a separate goroutine, and it seems that at the moment handler can not access the connection.

So, can somebody point to something that I am missing? How can I make the RabbitMQ connection available for the handler?

Body:
I have a go-fiber app that tries to publish messages to RabbitMQ.
And here is the simplified version of the app:

// main.go
type custom_handler struct {
    RMQConn *rabbitmq.Connection
}

func newHandler(conn *rabbitmq.Connection) custom_handler {
    return custom_handler{
        RMQConn: conn,
    }
}

func main() {
    var hndlr custom_handler
    if !fiber.IsChild() {
        messageq.ConnectMQ()
        hndlr = newHandler(messageq.RMQConn)
        log.Println(messageq.RMQConn) // not nil
    }

    engine := html.New("./static", ".html")
    app := fiber.New(fiber.Config{
        Views:     engine,
        Prefork:   true,  // ATTENTION!!!
    })

    app.Use(cors.New())
    app.Get("/", func(c *fiber.Ctx) error {
        return c.Render("index", fiber.Map{})
    })

    app.Post("/", hndlr.handleFileupload)

    log.Fatal(app.Listen(":8080"))
}

func (hndlr custom_handler) handleFileupload(c *fiber.Ctx) error {
    log.Println(hndlr.RMQConn) // nil
    RMQChan, err := hndlr.RMQConn.Channel()
    if err != nil {
        return err
    }
    defer RMQChan.Close()
}

And messageq package looks like this:

// messageq.go
var RMQConn *rabbitmq.Connection

func ConnectMQ() {
    var err error
    amqpServerURL := os.Getenv("RABBITMQ_SERVER_URL")
    RMQConn, err = rabbitmq.Dial(amqpServerURL)
    if err != nil {
        panic(err)
    }
}

afaik, RabbitMQ Connections can be shared between goroutines.
But when I run the app, I get this segmentation violation error:

producer_1  | panic: runtime error: invalid memory address or nil pointer dereference
producer_1  | [signal SIGSEGV: segmentation violation code=0x1 addr=0x14 pc=0x8ef6db]
imgress-producer_1  |
producer_1  | goroutine 7 [running]:
producer_1  | github.com/rabbitmq/amqp091-go.(*Connection).allocateChannel(0x0)
producer_1  |   /go/pkg/mod/github.com/rabbitmq/amqp091-go@v1.5.0/connection.go:679 +0x5b
producer_1  | github.com/rabbitmq/amqp091-go.(*Connection).openChannel(0x4f46c8?)
producer_1  |   /go/pkg/mod/github.com/rabbitmq/amqp091-go@v1.5.0/connection.go:709 +0x25
producer_1  | github.com/rabbitmq/amqp091-go.(*Connection).Channel(...)
producer_1  |   /go/pkg/mod/github.com/rabbitmq/amqp091-go@v1.5.0/connection.go:736
producer_1  | main.ValidateAndPublish({0xc0000120c8, 0x1, 0xb7aeff?}, 0x1?, {0xc0000e7f38, 0x8}, 0xffffffffffffffff?)
producer_1  |   /app/validate.go:14 +0x8a
producer_1  | main.custom_handler.handleFileupload({0x0?, 0x0?}, 0xc00015f080?)
producer_1  |   /app/main.go:94 +0x4bb
producer_1  | github.com/gofiber/fiber/v2.(*App).next(0xc000221b80, 0xc00009e000)
producer_1  |   /go/pkg/mod/github.com/gofiber/fiber/v2@v2.39.0/router.go:132 +0x1c2
producer_1  | github.com/gofiber/fiber/v2.(*Ctx).Next(0xc0001bcf18?)
producer_1  |   /go/pkg/mod/github.com/gofiber/fiber/v2@v2.39.0/ctx.go:945 +0x53
producer_1  | github.com/gofiber/fiber/v2/middleware/cors.New.func1(0xc00009e000)
producer_1  |   /go/pkg/mod/github.com/gofiber/fiber/v2@v2.39.0/middleware/cors/cors.go:141 +0x286
producer_1  | github.com/gofiber/fiber/v2.(*App).next(0xc000221b80, 0xc00009e000)
producer_1  |   /go/pkg/mod/github.com/gofiber/fiber/v2@v2.39.0/router.go:132 +0x1c2
producer_1  | github.com/gofiber/fiber/v2.(*App).handler(0xc000221b80, 0x485df7?)
producer_1  |   /go/pkg/mod/github.com/gofiber/fiber/v2@v2.39.0/router.go:159 +0x45
producer_1  | github.com/valyala/fasthttp.(*Server).serveConn(0xc0001478c0, {0xc8dd90?, 0xc000012070})
producer_1  |   /go/pkg/mod/github.com/valyala/fasthttp@v1.40.0/server.go:2311 +0x1268
producer_1  | github.com/valyala/fasthttp.(*workerPool).workerFunc(0xc0000000a0, 0xc0000400a0)
producer_1  |   /go/pkg/mod/github.com/valyala/fasthttp@v1.40.0/workerpool.go:224 +0xa9
producer_1  | github.com/valyala/fasthttp.(*workerPool).getCh.func1()
producer_1  |   /go/pkg/mod/github.com/valyala/fasthttp@v1.40.0/workerpool.go:196 +0x38
producer_1  | created by github.com/valyala/fasthttp.(*workerPool).getCh
producer_1  |   /go/pkg/mod/github.com/valyala/fasthttp@v1.40.0/workerpool.go:195 +0x1b0

I am assuming because I do Prefork: true while creating the app, every request will be handled in a separate goroutine, and it seems that at the moment handler can not access the connection.

So, can somebody point to something that I am missing? How can I make the RabbitMQ connection available for the handler?


来源: stackexchange

问:
How to center a frame on a canvas?
type here

I have been working on a quiz system for my class 12 school project using customtkinter for GUI.
on creating a scrollable frame on canvas the frame is sticking to the bottom right side and not centering
enter image description here

sample code

```<code>    from customtkinter import *
    import tkinter

    center_frame = CTk()
    mainframe = CTkFrame(master=center_frame)
    mainframe.pack(fill=tkinter.BOTH, expand=1)

    mycanvas = CTkCanvas(mainframe)
    mycanvas.pack(side=tkinter.LEFT, fill=tkinter.BOTH, expand=1)
    mycanvas.configure(bg="#292929", highlightthickness=0)

    myscrollbar = CTkScrollbar(mainframe, orientation=tkinter.VERTICAL, command=mycanvas.yview)
    myscrollbar.pack(side=tkinter.RIGHT, fill=tkinter.Y)
    mycanvas.configure(yscrollcommand=myscrollbar.set)
    mycanvas.bind("<Configure>",lambda e: mycanvas.configure(scrollregion=mycanvas.bbox("all")),)
    secondframe = CTkFrame(mycanvas)
    x0 = center_frame.winfo_screenwidth() / 2
    y0 = secondframe.winfo_screenheight() / 2

    mycanvas.create_window((x0, y0), window=secondframe, anchor="n")

    center_frame.mainloop()

</code>```

this is my main project
enter image description here
enter image description here

```<code>x0 = center_frame.winfo_screenwidth() / 2
y0 = secondframe.winfo_screenheight() / 2
</code>```

using this piece of code i was expecting to center the frame as told by another post on this website
but all it did was change the position of the frame from this:
enter image description here

to this:
enter image description here

ContentLicense: CC BY-SA 4.0

Title: How to center a frame on a canvas?

Body:
type here

I have been working on a quiz system for my class 12 school project using customtkinter for GUI.
on creating a scrollable frame on canvas the frame is sticking to the bottom right side and not centering
enter image description here

sample code

    from customtkinter import *
    import tkinter

    center_frame = CTk()
    mainframe = CTkFrame(master=center_frame)
    mainframe.pack(fill=tkinter.BOTH, expand=1)

    mycanvas = CTkCanvas(mainframe)
    mycanvas.pack(side=tkinter.LEFT, fill=tkinter.BOTH, expand=1)
    mycanvas.configure(bg="#292929", highlightthickness=0)

    myscrollbar = CTkScrollbar(mainframe, orientation=tkinter.VERTICAL, command=mycanvas.yview)
    myscrollbar.pack(side=tkinter.RIGHT, fill=tkinter.Y)
    mycanvas.configure(yscrollcommand=myscrollbar.set)
    mycanvas.bind("<Configure>",lambda e: mycanvas.configure(scrollregion=mycanvas.bbox("all")),)
    secondframe = CTkFrame(mycanvas)
    x0 = center_frame.winfo_screenwidth() / 2
    y0 = secondframe.winfo_screenheight() / 2

    mycanvas.create_window((x0, y0), window=secondframe, anchor="n")

    center_frame.mainloop()

this is my main project
enter image description here
enter image description here

x0 = center_frame.winfo_screenwidth() / 2
y0 = secondframe.winfo_screenheight() / 2

using this piece of code i was expecting to center the frame as told by another post on this website
but all it did was change the position of the frame from this:
enter image description here

to this:
enter image description here


问:
Password Encrypted Instagram with Burp Suite
image

I was trying to see if it is possible to check the username and the password on the login form of Instagram by making a request from Burp suite. Apparently, the username is clean but the password field seems to be encrypted with evp_AES_256 format. We cab clearly see enc_password=(encryption).

Is there a way to replace the encryption for adding password as a payload?

I saw some script with the following format >

```<code> 'enc_password': f'#PWD_INSTAGRAM_BROWSER:0:{time}:<PLAIN PASSWORD HERE>'
```(https://i.stack.imgur.com/VSCYT.png)](https://www.stackoverflow.com/)

i tried to replace the same code on enc_password but the payload does not work!

I tried on many forum and google
```

Body:
image

I was trying to see if it is possible to check the username and the password on the login form of Instagram by making a request from Burp suite. Apparently, the username is clean but the password field seems to be encrypted with evp_AES_256 format. We cab clearly see enc_password=(encryption).

Is there a way to replace the encryption for adding password as a payload?

I saw some script with the following format >

 'enc_password': f'#PWD_INSTAGRAM_BROWSER:0:{time}:<PLAIN PASSWORD HERE>'
```(https://i.stack.imgur.com/VSCYT.png)](https://www.stackoverflow.com/)

i tried to replace the same code on enc_password but the payload does not work!

I tried on many forum and google


问:
Getting Exception while retrieving Session.SessionID
I am getting an exception usually at night on a new project of mine.  It is deployed to a hosting provider and visable to everyone.

My exception is:

Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the <system.web><httpModules> section in the application configuration.

In my web.config there is:

<pages validateRequest="false" enableSessionState="true"
       enableViewStateMac="true" enableEventValidation="true"
       viewStateEncryptionMode="Always">
```
<p>The exception is happening while getting <code>Session.SessionID</code> within one of my modules.  This module is present on all pages in the application.</p>
<p>The application runs fine when I am here at work - but a night when I am not here this happens. I also never got this error while running application on my local dev machine. So I suspect a bot.  Or possibly, hosting company shutting down services for some reason?</p>
<p>Is there any way to prevent this from happening?  Like</p>
<pre class="lang-cs prettyprint-override"><code>if(Session.Isavailable)
</code>```

or something I can add to my function in programmatically?

Body:
I am getting an exception usually at night on a new project of mine.  It is deployed to a hosting provider and visable to everyone.

My exception is:

Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the <system.web><httpModules> section in the application configuration.

In my web.config there is:

<pages validateRequest="false" enableSessionState="true"
       enableViewStateMac="true" enableEventValidation="true"
       viewStateEncryptionMode="Always">

The exception is happening while getting Session.SessionID within one of my modules.  This module is present on all pages in the application.

The application runs fine when I am here at work - but a night when I am not here this happens. I also never got this error while running application on my local dev machine. So I suspect a bot.  Or possibly, hosting company shutting down services for some reason?

Is there any way to prevent this from happening?  Like

if(Session.Isavailable)

or something I can add to my function in programmatically?


问:
How do you slice an array of a dynamic dimension in numba?
I have a script that looks as following:

```<code>import numba as nb
@nb.njit
def test(v):
    n = 1
    if len(v.shape)>1:
        n = max(n,v.shape[1])
    return n
test(np.array([1,2]))
</code>```

This works fine without the njit decorator, but when I use it like in my example I get the error message

```<code>numba.core.errors.TypingError: Failed in nopython mode pipeline (step: nopython frontend)
tuple index out of range
During: typing of static-get-item at my_script.py (7)

File "my_script.py", line 7:
def test(v):
    <source elided>
        n = max(n,v.shape[1])
        ^
</code>```

How can I rewrite this function to make it dynamically check the shape of my array?

Body:
I have a script that looks as following:

import numba as nb
@nb.njit
def test(v):
    n = 1
    if len(v.shape)>1:
        n = max(n,v.shape[1])
    return n
test(np.array([1,2]))

This works fine without the njit decorator, but when I use it like in my example I get the error message

numba.core.errors.TypingError: Failed in nopython mode pipeline (step: nopython frontend)
tuple index out of range
During: typing of static-get-item at my_script.py (7)

File "my_script.py", line 7:
def test(v):
    <source elided>
        n = max(n,v.shape[1])
        ^

How can I rewrite this function to make it dynamically check the shape of my array?


问:
Displaying BBOX hash in URL
I think I'm doing something wrong in the variables or syntax... i don't know, help me to correct my code. (I'm using Leaflet for the map show)

Desired Behavior

The user should be able to see the BBOX entering the coordinates into the URL, for example:

.com/#013.0,052.0,013.5,052.5

I only care that the BBOX is shown, I don't care that the URL coordinates change when zooming or moving around the map.

My HTML

```<code><!DOCTYPE html>

<html>
  <header>
    <link rel="stylesheet" href="style.css" />

    <link
      rel="stylesheet"
      href="https://unpkg.com/leaflet@1.9.3/dist/leaflet.css"
      integrity="sha256-kLaT2GOSpHechhsozzB+flnD+zUyjE2LlfWPgU04xyI="
      crossorigin=""
    />

    <script
      src="https://unpkg.com/leaflet@1.9.3/dist/leaflet.js"
      integrity="sha256-WBkoXOwTeyKclOHuWtc+i2uENFpDZ9YPdf5Hf+D7ewM="
      crossorigin=""
    ></script>
  </header>

  <body>
    <div id="map"></div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

    <script src="https://unpkg.com/leaflet@1.0.1/dist/leaflet.js"></script>

    <script src="leaflet-hash.js"></script>

    <script>
      var map = L.map("map").setView([42, 12], 4);
      // var hash = new L.hash(map);

      var urlhash = window.location.hash.substring(1).split("/");
      var boundingBox = "";

      L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
        maxZoom: 22,
        minZoom: 1,
        continuousWorld: false,
        noWrap: false,
        attribution:
          'Data by <a href="http://openstreetmap.org">OpenStreetMap</a>, under <a href="http://www.openstreetmap.org/copyright">ODbL</a>.',
        detectRetina: false,
      }).addTo(map);

      var bboxField = L.control({
        position: "bottomleft",
      });

      bboxField.onAdd = function (map) {
        //create div container for control
        var div = L.DomUtil.create("div", "myButtonBar");
        //prevent mouse events from propagating through to the map
        L.DomEvent.disableClickPropagation(div);
        //create custom radio buttons
        div.innerHTML =
          'BBOX (Left (LON) ,Bottom (LAT), Right (LON), Top (LAT), comma separated, with or without decimal point):<br><input type="text" id="bbox_field"/><button id="setDimensions">Display BBOX</button><button id="remove">Remove</button>';

        return div;
      };

      bboxField.addTo(map);
      $(".myButtonBar").css("font-weight", "bold");
      if (urlhash[0] !== "") {
        $("#bbox_field").val(urlhash[0]);

        draw_bbox(urlhash[0]);
      }

      function draw_bbox(box) {
        var myarray = box.split(",");
        var bounds = [
          [myarray[1], myarray[0]],
          [myarray[3], myarray[2]],
        ];

        boundingBox = L.rectangle(bounds, { color: "#ff7800", weight: 1 });
        map.removeLayer(boundingBox);
        boundingBox.addTo(map);
        map.fitBounds(boundingBox.getBounds());
        map.setZoom(map.getZoom() - 1);
      }

      $("#setDimensions").click(function () {
        draw_bbox($("#bbox_field").val());
      });

      $("#bbox_field").keyup(function (event) {
        if (event.keyCode === 13) {
          $("#setDimensions").click();
        }
      });

      // console.log(bbox)
      $("#remove").click(function () {
        map.removeLayer(boundingBox);
      });
    </script>
  </body>
</html>
</code>```

Leaflet Hash Plugin Code

```<code>(function(window) {
    var HAS_HASHCHANGE = (function() {
        var doc_mode = window.documentMode;
        return ('onhashchange' in window) &&
            (doc_mode === undefined || doc_mode > 7);
    })();

    L.hash = function(map) {
        this.onHashChange = L.Util.bind(this.onHashChange, this);

        if (map) {
            this.init(map);
        }
    };

    L.hash.parseHash = function(hash) {
        if(hash.indexOf('#') === 0) {
            hash = hash.substr(1);
        }
        var args = hash.split("/");
        if (args.length == 3) {
            var zoom = parseInt(args[0], 10),
            lat = parseFloat(args[1]),
            lon = parseFloat(args[2]);
            if (isNaN(zoom) || isNaN(lat) || isNaN(lon)) {
                return false;
            } else {
                return {
                    center: new L.LatLng(lat, lon),
                    zoom: zoom
                };
            }
        } else {
            return false;
        }
    };

    L.hash.formatHash = function(map) {
        var center = map.getCenter(),
            zoom = map.getZoom(),
            precision = Math.max(0, Math.ceil(Math.log(zoom) / Math.LN2));

        return "#" + [zoom,
            center.lat.toFixed(precision),
            center.lng.toFixed(precision)
        ].join("/");
    },

    L.hash.prototype = {
        map: null,
        lastHash: null,

        parseHash: L.hash.parseHash,
        formatHash: L.hash.formatHash,

        init: function(map) {
            this.map = map;

            // reset the hash
            this.lastHash = null;
            this.onHashChange();

            if (!this.isListening) {
                this.startListening();
            }
        },

        removeFrom: function(map) {
            if (this.changeTimeout) {
                clearTimeout(this.changeTimeout);
            }

            if (this.isListening) {
                this.stopListening();
            }

            this.map = null;
        },

        onMapMove: function() {
            // bail if we're moving the map (updating from a hash),
            // or if the map is not yet loaded

            if (this.movingMap || !this.map._loaded) {
                return false;
            }

            var hash = this.formatHash(this.map);
            if (this.lastHash != hash) {
                location.replace(hash);
                this.lastHash = hash;
            }
        },

        movingMap: false,
        update: function() {
            var hash = location.hash;
            if (hash === this.lastHash) {
                return;
            }
            var parsed = this.parseHash(hash);
            if (parsed) {
                this.movingMap = true;

                this.map.setView(parsed.center, parsed.zoom);

                this.movingMap = false;
            } else {
                this.onMapMove(this.map);
            }
        },

        // defer hash change updates every 100ms
        changeDefer: 100,
        changeTimeout: null,
        onHashChange: function() {
            // throttle calls to update() so that they only happen every
            // `changeDefer` ms
            if (!this.changeTimeout) {
                var that = this;
                this.changeTimeout = setTimeout(function() {
                    that.update();
                    that.changeTimeout = null;
                }, this.changeDefer);
            }
        },

        isListening: false,
        hashChangeInterval: null,
        startListening: function() {
            this.map.on("moveend", this.onMapMove, this);

            if (HAS_HASHCHANGE) {
                L.DomEvent.addListener(window, "hashchange", this.onHashChange);
            } else {
                clearInterval(this.hashChangeInterval);
                this.hashChangeInterval = setInterval(this.onHashChange, 50);
            }
            this.isListening = true;
        },

        stopListening: function() {
            this.map.off("moveend", this.onMapMove, this);

            if (HAS_HASHCHANGE) {
                L.DomEvent.removeListener(window, "hashchange", this.onHashChange);
            } else {
                clearInterval(this.hashChangeInterval);
            }
            this.isListening = false;
        }
    };
    L.hash = function(map) {
        return new L.hash(map);
    };
    L.map.prototype.addHash = function() {
        this._hash = L.hash(this);
    };
    L.map.prototype.removeHash = function() {
        this._hash.removeFrom();
    };
})(window);
</code>```

Title: Displaying BBOX hash in URL

Body:
I think I'm doing something wrong in the variables or syntax... i don't know, help me to correct my code. (I'm using Leaflet for the map show)

Desired Behavior

The user should be able to see the BBOX entering the coordinates into the URL, for example:

.com/#013.0,052.0,013.5,052.5

I only care that the BBOX is shown, I don't care that the URL coordinates change when zooming or moving around the map.

My HTML

<!DOCTYPE html>

    <link rel="stylesheet" href="style.css" />

    <link
      rel="stylesheet"
      href="https://unpkg.com/leaflet@1.9.3/dist/leaflet.css"
      integrity="sha256-kLaT2GOSpHechhsozzB+flnD+zUyjE2LlfWPgU04xyI="
      crossorigin=""
    />

Leaflet Hash Plugin Code

(function(window) {
    var HAS_HASHCHANGE = (function() {
        var doc_mode = window.documentMode;
        return ('onhashchange' in window) &&
            (doc_mode === undefined || doc_mode > 7);
    })();

    L.hash = function(map) {
        this.onHashChange = L.Util.bind(this.onHashChange, this);

        if (map) {
            this.init(map);
        }
    };

    L.hash.parseHash = function(hash) {
        if(hash.indexOf('#') === 0) {
            hash = hash.substr(1);
        }
        var args = hash.split("/");
        if (args.length == 3) {
            var zoom = parseInt(args[0], 10),
            lat = parseFloat(args[1]),
            lon = parseFloat(args[2]);
            if (isNaN(zoom) || isNaN(lat) || isNaN(lon)) {
                return false;
            } else {
                return {
                    center: new L.LatLng(lat, lon),
                    zoom: zoom
                };
            }
        } else {
            return false;
        }
    };

    L.hash.formatHash = function(map) {
        var center = map.getCenter(),
            zoom = map.getZoom(),
            precision = Math.max(0, Math.ceil(Math.log(zoom) / Math.LN2));

        return "#" + [zoom,
            center.lat.toFixed(precision),
            center.lng.toFixed(precision)
        ].join("/");
    },

    L.hash.prototype = {
        map: null,
        lastHash: null,

        parseHash: L.hash.parseHash,
        formatHash: L.hash.formatHash,

        init: function(map) {
            this.map = map;

            // reset the hash
            this.lastHash = null;
            this.onHashChange();

            if (!this.isListening) {
                this.startListening();
            }
        },

        removeFrom: function(map) {
            if (this.changeTimeout) {
                clearTimeout(this.changeTimeout);
            }

            if (this.isListening) {
                this.stopListening();
            }

            this.map = null;
        },

        onMapMove: function() {
            // bail if we're moving the map (updating from a hash),
            // or if the map is not yet loaded

            if (this.movingMap || !this.map._loaded) {
                return false;
            }

            var hash = this.formatHash(this.map);
            if (this.lastHash != hash) {
                location.replace(hash);
                this.lastHash = hash;
            }
        },

        movingMap: false,
        update: function() {
            var hash = location.hash;
            if (hash === this.lastHash) {
                return;
            }
            var parsed = this.parseHash(hash);
            if (parsed) {
                this.movingMap = true;

                this.map.setView(parsed.center, parsed.zoom);

                this.movingMap = false;
            } else {
                this.onMapMove(this.map);
            }
        },

        // defer hash change updates every 100ms
        changeDefer: 100,
        changeTimeout: null,
        onHashChange: function() {
            // throttle calls to update() so that they only happen every
            // `changeDefer` ms
            if (!this.changeTimeout) {
                var that = this;
                this.changeTimeout = setTimeout(function() {
                    that.update();
                    that.changeTimeout = null;
                }, this.changeDefer);
            }
        },

        isListening: false,
        hashChangeInterval: null,
        startListening: function() {
            this.map.on("moveend", this.onMapMove, this);

            if (HAS_HASHCHANGE) {
                L.DomEvent.addListener(window, "hashchange", this.onHashChange);
            } else {
                clearInterval(this.hashChangeInterval);
                this.hashChangeInterval = setInterval(this.onHashChange, 50);
            }
            this.isListening = true;
        },

        stopListening: function() {
            this.map.off("moveend", this.onMapMove, this);

            if (HAS_HASHCHANGE) {
                L.DomEvent.removeListener(window, "hashchange", this.onHashChange);
            } else {
                clearInterval(this.hashChangeInterval);
            }
            this.isListening = false;
        }
    };
    L.hash = function(map) {
        return new L.hash(map);
    };
    L.map.prototype.addHash = function() {
        this._hash = L.hash(this);
    };
    L.map.prototype.removeHash = function() {
        this._hash.removeFrom();
    };
})(window);


问:
I have a problem creating the Unity 2d Platformer game. Why doesn't my code work on a tilemap?
I was making a platform that bounces the player after a certain period of time when the player touches it. I attached this code component to the GameObject, which is a tilemap, and it doesn't work properly. What's wrong with my code? The code and scriptable object are as follows.

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ExplosionPlatform : PlatformBase
{
    public float explosionPower = 20f;
    public float waitTime = 1.5f;
    public float colTime = 0f;
    public bool isDamageOnce = false;
    public Vector2 area = new Vector2(2, 2);
    public Vector2 positionModify = new Vector2(1, 0);
    private void OnCollisionEnter2D(Collision2D collision)
    {
        StartCoroutine(Explosion());
    }

    private IEnumerator Explosion()
    {
        Debug.Log("ASDF");

        yield return new WaitForSeconds(waitTime);

        Collider2D[] player = Physics2D.OverlapBoxAll(transform.position + (Vector3)positionModify, area, 0);

        foreach (Collider2D col in player)
        {
            if (col.CompareTag("Player"))
            {
                col.gameObject.GetComponent<Rigidbody2D>().AddForce(Vector2.up * explosionPower, ForceMode2D.Impulse);
                Damage();

                isDamageOnce = true;
                yield return new WaitForSeconds(3f);
                isDamageOnce = false;
            }
        }
    }

    private void OnDrawGizmos()
    {
        Gizmos.color = Color.blue;
        Gizmos.DrawWireCube(transform.position + (Vector3)positionModify, area);
    }
}
</code>```

I have confirmed that the code below works properly on GameObject, which is Unity 2d Sprite. Is there any way to use that code while using the tile map?

Body:
I was making a platform that bounces the player after a certain period of time when the player touches it. I attached this code component to the GameObject, which is a tilemap, and it doesn't work properly. What's wrong with my code? The code and scriptable object are as follows.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ExplosionPlatform : PlatformBase
{
    public float explosionPower = 20f;
    public float waitTime = 1.5f;
    public float colTime = 0f;
    public bool isDamageOnce = false;
    public Vector2 area = new Vector2(2, 2);
    public Vector2 positionModify = new Vector2(1, 0);
    private void OnCollisionEnter2D(Collision2D collision)
    {
        StartCoroutine(Explosion());
    }

    private IEnumerator Explosion()
    {
        Debug.Log("ASDF");

        yield return new WaitForSeconds(waitTime);

        Collider2D[] player = Physics2D.OverlapBoxAll(transform.position + (Vector3)positionModify, area, 0);

        foreach (Collider2D col in player)
        {
            if (col.CompareTag("Player"))
            {
                col.gameObject.GetComponent<Rigidbody2D>().AddForce(Vector2.up * explosionPower, ForceMode2D.Impulse);
                Damage();

                isDamageOnce = true;
                yield return new WaitForSeconds(3f);
                isDamageOnce = false;
            }
        }
    }

    private void OnDrawGizmos()
    {
        Gizmos.color = Color.blue;
        Gizmos.DrawWireCube(transform.position + (Vector3)positionModify, area);
    }
}

I have confirmed that the code below works properly on GameObject, which is Unity 2d Sprite. Is there any way to use that code while using the tile map?


问:
When tracing shared library functions with funclatency, no function names were displayed
When using the bcc tool funclatency, there are unknown function names.
It would be helpful if I could track the entry and return values of a number of functions contained in the library ibverbs (Infiniband).

I use funclatency to print a histogram of the ibverbs functions called by perftest.

https://github.com/iovisor/bcc/tree/master/tools

To send packages between two nodes, I use the perftest.

https://github.com/linux-rdma/perftest

To compile the perftest application, I used the following compiler flags:

```<code>CFLAGS = -g -Wall -D_GNU_SOURCE -O3 -ggdb3 -O2 -fno-omit-frame-pointer
</code>```

System:

```<code>Distributor ID: Debian
Description: Debian GNU/Linux 11 (bullseye)
Release: 11
Codename: bullseye
</code>```

I use funclatency like this:

```<code>sudo funclatency-bpfcc ibverbs:ibv_get*
</code>```

funclatency output:

```<code>Tracing 13 functions for "ibverbs:ibv_get*"... Hit Ctrl-C to end.
Function = b'[unknown]' [784402]
     nsecs               : count     distribution
         0 -> 1          : 0        |                                        |
         2 -> 3          : 0        |                                        |
         4 -> 7          : 0        |                                        |
         8 -> 15         : 0        |                                        |
        16 -> 31         : 0        |                                        |
        32 -> 63         : 0        |                                        |
        64 -> 127        : 0        |                                        |
       128 -> 255        : 0        |                                        |
       256 -> 511        : 0        |                                        |
       512 -> 1023       : 0        |                                        |
      1024 -> 2047       : 468      |****************************            |
      2048 -> 4095       : 512      |******************************          |
      4096 -> 8191       : 664      |****************************************|
      8192 -> 16383      : 332      |********************                    |
     16384 -> 32767      : 14       |                                        |
     32768 -> 65535      : 3        |                                        |
     65536 -> 131071     : 6        |                                        |
    131072 -> 262143     : 0        |                                        |
    262144 -> 524287     : 0        |                                        |
    524288 -> 1048575    : 0        |                                        |
   1048576 -> 2097151    : 0        |                                        |
   2097152 -> 4194303    : 0        |                                        |
   4194304 -> 8388607    : 0        |                                        |
   8388608 -> 16777215   : 1        |                                        |
</code>```

Here is the source code for the translation of a memory address into a function name:

https://github.com/iovisor/bcc/blob/master/src/python/bcc/init.py

```<code>    def sym(addr, pid, show_module=False, show_offset=False, demangle=True):
    """sym(addr, pid, show_module=False, show_offset=False)

    Translate a memory address into a function name for a pid, which is
    returned. When show_module is True, the module name is also included.
    When show_offset is True, the instruction offset as a hexadecimal
    number is also included in the string.

    A pid of less than zero will access the kernel symbol cache.

    Example output when both show_module and show_offset are True:
        "start_thread+0x202 [libpthread-2.24.so]"

    Example output when both show_module and show_offset are False:
        "start_thread"
    """

    #addr is of type stacktrace_build_id
    #so invoke the bsym address resolver
    typeofaddr = str(type(addr))
    if typeofaddr.find('bpf_stack_build_id') != -1:
      sym = bcc_symbol()
      b = bcc_stacktrace_build_id()
      b.status = addr.status
      b.build_id = addr.build_id
      b.u.offset = addr.offset
      res = lib.bcc_buildsymcache_resolve(BPF._bsymcache,
                                          ct.byref(b),
                                          ct.byref(sym))
      if res < 0:
        if sym.module and sym.offset:
          name,offset,module = (None, sym.offset,
                    ct.cast(sym.module, ct.c_char_p).value)
        else:
          name, offset, module = (None, addr, None)
      else:
        name, offset, module = (sym.name, sym.offset,
                                ct.cast(sym.module, ct.c_char_p).value)
    else:
      name, offset, module = BPF._sym_cache(pid).resolve(addr, demangle)

    offset = b"+0x%x" % offset if show_offset and name is not None else b""
    name = name or b"[unknown]"
    name = name + offset
    module = b" [%s]" % os.path.basename(module) \
        if show_module and module is not None else b""
    return name + module
</code>```

How can I read the function name correctly? It should not just return b'[unknown]'!

Body:
When using the bcc tool funclatency, there are unknown function names.
It would be helpful if I could track the entry and return values of a number of functions contained in the library ibverbs (Infiniband).

I use funclatency to print a histogram of the ibverbs functions called by perftest.

https://github.com/iovisor/bcc/tree/master/tools

To send packages between two nodes, I use the perftest.

https://github.com/linux-rdma/perftest

To compile the perftest application, I used the following compiler flags:

CFLAGS = -g -Wall -D_GNU_SOURCE -O3 -ggdb3 -O2 -fno-omit-frame-pointer

System:

Distributor ID: Debian
Description: Debian GNU/Linux 11 (bullseye)
Release: 11
Codename: bullseye

I use funclatency like this:

sudo funclatency-bpfcc ibverbs:ibv_get*

funclatency output:

Tracing 13 functions for "ibverbs:ibv_get*"... Hit Ctrl-C to end.
Function = b'[unknown]' [784402]
     nsecs               : count     distribution
         0 -> 1          : 0        |                                        |
         2 -> 3          : 0        |                                        |
         4 -> 7          : 0        |                                        |
         8 -> 15         : 0        |                                        |
        16 -> 31         : 0        |                                        |
        32 -> 63         : 0        |                                        |
        64 -> 127        : 0        |                                        |
       128 -> 255        : 0        |                                        |
       256 -> 511        : 0        |                                        |
       512 -> 1023       : 0        |                                        |
      1024 -> 2047       : 468      |****************************            |
      2048 -> 4095       : 512      |******************************          |
      4096 -> 8191       : 664      |****************************************|
      8192 -> 16383      : 332      |********************                    |
     16384 -> 32767      : 14       |                                        |
     32768 -> 65535      : 3        |                                        |
     65536 -> 131071     : 6        |                                        |
    131072 -> 262143     : 0        |                                        |
    262144 -> 524287     : 0        |                                        |
    524288 -> 1048575    : 0        |                                        |
   1048576 -> 2097151    : 0        |                                        |
   2097152 -> 4194303    : 0        |                                        |
   4194304 -> 8388607    : 0        |                                        |
   8388608 -> 16777215   : 1        |                                        |

Here is the source code for the translation of a memory address into a function name:

https://github.com/iovisor/bcc/blob/master/src/python/bcc/init.py

    def sym(addr, pid, show_module=False, show_offset=False, demangle=True):
    """sym(addr, pid, show_module=False, show_offset=False)

    Translate a memory address into a function name for a pid, which is
    returned. When show_module is True, the module name is also included.
    When show_offset is True, the instruction offset as a hexadecimal
    number is also included in the string.

    A pid of less than zero will access the kernel symbol cache.

    Example output when both show_module and show_offset are True:
        "start_thread+0x202 [libpthread-2.24.so]"

    Example output when both show_module and show_offset are False:
        "start_thread"
    """

    #addr is of type stacktrace_build_id
    #so invoke the bsym address resolver
    typeofaddr = str(type(addr))
    if typeofaddr.find('bpf_stack_build_id') != -1:
      sym = bcc_symbol()
      b = bcc_stacktrace_build_id()
      b.status = addr.status
      b.build_id = addr.build_id
      b.u.offset = addr.offset
      res = lib.bcc_buildsymcache_resolve(BPF._bsymcache,
                                          ct.byref(b),
                                          ct.byref(sym))
      if res < 0:
        if sym.module and sym.offset:
          name,offset,module = (None, sym.offset,
                    ct.cast(sym.module, ct.c_char_p).value)
        else:
          name, offset, module = (None, addr, None)
      else:
        name, offset, module = (sym.name, sym.offset,
                                ct.cast(sym.module, ct.c_char_p).value)
    else:
      name, offset, module = BPF._sym_cache(pid).resolve(addr, demangle)

    offset = b"+0x%x" % offset if show_offset and name is not None else b""
    name = name or b"[unknown]"
    name = name + offset
    module = b" [%s]" % os.path.basename(module) \
        if show_module and module is not None else b""
    return name + module

How can I read the function name correctly? It should not just return b'[unknown]'!


问:
Problem playing media with GStreamer and SRT protocol
I'm new to GStreamer and I'm trying to output the video on another port with the SRT protocol. So far I have done this and it doesn't work:

```<code>typedef struct _CustomData
{
  GstElement *pipeline;
  GstElement *source;
  GstElement *sink;
} CustomData;

static void pad_added_handler (GstElement * src, GstPad * pad, CustomData * data);

int main (int argc, char *argv[]) {
 CustomData data;
 GstBus *bus;
 GstMessage *msg;
 GstStateChangeReturn ret;
 gboolean terminate = FALSE;

 /* Initialize GStreamer */
 gst_init (&argc, &argv);

 /* Create the elements */
 data.source = gst_element_factory_make ("uridecodebin", "source");
 data.sink = gst_element_make_from_uri (GST_URI_SINK,"srt://my_uri", NULL, NULL);

 /* Create the empty pipeline */
 data.pipeline = gst_pipeline_new ("test-pipeline");

 if (!data.pipeline || !data.source || !data.sink) {
   g_printerr ("Not all elements could be created.\n");
   return -1;
 }

 /* Build the pipeline. Note that we are NOT linking the source at this point. We will do it later. */
 gst_bin_add_many (GST_BIN (data.pipeline), data.source, data.sink, NULL);

 /* Set the URI to play */
 g_object_set (data.source, "uri", "srt://my_uri", NULL);

 /* Connect to the pad-added signal */
 g_signal_connect (data.source, "pad-added", G_CALLBACK (pad_added_handler), &data);

 /* Start playing */
 ret = gst_element_set_state (data.pipeline, GST_STATE_PLAYING);
 if (ret == GST_STATE_CHANGE_FAILURE) {
   g_printerr ("Unable to set the pipeline to the playing state.\n");
   gst_object_unref (data.pipeline);
   return -1;
 }

 /* Listen to the bus */
 bus = gst_element_get_bus (data.pipeline);
 do {
   msg = gst_bus_timed_pop_filtered (bus, GST_CLOCK_TIME_NONE,
    GST_MESSAGE_STATE_CHANGED | GST_MESSAGE_ERROR | GST_MESSAGE_EOS);
   ...
  } while (!terminate);

  /* Free resources */
  gst_object_unref (bus);
  gst_element_set_state (data.pipeline, GST_STATE_NULL);
  gst_object_unref (data.pipeline);
  return 0;
}
</code>```

And pad_added_handler the function will be called by the padd-added signal:

```<code>/* This function will be called by the pad-added signal */
static void pad_added_handler (GstElement * src, GstPad * new_pad, CustomData * data)
{
  GstPad *sink_pad = gst_element_get_static_pad (data->sink, "sink");
  GstPadLinkReturn ret;
  GstCaps *new_pad_caps = NULL;
  GstStructure *new_pad_struct = NULL;
  const gchar *new_pad_type = NULL;

  g_print ("Received new pad '%s' from '%s':\n", GST_PAD_NAME (new_pad), GST_ELEMENT_NAME (src));

  /* If our converter is already linked, we have nothing to do here */
  if (gst_pad_is_linked (sink_pad)) {
    g_print ("We are already linked. Ignoring.\n");
    goto exit;
  }

  /* Check the new pad's type */
  new_pad_caps = gst_pad_get_current_caps (new_pad);
  new_pad_struct = gst_caps_get_structure (new_pad_caps, 0);
  new_pad_type = gst_structure_get_name (new_pad_struct);
  if (!g_str_has_prefix (new_pad_type, "video/x-raw")) {
    g_print ("It has type '%s' which is not raw audio. Ignoring.\n",new_pad_type);
   goto exit;
  }

  /* Attempt the link */
  ret = gst_pad_link (new_pad, sink_pad);
  if (GST_PAD_LINK_FAILED (ret)) {
    g_print ("Type is '%s' but link failed.\n", new_pad_type);
  } else {
    g_print ("Link succeeded (type '%s').\n", new_pad_type);
  }

  exit:
  /* Unreference the new pad's caps, if we got them */
  if (new_pad_caps != NULL)
    gst_caps_unref (new_pad_caps);

  /* Unreference the sink pad */
   gst_object_unref (sink_pad);
}
</code>```

I don't get any error when running the code but when I try to read the media I get the following error: Operation not supported: Invalid socket ID.

Body:
I'm new to GStreamer and I'm trying to output the video on another port with the SRT protocol. So far I have done this and it doesn't work:

typedef struct _CustomData
{
  GstElement *pipeline;
  GstElement *source;
  GstElement *sink;
} CustomData;

static void pad_added_handler (GstElement * src, GstPad * pad, CustomData * data);

int main (int argc, char *argv[]) {
 CustomData data;
 GstBus *bus;
 GstMessage *msg;
 GstStateChangeReturn ret;
 gboolean terminate = FALSE;

 /* Initialize GStreamer */
 gst_init (&argc, &argv);

 /* Create the elements */
 data.source = gst_element_factory_make ("uridecodebin", "source");
 data.sink = gst_element_make_from_uri (GST_URI_SINK,"srt://my_uri", NULL, NULL);

 /* Create the empty pipeline */
 data.pipeline = gst_pipeline_new ("test-pipeline");

 if (!data.pipeline || !data.source || !data.sink) {
   g_printerr ("Not all elements could be created.\n");
   return -1;
 }

 /* Build the pipeline. Note that we are NOT linking the source at this point. We will do it later. */
 gst_bin_add_many (GST_BIN (data.pipeline), data.source, data.sink, NULL);

 /* Set the URI to play */
 g_object_set (data.source, "uri", "srt://my_uri", NULL);

 /* Connect to the pad-added signal */
 g_signal_connect (data.source, "pad-added", G_CALLBACK (pad_added_handler), &data);

 /* Start playing */
 ret = gst_element_set_state (data.pipeline, GST_STATE_PLAYING);
 if (ret == GST_STATE_CHANGE_FAILURE) {
   g_printerr ("Unable to set the pipeline to the playing state.\n");
   gst_object_unref (data.pipeline);
   return -1;
 }

 /* Listen to the bus */
 bus = gst_element_get_bus (data.pipeline);
 do {
   msg = gst_bus_timed_pop_filtered (bus, GST_CLOCK_TIME_NONE,
    GST_MESSAGE_STATE_CHANGED | GST_MESSAGE_ERROR | GST_MESSAGE_EOS);
   ...
  } while (!terminate);

  /* Free resources */
  gst_object_unref (bus);
  gst_element_set_state (data.pipeline, GST_STATE_NULL);
  gst_object_unref (data.pipeline);
  return 0;
}

And pad_added_handler the function will be called by the padd-added signal:

/* This function will be called by the pad-added signal */
static void pad_added_handler (GstElement * src, GstPad * new_pad, CustomData * data)
{
  GstPad *sink_pad = gst_element_get_static_pad (data->sink, "sink");
  GstPadLinkReturn ret;
  GstCaps *new_pad_caps = NULL;
  GstStructure *new_pad_struct = NULL;
  const gchar *new_pad_type = NULL;

  g_print ("Received new pad '%s' from '%s':\n", GST_PAD_NAME (new_pad), GST_ELEMENT_NAME (src));

  /* If our converter is already linked, we have nothing to do here */
  if (gst_pad_is_linked (sink_pad)) {
    g_print ("We are already linked. Ignoring.\n");
    goto exit;
  }

  /* Check the new pad's type */
  new_pad_caps = gst_pad_get_current_caps (new_pad);
  new_pad_struct = gst_caps_get_structure (new_pad_caps, 0);
  new_pad_type = gst_structure_get_name (new_pad_struct);
  if (!g_str_has_prefix (new_pad_type, "video/x-raw")) {
    g_print ("It has type '%s' which is not raw audio. Ignoring.\n",new_pad_type);
   goto exit;
  }

  /* Attempt the link */
  ret = gst_pad_link (new_pad, sink_pad);
  if (GST_PAD_LINK_FAILED (ret)) {
    g_print ("Type is '%s' but link failed.\n", new_pad_type);
  } else {
    g_print ("Link succeeded (type '%s').\n", new_pad_type);
  }

  exit:
  /* Unreference the new pad's caps, if we got them */
  if (new_pad_caps != NULL)
    gst_caps_unref (new_pad_caps);

  /* Unreference the sink pad */
   gst_object_unref (sink_pad);
}

I don't get any error when running the code but when I try to read the media I get the following error: Operation not supported: Invalid socket ID.


问:
Is there a correct way to tint PDF icons for iOS?
I'm a UX designer - so bear with me. We have an issue where we want to use PDF files as icons for our iOS app. This works fine if we were to only use them in one color. However we have situations where we need to change the color based on the BG they are used on.

The issue is that we are not able to tint the PDFs - they remain white.

The icons are all made in Figma and are used for web / android and iOS. They work perfectly as SVGs and are flattened - so that should not be the issue. Might it have something to do with the way PDF exports work from Figma perhaps?

To tint the PDFs we use renderingMode(_:) which does not seem to actually tint our PDF icons. It works for PNGs, which of course is not optimal as the icons turn out very grainy.

Here is an example of the code used:

```<code>SwiftUI.Image.init(uiImage: uiImage)
.renderingMode(.template)
.foregroundColor(label.tintColor)
</code>```

Here is an example SVG & PDF from the icons that do not work:
Icons from Wetransfer

Body:
I'm a UX designer - so bear with me. We have an issue where we want to use PDF files as icons for our iOS app. This works fine if we were to only use them in one color. However we have situations where we need to change the color based on the BG they are used on.

The issue is that we are not able to tint the PDFs - they remain white.

The icons are all made in Figma and are used for web / android and iOS. They work perfectly as SVGs and are flattened - so that should not be the issue. Might it have something to do with the way PDF exports work from Figma perhaps?

To tint the PDFs we use renderingMode(_:) which does not seem to actually tint our PDF icons. It works for PNGs, which of course is not optimal as the icons turn out very grainy.

Here is an example of the code used:

SwiftUI.Image.init(uiImage: uiImage)
.renderingMode(.template)
.foregroundColor(label.tintColor)

Here is an example SVG & PDF from the icons that do not work:
Icons from Wetransfer


问:
How to add Tags to a model with django-taggits? (django)
I basically have a template which shows all the Tags you can click one. Then I get the Value of the checkbox (it is the Id of the Taggit Items, because I load the Tags from the Database in my Template) and send it to the database. But how can I give a model in my case a Post the Tag?
In Pseudocode that would be:

```<code>Create object Post
Get tags from frontend
>>> 1, 2
create taggit_taggeditem
give item: object id: 22 tag ids: 1, 2

</code>```

Thank you for answers. I don't have any ideas how to do that : ) .

Body:
I basically have a template which shows all the Tags you can click one. Then I get the Value of the checkbox (it is the Id of the Taggit Items, because I load the Tags from the Database in my Template) and send it to the database. But how can I give a model in my case a Post the Tag?
In Pseudocode that would be:

Create object Post
Get tags from frontend
>>> 1, 2
create taggit_taggeditem
give item: object id: 22 tag ids: 1, 2

Thank you for answers. I don't have any ideas how to do that : ) .


问:
How to get 2 specific data from firebase using Xamarin
I've been trying to work on this code example I found online. I want to display the name and email welcome page after I log in but it doesn't show the name only the E-mail

This is the firebasehelper

```<code>public static async Task<List<Citizen>> GetAllCitizen()
        {
            try
            {
                var citizenlist = (await firebase
                    .Child("Citizen").OnceAsync<Citizen>()).Select(item =>
                new Citizen
                {
                    Email = item.Object.Email,
                    Password = item.Object.Password,
                    FirstName= item.Object.FirstName

                }).ToList();
                return citizenlist;
            }
            catch (Exception e)
            {
                Debug.WriteLine($"Error:{e}");
                return null;
            }
        }
        //Read
        public static async Task<Citizen> GetCitizen(string email, string firstName)
        {
            try
            {
                var allCitizen = await GetAllCitizen();
                await firebase.Child("Citizen")
                .OnceAsync<Citizen>();
                return allCitizen.Where(a => a.Email == email).FirstOrDefault();
            }
            catch (Exception e)
            {
                Debug.WriteLine($"Error:{e}");
                return null;
            }
        }
</code>```

This is the WelcomeVM

```<code>public class WelcomeVM : INotifyPropertyChanged
    {
        public WelcomeVM(string email2, string firstName2)
            {
                FirstName = firstName2;
               Email = email2;
            }

            private string firstName;
            public string FirstName
            {
                get { return firstName; }
                set { firstName = value; }
            }
        private string email;

        public string Email
        {
            get { return email; }
            set { email = value; }
        }
        private string password;

            public event PropertyChangedEventHandler PropertyChanged;
</code>```

The welcome xaml

```<code><ContentPage.Content>
        <StackLayout>
            <Label Text="{Binding FirstName, StringFormat='Welcome {0}'}" Margin="10" FontSize="25"/>
            <Label Text="{Binding Email, StringFormat='Welcome {0}'}" Margin="10" FontSize="20"/>
            <Label Text="{Binding FirstName, StringFormat='Welcome {0}'}" Margin="10" FontSize="20"/>
</code>```

I copied the code that displays the E-mail but it doesn't show the name only the E-mail

Body:
I've been trying to work on this code example I found online. I want to display the name and email welcome page after I log in but it doesn't show the name only the E-mail

This is the firebasehelper

public static async Task<List<Citizen>> GetAllCitizen()
        {
            try
            {
                var citizenlist = (await firebase
                    .Child("Citizen").OnceAsync<Citizen>()).Select(item =>
                new Citizen
                {
                    Email = item.Object.Email,
                    Password = item.Object.Password,
                    FirstName= item.Object.FirstName

                }).ToList();
                return citizenlist;
            }
            catch (Exception e)
            {
                Debug.WriteLine($"Error:{e}");
                return null;
            }
        }
        //Read
        public static async Task<Citizen> GetCitizen(string email, string firstName)
        {
            try
            {
                var allCitizen = await GetAllCitizen();
                await firebase.Child("Citizen")
                .OnceAsync<Citizen>();
                return allCitizen.Where(a => a.Email == email).FirstOrDefault();
            }
            catch (Exception e)
            {
                Debug.WriteLine($"Error:{e}");
                return null;
            }
        }

This is the WelcomeVM

public class WelcomeVM : INotifyPropertyChanged
    {
        public WelcomeVM(string email2, string firstName2)
            {
                FirstName = firstName2;
               Email = email2;
            }

            private string firstName;
            public string FirstName
            {
                get { return firstName; }
                set { firstName = value; }
            }
        private string email;

        public string Email
        {
            get { return email; }
            set { email = value; }
        }
        private string password;

            public event PropertyChangedEventHandler PropertyChanged;

The welcome xaml

<ContentPage.Content>
        <StackLayout>

I copied the code that displays the E-mail but it doesn't show the name only the E-mail


问:
Kotlin - Should I Introduce Null?
What is the best practice to avoid returning null in the below situation? I feel like introducing null in Kotlin is a smell, but is it in this circumstance? Is there a better alternative?</p>
```<code>fun getMatch(s1: String, s2: String) : Match? {
    MatcherType.values().forEach(){
        Matcher matcher = getMatcher(it)
        Match match = matcher.match(s1, s2)
        if(match != null){
          return match
        }
    }
    return null
}
</code>```

Title: Kotlin - Should I Introduce Null?

Body:
What is the best practice to avoid returning null in the below situation? I feel like introducing null in Kotlin is a smell, but is it in this circumstance? Is there a better alternative?

fun getMatch(s1: String, s2: String) : Match? {
    MatcherType.values().forEach(){
        Matcher matcher = getMatcher(it)
        Match match = matcher.match(s1, s2)
        if(match != null){
          return match
        }
    }
    return null
}


问:
How to add a download option on an embbeded video from a video hosting platform in HTML
i uploaded a video on a video hosting platform then i embbeded it on my web page that people can see it from there and  i also want people to be able to download that video from my page but the download option is it not there soo how can add it.

<!doctype HTML>

<title></title>

<button>download</button>

```


问:
this.props.contextValue.store.getState is not a function when adding a custom input
I'm running into an issue with adding my own custon input after following the documentation for Autocomplete.

The error I get is "this.props.contextValue.store.getState is not a function" when adding my CustomSearchBox component. Can anyone advise what I'm doing wrong?

Usage:

```<code><InstantSearch
  searchClient={algoliaClient}
  indexName="plp"
>
   <CustomSearchBox /> // Errors when I add this

   <Autocomplete
      searchClient={algoliaClient}
      placeholder="Search products"
      detachedMediaQuery="none"
      openOnFocus
    />

    <RefinementList attribute="DIAMETER" />

    <HitWrapper>
        <Hits hitComponent={Hit} />
    </HitWrapper>
</InstantSearch>
</code>```

Custom search box component

```<code>import React from 'react';
import { connectSearchBox } from 'react-instantsearch-dom';

const SearchBox = ({ currentRefinement, isSearchStalled, refine }) => (
    <form noValidate action="" role="search">
        <input
            type="search"
            value={currentRefinement}
            onChange={event => refine(event.currentTarget.value)}
        />
        {isSearchStalled ? 'My search is stalled' : ''}
    </form>
);

const CustomSearchBox = connectSearchBox(SearchBox);

export default CustomSearchBox;

</code>```

Body:
I'm running into an issue with adding my own custon input after following the documentation for Autocomplete.

The error I get is "this.props.contextValue.store.getState is not a function" when adding my CustomSearchBox component. Can anyone advise what I'm doing wrong?

Usage:

<InstantSearch
  searchClient={algoliaClient}
  indexName="plp"
>
   <CustomSearchBox /> // Errors when I add this

   <Autocomplete
      searchClient={algoliaClient}
      placeholder="Search products"
      detachedMediaQuery="none"
      openOnFocus
    />

    <RefinementList attribute="DIAMETER" />

    <HitWrapper>
        <Hits hitComponent={Hit} />
    </HitWrapper>
</InstantSearch>

Custom search box component

import React from 'react';
import { connectSearchBox } from 'react-instantsearch-dom';

const SearchBox = ({ currentRefinement, isSearchStalled, refine }) => (
    <form noValidate action="" role="search">
        <input
            type="search"
            value={currentRefinement}
            onChange={event => refine(event.currentTarget.value)}
        />
        {isSearchStalled ? 'My search is stalled' : ''}
    </form>
);

const CustomSearchBox = connectSearchBox(SearchBox);

export default CustomSearchBox;


问:
Cloudant: couch returned 500
Getting cloudant error on find query:

```<code>{
   "selector": {
      "isValid": {
         "$eq": true
      }
   }
}
</code>```
```<code>Could not find document query: "{exit,lru} couch returned 500"
Could not find document query: "{exit,noproc} couch returned 500"
</code>```

Trying to execute simple find query and getting this error. The expected result should be returned result of the query.

Title: Cloudant: couch returned 500

Body:
Getting cloudant error on find query:

{
   "selector": {
      "isValid": {
         "$eq": true
      }
   }
}

Could not find document query: "{exit,lru} couch returned 500"
Could not find document query: "{exit,noproc} couch returned 500"

Trying to execute simple find query and getting this error. The expected result should be returned result of the query.


问:
Why does this one single accesskey not work on Firefox?
I'm using Firefox on MacOS and a specific access key isn't working:

Name
<input id="name" name="name" value="" tabindex="1" type="text" />
```

This works on Safari and Chrome, but not Firefox. When I use Control+Option+n, the focus is not set on the "name" field. There are 2 other fields in the form, and their access keys work as expected. There are no conflicts on the page for the access key (i.e. accesskey="n" is only defined once). There are no conflicts on the page for the target element name (i.e. id="name" is only defined once).

I can use the developer tools to change the accesskey on that label to something else (e.g. w) and it works, so the link between the  and the <input> is correct. There is something about the n specifically.

I haven't been able to find any information online about any "access keys that don't work (for some reason)" but I'm starting to wonder if the n access key conflicts with something in Firefox.

Installed plug-ins are uBlock Origin, Firefox Devtools ADB Extension, and Power Close.

Body:
I'm using Firefox on MacOS and a specific access key isn't working:

Name
<input id="name" name="name" value="" tabindex="1" type="text" />

This works on Safari and Chrome, but not Firefox. When I use Control+Option+n, the focus is not set on the "name" field. There are 2 other fields in the form, and their access keys work as expected. There are no conflicts on the page for the access key (i.e. accesskey="n" is only defined once). There are no conflicts on the page for the target element name (i.e. id="name" is only defined once).

I can use the developer tools to change the accesskey on that label to something else (e.g. w) and it works, so the link between the  and the <input> is correct. There is something about the n specifically.

I haven't been able to find any information online about any "access keys that don't work (for some reason)" but I'm starting to wonder if the n access key conflicts with something in Firefox.

Installed plug-ins are uBlock Origin, Firefox Devtools ADB Extension, and Power Close.


问:
Next.js <Link> not passing query when opening a new tab
I'm using the following Link component as an anchor to go to another page of my website. As you can see I'm passing values using query: {is_default: true}.

So it's working fine when I use the Link clicking with my left mouse click.

When I use the middle mouse button to open in new tab, the query is arriving to the new page as an empty object {}. I have read next documentation and doesn't seems to talk about that...
¿Any ideas of how to fix that?

Link component:

```<code><Link
   href={{
         pathname: '/backend/cashback/apply/',
         query: {is_default: true}
   }} as={'/backend/cashback/apply'} passHref
>
  <a className={styles.withTable__new} href= {'/backend/cashback/apply/'}>
        <img src="/backend/create-campaign.svg" alt="impacts" />
        {t("backend:policies_create_new")}
  </a>
</Link>
</code>```

Retrieving data from query in getServerSideProps:

```<code>export const getServerSideProps = wrapper.getServerSideProps(
  (store) =>
    async ({ req, locale, locales, defaultLocale, query }) => {
</code>```

Body:
I'm using the following Link component as an anchor to go to another page of my website. As you can see I'm passing values using query: {is_default: true}.

So it's working fine when I use the Link clicking with my left mouse click.

When I use the middle mouse button to open in new tab, the query is arriving to the new page as an empty object {}. I have read next documentation and doesn't seems to talk about that...
¿Any ideas of how to fix that?

Link component:

<Link
   href={{
         pathname: '/backend/cashback/apply/',
         query: {is_default: true}
   }} as={'/backend/cashback/apply'} passHref
>

        {t("backend:policies_create_new")}

</Link>

Retrieving data from query in getServerSideProps:

export const getServerSideProps = wrapper.getServerSideProps(
  (store) =>
    async ({ req, locale, locales, defaultLocale, query }) => {


问:
Can't handle unfamiliar date format in BigQuery
I'm trying to query a BigQuery table that has column "date" (set to type DATE in the schema) formatted as yyyy-mm-dd-??. In other words, there's an extra set of information about the date and I'm not really sure what it is. When I try to query the "date" column I run into the error:

SQL Error [100032] [HY000]: [Simba]BigQueryJDBCDriver Error executing query job. Message: Invalid date: '2022-09-03-01'

I've tried cast(date as string), cast(left(date, 10) as string), all types of workarounds, but the error persists. It seems that no matter how much I try and nail it home in the query that I want this weird date column to be read as a string, so that I can work with it, BigQuery still wants to take it as a date, I guess because that's how it's setup in the schema. I don't care if this is parsed into a date properly or if it's read as a string and then I can parse it from there, I just want to be able to query the date column without getting an error.


问:
I want to know how i could read all the files in the list and give out all matches
The for-loop only gives out one match
I want to know how i could read all the files in the list and give out all matches.Furthermore on the first approach it only gives me back the first match not every match.
The programming language my code is written in is Python</p>
```<code>for columname in(fnmatch.fnmatch(column_names, pattern)):
    print (column_names)
    list=\[\]
    list.append(column_names)
    print(list)
    for i in range(len(list)):
        new_df=dataframe\_.drop(list\[x\], axis=1)

</code>```

Body:
The for-loop only gives out one match
I want to know how i could read all the files in the list and give out all matches.Furthermore on the first approach it only gives me back the first match not every match.
The programming language my code is written in is Python

for columname in(fnmatch.fnmatch(column_names, pattern)):
    print (column_names)
    list=\[\]
    list.append(column_names)
    print(list)
    for i in range(len(list)):
        new_df=dataframe\_.drop(list\[x\], axis=1)


问:
Power Apps: Date field doesn't exclude weekends and holidays
I have an SP list custom Power Apps form and I need the date range to exclude weekends and holidays. For example, if a user picks a date that is Saturday, set the date to Friday but a prompt letting them know that they picked a weekend/holiday is acceptable too.

Function isWeekday(date as Date) as Boolean
return Weekday(date) >= 1 and Weekday(date) <=5
End Function

If(DataCardValue20.Selected.Value="Yes",If(DataCardValue15.Selected.Value ="green",
DateAdd(DataCardValue23.SelectedDate,-1),
If(DataCardValue15.Selected.Value="blue",DateAdd(DataCardValue23.SelectedDate,-2),
If(DataCardValue15.Selected.Value="yellow",DateAdd(DataCardValue23.SelectedDate,-3),
If(DataCardValue15.Selected.Value="orange",DateAdd(DataCardValue23.SelectedDate,-4),
If(DataCardValue15.Selected.Value="red",DateAdd(DataCardValue23.SelectedDate,-5),
))))))

The function didn't work, I tried putting it in OnChange too but nothing. Any help or guidance for the best way to accomplish this is greatly appreciated.


问:
Use query options in relative path in HTML JS
I've got a function that is called by a press of a button that is

function DownloadBase() {
  window.location.href = "../direct-download?variant=base"
}
```

and I wanted it to open the direct-download/index.html with the queries variant=base

Resould should be:   https://domain/direct-download?variant=base

But instead I get it without the query options.

Is it possible to do? Am I missing something?

Thanks

Body:
I've got a function that is called by a press of a button that is

function DownloadBase() {
  window.location.href = "../direct-download?variant=base"
}

and I wanted it to open the direct-download/index.html with the queries variant=base

Resould should be:   https://domain/direct-download?variant=base

But instead I get it without the query options.

Is it possible to do? Am I missing something?

Thanks


问:
Is it possible to join two unrelated models based on a string column using Django-ORM
Currently, in a project that I'm working on, we are using the library called drf-api-tracking for logging each request that related data like an audit. The library is providing a mixin called LoggingMixin and by using that we are logging the API-related URL, status codes, requests, responses and etc. To save these data, the mixing is using a model called, APIRequestLog which is provided by the library.

Let's assume the APIRequestLog model is like the below,

```<code>class APIRequesLog(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    url = models.CharField(null=True, blank=True)
    ...
</code>```

In our system there we have a model called Dashboard and this model has an attribute called URL.

Let's assume the Dashboard model is like below,

```<code>class Dashboard(models.Model):
    shortname = models.CharField(null=True, blank=True)
    url = models.CharField(null=True, blank=True)
    ...
</code>```

My requirement is when I query the dashboard model, I need to get all the APIRequestLog records that are similar to the dashboard URL. I know that we can achieve this by iterating the dashboard records and filtering the APIRequestLog which has a similar URL to an iterating dashboard URL. But that would be time-consuming. Is there any method that we can join these two models based on the URL column and fetch the data at once? If so please help me to figure this out and thank you for your support in advance.

Note: The Dashboard model and APIRequesLog model do not have any foreign key relationship between the models and it's possible to import the APIRequesLog model to any place in the project even if it's a model from a library

I went through this question and this question but that did not help with my scenario

Body:
Currently, in a project that I'm working on, we are using the library called drf-api-tracking for logging each request that related data like an audit. The library is providing a mixin called LoggingMixin and by using that we are logging the API-related URL, status codes, requests, responses and etc. To save these data, the mixing is using a model called, APIRequestLog which is provided by the library.

Let's assume the APIRequestLog model is like the below,

class APIRequesLog(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    url = models.CharField(null=True, blank=True)
    ...

In our system there we have a model called Dashboard and this model has an attribute called URL.

Let's assume the Dashboard model is like below,

class Dashboard(models.Model):
    shortname = models.CharField(null=True, blank=True)
    url = models.CharField(null=True, blank=True)
    ...

My requirement is when I query the dashboard model, I need to get all the APIRequestLog records that are similar to the dashboard URL. I know that we can achieve this by iterating the dashboard records and filtering the APIRequestLog which has a similar URL to an iterating dashboard URL. But that would be time-consuming. Is there any method that we can join these two models based on the URL column and fetch the data at once? If so please help me to figure this out and thank you for your support in advance.

Note: The Dashboard model and APIRequesLog model do not have any foreign key relationship between the models and it's possible to import the APIRequesLog model to any place in the project even if it's a model from a library

I went through this question and this question but that did not help with my scenario


问:
Writing GIFs and videos from JPGs using Magick is slow and of poor quality
I often write something like 300 frames that I want to make into a 20 second animation using the magick package in R. I am finding that to write the frames to a 300 jpegs and then bringing them into photoshop is more reliable than working with either image_write_gif or image_write_video.  Nevertheless, I would like to do everything in R and hope that someone has a suggestion for something more robust.

There is a similar question "slow or failed writing image vector to *.gif with magick in R?"  That question does not include a reproducible example and has not been answered.

I have experimented with image_write_gif and image_write_video as well as image_write.  It takes about 10 times longer to write the gif and write the video than to just write the images.  Also, in the examples below you get a smooth gradation of grey in the individual images, but the graduation breaks down a bit in the gif and the mp4 and there is some flickering.

```<code>library(magick)
pic1 <- image_blank(600, 600, pseudo_image = "gradient:white-black")
pic1 <- image_convert(pic1, format = "jpeg")
stack <- image_morph(c(pic1, image_negate(pic1)), frames = 100)
length(stack)

a <- Sys.time()
for (i in 1:length(stack)) {
  image_write(stack[i], path = paste0("test", i, ".jpg"))
}
b <- Sys.time()
b - a

a <- Sys.time()
image_write_gif(stack, "test.gif")
b <- Sys.time()
b - a

a <- Sys.time()
image_write_video(stack, "test.mp4")
b <- Sys.time()
b - a
</code>```

The first step (writing the individual jpegs takes about a half a second.  Writing the gif takes 6 seconds and the mp4 takes 4 seconds on my MacBook that is a 2018 vintage.

Body:
I often write something like 300 frames that I want to make into a 20 second animation using the magick package in R. I am finding that to write the frames to a 300 jpegs and then bringing them into photoshop is more reliable than working with either image_write_gif or image_write_video.  Nevertheless, I would like to do everything in R and hope that someone has a suggestion for something more robust.

There is a similar question "slow or failed writing image vector to *.gif with magick in R?"  That question does not include a reproducible example and has not been answered.

I have experimented with image_write_gif and image_write_video as well as image_write.  It takes about 10 times longer to write the gif and write the video than to just write the images.  Also, in the examples below you get a smooth gradation of grey in the individual images, but the graduation breaks down a bit in the gif and the mp4 and there is some flickering.

library(magick)
pic1 <- image_blank(600, 600, pseudo_image = "gradient:white-black")
pic1 <- image_convert(pic1, format = "jpeg")
stack <- image_morph(c(pic1, image_negate(pic1)), frames = 100)
length(stack)

a <- Sys.time()
for (i in 1:length(stack)) {
  image_write(stack[i], path = paste0("test", i, ".jpg"))
}
b <- Sys.time()
b - a

a <- Sys.time()
image_write_gif(stack, "test.gif")
b <- Sys.time()
b - a

a <- Sys.time()
image_write_video(stack, "test.mp4")
b <- Sys.time()
b - a

The first step (writing the individual jpegs takes about a half a second.  Writing the gif takes 6 seconds and the mp4 takes 4 seconds on my MacBook that is a 2018 vintage.


问:
Data Vault - Deleted record from Multi Active Satellite
I am trying to figure out how to handle following situation.

I have a table in source system, which ends up as MAS in our system, let's call the table A, the related hub that is filled by it H_A and the related MAS sat as MAS_A. The table 'A' holds phone numbers of customers. One customer can have work or home phone number, that's why MAS.

Today, we have received another table, which tracks delete of records in the above mentioned table A. Let's call this table B.

How do I properly handle information coming from table B, which states, that only the "work" phone number was deleted, yet the "home" phone number stays in place? Which means I can't create link towards the H_A, but I'd need something like record tracking satellite which would be linked to the MAS_A? It's good to know once the record is deleted, it can't be recreated with the same ID in the source system. I know that sat-link-sat is not DV2.0 proper modelling solution and I don't know how to handle this properly.


问:
Is it safe if the credential is included in request body
I wonder why the user credential is included in the request body when I authenticate the user's JWT with using passport?

enter image description here

enter image description here

I suppose it's not safe to include the credential in the request ? How can i exclude it?


问:
Discord.py with openai can't use same command at same time
When a command is "thinking" it must wait for it to finish the same command before continuing.

If I add sync_to_async to both commands, the openaitest2 will always be stuck in "sending command" before the openaitest execution ends.
image

```<code>    @test_group.command()
    async def openaitest(self, interaction: discord.Interaction, text: str):
        import openai
        from asgiref.sync import sync_to_async

        await interaction.response.defer()

        response = await sync_to_async(openai.Completion.create)(
            model="text-davinci-003",
            prompt=f" Q:{text}\n A:",
            temperature=0.9,
            max_tokens=3500,
            top_p=1,
            frequency_penalty=0.0,
            presence_penalty=0.6,
            stop=[" Q:"],
        )

        ans = response["choices"][0]["text"]
        await interaction.followup.send(ans)

    @test_group.command()
    async def openaitest2(self, interaction: discord.Interaction, text: str):
        import openai
        from asgiref.sync import sync_to_async

        await interaction.response.defer()

        response = await sync_to_async(openai.Completion.create)(
            model="text-davinci-003",
            prompt=f" Q:{text}\n A:",
            temperature=0.9,
            max_tokens=3500,
            top_p=1,
            frequency_penalty=0.0,
            presence_penalty=0.6,
            stop=[" Q:"],
        )

        ans = response["choices"][0]["text"]
        await interaction.followup.send(ans)
</code>```

If I only add sync_to_async to openaitest, openaitest2 can work normally before the end of openaitest execution, but it will be stuck in "thinking" when using openaitest again. When openaitest is sent for the first time, I deliberately pass in a prompt that will take a long time. The second incoming prompt takes less time, I hope that openaitest will continue "thinking" when it is sent for the first time, and openaitest will give me the answer first when it is sent for the second time.
image
image

```<code>    @test_group.command()
    async def openaitest(self, interaction: discord.Interaction, text: str):
        import openai
        from asgiref.sync import sync_to_async

        await interaction.response.defer()

        response = await sync_to_async(openai.Completion.create)(
            model="text-davinci-003",
            prompt=f" Q:{text}\n A:",
            temperature=0.9,
            max_tokens=3500,
            top_p=1,
            frequency_penalty=0.0,
            presence_penalty=0.6,
            stop=[" Q:"],
        )

        ans = response["choices"][0]["text"]
        await interaction.followup.send(ans)

    @test_group.command()
    async def openaitest2(self, interaction: discord.Interaction, text: str):
        import openai

        await interaction.response.defer()

        response = await openai.Completion.create(
            model="text-davinci-003",
            prompt=f" Q:{text}\n A:",
            temperature=0.9,
            max_tokens=3500,
            top_p=1,
            frequency_penalty=0.0,
            presence_penalty=0.6,
            stop=[" Q:"],
        )

        ans = response["choices"][0]["text"]
        await interaction.followup.send(ans)
</code>```

If I don't add sync_to_async on both sides, I can't use any command when openaitest is "thinking", including openaitest2 and all other commands I made
image

```<code>    @test_group.command()
    async def openaitest(self, interaction: discord.Interaction, text: str):
        import openai

        await interaction.response.defer()

        response = openai.Completion.create(
            model="text-davinci-003",
            prompt=f" Q:{text}\n A:",
            temperature=0.9,
            max_tokens=3500,
            top_p=1,
            frequency_penalty=0.0,
            presence_penalty=0.6,
            stop=[" Q:"],
        )

        ans = response["choices"][0]["text"]
        await interaction.followup.send(ans)

    @test_group.command()
    async def openaitest2(self, interaction: discord.Interaction, text: str):
        import openai

        await interaction.response.defer()

        response = await openai.Completion.create(
            model="text-davinci-003",
            prompt=f" Q:{text}\n A:",
            temperature=0.9,
            max_tokens=3500,
            top_p=1,
            frequency_penalty=0.0,
            presence_penalty=0.6,
            stop=[" Q:"],
        )

        ans = response["choices"][0]["text"]
        await interaction.followup.send(ans)
</code>```

Body:
When a command is "thinking" it must wait for it to finish the same command before continuing.

If I add sync_to_async to both commands, the openaitest2 will always be stuck in "sending command" before the openaitest execution ends.
image

    @test_group.command()
    async def openaitest(self, interaction: discord.Interaction, text: str):
        import openai
        from asgiref.sync import sync_to_async

        await interaction.response.defer()

        response = await sync_to_async(openai.Completion.create)(
            model="text-davinci-003",
            prompt=f" Q:{text}\n A:",
            temperature=0.9,
            max_tokens=3500,
            top_p=1,
            frequency_penalty=0.0,
            presence_penalty=0.6,
            stop=[" Q:"],
        )

        ans = response["choices"][0]["text"]
        await interaction.followup.send(ans)

    @test_group.command()
    async def openaitest2(self, interaction: discord.Interaction, text: str):
        import openai
        from asgiref.sync import sync_to_async

        await interaction.response.defer()

        response = await sync_to_async(openai.Completion.create)(
            model="text-davinci-003",
            prompt=f" Q:{text}\n A:",
            temperature=0.9,
            max_tokens=3500,
            top_p=1,
            frequency_penalty=0.0,
            presence_penalty=0.6,
            stop=[" Q:"],
        )

        ans = response["choices"][0]["text"]
        await interaction.followup.send(ans)

If I only add sync_to_async to openaitest, openaitest2 can work normally before the end of openaitest execution, but it will be stuck in "thinking" when using openaitest again. When openaitest is sent for the first time, I deliberately pass in a prompt that will take a long time. The second incoming prompt takes less time, I hope that openaitest will continue "thinking" when it is sent for the first time, and openaitest will give me the answer first when it is sent for the second time.
image
image

    @test_group.command()
    async def openaitest(self, interaction: discord.Interaction, text: str):
        import openai
        from asgiref.sync import sync_to_async

        await interaction.response.defer()

        response = await sync_to_async(openai.Completion.create)(
            model="text-davinci-003",
            prompt=f" Q:{text}\n A:",
            temperature=0.9,
            max_tokens=3500,
            top_p=1,
            frequency_penalty=0.0,
            presence_penalty=0.6,
            stop=[" Q:"],
        )

        ans = response["choices"][0]["text"]
        await interaction.followup.send(ans)

    @test_group.command()
    async def openaitest2(self, interaction: discord.Interaction, text: str):
        import openai

        await interaction.response.defer()

        response = await openai.Completion.create(
            model="text-davinci-003",
            prompt=f" Q:{text}\n A:",
            temperature=0.9,
            max_tokens=3500,
            top_p=1,
            frequency_penalty=0.0,
            presence_penalty=0.6,
            stop=[" Q:"],
        )

        ans = response["choices"][0]["text"]
        await interaction.followup.send(ans)

If I don't add sync_to_async on both sides, I can't use any command when openaitest is "thinking", including openaitest2 and all other commands I made
image

    @test_group.command()
    async def openaitest(self, interaction: discord.Interaction, text: str):
        import openai

        await interaction.response.defer()

        response = openai.Completion.create(
            model="text-davinci-003",
            prompt=f" Q:{text}\n A:",
            temperature=0.9,
            max_tokens=3500,
            top_p=1,
            frequency_penalty=0.0,
            presence_penalty=0.6,
            stop=[" Q:"],
        )

        ans = response["choices"][0]["text"]
        await interaction.followup.send(ans)

    @test_group.command()
    async def openaitest2(self, interaction: discord.Interaction, text: str):
        import openai

        await interaction.response.defer()

        response = await openai.Completion.create(
            model="text-davinci-003",
            prompt=f" Q:{text}\n A:",
            temperature=0.9,
            max_tokens=3500,
            top_p=1,
            frequency_penalty=0.0,
            presence_penalty=0.6,
            stop=[" Q:"],
        )

        ans = response["choices"][0]["text"]
        await interaction.followup.send(ans)


问:
unrecognized selector sent to instance ... was thrown while invoking on target with params
I'm using a library in my react-native project where I'm getting this error

Below is one of the function in the Implementation file of the ios folder of library I'm using. I'm getting error on calling the below function.
Also, I'm getting this error since I updated to Xcode 14.1 (and iOS 16.1), with react-native (0.66.4)

```<code>RCT_EXPORT_METHOD(getCardToken:(NSString *)cardNumber expirationDate:(NSString *)expirationDate CVV:(NSString *)CVV resolve: (RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
    BMSCardInfo *card = [BMSCardInfo new];
    card.cardNumber = cardNumber;
    card.expirationDate = expirationDate;
    card.CVV = CVV;

    [[BMSAPI instance] generateAccountForCard:card completion:^(BMSAccount *account, NSError *error){
        if (account) {
            resolve(account.token);
        } else {
            reject(@"error", error.localizedDescription, error);
        }
    }];
}
</code>```

Body:
I'm using a library in my react-native project where I'm getting this error

Below is one of the function in the Implementation file of the ios folder of library I'm using. I'm getting error on calling the below function.
Also, I'm getting this error since I updated to Xcode 14.1 (and iOS 16.1), with react-native (0.66.4)

RCT_EXPORT_METHOD(getCardToken:(NSString *)cardNumber expirationDate:(NSString *)expirationDate CVV:(NSString *)CVV resolve: (RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
    BMSCardInfo *card = [BMSCardInfo new];
    card.cardNumber = cardNumber;
    card.expirationDate = expirationDate;
    card.CVV = CVV;

    [[BMSAPI instance] generateAccountForCard:card completion:^(BMSAccount *account, NSError *error){
        if (account) {
            resolve(account.token);
        } else {
            reject(@"error", error.localizedDescription, error);
        }
    }];
}


问:
AWS CDK. Aurora + fargate service
I am trying to create a Fargate Service that connects to an Aurora Postgres DB through the CDK, but I am unable. I get an error connection. This should be pretty straightforward though. Does anybody have any resources?

export class myStack extends cdk.Stack {
    constructor(scope: Construct, id: string, props?: cdk.StackProps) {
        super(scope, id, props);

        const DATABASE_NAME = "myDatabase";

        const vpc = new ec2.Vpc(this, "myVpc");

        const cluster = new ecs.Cluster(this, "myCluster", {
            vpc: vpc
        });

        const databaseAdminSecret = new Secret(this, 'myCredentialsSecret', {
            secretName: 'database-secret',
            description: 'Database auto-generated user password',
            generateSecretString: {
                secretStringTemplate: JSON.stringify({username: 'boss'}),
                generateStringKey: 'password',
                passwordLength: 30,
                excludeCharacters: "\"@/\\",
                excludePunctuation: true,
            }
        });

        const database = new rds.DatabaseCluster(this, 'myDatabase', {
            engine: rds.DatabaseClusterEngine.auroraPostgres({
                version: rds.AuroraPostgresEngineVersion.VER_14_5
            }),
            credentials: rds.Credentials.fromSecret(databaseAdminSecret),
            instanceProps: {
                vpc,
            },
            defaultDatabaseName: DATABASE_NAME,
            port: 5432,
        });

        // Create a load-balanced Fargate service and make it public
        const service = new ecs_patterns.ApplicationLoadBalancedFargateService(this, "myService", {
            cluster: cluster, // Required
            taskImageOptions: {
                image: ecs.ContainerImage.fromRegistry('my-custom-image'),
                environment: {

                    DB_URL: `jdbc:postgresql://${database.clusterEndpoint.socketAddress}/${DATABASE_NAME}`,
                    DB_USERNAME: databaseAdminSecret.secretValueFromJson('username').unsafeUnwrap().toString(),
                    DB_PASSWORD: databaseAdminSecret.secretValueFromJson('password').unsafeUnwrap().toString(),

                },
            },
        });

        // Allow the service to connect to the database
        database.connections.allowDefaultPortFrom(service.service);
    }
}

```

When I spin up this stack with cdk deploy my Fargate service ends up dying because "Connection was refused".

What am I doing wrong?

Thanks,

Title: AWS CDK. Aurora + fargate service

Body:
I am trying to create a Fargate Service that connects to an Aurora Postgres DB through the CDK, but I am unable. I get an error connection. This should be pretty straightforward though. Does anybody have any resources?

export class myStack extends cdk.Stack {
    constructor(scope: Construct, id: string, props?: cdk.StackProps) {
        super(scope, id, props);

        const DATABASE_NAME = "myDatabase";

        const vpc = new ec2.Vpc(this, "myVpc");

        const cluster = new ecs.Cluster(this, "myCluster", {
            vpc: vpc
        });

        const databaseAdminSecret = new Secret(this, 'myCredentialsSecret', {
            secretName: 'database-secret',
            description: 'Database auto-generated user password',
            generateSecretString: {
                secretStringTemplate: JSON.stringify({username: 'boss'}),
                generateStringKey: 'password',
                passwordLength: 30,
                excludeCharacters: "\"@/\\",
                excludePunctuation: true,
            }
        });

        const database = new rds.DatabaseCluster(this, 'myDatabase', {
            engine: rds.DatabaseClusterEngine.auroraPostgres({
                version: rds.AuroraPostgresEngineVersion.VER_14_5
            }),
            credentials: rds.Credentials.fromSecret(databaseAdminSecret),
            instanceProps: {
                vpc,
            },
            defaultDatabaseName: DATABASE_NAME,
            port: 5432,
        });

        // Create a load-balanced Fargate service and make it public
        const service = new ecs_patterns.ApplicationLoadBalancedFargateService(this, "myService", {
            cluster: cluster, // Required
            taskImageOptions: {
                image: ecs.ContainerImage.fromRegistry('my-custom-image'),
                environment: {

                    DB_URL: `jdbc:postgresql://${database.clusterEndpoint.socketAddress}/${DATABASE_NAME}`,
                    DB_USERNAME: databaseAdminSecret.secretValueFromJson('username').unsafeUnwrap().toString(),
                    DB_PASSWORD: databaseAdminSecret.secretValueFromJson('password').unsafeUnwrap().toString(),

                },
            },
        });

        // Allow the service to connect to the database
        database.connections.allowDefaultPortFrom(service.service);
    }
}

When I spin up this stack with cdk deploy my Fargate service ends up dying because "Connection was refused".

What am I doing wrong?

Thanks,