问:
C# Kafka: How to Create a NetworkException Error
I am writing an integration test for my app and would like to test my exception-handling functionality. More specifically, I need my Kafka Producer's DeliveryReport to claim that a Kafka NetworkException has occurred -- which will trigger my app's Kafka NetworkException logic. This will allow me to see how well my application handles a Kafka NetworkException.

Below is my application's Send() logic -- which produces a message via Kafka, along with the DeliveryResult method that gets passed to the producer -- this handles the Kafka response; which is what should notify me of a NetworkException if one should occur:

        public void Send(
            ProducerMessage<TKey, TValue> producerMessage,
            string topic,
            Action<McFlowProducerResult<TKey, TValue>> callback = null)
        {

            _producer.Produce(topic, producerMessage,
                    deliveryReport => HandleDeliveryReport(deliveryReport, callback));

        }

        private Task HandleDeliveryReportErrorAsync(DeliveryReport<string, string> deliveryReport)
        {
            if (deliveryReport.Error.Code == ErrorCode.NetworkException)
            {
                _logger.LogError("Sending message to DynamoDb");
                return _fatalErrorHandler
                    .HandleError(new McFlowProducerResult<string, string>(deliveryReport));
            }

            return Task.CompletedTask;
        }

        private void HandleDeliveryReport(DeliveryReport<string, string> deliveryReport,
            Action<McFlowProducerResult<TKey,TValue>> callback)
        {
            var mcflowProducerResult = new McFlowProducerResult<string, string>(deliveryReport);

            if (!deliveryReport.Error.IsError)
            {
                _logger.LogInformation("Message Sent successfully  to DLQ TOPIC");
                callback?.Invoke(mcflowProducerResult as McFlowProducerResult<TKey, TValue>);
            }

            _logger.LogError("Unable to send the message to DLQ TOPIC: {Topic}. Error Reason :{Error}",
                deliveryReport.Topic, deliveryReport.Error.Reason);

            HandleDeliveryReportErrorAsync(deliveryReport).ConfigureAwait(false).GetAwaiter().GetResult();
        }
```
<p>Below is my integration test, which successfully produces messages into the specified topic and consumes them just fine.  The problem is, I want to purposely cause a Kafka <code>NetworkException</code>, so that I can see my <code>DeliveryHandler</code>'s <code>HandleDeliveryReportErrorAsync</code> logic in action:</p>
<pre class="lang-cs prettyprint-override"><code>        [Fact]
        public async Task CreateNetworkException()
        {
            const string dlqTopicName = TOPIC_NAME + "-producer-dlq";
            var serializedProducerMessageKey = _mcFlowMessageSerializer.Serialize(_producerMessage.Message.Key);

            await _topicFixture.CreateTopic(dlqTopicName, 1, 1);

            var testUtil = new ConsumerTestHarness(_confluentConsumerConfig);

            var deliveryReportTaskCompletionSource = new TaskCompletionSource<McFlowProducerResult<string, object>>();
            McFlowProducerResult<string, object> callbackResult = null;

            _mcFlowDlqProducer.Send(_producerMessage, dlqTopicName,
                (deliveryResult) =>
                {
                    callbackResult = deliveryResult;
                    deliveryReportTaskCompletionSource.SetResult(deliveryResult);
                });

            await deliveryReportTaskCompletionSource.Task;

            testUtil.Consume(dlqTopicName, TimeSpan.FromSeconds(5));
            var results = testUtil.Results;

            var expectedMessage
                = results.Find(message
                    => message.Message.Key.Equals(serializedProducerMessageKey));

            Assert.Equal(serializedProducerMessageKey, expectedMessage.Message.Key);
        }
</code>```

This is the ProducerConfig I'm using to create my Kafka Producer in my integration test:

        var confluentProducerConfig = new ProducerConfig()
        {
            BootstrapServers = "localhost:29092/1",
            Acks = Acks.All
        };
```

How can I create the conditions for a Kafka NetworkException to occur?

Body:
I am writing an integration test for my app and would like to test my exception-handling functionality. More specifically, I need my Kafka Producer's DeliveryReport to claim that a Kafka NetworkException has occurred -- which will trigger my app's Kafka NetworkException logic. This will allow me to see how well my application handles a Kafka NetworkException.

Below is my application's Send() logic -- which produces a message via Kafka, along with the DeliveryResult method that gets passed to the producer -- this handles the Kafka response; which is what should notify me of a NetworkException if one should occur:

        public void Send(
            ProducerMessage<TKey, TValue> producerMessage,
            string topic,
            Action<McFlowProducerResult<TKey, TValue>> callback = null)
        {

            _producer.Produce(topic, producerMessage,
                    deliveryReport => HandleDeliveryReport(deliveryReport, callback));

        }

        private Task HandleDeliveryReportErrorAsync(DeliveryReport<string, string> deliveryReport)
        {
            if (deliveryReport.Error.Code == ErrorCode.NetworkException)
            {
                _logger.LogError("Sending message to DynamoDb");
                return _fatalErrorHandler
                    .HandleError(new McFlowProducerResult<string, string>(deliveryReport));
            }

            return Task.CompletedTask;
        }

        private void HandleDeliveryReport(DeliveryReport<string, string> deliveryReport,
            Action<McFlowProducerResult<TKey,TValue>> callback)
        {
            var mcflowProducerResult = new McFlowProducerResult<string, string>(deliveryReport);

            if (!deliveryReport.Error.IsError)
            {
                _logger.LogInformation("Message Sent successfully  to DLQ TOPIC");
                callback?.Invoke(mcflowProducerResult as McFlowProducerResult<TKey, TValue>);
            }

            _logger.LogError("Unable to send the message to DLQ TOPIC: {Topic}. Error Reason :{Error}",
                deliveryReport.Topic, deliveryReport.Error.Reason);

            HandleDeliveryReportErrorAsync(deliveryReport).ConfigureAwait(false).GetAwaiter().GetResult();
        }

Below is my integration test, which successfully produces messages into the specified topic and consumes them just fine.  The problem is, I want to purposely cause a Kafka NetworkException, so that I can see my DeliveryHandler's HandleDeliveryReportErrorAsync logic in action:

        [Fact]
        public async Task CreateNetworkException()
        {
            const string dlqTopicName = TOPIC_NAME + "-producer-dlq";
            var serializedProducerMessageKey = _mcFlowMessageSerializer.Serialize(_producerMessage.Message.Key);

            await _topicFixture.CreateTopic(dlqTopicName, 1, 1);

            var testUtil = new ConsumerTestHarness(_confluentConsumerConfig);

            var deliveryReportTaskCompletionSource = new TaskCompletionSource<McFlowProducerResult<string, object>>();
            McFlowProducerResult<string, object> callbackResult = null;

            _mcFlowDlqProducer.Send(_producerMessage, dlqTopicName,
                (deliveryResult) =>
                {
                    callbackResult = deliveryResult;
                    deliveryReportTaskCompletionSource.SetResult(deliveryResult);
                });

            await deliveryReportTaskCompletionSource.Task;

            testUtil.Consume(dlqTopicName, TimeSpan.FromSeconds(5));
            var results = testUtil.Results;

            var expectedMessage
                = results.Find(message
                    => message.Message.Key.Equals(serializedProducerMessageKey));

            Assert.Equal(serializedProducerMessageKey, expectedMessage.Message.Key);
        }

This is the ProducerConfig I'm using to create my Kafka Producer in my integration test:

        var confluentProducerConfig = new ProducerConfig()
        {
            BootstrapServers = "localhost:29092/1",
            Acks = Acks.All
        };

How can I create the conditions for a Kafka NetworkException to occur?


来源: stackexchange

问:
Format Timestamp on Google Apps Script HTML Print
I haven't been able to figure out how to properly set a timestamp format for the output result of the script.

The script I've got pulls data from a Google Sheet, checks that the user viewing the HTML page is on the sheet, and returns only those values that match the signed in user's email (allowing them to view only their records). The script then prints out the matching records on an HTML page.

The problem is the timestamp column and it's formatting.

The values stored in the GS is the timestamp of when the entry was submitted, and is:

MM/DD/YYY HH:MM:SS.
```
<p>When the script runs, the HTML output format of the timestamp column is the default:</p>
<pre class="lang-none prettyprint-override"><code>Fri Dec 09 2022 15:16:47 GMT-0700 (Mountain Standard Time)
</code>```

I would like to keep the formatting as it's stored in the GS. I have tried multiple things here, but none seem to work.

This is the section of my script that pulls the sheet data and sends it to the Index.html page as a table:

```<code>function getData() {
  var sheetName = dataSheet;
  var activeSheet = ss.getSheetByName(sheetName);
  var values = activeSheet.getDataRange().getValues();
  var header = values[0];
  var emailIndex = header.indexOf(emailHeader);
  var userData = [];
  for (var i = 0; i < values.length; i++) {
    if (values[i][emailIndex] == activeUser) {
      userData.push(values[i]);
    }
  }
  if (userData.length > 0) {
    var tableStart = '\n<table class="table table-hover table-sm">';
    var tableHead = '\n<thead>\n<tr>';
    for (var j = 0; j < header.length; j++) {
      tableHead = tableHead + '\n<th>' + header[j] + '</th>';
    }
    tableHead = tableHead + '\n</tr>\n</thead>';
    var tableBody = '\n<tbody>';
    for (var k = 0; k < userData.length; k++) {
      tableBody = tableBody + '\n<tr>';
      for (var l = 0; l < userData[0].length; l++) {
        tableBody = tableBody + '\n<td>' + userData[k][l] + '</td>';
      }
      tableBody = tableBody + '\n</tr>\n';
    }
    var tableEnd = '</tbody>\n</table>';
    var tableHtml = tableStart + tableHead + tableBody + tableEnd;
    return tableHtml;
  } else {
    return '<table class="table"><tbody><tr><td>No data found.</td></tr></tbody></table>';
  }
}
</code>```

This is from the HTML page:

```

ContentLicense: CC BY-SA 4.0

Body:
I haven't been able to figure out how to properly set a timestamp format for the output result of the script.

The script I've got pulls data from a Google Sheet, checks that the user viewing the HTML page is on the sheet, and returns only those values that match the signed in user's email (allowing them to view only their records). The script then prints out the matching records on an HTML page.

The problem is the timestamp column and it's formatting.

The values stored in the GS is the timestamp of when the entry was submitted, and is:

MM/DD/YYY HH:MM:SS.

When the script runs, the HTML output format of the timestamp column is the default:

Fri Dec 09 2022 15:16:47 GMT-0700 (Mountain Standard Time)

I would like to keep the formatting as it's stored in the GS. I have tried multiple things here, but none seem to work.

This is the section of my script that pulls the sheet data and sends it to the Index.html page as a table:

function getData() {
  var sheetName = dataSheet;
  var activeSheet = ss.getSheetByName(sheetName);
  var values = activeSheet.getDataRange().getValues();
  var header = values[0];
  var emailIndex = header.indexOf(emailHeader);
  var userData = [];
  for (var i = 0; i < values.length; i++) {
    if (values[i][emailIndex] == activeUser) {
      userData.push(values[i]);
    }
  }
  if (userData.length > 0) {
    var tableStart = '\n
';
    var tableHead = '\n
\n
';
    for (var j = 0; j < header.length; j++) {
      tableHead = tableHead + '\n' + header[j] + '	';
    }
    tableHead = tableHead + '\n
\n
';
    var tableBody = '\n
';
    for (var k = 0; k < userData.length; k++) {
      tableBody = tableBody + '\n
';
      for (var l = 0; l < userData[0].length; l++) {
        tableBody = tableBody + '\n' + userData[k][l] + '	';
      }
      tableBody = tableBody + '\n
\n';
    }
    var tableEnd = '
\n
';
    var tableHtml = tableStart + tableHead + tableBody + tableEnd;
    return tableHtml;
  } else {
    return '

No data found.

';
  }
}

This is from the HTML page:


问:
Hello World NASM Shell Error in .exe file
Im running a Windows OS 64-bit i am trying to do a simple Helloworld Using NASM Shell Already had MingW Installed, its just that when the exe.file is executed it shows win32 exception, and .exe file has stopped working

Already tried to compile using
nasm -f elf64 and gcc

Sample ASM File
`

```<code>SECTION .data
msg:    db "Hello World",10
len:    equ $-msg

    SECTION .text
        global main
main:

    mov edx,len
    mov ecx,msg
    mov ebx,1
    mov eax,4
    int 0x80

    mov ebx,0
    mov eax,1
    int 0x80
</code>```

`

Im just expecting a simple Hello World Using Assembly Language, already tried to install linux subservice for windows

Body:
Im running a Windows OS 64-bit i am trying to do a simple Helloworld Using NASM Shell Already had MingW Installed, its just that when the exe.file is executed it shows win32 exception, and .exe file has stopped working

Already tried to compile using
nasm -f elf64 and gcc

Sample ASM File
`

SECTION .data
msg:    db "Hello World",10
len:    equ $-msg

    SECTION .text
        global main
main:

    mov edx,len
    mov ecx,msg
    mov ebx,1
    mov eax,4
    int 0x80

    mov ebx,0
    mov eax,1
    int 0x80

`

Im just expecting a simple Hello World Using Assembly Language, already tried to install linux subservice for windows


问:
ODE fitting with Python - least squares takes to long to compute
I'm trying to replicate the results of "Modeling Plasma Virus Concentration during Primary HIV Infection", by fitting the data sets to my ODE.
Essencially I need to fit 4 parameters (d, k, delta, p) to a dif. equation given a data set.

Up until now I got the following code done (I'm a begginer):

```<code>c = 3 #global constant
v0= 10e-6

#dados
timeDataPatient1=np.array([0,22,43,78,106,146,183,230,268,358,435,489,519,534,584,610,687,778])
VirDataPatient1=10e3*np.array([v0*10e-3,27.2,210,85.9,81.1,46.2,60.1,82.8,103,72.1,79.4,70.4,207,42.6,10.8,54.2,22.3,40.8])

xdata = timeDataPatient1
ydata = VirDataPatient1

#inicial condition and max time of data set
IC = [10,0,10e-6]
t_max = max(xdata)

def diffeqs(t,y,d,k,delta,p):
    '''Model of the differencial equation'''
    global lam, c

    T=y[0]
    I=y[1]
    V=y[2]

    dT = 10*d - d*T-k*T*V
    dI = k*T*V - delta*I
    dV = p*I-c*V

    return [dT,dI,dV]

def Vtime(theta):
    '''solves the differencial equation, and returns the values of the model on the time points corresponding to the data set'''

    global t_max, IC, xdata

    sol = solve_ivp(diffeqs, (0,t_max), IC, args = (theta),t_eval=xdata)

    return sol.y[2]

#now I define the objetive function to minimize. For a parameter theta, that corresponds to d,k,delta,p in the ODE model,it calculates the difference between the log of the data given and the predicts by the ODE model.

def calcErrorHIV(theta):
    '''objetive function given in the paper'''
    global ydata

    dif = np.log(ydata)-np.log(Vtime(theta))

    return sum(dif**2)

#should return theta parameters that best fits the data, but It doesn't compute.
sp.optimize.least_squares(calcErrorHIV,[0.013,0.46e-2,0.40,980])
</code>```

but when I try to run the otimize or least_squares function I get no result.

Does my code have a problem or the 4 parameters problem takes a long time to solve?

Thanks for the help.

Edit: I tried the inicial guess [0.013,0.46 10*(-3),0.40,980]

Edit2: Added extra info about the problem.

Body:
I'm trying to replicate the results of "Modeling Plasma Virus Concentration during Primary HIV Infection", by fitting the data sets to my ODE.
Essencially I need to fit 4 parameters (d, k, delta, p) to a dif. equation given a data set.

Up until now I got the following code done (I'm a begginer):

c = 3 #global constant
v0= 10e-6

#dados
timeDataPatient1=np.array([0,22,43,78,106,146,183,230,268,358,435,489,519,534,584,610,687,778])
VirDataPatient1=10e3*np.array([v0*10e-3,27.2,210,85.9,81.1,46.2,60.1,82.8,103,72.1,79.4,70.4,207,42.6,10.8,54.2,22.3,40.8])

xdata = timeDataPatient1
ydata = VirDataPatient1

#inicial condition and max time of data set
IC = [10,0,10e-6]
t_max = max(xdata)

def diffeqs(t,y,d,k,delta,p):
    '''Model of the differencial equation'''
    global lam, c

    T=y[0]
    I=y[1]
    V=y[2]

    dT = 10*d - d*T-k*T*V
    dI = k*T*V - delta*I
    dV = p*I-c*V

    return [dT,dI,dV]

def Vtime(theta):
    '''solves the differencial equation, and returns the values of the model on the time points corresponding to the data set'''

    global t_max, IC, xdata

    sol = solve_ivp(diffeqs, (0,t_max), IC, args = (theta),t_eval=xdata)

    return sol.y[2]

#now I define the objetive function to minimize. For a parameter theta, that corresponds to d,k,delta,p in the ODE model,it calculates the difference between the log of the data given and the predicts by the ODE model.

def calcErrorHIV(theta):
    '''objetive function given in the paper'''
    global ydata

    dif = np.log(ydata)-np.log(Vtime(theta))

    return sum(dif**2)

#should return theta parameters that best fits the data, but It doesn't compute.
sp.optimize.least_squares(calcErrorHIV,[0.013,0.46e-2,0.40,980])

but when I try to run the otimize or least_squares function I get no result.

Does my code have a problem or the 4 parameters problem takes a long time to solve?

Thanks for the help.

Edit: I tried the inicial guess [0.013,0.46 10*(-3),0.40,980]

Edit2: Added extra info about the problem.


问:
RuntimeError: Input type (torch.cuda.FloatTensor) and weight type (torch.FloatTensor) should be the same. How to fix it?
I am trying to fix Multi-Tacotron-Voice-Cloning because the original site is not working.

When I call !python demo_cli.py -p "audio/input/ex.wav" -t "Hello my friends" --no_sound
throws this error: "RuntimeError: Input type (torch.cuda.FloatTensor) and weight type (torch.FloatTensor) should be the same"

I have selected GPU runtime in google colab settings.

Google colab: https://colab.research.google.com/drive/1ovleVvsZ_4HAYXKSP-_IF7381lDPvk77?usp=sharing

What needs to be changed in the demo_cli.py to make it work?

demo_cli.py:

```<code>from encoder.params_model import model_embedding_size as speaker_embedding_size
from utils.argutils import print_args
from synthesizer.inference import Synthesizer
from encoder import inference as encoder
from vocoder import inference as vocoder
from pathlib import Path
import numpy as np
import librosa
import argparse
import torch
import sys
from g2p.train import g2p
import soundfile as sf

if __name__ == '__main__':
    ## Info & args
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )
    parser.add_argument("-e", "--enc_model_fpath", type=Path,
                        default="encoder/saved_models/pretrained.pt",
                        help="Path to a saved encoder")
    parser.add_argument("-s", "--syn_model_dir", type=Path,
                        default="synthesizer/saved_models/logs-pretrained/",
                        help="Directory containing the synthesizer model")
    parser.add_argument("-v", "--voc_model_fpath", type=Path,
                        default="vocoder/saved_models/pretrained/pretrained.pt",
                        help="Path to a saved vocoder")
    parser.add_argument("--low_mem", action="store_true", help=\
        "If True, the memory used by the synthesizer will be freed after each use. Adds large "
        "overhead but allows to save some GPU memory for lower-end GPUs.")
    parser.add_argument("--no_sound", action="store_true", help=\
        "If True, audio won't be played.")
    parser.add_argument("-t", "--text",
                        default="Hello my friends",
                        help="Text")
    parser.add_argument("-p", "--path_wav", type=Path,
                        default="audio/input/ex.wav",
                        help="wav file")
    args = parser.parse_args()
    print_args(args, parser)
    if not args.no_sound:
        import sounddevice as sd

    ## Load the models one by one.
    print("Preparing the encoder, the synthesizer and the vocoder...")
    encoder.load_model(args.enc_model_fpath)
    print("args.enc_model_fpath:")
    print(args.enc_model_fpath)
    synthesizer = Synthesizer(args.syn_model_dir.joinpath("taco_pretrained"), low_mem=args.low_mem)

    vocoder.load_model(args.voc_model_fpath)
    print("args.voc_model_fpath:")
    print(args.voc_model_fpath)

    ## Run a test
    print("Testing your configuration with small inputs.")
    # Forward an audio waveform of zeroes that lasts 1 second. Notice how we can get the encoder's
    # sampling rate, which may differ.
    # If you're unfamiliar with digital audio, know that it is encoded as an array of floats
    # (or sometimes integers, but mostly floats in this projects) ranging from -1 to 1.
    # The sampling rate is the number of values (samples) recorded per second, it is set to
    # 16000 for the encoder. Creating an array of length <sampling_rate> will always correspond
    # to an audio of 1 second.
    print("\tTesting the encoder...")
    encoder.embed_utterance(np.zeros(encoder.sampling_rate))

    # Create a dummy embedding. You would normally use the embedding that encoder.embed_utterance
    # returns, but here we're going to make one ourselves just for the sake of showing that it's
    # possible.
    embed = np.random.rand(speaker_embedding_size)
    # Embeddings are L2-normalized (this isn't important here, but if you want to make your own
    # embeddings it will be).
    embed /= np.linalg.norm(embed)
    # The synthesizer can handle multiple inputs with batching. Let's create another embedding to
    # illustrate that
    embeds = [embed, np.zeros(speaker_embedding_size)]
    texts = ["test 1", "test 2"]
    print("\tTesting the synthesizer... (loading the model will output a lot of text)")
    mels = synthesizer.synthesize_spectrograms(texts, embeds)

    # The vocoder synthesizes one waveform at a time, but it's more efficient for long ones. We
    # can concatenate the mel spectrograms to a single one.
    mel = np.concatenate(mels, axis=1)
    # The vocoder can take a callback function to display the generation. More on that later. For
    # now we'll simply hide it like this:
    no_action = lambda *args: None
    print("\tTesting the vocoder...")
    # For the sake of making this test short, we'll pass a short target length. The target length
    # is the length of the wav segments that are processed in parallel. E.g. for audio sampled
    # at 16000 Hertz, a target length of 8000 means that the target audio will be cut in chunks of
    # 0.5 seconds which will all be generated together. The parameters here are absurdly short, and
    # that has a detrimental effect on the quality of the audio. The default parameters are
    # recommended in general.
    vocoder.infer_waveform(mel, target=200, overlap=50, progress_callback=no_action)

    print("All test passed! You can now synthesize speech.\n\n")

    ## Interactive speech generation
    print("This is a GUI-less example of interface to SV2TTS. The purpose of this script is to "
          "show how you can interface this project easily with your own. See the source code for "
          "an explanation of what is happening.\n")

    print("Interactive generation loop")
    num_generated = 0

    # Get the reference audio filepath
    #message = "Reference voice: enter an audio filepath of a voice to be cloned(Введите путь до клонируемого файла, например audio/input/ex.wav) (mp3, " \
    #          "wav, m4a, flac, ...):\n"
    #in_fpath = Path(input(message).replace("\"", "").replace("\'", ""))
    in_fpath = args.path_wav

    ## Computing the embedding
    # First, we load the wav using the function that the speaker encoder provides. This is
    # important: there is preprocessing that must be applied.

    # The following two methods are equivalent:
    # - Directly load from the filepath:
    preprocessed_wav = encoder.preprocess_wav(in_fpath)
    # - If the wav is already loaded:
    original_wav, sampling_rate = librosa.load(in_fpath)
    preprocessed_wav = encoder.preprocess_wav(original_wav, sampling_rate)
    print("Loaded file succesfully")

    # Then we derive the embedding. There are many functions and parameters that the
    # speaker encoder interfaces. These are mostly for in-depth research. You will typically
    # only use this function (with its default parameters):
    embed = encoder.embed_utterance(preprocessed_wav)
    print("Created the embedding")

    ## Generating the spectrogram
    # text = input("Write a sentence (+-20 words) to be synthesized:(Введите предложение для синтеза)\n")

    # The synthesizer works in batch, so you need to put your data in a list or numpy array
    texts = [args.text]
    texts = g2p(texts)
    print(texts)
    embeds = [embed]
    # If you know what the attention layer alignments are, you can retrieve them here by
    # passing return_alignments=True
    specs = synthesizer.synthesize_spectrograms(texts, embeds)
    spec = specs[0]
    print("Created the mel spectrogram")

    ## Generating the waveform
    print("Synthesizing the waveform:")
    # Synthesizing the waveform is fairly straightforward. Remember that the longer the
    # spectrogram, the more time-efficient the vocoder.
    generated_wav = vocoder.infer_waveform(spec)

    ## Post-generation
    # There's a bug with sounddevice that makes the audio cut one second earlier, so we
    # pad it.
    generated_wav = np.pad(generated_wav, (0, synthesizer.sample_rate), mode="constant")

    # Play the audio (non-blocking)
    if not args.no_sound:
        sd.stop()
        sd.play(generated_wav, synthesizer.sample_rate)

    # Save it on the disk
    fpath = "audio/output/demo_output_%02d.wav" % num_generated
    print(generated_wav.dtype)
    sf.write(fpath, generated_wav.astype(np.float32),
                             synthesizer.sample_rate)
    num_generated += 1
    print("\nSaved output as %s\n\n" % fpath)
</code>```

Body:
I am trying to fix Multi-Tacotron-Voice-Cloning because the original site is not working.

When I call !python demo_cli.py -p "audio/input/ex.wav" -t "Hello my friends" --no_sound
throws this error: "RuntimeError: Input type (torch.cuda.FloatTensor) and weight type (torch.FloatTensor) should be the same"

I have selected GPU runtime in google colab settings.

Google colab: https://colab.research.google.com/drive/1ovleVvsZ_4HAYXKSP-_IF7381lDPvk77?usp=sharing

What needs to be changed in the demo_cli.py to make it work?

demo_cli.py:

from encoder.params_model import model_embedding_size as speaker_embedding_size
from utils.argutils import print_args
from synthesizer.inference import Synthesizer
from encoder import inference as encoder
from vocoder import inference as vocoder
from pathlib import Path
import numpy as np
import librosa
import argparse
import torch
import sys
from g2p.train import g2p
import soundfile as sf

if __name__ == '__main__':
    ## Info & args
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )
    parser.add_argument("-e", "--enc_model_fpath", type=Path,
                        default="encoder/saved_models/pretrained.pt",
                        help="Path to a saved encoder")
    parser.add_argument("-s", "--syn_model_dir", type=Path,
                        default="synthesizer/saved_models/logs-pretrained/",
                        help="Directory containing the synthesizer model")
    parser.add_argument("-v", "--voc_model_fpath", type=Path,
                        default="vocoder/saved_models/pretrained/pretrained.pt",
                        help="Path to a saved vocoder")
    parser.add_argument("--low_mem", action="store_true", help=\
        "If True, the memory used by the synthesizer will be freed after each use. Adds large "
        "overhead but allows to save some GPU memory for lower-end GPUs.")
    parser.add_argument("--no_sound", action="store_true", help=\
        "If True, audio won't be played.")
    parser.add_argument("-t", "--text",
                        default="Hello my friends",
                        help="Text")
    parser.add_argument("-p", "--path_wav", type=Path,
                        default="audio/input/ex.wav",
                        help="wav file")
    args = parser.parse_args()
    print_args(args, parser)
    if not args.no_sound:
        import sounddevice as sd

    ## Load the models one by one.
    print("Preparing the encoder, the synthesizer and the vocoder...")
    encoder.load_model(args.enc_model_fpath)
    print("args.enc_model_fpath:")
    print(args.enc_model_fpath)
    synthesizer = Synthesizer(args.syn_model_dir.joinpath("taco_pretrained"), low_mem=args.low_mem)

    vocoder.load_model(args.voc_model_fpath)
    print("args.voc_model_fpath:")
    print(args.voc_model_fpath)

    ## Run a test
    print("Testing your configuration with small inputs.")
    # Forward an audio waveform of zeroes that lasts 1 second. Notice how we can get the encoder's
    # sampling rate, which may differ.
    # If you're unfamiliar with digital audio, know that it is encoded as an array of floats
    # (or sometimes integers, but mostly floats in this projects) ranging from -1 to 1.
    # The sampling rate is the number of values (samples) recorded per second, it is set to
    # 16000 for the encoder. Creating an array of length <sampling_rate> will always correspond
    # to an audio of 1 second.
    print("\tTesting the encoder...")
    encoder.embed_utterance(np.zeros(encoder.sampling_rate))

    # Create a dummy embedding. You would normally use the embedding that encoder.embed_utterance
    # returns, but here we're going to make one ourselves just for the sake of showing that it's
    # possible.
    embed = np.random.rand(speaker_embedding_size)
    # Embeddings are L2-normalized (this isn't important here, but if you want to make your own
    # embeddings it will be).
    embed /= np.linalg.norm(embed)
    # The synthesizer can handle multiple inputs with batching. Let's create another embedding to
    # illustrate that
    embeds = [embed, np.zeros(speaker_embedding_size)]
    texts = ["test 1", "test 2"]
    print("\tTesting the synthesizer... (loading the model will output a lot of text)")
    mels = synthesizer.synthesize_spectrograms(texts, embeds)

    # The vocoder synthesizes one waveform at a time, but it's more efficient for long ones. We
    # can concatenate the mel spectrograms to a single one.
    mel = np.concatenate(mels, axis=1)
    # The vocoder can take a callback function to display the generation. More on that later. For
    # now we'll simply hide it like this:
    no_action = lambda *args: None
    print("\tTesting the vocoder...")
    # For the sake of making this test short, we'll pass a short target length. The target length
    # is the length of the wav segments that are processed in parallel. E.g. for audio sampled
    # at 16000 Hertz, a target length of 8000 means that the target audio will be cut in chunks of
    # 0.5 seconds which will all be generated together. The parameters here are absurdly short, and
    # that has a detrimental effect on the quality of the audio. The default parameters are
    # recommended in general.
    vocoder.infer_waveform(mel, target=200, overlap=50, progress_callback=no_action)

    print("All test passed! You can now synthesize speech.\n\n")

    ## Interactive speech generation
    print("This is a GUI-less example of interface to SV2TTS. The purpose of this script is to "
          "show how you can interface this project easily with your own. See the source code for "
          "an explanation of what is happening.\n")

    print("Interactive generation loop")
    num_generated = 0

    # Get the reference audio filepath
    #message = "Reference voice: enter an audio filepath of a voice to be cloned(Введите путь до клонируемого файла, например audio/input/ex.wav) (mp3, " \
    #          "wav, m4a, flac, ...):\n"
    #in_fpath = Path(input(message).replace("\"", "").replace("\'", ""))
    in_fpath = args.path_wav

    ## Computing the embedding
    # First, we load the wav using the function that the speaker encoder provides. This is
    # important: there is preprocessing that must be applied.

    # The following two methods are equivalent:
    # - Directly load from the filepath:
    preprocessed_wav = encoder.preprocess_wav(in_fpath)
    # - If the wav is already loaded:
    original_wav, sampling_rate = librosa.load(in_fpath)
    preprocessed_wav = encoder.preprocess_wav(original_wav, sampling_rate)
    print("Loaded file succesfully")

    # Then we derive the embedding. There are many functions and parameters that the
    # speaker encoder interfaces. These are mostly for in-depth research. You will typically
    # only use this function (with its default parameters):
    embed = encoder.embed_utterance(preprocessed_wav)
    print("Created the embedding")

    ## Generating the spectrogram
    # text = input("Write a sentence (+-20 words) to be synthesized:(Введите предложение для синтеза)\n")

    # The synthesizer works in batch, so you need to put your data in a list or numpy array
    texts = [args.text]
    texts = g2p(texts)
    print(texts)
    embeds = [embed]
    # If you know what the attention layer alignments are, you can retrieve them here by
    # passing return_alignments=True
    specs = synthesizer.synthesize_spectrograms(texts, embeds)
    spec = specs[0]
    print("Created the mel spectrogram")

    ## Generating the waveform
    print("Synthesizing the waveform:")
    # Synthesizing the waveform is fairly straightforward. Remember that the longer the
    # spectrogram, the more time-efficient the vocoder.
    generated_wav = vocoder.infer_waveform(spec)

    ## Post-generation
    # There's a bug with sounddevice that makes the audio cut one second earlier, so we
    # pad it.
    generated_wav = np.pad(generated_wav, (0, synthesizer.sample_rate), mode="constant")

    # Play the audio (non-blocking)
    if not args.no_sound:
        sd.stop()
        sd.play(generated_wav, synthesizer.sample_rate)

    # Save it on the disk
    fpath = "audio/output/demo_output_%02d.wav" % num_generated
    print(generated_wav.dtype)
    sf.write(fpath, generated_wav.astype(np.float32),
                             synthesizer.sample_rate)
    num_generated += 1
    print("\nSaved output as %s\n\n" % fpath)


问:
java.lang.NoClassDefFoundError in Ant
I faced with the problem, when I am creating build.xml in Ant. The jar file is created, but at run stage throws this error:

```<code>     [java] Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/boot/SpringApplication
     [java]     at com.example.DemoApplication.main(Unknown Source)
     [java] Caused by: java.lang.ClassNotFoundException: org.springframework.boot.SpringApplication
     [java]     at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
     [java]     at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
     [java]     at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)
     [java]     ... 1 more
     [java] Java Result: 1
</code>```

This is my build.xml file:

```<code>
    <path id="classpath">
        <fileset dir="lib" includes="**/*.jar" />
    </path>

    <target name="clean">
        <delete dir="build"/>
        <delete dir="lib"/>
    </target>

    <target name="compile">
        <mkdir dir="build/classes"/>
        <javac srcdir="src" destdir="build/classes" classpathref="classpath"/>
    </target>

    <target name="jar">
        <mkdir dir="build/jar"/>
        <jar destfile="build/jar/HelloWorld.jar" basedir="build/classes">
            <manifest>
                <attribute name="Main-Class" value="com.example.DemoApplication"/>
            </manifest>
        </jar>
    </target>

    <target name="run" depends="jar">
        <java jar="build/jar/HelloWorld.jar" fork="true" />
    </target>

    <target name="all" depends="clean,resolve, compile, jar, run"/>

    <target name="resolve">
        <ivy:retrieve />
    </target>

</project>
</code>```

How could this problem be solved?

Title: java.lang.NoClassDefFoundError in Ant

Body:
I faced with the problem, when I am creating build.xml in Ant. The jar file is created, but at run stage throws this error:

     [java] Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/boot/SpringApplication
     [java]     at com.example.DemoApplication.main(Unknown Source)
     [java] Caused by: java.lang.ClassNotFoundException: org.springframework.boot.SpringApplication
     [java]     at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
     [java]     at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
     [java]     at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)
     [java]     ... 1 more
     [java] Java Result: 1

This is my build.xml file:

    <path id="classpath">
        <fileset dir="lib" includes="**/*.jar" />
    </path>

    <target name="clean">
        <delete dir="build"/>
        <delete dir="lib"/>
    </target>

    <target name="compile">
        <mkdir dir="build/classes"/>
        <javac srcdir="src" destdir="build/classes" classpathref="classpath"/>
    </target>

    <target name="jar">
        <mkdir dir="build/jar"/>
        <jar destfile="build/jar/HelloWorld.jar" basedir="build/classes">
            <manifest>
                <attribute name="Main-Class" value="com.example.DemoApplication"/>
            </manifest>
        </jar>
    </target>

    <target name="run" depends="jar">
        <java jar="build/jar/HelloWorld.jar" fork="true" />
    </target>

    <target name="all" depends="clean,resolve, compile, jar, run"/>

    <target name="resolve">
        <ivy:retrieve />
    </target>

</project>

How could this problem be solved?


问:
Loss of a windows cluster node - rebuild
We've had a Windows cluster node bite the dust and evicted it from the cluster, so we now have a single node running with a cloud witness configured.

We need to deploy a new machine to replace the failed node and bring it into the cluster. Should I deploy a new machine with the same name and IP of the failed node so it uses the original computer object (retains security settings) or doesn't it make any difference?


问:
Flutter / Dart - If 2 text input boxes had numbers in them, they would calculate a result. But now they don't
Flutter / Dart - I'm new to coding so may be asking a simple question, but when 2 text input boxes had numbers entered into them, they would calculate a result. But when I transpose results into the same 2 boxes they don't calculate anymore. Is this related to them somehow no longer being strings and if so where and how do I fix that please? Thanks

```<code>import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    const appTitle = 'Diabetic insulin dosage';
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: appTitle,
      home: Scaffold(
        appBar: AppBar(
          title: const Text(appTitle),
          backgroundColor: Colors.green,
          foregroundColor: Colors.black,
        ),
        body: const AddTwoNumbers(),
        backgroundColor: Colors.white,
      ),
    );
  }
}

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

  @override
  // ignore: library_private_types_in_public_api
  _AddTwoNumbersState createState() => _AddTwoNumbersState();
}

class _AddTwoNumbersState extends State<AddTwoNumbers> {
  Color _fillColor = Colors.white;

  TextEditingController numR1C1controller =
      TextEditingController(); //Changed name of the texteditingcontroller as Row as R and Column as C
  TextEditingController numR1C2controller = TextEditingController();
  TextEditingController numR1C3controller = TextEditingController();
  TextEditingController numR2C1controller = TextEditingController();
  TextEditingController numR2C2controller = TextEditingController();
  TextEditingController numR2C3controller = TextEditingController();
  TextEditingController numR3C1controller = TextEditingController();
  TextEditingController numR3C2controller = TextEditingController();
  TextEditingController numR3C3controller = TextEditingController();
  TextEditingController numR4C1controller = TextEditingController();
  TextEditingController numR4C2controller = TextEditingController();
  TextEditingController numR4C3controller = TextEditingController();

  String result = "0";
  String result2 = "0";
  String result3 = "0";
  String result4 = "0";

  // MAKE LIST OF MAP TO KEEP TRACK OF EACH BUTTONS
  List<Map> buttons = [
    {"name": "BreakFast", "active": false, "value": 1.0},
    {"name": "Lunch", "active": false, "value": 0.6},
    {"name": "Tea", "active": false, "value": 0.55},
  ];

  // YOU CAN SET VARIABLE TO CURRENT MEAL NAME AND CAN CHECK WHETHER IT'S (breakFast) OR NOT
  String? currentMealType;

  // TOGGLE BUTTON FUNCTION
  toggleButtons(Map obj) {
    for (var i in buttons) {
      if (i['name'] == obj['name']) {
        i['active'] = !i['active'];
        numR3C2controller.text = obj['value'].toString();
        _calculateR3();
      } else {
        i['active'] = false;
      }
    }

    setState(() {});
  }

  _calculateR1() {
    if (numR1C1controller.text.isNotEmpty &&
        numR1C2controller.text.isNotEmpty) {
      double sum = double.parse(numR1C1controller.text) -
          double.parse(numR1C2controller.text);
      numR2C2controller.text = numR1C2controller.text; // <--- add this
      numR3C1controller.text = numR1C1controller.text; // <--- add this
      // numR1C3controller.text = sum.toStringAsFixed(1);
      result = sum.toStringAsFixed(1);
    }

    if (numR1C2controller.text.isNotEmpty) {
      setState(() {
        _fillColor = double.parse(numR1C2controller.text) < 5
            ? Colors.red
            : double.parse(numR1C2controller.text) > 9.1
                ? Colors.orange
                : Colors.green;
      });
    } else {
      setState(() {
        _fillColor = Colors.white;
      });
    }
  }

  _calculateR2() {
    if (numR2C1controller.text.isNotEmpty &&
        numR2C2controller.text.isNotEmpty) {
      setState(() {
        double sum = double.parse(numR2C2controller.text) -
            double.parse(numR2C1controller.text);
        numR2C3controller.text = sum.toStringAsFixed(1);
        result2 = sum.toStringAsFixed(1);
      });
    }
  }

  _calculateR3() {
    if (numR3C1controller.text.isNotEmpty &&
        numR3C2controller.text.isNotEmpty) {
      setState(() {
        double sum = double.parse(numR3C1controller.text) *
            double.parse(numR3C2controller.text);
        numR3C3controller.text = sum.toStringAsFixed(1);
        result3 = sum.toStringAsFixed(1);
      });
    }
  }

  _calculateR4() {
    if (numR4C1controller.text.isNotEmpty &&
        numR4C2controller.text.isNotEmpty) {
      setState(() {
        double sum = double.parse(numR4C1controller.text) /
            double.parse(numR4C2controller.text);
        numR4C3controller.text = sum.toStringAsFixed(1);
        result4 = sum.toStringAsFixed(1);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(10.0),
      child: Column(
        children: [
          const Padding(
            padding: EdgeInsets.all(6.0),
            child: Text('Please pick a meal'),
          ),

          // HERE IS THE VIEW FOR BUTTONS
          //******************************

          Row(
            children: buttons
                .map(
                  (btn) => Expanded(
                    child: GestureDetector(
                      onTap: () => toggleButtons(btn),
                      child: Container(
                        padding: const EdgeInsets.all(20.0),
                        margin: const EdgeInsets.only(bottom: 10, right: 10),
                        decoration: BoxDecoration(
                            color: btn['active'] ? Colors.red : Colors.white,
                            border: Border.all(color: Colors.grey[300]!)),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Text(btn['name'],
                                style: TextStyle(
                                    color: btn['active']
                                        ? Colors.white
                                        : Colors.black)),
                            Text(btn['value'].toString(),
                                style: TextStyle(
                                    color: btn['active']
                                        ? Colors.white
                                        : Colors.black))
                          ],
                        ),
                      ),
                    ),
                  ),
                )
                .toList(),
          ),
          const Padding(
            padding: EdgeInsets.all(6.0),
            child: Text('Input Data'),
          ),

          //******************************

          Row(
            children: <Widget>[
              Expanded(
                child: TextField(
                  textAlign: TextAlign.center,
                  style: const TextStyle(fontSize: 14.0),
                  controller: numR1C1controller,
                  onChanged: (value) => _calculateR1(),
                  keyboardType:
                      const TextInputType.numberWithOptions(decimal: true),
                  inputFormatters: <TextInputFormatter>[
                    FilteringTextInputFormatter.allow(
                        RegExp(r'^(\d+)?\.?\d{0,1}'))
                  ],
                  decoration: InputDecoration(
                      border: const OutlineInputBorder(),
                      labelText: 'Carbs in Meal',
                      isDense: true,
                      hintText: 'Enter First Number',
                      fillColor: _fillColor,
                      filled: false),
                ),
              ),
              const SizedBox(
                width: 8,
              ),
              Expanded(
                child: TextField(
                  textAlign: TextAlign.center,
                  style: const TextStyle(fontSize: 14.0),
                  onChanged: (value) => _calculateR1(),
                  keyboardType:
                      const TextInputType.numberWithOptions(decimal: true),
                  controller: numR1C2controller,
                  inputFormatters: <TextInputFormatter>[
                    FilteringTextInputFormatter.allow(
                        RegExp(r'^(\d+)?\.?\d{0,1}'))
                  ],
                  decoration: InputDecoration(
                      border: const OutlineInputBorder(),
                      filled: true,
                      labelText: 'Current B/G Level',
                      isDense: true,
                      hintText: 'Enter Second Number',
                      fillColor: _fillColor),
                ),
              ),
              const SizedBox(
                width: 8,
              ),
              Expanded(
                child: TextField(
                  textAlign: TextAlign.center,
                  style: const TextStyle(fontSize: 14.0),
                  onChanged: (value) => _calculateR1(),
                  keyboardType:
                      const TextInputType.numberWithOptions(decimal: true),
                  controller: numR1C3controller,
                  inputFormatters: <TextInputFormatter>[
                    FilteringTextInputFormatter.allow(
                        RegExp(r'^(\d+)?\.?\d{0,2}'))
                  ],
                  decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: 'Excercise Factor',
                    isDense: true,
                    hintText: '',
                  ),
                ),
              ),
              const SizedBox(
                width: 8,
              ),
            ],
          ),
          const SizedBox(
            height: 8,
          ),
          const Padding(
            padding: EdgeInsets.all(6.0),
            child: Text('Calculations'),
          ),
          Row(
            children: [
              Expanded(
                child: TextField(
                  textAlign: TextAlign.center,
                  style: const TextStyle(fontSize: 20.0, height: 1.0),
                  onChanged: (value) => _calculateR2(),
                  keyboardType:
                      const TextInputType.numberWithOptions(decimal: true),
                  controller: numR2C1controller,
                  inputFormatters: <TextInputFormatter>[
                    FilteringTextInputFormatter.allow(
                        RegExp(r'^(\d+)?\.?\d{0,2}'))
                  ],
                  decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: 'Target Level',
                    isDense: true,
                    hintText: 'Enter Third Number',
                  ),
                ),
              ),
              const SizedBox(
                width: 8,
              ),
              Expanded(
                child: TextField(
                  textAlign: TextAlign.center,
                  style: const TextStyle(fontSize: 20.0),
                  onChanged: (value) => _calculateR2(),
                  keyboardType:
                      const TextInputType.numberWithOptions(decimal: true),
                  controller: numR2C2controller,
                  inputFormatters: <TextInputFormatter>[
                    FilteringTextInputFormatter.allow(
                        RegExp(r'^(\d+)?\.?\d{0,2}'))
                  ],
                  decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: 'Current Level',
                    isDense: true,
                    hintText: 'Enter Fourth Number',
                  ),
                ),
              ),
              const SizedBox(
                width: 8,
              ),
              Expanded(
                child: TextField(
                  textAlign: TextAlign.center,
                  style: const TextStyle(fontSize: 20.0),
                  onChanged: (value) => _calculateR3(),
                  keyboardType:
                      const TextInputType.numberWithOptions(decimal: true),
                  controller: numR2C3controller,
                  inputFormatters: <TextInputFormatter>[
                    FilteringTextInputFormatter.digitsOnly
                  ],
                  decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: 'Result 2',
                    isDense: true,
                    hintText: '',
                  ),
                ),
              ),
              const SizedBox(
                width: 8,
              ),
            ],
          ),
          const SizedBox(
            height: 8,
          ),
          Row(
            children: [
              Expanded(
                child: TextField(
                  textAlign: TextAlign.center,
                  style: const TextStyle(fontSize: 20.0),
                  onChanged: (value) => _calculateR3(),
                  keyboardType:
                      const TextInputType.numberWithOptions(decimal: true),
                  controller: numR3C1controller,
                  inputFormatters: <TextInputFormatter>[
                    FilteringTextInputFormatter.allow(
                        RegExp(r'^(\d+)?\.?\d{0,2}'))
                  ],
                  decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: 'Meal Carbs',
                    // isDense: true,
                    hintText: 'Enter Fifth Number',
                  ),
                ),
              ),
              const SizedBox(
                width: 8,
              ),
              Expanded(
                child: TextField(
                  textAlign: TextAlign.center,
                  style: const TextStyle(fontSize: 20.0),
                  onChanged: (value) => _calculateR3(),
                  keyboardType:
                      const TextInputType.numberWithOptions(decimal: true),
                  controller: numR3C2controller,
                  inputFormatters: <TextInputFormatter>[
                    FilteringTextInputFormatter.allow(
                        RegExp(r'^(\d+)?\.?\d{0,2}'))
                  ],
                  decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: 'Meal Ratio',
                    // isDense: true,
                    hintText: 'Enter Sixth Number',
                  ),
                ),
              ),
              const SizedBox(
                width: 8,
              ),
              Expanded(
                child: TextField(
                  textAlign: TextAlign.center,
                  style: const TextStyle(fontSize: 20.0),
                  onChanged: (value) => _calculateR3(),
                  keyboardType:
                      const TextInputType.numberWithOptions(decimal: true),
                  controller: numR3C3controller,
                  inputFormatters: <TextInputFormatter>[
                    FilteringTextInputFormatter.allow(
                        RegExp(r'^(\d+)?\.?\d{0,2}'))
                  ],
                  decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: 'Result 3',
                    // isDense: true,
                    hintText: '',
                  ),
                ),
              ),
              const SizedBox(
                width: 8,
              ),
            ],
          ),
          const SizedBox(
            height: 8,
          ),
          Row(
            children: [
              Expanded(
                child: TextField(
                  textAlign: TextAlign.center,
                  style: const TextStyle(fontSize: 20.0),
                  onChanged: (value) => _calculateR3(),
                  keyboardType:
                      const TextInputType.numberWithOptions(decimal: true),
                  controller: numR4C1controller,
                  inputFormatters: <TextInputFormatter>[
                    FilteringTextInputFormatter.allow(
                        RegExp(r'^(\d+)?\.?\d{0,2}'))
                  ],
                  decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: 'Next One',
                    // isDense: true,
                    hintText: 'Enter Seventh Number',
                  ),
                  readOnly: true, //<-- add this
                ),
              ),
              const SizedBox(
                width: 8,
              ),
              Expanded(
                child: TextField(
                  textAlign: TextAlign.center,
                  style: const TextStyle(fontSize: 20.0),
                  onChanged: (value) => _calculateR4(),
                  keyboardType:
                      const TextInputType.numberWithOptions(decimal: true),
                  controller: numR4C2controller,
                  inputFormatters: <TextInputFormatter>[
                    FilteringTextInputFormatter.allow(
                        RegExp(r'^(\d+)?\.?\d{0,2}'))
                  ],
                  decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: 'Next Two',
                    // isDense: true,
                    hintText: 'Enter Eighth Number',
                  ),
                ),
              ),
              const SizedBox(
                width: 8,
              ),
              Expanded(
                child: TextField(
                  textAlign: TextAlign.center,
                  style: const TextStyle(fontSize: 20.0),
                  onChanged: (value) => _calculateR4(),
                  keyboardType:
                      const TextInputType.numberWithOptions(decimal: true),
                  controller: numR4C3controller,
                  inputFormatters: <TextInputFormatter>[
                    FilteringTextInputFormatter.digitsOnly
                  ],
                  decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: 'Result 4',
                    // isDense: true,
                    hintText: '',
                  ),
                ),
              ),
              const SizedBox(
                width: 8,
              ),
            ],
          ),
        ],
      ),
    );
  }
}

</code>```

Body:
Flutter / Dart - I'm new to coding so may be asking a simple question, but when 2 text input boxes had numbers entered into them, they would calculate a result. But when I transpose results into the same 2 boxes they don't calculate anymore. Is this related to them somehow no longer being strings and if so where and how do I fix that please? Thanks

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    const appTitle = 'Diabetic insulin dosage';
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: appTitle,
      home: Scaffold(
        appBar: AppBar(
          title: const Text(appTitle),
          backgroundColor: Colors.green,
          foregroundColor: Colors.black,
        ),
        body: const AddTwoNumbers(),
        backgroundColor: Colors.white,
      ),
    );
  }
}

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

  @override
  // ignore: library_private_types_in_public_api
  _AddTwoNumbersState createState() => _AddTwoNumbersState();
}

class _AddTwoNumbersState extends State<AddTwoNumbers> {
  Color _fillColor = Colors.white;

  TextEditingController numR1C1controller =
      TextEditingController(); //Changed name of the texteditingcontroller as Row as R and Column as C
  TextEditingController numR1C2controller = TextEditingController();
  TextEditingController numR1C3controller = TextEditingController();
  TextEditingController numR2C1controller = TextEditingController();
  TextEditingController numR2C2controller = TextEditingController();
  TextEditingController numR2C3controller = TextEditingController();
  TextEditingController numR3C1controller = TextEditingController();
  TextEditingController numR3C2controller = TextEditingController();
  TextEditingController numR3C3controller = TextEditingController();
  TextEditingController numR4C1controller = TextEditingController();
  TextEditingController numR4C2controller = TextEditingController();
  TextEditingController numR4C3controller = TextEditingController();

  String result = "0";
  String result2 = "0";
  String result3 = "0";
  String result4 = "0";

  // MAKE LIST OF MAP TO KEEP TRACK OF EACH BUTTONS
  List<Map> buttons = [
    {"name": "BreakFast", "active": false, "value": 1.0},
    {"name": "Lunch", "active": false, "value": 0.6},
    {"name": "Tea", "active": false, "value": 0.55},
  ];

  // YOU CAN SET VARIABLE TO CURRENT MEAL NAME AND CAN CHECK WHETHER IT'S (breakFast) OR NOT
  String? currentMealType;

  // TOGGLE BUTTON FUNCTION
  toggleButtons(Map obj) {
    for (var i in buttons) {
      if (i['name'] == obj['name']) {
        i['active'] = !i['active'];
        numR3C2controller.text = obj['value'].toString();
        _calculateR3();
      } else {
        i['active'] = false;
      }
    }

    setState(() {});
  }

  _calculateR1() {
    if (numR1C1controller.text.isNotEmpty &&
        numR1C2controller.text.isNotEmpty) {
      double sum = double.parse(numR1C1controller.text) -
          double.parse(numR1C2controller.text);
      numR2C2controller.text = numR1C2controller.text; // <--- add this
      numR3C1controller.text = numR1C1controller.text; // <--- add this
      // numR1C3controller.text = sum.toStringAsFixed(1);
      result = sum.toStringAsFixed(1);
    }

    if (numR1C2controller.text.isNotEmpty) {
      setState(() {
        _fillColor = double.parse(numR1C2controller.text) < 5
            ? Colors.red
            : double.parse(numR1C2controller.text) > 9.1
                ? Colors.orange
                : Colors.green;
      });
    } else {
      setState(() {
        _fillColor = Colors.white;
      });
    }
  }

  _calculateR2() {
    if (numR2C1controller.text.isNotEmpty &&
        numR2C2controller.text.isNotEmpty) {
      setState(() {
        double sum = double.parse(numR2C2controller.text) -
            double.parse(numR2C1controller.text);
        numR2C3controller.text = sum.toStringAsFixed(1);
        result2 = sum.toStringAsFixed(1);
      });
    }
  }

  _calculateR3() {
    if (numR3C1controller.text.isNotEmpty &&
        numR3C2controller.text.isNotEmpty) {
      setState(() {
        double sum = double.parse(numR3C1controller.text) *
            double.parse(numR3C2controller.text);
        numR3C3controller.text = sum.toStringAsFixed(1);
        result3 = sum.toStringAsFixed(1);
      });
    }
  }

  _calculateR4() {
    if (numR4C1controller.text.isNotEmpty &&
        numR4C2controller.text.isNotEmpty) {
      setState(() {
        double sum = double.parse(numR4C1controller.text) /
            double.parse(numR4C2controller.text);
        numR4C3controller.text = sum.toStringAsFixed(1);
        result4 = sum.toStringAsFixed(1);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(10.0),
      child: Column(
        children: [
          const Padding(
            padding: EdgeInsets.all(6.0),
            child: Text('Please pick a meal'),
          ),

          // HERE IS THE VIEW FOR BUTTONS
          //******************************

          Row(
            children: buttons
                .map(
                  (btn) => Expanded(
                    child: GestureDetector(
                      onTap: () => toggleButtons(btn),
                      child: Container(
                        padding: const EdgeInsets.all(20.0),
                        margin: const EdgeInsets.only(bottom: 10, right: 10),
                        decoration: BoxDecoration(
                            color: btn['active'] ? Colors.red : Colors.white,
                            border: Border.all(color: Colors.grey[300]!)),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Text(btn['name'],
                                style: TextStyle(
                                    color: btn['active']
                                        ? Colors.white
                                        : Colors.black)),
                            Text(btn['value'].toString(),
                                style: TextStyle(
                                    color: btn['active']
                                        ? Colors.white
                                        : Colors.black))
                          ],
                        ),
                      ),
                    ),
                  ),
                )
                .toList(),
          ),
          const Padding(
            padding: EdgeInsets.all(6.0),
            child: Text('Input Data'),
          ),

          //******************************

          Row(
            children: <Widget>[
              Expanded(
                child: TextField(
                  textAlign: TextAlign.center,
                  style: const TextStyle(fontSize: 14.0),
                  controller: numR1C1controller,
                  onChanged: (value) => _calculateR1(),
                  keyboardType:
                      const TextInputType.numberWithOptions(decimal: true),
                  inputFormatters: <TextInputFormatter>[
                    FilteringTextInputFormatter.allow(
                        RegExp(r'^(\d+)?\.?\d{0,1}'))
                  ],
                  decoration: InputDecoration(
                      border: const OutlineInputBorder(),
                      labelText: 'Carbs in Meal',
                      isDense: true,
                      hintText: 'Enter First Number',
                      fillColor: _fillColor,
                      filled: false),
                ),
              ),
              const SizedBox(
                width: 8,
              ),
              Expanded(
                child: TextField(
                  textAlign: TextAlign.center,
                  style: const TextStyle(fontSize: 14.0),
                  onChanged: (value) => _calculateR1(),
                  keyboardType:
                      const TextInputType.numberWithOptions(decimal: true),
                  controller: numR1C2controller,
                  inputFormatters: <TextInputFormatter>[
                    FilteringTextInputFormatter.allow(
                        RegExp(r'^(\d+)?\.?\d{0,1}'))
                  ],
                  decoration: InputDecoration(
                      border: const OutlineInputBorder(),
                      filled: true,
                      labelText: 'Current B/G Level',
                      isDense: true,
                      hintText: 'Enter Second Number',
                      fillColor: _fillColor),
                ),
              ),
              const SizedBox(
                width: 8,
              ),
              Expanded(
                child: TextField(
                  textAlign: TextAlign.center,
                  style: const TextStyle(fontSize: 14.0),
                  onChanged: (value) => _calculateR1(),
                  keyboardType:
                      const TextInputType.numberWithOptions(decimal: true),
                  controller: numR1C3controller,
                  inputFormatters: <TextInputFormatter>[
                    FilteringTextInputFormatter.allow(
                        RegExp(r'^(\d+)?\.?\d{0,2}'))
                  ],
                  decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: 'Excercise Factor',
                    isDense: true,
                    hintText: '',
                  ),
                ),
              ),
              const SizedBox(
                width: 8,
              ),
            ],
          ),
          const SizedBox(
            height: 8,
          ),
          const Padding(
            padding: EdgeInsets.all(6.0),
            child: Text('Calculations'),
          ),
          Row(
            children: [
              Expanded(
                child: TextField(
                  textAlign: TextAlign.center,
                  style: const TextStyle(fontSize: 20.0, height: 1.0),
                  onChanged: (value) => _calculateR2(),
                  keyboardType:
                      const TextInputType.numberWithOptions(decimal: true),
                  controller: numR2C1controller,
                  inputFormatters: <TextInputFormatter>[
                    FilteringTextInputFormatter.allow(
                        RegExp(r'^(\d+)?\.?\d{0,2}'))
                  ],
                  decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: 'Target Level',
                    isDense: true,
                    hintText: 'Enter Third Number',
                  ),
                ),
              ),
              const SizedBox(
                width: 8,
              ),
              Expanded(
                child: TextField(
                  textAlign: TextAlign.center,
                  style: const TextStyle(fontSize: 20.0),
                  onChanged: (value) => _calculateR2(),
                  keyboardType:
                      const TextInputType.numberWithOptions(decimal: true),
                  controller: numR2C2controller,
                  inputFormatters: <TextInputFormatter>[
                    FilteringTextInputFormatter.allow(
                        RegExp(r'^(\d+)?\.?\d{0,2}'))
                  ],
                  decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: 'Current Level',
                    isDense: true,
                    hintText: 'Enter Fourth Number',
                  ),
                ),
              ),
              const SizedBox(
                width: 8,
              ),
              Expanded(
                child: TextField(
                  textAlign: TextAlign.center,
                  style: const TextStyle(fontSize: 20.0),
                  onChanged: (value) => _calculateR3(),
                  keyboardType:
                      const TextInputType.numberWithOptions(decimal: true),
                  controller: numR2C3controller,
                  inputFormatters: <TextInputFormatter>[
                    FilteringTextInputFormatter.digitsOnly
                  ],
                  decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: 'Result 2',
                    isDense: true,
                    hintText: '',
                  ),
                ),
              ),
              const SizedBox(
                width: 8,
              ),
            ],
          ),
          const SizedBox(
            height: 8,
          ),
          Row(
            children: [
              Expanded(
                child: TextField(
                  textAlign: TextAlign.center,
                  style: const TextStyle(fontSize: 20.0),
                  onChanged: (value) => _calculateR3(),
                  keyboardType:
                      const TextInputType.numberWithOptions(decimal: true),
                  controller: numR3C1controller,
                  inputFormatters: <TextInputFormatter>[
                    FilteringTextInputFormatter.allow(
                        RegExp(r'^(\d+)?\.?\d{0,2}'))
                  ],
                  decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: 'Meal Carbs',
                    // isDense: true,
                    hintText: 'Enter Fifth Number',
                  ),
                ),
              ),
              const SizedBox(
                width: 8,
              ),
              Expanded(
                child: TextField(
                  textAlign: TextAlign.center,
                  style: const TextStyle(fontSize: 20.0),
                  onChanged: (value) => _calculateR3(),
                  keyboardType:
                      const TextInputType.numberWithOptions(decimal: true),
                  controller: numR3C2controller,
                  inputFormatters: <TextInputFormatter>[
                    FilteringTextInputFormatter.allow(
                        RegExp(r'^(\d+)?\.?\d{0,2}'))
                  ],
                  decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: 'Meal Ratio',
                    // isDense: true,
                    hintText: 'Enter Sixth Number',
                  ),
                ),
              ),
              const SizedBox(
                width: 8,
              ),
              Expanded(
                child: TextField(
                  textAlign: TextAlign.center,
                  style: const TextStyle(fontSize: 20.0),
                  onChanged: (value) => _calculateR3(),
                  keyboardType:
                      const TextInputType.numberWithOptions(decimal: true),
                  controller: numR3C3controller,
                  inputFormatters: <TextInputFormatter>[
                    FilteringTextInputFormatter.allow(
                        RegExp(r'^(\d+)?\.?\d{0,2}'))
                  ],
                  decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: 'Result 3',
                    // isDense: true,
                    hintText: '',
                  ),
                ),
              ),
              const SizedBox(
                width: 8,
              ),
            ],
          ),
          const SizedBox(
            height: 8,
          ),
          Row(
            children: [
              Expanded(
                child: TextField(
                  textAlign: TextAlign.center,
                  style: const TextStyle(fontSize: 20.0),
                  onChanged: (value) => _calculateR3(),
                  keyboardType:
                      const TextInputType.numberWithOptions(decimal: true),
                  controller: numR4C1controller,
                  inputFormatters: <TextInputFormatter>[
                    FilteringTextInputFormatter.allow(
                        RegExp(r'^(\d+)?\.?\d{0,2}'))
                  ],
                  decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: 'Next One',
                    // isDense: true,
                    hintText: 'Enter Seventh Number',
                  ),
                  readOnly: true, //<-- add this
                ),
              ),
              const SizedBox(
                width: 8,
              ),
              Expanded(
                child: TextField(
                  textAlign: TextAlign.center,
                  style: const TextStyle(fontSize: 20.0),
                  onChanged: (value) => _calculateR4(),
                  keyboardType:
                      const TextInputType.numberWithOptions(decimal: true),
                  controller: numR4C2controller,
                  inputFormatters: <TextInputFormatter>[
                    FilteringTextInputFormatter.allow(
                        RegExp(r'^(\d+)?\.?\d{0,2}'))
                  ],
                  decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: 'Next Two',
                    // isDense: true,
                    hintText: 'Enter Eighth Number',
                  ),
                ),
              ),
              const SizedBox(
                width: 8,
              ),
              Expanded(
                child: TextField(
                  textAlign: TextAlign.center,
                  style: const TextStyle(fontSize: 20.0),
                  onChanged: (value) => _calculateR4(),
                  keyboardType:
                      const TextInputType.numberWithOptions(decimal: true),
                  controller: numR4C3controller,
                  inputFormatters: <TextInputFormatter>[
                    FilteringTextInputFormatter.digitsOnly
                  ],
                  decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: 'Result 4',
                    // isDense: true,
                    hintText: '',
                  ),
                ),
              ),
              const SizedBox(
                width: 8,
              ),
            ],
          ),
        ],
      ),
    );
  }
}


问:
can anyone explain to me why is this assembly code not working?
so we have a microcontroller with a keyboard and a screen and LED'S

var nokey define that no key was pressed, ppi_pa3 is a speaker, keybd is the keyboard
when i press any key the micro controller notice it and actually display that on the leds (executed in line 71)
then if the key is pressed status get the value 1 and the isr_freqtimer should be executed but it is not working can anyone please help

```<code>

        org 100h
        cpu 8086

        jmp start

; Variablen

status  db 00000000b    ; Statusbyte
;                 ^
;                 |
;                 +-----> Ton (1, an) / (0, aus)

; Konstanten
intab0      equ 20h     ; Adresse Interrupttabelle PIT, Kanal 1
intab1      equ intab0 + 1 * 4  ; Adresse Interrupttabelle PIT, Kanal 2
intab7      equ intab0 + 7 * 4  ; Adresse Interrupttabelle Lichttaster
eoi         equ 20h     ; End Of Interrupt (EOI)
clrscr      equ 0       ; Clear Screen
getkey      equ 1       ; Funktion auf Tastatureingabe warten
ascii       equ 2       ; Funktion ASCII-Zeichenausgabe
hexbyte     equ 4       ; HEX-Byte Ausgabe
conin       equ 5       ; Console IN
conout      equ 6       ; Console OUT
pitc        equ 0a6h    ; Steuerkanal PIT
pit1        equ 0a2h    ; Counter 1 PIT
pit2        equ 0a4h    ; Counter 2 PIT
ppi_ctl     equ 0b6h    ; Steuerkanal PPI (Parallelinterface)
ppi_a       equ 0b0h    ; Kanal A PPI
ppi_pa0     equ 1       ; LED 0
ppi_pa1     equ 2       ; LED 1
ppi_pa2     equ 4       ; LED 2
ppi_pa3     equ 8       ; Lautsprecher
ppi_pa6     equ 1 << 6  ; Servomotor
ppi_b       equ 0b2h    ; Kanal B PPI
ppi_c       equ 0b4h    ; Kanal C PPI
ocw_2_3     equ 0c0h    ; PIC (Interruptcontroller), OCW2,3
ocw_1       equ 0c2h    ; PIC (Interruptcontroller), OCW1
icw_1       equ 0c0h    ; PIC (Interruptcontroller), ICW1
icw_2_4     equ 0c2h    ; PIC (Interruptcontroller), ICW2,4
leds        equ 0       ; LED Port
schalter    equ 0       ; Schalterport
keybd       equ 80h     ; SBC-86 Tastatur
gokey       equ 11h     ; Taste "GO"
outkey      equ 15h     ; Taste "OUT"
sseg7       equ 9eh     ; Segmentanzeige 7
tcfreq      equ 440     ; initiale Frequenz
basefreq    equ 1843200 ; Basistakt in Hz
nokey       equ 7       ; keine Taste gedrueckt

start:

; Initialisierung

    mov ah, clrscr      ; Anzeige aus
    int conout

    mov byte [status], 0    ; Init. Statusbyte und alle LEDs
    mov al, 0
    out ppi_a, al
    out leds, al

    call init,          ; Controller und Interruptsystem scharfmachen

; Hintergrundprogramm (ist immer aktiv, wenn im Service nichts zu tun ist)
; Hier sollten Ausgaben auf das Display getätigt werden, Tastatureingaben, etc.

again:

; Code des Hintergrundprogammes
    in al,keybd
    out 0,al
    mov ah,al
    and ah, nokey
    cmp ah,7
    je silence
    or byte[status],1
    jmp again

silence:
    and byte[status], ~1
    jmp again

; Initialisierung Controller und Interruptsystem

init:
    cli         ; Interrupts aus

; PIT-Init.

;   Nichts zu tun, das macht die Main-Loop :-)
;   mov al, 01110110b   ; Kanal 1, Mode 3, 16-Bit ZK
;   out pitc, al        ; Steuerkanal
;   mov al, tcfreq & 0ffh   ; Low-Teil Zeitkonstante
;   out pit1, al
;   mov al, tcfreq >> 8 ; High-Teil Zeitkonstante
;   out pit1, al

; PPI-Init.
    mov al, 10001011b   ; PPI A/B/C Mode 0, A Output, sonst Input
    out ppi_ctl, al
    jmp short $+2       ; I/O-Delay
    mov al, 0           ; LED's aus (high aktiv)
    out ppi_a, al

; PIC-Init.
    mov al, 00010011b   ; ICW1, ICW4 benoetigt, Bit 2 egal,
                        ; Flankentriggerung
    out icw_1, al
    jmp short $+2       ; I/O-Delay
    mov al, 00001000b   ; ICW2, auf INT 8 gemapped
    out icw_2_4, al
    jmp short $+2       ; I/O-Delay
    mov al, 00010001b   ; ICW4, MCS-86, EOI, non-buffered,
                ; fully nested
    out icw_2_4, al
    jmp short $+2       ; I/O-Delay
    mov al, 11111110b   ; Kanal 0, 1 + 7 am PIC demaskieren
                        ; PIT K1
    out ocw_1, al

; Interrupttabelle init.

    mov word [intab0], isr_freqtimer    ; Interrupttabelle (Timer K1)
                        ; initialisieren (Offset)
    mov [intab0 + 2], cs        ; (Segmentadresse)

    sti                 ; ab jetzt Interrupts
    ret

;------------------------ Serviceroutine -----------------------------------

isr_freqtimer:              ; Timer fuer Lautsprecher
    push ax
    test byte[status],1
    jz isr_freqtimer_out
    in al, ppi_a
    xor al, ppi_pa3
    out ppi_a,al

; Code der Serviceroutine fuer die Lautsprecherausgabe

isr_freqtimer_out:      ; Ausgang aus dem Service
    mov al, eoi         ; EOI an PIC
    out ocw_2_3, al
    pop ax
    iret

;Frequenzen in zwei Oktaven von c4 bis b5 in Hertz (Hz)

tonleiter:
    dw 262 ; c4   0
    dw 277 ; c#4  1
    dw 294 ; d4   2
    dw 311 ; d#4  3
    dw 329 ; e4   4
    dw 349 ; f4   5
    dw 370 ; f#4  6
    dw 392 ; g4   7
    dw 415 ; g#4  8
    dw 440 ; a4   9
    dw 466 ; a#4  10
    dw 493 ; b4   11
    dw 523 ; c5   12
    dw 554 ; c#5  13
    dw 587 ; d5   14
    dw 622 ; d#5  15
    dw 659 ; e5   16
    dw 698 ; f5   17
    dw 740 ; f#5  18
    dw 784 ; g5   19
    dw 830 ; g#5  20
    dw 880 ; a5   21
    dw 932 ; a#5  22
    dw 987 ; b5   23

</code>```

Body:
so we have a microcontroller with a keyboard and a screen and LED'S

var nokey define that no key was pressed, ppi_pa3 is a speaker, keybd is the keyboard
when i press any key the micro controller notice it and actually display that on the leds (executed in line 71)
then if the key is pressed status get the value 1 and the isr_freqtimer should be executed but it is not working can anyone please help

        org 100h
        cpu 8086

        jmp start

; Variablen

status  db 00000000b    ; Statusbyte
;                 ^
;                 |
;                 +-----> Ton (1, an) / (0, aus)

; Konstanten
intab0      equ 20h     ; Adresse Interrupttabelle PIT, Kanal 1
intab1      equ intab0 + 1 * 4  ; Adresse Interrupttabelle PIT, Kanal 2
intab7      equ intab0 + 7 * 4  ; Adresse Interrupttabelle Lichttaster
eoi         equ 20h     ; End Of Interrupt (EOI)
clrscr      equ 0       ; Clear Screen
getkey      equ 1       ; Funktion auf Tastatureingabe warten
ascii       equ 2       ; Funktion ASCII-Zeichenausgabe
hexbyte     equ 4       ; HEX-Byte Ausgabe
conin       equ 5       ; Console IN
conout      equ 6       ; Console OUT
pitc        equ 0a6h    ; Steuerkanal PIT
pit1        equ 0a2h    ; Counter 1 PIT
pit2        equ 0a4h    ; Counter 2 PIT
ppi_ctl     equ 0b6h    ; Steuerkanal PPI (Parallelinterface)
ppi_a       equ 0b0h    ; Kanal A PPI
ppi_pa0     equ 1       ; LED 0
ppi_pa1     equ 2       ; LED 1
ppi_pa2     equ 4       ; LED 2
ppi_pa3     equ 8       ; Lautsprecher
ppi_pa6     equ 1 << 6  ; Servomotor
ppi_b       equ 0b2h    ; Kanal B PPI
ppi_c       equ 0b4h    ; Kanal C PPI
ocw_2_3     equ 0c0h    ; PIC (Interruptcontroller), OCW2,3
ocw_1       equ 0c2h    ; PIC (Interruptcontroller), OCW1
icw_1       equ 0c0h    ; PIC (Interruptcontroller), ICW1
icw_2_4     equ 0c2h    ; PIC (Interruptcontroller), ICW2,4
leds        equ 0       ; LED Port
schalter    equ 0       ; Schalterport
keybd       equ 80h     ; SBC-86 Tastatur
gokey       equ 11h     ; Taste "GO"
outkey      equ 15h     ; Taste "OUT"
sseg7       equ 9eh     ; Segmentanzeige 7
tcfreq      equ 440     ; initiale Frequenz
basefreq    equ 1843200 ; Basistakt in Hz
nokey       equ 7       ; keine Taste gedrueckt

start:

; Initialisierung

    mov ah, clrscr      ; Anzeige aus
    int conout

    mov byte [status], 0    ; Init. Statusbyte und alle LEDs
    mov al, 0
    out ppi_a, al
    out leds, al

    call init,          ; Controller und Interruptsystem scharfmachen

; Hintergrundprogramm (ist immer aktiv, wenn im Service nichts zu tun ist)
; Hier sollten Ausgaben auf das Display getätigt werden, Tastatureingaben, etc.

again:

; Code des Hintergrundprogammes
    in al,keybd
    out 0,al
    mov ah,al
    and ah, nokey
    cmp ah,7
    je silence
    or byte[status],1
    jmp again

silence:
    and byte[status], ~1
    jmp again

; Initialisierung Controller und Interruptsystem

init:
    cli         ; Interrupts aus

; PIT-Init.

;   Nichts zu tun, das macht die Main-Loop :-)
;   mov al, 01110110b   ; Kanal 1, Mode 3, 16-Bit ZK
;   out pitc, al        ; Steuerkanal
;   mov al, tcfreq & 0ffh   ; Low-Teil Zeitkonstante
;   out pit1, al
;   mov al, tcfreq >> 8 ; High-Teil Zeitkonstante
;   out pit1, al

; PPI-Init.
    mov al, 10001011b   ; PPI A/B/C Mode 0, A Output, sonst Input
    out ppi_ctl, al
    jmp short $+2       ; I/O-Delay
    mov al, 0           ; LED's aus (high aktiv)
    out ppi_a, al

; PIC-Init.
    mov al, 00010011b   ; ICW1, ICW4 benoetigt, Bit 2 egal,
                        ; Flankentriggerung
    out icw_1, al
    jmp short $+2       ; I/O-Delay
    mov al, 00001000b   ; ICW2, auf INT 8 gemapped
    out icw_2_4, al
    jmp short $+2       ; I/O-Delay
    mov al, 00010001b   ; ICW4, MCS-86, EOI, non-buffered,
                ; fully nested
    out icw_2_4, al
    jmp short $+2       ; I/O-Delay
    mov al, 11111110b   ; Kanal 0, 1 + 7 am PIC demaskieren
                        ; PIT K1
    out ocw_1, al

; Interrupttabelle init.

    mov word [intab0], isr_freqtimer    ; Interrupttabelle (Timer K1)
                        ; initialisieren (Offset)
    mov [intab0 + 2], cs        ; (Segmentadresse)

    sti                 ; ab jetzt Interrupts
    ret

;------------------------ Serviceroutine -----------------------------------

isr_freqtimer:              ; Timer fuer Lautsprecher
    push ax
    test byte[status],1
    jz isr_freqtimer_out
    in al, ppi_a
    xor al, ppi_pa3
    out ppi_a,al

; Code der Serviceroutine fuer die Lautsprecherausgabe

isr_freqtimer_out:      ; Ausgang aus dem Service
    mov al, eoi         ; EOI an PIC
    out ocw_2_3, al
    pop ax
    iret

;Frequenzen in zwei Oktaven von c4 bis b5 in Hertz (Hz)

tonleiter:
    dw 262 ; c4   0
    dw 277 ; c#4  1
    dw 294 ; d4   2
    dw 311 ; d#4  3
    dw 329 ; e4   4
    dw 349 ; f4   5
    dw 370 ; f#4  6
    dw 392 ; g4   7
    dw 415 ; g#4  8
    dw 440 ; a4   9
    dw 466 ; a#4  10
    dw 493 ; b4   11
    dw 523 ; c5   12
    dw 554 ; c#5  13
    dw 587 ; d5   14
    dw 622 ; d#5  15
    dw 659 ; e5   16
    dw 698 ; f5   17
    dw 740 ; f#5  18
    dw 784 ; g5   19
    dw 830 ; g#5  20
    dw 880 ; a5   21
    dw 932 ; a#5  22
    dw 987 ; b5   23


问:
Using libusb with a kernel driver
I am trying to control a USB device in the userspace through libusb and power manage the same USB device through a kernel driver (so that I can set autosuspend and the device can suspend when the system suspends).

I added a skeleton empty driver for testing like this:

static int x_probe(struct usb_interface *intf, const struct usb_device_id *id)
{
    return 0;
}

static void x_disconnect(struct usb_interface *intf)
{
}

static int x_suspend(struct usb_interface *intf, pm_message_t message)
{
    return 0;
}

static int x_resume(struct usb_interface *intf)
{
    return 0;
}

static struct usb_driver x_driver = {
    .name = "X",
    .id_table = x_table,
    .probe = x_probe,
    .disconnect = x_disconnect,
    .suspend = x_suspend,
    .resume = x_resume,
    .reset_resume = x_resume,
    .supports_autosuspend = 1,
    .disable_hub_initiated_lpm = 0,
};
```
<p>In the userspace, I wish to claim interface through <code>libusb</code>, so I am trying to detach the kernel driver, like this:</p>
<pre class="lang-c prettyprint-override"><code>if (libusb_kernel_driver_active(dev_handle, interface_number))
{
    libusb_detach_kernel_driver(dev_handle, interface_number);
}
libusb_claim_interface(dev_handle, interface_number);
</code>```

However, it seems that libusb_kernel_driver_active() (or libusb_detach_kernel_driver() if I remove libusb_kernel_driver_active()) runs indefinitely. (not going further without any returned value) Also x_probe() and x_disconnect() are called multiple times indefinitely.

Would there be specific requirements in the driver's ->probe() and/or ->disconnect() callbacks to use with libusb in the userspace? Or requirements in libusb usage to be used with a driver?

Would it be sensible to use libusb and driver together for a single device?

Title: Using libusb with a kernel driver

Body:
I am trying to control a USB device in the userspace through libusb and power manage the same USB device through a kernel driver (so that I can set autosuspend and the device can suspend when the system suspends).

I added a skeleton empty driver for testing like this:

static int x_probe(struct usb_interface *intf, const struct usb_device_id *id)
{
    return 0;
}

static void x_disconnect(struct usb_interface *intf)
{
}

static int x_suspend(struct usb_interface *intf, pm_message_t message)
{
    return 0;
}

static int x_resume(struct usb_interface *intf)
{
    return 0;
}

static struct usb_driver x_driver = {
    .name = "X",
    .id_table = x_table,
    .probe = x_probe,
    .disconnect = x_disconnect,
    .suspend = x_suspend,
    .resume = x_resume,
    .reset_resume = x_resume,
    .supports_autosuspend = 1,
    .disable_hub_initiated_lpm = 0,
};

In the userspace, I wish to claim interface through libusb, so I am trying to detach the kernel driver, like this:

if (libusb_kernel_driver_active(dev_handle, interface_number))
{
    libusb_detach_kernel_driver(dev_handle, interface_number);
}
libusb_claim_interface(dev_handle, interface_number);

However, it seems that libusb_kernel_driver_active() (or libusb_detach_kernel_driver() if I remove libusb_kernel_driver_active()) runs indefinitely. (not going further without any returned value) Also x_probe() and x_disconnect() are called multiple times indefinitely.

Would there be specific requirements in the driver's ->probe() and/or ->disconnect() callbacks to use with libusb in the userspace? Or requirements in libusb usage to be used with a driver?

Would it be sensible to use libusb and driver together for a single device?


问:
Why does VisualStudio Code not find R client
I am having a weird issue.
I am trying to use R in VisualStudio Code on a Manjaro KDE laptop.
When coding i get the error;

"Cannot find R client at /usr/bin/R. Please check r.rterm setting."

I have launched R on its own in the terminal and it is working fine.

The first thing i tried was adding a path to rpath and rterm, but that has not worked so far. I have tried many other possible places for the R file in the settings, but nothing is working. I get the same error every time.
All help is appreciated.


问:
I want to find the length of the LineRenderer and put it in RayCast's factor
```<code>public IEnumerator Attack()
{
    while (true)
    {
        yield return new WaitForSeconds(Random.Range(2f, 5f));
        lr.enabled = true;
        while (true)
        {
            lr.SetPosition(0, transform.position);
            lr.SetPosition(1, GameManager.Instance.Player.transform.position);
            curTime += Time.deltaTime;
            if (curTime >= 1.5f)
            {
                curTime = 0f;
                break;
            }
            yield return null;
        }
        lr.enabled = false;
        Physics.Raycast(transform.position, GameManager.Instance.Player.transform.position, out hit, 500f);
        if (hit.transform.gameObject.CompareTag("Player"))
        {
            Instantiate(bullet, transform);
        }
        else
        {
            continue;
        }
    }
}
</code>```

I'd like to create a function to find the length of the LineRenderer. As you can see from the code, shoot RayCast and instantiate the bullet when the hit object is Player. However, it is not easy to find the exact location because the player position has changed. So I want to get the most similar length of LineRenderer, what should I do?

Before the code was modified, the LineRenderer was not properly drawn, so I tried many things by changing the while statement and changing the Coroutine order. But now I'm drawing a LineRenderer, but I can't execute the if statement, so I found the LineRenderer function, but I couldn't find the result I wanted.

Body:
public IEnumerator Attack()
{
    while (true)
    {
        yield return new WaitForSeconds(Random.Range(2f, 5f));
        lr.enabled = true;
        while (true)
        {
            lr.SetPosition(0, transform.position);
            lr.SetPosition(1, GameManager.Instance.Player.transform.position);
            curTime += Time.deltaTime;
            if (curTime >= 1.5f)
            {
                curTime = 0f;
                break;
            }
            yield return null;
        }
        lr.enabled = false;
        Physics.Raycast(transform.position, GameManager.Instance.Player.transform.position, out hit, 500f);
        if (hit.transform.gameObject.CompareTag("Player"))
        {
            Instantiate(bullet, transform);
        }
        else
        {
            continue;
        }
    }
}

I'd like to create a function to find the length of the LineRenderer. As you can see from the code, shoot RayCast and instantiate the bullet when the hit object is Player. However, it is not easy to find the exact location because the player position has changed. So I want to get the most similar length of LineRenderer, what should I do?

Before the code was modified, the LineRenderer was not properly drawn, so I tried many things by changing the while statement and changing the Coroutine order. But now I'm drawing a LineRenderer, but I can't execute the if statement, so I found the LineRenderer function, but I couldn't find the result I wanted.


问:
Keras Predicted Forecast Data isn't continuous with historical data
I am trying to forecast data into the future however, my forecast seemingly, isn't matching up with my historical data.

```<code>train_dates = pd.to_datetime(df.index)

n_future = 30 #look 30 years into the future
forecast_period_dates = pd.date_range(list(train_dates)[-1], periods=n_future, freq='1y').tolist()
forecast_period_dates

forecast = hpModel.predict(xTrain[-n_future:])

forecast_copies = np.repeat(forecast, xTrain.shape[1], axis=-1) # np gives us an array that we can prepare a diagram
y_pred_future = scaler.inverse_transform(forecast_copies)[:,0] # reverse the scaler number to the original number

forecast_dates = []
for time_i in forecast_period_dates:
    forecast_dates.append(time_i.date())
df_forecast = pd.DataFrame({'Date':np.array(forecast_dates), 'Prediction':y_pred_future})
df_forecast['Date']=pd.to_datetime(df_forecast['Date'])
plt.rcParams['figure.figsize'] = (12,8)

plt.plot(df_forecast['Date'],df_forecast['Prediction'], label = 'Predicted', linewidth = 3, color = 'r')
plt.plot(df['1970':], label = 'Historical Data', linewidth = 3, color='b')

plt.ylabel('GHG Per Capita/Tonne')
plt.xlabel('Year')
plt.legend(loc = 'lower left')
</code>```

As you can see from the graph, the data predicted doesn't even match up with the historical data, and I am unsure as to why.

I thought it may have been due trying to predict off of xTrain, therefore, I tried to predict off xTest but that didn't change anything. The data still didn't match up.

Body:
I am trying to forecast data into the future however, my forecast seemingly, isn't matching up with my historical data.

train_dates = pd.to_datetime(df.index)

n_future = 30 #look 30 years into the future
forecast_period_dates = pd.date_range(list(train_dates)[-1], periods=n_future, freq='1y').tolist()
forecast_period_dates

forecast = hpModel.predict(xTrain[-n_future:])

forecast_copies = np.repeat(forecast, xTrain.shape[1], axis=-1) # np gives us an array that we can prepare a diagram
y_pred_future = scaler.inverse_transform(forecast_copies)[:,0] # reverse the scaler number to the original number

forecast_dates = []
for time_i in forecast_period_dates:
    forecast_dates.append(time_i.date())
df_forecast = pd.DataFrame({'Date':np.array(forecast_dates), 'Prediction':y_pred_future})
df_forecast['Date']=pd.to_datetime(df_forecast['Date'])
plt.rcParams['figure.figsize'] = (12,8)

plt.plot(df_forecast['Date'],df_forecast['Prediction'], label = 'Predicted', linewidth = 3, color = 'r')
plt.plot(df['1970':], label = 'Historical Data', linewidth = 3, color='b')

plt.ylabel('GHG Per Capita/Tonne')
plt.xlabel('Year')
plt.legend(loc = 'lower left')

As you can see from the graph, the data predicted doesn't even match up with the historical data, and I am unsure as to why.

I thought it may have been due trying to predict off of xTrain, therefore, I tried to predict off xTest but that didn't change anything. The data still didn't match up.


问:
How to refresh data in frontend using React Native?
I am using useSWR hook in Next.js and refreshInterval as a parameter to update the data from MongoDB database. When for example another user adds a comment, it will be updated on the screen.

Now I want to get the same behaviour in React Native using Node/Express server as a backend.

What should I do?

Send a request to the backend e.g. every second and check if there were changes? I suppose useSWR works like this.

Push the notification somehow starting with MongoDB and then from Node/Express to Android / iOS device? How to do it?

I am considering, which is the best solution, but have no idea at the time.


问:
How can I load all my keymaps from neovim to vscode with the Vim extension?
How can I load my keymaps from my init.lua when I use VS Code with the Vim extansion?

I have added init.lua path to Vim extension but it does not load the keymaps