问:
How to replace default user-agent sent with gRPC request in basic gRPC implementation using .NET Grpc.Net.* packages?
I've noticed that, if I sent a gRPC request using .NET Grpc.Net.* implementation, the client automatically attaches some headers to the request. Please consider the following snippet:

```<code>public class Dummy
{
    private readonly OrderingService.OrdersClient _ordersClient;
    private readonly IDateTimeProvider _dateTimeProvider;

    public Dummy(
        OrderingService.OrdersClient ordersClient,
        IDateTimeProvider dateTimeProvider)
    {
        _ordersClient = ordersClient;
        _dateTimeProvider = dateTimeProvider;
    }

    protected override async Task<GetOrdersResponseModel> GetOrderInfoAsync(GetOrdersRequestModel request)
    {
        var deadline = _dateTimeProvider.UtcTimestamp.AddMilliseconds(5000);

        var response = await _ordersClient.GetOrdersAsync(
            request,
            deadline: deadline);

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

Don't mind the simplicity of this snippet - it's just for example purposes. In here I inject the gRPC client, and I don't set any user-agent metadata header. If I inspected the request metadata on the server side in that case I get the following string:

```<code>Headers: {x-grpc-full-method-name=xxx, grpc-accept-encoding=identity,gzip,deflate, traceparent=xxx, content-type=application/grpc, user-agent=grpc-dotnet/2.49.0 (.NET 6.0.4; CLR 6.0.4; net6.0; windows; x64), grpc-timeout=984m}
</code>```

The gRPC client adds some info about the user-agent automatically. If I tried to set the user-agent header value manually using the following code:

```<code>public class Dummy
{
    private readonly OrderingService.OrdersClient _ordersClient;
    private readonly IDateTimeProvider _dateTimeProvider;

    public Dummy(
        OrderingService.OrdersClient ordersClient,
        IDateTimeProvider dateTimeProvider)
    {
        _ordersClient = ordersClient;
        _dateTimeProvider = dateTimeProvider;
    }

    protected override async Task<GetOrdersResponseModel> GetOrderInfoAsync(GetOrdersRequestModel request)
    {
        var deadline = _dateTimeProvider.UtcTimestamp.AddMilliseconds(5000);
        var metadata = new Metadata { { "user-agent", "foo" } };

        var response = await _ordersClient.GetOrdersAsync(
            request,
            metadata,
            deadline: deadline);

        ...
    }
}

</code>```

I get something like this:

```<code>Headers: {x-grpc-full-method-name=xxx, grpc-accept-encoding=identity,gzip,deflate, traceparent=xxx, content-type=application/grpc, user-agent=grpc-dotnet/2.49.0 (.NET 6.0.4; CLR 6.0.4; net6.0; windows; x64) foo, grpc-timeout=984m}
</code>```

The "foo" has been concatenated to the user-agent header, but I'd like to replace the whole string in there. So I wish to have that one:

```<code>Headers: {x-grpc-full-method-name=xxx, grpc-accept-encoding=identity,gzip,deflate, traceparent=xxx, content-type=application/grpc, user-agent=foo, grpc-timeout=984m}
</code>```

How to achieve that using .NET implementation for gRPC?? Could anyone help? Thanks in advance!

Body:
I've noticed that, if I sent a gRPC request using .NET Grpc.Net.* implementation, the client automatically attaches some headers to the request. Please consider the following snippet:

public class Dummy
{
    private readonly OrderingService.OrdersClient _ordersClient;
    private readonly IDateTimeProvider _dateTimeProvider;

    public Dummy(
        OrderingService.OrdersClient ordersClient,
        IDateTimeProvider dateTimeProvider)
    {
        _ordersClient = ordersClient;
        _dateTimeProvider = dateTimeProvider;
    }

    protected override async Task<GetOrdersResponseModel> GetOrderInfoAsync(GetOrdersRequestModel request)
    {
        var deadline = _dateTimeProvider.UtcTimestamp.AddMilliseconds(5000);

        var response = await _ordersClient.GetOrdersAsync(
            request,
            deadline: deadline);

        ...
    }
}

Don't mind the simplicity of this snippet - it's just for example purposes. In here I inject the gRPC client, and I don't set any user-agent metadata header. If I inspected the request metadata on the server side in that case I get the following string:

Headers: {x-grpc-full-method-name=xxx, grpc-accept-encoding=identity,gzip,deflate, traceparent=xxx, content-type=application/grpc, user-agent=grpc-dotnet/2.49.0 (.NET 6.0.4; CLR 6.0.4; net6.0; windows; x64), grpc-timeout=984m}

The gRPC client adds some info about the user-agent automatically. If I tried to set the user-agent header value manually using the following code:

public class Dummy
{
    private readonly OrderingService.OrdersClient _ordersClient;
    private readonly IDateTimeProvider _dateTimeProvider;

    public Dummy(
        OrderingService.OrdersClient ordersClient,
        IDateTimeProvider dateTimeProvider)
    {
        _ordersClient = ordersClient;
        _dateTimeProvider = dateTimeProvider;
    }

    protected override async Task<GetOrdersResponseModel> GetOrderInfoAsync(GetOrdersRequestModel request)
    {
        var deadline = _dateTimeProvider.UtcTimestamp.AddMilliseconds(5000);
        var metadata = new Metadata { { "user-agent", "foo" } };

        var response = await _ordersClient.GetOrdersAsync(
            request,
            metadata,
            deadline: deadline);

        ...
    }
}

I get something like this:

Headers: {x-grpc-full-method-name=xxx, grpc-accept-encoding=identity,gzip,deflate, traceparent=xxx, content-type=application/grpc, user-agent=grpc-dotnet/2.49.0 (.NET 6.0.4; CLR 6.0.4; net6.0; windows; x64) foo, grpc-timeout=984m}

The "foo" has been concatenated to the user-agent header, but I'd like to replace the whole string in there. So I wish to have that one:

Headers: {x-grpc-full-method-name=xxx, grpc-accept-encoding=identity,gzip,deflate, traceparent=xxx, content-type=application/grpc, user-agent=foo, grpc-timeout=984m}

How to achieve that using .NET implementation for gRPC?? Could anyone help? Thanks in advance!


来源: stackexchange

问:
Retry of failed message in Kafka Spring Webflux using Kotlin
I am trying to setup the Kafka reactive Consumer the way it retries processing of a message when it is not acknowledged. The issue is the message is never retried and processed only once. Here are parts of code invoked by my automated test...
My ReactiveKafkaConsumerTemplate looks like this:

```<code>    @Bean
    fun testKafkaConsumerTemplate(kafkaProperties: KafkaProperties): ReactiveKafkaConsumerTemplate<String, TestDto> {
        val props = kafkaProperties.buildConsumerProperties()
        val basicReceiverOptions: ReceiverOptions<String, TestDto> = ReceiverOptions.create(props)
        val kafkaReceiverOptions = basicReceiverOptions.commitInterval(Duration.ZERO)
                .commitBatchSize(1)
                .pollTimeout(Duration.ofSeconds(2))
                .subscription(Collections.singletonList("TestTopic"))
        return ReactiveKafkaConsumerTemplate(kafkaReceiverOptions)
    }
</code>```

additional config from application.yml

```<code>spring:
  kafka:
    bootstrap-servers: localhost:9092
    producer:
      key-serializer: org.apache.kafka.common.serialization.StringSerializer
      value-serializer: org.springframework.kafka.support.serializer.JsonSerializer
    consumer:
      group-id: messaging-java
      key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
      value-deserializer: org.springframework.kafka.support.serializer.JsonDeserializer
      auto-offset-reset: earliest
      enable-auto-commit: false
</code>```

Here you can see in my test consumer I am just throwing an exeption when a message is processed for the first time so it is ton acknowledged. But the retry never happens (My automated test is waiting 20 seconds for the retry), the consumer runs the message processing just once

```<code> @EventListener(ApplicationReadyEvent::class)
    fun consume() {
        testKafkaConsumerTemplate.receive()
                .doOnCancel {
                    coroutineScope.cancel()
                }
                .doOnNext { record ->
                    coroutineScope.launch {
                        log.info("Received a confirmation in the TestTopic")
                        try {
                            counter++
                            if (counter == 1L) {
                                throw RuntimeException("Controlled testing exception")
                            }
                            record.receiverOffset().acknowledge()
                        } catch (ex: Exception) {

                            log.info("Error in processing TestDto")
                        }
                    }
                }.subscribe()
    }
</code>```

Any idea what am I missing?

ContentLicense: CC BY-SA 4.0

Body:
I am trying to setup the Kafka reactive Consumer the way it retries processing of a message when it is not acknowledged. The issue is the message is never retried and processed only once. Here are parts of code invoked by my automated test...
My ReactiveKafkaConsumerTemplate looks like this:

    @Bean
    fun testKafkaConsumerTemplate(kafkaProperties: KafkaProperties): ReactiveKafkaConsumerTemplate<String, TestDto> {
        val props = kafkaProperties.buildConsumerProperties()
        val basicReceiverOptions: ReceiverOptions<String, TestDto> = ReceiverOptions.create(props)
        val kafkaReceiverOptions = basicReceiverOptions.commitInterval(Duration.ZERO)
                .commitBatchSize(1)
                .pollTimeout(Duration.ofSeconds(2))
                .subscription(Collections.singletonList("TestTopic"))
        return ReactiveKafkaConsumerTemplate(kafkaReceiverOptions)
    }

additional config from application.yml

spring:
  kafka:
    bootstrap-servers: localhost:9092
    producer:
      key-serializer: org.apache.kafka.common.serialization.StringSerializer
      value-serializer: org.springframework.kafka.support.serializer.JsonSerializer
    consumer:
      group-id: messaging-java
      key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
      value-deserializer: org.springframework.kafka.support.serializer.JsonDeserializer
      auto-offset-reset: earliest
      enable-auto-commit: false

Here you can see in my test consumer I am just throwing an exeption when a message is processed for the first time so it is ton acknowledged. But the retry never happens (My automated test is waiting 20 seconds for the retry), the consumer runs the message processing just once

 @EventListener(ApplicationReadyEvent::class)
    fun consume() {
        testKafkaConsumerTemplate.receive()
                .doOnCancel {
                    coroutineScope.cancel()
                }
                .doOnNext { record ->
                    coroutineScope.launch {
                        log.info("Received a confirmation in the TestTopic")
                        try {
                            counter++
                            if (counter == 1L) {
                                throw RuntimeException("Controlled testing exception")
                            }
                            record.receiverOffset().acknowledge()
                        } catch (ex: Exception) {

                            log.info("Error in processing TestDto")
                        }
                    }
                }.subscribe()
    }

Any idea what am I missing?


问:
Equation not viewing properly in tinymce editor
Integrated tinymce-equation-editor plugin in TinyMCE editor. When adding equation through the plugin window, it is not viewing properly in the TinyMCE editor.

Eequation in plugin window

Same equation when inserted in TinyMCE editor

Tried adding equations.


问:
How to prevent overlapping in react-chartjs-2 and make chart bar scrollable?
I am trying to draw a bar chart using react-chartjs-2, i am using typescript
because i have a big amount of data, there is overlapping in the chart, i want to prevent overlapping, instead of that, i want horizontal scrolling

my config is as follow:

```<code>// options
export const options = {
  responsive: true,
  maintainAspectRatio: false,
  plugins: {
    legend: {
      display: false,
    },
  },
  scales: {
    x: {
      beginAtZero: 0,
      labelAutoFit: false,
      grid: {
        offset: false,
      },
    },
  },
};

// labels
const labels = [...new Array(200)].map((_, i) => i * 3);

// data
export const data = {
  labels,
  datasets: [
    {
      label: 'Dataset 1',
      data: [...Array(200)].map(() => ~~(1 + Math.random() * 100)),
      backgroundColor: '#454547',
      barThickness: 8,
      barPercentage: 0.5,
      borderWidth: {
        top: 2,
        right: 0,
        bottom: 0,
        left: 0,
      },
      borderColor: ['white'],
    },
  ],
};
</code>```

and my main function is as follow:

```<code>export default function FooterCpu() {
  return (
    <div className='max-h-[160px] '>
      <Bar className='myChart' options={options} data={data} />
    </div>
  );
}
</code>```

the result is as follow:
bar chart with overlapping

anyone knows how can i prevent overlapping and instead of that make it horizontally scrollble?
thanx in advance

Body:
I am trying to draw a bar chart using react-chartjs-2, i am using typescript
because i have a big amount of data, there is overlapping in the chart, i want to prevent overlapping, instead of that, i want horizontal scrolling

my config is as follow:

// options
export const options = {
  responsive: true,
  maintainAspectRatio: false,
  plugins: {
    legend: {
      display: false,
    },
  },
  scales: {
    x: {
      beginAtZero: 0,
      labelAutoFit: false,
      grid: {
        offset: false,
      },
    },
  },
};

// labels
const labels = [...new Array(200)].map((_, i) => i * 3);

// data
export const data = {
  labels,
  datasets: [
    {
      label: 'Dataset 1',
      data: [...Array(200)].map(() => ~~(1 + Math.random() * 100)),
      backgroundColor: '#454547',
      barThickness: 8,
      barPercentage: 0.5,
      borderWidth: {
        top: 2,
        right: 0,
        bottom: 0,
        left: 0,
      },
      borderColor: ['white'],
    },
  ],
};

and my main function is as follow:

export default function FooterCpu() {
  return (

      <Bar className='myChart' options={options} data={data} />

  );
}

the result is as follow:
bar chart with overlapping

anyone knows how can i prevent overlapping and instead of that make it horizontally scrollble?
thanx in advance


问:
Build method not executed after StreamBuilder has called the widget
I'm doing a registration page via Firebase, which redirects the user to a new page (called CompleteProfile) after the user has verified his email.

My main.dart has:

```<code>StreamBuilder(
          stream: Auth().authStateChanges,
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              return const VerifyEmailPage();
            } else {
              return const AuthPage();
            }
          },
        )
</code>```

As the user is not logged in, he arrives on the the AuthPage() where he has to register him. By pressing a button to finish the registration he's now logged in, so VerifyEmailPage() is called.

VerifyEmailPage.dart:

```<code>class VerifyEmailPage extends StatefulWidget {
  const VerifyEmailPage({super.key});

  @override
  State<VerifyEmailPage> createState() => _VerifyEmailPageState();
}

class _VerifyEmailPageState extends State<VerifyEmailPage> {
  bool isEmailVerified = false;
  bool canResendEmail = false;
  Timer? timer;

  @override
  void initState() {
    super.initState();
    isEmailVerified = FirebaseAuth.instance.currentUser!.emailVerified;

    if (!isEmailVerified) {
      sendVerificationEmail();
      timer = Timer.periodic(
          const Duration(seconds: 3), (_) => checkEmailVerified());
    }
  }

  Future sendVerificationEmail() async {
    try {
      final user = FirebaseAuth.instance.currentUser!;
      await user.sendEmailVerification();
      setState(() => canResendEmail = false);
      await Future.delayed(const Duration(seconds: 5));
      setState(() => canResendEmail = true);
    } catch (e) {
      debugPrint(e.toString());
    }
  }

  Future checkEmailVerified() async {
    await FirebaseAuth.instance.currentUser!.reload();
    setState(() {
      isEmailVerified = FirebaseAuth.instance.currentUser!.emailVerified;
    });
    if (isEmailVerified) timer?.cancel();
  }

  @override
  void dispose() {
    timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) => isEmailVerified
      ? const CompleteProfile()
      : Scaffold(body: /* ... */);
}
</code>```

I know that initState() is executed, but the build method never. So I'm still seeing the AuthPage() with the initState of VerifyEmailPage() running.

Body:
I'm doing a registration page via Firebase, which redirects the user to a new page (called CompleteProfile) after the user has verified his email.

My main.dart has:

StreamBuilder(
          stream: Auth().authStateChanges,
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              return const VerifyEmailPage();
            } else {
              return const AuthPage();
            }
          },
        )

As the user is not logged in, he arrives on the the AuthPage() where he has to register him. By pressing a button to finish the registration he's now logged in, so VerifyEmailPage() is called.

VerifyEmailPage.dart:

class VerifyEmailPage extends StatefulWidget {
  const VerifyEmailPage({super.key});

  @override
  State<VerifyEmailPage> createState() => _VerifyEmailPageState();
}

class _VerifyEmailPageState extends State<VerifyEmailPage> {
  bool isEmailVerified = false;
  bool canResendEmail = false;
  Timer? timer;

  @override
  void initState() {
    super.initState();
    isEmailVerified = FirebaseAuth.instance.currentUser!.emailVerified;

    if (!isEmailVerified) {
      sendVerificationEmail();
      timer = Timer.periodic(
          const Duration(seconds: 3), (_) => checkEmailVerified());
    }
  }

  Future sendVerificationEmail() async {
    try {
      final user = FirebaseAuth.instance.currentUser!;
      await user.sendEmailVerification();
      setState(() => canResendEmail = false);
      await Future.delayed(const Duration(seconds: 5));
      setState(() => canResendEmail = true);
    } catch (e) {
      debugPrint(e.toString());
    }
  }

  Future checkEmailVerified() async {
    await FirebaseAuth.instance.currentUser!.reload();
    setState(() {
      isEmailVerified = FirebaseAuth.instance.currentUser!.emailVerified;
    });
    if (isEmailVerified) timer?.cancel();
  }

  @override
  void dispose() {
    timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) => isEmailVerified
      ? const CompleteProfile()
      : Scaffold(body: /* ... */);
}

I know that initState() is executed, but the build method never. So I'm still seeing the AuthPage() with the initState of VerifyEmailPage() running.


问:
APN notification is not working but responce from api is success
I am implemented APN (apple push notification) it is getting success. I am getting result

Blockquote
[1] => Pushok\Response Object
(
[apnsId:Pushok\Response:private] => XXXXXXXXXXXXXXXXXXXXX
[deviceToken:Pushok\Response:private] => XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
[statusCode:Pushok\Response:private] => 200
[errorReason:Pushok\Response:private] =>
[error410Timestamp:Pushok\Response:private] =>
)

but in the app, I am not able to receive any notifications in the app. The app is built in expo react native. I am using an expo-notification package and using the getDevicePushTokenAsync() function.


问:
How can I verify my google play console account as a developer from Australia
When creating a google play console account it requires verification, the issue is when I attempt to verify myself it requests a U.S. based address.

There doesn't seem to be anyway to signup with a Australian address that I can find, I assume there's a way that I just can't find as I'm more than sure not every Google play developer is U.S. based.


问:
Socket and EC2 TimeoutError: [Errno 60] Operation timed out
I am trying to connect a socket from client to EC2 socket server on ubuntu, I want each message being sent from the client to the server to be printed in the server.

Locally, it works fine.

I can send multiple messages or even flood the server and I’ll be able to see each message in logs and get feedback.

The unwanted behavior starts to occur when I host the server in EC2.

For the first four messages, the feedback I am looking for is shown at server. But, after the fourth one, it starts to break.

In the client side, the error it raises, is the following:

```<code>   in recvMessage
          serverMessage = clientSocket.recv(1024).decode("utf-8")
                    ^^^^^^^^^^^^^^^^^^^^^^^
        TimeoutError: [Errno 60] Operation timed out
</code>```

I’m using Flask server only in the client side as a trigger to this action, by sending a post request with Postman.

Furthermore, I found that if I initiate a new socket connection (New client instance) I can keep sending and receiving feedback, as long as it is less then 4 messages.

```<code>     Console in client:
     localhost - - [DATE] "GET /print?msg=Hello HTTP/1.1" 200 -
     localhost - - [DATE] "GET /print?msg=Hello HTTP/1.1" 200 -
     localhost - - [DATE] "GET /print?msg=Hello HTTP/1.1" 200 -
     localhost - - [DATE] "GET /print?msg=Hello HTTP/1.1" 200 -
     localhost - - [DATE] "GET /print?msg=Hello HTTP/1.1" 200 -
     localhost - - [DATE] "GET /print?msg=Hello HTTP/1.1" 200 -
</code>```

Console in EC2 server:

```     MY.IP.FROM.CLIENT says: Hello
     MY.IP.FROM.CLIENT says: Hello
     MY.IP.FROM.CLIENT says: Hello
     MY.IP.FROM.CLIENT says: Hello`
```

(I Expect to get 6)

Github link for the code I'm using (2 Files - Client.py and Server.py)

Because I thought it has something to do with the buffer, I tried changing the values of
clientSocket.recv(1024).decode("utf-8") from 1024 to some random numbers, but didn't manage to make it work. While it works locally I find it harder to try think of other things to try.

Body:
I am trying to connect a socket from client to EC2 socket server on ubuntu, I want each message being sent from the client to the server to be printed in the server.

Locally, it works fine.

I can send multiple messages or even flood the server and I’ll be able to see each message in logs and get feedback.

The unwanted behavior starts to occur when I host the server in EC2.

For the first four messages, the feedback I am looking for is shown at server. But, after the fourth one, it starts to break.

In the client side, the error it raises, is the following:

   in recvMessage
          serverMessage = clientSocket.recv(1024).decode("utf-8")
                    ^^^^^^^^^^^^^^^^^^^^^^^
        TimeoutError: [Errno 60] Operation timed out

I’m using Flask server only in the client side as a trigger to this action, by sending a post request with Postman.

Furthermore, I found that if I initiate a new socket connection (New client instance) I can keep sending and receiving feedback, as long as it is less then 4 messages.

     Console in client:
     localhost - - [DATE] "GET /print?msg=Hello HTTP/1.1" 200 -
     localhost - - [DATE] "GET /print?msg=Hello HTTP/1.1" 200 -
     localhost - - [DATE] "GET /print?msg=Hello HTTP/1.1" 200 -
     localhost - - [DATE] "GET /print?msg=Hello HTTP/1.1" 200 -
     localhost - - [DATE] "GET /print?msg=Hello HTTP/1.1" 200 -
     localhost - - [DATE] "GET /print?msg=Hello HTTP/1.1" 200 -

Console in EC2 server:

     MY.IP.FROM.CLIENT says: Hello
     MY.IP.FROM.CLIENT says: Hello
     MY.IP.FROM.CLIENT says: Hello
     MY.IP.FROM.CLIENT says: Hello`

(I Expect to get 6)

Github link for the code I'm using (2 Files - Client.py and Server.py)

Because I thought it has something to do with the buffer, I tried changing the values of
clientSocket.recv(1024).decode("utf-8") from 1024 to some random numbers, but didn't manage to make it work. While it works locally I find it harder to try think of other things to try.


问:
Receive object reference error when iterate the xdocument to retrieve xml element value
```<code>Dim lstrReadXml As String = String.Empty
mobjComFun.ReadTextFile(System.Windows.Forms.Application.StartupPath & "\GoFirstBookingXML\GetBookRes.xml", lstrReadXml)
Dim lobjXdoc As XDocument = XDocument.Parse(lstrReadXml)
Dim lobjNs As New XmlNamespaceManager(lobjXdoc.CreateReader.NameTable)
lobjNs.AddNamespace("s", "http://schemas.xmlsoap.org/soap/envelope/")
lobjNs.AddNamespace("sc", "http://schemas.navitaire.com/WebServices/ServiceContracts/BookingService")
lobjNs.AddNamespace("dc", "http://schemas.navitaire.com/WebServices/DataContracts/Booking")
lobjNs.AddNamespace("a", "http://schemas.navitaire.com/WebServices/DataContracts/Common")

Dim lstrErrorMsg = String.Empty, lstrQueryStr As String = String.Empty
Dim lstrPaxNames As New StringBuilder
'Dim lstrFirstName As String = mobjComFun.GetElementValue(lobjXdoc, "/s:Envelope/s:Body/sc:GetBookingResponse/dc:Booking/dc:Passengers/dc:Passenger/dc:Names", lobjNs, lstrErrorMsg)
For Each lobXnode In lobjXdoc.XPathSelectElements("/s:Envelope/s:Body/sc:GetBookingResponse/dc:Booking/dc:Passengers/dc:Passenger", lobjNs)
    If Not lobXnode Is Nothing Then
        Dim lobjIEnum As IEnumerable(Of XElement) = From Nam In lobXnode.Elements(lobjNs. & "Names")
                                                    Select Nam

        Dim lstrLN As String = lobXnode.Document.Element("LastName").Value
        lstrPaxNames.Append(lobXnode.XPathSelectElement("/dc:Names", lobjNs).Value)
        lstrPaxNames.Append(lobXnode.XPathSelectElement("/dc:Names/dc:BookingName/dc:LastName", lobjNs).Value & "/")
        lstrPaxNames.Append(lobXnode.XPathSelectElement("/dc:Names/dc:BookingName/dc:FirstName", lobjNs).Value & " Y58TWL ")

    End If
Next
</code>```

When trying to foreach iterate the XDocument, I receive the object reference error when trying to get the element value inside the iteration.

Body:
Dim lstrReadXml As String = String.Empty
mobjComFun.ReadTextFile(System.Windows.Forms.Application.StartupPath & "\GoFirstBookingXML\GetBookRes.xml", lstrReadXml)
Dim lobjXdoc As XDocument = XDocument.Parse(lstrReadXml)
Dim lobjNs As New XmlNamespaceManager(lobjXdoc.CreateReader.NameTable)
lobjNs.AddNamespace("s", "http://schemas.xmlsoap.org/soap/envelope/")
lobjNs.AddNamespace("sc", "http://schemas.navitaire.com/WebServices/ServiceContracts/BookingService")
lobjNs.AddNamespace("dc", "http://schemas.navitaire.com/WebServices/DataContracts/Booking")
lobjNs.AddNamespace("a", "http://schemas.navitaire.com/WebServices/DataContracts/Common")

Dim lstrErrorMsg = String.Empty, lstrQueryStr As String = String.Empty
Dim lstrPaxNames As New StringBuilder
'Dim lstrFirstName As String = mobjComFun.GetElementValue(lobjXdoc, "/s:Envelope/s:Body/sc:GetBookingResponse/dc:Booking/dc:Passengers/dc:Passenger/dc:Names", lobjNs, lstrErrorMsg)
For Each lobXnode In lobjXdoc.XPathSelectElements("/s:Envelope/s:Body/sc:GetBookingResponse/dc:Booking/dc:Passengers/dc:Passenger", lobjNs)
    If Not lobXnode Is Nothing Then
        Dim lobjIEnum As IEnumerable(Of XElement) = From Nam In lobXnode.Elements(lobjNs. & "Names")
                                                    Select Nam

        Dim lstrLN As String = lobXnode.Document.Element("LastName").Value
        lstrPaxNames.Append(lobXnode.XPathSelectElement("/dc:Names", lobjNs).Value)
        lstrPaxNames.Append(lobXnode.XPathSelectElement("/dc:Names/dc:BookingName/dc:LastName", lobjNs).Value & "/")
        lstrPaxNames.Append(lobXnode.XPathSelectElement("/dc:Names/dc:BookingName/dc:FirstName", lobjNs).Value & " Y58TWL ")

    End If
Next

When trying to foreach iterate the XDocument, I receive the object reference error when trying to get the element value inside the iteration.


问:
Table validation to find wrong rowspan or column value
I have the below XML file in which

```<code><table-wrap id="tbl4" position="float">
            <label>Table E3</label>
            <caption>
                <p></p>
            </caption>
            <alternatives>
                <graphic xmlns:xlink="http://www.w3.org/1999/xlink"
                         xlink:href="EEMCS-01-2021-001110.tif"/>
                <table frame="hsides">
                    <colgroup>
                        <col align="left"/>
                        <col align="left"/>
                        <col align="left"/>
                        <col align="left"/>
                         <col align="left"/>
                         <col align="left"/>
                         <col align="left"/>
                    </colgroup>
                    <thead>
                        <tr>
                            <th rowspan="2" align="left">1</th>
                            <th colspan="5" align="center">2</th>
                            <th rowspan="2" align="center">3</th>
                        </tr>
                        <tr>
                            <th align="center">4</th>
                            <th align="center">5</th>
                            <th align="center">6</th>
                            <th align="center">7</th>
                            <th align="center">8</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>9</td>
                            <td rowspan="2">10</td>
                            <td>11</td>
                            <td>12</td>
                            <td>13</td>
                            <td>14</td>
                            <td rowspan="2">15</td>
                        </tr>
                        <tr>
                            <td>16</td>
                            <td>17</td>
                            <td>18</td>
                            <td>19</td>
                            <td>20</td>
                        </tr>
                        <tr>
                            <td>21</td>
                            <td colspan="2">22</td>
                            <td rowspan="2">23</td>
                            <td colspan="2">24</td>
                            <td>25</td>
                        </tr>
                        <tr>
                            <td>26</td>
                            <td>27</td>
                            <td>28</td>
                            <td>29</td>
                            <td>30</td>
                            <td>31</td>
                        </tr>
                        <tr>
                            <td rowspan="2">32</td>
                            <td colspan="2">33</td>
                            <td>34</td>
                            <td colspan="2">35</td>
                            <td rowspan="3">36</td>
                        </tr>
                        <tr>
                            <td>37</td>
                            <td>38</td>
                            <td>39</td>
                            <td>40</td>
                            <td>41</td>
                        </tr>
                    </tbody>
                </table>
            </alternatives>
        </table-wrap>

</code>```

I want to validate the wrong rowspan or colspan count mentioned in the XML file. Here example, " 36 	" has rowspan="3" before the last row which is wrong. Therefore, an additional row should be generated in the final XML output. However, the output of the table was created in box format not differed now when the rowspan was mentioned wrongly.

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" version="2.0" exclude-result-prefixes="xs">

    <xsl:output indent="yes" omit-xml-declaration="yes" />

    <xsl:variable name="table_with_no_rowspans">
        <xsl:apply-templates mode="rowspan"/>
    </xsl:variable>

    <xsl:template match="/">
        <xsl:apply-templates select="$table_with_no_rowspans/*" mode="final" />
    </xsl:template>

    <xsl:template match="@*|*" mode="#all">
        <xsl:copy>
            <xsl:apply-templates select="@*|*" mode="#current" />
        </xsl:copy>
    </xsl:template>

    <!-- make sure it works for both table/tr and table/tbody/tr and table/thead/tr -->
    <xsl:template match="table/tbody | table[not(tbody | thead)] | table/thead" mode="rowspan">
        <xsl:copy>
            <xsl:copy-of select="tr[1]" />
            <xsl:apply-templates select="tr[2]" mode="rowspan">
                <xsl:with-param name="previousRow" select="tr[1]" />
            </xsl:apply-templates>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="tr" mode="rowspan">
        <xsl:param name="previousRow" as="element()" />

        <xsl:variable name="currentRow" select="." />

        <xsl:variable name="normalizedTDs">
            <xsl:for-each select="$previousRow/*">
                <xsl:choose>
                    <xsl:when test="@rowspan > 1">
                        <xsl:copy>
                            <xsl:attribute name="rowspan">
                                <xsl:value-of select="@rowspan - 1" />
                            </xsl:attribute><!--
                            <xsl:copy-of select="@*[not(name() = 'rowspan')]" />
                            <xsl:copy-of select="node()" />
                        --></xsl:copy>
                    </xsl:when>
                    <xsl:otherwise>
                        <xsl:copy-of select="$currentRow/*[1 + count(current()/preceding-sibling::*[not(@rowspan) or (@rowspan = 1)])]" />
                    </xsl:otherwise>
                </xsl:choose>
            </xsl:for-each>
        </xsl:variable>

        <xsl:variable name="newRow" as="element(tr)">
            <xsl:copy>
                <xsl:copy-of select="$currentRow/@*" />
                <xsl:copy-of select="$normalizedTDs" />
            </xsl:copy>
        </xsl:variable>

        <xsl:copy-of select="$newRow" />

        <xsl:apply-templates select="following-sibling::tr[1]" mode="rowspan">
            <xsl:with-param name="previousRow" select="$newRow" />
        </xsl:apply-templates>
    </xsl:template>

    <xsl:template match="td | th" mode="final">
        <xsl:choose>
            <xsl:when test="@rowspan">
                <xsl:copy>
                    <xsl:copy-of select="@* except @rowspan" />
                    <xsl:copy-of select="node()" />
                </xsl:copy>
            </xsl:when>
            <xsl:otherwise>
                <xsl:copy-of select="." />
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>

</xsl:stylesheet>
</code>```

I have used the above code but it producing table in box format and some of the values are missing in output due to wrong rowspan. Please suggest me the correct approach.

Now I get the XML output as below:

```<code><table-wrap id="tbl4" position="float">
   <label/>
   <caption>
      <p/>
   </caption>
   <alternatives>
      <graphic xmlns:xlink="http://www.w3.org/1999/xlink"
               xlink:href="EEMCS-01-2021-001110.tif"/>
      <table frame="hsides">
         <colgroup>
            <col align="left"/>
            <col align="left"/>
            <col align="left"/>
            <col align="left"/>
            <col align="left"/>
            <col align="left"/>
            <col align="left"/>
         </colgroup>
         <thead>
            <tr>
               <th align="left">1</th>
               <th colspan="5" align="center">2</th>
               <th align="center">3</th>
            </tr>
            <tr>
               <th/>
               <th align="center">4</th>
               <th/>
            </tr>
         </thead>
         <tbody>
            <tr>
               <td>9</td>
               <td>10</td>
               <td>11</td>
               <td>12</td>
               <td>13</td>
               <td>14</td>
               <td>15</td>
            </tr>
            <tr>
               <td>16</td>
               <td/>
               <td>17</td>
               <td>18</td>
               <td>19</td>
               <td>20</td>
               <td/>
            </tr>
            <tr>
               <td>21</td>
               <td colspan="2">22</td>
               <td>23</td>
               <td colspan="2">24</td>
               <td>25</td>
            </tr>
            <tr>
               <td>26</td>
               <td>27</td>
               <td/>
               <td>28</td>
               <td>29</td>
            </tr>
            <tr>
               <td>32</td>
               <td colspan="2">33</td>
               <td>34</td>
               <td colspan="2">35</td>
               <td>36</td>
            </tr>
            <tr>
               <td/>
               <td>37</td>
               <td>38</td>
               <td>39</td>
               <td/>
            </tr>
         </tbody>
      </table>
   </alternatives>
</table-wrap>

</code>```

In the last row "
", entries "40	41	" are missing due wrong usage of rowspan value in " 36 	". Similarly in "
" entries "6	 7	 8	 are missing in "
" entries 30	 31	 are missing.

Expected XML output:

```<code><table-wrap id="tbl4" position="float">
   <label/>
   <caption>
      <p/>
   </caption>
   <alternatives>
      <graphic xmlns:xlink="http://www.w3.org/1999/xlink"
               xlink:href="EEMCS-01-2021-001110.tif"/>
      <table frame="hsides">
         <colgroup>
            <col align="left"/>
            <col align="left"/>
            <col align="left"/>
            <col align="left"/>
            <col align="left"/>
            <col align="left"/>
            <col align="left"/>
         </colgroup>
         <thead>
            <tr>
               <th align="left">1</th>
               <th colspan="5" align="center">2</th>
               <th align="center">3</th>
            </tr>
            <tr>
               <th/>
               <th align="center">4</th>
               <th align="center">5</th>
               <th align="center">6</th>
               <th align="center">7</th>
               <th align="center">8</th>
               <th/>
            </tr>
         </thead>
         <tbody>
            <tr>
               <td>9</td>
               <td>10</td>
               <td>11</td>
               <td>12</td>
               <td>13</td>
               <td>14</td>
               <td>15</td>
            </tr>
            <tr>
               <td>16</td>
               <td/>
               <td>17</td>
               <td>18</td>
               <td>19</td>
               <td>20</td>
               <td/>
            </tr>
            <tr>
               <td>21</td>
               <td colspan="2">22</td>
               <td>23</td>
               <td colspan="2">24</td>
               <td>25</td>
            </tr>
            <tr>
               <td>26</td>
               <td>27</td>
               <td/>
               <td>28</td>
               <td>29</td>
               <td>30</td>
               <td>31</td>
            </tr>
            <tr>
               <td>32</td>
               <td colspan="2">33</td>
               <td>34</td>
               <td colspan="2">35</td>
               <td>36</td>
            </tr>
            <tr>
               <td/>
               <td>37</td>
               <td>38</td>
               <td>39</td>
               <td/>
               <td>40</td>
               <td>41</td>
            </tr>
            <tr>
               <td/>
            </tr>
         </tbody>
      </table>
   </alternatives>
</table-wrap>

</code>```

I know the above expected is not a proper table but based on input  the wrong table should be generated to validate further.

Body:
I have the below XML file in which

            Table E3

            <alternatives>
                <graphic xmlns:xlink="http://www.w3.org/1999/xlink"
                         xlink:href="EEMCS-01-2021-001110.tif"/>

                    <colgroup>
                        <col align="left"/>
                        <col align="left"/>
                        <col align="left"/>
                        <col align="left"/>
                         <col align="left"/>
                         <col align="left"/>
                         <col align="left"/>
                    </colgroup>

                            1
                            2
                            3

                            4
                            5
                            6
                            7
                            8

                            9
                            10
                            11
                            12
                            13
                            14
                            15

                            16
                            17
                            18
                            19
                            20

                            21
                            22
                            23
                            24
                            25

                            26
                            27
                            28
                            29
                            30
                            31

                            32
                            33
                            34
                            35
                            36

                            37
                            38
                            39
                            40
                            41

            </alternatives>

I want to validate the wrong rowspan or colspan count mentioned in the XML file. Here example, " 36 	" has rowspan="3" before the last row which is wrong. Therefore, an additional row should be generated in the final XML output. However, the output of the table was created in box format not differed now when the rowspan was mentioned wrongly.

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" version="2.0" exclude-result-prefixes="xs">

    <xsl:output indent="yes" omit-xml-declaration="yes" />

    <xsl:variable name="table_with_no_rowspans">
        <xsl:apply-templates mode="rowspan"/>
    </xsl:variable>

    <xsl:template match="/">
        <xsl:apply-templates select="$table_with_no_rowspans/*" mode="final" />
    </xsl:template>

    <xsl:template match="@*|*" mode="#all">
        <xsl:copy>
            <xsl:apply-templates select="@*|*" mode="#current" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="table/tbody | table[not(tbody | thead)] | table/thead" mode="rowspan">
        <xsl:copy>
            <xsl:copy-of select="tr[1]" />
            <xsl:apply-templates select="tr[2]" mode="rowspan">
                <xsl:with-param name="previousRow" select="tr[1]" />
            </xsl:apply-templates>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="tr" mode="rowspan">
        <xsl:param name="previousRow" as="element()" />

        <xsl:variable name="currentRow" select="." />

        <xsl:variable name="normalizedTDs">
            <xsl:for-each select="$previousRow/*">
                <xsl:choose>
                    <xsl:when test="@rowspan > 1">
                        <xsl:copy>
                            <xsl:attribute name="rowspan">
                                <xsl:value-of select="@rowspan - 1" />
                            </xsl:attribute></xsl:copy>
                    </xsl:when>
                    <xsl:otherwise>
                        <xsl:copy-of select="$currentRow/*[1 + count(current()/preceding-sibling::*[not(@rowspan) or (@rowspan = 1)])]" />
                    </xsl:otherwise>
                </xsl:choose>
            </xsl:for-each>
        </xsl:variable>

        <xsl:variable name="newRow" as="element(tr)">
            <xsl:copy>
                <xsl:copy-of select="$currentRow/@*" />
                <xsl:copy-of select="$normalizedTDs" />
            </xsl:copy>
        </xsl:variable>

        <xsl:copy-of select="$newRow" />

        <xsl:apply-templates select="following-sibling::tr[1]" mode="rowspan">
            <xsl:with-param name="previousRow" select="$newRow" />
        </xsl:apply-templates>
    </xsl:template>

    <xsl:template match="td | th" mode="final">
        <xsl:choose>
            <xsl:when test="@rowspan">
                <xsl:copy>
                    <xsl:copy-of select="@* except @rowspan" />
                    <xsl:copy-of select="node()" />
                </xsl:copy>
            </xsl:when>
            <xsl:otherwise>
                <xsl:copy-of select="." />
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>

</xsl:stylesheet>

I have used the above code but it producing table in box format and some of the values are missing in output due to wrong rowspan. Please suggest me the correct approach.

Now I get the XML output as below:

   <alternatives>
      <graphic xmlns:xlink="http://www.w3.org/1999/xlink"
               xlink:href="EEMCS-01-2021-001110.tif"/>

         <colgroup>
            <col align="left"/>
            <col align="left"/>
            <col align="left"/>
            <col align="left"/>
            <col align="left"/>
            <col align="left"/>
            <col align="left"/>
         </colgroup>

               1
               2
               3

               4

               9
               10
               11
               12
               13
               14
               15

               16

               17
               18
               19
               20

               21
               22
               23
               24
               25

               26
               27

               28
               29

               32
               33
               34
               35
               36

               37
               38
               39

   </alternatives>

In the last row "
", entries "40	41	" are missing due wrong usage of rowspan value in " 36 	". Similarly in "
" entries "6	 7	 8	 are missing in "
" entries 30	 31	 are missing.

Expected XML output:

   <alternatives>
      <graphic xmlns:xlink="http://www.w3.org/1999/xlink"
               xlink:href="EEMCS-01-2021-001110.tif"/>

         <colgroup>
            <col align="left"/>
            <col align="left"/>
            <col align="left"/>
            <col align="left"/>
            <col align="left"/>
            <col align="left"/>
            <col align="left"/>
         </colgroup>

               1
               2
               3

               4
               5
               6
               7
               8

               9
               10
               11
               12
               13
               14
               15

               16

               17
               18
               19
               20

               21
               22
               23
               24
               25

               26
               27

               28
               29
               30
               31

               32
               33
               34
               35
               36

               37
               38
               39

               40
               41

   </alternatives>

I know the above expected is not a proper table but based on input  the wrong table should be generated to validate further.


问:
Not able to share my spreadsheet after making changes to an excel file with anyone?
I have Macbook M2 Air.

I have made changes to an excel file in my mac spreadsheet now I am sharing it to someone but change is not reflecting?

I saved my file and mailed as well as send that file through the document via whatsApp, but the file didn't get changes done by me.

I am trying it through my macbook.


问:
How to use GamilService with OIDC Authentication in a Blazor Webassembly .net6 client
I would like to use GmailService (Google.Apis.Gmail.v1) in my Blazor-Wasm app.
I have already implemented the OIDC-Authentication with

```<code>builder.Services.AddOidcAuthentication(options =>
{
    builder.Configuration.Bind("Google", options.ProviderOptions);
});
</code>```

and CascadingAuthenticationState and AuthorizeRouteView.
The authentication is successful, I will be requested to allow permissions to my gmail account.

now I want to create and use a GmailService insance in my razor page, but I cannot find an example, how do it.

can you please help me?

Body:
I would like to use GmailService (Google.Apis.Gmail.v1) in my Blazor-Wasm app.
I have already implemented the OIDC-Authentication with

builder.Services.AddOidcAuthentication(options =>
{
    builder.Configuration.Bind("Google", options.ProviderOptions);
});

and CascadingAuthenticationState and AuthorizeRouteView.
The authentication is successful, I will be requested to allow permissions to my gmail account.

now I want to create and use a GmailService insance in my razor page, but I cannot find an example, how do it.

can you please help me?


问:
How to find mean position of white pixels on video stream OpenCV
I've searched this question up and found multiple stack overflow posts about this but they weren't helpful. I've written code to find the white pixels in an image and then draw a circle around them, but the problem is there are multiple white pixels in an image so what happens is that the circle moves rapidly from one pixel to another because all the pixels are white. I want to find the average position of all the white pixels so that the circle stays consistent.

Here's my current code:

```<code>import cv2
import numpy as np

URL = "http://192.168.1.104:81/stream"

cap = cv2.VideoCapture(URL)

def mask():
    # for masking white
    sensitivity = 20
    lower_white = np.array([0, 0, 255 - sensitivity])
    upper_white = np.array([255, sensitivity, 255])
    mask = cv2.inRange(hsv, lower_white, upper_white)
    result = cv2.bitwise_and(frame, frame, mask=mask)
    return result

def coord_of_white():
    Y, X = np.where(np.all(frame == [255, 255, 255], axis=2))
    zipped = np.column_stack((X, Y))
    for points in zipped:
        return cv2.circle(frame, points, 20, (0, 0, 255))  # displays circles at the coordinates of white pixels

while True:
    if cap.isOpened():
        ret, frame = cap.read()
        hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
        coord_of_white()
        cv2.imshow("ESP32 CAM", cv2.flip(frame, 0))
        cv2.imshow("ESP32 CAM MASK", cv2.flip(mask(), 0))
        if cv2.waitKey(1) == ord("q"):
            break

cv2.destroyAllWindows()
cap.release()
</code>```

Body:
I've searched this question up and found multiple stack overflow posts about this but they weren't helpful. I've written code to find the white pixels in an image and then draw a circle around them, but the problem is there are multiple white pixels in an image so what happens is that the circle moves rapidly from one pixel to another because all the pixels are white. I want to find the average position of all the white pixels so that the circle stays consistent.

Here's my current code:

import cv2
import numpy as np

URL = "http://192.168.1.104:81/stream"

cap = cv2.VideoCapture(URL)

def mask():
    # for masking white
    sensitivity = 20
    lower_white = np.array([0, 0, 255 - sensitivity])
    upper_white = np.array([255, sensitivity, 255])
    mask = cv2.inRange(hsv, lower_white, upper_white)
    result = cv2.bitwise_and(frame, frame, mask=mask)
    return result

def coord_of_white():
    Y, X = np.where(np.all(frame == [255, 255, 255], axis=2))
    zipped = np.column_stack((X, Y))
    for points in zipped:
        return cv2.circle(frame, points, 20, (0, 0, 255))  # displays circles at the coordinates of white pixels

while True:
    if cap.isOpened():
        ret, frame = cap.read()
        hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
        coord_of_white()
        cv2.imshow("ESP32 CAM", cv2.flip(frame, 0))
        cv2.imshow("ESP32 CAM MASK", cv2.flip(mask(), 0))
        if cv2.waitKey(1) == ord("q"):
            break

cv2.destroyAllWindows()
cap.release()


问:
Dirichlet Process manually
I am implementing the Dirichlet Mixture Model using the EM algorithm in R, but am experiencing issues with the results. I generated two binomial distributions with fractions of (70%, 30%) and means of (0.05, 0.18), and trimmed 5% of the data set near 0. However, I am using a Beta distribution for clustering instead of a binomial distribution. Additionally, I am updating the mean and variance of the distributions rather than the alpha and beta parameters in order to impose constraints on the variance of each distribution.

I expected to obtain results similar to the ground truth settings, but instead I am getting pi values of (1, 0) and means of (0.09, 0.21). I am not sure if there are errors in my EM algorithm implementation or issues with parameter initialization.

I am including my R code for the data generation and DMM below. I would appreciate any help in identifying the cause of the problem and suggestions for how to resolve it.

```<code>library(dplyr)
library(data.table)
library(tidyverse)
set.seed(42)

#read count
cover <- 100

#Ground Truth Setting
subclone_f <- c(0.7, 0.3) # Ground Truth Setting - proportion
subclone_vaf <- c(0.05, 0.18) # Ground Truth Setting - mean

n_muts <- 45000
n_clone <-length(subclone_f)

#generating the virtual mutation notation: subclonal if 2, clonal if 1
mut_type <- sample.int(2, n_muts, prob = subclone_f, replace = TRUE)
mut_type

#generating negative binomial distribution(read count) for the given coverage
mut_reads <- rbinom(n_muts, cover, prob = subclone_vaf[mut_type]) %>% data.frame()
mut_reads

vaf <- (mut_reads/cover) %>% data.frame()

# Truncate the low count reads
n <- 0.95 * nrow(vaf) # cut-off setting
vaf_trim <- sapply(vaf, function(x) sort(x, decreasing = TRUE)[1:n])
colnames(vaf_trim) <- c("vaf")
hist(vaf_trim, breaks=seq(0,0.75,by=0.0001))

# Mixture Model
# Parameter Initialization (for 2 subclonality)
pi <- c(0.5, 0.5) # Mixture proportion weight: sums up to 1
alpha <- c(2,3)
beta <- c(20,5)
Mu[1] <- alpha[1] / (alpha[1] + beta[1])
Mu[2] <- alpha[2] / (alpha[2] + beta[2])
var[1] <- alpha[1]*beta[1] / ((alpha[1] + beta[1])^2 * (alpha[1] + beta[1] +1))
var[2] <- alpha[2]*beta[2] / ((alpha[2] + beta[2])^2 * (alpha[2] + beta[2] +1))
tau <-c(0.05, 0.05)

loglike[1] <- 0.5
loglike[2] <- 0.5

k <- 2

Nu <-  1/ (alpha + beta + 1)  # control the variance: same across the distributions> Originally wanted to implement the same Nu for 2 distributions but I don't know how to do that.
n_cluster <- nrow(data.frame(pi))

logdbeta <- function(x, alpha, beta) {
  sum(sapply(x, function(x) {dbeta(x, alpha, beta, log = TRUE)}))
}

estBetaParams <- function(mu, var) {
  alpha <- ((1 - mu) / var - (1 / mu)) * mu ^ 2
  beta <- alpha * (1 / mu - 1)
  return(params = list(alpha = alpha, beta = beta))
}

# Loop for the EM algorithm
while(abs(loglike[k]-loglike[k-1]) >= 0.00001) {
  # E step
  total <- (pi[1]*dbeta(vaf_trim, alpha[1], beta[1])) +  (pi[2]*dbeta(vaf_trim, alpha[2], beta[2]))
  tau1 <- pi[1]*(dbeta(vaf_trim, alpha[1], beta[1]))/ total
  tau2 <- pi[2]*(dbeta(vaf_trim, alpha[2], beta[2]))/ total

  # M step
  pi[1] <- sum(tau1)/length(vaf_trim) # Update Pi(weight)
  pi[2] <- sum(tau2)/length(vaf_trim)

  Mu[1] <- sum(tau1*vaf_trim)/sum(tau1) # Update Mu
  Mu[2] <- sum(tau2*vaf_trim)/sum(tau2)

  #Nu <-  alpha + beta
  Nu <- 1/ (alpha + beta + 1)
  # Our main aim was to share the same coefficient for all dist

  var[1] <- Mu[1] * (1-Mu[1]) * Nu[1] # Update Variance
  var[2] <- Mu[2] * (1-Mu[2]) * Nu[2]

  #Update in terms of alpha and beta
  estBetaParams(Mu[1], var[1])
  estBetaParams(Mu[2], var[2])

  # Maximize the loglikelihood
  loglike[k+1]<-sum(tau1*(log(pi[1])+logdbeta(vaf_trim,Mu[1],var[1])))+sum(tau2*(log(pi[2])+logdbeta(vaf_trim,Mu[2],var[2])))
  k<-k+1
}

# Print estimates
EM <- data.table(param = c("pi", "Mean"), pi = pi, Mean = Mu)
knitr::kable(EM)
</code>```

Title: Dirichlet Process manually

Body:
I am implementing the Dirichlet Mixture Model using the EM algorithm in R, but am experiencing issues with the results. I generated two binomial distributions with fractions of (70%, 30%) and means of (0.05, 0.18), and trimmed 5% of the data set near 0. However, I am using a Beta distribution for clustering instead of a binomial distribution. Additionally, I am updating the mean and variance of the distributions rather than the alpha and beta parameters in order to impose constraints on the variance of each distribution.

I expected to obtain results similar to the ground truth settings, but instead I am getting pi values of (1, 0) and means of (0.09, 0.21). I am not sure if there are errors in my EM algorithm implementation or issues with parameter initialization.

I am including my R code for the data generation and DMM below. I would appreciate any help in identifying the cause of the problem and suggestions for how to resolve it.

library(dplyr)
library(data.table)
library(tidyverse)
set.seed(42)

#read count
cover <- 100

#Ground Truth Setting
subclone_f <- c(0.7, 0.3) # Ground Truth Setting - proportion
subclone_vaf <- c(0.05, 0.18) # Ground Truth Setting - mean

n_muts <- 45000
n_clone <-length(subclone_f)

#generating the virtual mutation notation: subclonal if 2, clonal if 1
mut_type <- sample.int(2, n_muts, prob = subclone_f, replace = TRUE)
mut_type

#generating negative binomial distribution(read count) for the given coverage
mut_reads <- rbinom(n_muts, cover, prob = subclone_vaf[mut_type]) %>% data.frame()
mut_reads

vaf <- (mut_reads/cover) %>% data.frame()

# Truncate the low count reads
n <- 0.95 * nrow(vaf) # cut-off setting
vaf_trim <- sapply(vaf, function(x) sort(x, decreasing = TRUE)[1:n])
colnames(vaf_trim) <- c("vaf")
hist(vaf_trim, breaks=seq(0,0.75,by=0.0001))

# Mixture Model
# Parameter Initialization (for 2 subclonality)
pi <- c(0.5, 0.5) # Mixture proportion weight: sums up to 1
alpha <- c(2,3)
beta <- c(20,5)
Mu[1] <- alpha[1] / (alpha[1] + beta[1])
Mu[2] <- alpha[2] / (alpha[2] + beta[2])
var[1] <- alpha[1]*beta[1] / ((alpha[1] + beta[1])^2 * (alpha[1] + beta[1] +1))
var[2] <- alpha[2]*beta[2] / ((alpha[2] + beta[2])^2 * (alpha[2] + beta[2] +1))
tau <-c(0.05, 0.05)

loglike[1] <- 0.5
loglike[2] <- 0.5

k <- 2

Nu <-  1/ (alpha + beta + 1)  # control the variance: same across the distributions> Originally wanted to implement the same Nu for 2 distributions but I don't know how to do that.
n_cluster <- nrow(data.frame(pi))

logdbeta <- function(x, alpha, beta) {
  sum(sapply(x, function(x) {dbeta(x, alpha, beta, log = TRUE)}))
}

estBetaParams <- function(mu, var) {
  alpha <- ((1 - mu) / var - (1 / mu)) * mu ^ 2
  beta <- alpha * (1 / mu - 1)
  return(params = list(alpha = alpha, beta = beta))
}

# Loop for the EM algorithm
while(abs(loglike[k]-loglike[k-1]) >= 0.00001) {
  # E step
  total <- (pi[1]*dbeta(vaf_trim, alpha[1], beta[1])) +  (pi[2]*dbeta(vaf_trim, alpha[2], beta[2]))
  tau1 <- pi[1]*(dbeta(vaf_trim, alpha[1], beta[1]))/ total
  tau2 <- pi[2]*(dbeta(vaf_trim, alpha[2], beta[2]))/ total

  # M step
  pi[1] <- sum(tau1)/length(vaf_trim) # Update Pi(weight)
  pi[2] <- sum(tau2)/length(vaf_trim)

  Mu[1] <- sum(tau1*vaf_trim)/sum(tau1) # Update Mu
  Mu[2] <- sum(tau2*vaf_trim)/sum(tau2)

  #Nu <-  alpha + beta
  Nu <- 1/ (alpha + beta + 1)
  # Our main aim was to share the same coefficient for all dist

  var[1] <- Mu[1] * (1-Mu[1]) * Nu[1] # Update Variance
  var[2] <- Mu[2] * (1-Mu[2]) * Nu[2]

  #Update in terms of alpha and beta
  estBetaParams(Mu[1], var[1])
  estBetaParams(Mu[2], var[2])

  # Maximize the loglikelihood
  loglike[k+1]<-sum(tau1*(log(pi[1])+logdbeta(vaf_trim,Mu[1],var[1])))+sum(tau2*(log(pi[2])+logdbeta(vaf_trim,Mu[2],var[2])))
  k<-k+1
}

# Print estimates
EM <- data.table(param = c("pi", "Mean"), pi = pi, Mean = Mu)
knitr::kable(EM)


问:
How to connect onClick events on website with MongoDB
I'm trying to design a Virtual Piano. All my sounds of individual keys are stored in MongoDB. How to play the particular key sound when the user clicks it??
I tried making all keys as buttons atop the piano image and assigning ids to each key. And then using get request, used findById() of mongoDB to find that key sound. But it doesnt seem to play.</p>


问:
IBM informix database is not online
I have cisco contact center express(UCCX) server that is leveraging IBM informix database. UCCX upgrade is failing and when we checked the logs i fund that the upgrade script is trying to access the database to upgrade it but it is offline:

```<code>2022-12-14 23:18:38,549 - uccxdb.install - INFO - UCCX DB is offline, waiting to go On-Line
</code>```

I then checked informix database logs and i saw that onmode utility failed to initialize the shared memory for INFORMIXSERVER instance:

```<code>2022-12-14 23:22:09 :INFO: -----> status()
2022-12-14 23:22:09 :INFO: Executing [onstat - | grep "On-Line" >/dev/null 2>&1]
2022-12-14 23:22:09 :INFO: Command:[onstat - | grep "On-Line" >/dev/null 2>&1] returnCode:[256]
2022-12-14 23:22:09 :INFO: UccxDB is not running
2022-12-14 23:22:09 :INFO: /opt/cisco/uccx/conf/UccxDB.pid deleted
2022-12-14 23:22:09 :INFO: <----- status()
2022-12-14 23:22:09 :INFO: Folder [/opt/cisco/uccx/conf] already exist
2022-12-14 23:22:09 :INFO: -----> cleanupSharedMemory()
2022-12-14 23:22:09 :INFO: Executing [onmode -yuck >> /var/log/active/uccx/log/out_UccxDB.log 2>&1]
shared memory not initialized for INFORMIXSERVER 'uccx01_uccx'
</code>```

anyone has suggestion about what should be done? appreciate any useful information or advice.

Title: IBM informix database is not online

Body:
I have cisco contact center express(UCCX) server that is leveraging IBM informix database. UCCX upgrade is failing and when we checked the logs i fund that the upgrade script is trying to access the database to upgrade it but it is offline:

2022-12-14 23:18:38,549 - uccxdb.install - INFO - UCCX DB is offline, waiting to go On-Line

I then checked informix database logs and i saw that onmode utility failed to initialize the shared memory for INFORMIXSERVER instance:

2022-12-14 23:22:09 :INFO: -----> status()
2022-12-14 23:22:09 :INFO: Executing [onstat - | grep "On-Line" >/dev/null 2>&1]
2022-12-14 23:22:09 :INFO: Command:[onstat - | grep "On-Line" >/dev/null 2>&1] returnCode:[256]
2022-12-14 23:22:09 :INFO: UccxDB is not running
2022-12-14 23:22:09 :INFO: /opt/cisco/uccx/conf/UccxDB.pid deleted
2022-12-14 23:22:09 :INFO: <----- status()
2022-12-14 23:22:09 :INFO: Folder [/opt/cisco/uccx/conf] already exist
2022-12-14 23:22:09 :INFO: -----> cleanupSharedMemory()
2022-12-14 23:22:09 :INFO: Executing [onmode -yuck >> /var/log/active/uccx/log/out_UccxDB.log 2>&1]
shared memory not initialized for INFORMIXSERVER 'uccx01_uccx'

anyone has suggestion about what should be done? appreciate any useful information or advice.


问:
How to update a value in an object stored in a Redis
Im very new to Redis but it seems like somthing my program need to work faster.

I have build my whole database with mongoose/mongodbAtlas.

But is there a way to update one item in the object I got from the database and  set in cache. I want to update a location in the setted redis key many times and only need to save the last updated location to the actual database.

So far I have some code to get 1 object from the database and store it in redis but I want to implement the updating part in this function as it is used for the PUT request to update a persons location every second

```<code>const updateLocation = async (req, res) => {
const { id} = req.params;

if (!redisClient.isOpen) {
    await redisClient.connect()
    console.log('connected')
}

const value = await redisClient.get(`person-${id}`)

if (value) {
    res.json(value)
    // Here I would like to update the documents location everytime
    //this endpoint is called from frontend
} else {
    const res = await Person.findById(id);

    await redisClient.set(`person-${id}`, res);
    console.log("from source data")
    res.status(200).json(res);

}

};
</code>```

Body:
Im very new to Redis but it seems like somthing my program need to work faster.

I have build my whole database with mongoose/mongodbAtlas.

But is there a way to update one item in the object I got from the database and  set in cache. I want to update a location in the setted redis key many times and only need to save the last updated location to the actual database.

So far I have some code to get 1 object from the database and store it in redis but I want to implement the updating part in this function as it is used for the PUT request to update a persons location every second

const updateLocation = async (req, res) => {
const { id} = req.params;

if (!redisClient.isOpen) {
    await redisClient.connect()
    console.log('connected')
}

const value = await redisClient.get(`person-${id}`)

if (value) {
    res.json(value)
    // Here I would like to update the documents location everytime
    //this endpoint is called from frontend
} else {
    const res = await Person.findById(id);

    await redisClient.set(`person-${id}`, res);
    console.log("from source data")
    res.status(200).json(res);

}

};


问:
Lua function constantly returning false out of SQL function
I have this code

```<code>function IsAuthorized(xPlayer, doorID, locked, usedLockpick)
    local jobName, grade = {}, {}
    jobName[1] = xPlayer.job.name
    grade[1] = xPlayer.job.grade
    if xPlayer.job2 then
        jobName[2] = xPlayer.job2.name
        grade[2] = xPlayer.job2.grade
    end
    local canOpen = false

    if doorID.lockpick and usedLockpick then
        count = xPlayer.getInventoryItem('lockpick').count
        if count and count >= 1 then canOpen = true end
    end

    if not canOpen and doorID.authorizedJobs then
        for job,rank in pairs(doorID.authorizedJobs) do
            if (job == jobName[1] and rank <= grade[1]) or (jobName[2] and job == jobName[2] and rank <= grade[2]) then
                canOpen = true
                if canOpen then break end
            end
        end
    end

    if not canOpen and doorID.items then
        local count
        for k,v in pairs(doorID.items) do
            count = xPlayer.getInventoryItem(v).count
            if count and count >= 1 then
                canOpen = true
                local consumables = { ['ticket']=1 }
                if locked and consumables[v] then
                    xPlayer.removeInventoryItem(v, 1)
                end
                break
            end
        end
        if not count or count < 1 then canOpen = false end
    end

    if not canOpen then
        local group = xPlayer.getGroup()
        if group == 'management' or group == 'owner' then
            print(group..' '..xPlayer.getName()..' was authorised to use a door')
            canOpen = true
        end
        if doorID.authorizedgang then
            print(xPlayer.identifier .. " | " .. doorID.authorizedgang)
            MySQL.Async.fetchSingle('SELECT * FROM users WHERE identifier = ? AND gang = ?', {xPlayer.identifier, doorID.authorizedgang}, function(foundplayer)
                if foundplayer then
                    print("found")
                    canOpen = true
                    print(canOpen)
                end
----------------------------canopen returns true until here
            end)
        end
    end

    print(canOpen)
    return canOpen
end

</code>```

Essentially what is does is return a true or false value based on the if statements. I did not write this script myself, I simply added on. The code that I added to this function is

```<code>if doorID.authorizedgang then
            print(xPlayer.identifier .. " | " .. doorID.authorizedgang)
            MySQL.Async.fetchSingle('SELECT * FROM users WHERE identifier = ? AND gang = ?', {xPlayer.identifier, doorID.authorizedgang}, function(foundplayer)
                if foundplayer then
                    print("found")
                    canOpen = true
                    print(canOpen)
                end
----------------------------canopen returns true until here
            end)
        end
</code>```

This code essentially makes a database call to check if it'll find a player with X identifier and Y gang, and this actually does work because it prints out "found" and canOpen returns true until the line that I marked, after this it returns false at the bottom of the function.

I've been trying other ways to get the data but ultimately I need the SQL DB call for this and im not sure why the variable isnt setting when in fact the database returns found. Any ideas what I could be doing wrong here?

Body:
I have this code

function IsAuthorized(xPlayer, doorID, locked, usedLockpick)
    local jobName, grade = {}, {}
    jobName[1] = xPlayer.job.name
    grade[1] = xPlayer.job.grade
    if xPlayer.job2 then
        jobName[2] = xPlayer.job2.name
        grade[2] = xPlayer.job2.grade
    end
    local canOpen = false

    if doorID.lockpick and usedLockpick then
        count = xPlayer.getInventoryItem('lockpick').count
        if count and count >= 1 then canOpen = true end
    end

    if not canOpen and doorID.authorizedJobs then
        for job,rank in pairs(doorID.authorizedJobs) do
            if (job == jobName[1] and rank <= grade[1]) or (jobName[2] and job == jobName[2] and rank <= grade[2]) then
                canOpen = true
                if canOpen then break end
            end
        end
    end

    if not canOpen and doorID.items then
        local count
        for k,v in pairs(doorID.items) do
            count = xPlayer.getInventoryItem(v).count
            if count and count >= 1 then
                canOpen = true
                local consumables = { ['ticket']=1 }
                if locked and consumables[v] then
                    xPlayer.removeInventoryItem(v, 1)
                end
                break
            end
        end
        if not count or count < 1 then canOpen = false end
    end

    if not canOpen then
        local group = xPlayer.getGroup()
        if group == 'management' or group == 'owner' then
            print(group..' '..xPlayer.getName()..' was authorised to use a door')
            canOpen = true
        end
        if doorID.authorizedgang then
            print(xPlayer.identifier .. " | " .. doorID.authorizedgang)
            MySQL.Async.fetchSingle('SELECT * FROM users WHERE identifier = ? AND gang = ?', {xPlayer.identifier, doorID.authorizedgang}, function(foundplayer)
                if foundplayer then
                    print("found")
                    canOpen = true
                    print(canOpen)
                end
----------------------------canopen returns true until here
            end)
        end
    end

    print(canOpen)
    return canOpen
end

Essentially what is does is return a true or false value based on the if statements. I did not write this script myself, I simply added on. The code that I added to this function is

if doorID.authorizedgang then
            print(xPlayer.identifier .. " | " .. doorID.authorizedgang)
            MySQL.Async.fetchSingle('SELECT * FROM users WHERE identifier = ? AND gang = ?', {xPlayer.identifier, doorID.authorizedgang}, function(foundplayer)
                if foundplayer then
                    print("found")
                    canOpen = true
                    print(canOpen)
                end
----------------------------canopen returns true until here
            end)
        end

This code essentially makes a database call to check if it'll find a player with X identifier and Y gang, and this actually does work because it prints out "found" and canOpen returns true until the line that I marked, after this it returns false at the bottom of the function.

I've been trying other ways to get the data but ultimately I need the SQL DB call for this and im not sure why the variable isnt setting when in fact the database returns found. Any ideas what I could be doing wrong here?


问:
Dynamic Mat-tab with Mat-table filter on nested object
I've a dynamic mat-tab that have a nested object on a mat-table within each tab. I want to implement a filter on each mat-table within the tab. How do I do that? The datasource for the mat-table is within the tab nested object.

Here is the HTML :

    <mat-card>
        <mat-card-header>
        <mat-card-title>Warehouse Inventory</mat-card-title>
        </mat-card-header>
        <mat-card-content>
        <mat-tab-group>
        <mat-tab *ngFor="let wh of whouses; let i = index" [label]="wh.description">

                <button class="float-right" mat-icon-button (click)="addInventory({loc_code: wh.loc_code, desc: wh.description})"><mat-icon>add</mat-icon></button><button class="float-right" mat-icon-button (click)="refreshData()"><mat-icon>refresh</mat-icon></button>

            <mat-form-field appearance="fill" class="input-filter">
                <mat-label>Filter</mat-label>
                <input matInput (keyup)="applyFilter($event)" placeholder="Ex. ium" #input>
            </mat-form-field>

                <ng-container matColumnDef="category">
                 Category
                 {{element.category}}
                </ng-container>

                <ng-container matColumnDef="loc_code">
                 WH Code
                 {{element.loc_code}}
                </ng-container>

                <ng-container matColumnDef="project_no">
                 Project No.
                 {{element.project_no}}
                </ng-container>

                <ng-container matColumnDef="item_code">
                 Item Code
                 {{element.item_code}}
                </ng-container>

                <ng-container matColumnDef="item">
                 Item
                 {{element.item}}
                </ng-container>

                <ng-container matColumnDef="qty">
                 Quantity
                 {{element.qty}}
                </ng-container>

        </mat-tab>
        </mat-tab-group>
        </mat-card-content>
    </mat-card>

```


问:
How to solve the error "could not install packages due to an OSError: [Errno 2] No such file or directory" after trying to install requirements.txt
After updating Python to the latest version, previous files were over-written and I was left with this error when trying to run:

```<code>pip install -r requirements.txt
</code>```

Error:

Processing /System/Volumes/Data/SWE/Apps/DT/BuildRoots/BuildRoot1/ActiveBuildRoot/Library/Caches/com.apple.xbs/Sources/python3/python3-124/altgraph-0.17.2-py2.py3-none-any.whl

ERROR: Could not install packages due to an OSError: [Errno 2] No such file or directory: '/System/Volumes/Data/SWE/Apps/DT/BuildRoots/BuildRoot1/ActiveBuildRoot/Library/Caches/com.apple.xbs/Sources/python3/python3-124/altgraph-0.17.2-py2.py3-none-any.whl'

How would one go about solving or understanding the approach to fixing this issue? I am not quite sure where to begin, so any help would be really appreciated.

I should be expecting the line to run without any errors and the web app should be able to run as well, but I encountered the previous error.

When I ran:

```<code>python manage.py runserver
</code>```

I encountered this error too:

ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?

The virtual environment is indeed active, my problem is trying to download all the requirements and encountering the aforementioned error.

Body:
After updating Python to the latest version, previous files were over-written and I was left with this error when trying to run:

pip install -r requirements.txt

Error:

Processing /System/Volumes/Data/SWE/Apps/DT/BuildRoots/BuildRoot1/ActiveBuildRoot/Library/Caches/com.apple.xbs/Sources/python3/python3-124/altgraph-0.17.2-py2.py3-none-any.whl

ERROR: Could not install packages due to an OSError: [Errno 2] No such file or directory: '/System/Volumes/Data/SWE/Apps/DT/BuildRoots/BuildRoot1/ActiveBuildRoot/Library/Caches/com.apple.xbs/Sources/python3/python3-124/altgraph-0.17.2-py2.py3-none-any.whl'

How would one go about solving or understanding the approach to fixing this issue? I am not quite sure where to begin, so any help would be really appreciated.

I should be expecting the line to run without any errors and the web app should be able to run as well, but I encountered the previous error.

When I ran:

python manage.py runserver

I encountered this error too:

ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?

The virtual environment is indeed active, my problem is trying to download all the requirements and encountering the aforementioned error.


问:
How to bind button with input field in ngFor loop?
I have a situation where I'll be adding count of items to generate a bill. For that I'll be looping the purchaseCount input field and the add button along with it based on the number of records. What I want is that the button in a row should be enabled only if the purchaseCount field for that row is filled.

My HTML code

`

```<code><table class="table table-hover" style="width: 100%;">
      <thead>
        <tr>
          <th>Item</th>
          <th>Stock available</th>
          <th>Price</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let item of inventoryList">

          <td>{{ item.item }}</td>
          <td> {{ item.count }}</td>
          <td> {{ item.sellingPrice }}</td>

          <td>
            <button type="button" class="btn btn-primary" style="margin:5px; width:100px" (click)="onAdd(item)">Add Item</button>
          <input  type="number" formControlName="purchaseCount" class="form-control" style="margin:5px; width:100px" placeholder="Count"></td>

        </tr>
      </tbody>
    </table>
</code>```

`

Here I want button to be enabled only if purchaseCount is filled in the below line.

I saw some scenarios where ngModel has been recommended but I don't think it can be implemented in my case.

Can someone suggest any possible way to do this

Sample UI Screenshot

Body:
I have a situation where I'll be adding count of items to generate a bill. For that I'll be looping the purchaseCount input field and the add button along with it based on the number of records. What I want is that the button in a row should be enabled only if the purchaseCount field for that row is filled.

My HTML code

`

          Item
          Stock available
          Price

          {{ item.item }}
           {{ item.count }}
           {{ item.sellingPrice }}

            <button type="button" class="btn btn-primary" style="margin:5px; width:100px" (click)="onAdd(item)">Add Item</button>
          <input  type="number" formControlName="purchaseCount" class="form-control" style="margin:5px; width:100px" placeholder="Count">

`

Here I want button to be enabled only if purchaseCount is filled in the below line.

I saw some scenarios where ngModel has been recommended but I don't think it can be implemented in my case.

Can someone suggest any possible way to do this

Sample UI Screenshot


问:
In TensorFlow 1 / Keras, how to see the value of a Tensor during training?
On my Keras model, I need to see the output of a hidden layer during training.

Here is what I have done:

```<code>net = Model(x, [y, hidden_layer])
</code>```

then, I constructed a custom callback

```<code>class CustomCallback(keras.callbacks.Callback):
    def on_batch_end(self):
        print(self.model.output[1])
</code>```

But, when I run the training with:

```<code>net.train_on_batch(train_data)
</code>```

I get:

ValueError: Error when checking model target: the list of Numpy arrays
that you are passing to your model is not the size the model expected.
Expected to see 2 array(s), but instead got the following list of 1
arrays:

Any idea ?

Thanks

Body:
On my Keras model, I need to see the output of a hidden layer during training.

Here is what I have done:

net = Model(x, [y, hidden_layer])

then, I constructed a custom callback

class CustomCallback(keras.callbacks.Callback):
    def on_batch_end(self):
        print(self.model.output[1])

But, when I run the training with:

net.train_on_batch(train_data)

I get:

ValueError: Error when checking model target: the list of Numpy arrays
that you are passing to your model is not the size the model expected.
Expected to see 2 array(s), but instead got the following list of 1
arrays:

Any idea ?

Thanks


问:
Declare a type from a JSON nested objects dynamically in TypeScript
I have a JSON file that looks like that:

```<code>{
  "key1": {
    "key1_1": "value1_1",
    "key1_2": "value1_2",
    ...
    "key1_n": "value1_n"
  },
  "key2": {
    "key2_1": "value2_1",
    "key2_2": "value2_2",
    ...
    "key2_m": "value2_m"
  },
  ...
  "keyx": {
    "keyx_1": "valuex_1",
    "keyx_2": "valuex_2",
    ...
    "keyx_y": "valuex_y",
  }
}
</code>```

I'm trying to declare a type for the nested objects of each keyx. I tried:

```<code>import data from './data.json';

type Data = typeof data;
type Key = keyof Data;
type Nested = Data[Key];
</code>```

The goal is to have a custom hook in React that get a key and returns the nested object of that key:

```<code>const d = useData('key1');
d.key1_1 // call it
</code>```

The json object can be dynamic but only in this structure, no more than one level of nesting.

How can I define this type properly so that I can call it as:

```<code>data.keyx.keyx_y
</code>```

Any ideas?

Body:
I have a JSON file that looks like that:

{
  "key1": {
    "key1_1": "value1_1",
    "key1_2": "value1_2",
    ...
    "key1_n": "value1_n"
  },
  "key2": {
    "key2_1": "value2_1",
    "key2_2": "value2_2",
    ...
    "key2_m": "value2_m"
  },
  ...
  "keyx": {
    "keyx_1": "valuex_1",
    "keyx_2": "valuex_2",
    ...
    "keyx_y": "valuex_y",
  }
}

I'm trying to declare a type for the nested objects of each keyx. I tried:

import data from './data.json';

type Data = typeof data;
type Key = keyof Data;
type Nested = Data[Key];

The goal is to have a custom hook in React that get a key and returns the nested object of that key:

const d = useData('key1');
d.key1_1 // call it

The json object can be dynamic but only in this structure, no more than one level of nesting.

How can I define this type properly so that I can call it as:

data.keyx.keyx_y

Any ideas?


问:
Python's binary representation of negative numbers
I have been trying to understand which representation is used by python for storing negative integers (1s complement, 2s complement or signed bit representation). For that, I tried out these functions

```<code>>>> bin(-10)
'-0b1010'
>>> bin(10)
'0b1010'
>>> format(10,'b')
'1010'
>>> format(-10,'b')
'-1010'
>>> format(-10,'16b')
'           -1010'
>>> format(-10,'32b')
'                           -1010'
>>> format(-10,'64b')
'                                                           -1010'
</code>```

However, -1010 is not any of the above 3 representations (how is it storing the - symbol ?). The representation here I am getting is just - in front of the standard binary representation of the positive counterpart. So, how can I know the actual representation?

Body:
I have been trying to understand which representation is used by python for storing negative integers (1s complement, 2s complement or signed bit representation). For that, I tried out these functions

>>> bin(-10)
'-0b1010'
>>> bin(10)
'0b1010'
>>> format(10,'b')
'1010'
>>> format(-10,'b')
'-1010'
>>> format(-10,'16b')
'           -1010'
>>> format(-10,'32b')
'                           -1010'
>>> format(-10,'64b')
'                                                           -1010'

However, -1010 is not any of the above 3 representations (how is it storing the - symbol ?). The representation here I am getting is just - in front of the standard binary representation of the positive counterpart. So, how can I know the actual representation?


问:
How to add full permission to network service through C#
I'm trying to give Network service full access to one folder that is already existing. Is it possible to get it done through code?</p>


问:
there are two input fields and each field is managed by separate states to strore values,with onsubmit how can i get all these input field values?
i am writing code for forget password in react

here the first input field which consists of Email and also there is a sendOtp button when i click on sendOtp the email which is entered it stores into a object separately

the second field which consist for otp when a user enters it also stores into a object separately

after these input fields there is a button i used onsubmit when i click on button the email and otp should be stored in array but it is not coming can any help please?????

```<code>import React, {useState} from "react";

const ForgotForm = () => {

    const [emai, setEmai] = useState({
    Email:""
  })

  const [otp, setOtp] = useState({
    Otp:""
  })
const handleChange =(e)=> {
  const {name, value} = e.target;
  setEmai({...emai, [name]: value})
}

const consoleEmail = (e) => {
  e.preventDefault();
  console.log(emai)
  setEmai({Email:""})
}

const handleOTP = (e) =>{
  const {name, value} = e.target;
  setOtp({...otp, [name]: value})
  console.log(otp)
}

const [forme,setForme] = useState({
  emai:"",
  otp:""
})

const handleData = (e) => {
  const {name, value} = e.target;
  setForme({...emai,...otp, [name]:value})
}

const handleSubmit = (e)=>{
  e.preventDefault()
  setForme({emai:"",otp:""})
  console.log(forme)
}
  return (
    <>
      <div className="forget-password">
        <h1>Forgot Password</h1>

        <div className="email-button">
          <input type="text" placeholder="Email" onChange={handleChange} name="Email" value={emai.Email}/>
          <button onClick={consoleEmail}>Send Otp</button>
        </div>
        <div className="otp-button">
          <input type="text" placeholder="Otp" onChange={handleOTP} name="Otp" value={otp.Otp}/>
        </div>
        <button onSubmit={handleSubmit}>Submit</button>
      </div>
    </>
  );
};

export default ForgotForm;

</code>```

enter image description here

Body:
i am writing code for forget password in react

here the first input field which consists of Email and also there is a sendOtp button when i click on sendOtp the email which is entered it stores into a object separately

the second field which consist for otp when a user enters it also stores into a object separately

after these input fields there is a button i used onsubmit when i click on button the email and otp should be stored in array but it is not coming can any help please?????

import React, {useState} from "react";

const ForgotForm = () => {

    const [emai, setEmai] = useState({
    Email:""
  })

  const [otp, setOtp] = useState({
    Otp:""
  })
const handleChange =(e)=> {
  const {name, value} = e.target;
  setEmai({...emai, [name]: value})
}

const consoleEmail = (e) => {
  e.preventDefault();
  console.log(emai)
  setEmai({Email:""})
}

const handleOTP = (e) =>{
  const {name, value} = e.target;
  setOtp({...otp, [name]: value})
  console.log(otp)
}

const [forme,setForme] = useState({
  emai:"",
  otp:""
})

const handleData = (e) => {
  const {name, value} = e.target;
  setForme({...emai,...otp, [name]:value})
}

const handleSubmit = (e)=>{
  e.preventDefault()
  setForme({emai:"",otp:""})
  console.log(forme)
}
  return (
    <>

Forgot Password

          <input type="text" placeholder="Email" onChange={handleChange} name="Email" value={emai.Email}/>
          <button onClick={consoleEmail}>Send Otp</button>

          <input type="text" placeholder="Otp" onChange={handleOTP} name="Otp" value={otp.Otp}/>

        <button onSubmit={handleSubmit}>Submit</button>

    </>
  );
};

export default ForgotForm;

enter image description here


问:
Beacon is broadcasting, even though my device's bluetooth is switched off
I need to know if I can broadcast an EDDYSTONE beacon even though my android(12) device's Bluetooth is deactivated. I am using this PLUGIN to broadcast.

I am asking this because what I have observed is that even though my Bluetooth is turned OFF, I am still able to broadcast the BLE signal.
Also, any clue what exact permission we require to broadcast a beacon in android?

Thanks in advance.


问:
IntegrityError at /accounts/ProfileRegister/ UNIQUE constraint failed: auth_user.id
I am creating a registration page, and after finishing the work, I received this error, everything is saved, but the information is not displayed in the profile section. I am a beginner.

Views

```<code>def ProfileRegisterView(request):

    if request.method=='POST':
        profileRegisterForm=ProfileRegisterForm(request.POST,request.FILES)
        if profileRegisterForm.is_valid():
            user=User.objects.create_user(
                username=profileRegisterForm.cleaned_data['username'],
                email=profileRegisterForm.cleaned_data['email'],
                password=profileRegisterForm.cleaned_data['password'],
                first_name=profileRegisterForm.cleaned_data['first_name'],
                last_name=profileRegisterForm.cleaned_data['last_name'],)
            user.save(profileRegisterForm)
            profileModel=ProfileModel(user=user,
                                      profileImage=profileRegisterForm.cleaned_data['profileImage'],
                                      Gender=profileRegisterForm.cleaned_data['Gender'],
                                      Credit=profileRegisterForm.cleaned_data['Credit'])
            profileModel.save()
            return HttpResponseRedirect(reverse(ticketsale.views.concertListView))
    else:
        profileRegisterForm=ProfileRegisterForm()

    context={
        "formData":profileRegisterForm
    }

    return render(request,"accounts/ProfileRegister.html",context)
</code>```

template

```<code>{% extends 'ticketsale/layout.html' %}
{%block titlepage%}
ثبت نام
{% endblock %}

{%block mainContent%}
<form action="" method="POST" class="form form-control bg-dark p-5" enctype="multipart/form-data">
    {% csrf_token %}
    {% comment %} {{ Concertform }} {% endcomment %}
    <div class="container">
        <div class="row">
            <div class="col-md-6">
                <p class="form form-control">نام: {{ formData.first_name }}</p>
                <p class="form form-control">نام خانوادگی: {{ formData.last_name }}</p>
                <p class="form form-control">جنسیت : {{ formData.Gender}}</p>
                <p class="form form-control">مقداراعتبار : {{ formData.Credit }}</p>
            </div>
            <div class="col-md-6">
                <p class="form form-control">ایمیل: {{ formData.email }}</p>
                <p class="form form-control">نام کاربری: {{ formData.username }}</p>
                <p class="form form-control">رمز عبور: {{ formData.password }}</p>
                {{ formData.profileImage }}
            </div>
        </div>
    </div>
    <button type="submit" class="btn btn-info">ثبت نام</button>
</form>
{% endblock %}
</code>```

Models

```<code>class ProfileModel(models.Model):
    class Meta:
        verbose_name="کاربر"
        verbose_name_plural="کاربر"

    user=models.OneToOneField(User,on_delete=models.CASCADE,verbose_name="کاربری",related_name="profile")
    # Name=models.CharField(max_length=100,verbose_name="نام")
    # Family=models.CharField(max_length=100,verbose_name="نام خانوادگی")
    profileImage=models.ImageField(upload_to="profileImage/",verbose_name="عکس")
    Man=1
    Woman=2
    status_chioces=((Man,"مرد"),(Woman,"زن"))
    Gender=models.IntegerField(choices=status_chioces,verbose_name="جنسیت")
    Credit=models.IntegerField(verbose_name="اعتبار",default=0)

</code>```

forms

```<code>class ProfileRegisterForm(forms.ModelForm):
    first_name=forms.CharField(max_length=100)
    last_name=forms.CharField(max_length=100)
    username=forms.CharField(max_length=100)
    password=forms.CharField(widget=forms.PasswordInput)
    email=forms.CharField(widget=forms.EmailInput)

    class Meta:
        model=ProfileModel
        fields=['profileImage','Gender','Credit']
</code>```

I expect that after registration, the complete profile will be created and there is no need to enter the information manually

Body:
I am creating a registration page, and after finishing the work, I received this error, everything is saved, but the information is not displayed in the profile section. I am a beginner.

Views

def ProfileRegisterView(request):

    if request.method=='POST':
        profileRegisterForm=ProfileRegisterForm(request.POST,request.FILES)
        if profileRegisterForm.is_valid():
            user=User.objects.create_user(
                username=profileRegisterForm.cleaned_data['username'],
                email=profileRegisterForm.cleaned_data['email'],
                password=profileRegisterForm.cleaned_data['password'],
                first_name=profileRegisterForm.cleaned_data['first_name'],
                last_name=profileRegisterForm.cleaned_data['last_name'],)
            user.save(profileRegisterForm)
            profileModel=ProfileModel(user=user,
                                      profileImage=profileRegisterForm.cleaned_data['profileImage'],
                                      Gender=profileRegisterForm.cleaned_data['Gender'],
                                      Credit=profileRegisterForm.cleaned_data['Credit'])
            profileModel.save()
            return HttpResponseRedirect(reverse(ticketsale.views.concertListView))
    else:
        profileRegisterForm=ProfileRegisterForm()

    context={
        "formData":profileRegisterForm
    }

    return render(request,"accounts/ProfileRegister.html",context)

template

{% extends 'ticketsale/layout.html' %}
{%block titlepage%}
ثبت نام
{% endblock %}

{%block mainContent%}
<form action="" method="POST" class="form form-control bg-dark p-5" enctype="multipart/form-data">
    {% csrf_token %}
    {% comment %} {{ Concertform }} {% endcomment %}

نام: {{ formData.first_name }}

نام خانوادگی: {{ formData.last_name }}

جنسیت : {{ formData.Gender}}

مقداراعتبار : {{ formData.Credit }}

ایمیل: {{ formData.email }}

نام کاربری: {{ formData.username }}

رمز عبور: {{ formData.password }}

                {{ formData.profileImage }}

    <button type="submit" class="btn btn-info">ثبت نام</button>
</form>
{% endblock %}

Models

class ProfileModel(models.Model):
    class Meta:
        verbose_name="کاربر"
        verbose_name_plural="کاربر"

    user=models.OneToOneField(User,on_delete=models.CASCADE,verbose_name="کاربری",related_name="profile")
    # Name=models.CharField(max_length=100,verbose_name="نام")
    # Family=models.CharField(max_length=100,verbose_name="نام خانوادگی")
    profileImage=models.ImageField(upload_to="profileImage/",verbose_name="عکس")
    Man=1
    Woman=2
    status_chioces=((Man,"مرد"),(Woman,"زن"))
    Gender=models.IntegerField(choices=status_chioces,verbose_name="جنسیت")
    Credit=models.IntegerField(verbose_name="اعتبار",default=0)

forms

class ProfileRegisterForm(forms.ModelForm):
    first_name=forms.CharField(max_length=100)
    last_name=forms.CharField(max_length=100)
    username=forms.CharField(max_length=100)
    password=forms.CharField(widget=forms.PasswordInput)
    email=forms.CharField(widget=forms.EmailInput)

    class Meta:
        model=ProfileModel
        fields=['profileImage','Gender','Credit']

I expect that after registration, the complete profile will be created and there is no need to enter the information manually