问:
Usage of ID tokens and Access tokens, with external Authentication, AWS backend and graphql language
I am currently working on building a mobile app which will require the users be authenticated, and have them specific privileges on what they can do (for example, a logged in user will only be able to manage some of their data held in the backend database).

I think I do understand the differences between ID token (user identity) and Access token (for authorizing between the mobile phone client and the back-end), but I am not sure what I intend to do conforms to the best practices regarding authentication and authorization.

Let me summarize what I am planning to do:

front end will be a Flutter/Dart mobile app

authentication will be done through Google Firebase Authentication service

my back end will be hosted in AWS:

API Gateway will serve a unique graphQL endpoint

API Gateway has an associated Lambda authorizer function which processes requests prior to the actual "application" Lambda functions

"application" Lambda function serves GraphQL requests (using python ariadne library), including authorization business logic

Database is a managed PostGreSQL inside AWS

The authentication / authorization workflow is as follow:

Not all of this has been implemented yet, but on the paper I think it could work.

However, it goes against several good practices regarding token usage:

the ID token is sent along an API call which is advised against (see this nice auth0 blog post)

I make no usage of access token between the front end and the back-end (could the AWS policy generated at step 5 fullfill this role?)

I do not leverage the audience claims in tokens

Note: as GraphQL exposes a single endpoint, I am not sure of what the content of the access token should be

I am new to Authentication / Authorization and would gladly have some insight regarding the best way to actually make everything work as per best practices, accounting to the following contraints:

authentication is outside of AWS

the APIs are GraphQL


来源: stackexchange

问:
convert and insert, optional field
In convert and insert, is it's possible to have a field optional output to an object, if the data for the field is null?  I don't know if there is a way to configure a schema for such a situation.

I tried looking at the documentation I had from 1.5 years ago.

ContentLicense: CC BY-SA 4.0

Title: convert and insert, optional field


问:
Insert into Oracle Table adds random characters to string when using SQL Server linked server
I am trying to operate a simple INSERT command from my mssql host database into my oracle's linked server destination database.
Our environment is a mssql 2016 server on hostside, oracle 19c linked server database and linked server connection established.

I am trying to INSERT data into my orcle table:

X_PARTNO_BARC, structure as shown:

My Insert statement:

```<code>SELECT
CAST(A.ARANUMMER as varchar(20)) as PARTNO,
CAST(BC.BCCODE as varchar(40)) as EANNUM,
CAST('SQL' as varchar(20)) as CRTUSR,
CAST(format(getdate(),'yyyyMMddhhmmss') as varchar(14)) as CRTDTM
INTO #tmptest
FROM BARCODES BC WITH (NOLOCK)
INNER JOIN AEL A WITH (NOLOCK) ON A.ARIDNR = BC.BCIDNR

INSERT INTO OPENQUERY (DC21WMS,'SELECT * FROM X_PARTNO_BARC')
--(partno,eannum,crtusr,crtdtm)

SELECT * FROM #tmptest

</code>```

My desired output is:

But then it adds these strange characters to my destination columns

What am i doing wrong?
i played a little bit with the column length on host side. eg. using varchar(max) instead. It changes the output but to other strings

Body:
I am trying to operate a simple INSERT command from my mssql host database into my oracle's linked server destination database.
Our environment is a mssql 2016 server on hostside, oracle 19c linked server database and linked server connection established.

I am trying to INSERT data into my orcle table:

X_PARTNO_BARC, structure as shown:

My Insert statement:

SELECT
CAST(A.ARANUMMER as varchar(20)) as PARTNO,
CAST(BC.BCCODE as varchar(40)) as EANNUM,
CAST('SQL' as varchar(20)) as CRTUSR,
CAST(format(getdate(),'yyyyMMddhhmmss') as varchar(14)) as CRTDTM
INTO #tmptest
FROM BARCODES BC WITH (NOLOCK)
INNER JOIN AEL A WITH (NOLOCK) ON A.ARIDNR = BC.BCIDNR

INSERT INTO OPENQUERY (DC21WMS,'SELECT * FROM X_PARTNO_BARC')
--(partno,eannum,crtusr,crtdtm)

SELECT * FROM #tmptest

My desired output is:

But then it adds these strange characters to my destination columns

What am i doing wrong?
i played a little bit with the column length on host side. eg. using varchar(max) instead. It changes the output but to other strings


问:
EF Core 6. Allowing zero to be used as a key
I am working on a system where a composite key can have the value (long > 0, 0). Could be PK(456, 0).
I am looking for a way to tell EF that Zero is okay as a key value. In NHibernate you can set an unsaved value for a key.</p>


问:
Swiper clicking next or prev slide items, moves slider along
In my swiper settings, I have more than 1 slide in view. You can see the current and the previous and next slide.

I'm having trouble making it so that when you click either the next slide or the previous slide it moves the slide in the clicked direction. Currently, it's attached to the classes but this seems to be updating in the html but not in the JS.

```<code>const swiper = new Swiper('.swiper', {
    // Optional parameters
    direction: 'horizontal',
    loop: true,
    slidesPerView: 1.8,
    centeredSlides: true,
    spaceBetween: 10,
    watchSlidesProgress: true,

    // If we need pagination
    pagination: {
        el: '.swiper-pagination',
        dynamicBullets: true,
    },

    // Navigation arrows
    navigation: {
        nextEl: '.swiper-slide-next',
        prevEl: '.swiper-slide-prev',
    },

    // And if we need scrollbar
    scrollbar: {
        el: '.swiper-scrollbar',
    },
});
</code>```

Body:
In my swiper settings, I have more than 1 slide in view. You can see the current and the previous and next slide.

I'm having trouble making it so that when you click either the next slide or the previous slide it moves the slide in the clicked direction. Currently, it's attached to the classes but this seems to be updating in the html but not in the JS.

const swiper = new Swiper('.swiper', {
    // Optional parameters
    direction: 'horizontal',
    loop: true,
    slidesPerView: 1.8,
    centeredSlides: true,
    spaceBetween: 10,
    watchSlidesProgress: true,

    // If we need pagination
    pagination: {
        el: '.swiper-pagination',
        dynamicBullets: true,
    },

    // Navigation arrows
    navigation: {
        nextEl: '.swiper-slide-next',
        prevEl: '.swiper-slide-prev',
    },

    // And if we need scrollbar
    scrollbar: {
        el: '.swiper-scrollbar',
    },
});


问:
tkinter drag-and-drop when clicking near linear objects
In my user interface I want to allow a user to drag a crosshair over a canvas which will be displaying a photo. I observed that it is unreasonably difficult for user to click on the lines of a crosshair to get a "direct hit". I want to be able to drag if the users click is anywhere within the RADIUS of the crosshair, not just on one of the lines. The code here demonstrates this not working, even though my click function is carefully and successfully detecting a hit within that radius.

I would also like for the user to be able to click in a new location, have the crosshair appear there and then be able to drag it from that point.

So far, failing on both counts. You have to hit it directly on the circle or one of the lines in order to drag it. Can anyone suggest a clean fix?

```<code>import tkinter as tk
import math
CROSS_HAIR_SIZE = 30

class View(tk.Canvas):
    def __init__(self, parent, width=1000, height=750):
        super().__init__(parent, width=width, height=height)
        self.pack(fill="both", expand=True)
        self.crosspoint = [-100, -100]
        self.bind("<Button-1>", self.click)

    def crosshair(self, x, y, size, color, tag="cross"):
        a = self.create_line(x - size, y, x + size, y, fill=color, width=1, tag=tag)
        b = self.create_line(x, y - size, x, y + size, fill=color, width=1, tag=tag)
        self.create_oval(x - size, y - size, x + size, y + size, outline=color, tag=tag)
        self.crosspoint = [x, y]

    def click(self, event):
        click1(self, event, (event.x, event.y))

    def startDragging(self, event, tag):
        # note: dragPoint is carried in physical coordinates, not image coordinates
        self.tag_bind(tag, "<ButtonRelease-1>", self.dragStop)
        self.tag_bind(tag, "<B1-Motion>", self.drag)
        self.dragPoint = (event.x, event.y)
        self.dragTag = tag

    def dragStop(self, event):
        if not self.dragPoint: return
        self.crosspoint = (event.x, event.y)
        self.dragPoint = None

    def drag(self, event):
        if not self.dragPoint: return
        # compute how much the mouse has moved
        xy = (event.x, event.y)
        delta = sub(xy, self.dragPoint)
        self.move(self.dragTag, delta[0], delta[1])
        self.dragPoint = xy

def sub(v1, v2):
    return (v1[0] - v2[0], v1[1] - v2[1])

def click1(view, event, xy):
    if math.dist(view.crosspoint, xy) <= CROSS_HAIR_SIZE:
        view.startDragging(event, "cross")
        print("drag inside radius")
    else:
        view.crosspoint = xy
        # it's simplest to just start over with the crosshair
        x, y = xy

        view.delete("cross")
        view.crosshair(x, y, CROSS_HAIR_SIZE, "red", tag="cross")
        view.startDragging(event, "cross")
        print("drag outside radius")

root = tk.Tk()
root.geometry("600x600")
view = View(root)
cross = view.crosshair(150, 150, CROSS_HAIR_SIZE, "red")
root.mainloop()
</code>```

Body:
In my user interface I want to allow a user to drag a crosshair over a canvas which will be displaying a photo. I observed that it is unreasonably difficult for user to click on the lines of a crosshair to get a "direct hit". I want to be able to drag if the users click is anywhere within the RADIUS of the crosshair, not just on one of the lines. The code here demonstrates this not working, even though my click function is carefully and successfully detecting a hit within that radius.

I would also like for the user to be able to click in a new location, have the crosshair appear there and then be able to drag it from that point.

So far, failing on both counts. You have to hit it directly on the circle or one of the lines in order to drag it. Can anyone suggest a clean fix?

import tkinter as tk
import math
CROSS_HAIR_SIZE = 30

class View(tk.Canvas):
    def __init__(self, parent, width=1000, height=750):
        super().__init__(parent, width=width, height=height)
        self.pack(fill="both", expand=True)
        self.crosspoint = [-100, -100]
        self.bind("<Button-1>", self.click)

    def crosshair(self, x, y, size, color, tag="cross"):
        a = self.create_line(x - size, y, x + size, y, fill=color, width=1, tag=tag)
        b = self.create_line(x, y - size, x, y + size, fill=color, width=1, tag=tag)
        self.create_oval(x - size, y - size, x + size, y + size, outline=color, tag=tag)
        self.crosspoint = [x, y]

    def click(self, event):
        click1(self, event, (event.x, event.y))

    def startDragging(self, event, tag):
        # note: dragPoint is carried in physical coordinates, not image coordinates
        self.tag_bind(tag, "<ButtonRelease-1>", self.dragStop)
        self.tag_bind(tag, "<B1-Motion>", self.drag)
        self.dragPoint = (event.x, event.y)
        self.dragTag = tag

    def dragStop(self, event):
        if not self.dragPoint: return
        self.crosspoint = (event.x, event.y)
        self.dragPoint = None

    def drag(self, event):
        if not self.dragPoint: return
        # compute how much the mouse has moved
        xy = (event.x, event.y)
        delta = sub(xy, self.dragPoint)
        self.move(self.dragTag, delta[0], delta[1])
        self.dragPoint = xy

def sub(v1, v2):
    return (v1[0] - v2[0], v1[1] - v2[1])

def click1(view, event, xy):
    if math.dist(view.crosspoint, xy) <= CROSS_HAIR_SIZE:
        view.startDragging(event, "cross")
        print("drag inside radius")
    else:
        view.crosspoint = xy
        # it's simplest to just start over with the crosshair
        x, y = xy

        view.delete("cross")
        view.crosshair(x, y, CROSS_HAIR_SIZE, "red", tag="cross")
        view.startDragging(event, "cross")
        print("drag outside radius")

root = tk.Tk()
root.geometry("600x600")
view = View(root)
cross = view.crosshair(150, 150, CROSS_HAIR_SIZE, "red")
root.mainloop()


问:
wsse:Security Apache-cxf SOAP Web-services exception
We have a legacy SOAP web-services that we are rewriting so we have taken the WSDL files from old web-services and wrote the service side web-services using apache cxf. There are several clients that are using these web-services (so we cannot change anything on client side). Below is old / existing sample soap call-

EXISTING / OLD -

```<code><s:Envelope
    xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
    <s:Header>
        <o:Security s:mustUnderstand="1"
            xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
            <u:Timestamp u:Id="_0">
                <u:Created>2022-12-09T13:05:53.322Z</u:Created>
                <u:Expires>2022-12-09T13:15:53.322Z</u:Expires>
            </u:Timestamp>
            <o:UsernameToken u:Id="uuid-62444dfc-4a39-4c03-8761-15eb4410d435-1">
                <o:Username>****</o:Username>
                <o:Password>****</o:Password>
            </o:UsernameToken>
        </o:Security>
    </s:Header>
    <s:Body
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <readPersonIn
            xmlns="http://j2ee.netbeans.org/wsdl/UpdatePerson">
            <GPN>ABCDEF</GPN>
            <UserId>BCDEFF</UserId>
            <Brand>GOLU</Brand>
        </readPersonIn>
    </s:Body>
</s:Envelope>
</code>```

We used the wsdl and wrote the SOAP api that accepts below call perfectly.

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:upd="http://j2ee.netbeans.org/wsdl/UpdatePerson">
     <soapenv:Header>
   <wsse:Security soapenv:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
         <wsse:UsernameToken wsu:Id="UsernameToken-45845DC0AB964F817E15567362394917">
            <wsse:Username>******</wsse:Username>
            <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">*****</wsse:Password>
         </wsse:UsernameToken>
      </wsse:Security>
   </soapenv:Header>
   <soapenv:Body>
      <upd:readPersonIn>
         <upd:GPN>12345</upd:GPN>
         <upd:UserId>BCDEFF</upd:UserId>
         <upd:Brand>GOLU</upd:Brand>
      </upd:readPersonIn>
   </soapenv:Body>
</soapenv:Envelope>
</code>```

However when we play the legacy / old client call to newly written SOAP API we are getting below exception-

```<code>Dec 12, 2022 4:46:23 PM org.apache.cxf.phase.PhaseInterceptorChain doDefaultLogging
WARNING: Interceptor for {http://j2ee.netbeans.org/wsdl/Person}PersonPortTypeService has thrown exception, unwinding now
org.apache.cxf.binding.soap.SoapFault: A security error was encountered when verifying the message
        at org.apache.cxf.ws.security.wss4j.WSS4JUtils.createSoapFault(WSS4JUtils.java:233)
        at org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor.handleMessageInternal(WSS4JInInterceptor.java:317)
        at org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor.handleMessage(WSS4JInInterceptor.java:171)
        at org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor.handleMessage(WSS4JInInterceptor.java:80)
        at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308)
        at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
        at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:252)
        at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:234)
        at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:208)
        at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:160)
        at org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:180)
        at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:299)
        at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doPost(AbstractHTTPServlet.java:218)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:652)
        at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:274)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:888)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1597)
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.lang.Thread.run(Thread.java:748)
Caused by: org.apache.wss4j.common.ext.WSSecurityException: An error was discovered processing the <wsse:Security> header
        at org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor.checkActions(WSS4JInInterceptor.java:361)
        at org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor.handleMessageInternal(WSS4JInInterceptor.java:276)
        ... 31 more
</code>```

Our limitation is that we cannot change the client code (as we do not have any control and there are several places). It seems it is related to security header processing that new code is not able to process / validate the UserNameToken in old format. Any guidance / help will is appreciated ?.

TIA.
Vijay

We are playing old call with new soap api and getting error.

Body:
We have a legacy SOAP web-services that we are rewriting so we have taken the WSDL files from old web-services and wrote the service side web-services using apache cxf. There are several clients that are using these web-services (so we cannot change anything on client side). Below is old / existing sample soap call-

EXISTING / OLD -

<s:Envelope
    xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
    <s:Header>
        <o:Security s:mustUnderstand="1"
            xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">

                2022-12-09T13:05:53.322Z
                2022-12-09T13:15:53.322Z

            <o:UsernameToken u:Id="uuid-62444dfc-4a39-4c03-8761-15eb4410d435-1">
                <o:Username>****</o:Username>
                <o:Password>****</o:Password>
            </o:UsernameToken>
        </o:Security>
    </s:Header>
    <s:Body
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <readPersonIn
            xmlns="http://j2ee.netbeans.org/wsdl/UpdatePerson">
            <GPN>ABCDEF</GPN>
            <UserId>BCDEFF</UserId>
            <Brand>GOLU</Brand>
        </readPersonIn>
    </s:Body>
</s:Envelope>

We used the wsdl and wrote the SOAP api that accepts below call perfectly.

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:upd="http://j2ee.netbeans.org/wsdl/UpdatePerson">
     <soapenv:Header>
   <wsse:Security soapenv:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
         <wsse:UsernameToken wsu:Id="UsernameToken-45845DC0AB964F817E15567362394917">
            <wsse:Username>******</wsse:Username>
            <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">*****</wsse:Password>
         </wsse:UsernameToken>
      </wsse:Security>
   </soapenv:Header>
   <soapenv:Body>
      <upd:readPersonIn>
         <upd:GPN>12345</upd:GPN>
         <upd:UserId>BCDEFF</upd:UserId>
         <upd:Brand>GOLU</upd:Brand>
      </upd:readPersonIn>
   </soapenv:Body>
</soapenv:Envelope>

However when we play the legacy / old client call to newly written SOAP API we are getting below exception-

Dec 12, 2022 4:46:23 PM org.apache.cxf.phase.PhaseInterceptorChain doDefaultLogging
WARNING: Interceptor for {http://j2ee.netbeans.org/wsdl/Person}PersonPortTypeService has thrown exception, unwinding now
org.apache.cxf.binding.soap.SoapFault: A security error was encountered when verifying the message
        at org.apache.cxf.ws.security.wss4j.WSS4JUtils.createSoapFault(WSS4JUtils.java:233)
        at org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor.handleMessageInternal(WSS4JInInterceptor.java:317)
        at org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor.handleMessage(WSS4JInInterceptor.java:171)
        at org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor.handleMessage(WSS4JInInterceptor.java:80)
        at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308)
        at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
        at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:252)
        at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:234)
        at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:208)
        at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:160)
        at org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:180)
        at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:299)
        at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doPost(AbstractHTTPServlet.java:218)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:652)
        at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:274)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:888)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1597)
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.lang.Thread.run(Thread.java:748)
Caused by: org.apache.wss4j.common.ext.WSSecurityException: An error was discovered processing the <wsse:Security> header
        at org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor.checkActions(WSS4JInInterceptor.java:361)
        at org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor.handleMessageInternal(WSS4JInInterceptor.java:276)
        ... 31 more

Our limitation is that we cannot change the client code (as we do not have any control and there are several places). It seems it is related to security header processing that new code is not able to process / validate the UserNameToken in old format. Any guidance / help will is appreciated ?.

TIA.
Vijay

We are playing old call with new soap api and getting error.


问:
Replace values in a dataframe with intervals from another dataframe
I have two dataframes.

The first looks like this:

```<code>df_1 = pd.DataFrame({ 'x': [pd.Interval(0.0, 50.0, closed='right'),
                        pd.Interval(50.0, np.inf, closed='right')],
                'y':[pd.Interval(-np.inf, 20, closed='left'),
                        pd.Interval(20, np.inf, closed='left')] })

display(df_1)
</code>```

The second one looks like this:

```<code>df_2 = pd.DataFrame({'x':[1, 2, 20,60, 123, 2], 'y':[20, 12, -234, 1222, 1, np.NaN]})
display(df_2)
</code>```

So I want to create a new dataframe which would lookup values in the second dataframe and if they do match within the intervals from the first dataframe, the new dataframe will return the intervals:

```<code>df_3 = pd.DataFrame({'a':[pd.Interval(0.0, 50.0, closed='right'),
                      pd.Interval(0.0, 50.0, closed='right'),
                      pd.Interval(0.0, 50.0, closed='right'),
                      pd.Interval(50.0, np.inf, closed='right'),
                      pd.Interval(50.0, np.inf, closed='right'),
                      pd.Interval(0.0, 50.0, closed='right')],
                 'b':[ pd.Interval(20, np.inf, closed='left'),
                      pd.Interval(20, np.inf, closed='left'),
                       pd.Interval(20, np.inf, closed='left'),
                       pd.Interval(20, np.inf, closed='left'),
                       pd.Interval(20, np.inf, closed='left'),
                      np.NaN]})
display(df_3)
</code>```

Please note that the columns in both tables must be merged to each other. That it is, x to x and y to y respectively.

I have tried using np.select and np.where but it is too time consuming

Body:
I have two dataframes.

The first looks like this:

df_1 = pd.DataFrame({ 'x': [pd.Interval(0.0, 50.0, closed='right'),
                        pd.Interval(50.0, np.inf, closed='right')],
                'y':[pd.Interval(-np.inf, 20, closed='left'),
                        pd.Interval(20, np.inf, closed='left')] })

display(df_1)

The second one looks like this:

df_2 = pd.DataFrame({'x':[1, 2, 20,60, 123, 2], 'y':[20, 12, -234, 1222, 1, np.NaN]})
display(df_2)

So I want to create a new dataframe which would lookup values in the second dataframe and if they do match within the intervals from the first dataframe, the new dataframe will return the intervals:

df_3 = pd.DataFrame({'a':[pd.Interval(0.0, 50.0, closed='right'),
                      pd.Interval(0.0, 50.0, closed='right'),
                      pd.Interval(0.0, 50.0, closed='right'),
                      pd.Interval(50.0, np.inf, closed='right'),
                      pd.Interval(50.0, np.inf, closed='right'),
                      pd.Interval(0.0, 50.0, closed='right')],
                 'b':[ pd.Interval(20, np.inf, closed='left'),
                      pd.Interval(20, np.inf, closed='left'),
                       pd.Interval(20, np.inf, closed='left'),
                       pd.Interval(20, np.inf, closed='left'),
                       pd.Interval(20, np.inf, closed='left'),
                      np.NaN]})
display(df_3)

Please note that the columns in both tables must be merged to each other. That it is, x to x and y to y respectively.

I have tried using np.select and np.where but it is too time consuming


问:
Dotnet Avro reflect with logical types throws exception
I have a record schema which contains a logical type:

{
  "name": "MyRecord",
  "type": "record",
  "namespace": "some.myRecord",
  "fields": [
    {
      "name": "myName",
      "type": "string"
    },
    {
      "name": "myDate",
      "type": [
        "null",
        {
          "type": "int",
          "logicalType": "date"
        }
      ],
      "default": null
    }
  ]
}
```
<p>I declared the c# class as follows:</p>
<pre class="lang-cs prettyprint-override"><code>public class MyRecord
{
  [AvroField("myName")]
  public string MyName{ get; set; }
  [AvroField("myDate", typeof(DateTimeOffsetToLongConverter))]
  public DateTimeOffset MyDate{ get; set; }
}
</code>```

However, when I try to serialize an object, I get an exception:

```<code>   Avro.AvroException : Unknown schema type: Logical in field myDate
---- Avro.AvroException : Unknown schema type: Logical
</code>```

This is the code snippet that I am running:

var classCache = new ClassCache();
var schema = Schema.Parse(definition);
var writer = new ReflectWriter<MyRecord>(schema, classCache);
using (var stream = new MemoryStream())
{
  writer.Write(myRecordInstance, new BinaryEncoder(stream));
}
```

Body:
I have a record schema which contains a logical type:

{
  "name": "MyRecord",
  "type": "record",
  "namespace": "some.myRecord",
  "fields": [
    {
      "name": "myName",
      "type": "string"
    },
    {
      "name": "myDate",
      "type": [
        "null",
        {
          "type": "int",
          "logicalType": "date"
        }
      ],
      "default": null
    }
  ]
}

I declared the c# class as follows:

public class MyRecord
{
  [AvroField("myName")]
  public string MyName{ get; set; }
  [AvroField("myDate", typeof(DateTimeOffsetToLongConverter))]
  public DateTimeOffset MyDate{ get; set; }
}

However, when I try to serialize an object, I get an exception:

   Avro.AvroException : Unknown schema type: Logical in field myDate
---- Avro.AvroException : Unknown schema type: Logical

This is the code snippet that I am running:

var classCache = new ClassCache();
var schema = Schema.Parse(definition);
var writer = new ReflectWriter<MyRecord>(schema, classCache);
using (var stream = new MemoryStream())
{
  writer.Write(myRecordInstance, new BinaryEncoder(stream));
}


问:
Using System.Net.Http.HttpClient in legacy WinForms Framework 4.8 app without async
I have a .Net Framework 4.8 WinForms app which was initially developed over a decade ago before Tasks was a thing in .Net.  Until today the app has never had to worry itself with using Tasks, but the day has finally come.

There is one dependency injection service that needs a new implementation.  It needs to get data from a REST service so will be using the System.Net.Http.HttpClient with all of its Task-based methods.

How does one go about making calls into the System.Net.Http.HttpClient when it is not possible to add async to the calling class?


Title: <script> tag in production

Body:
Google say that they do not recommend using the script tag to include Firebase in a production web app. I don't use build tools and I was wondering if there was a security risk in using script or if it is just best practice for some other reason?

I have looked at the documentation and cant see any explanation as to why script is not recommended for production apps.


问:
Is there an alternative for huggingface's Trainer class for Tensorflow?
I am currnetly trying to find a good trainer for Tensorflow similar to Huggingface's Trainer. However, I am unable to find one with such a reach functionality. Can you recommend me something?

I tried to search on google but with no good result.


问:
What values can we send to Stripe using Omnipay
I have two questions
One:
What values can we send to Stripe using Omnipay authorize(), example below is only sending amount and description

```<code>$response = $gateway->authorize([
     'amount'                   => '10.00',
     'currency'                 => 'USD',
     'description'              => 'This is a test purchase transaction.',
     'paymentMethod'            => $paymentMethod,
     'returnUrl'                => $completePaymentUrl,
     'confirm'                  => true,
 ])->send();
</code>```

what if we want name and email to be sent, how can we achieve this also

Two:
the payment intent we get back from the above request, is generating error log on Godaddy server, I am using the following code;

```<code>$paymentIntentReference = $response->getPaymentIntentReference();
$response = $gateway->confirm([
    'paymentIntentReference' => $paymentIntentReference,
    'returnUrl' => $completePaymentUrl,
])->send();
</code>```

error log: PHP Fatal error:  Uncaught Omnipay\Common\Exception\InvalidRequestException: The paymentIntentReference parameter is required

by my confusion is that in spite of this error log the payment process is being complete, so should I worry about this error or not,

and I hope this time I asked my question in the right manner

thanks in advance

Body:
I have two questions
One:
What values can we send to Stripe using Omnipay authorize(), example below is only sending amount and description

$response = $gateway->authorize([
     'amount'                   => '10.00',
     'currency'                 => 'USD',
     'description'              => 'This is a test purchase transaction.',
     'paymentMethod'            => $paymentMethod,
     'returnUrl'                => $completePaymentUrl,
     'confirm'                  => true,
 ])->send();

what if we want name and email to be sent, how can we achieve this also

Two:
the payment intent we get back from the above request, is generating error log on Godaddy server, I am using the following code;

$paymentIntentReference = $response->getPaymentIntentReference();
$response = $gateway->confirm([
    'paymentIntentReference' => $paymentIntentReference,
    'returnUrl' => $completePaymentUrl,
])->send();

error log: PHP Fatal error:  Uncaught Omnipay\Common\Exception\InvalidRequestException: The paymentIntentReference parameter is required

by my confusion is that in spite of this error log the payment process is being complete, so should I worry about this error or not,

and I hope this time I asked my question in the right manner

thanks in advance


问:
Adding OAuth / OIDC features using KeyCloak to existing application with java backend (run inside Tomcat) and Polymer (javascript) frontend
I have been trying to read through existing information about this topic. I even installed KeyCloak server locally, configured the realm, the client and used Postman to send some requests to KeyCloak, and received some json response.
My problem is that - unless I misunderstand something - none of the descriptions seem to fit my goals.
Our application already has user management and we rely on user identity and roles / access rights configured in the system. The backend runs inside Tomcat and we run a Polymer 1.0 / Javascript frontend to call the REST services of our backend. I cannot get rid of user management as our DB is highly dependant on user to object assignment when deciding the scope of the objects for which the particular user is responsible.
All we need is an extension of our system by the possibility of foreign authentications (like social logins) in the future.

We have now explicit login that delivers a session cookie, Servlet filters to check the presence of this cookie, etc. In the server we use the login token / user identity in each REST call to filter the results from the DB to those available to the particular user.
What I need is a flow like:

in the fronted we check if we have active session (existing code)

if not we redirected the user so far to our own login page, logged in, created the session cookie on server and then returned it. On client side we saved this and added to every REST request as authoriation token.
Now with OIDC I'd like to insert a new unprotected query that checks if OIDC is configured. If not, we keep the old solution. If yes, I'd like to get redirected to KeyCloak login, and - and this is the most important for me - I'd like to get back the user identity (or some role that we associate administratively to the user - using which I could identify one of our configured users.

I tried experimenting with the Tomcat solution but that simply blindly hides the authentication procedure and merely allows or blocks REST access to the backend resources. This is not enough for me, I need some kind of user identity which I can use in the server side.

Also a javascript solution only provides communication between frontend and keycloak, but we need the backend to know who has logged in.

I think this topic and all the used lingo is too complicated for me. Could anyone give me some easy advice how to solve this with best practices?

Thank you very much


问:
Trying to enter the model.py values got this error
If i need to take default value in django rest_framework how should i need to take entries in json format

models.py

```<code>class Employee(models.Model):
    id=models.AutoField(primary_key=True)
    name=models.CharField(max_length=200)
    email=models.CharField(max_length=200,unique=True)
    empid=models.IntegerField(blank=True,null=True)
    phone=models.CharField(max_length=15,unique=True)
</code>```

thunder_client

```<code>{
  "id":1,
  "name":"abhishek kannu",
  "email":"Abhishek17rd@gmail.com",
  "phone":7353557213

}
</code>```

error

```<code>{
  "empid": [
    "This field is required."
  ]
}
</code>```

Body:
If i need to take default value in django rest_framework how should i need to take entries in json format

models.py

class Employee(models.Model):
    id=models.AutoField(primary_key=True)
    name=models.CharField(max_length=200)
    email=models.CharField(max_length=200,unique=True)
    empid=models.IntegerField(blank=True,null=True)
    phone=models.CharField(max_length=15,unique=True)

thunder_client

{
  "id":1,
  "name":"abhishek kannu",
  "email":"Abhishek17rd@gmail.com",
  "phone":7353557213

}

error

{
  "empid": [
    "This field is required."
  ]
}


问:
GitLab CI/CD merge request diff list (with powershell executor)
I am not able to pull data with a list of changed files (based ona merge request) from GitLab API /merge_requests/iid/diff (endpoint does not exist for our instance) so I tried to extract it with a job script.

I have a gitlab runner installed on a remote machine with powershell executor and registered with GitLab.

.yaml:

```<code> info-job:
  stage: build
  tags: testrunner
  script: git diff --name-only remotes/origin/$(CI_MERGE_REQUEST_TARGET_BRANCH_NAME)...(remotes/origin/$(CI_COMMIT_REF_NAME)
</code>```

Execution of this job results in the following error:

```<code>  fatal: ambiguous argument 'remotes/origin/...remotes/origin/main': unknown revision or path not in the working tree.
</code>```

How to pull it off with a script?

Body:
I am not able to pull data with a list of changed files (based ona merge request) from GitLab API /merge_requests/iid/diff (endpoint does not exist for our instance) so I tried to extract it with a job script.

I have a gitlab runner installed on a remote machine with powershell executor and registered with GitLab.

.yaml:

 info-job:
  stage: build
  tags: testrunner
  script: git diff --name-only remotes/origin/$(CI_MERGE_REQUEST_TARGET_BRANCH_NAME)...(remotes/origin/$(CI_COMMIT_REF_NAME)

Execution of this job results in the following error:

  fatal: ambiguous argument 'remotes/origin/...remotes/origin/main': unknown revision or path not in the working tree.

How to pull it off with a script?


问:
How can I get an ImageMap to postback and also stay highlighted?
I am trying to create an ImageMap that highlights areas as you hover, stays highlighted once clicked, and also does a postback so I can load a datagrid based on which area was clicked.

I have it working to highlight on hover and stay highlighted when clicked.  But I can't get it to postback.  I added a dopostback to the javascript and then I was able to postback and get the area clicked, but all of the highlighting stopped.

```<code><script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="Scripts/jquery.maphilight.js" type="text/javascript"></script>
<script src="Scripts/jquery.maphilight.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript"  src="https://cdnjs.cloudflare.com/ajax/libs/maphilight/1.4.0/jquery.maphilight.min.js"></script>

     <script type="text/javascript">
         $(function () {

             $('.map').maphilight({
                 fillColor: '008800'
             });

             $('map area').click(function (e) {
                 e.preventDefault();
                 var clickedArea = $(this); // remember clicked area
                 // foreach area
                 $('map area').each(function () {
                     hData = $(this).data('maphilight') || {}; // get
                     hData.alwaysOn = $(this).is(clickedArea); // modify
                     $(this).data('maphilight', hData).trigger('alwaysOn.maphilight'); // set
                     var strng = String($(this))
                 });
                 $("#lblSelection").empty();
                 $("#lblSelection").text($(this).attr("Id"));

                 //dopostback code here
             });

         });
         function KeepHighlight(elem) {
             var Id = $(elem).attr("Id");
             alert(Id)
             return Id;
         };
         $(function () {
             $('.map').maphilight();
         });

     </script>

      <asp:LinkButton ID="LinkButton1" runat="server" />

<asp:ImageMap Width="600px" CssClass="map rotate_image" ID="BirdsEyeView" runat="Server" ImageUrl="/images/BirdsEyeView.png" Visible="true">
     <asp:PolygonHotSpot PostBackValue="TopRight"  AlternateText="TopRight" Coordinates="74,30,67,39,60,45,70,46,79,47,82,55,83,78,87,114,86,156,82,211,80,219,62,219,64,225,73,232,72,241,26,236,19,235,15,229,13,205,15,195,25,190,35,189,42,193,41,77,20,76,15,73,11,65,14,42,20,31,32,31,55,28" HotSpotMode="PostBack" />
     <asp:PolygonHotSpot PostBackValue="TopLeft" AlternateText="TopLeft" Coordinates="81,47,85,74,86,108,86,139,83,178,83,222,162,220,163,46" HotSpotMode="PostBack" />
     <asp:PolygonHotSpot PostBackValue="MiddleRight" AlternateText="MiddleRight" Coordinates="163,35,163,236,184,234,206,233,247,231,260,231,289,230,322,230,325,34,260,32,247,35,208,34,184,32,166,31" HotSpotMode="PostBack" />
     <asp:PolygonHotSpot PostBackValue="MiddleLeft" AlternateText="MiddleLeft" Coordinates="326,33,324,230,340,231,352,232,365,226,378,217,387,201,393,184,399,167,403,154,404,137,403,118,402,102,399,84,392,63,382,46,374,37,354,33" HotSpotMode="PostBack" />
     <asp:PolygonHotSpot PostBackValue="TopRight" AlternateText="TopRight" Coordinates="366,30,383,41,398,64,403,85,406,112,406,135,406,148,404,164,401,179,393,199,384,213,377,224,367,231,362,235,376,235,395,234,421,232,443,228,461,223,476,218,497,212,520,200,532,193,543,184,553,177,563,165,571,153,579,141,584,130,576,117,563,102,544,81,520,66,499,57,480,49,458,42,434,36,406,30,384,28" HotSpotMode="PostBack" />
     <asp:PolygonHotSpot PostBackValue="TopLeft" AlternateText="TopLeft" Coordinates="62,221,72,231,73,239,114,249,127,250,162,251,201,255,243,257,273,256,297,258,340,258,374,257,426,249,450,246,488,237,512,226,533,214,554,196,567,183,578,168,583,157,591,145,594,135,587,134,584,145,578,154,573,159,559,171,565,163,554,177,545,185,536,191,521,202,507,210,492,216,477,221,457,228,443,231,431,233,414,235,401,236,384,239,369,239,350,242,335,243,313,245,297,246,281,246,265,246,250,245,231,248,214,246,193,245,173,243,164,237,164,221,138,219,120,220,96,219,81,219" HotSpotMode="PostBack" />
     <asp:PolygonHotSpot PostBackValue="MiddleRight" AlternateText="MiddleRight" Coordinates="62,43,77,44,97,42,115,42,138,43,163,43,163,30,159,21,161,13,148,14,129,16,112,17,98,22,81,26,74,27" HotSpotMode="PostBack" />
     <asp:PolygonHotSpot PostBackValue="MiddleLeft" AlternateText="MiddleLeft" Coordinates="585,132,574,115,566,100,549,85,535,74,522,66,504,57,481,47,454,39,424,32,390,27,370,27,352,25,332,24,307,23,280,22,262,22,248,21,227,21,213,21,199,21,184,22,162,25,163,14,187,12,208,11,236,12,269,11,291,10,317,10,342,9,367,10,391,12,408,14,436,18,458,23,477,27,494,32,509,40,525,48,539,58,547,65,561,78,570,88,577,100,586,113,595,131" HotSpotMode="PostBack" />
</asp:ImageMap>

To get it to postback, I'm adding the following where it says //dopostback code here:
     __doPostBack('<%= LinkButton1.UniqueID %>', $(this).attr("Id"));)

</code>```

Body:
I am trying to create an ImageMap that highlights areas as you hover, stays highlighted once clicked, and also does a postback so I can load a datagrid based on which area was clicked.

I have it working to highlight on hover and stay highlighted when clicked.  But I can't get it to postback.  I added a dopostback to the javascript and then I was able to postback and get the area clicked, but all of the highlighting stopped.

      <asp:LinkButton ID="LinkButton1" runat="server" />

<asp:ImageMap Width="600px" CssClass="map rotate_image" ID="BirdsEyeView" runat="Server" ImageUrl="/images/BirdsEyeView.png" Visible="true">
     <asp:PolygonHotSpot PostBackValue="TopRight"  AlternateText="TopRight" Coordinates="74,30,67,39,60,45,70,46,79,47,82,55,83,78,87,114,86,156,82,211,80,219,62,219,64,225,73,232,72,241,26,236,19,235,15,229,13,205,15,195,25,190,35,189,42,193,41,77,20,76,15,73,11,65,14,42,20,31,32,31,55,28" HotSpotMode="PostBack" />
     <asp:PolygonHotSpot PostBackValue="TopLeft" AlternateText="TopLeft" Coordinates="81,47,85,74,86,108,86,139,83,178,83,222,162,220,163,46" HotSpotMode="PostBack" />
     <asp:PolygonHotSpot PostBackValue="MiddleRight" AlternateText="MiddleRight" Coordinates="163,35,163,236,184,234,206,233,247,231,260,231,289,230,322,230,325,34,260,32,247,35,208,34,184,32,166,31" HotSpotMode="PostBack" />
     <asp:PolygonHotSpot PostBackValue="MiddleLeft" AlternateText="MiddleLeft" Coordinates="326,33,324,230,340,231,352,232,365,226,378,217,387,201,393,184,399,167,403,154,404,137,403,118,402,102,399,84,392,63,382,46,374,37,354,33" HotSpotMode="PostBack" />
     <asp:PolygonHotSpot PostBackValue="TopRight" AlternateText="TopRight" Coordinates="366,30,383,41,398,64,403,85,406,112,406,135,406,148,404,164,401,179,393,199,384,213,377,224,367,231,362,235,376,235,395,234,421,232,443,228,461,223,476,218,497,212,520,200,532,193,543,184,553,177,563,165,571,153,579,141,584,130,576,117,563,102,544,81,520,66,499,57,480,49,458,42,434,36,406,30,384,28" HotSpotMode="PostBack" />
     <asp:PolygonHotSpot PostBackValue="TopLeft" AlternateText="TopLeft" Coordinates="62,221,72,231,73,239,114,249,127,250,162,251,201,255,243,257,273,256,297,258,340,258,374,257,426,249,450,246,488,237,512,226,533,214,554,196,567,183,578,168,583,157,591,145,594,135,587,134,584,145,578,154,573,159,559,171,565,163,554,177,545,185,536,191,521,202,507,210,492,216,477,221,457,228,443,231,431,233,414,235,401,236,384,239,369,239,350,242,335,243,313,245,297,246,281,246,265,246,250,245,231,248,214,246,193,245,173,243,164,237,164,221,138,219,120,220,96,219,81,219" HotSpotMode="PostBack" />
     <asp:PolygonHotSpot PostBackValue="MiddleRight" AlternateText="MiddleRight" Coordinates="62,43,77,44,97,42,115,42,138,43,163,43,163,30,159,21,161,13,148,14,129,16,112,17,98,22,81,26,74,27" HotSpotMode="PostBack" />
     <asp:PolygonHotSpot PostBackValue="MiddleLeft" AlternateText="MiddleLeft" Coordinates="585,132,574,115,566,100,549,85,535,74,522,66,504,57,481,47,454,39,424,32,390,27,370,27,352,25,332,24,307,23,280,22,262,22,248,21,227,21,213,21,199,21,184,22,162,25,163,14,187,12,208,11,236,12,269,11,291,10,317,10,342,9,367,10,391,12,408,14,436,18,458,23,477,27,494,32,509,40,525,48,539,58,547,65,561,78,570,88,577,100,586,113,595,131" HotSpotMode="PostBack" />
</asp:ImageMap>

To get it to postback, I'm adding the following where it says //dopostback code here:
     __doPostBack('<%= LinkButton1.UniqueID %>', $(this).attr("Id"));)


问:
Can you Hide your API Key on GH-Pages?
GitHub Pages requires your repository to be public. However, I have an .env variable that is using an API key to call my CMS, and I would not like that API key to be shown.

Does GitHub or GitHub Pages have a way to do that?

I have used a .gitignore, but it does not solve my problem.

Title: Can you Hide your API Key on GH-Pages?


问:
g++ file.cpp -o file -l wolfssl:undefined reference to 'sp_init' collect2: error :ld returned 1 exit status
```<code>#include <iostream>
#include <string>
#include <unistd.h>
#include <wolfssl/options.h>
#include <wolfssl/wolfcrypt/settings.h>
#include <wolfssl/ssl.h>
#include <wolfssl/wolfcrypt/types.h>
#include <wolfssl/wolfcrypt/random.h>
#include <wolfssl/wolfcrypt/ecc.h>
#include <wolfssl/wolfcrypt/sp_int.h>
#include <wolfssl/wolfcrypt/integer.h>
#include <wolfssl/wolfcrypt/wolfmath.h>
using namespace std;
int main(){
    ecc_key key;
    WC_RNG rng;
    wc_ecc_init(&key);
    wc_InitGng(&rng);
    int curveId = ECC_SECP521R1;

    const ecc_set_type* ecc_params;
    ecc_params = wc_ecc_get_curve_params(curveId);

    mp_int ord;     //order of ecc
    mp_int priv;    //privatekey
    int err;
    err = mp_init(&ord);
    cout<<err<<endl;
    err = mp_init(&priv);
    cout<<err<<endl;
    //err = mp_read_radix(&ord,ecc_params->order,MP_RADIX_HEX);   //
    //cout<<err<<endl;
    //err = wc_ecc_gen_k(&rng,120,&priv,&ord)
    return 0 ;
}

</code>```

enter image description here

i have include <wolfssl/wolfcrypt/sp_int.h>,but it told me undefined reference to 'sp_init'，one solution maybe work according tohttps://github.com/wolfSSL/wolfssl/pull/5328,but i  don't quite understand .how to solve this problem

Body:
#include <iostream>
#include <string>
#include <unistd.h>
#include <wolfssl/options.h>
#include <wolfssl/wolfcrypt/settings.h>
#include <wolfssl/ssl.h>
#include <wolfssl/wolfcrypt/types.h>
#include <wolfssl/wolfcrypt/random.h>
#include <wolfssl/wolfcrypt/ecc.h>
#include <wolfssl/wolfcrypt/sp_int.h>
#include <wolfssl/wolfcrypt/integer.h>
#include <wolfssl/wolfcrypt/wolfmath.h>
using namespace std;
int main(){
    ecc_key key;
    WC_RNG rng;
    wc_ecc_init(&key);
    wc_InitGng(&rng);
    int curveId = ECC_SECP521R1;

    const ecc_set_type* ecc_params;
    ecc_params = wc_ecc_get_curve_params(curveId);

    mp_int ord;     //order of ecc
    mp_int priv;    //privatekey
    int err;
    err = mp_init(&ord);
    cout<<err<<endl;
    err = mp_init(&priv);
    cout<<err<<endl;
    //err = mp_read_radix(&ord,ecc_params->order,MP_RADIX_HEX);   //
    //cout<<err<<endl;
    //err = wc_ecc_gen_k(&rng,120,&priv,&ord)
    return 0 ;
}

enter image description here

i have include <wolfssl/wolfcrypt/sp_int.h>,but it told me undefined reference to 'sp_init'，one solution maybe work according tohttps://github.com/wolfSSL/wolfssl/pull/5328,but i  don't quite understand .how to solve this problem


问:
Regarding the keycloak url not being displayed through react app sign in for a client
enter image description here

Failed to parse source map from 'C:\Users\admin\Desktop\KeycloakApp\login-app\node_modules\@react-keycloak\web\lib\@react-keycloak\web\withKeycloak.tsx' file: Error: ENOENT: no such file or directory, open 'C:\Users\admin\Desktop\KeycloakApp\login-app\node_modules\@react-keycloak\web\lib\@react-keycloak\web\withKeycloak.tsx'
```
```import Keycloak from "keycloak-js";
  const keycloak = new Keycloak({
    url: "http://localhost:8080/",
    realm: "Restapi-app",
    clientId: "react-auth"
```

});
export default keycloak;

Body:
enter image description here

Failed to parse source map from 'C:\Users\admin\Desktop\KeycloakApp\login-app\node_modules\@react-keycloak\web\lib\@react-keycloak\web\withKeycloak.tsx' file: Error: ENOENT: no such file or directory, open 'C:\Users\admin\Desktop\KeycloakApp\login-app\node_modules\@react-keycloak\web\lib\@react-keycloak\web\withKeycloak.tsx'

import Keycloak from "keycloak-js";
  const keycloak = new Keycloak({
    url: "http://localhost:8080/",
    realm: "Restapi-app",
    clientId: "react-auth"

});
export default keycloak;


问:
React JS update profile picture and save user settings

here I set the initial value of the avatar the user uploading

I'm trying to let the user upload his profile picture and when clicking the save button, a request is fired and updates the image

```<code>
 <Formik
          initialValues={{
            avatar: imageUploader,
}}
</code>```

the imageUploader is coming from this function:

```<code><a
                    onClick={() => imageUploader.current.click()}
                    onChange={handleImageUpload}
                  >
                    <input
                      type="file"
                      accept="image/*"
                      multiple="false"
                      onChange={(e) =>
                        setFieldValue("avatar", e.currentTarget.files[0])
                      }
                      ref={imageUploader}
                      className="d-none"
                      name="avatar"
                    />
                    Upload a Photo
                  </a>
</code>```

and the image tag itself :

the source of the image is coming from API response:

```<code><img
          src={users.map((user) => user.vocab_avatar)}
          className="rounded-circle img"
          ref={uploadedImage}
        />
</code>```

and when I upload the image and click on save button , the old image appears and doesn't save the uploaded image value

I'm excepting when the user opens the website, his profile picture is being displayed from the database and when the user clicks on upload photo the new photo should be saved

Body:
here I set the initial value of the avatar the user uploading

I'm trying to let the user upload his profile picture and when clicking the save button, a request is fired and updates the image

 <Formik
          initialValues={{
            avatar: imageUploader,
}}

the imageUploader is coming from this function:

 imageUploader.current.click()}
                    onChange={handleImageUpload}
                  >
                    <input
                      type="file"
                      accept="image/*"
                      multiple="false"
                      onChange={(e) =>
                        setFieldValue("avatar", e.currentTarget.files[0])
                      }
                      ref={imageUploader}
                      className="d-none"
                      name="avatar"
                    />
                    Upload a Photo

and the image tag itself :

the source of the image is coming from API response:

 user.vocab_avatar)}
          className="rounded-circle img"
          ref={uploadedImage}
        />

and when I upload the image and click on save button , the old image appears and doesn't save the uploaded image value

I'm excepting when the user opens the website, his profile picture is being displayed from the database and when the user clicks on upload photo the new photo should be saved


问:
Facing issue regarding react-perfect-scrollbar
I'm facing an issue with as scrollbar package(React-Perfect-Scrollbar). Actually this is not issue but default behaviour of scrollbar functionality, while loading list of image. I've given default min-height to image(50px). So, initially scrollbar will cover the scroll area as per the current height of the div, but as soon as the image will load scrollbar adjust its size as per the new height because different image have different height. Because of the entire behaviour i'm seeing the fluctuation in the size of the scrollbar. Is there any way using that way i can overcome this scrollbar?

i have tried some CSS and react-perfect-scrollbar npm package features but not getting the required solution.


问:
Automating Enter PEM pass phrase: in python script
I have a python script that creates ssl context and that is used in websockets.connect like:
async with websockets.connect(serviceURL,ssl=ssl_context) as websocket:

When above code is executed it prompts for PEM pass phrase.
I need to enter pem pass phrase value programmatically form same python script.

Could you pls suggest if the is a way to achieve the same?

I tried something like:

```<code>    child = pexpect.spawn('async with websockets.connect(serviceURL,ssl=ssl_context) as websocket:')

    child.expect('Enter PEM pass phrase:')
    child.sendline('ggadmin123')
</code>```

Still it is asking for passphrase.
Enter PEM pass phrase:

Body:
I have a python script that creates ssl context and that is used in websockets.connect like:
async with websockets.connect(serviceURL,ssl=ssl_context) as websocket:

When above code is executed it prompts for PEM pass phrase.
I need to enter pem pass phrase value programmatically form same python script.

Could you pls suggest if the is a way to achieve the same?

I tried something like:

    child = pexpect.spawn('async with websockets.connect(serviceURL,ssl=ssl_context) as websocket:')

    child.expect('Enter PEM pass phrase:')
    child.sendline('ggadmin123')

Still it is asking for passphrase.
Enter PEM pass phrase:


问:
Is it enough to remove access token and refresh token from front end application or somehow need to remove also from authorization server?
I am trying to learn oauth2 implementation. I am confused here, will it be enough to delete access token and refresh token from front end application or I have to delete it or invalidate any session or something from authorization server also. I am using spring-cloud-security for oauth2. My authorization server code as like below:</p>
```<code>@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private MyClientDetailsService clientDetailsService;

    @Autowired
    private MyUserDetailsService userDetailsService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.checkTokenAccess("isAuthenticated()").tokenKeyAccess("permitAll()");
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(clientDetailsService);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager).userDetailsService(userDetailsService);
    }

}
</code>```

Body:
I am trying to learn oauth2 implementation. I am confused here, will it be enough to delete access token and refresh token from front end application or I have to delete it or invalidate any session or something from authorization server also. I am using spring-cloud-security for oauth2. My authorization server code as like below:

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private MyClientDetailsService clientDetailsService;

    @Autowired
    private MyUserDetailsService userDetailsService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.checkTokenAccess("isAuthenticated()").tokenKeyAccess("permitAll()");
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(clientDetailsService);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager).userDetailsService(userDetailsService);
    }

}


问:
Bind child element position to parent element
I have a navigation that is horizontal. Under every choice I have a div that opens up on click. But the problem is that it binds it's position to the parent navigation button. I want every div that opens on the exact same spot. I want every child div that opens to open from the first element in the navigation bar.
So in this case i want the white open div to bind to "Nyheter" instead. I really can't solve it, I tried set a div element before the navigation that all div that opens binds to in css but it not seems to work.

```<code> <div class="Container">
                <nav class="NavHorizontal Grid Grid--alignMiddle">
                    @Navigation.RenderNavigation("master/navigationDesignHeader.cshtml", navigationSettings)
                </nav>
            </div>

//NavigationDesignheader.cshtml under this line

var elementId = 1;
foreach (var node in nodes)
{
    var idElement = "megaMenu" + elementId;
    <div class="NavHorizontal-item Grid-cell u-sizeFit" id="@idElement">
        <a class="Button Button--tab navigationHeaderLink u-pointer" onclick="toggleMenu('@elementId')">
            @node.Name
        </a>
        @RenderMegaMenu(node.Nodes, node.Link, node.Name)
    </div>
    elementId++;
}
</code>```

Megamenu:

```<code><div>
    <div id="megaMenuDropdown" class="Container megaMenuDropdown-content displayNone">

        <div class="Grid Grid--withGutter">
            <div class="Grid-cell u-sizefull u-mt-10">
                <a href="@nodeLink" class="colorBlue" style="font-size: 20px !important;">@nodeName</a>

                <div class="megaMenuToggle-closeBars u-pointer" style="float:right">
                    <span class="megaMenuToggle-closeBar"></span>
                    <span class="megaMenuToggle-closeBar"></span>
                </div>
            </div>
        </div>

        <hr class="colorBlue" />

        <div class="Grid Grid--withGutter">
            <div class="Grid-cell u-size12of12 u-md-size6of12 u-lg-size6of12">
                <ul>
                    @foreach (var node in firstColumn)
                    {
                        <li class="u-mb-10 linkHover">
                            <a class="userLink colorBlue" href="@node.Link">@node.Name</a>

                        </li>
                    }
                </ul>
            </div>
            @if (moreThanTen)
            {
                <div class="Grid-cell u-size12of12 u-md-size6of12 u-lg-size6of12">
                    <ul>
                        @foreach (var node in secondColumn)
                        {
                            <li class="u-mb-10 linkHover">
                                <a class="userLink colorBlue" href="@node.Link">@node.Name</a>

                            </li>
                        }
                    </ul>
                </div>
            }

        </div>
    </div>
</div>
</code>```

Any suggestions?

Body:
I have a navigation that is horizontal. Under every choice I have a div that opens up on click. But the problem is that it binds it's position to the parent navigation button. I want every div that opens on the exact same spot. I want every child div that opens to open from the first element in the navigation bar.
So in this case i want the white open div to bind to "Nyheter" instead. I really can't solve it, I tried set a div element before the navigation that all div that opens binds to in css but it not seems to work.

                    @Navigation.RenderNavigation("master/navigationDesignHeader.cshtml", navigationSettings)

//NavigationDesignheader.cshtml under this line

var elementId = 1;
foreach (var node in nodes)
{
    var idElement = "megaMenu" + elementId;

            @node.Name

        @RenderMegaMenu(node.Nodes, node.Link, node.Name)

    elementId++;
}

Megamenu:

                @nodeName

                    @foreach (var node in firstColumn)
                    {

                            @node.Name

                    }

            @if (moreThanTen)
            {

                        @foreach (var node in secondColumn)
                        {

                                @node.Name

                        }

            }

Any suggestions?


问:
sklearn decision tree using exactly same criterion multiple times
I have started learning scikit-learn using this tutorial but getting this decision tree

Shouldn't all Start_flow ≤ 0.611 values be separated at the start? There is no duplicate attribute in the dataset.


问:
Rouge-L score very low
I use huggingface transformer api to calculate the rouge score of summarization results. The rouge-1 and rouge-2 scores are fine, but I find my rouge-L score is very low compared to the results in papers.
For example, in the dataset of eife, the baseline model lead-k's rouge scores are 34.12 6.73 32.06, while mine is 37.18 7.97 15.05. Apparently, something goes wrong with my calculation.

Here is my code:

```<code>import evaluate
import transformers
import os
import torch
from datasets import list_datasets, load_dataset
import nltk
import numpy as np

rouge = evaluate.load('rouge')

elife = load_dataset('tomasg25/scientific_lay_summarisation', 'elife')
print(elife)
"""
lexsum = load_dataset('allenai/multi_lexsum')
print(lexsum)
"""
refs = []
predicts_lead3 = []
predicts_leadk = []
for text in elife['test']['summary']:
    refs.append(text)

for text in elife['test']['article']:

    predicts_lead3.append(' '.join(nltk.sent_tokenize(text)[:3]))
    predicts_leadk.append(' '.join(text.split(' ')[:383]))

result_3 = rouge.compute(predictions=predicts_lead3, references=refs)
print("lead 3 results:")
print(result_3)

result_k = rouge.compute(predictions=predicts_leadk, references=refs)
print("lead k results:")
print(result_k)
</code>```

Title: Rouge-L score very low

Body:
I use huggingface transformer api to calculate the rouge score of summarization results. The rouge-1 and rouge-2 scores are fine, but I find my rouge-L score is very low compared to the results in papers.
For example, in the dataset of eife, the baseline model lead-k's rouge scores are 34.12 6.73 32.06, while mine is 37.18 7.97 15.05. Apparently, something goes wrong with my calculation.

Here is my code:

import evaluate
import transformers
import os
import torch
from datasets import list_datasets, load_dataset
import nltk
import numpy as np

rouge = evaluate.load('rouge')

elife = load_dataset('tomasg25/scientific_lay_summarisation', 'elife')
print(elife)
"""
lexsum = load_dataset('allenai/multi_lexsum')
print(lexsum)
"""
refs = []
predicts_lead3 = []
predicts_leadk = []
for text in elife['test']['summary']:
    refs.append(text)

for text in elife['test']['article']:

    predicts_lead3.append(' '.join(nltk.sent_tokenize(text)[:3]))
    predicts_leadk.append(' '.join(text.split(' ')[:383]))

result_3 = rouge.compute(predictions=predicts_lead3, references=refs)
print("lead 3 results:")
print(result_3)

result_k = rouge.compute(predictions=predicts_leadk, references=refs)
print("lead k results:")
print(result_k)


问:
What could I do to speed up this data smoothing function?
The aim for this function is to smooth the data (based on a 1/3 octave window):

```<code>def getRollingMean(data, freq, fLim):
    meanData = []
    for fl in fLim:
        meanData.append(np.mean(data[(freq > fl[0]) & (freq < fl[1])]))
    return np.array(meanData)
</code>```

data is the data I want to smooth.

freq is a frequency axis of the same length as data.

fLim is a 2 columns array where columns 1 is the lower frequency limit of the 1/3 octave and column 2 is the upper frequency limit.
Each row corresponds to a value of freq.

Example:

data = [1,5,3,0]
freq = [100,150,225,337.5]
fLim = [(50, 200),
        (75,300),
        (112 450),
        (168,674)]

# Apply the function to get
mean = [3,3,2.6,3]
```

Unfortunately this function is very slow because I have a big amount of data. The length of the arrays can be for example 720,000!

How could I speed up this function?

Body:
The aim for this function is to smooth the data (based on a 1/3 octave window):

def getRollingMean(data, freq, fLim):
    meanData = []
    for fl in fLim:
        meanData.append(np.mean(data[(freq > fl[0]) & (freq < fl[1])]))
    return np.array(meanData)

data is the data I want to smooth.

freq is a frequency axis of the same length as data.

fLim is a 2 columns array where columns 1 is the lower frequency limit of the 1/3 octave and column 2 is the upper frequency limit.
Each row corresponds to a value of freq.

Example:

data = [1,5,3,0]
freq = [100,150,225,337.5]
fLim = [(50, 200),
        (75,300),
        (112 450),
        (168,674)]

# Apply the function to get
mean = [3,3,2.6,3]

Unfortunately this function is very slow because I have a big amount of data. The length of the arrays can be for example 720,000!

How could I speed up this function?


问:
Doctrine QueryBuilder Join with Subquery
I am looking for a way to perform this query in DQL :

```<code>SELECT
    t0_.product, t0_.creation_date, t0_.id pvId,
    t0_.product AS product,
    t0_.file_path AS file_path_3,
    t0_.product AS product_11
FROM table0 t0_
         join (
    select max(creation_date) as createdDate, id, product
    from table0
    group by product
) t0b on (t0b.createdDate = t0_.creation_date and t0_.product = t0b.product)
         LEFT JOIN table1 t1_ ON t0_.product = t1_.id
         LEFT JOIN table2 t2_ ON t1_.id = t2_.otherId
         LEFT JOIN table3 t3_ ON t2_.id = t3_.otherId
         LEFT JOIN table4 t4_ ON t2_.id = t4_.otherId
         LEFT JOIN table5 t5_ ON t4_.id = t5_.otherId
         LEFT JOIN table6 t6_ ON t4_.id = t6_.otherId
         LEFT JOIN table7 t7_ ON t6_.id = t7_.otherId
WHERE t6_.id = :identifier
GROUP BY p0_.product;
</code>```

explication : I have in table 'table0' several rows linked to table 'table1', I want to keep only the most recent one (column creation_date)

tableA.ID
tableA.propertyTableB.ID
tableA.createdAt

1
1
-4days

2
3
-3days

3
1
yesterday

4
3
today

5
1
today

6
1
-5 days

7
2
yesterday

8
2
today

I need to keep the rows : 4, 5, 8,

I need to get a queryBuilder object in order to do other operations behind it.

Has anyone already succeeded in this feat?

Thanks in advance <3

I need to keep the most recents rows from tableA related to tableB

EDIT : Maybe I find another way
no Select in the Join, just another JOIN like this :

```<code>FROM table0 t0
         LEFT JOIN table0Bis AS t0B ON t0B.identifier = t0.identifier AND t0B.creation_date > t0.creation_date
         LEFT JOIN table1 t1 ON t1.id = t0.foo
         LEFT JOIN table2 t2 ON t1.id = t2.bar
         LEFT JOIN table3 t3 ON t2.id = t3.rab
         LEFT JOIN table4 t4 ON t2.id = t4.oof
         LEFT JOIN table5 t5 ON t5.id = t4.toto
         LEFT JOIN table6 t6 ON t5.id = t6.lorem
         LEFT JOIN table7 t7 ON t6.id = t7.ipsum
where t7.id = :id AND t0B.creation_date IS NULL
group by t0.product;
</code>```

$queryBuilder = $this->createQueryBuilder('t0');

```<code>    $queryBuilder->leftJoin(
        'App\Entity\Table0',
        't0b',
        Join::WITH,
        't0b.product = t0.product AND t0b.creationDate > t0.creationDate')
        ->leftJoin('t0.foo', 't1')
        ->leftJoin('t1.bar', 't2')
        ->leftJoin('t2.bar', 't3')
        ->leftJoin('t3.rab', 't4')
        ->andWhere('t4.id = :ident')->setParameter('ident', $user->getId())
        ->andWhere('t0b.creationDate IS NULL')
        ->groupBy('t0.id', 't0.foobar')
        ->orderBy('t0.foobar', 'DESC')
    ;
</code>```

Body:
I am looking for a way to perform this query in DQL :

SELECT
    t0_.product, t0_.creation_date, t0_.id pvId,
    t0_.product AS product,
    t0_.file_path AS file_path_3,
    t0_.product AS product_11
FROM table0 t0_
         join (
    select max(creation_date) as createdDate, id, product
    from table0
    group by product
) t0b on (t0b.createdDate = t0_.creation_date and t0_.product = t0b.product)
         LEFT JOIN table1 t1_ ON t0_.product = t1_.id
         LEFT JOIN table2 t2_ ON t1_.id = t2_.otherId
         LEFT JOIN table3 t3_ ON t2_.id = t3_.otherId
         LEFT JOIN table4 t4_ ON t2_.id = t4_.otherId
         LEFT JOIN table5 t5_ ON t4_.id = t5_.otherId
         LEFT JOIN table6 t6_ ON t4_.id = t6_.otherId
         LEFT JOIN table7 t7_ ON t6_.id = t7_.otherId
WHERE t6_.id = :identifier
GROUP BY p0_.product;

explication : I have in table 'table0' several rows linked to table 'table1', I want to keep only the most recent one (column creation_date)

tableA.ID
tableA.propertyTableB.ID
tableA.createdAt

1
1
-4days

2
3
-3days

3
1
yesterday

4
3
today

5
1
today

6
1
-5 days

7
2
yesterday

8
2
today

I need to keep the rows : 4, 5, 8,

I need to get a queryBuilder object in order to do other operations behind it.

Has anyone already succeeded in this feat?

Thanks in advance <3

I need to keep the most recents rows from tableA related to tableB

EDIT : Maybe I find another way
no Select in the Join, just another JOIN like this :

FROM table0 t0
         LEFT JOIN table0Bis AS t0B ON t0B.identifier = t0.identifier AND t0B.creation_date > t0.creation_date
         LEFT JOIN table1 t1 ON t1.id = t0.foo
         LEFT JOIN table2 t2 ON t1.id = t2.bar
         LEFT JOIN table3 t3 ON t2.id = t3.rab
         LEFT JOIN table4 t4 ON t2.id = t4.oof
         LEFT JOIN table5 t5 ON t5.id = t4.toto
         LEFT JOIN table6 t6 ON t5.id = t6.lorem
         LEFT JOIN table7 t7 ON t6.id = t7.ipsum
where t7.id = :id AND t0B.creation_date IS NULL
group by t0.product;

$queryBuilder = $this->createQueryBuilder('t0');

    $queryBuilder->leftJoin(
        'App\Entity\Table0',
        't0b',
        Join::WITH,
        't0b.product = t0.product AND t0b.creationDate > t0.creationDate')
        ->leftJoin('t0.foo', 't1')
        ->leftJoin('t1.bar', 't2')
        ->leftJoin('t2.bar', 't3')
        ->leftJoin('t3.rab', 't4')
        ->andWhere('t4.id = :ident')->setParameter('ident', $user->getId())
        ->andWhere('t0b.creationDate IS NULL')
        ->groupBy('t0.id', 't0.foobar')
        ->orderBy('t0.foobar', 'DESC')
    ;


问:
SkLearn: how to add custom constraint to the Lasso implementation?
I'm using scikit-learn's Lasso implementation to solve a given over-determined problem interested in the sparsity and shrinking of the betas. However, I have an extra requirement for my specific problem which is to add a constraint per column (or predictor) element-wise multiplied to the solution so that the sum of each column is zero.

Let's say I have Ax=b with A over-determined and I need to find the best x. I then use Lasso but I also need that the sum of A*x column-wise be zero or as close to zero i.e.

```<code>A = pd.DataFrame(...)
x = ... # lasso solution at iter N
Axx = A*x # note this is element-wise multiplication and not MVM
# my constraint
if Axx.sum(axis=0).max() < 1e-10:
   # accept candidate solution
   return True
else:
   # constraint not satisfied
   return False
</code>```

How can I extend linear_model.Lasso with this extra problem-specific constraint?

Body:
I'm using scikit-learn's Lasso implementation to solve a given over-determined problem interested in the sparsity and shrinking of the betas. However, I have an extra requirement for my specific problem which is to add a constraint per column (or predictor) element-wise multiplied to the solution so that the sum of each column is zero.

Let's say I have Ax=b with A over-determined and I need to find the best x. I then use Lasso but I also need that the sum of A*x column-wise be zero or as close to zero i.e.

A = pd.DataFrame(...)
x = ... # lasso solution at iter N
Axx = A*x # note this is element-wise multiplication and not MVM
# my constraint
if Axx.sum(axis=0).max() < 1e-10:
   # accept candidate solution
   return True
else:
   # constraint not satisfied
   return False

How can I extend linear_model.Lasso with this extra problem-specific constraint?


问:
Webm duration broken
I am recording screen with mediaRecorder in 10 second chunks of video.

Then, with node.js, we put those videos together in a single webm.

The problem is that we can't see the duration of the video when we play it.

We tried the package webm-duration-fix but I can only apply it to the video fragments, and when joining them it is broken

I'm using Javascript on the front and node js on the back. In the back I get the video snippet and then apply fs.appendFileSync

```<code>app.post('/upload/', async (req, res) => {
    let dir = './videos';
    let testeador = req.body.testeador;
    let cliente = req.body.cliente;
    let id = req.body.id;
    let fragmento = req.body.fragmento;
    let idVideo = generateRandomCode()

    res.send('Archivo subido')

    fs.mkdirSync(`${dir}/${cliente}/${testeador}`, {
        recursive: true
    });

    fs.appendFileSync(`${dir}/${cliente}/${testeador}/${testeador}.webm`, req.files.video.data, (err) => {
        if (err) throw err;
    });

})
</code>```

Title: Webm duration broken

Body:
I am recording screen with mediaRecorder in 10 second chunks of video.

Then, with node.js, we put those videos together in a single webm.

The problem is that we can't see the duration of the video when we play it.

We tried the package webm-duration-fix but I can only apply it to the video fragments, and when joining them it is broken

I'm using Javascript on the front and node js on the back. In the back I get the video snippet and then apply fs.appendFileSync

app.post('/upload/', async (req, res) => {
    let dir = './videos';
    let testeador = req.body.testeador;
    let cliente = req.body.cliente;
    let id = req.body.id;
    let fragmento = req.body.fragmento;
    let idVideo = generateRandomCode()

    res.send('Archivo subido')

    fs.mkdirSync(`${dir}/${cliente}/${testeador}`, {
        recursive: true
    });

    fs.appendFileSync(`${dir}/${cliente}/${testeador}/${testeador}.webm`, req.files.video.data, (err) => {
        if (err) throw err;
    });

})


问:
Handling Pledge (performance based) donation with Stripe
I'm working on a fundraiser app.

Users can create a fundraiser - with a donation category - pledges (performance-based) donations.

That means - if a school has a running event - parents (or any other person) can go to a participant's fundraiser page and donate x amount of money per unit (in this case meter)

for example, the parent can decide to donate $1 per meter. therefore, if the kid ran 50 meters, the total amount will be - 50$.

I want to know what will be the best way to handle this kind of donation using Stripe.
What we are doing now is:

Creating a customer (if doesnt exist already) so we can store the card for later use. creating setup intent - sending the client's secret from the back end to the front end.

let customer = stripe.customers.create(options)

stripe.setupIntents.create({customer: customer.id ...})

On the front end - A donor filling the amount per unit (1$ per meter) - the donor can tip the platform (percent of the total amount or flat)

The donor filling the card inside Stripe form.

On the back end - we are attaching the card to the customer, storing data on the db (amount, tip, customer id, intent id)

When the event is over - the user can close the fundraiser and charge all the cards based on the amount and units. for example - we have 10 kids, each kid has 5 donations, each donation is 1$ per meter, and each kid ran 50 meters.

On the back end - we are looping through all the donations related to the fundraiser. creating a payment intent that automatically charged for each donation.

```<code>let donations = Donations.find({fundraiser: fundraiserId...})
donations.forEach((item)=>{
  stripe.paymentIntents.create(
        {
          payment_method: donation.payment_method,
          amount: donation.amount * participant.units + donation.tip,
          off_session: true,
          confirm: true,
          ...
        }
})
</code>```

The issues we are facing:

Stripe rate limiter - allows us to do 100 calls in a second for live mode. that means we need to slow our loop with interval.

Catching errors and success - in order to catch errors and success we need to async await, stripe functions returning promise. the problem with await is that it slows down the loop alot - one solution will be to use webhook to catch all the reponses - the issue is the amount of requests from stripe - we will need also to think about a rate limiter - but in case of multiple users requesting donations charges we can end up with many many incoming requests from stripe.

To not let all the users to request payments at once (to prevent massive requests - and sending massive amount of requests to stripe) - we need to handle a queue system (so we will not exceed the limit by Stripe and we can handle incoming requests from stripe). what do you think can be a good queue system - should it be on a seperate server? - do you think there is a better solution?

what fo you think would be the best approach in general to achieve the pledges (performance based) donations system.

**I can share more code if needed. and im willing to answer any question to clear it out.

Body:
I'm working on a fundraiser app.

Users can create a fundraiser - with a donation category - pledges (performance-based) donations.

That means - if a school has a running event - parents (or any other person) can go to a participant's fundraiser page and donate x amount of money per unit (in this case meter)

for example, the parent can decide to donate $1 per meter. therefore, if the kid ran 50 meters, the total amount will be - 50$.

I want to know what will be the best way to handle this kind of donation using Stripe.
What we are doing now is:

Creating a customer (if doesnt exist already) so we can store the card for later use. creating setup intent - sending the client's secret from the back end to the front end.

let customer = stripe.customers.create(options)

stripe.setupIntents.create({customer: customer.id ...})

On the front end - A donor filling the amount per unit (1$ per meter) - the donor can tip the platform (percent of the total amount or flat)

The donor filling the card inside Stripe form.

On the back end - we are attaching the card to the customer, storing data on the db (amount, tip, customer id, intent id)

When the event is over - the user can close the fundraiser and charge all the cards based on the amount and units. for example - we have 10 kids, each kid has 5 donations, each donation is 1$ per meter, and each kid ran 50 meters.

On the back end - we are looping through all the donations related to the fundraiser. creating a payment intent that automatically charged for each donation.

let donations = Donations.find({fundraiser: fundraiserId...})
donations.forEach((item)=>{
  stripe.paymentIntents.create(
        {
          payment_method: donation.payment_method,
          amount: donation.amount * participant.units + donation.tip,
          off_session: true,
          confirm: true,
          ...
        }
})

The issues we are facing:

Stripe rate limiter - allows us to do 100 calls in a second for live mode. that means we need to slow our loop with interval.

Catching errors and success - in order to catch errors and success we need to async await, stripe functions returning promise. the problem with await is that it slows down the loop alot - one solution will be to use webhook to catch all the reponses - the issue is the amount of requests from stripe - we will need also to think about a rate limiter - but in case of multiple users requesting donations charges we can end up with many many incoming requests from stripe.

To not let all the users to request payments at once (to prevent massive requests - and sending massive amount of requests to stripe) - we need to handle a queue system (so we will not exceed the limit by Stripe and we can handle incoming requests from stripe). what do you think can be a good queue system - should it be on a seperate server? - do you think there is a better solution?

what fo you think would be the best approach in general to achieve the pledges (performance based) donations system.

**I can share more code if needed. and im willing to answer any question to clear it out.


问:
How to atomically insert records with unique ordinal numbers specific to a certain column?
I have a database with two tables. The first one holds customers (most columns truncated for brevity):

CustomerId
Name

1
Wipers

2
Wipers Central

3
Ministores

4
Minerals

The second one holds their respective codes, that are used on documents:

CustomerId
CodePrefix
Ordinal

1
WIP
1

2
WIP
2

3
MIN
1

4
MIN
2

A customer code consists of a three-letter prefix and an ordinal number. A unique constraint is applied to CodePrefix and Ordinal.

I struggle to make an SQL statement that inserts new codes to the second table when multiple users try to assign document codes to customers with similar names at the same time.

What I've tried:

```<code>INSERT INTO CustomerCodes
(CustomerId, CodePrefix, Ordinal)
VALUES
(1, 'WIP',
  (
   SELECT ISNULL(MAX(Ordinal), 0) + 1
   FROM CustomerCodes
   WHERE CodePrefix = 'WIP'
  )
)
</code>```

It works most of the time, but for many simultaneous operations I get unique constraint violation.

What should I do to make it work regardless of how many concurrent transactions happens at the same time?

Body:
I have a database with two tables. The first one holds customers (most columns truncated for brevity):

CustomerId
Name

1
Wipers

2
Wipers Central

3
Ministores

4
Minerals

The second one holds their respective codes, that are used on documents:

CustomerId
CodePrefix
Ordinal

1
WIP
1

2
WIP
2

3
MIN
1

4
MIN
2

A customer code consists of a three-letter prefix and an ordinal number. A unique constraint is applied to CodePrefix and Ordinal.

I struggle to make an SQL statement that inserts new codes to the second table when multiple users try to assign document codes to customers with similar names at the same time.

What I've tried:

INSERT INTO CustomerCodes
(CustomerId, CodePrefix, Ordinal)
VALUES
(1, 'WIP',
  (
   SELECT ISNULL(MAX(Ordinal), 0) + 1
   FROM CustomerCodes
   WHERE CodePrefix = 'WIP'
  )
)

It works most of the time, but for many simultaneous operations I get unique constraint violation.

What should I do to make it work regardless of how many concurrent transactions happens at the same time?


问:
How to combine multiple images with one signal data in a dataset (Python/PyTorch/MultiModal)
I want to build a multimodal model, for every signal sequence i have several pictures.

Example:
For example i have 10 images that correspond to 5sec force data, which i want to combine in one batch.
That means i want to build a model where those 10 images will be "concatenated" with the force data (for example an array of one force value per ms).

That means i have for example 10 pictures with 3 * 480 * 720 dimensions and one force data (for example an array of lenght 5000) that i want to execute in one batch.

My question is how can i combine them in PyTorch so could create a multimodal model?

I tried to build a multimodla model and i am expecting to receive a code example how it could function (combining/executing 10 pictures in one batch).


问:
Translate a column with English and Dutch text to only English using GoogleTrans
I have a data frame with tweets and I want to translate it to only English. The problem is that the source column has both English and Dutch tweets. I used the following code to try to translate this column:

```<code>from googletrans import Translator
translator = Translator()

df_posts['text_en'] = df_posts['text'].apply(lambda x: translator.translate(x, dest='en').text)
</code>```

I tried some other code from stack as well, but nothing worked. I did update the translator package, so I don't have the common NoneType error anymore. The error I get looks like this:

error that needs to be solved

The source data in the "text" column from the df_posts data frame looks like this (note that this part only shows the English text that doesn't need to be translated):

data that needs translating

Body:
I have a data frame with tweets and I want to translate it to only English. The problem is that the source column has both English and Dutch tweets. I used the following code to try to translate this column:

from googletrans import Translator
translator = Translator()

df_posts['text_en'] = df_posts['text'].apply(lambda x: translator.translate(x, dest='en').text)

I tried some other code from stack as well, but nothing worked. I did update the translator package, so I don't have the common NoneType error anymore. The error I get looks like this:

error that needs to be solved

The source data in the "text" column from the df_posts data frame looks like this (note that this part only shows the English text that doesn't need to be translated):

data that needs translating


问:
Simulate click event in Matplotlib that triggers a pick event
I have a Matplotlib figure, with some lines.
I have a remove function that is called when a line is picked.
The function simply removes the artist from the axes when the pick event is fired.

I would like to be able to programmatically simulate a mouse click that would trigger the pick event, if the (x, y) position of the click is exactly on (or close enough to) a line vertex.

import numpy as np
import matplotlib.pyplot as plt

def remove(event):
    event.artist.remove()

N = 10
fig, ax = plt.subplots()
for i in range(N):
    line, = ax.plot(np.random.random(2), np.random.random(2), '-o', picker=5.0)

fig.canvas.mpl_connect('pick_event', remove)
```

I could call the remove function directly, with some (x, y) coordinates, but this would require me to know in advance which artist it corresponds to, instead of just letting Matplotlib figure that out, just like it does when I click with my mouse.

Basically, a function like simulate_pick(ax, x, y) that would:

do nothing if the (x, y) coords are not close enough to a line on the figure

call remove if (x, y) is close enough to a line

Body:
I have a Matplotlib figure, with some lines.
I have a remove function that is called when a line is picked.
The function simply removes the artist from the axes when the pick event is fired.

I would like to be able to programmatically simulate a mouse click that would trigger the pick event, if the (x, y) position of the click is exactly on (or close enough to) a line vertex.

import numpy as np
import matplotlib.pyplot as plt

def remove(event):
    event.artist.remove()

N = 10
fig, ax = plt.subplots()
for i in range(N):
    line, = ax.plot(np.random.random(2), np.random.random(2), '-o', picker=5.0)

fig.canvas.mpl_connect('pick_event', remove)

I could call the remove function directly, with some (x, y) coordinates, but this would require me to know in advance which artist it corresponds to, instead of just letting Matplotlib figure that out, just like it does when I click with my mouse.

Basically, a function like simulate_pick(ax, x, y) that would:

do nothing if the (x, y) coords are not close enough to a line on the figure

call remove if (x, y) is close enough to a line


问:
Django and Flutter configuration
How do i configure Django and Flutter for local development and how do i configure them for the deployment in a server? (Flutter as a frontend web project). I have tried to add static files directories in settings file. But I'm not sure what value do i give to this variable. Do i assign os.path.join(BASE_DIR, 'flutter_project/build/web/assets') to static files directories or do i have to assign something else?</p>

Title: Django and Flutter configuration


问:
Vercel deployment Error: Command "CI='' npm run build" exited with 1
I was making my portfolio with NextJs and testing live how it looks in production, anyway, everything was perfect until I make a component with grid images, the Vercel terminal shows an error, and then searched for the solution. The code doesn't shows any warnings or something like that.

I have to change the command build to CI='' npm run build, but now my project is okay with a new URL and my component with the images doesn't show, just 1 image is in the site. I don't know why, but now in the terminal, it shows me :

```<code>[10:07:12.718] Cloning github.com/LucianoCerullo77/portfoliov2 (Branch: main, Commit: ab73db1)
[10:07:12.723] Skipping build cache since Vercel CLI used --force option
[10:07:13.125] Cloning completed: 407.165ms
[10:07:13.532] Running "vercel build"
[10:07:14.022] Vercel CLI 28.8.0
[10:07:14.319] Installing dependencies...
[10:07:22.608]
[10:07:22.608] added 288 packages in 8s
[10:07:22.608]
[10:07:22.608] 98 packages are looking for funding
[10:07:22.609]   run `npm fund` for details
[10:07:22.625] Detected Next.js version: 13.0.6
[10:07:22.627] Running "CI='' npm run build"
[10:07:22.923]
[10:07:22.924] > portfoliov2@0.1.0 build
[10:07:22.924] > next build
[10:07:22.924]
[10:07:23.364] Attention: Next.js now collects completely anonymous telemetry regarding usage.
[10:07:23.365] This information is used to shape Next.js' roadmap and prioritize features.
[10:07:23.365] You can learn more, including how to opt-out if you'd not like to participate in this anonymous program, by visiting the following URL:
[10:07:23.365] https://nextjs.org/telemetry
[10:07:23.365]
[10:07:23.491] info  - Linting and checking validity of types...
[10:07:23.868] error - ESLint: Failed to load config "next/babel" to extend from. Referenced from: /vercel/path0/.eslintrc.json
[10:07:23.875] info  - Creating an optimized production build...
[10:07:23.919] info  - Disabled SWC as replacement for Babel because of custom Babel configuration ".babelrc" https://nextjs.org/docs/messages/swc-disabled
[10:07:24.425] info  - Using external babel configuration from /vercel/path0/.babelrc
[10:07:28.276] Failed to compile.
[10:07:28.277]
[10:07:28.277] ./components/Projects/index.jsx
[10:07:28.277] Module not found: Can't resolve '../../public/projects/Fennex.png' in '/vercel/path0/components/Projects'
[10:07:28.277]
[10:07:28.277] Import trace for requested module:
[10:07:28.278] ./components/Projects/index.jsx
[10:07:28.278]
[10:07:28.278] ./components/Projects/index.jsx
[10:07:28.278] Module not found: Can't resolve '../../public/projects/Olivia.png' in '/vercel/path0/components/Projects'
[10:07:28.278]
[10:07:28.278] Import trace for requested module:
[10:07:28.278] ./components/Projects/index.jsx
[10:07:28.278]
[10:07:28.278]
[10:07:28.278] > Build failed because of webpack errors
[10:07:28.310] Error: Command "CI='' npm run build" exited with 1
</code>```

I need help, I don't know how to fix it.

Body:
I was making my portfolio with NextJs and testing live how it looks in production, anyway, everything was perfect until I make a component with grid images, the Vercel terminal shows an error, and then searched for the solution. The code doesn't shows any warnings or something like that.

I have to change the command build to CI='' npm run build, but now my project is okay with a new URL and my component with the images doesn't show, just 1 image is in the site. I don't know why, but now in the terminal, it shows me :

[10:07:12.718] Cloning github.com/LucianoCerullo77/portfoliov2 (Branch: main, Commit: ab73db1)
[10:07:12.723] Skipping build cache since Vercel CLI used --force option
[10:07:13.125] Cloning completed: 407.165ms
[10:07:13.532] Running "vercel build"
[10:07:14.022] Vercel CLI 28.8.0
[10:07:14.319] Installing dependencies...
[10:07:22.608]
[10:07:22.608] added 288 packages in 8s
[10:07:22.608]
[10:07:22.608] 98 packages are looking for funding
[10:07:22.609]   run `npm fund` for details
[10:07:22.625] Detected Next.js version: 13.0.6
[10:07:22.627] Running "CI='' npm run build"
[10:07:22.923]
[10:07:22.924] > portfoliov2@0.1.0 build
[10:07:22.924] > next build
[10:07:22.924]
[10:07:23.364] Attention: Next.js now collects completely anonymous telemetry regarding usage.
[10:07:23.365] This information is used to shape Next.js' roadmap and prioritize features.
[10:07:23.365] You can learn more, including how to opt-out if you'd not like to participate in this anonymous program, by visiting the following URL:
[10:07:23.365] https://nextjs.org/telemetry
[10:07:23.365]
[10:07:23.491] info  - Linting and checking validity of types...
[10:07:23.868] error - ESLint: Failed to load config "next/babel" to extend from. Referenced from: /vercel/path0/.eslintrc.json
[10:07:23.875] info  - Creating an optimized production build...
[10:07:23.919] info  - Disabled SWC as replacement for Babel because of custom Babel configuration ".babelrc" https://nextjs.org/docs/messages/swc-disabled
[10:07:24.425] info  - Using external babel configuration from /vercel/path0/.babelrc
[10:07:28.276] Failed to compile.
[10:07:28.277]
[10:07:28.277] ./components/Projects/index.jsx
[10:07:28.277] Module not found: Can't resolve '../../public/projects/Fennex.png' in '/vercel/path0/components/Projects'
[10:07:28.277]
[10:07:28.277] Import trace for requested module:
[10:07:28.278] ./components/Projects/index.jsx
[10:07:28.278]
[10:07:28.278] ./components/Projects/index.jsx
[10:07:28.278] Module not found: Can't resolve '../../public/projects/Olivia.png' in '/vercel/path0/components/Projects'
[10:07:28.278]
[10:07:28.278] Import trace for requested module:
[10:07:28.278] ./components/Projects/index.jsx
[10:07:28.278]
[10:07:28.278]
[10:07:28.278] > Build failed because of webpack errors
[10:07:28.310] Error: Command "CI='' npm run build" exited with 1

I need help, I don't know how to fix it.


问:
I want to get count of null from each column of mysql table
I want to get the null count from each MySQL table column. I do not want to hardcode for a specific table. This means if I change the table name in the query and it will give me the null count of all the columns of that table</p>