问:
HuggingFace Pytorch trainer giving worse results than tensorflow
I’m trying to make the switch from tensorflow to pytorch, but I’m getting a good bit worse results when running a model in pytorch using Trainer.

I’m using bert-base-uncased, and as far as I can tell am using primarily the same settings across both (batch size, epochs, learning rate, etc). However I am getting a f1 score of 0.9967 from tensorflow, and a 0.944649446494465 from pytorch. The loss also seems to fluctuate a lot more in pytorch. I’m still pretty new to machine learning and python in general, so I feel like it’s gotta be something obvious, but I’ve yet to find it. Here are my scripts. Thanks in advance.

Tensorflow

```<code>SEQ_LEN = 256
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")

def train():
    def preprocess_function(examples):
        return tokenizer(examples["text"], max_length=SEQ_LEN, truncation=True, padding='max_length', add_special_tokens=True, return_attention_mask=True, return_token_type_ids=False, return_tensors='tf')

    dataset = load_dataset('json', data_files={"train": "full-items.json", "test": "validation-2.json"})

    tokenized = dataset.map(preprocess_function, batched=True)

    data_collator = DataCollatorWithPadding(tokenizer=tokenizer, return_tensors="tf")

    batch_size = 8
    num_epochs = 4
    batches_per_epoch = len(tokenized["train"]) // batch_size
    total_train_steps = int(batches_per_epoch * num_epochs)
    optimizer, schedule = create_optimizer(init_lr=4e-5, num_warmup_steps=0, num_train_steps=total_train_steps)

    id2label = {0: "NEGATIVE", 1: "POSITIVE"}
    label2id = {"NEGATIVE": 0, "POSITIVE": 1}

    model = TFAutoModelForSequenceClassification.from_pretrained(
        "bert-base-uncased", num_labels=2, id2label=id2label, label2id=label2id
    )

    tf_train_set = model.prepare_tf_dataset(
        tokenized["train"],
        shuffle=True,
        batch_size=batch_size,
        collate_fn=data_collator,
    )

    tf_validation_set = model.prepare_tf_dataset(
        tokenized["test"],
        shuffle=False,
        batch_size=batch_size,
        collate_fn=data_collator,
    )

    eval_metrics = evaluate.load("f1")

    def compute_metrics(eval_pred):
        predictions, labels = eval_pred
        predictions = np.argmax(predictions, axis=1)
        return eval_metrics.compute(predictions=predictions, references=labels)

    loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)

    METRICS = [
        tf.keras.metrics.SparseCategoricalAccuracy(name='accuracy'),
        tf.keras.metrics.SparseCategoricalCrossentropy(from_logits=True, name='sparse_crossentropy'),
    ]

    metric_callback = KerasMetricCallback(metric_fn=compute_metrics, eval_dataset=tf_train_set)
    early_stop = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=2)
    class_weights = dict(enumerate(sklearn.utils.class_weight.compute_class_weight('balanced',
                                                         classes=np.unique(tokenized["train"]["label"]),
                                                         y=tokenized["train"]["label"])))

    model.compile(optimizer=optimizer, loss=loss, metrics=METRICS)
    model.fit(x=tf_train_set, validation_data=tf_validation_set, epochs=num_epochs, class_weight=class_weights, callbacks=[early_stop, metric_callback])
    model.save_pretrained('lease_to_own_model', save_format="tf")
</code>```

Pytorch

```<code>def pyTorch():
    def preprocess_function(examples):
        return tokenizer(examples["text"], max_length=SEQ_LEN, truncation=True, padding='max_length', add_special_tokens=True, return_attention_mask=True, return_token_type_ids=False)

    dataset = load_dataset('json', data_files={"train": "full-items.json", "test": "validation-2.json"})
    tokenized = dataset.map(preprocess_function, batched=True)

    data_collator = DataCollatorWithPadding(tokenizer=tokenizer)

    eval_f1 = evaluate.load("f1")
    eval_accuracy = evaluate.load("accuracy")

    def compute_metrics(eval_pred):
        predictions, labels = eval_pred
        predictions = np.argmax(predictions, axis=1)
        f1 = eval_f1.compute(predictions=predictions, references=labels)
        accuracy = eval_accuracy.compute(predictions=predictions, references=labels)
        return {"accuracy": accuracy["accuracy"], "f1": f1["f1"]}

    id2label = {0: "NEGATIVE", 1: "POSITIVE"}
    label2id = {"NEGATIVE": 0, "POSITIVE": 1}

    model = AutoModelForSequenceClassification.from_pretrained(
        "bert-base-uncased", num_labels=2, id2label=id2label, label2id=label2id
    )
    device = torch.device("cuda")
    model.to(device)

    batch_size = 8

    training_args = TrainingArguments(
        num_train_epochs=4,
        output_dir="pytorch",
        learning_rate=4e-5,
        per_device_train_batch_size=batch_size,
        per_device_eval_batch_size=batch_size,
        evaluation_strategy="epoch",
        save_strategy="epoch",
        metric_for_best_model='f1',
        load_best_model_at_end=True,
        logging_strategy="epoch",
        warmup_steps=0,
    )

    class_weights = sklearn.utils.class_weight.compute_class_weight('balanced',
                                                         classes=np.unique(tokenized["train"]["label"]),
                                                         y=tokenized["train"]["label"])
    weights= torch.tensor(class_weights,dtype=torch.float).to(device)

    class CustomTrainer(Trainer):
        def compute_loss(self, model, inputs, return_outputs=False):
            labels = inputs.get("labels")
            outputs = model(**inputs)
            logits = outputs.get("logits")
            loss_fct = torch.nn.CrossEntropyLoss(weight=weights)
            loss = loss_fct(logits.view(-1, self.model.config.num_labels), labels.view(-1))
            return (loss, outputs) if return_outputs else loss

    trainer = CustomTrainer(
        model=model,
        args=training_args,
        train_dataset=tokenized["train"],
        eval_dataset=tokenized["test"],
        tokenizer=tokenizer,
        data_collator=data_collator,
        compute_metrics=compute_metrics,
    )

    trainer.train()

    trainer.save_model("pytorch")
</code>```

Body:
I’m trying to make the switch from tensorflow to pytorch, but I’m getting a good bit worse results when running a model in pytorch using Trainer.

I’m using bert-base-uncased, and as far as I can tell am using primarily the same settings across both (batch size, epochs, learning rate, etc). However I am getting a f1 score of 0.9967 from tensorflow, and a 0.944649446494465 from pytorch. The loss also seems to fluctuate a lot more in pytorch. I’m still pretty new to machine learning and python in general, so I feel like it’s gotta be something obvious, but I’ve yet to find it. Here are my scripts. Thanks in advance.

Tensorflow

SEQ_LEN = 256
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")

def train():
    def preprocess_function(examples):
        return tokenizer(examples["text"], max_length=SEQ_LEN, truncation=True, padding='max_length', add_special_tokens=True, return_attention_mask=True, return_token_type_ids=False, return_tensors='tf')

    dataset = load_dataset('json', data_files={"train": "full-items.json", "test": "validation-2.json"})

    tokenized = dataset.map(preprocess_function, batched=True)

    data_collator = DataCollatorWithPadding(tokenizer=tokenizer, return_tensors="tf")

    batch_size = 8
    num_epochs = 4
    batches_per_epoch = len(tokenized["train"]) // batch_size
    total_train_steps = int(batches_per_epoch * num_epochs)
    optimizer, schedule = create_optimizer(init_lr=4e-5, num_warmup_steps=0, num_train_steps=total_train_steps)

    id2label = {0: "NEGATIVE", 1: "POSITIVE"}
    label2id = {"NEGATIVE": 0, "POSITIVE": 1}

    model = TFAutoModelForSequenceClassification.from_pretrained(
        "bert-base-uncased", num_labels=2, id2label=id2label, label2id=label2id
    )

    tf_train_set = model.prepare_tf_dataset(
        tokenized["train"],
        shuffle=True,
        batch_size=batch_size,
        collate_fn=data_collator,
    )

    tf_validation_set = model.prepare_tf_dataset(
        tokenized["test"],
        shuffle=False,
        batch_size=batch_size,
        collate_fn=data_collator,
    )

    eval_metrics = evaluate.load("f1")

    def compute_metrics(eval_pred):
        predictions, labels = eval_pred
        predictions = np.argmax(predictions, axis=1)
        return eval_metrics.compute(predictions=predictions, references=labels)

    loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)

    METRICS = [
        tf.keras.metrics.SparseCategoricalAccuracy(name='accuracy'),
        tf.keras.metrics.SparseCategoricalCrossentropy(from_logits=True, name='sparse_crossentropy'),
    ]

    metric_callback = KerasMetricCallback(metric_fn=compute_metrics, eval_dataset=tf_train_set)
    early_stop = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=2)
    class_weights = dict(enumerate(sklearn.utils.class_weight.compute_class_weight('balanced',
                                                         classes=np.unique(tokenized["train"]["label"]),
                                                         y=tokenized["train"]["label"])))

    model.compile(optimizer=optimizer, loss=loss, metrics=METRICS)
    model.fit(x=tf_train_set, validation_data=tf_validation_set, epochs=num_epochs, class_weight=class_weights, callbacks=[early_stop, metric_callback])
    model.save_pretrained('lease_to_own_model', save_format="tf")

Pytorch

def pyTorch():
    def preprocess_function(examples):
        return tokenizer(examples["text"], max_length=SEQ_LEN, truncation=True, padding='max_length', add_special_tokens=True, return_attention_mask=True, return_token_type_ids=False)

    dataset = load_dataset('json', data_files={"train": "full-items.json", "test": "validation-2.json"})
    tokenized = dataset.map(preprocess_function, batched=True)

    data_collator = DataCollatorWithPadding(tokenizer=tokenizer)

    eval_f1 = evaluate.load("f1")
    eval_accuracy = evaluate.load("accuracy")

    def compute_metrics(eval_pred):
        predictions, labels = eval_pred
        predictions = np.argmax(predictions, axis=1)
        f1 = eval_f1.compute(predictions=predictions, references=labels)
        accuracy = eval_accuracy.compute(predictions=predictions, references=labels)
        return {"accuracy": accuracy["accuracy"], "f1": f1["f1"]}

    id2label = {0: "NEGATIVE", 1: "POSITIVE"}
    label2id = {"NEGATIVE": 0, "POSITIVE": 1}

    model = AutoModelForSequenceClassification.from_pretrained(
        "bert-base-uncased", num_labels=2, id2label=id2label, label2id=label2id
    )
    device = torch.device("cuda")
    model.to(device)

    batch_size = 8

    training_args = TrainingArguments(
        num_train_epochs=4,
        output_dir="pytorch",
        learning_rate=4e-5,
        per_device_train_batch_size=batch_size,
        per_device_eval_batch_size=batch_size,
        evaluation_strategy="epoch",
        save_strategy="epoch",
        metric_for_best_model='f1',
        load_best_model_at_end=True,
        logging_strategy="epoch",
        warmup_steps=0,
    )

    class_weights = sklearn.utils.class_weight.compute_class_weight('balanced',
                                                         classes=np.unique(tokenized["train"]["label"]),
                                                         y=tokenized["train"]["label"])
    weights= torch.tensor(class_weights,dtype=torch.float).to(device)

    class CustomTrainer(Trainer):
        def compute_loss(self, model, inputs, return_outputs=False):
            labels = inputs.get("labels")
            outputs = model(**inputs)
            logits = outputs.get("logits")
            loss_fct = torch.nn.CrossEntropyLoss(weight=weights)
            loss = loss_fct(logits.view(-1, self.model.config.num_labels), labels.view(-1))
            return (loss, outputs) if return_outputs else loss

    trainer = CustomTrainer(
        model=model,
        args=training_args,
        train_dataset=tokenized["train"],
        eval_dataset=tokenized["test"],
        tokenizer=tokenizer,
        data_collator=data_collator,
        compute_metrics=compute_metrics,
    )

    trainer.train()

    trainer.save_model("pytorch")


来源: stackexchange

问:
mongoengine how to use a variable as a field?
How do you use a variable as a field to find a specific value within a mongodb database? I am trying to target a list inside of a list in my collection making use of an integer variable that is grabbed from wtforms. When I try to input the variable I get an error message of:

```<code>mongoengine.errors.OperationError: Update failed (Cannot create field 'studentSlot' in element {Attendance: [ [] ]})
</code>```

the code segment:

```<code>if request.method == "POST":
        if "form" in request.form and form.validate_on_submit():
            klass = classes.objects(id = form.classid.data).first()

            studentSlot = form.slotid.data
            if klass:
                studentSlot = form.slotid.data
                klass.update(push__Attendance__studentSlot__1 = form.attended.data)
</code>```

example document:

```<code>{
    "_id" : ObjectId("637545927a45e617da1cba8e"),
    "CourseName" : "Themes in U.S. History",
    "Prerequiste" : [

    ],
    "MinimumRequirement" : [

    ],
    "Description" : "The course is an introduction to major issues in the history of the United States, from colonial times to the twentieth\r\ncentury. Topics may include: the origins of slavery and racism; industrialization and the growth of cities and suburbs;\r\nthe growth of the American empire; movements for social change.",
    "RoomID" : NumberInt(31),
    "BuildingID" : NumberInt(2),
    "Type" : "Undergraduate",
    "TimeSlot" : NumberInt(3),
    "Credits" : NumberInt(4),
    "MaxCapacity" : NumberInt(30),
    "Day" : "Tuesday & Thursday",
    "Professor" : ObjectId("638be8c63d5b3e062b56f8ea"),
    "Enrolled" : [
        ObjectId("6376b19ef448207c0a721245")
    ],
    "Department" : "American Studies",
    "Attendance" : [
        [

        ]
    ],
    "Grades" : [

    ],
    "Year" : NumberInt(2022),
    "Season" : "Spring",
    "StartDate" : ISODate("2022-01-26T00:00:00.000+0000"),
    "EndDate" : ISODate("2022-05-20T00:00:00.000+0000"),
    "Crn" : "AS536",
    "AttendanceDate" : [

    ]
}
</code>```

If studentSlot in the last line is replaced with 0 (for example), it works perfectly fine. This would be suitable if I didn't need to grab the slotid number from the user.

So put simply how do I make the studentSlot variable be read as the variable as opposed to being read as a field that doesn't exist?

Any help is appreciated.

ContentLicense: CC BY-SA 4.0

Body:
How do you use a variable as a field to find a specific value within a mongodb database? I am trying to target a list inside of a list in my collection making use of an integer variable that is grabbed from wtforms. When I try to input the variable I get an error message of:

mongoengine.errors.OperationError: Update failed (Cannot create field 'studentSlot' in element {Attendance: [ [] ]})

the code segment:

if request.method == "POST":
        if "form" in request.form and form.validate_on_submit():
            klass = classes.objects(id = form.classid.data).first()

            studentSlot = form.slotid.data
            if klass:
                studentSlot = form.slotid.data
                klass.update(push__Attendance__studentSlot__1 = form.attended.data)

example document:

{
    "_id" : ObjectId("637545927a45e617da1cba8e"),
    "CourseName" : "Themes in U.S. History",
    "Prerequiste" : [

    ],
    "MinimumRequirement" : [

    ],
    "Description" : "The course is an introduction to major issues in the history of the United States, from colonial times to the twentieth\r\ncentury. Topics may include: the origins of slavery and racism; industrialization and the growth of cities and suburbs;\r\nthe growth of the American empire; movements for social change.",
    "RoomID" : NumberInt(31),
    "BuildingID" : NumberInt(2),
    "Type" : "Undergraduate",
    "TimeSlot" : NumberInt(3),
    "Credits" : NumberInt(4),
    "MaxCapacity" : NumberInt(30),
    "Day" : "Tuesday & Thursday",
    "Professor" : ObjectId("638be8c63d5b3e062b56f8ea"),
    "Enrolled" : [
        ObjectId("6376b19ef448207c0a721245")
    ],
    "Department" : "American Studies",
    "Attendance" : [
        [

        ]
    ],
    "Grades" : [

    ],
    "Year" : NumberInt(2022),
    "Season" : "Spring",
    "StartDate" : ISODate("2022-01-26T00:00:00.000+0000"),
    "EndDate" : ISODate("2022-05-20T00:00:00.000+0000"),
    "Crn" : "AS536",
    "AttendanceDate" : [

    ]
}

If studentSlot in the last line is replaced with 0 (for example), it works perfectly fine. This would be suitable if I didn't need to grab the slotid number from the user.

So put simply how do I make the studentSlot variable be read as the variable as opposed to being read as a field that doesn't exist?

Any help is appreciated.


问:
Looking for an excel formula to autofill a column
I'm using a spreadsheet to assign box positions on shelves. The boxes are currently ranked by weight so that I can distribute that weight evenly across all shelves. As I'm assigning box positions, I would like excel to give me a running count for how many boxes have been assigned to each RACK and SHELF in the 'SHELF SPACE' column. A sample of the data is included below

What I'd like the SHELF SPACE column to do

I would like excel to find the previous SHELF SPACE for a given RACK and SHELF and add it to the BOX HEIGHT. The sum would then be the new SHELF SPACE value.

Entering by hand has taken a long time, so I've tried looking for formulas to help, but haven't had any luck piecing things together.

I've tried a lot of different formulas but the following has gotten me the closest.

what I've tried

I concatenated the 'RACK' and 'SHELF' columns, then I tried the following formula (which is in the image above):

INDEX(B2:B12,AGGREGATE(15,6,ROW(E2:E12)-1/(E2:E12="A4"),2))

I feel like this is getting me closer, but it can't give me a running count and only tracks box heights that match "A4" and the aggregate formula will only return a value if I input the K value.

UPDATE: 1/6/2023
I made the following formula, which gets me even closer, but this still only makes a running count for cells containing "A4". I would like it to make a running count for cells that also contain "B4" through "X4"

=IF(U2<>"A4","",SUMIF($U$2:U2,"A4",$P$2:P2))

UPDATE 1/6/2023

I made a nested if formula that seems to be doing what I want, but it is too long, so I've broken it in to 4 parts (1 string for each shelf). Here it is (from another spread sheet that I've been testing on). If it could be simplified, that would be great. I've also read that long nested IF statements can start producing errors.

IF(R2="A4",SUMIF($R$2:R2,"A4",$O$2:O2),IF(R2="B4",SUMIF($R$2:R2,"B4",$O$2:O2),IF(R2="C4",SUMIF($R$2:R2,"C4",$O$2:O2),IF(R2="D4",SUMIF($R$2:R2,"D4",$O$2:O2),IF(R2="E4",SUMIF($R$2:R2,"E4",$O$2:O2),IF(R2="F4",SUMIF($R$2:R2,"F4",$O$2:O2),IF(R2="G4",SUMIF($R$2:R2,"G4",$O$2:O2),IF(R2="H4",SUMIF($R$2:R2,"H4",$O$2:O2),IF(R2="I4",SUMIF($R$2:R2,"I4",$O$2:O2),IF(R2="J4",SUMIF($R$2:R2,"J4",$O$2:O2),IF(R2="K4",SUMIF($R$2:R2,"K4",$O$2:O2),IF(R2="L4",SUMIF($R$2:R2,"L4",$O$2:O2),IF(R2="M4",SUMIF($R$2:R2,"M4",$O$2:O2),IF(R2="N4",SUMIF($R$2:R2,"N4",$O$2:O2),IF(R2="O4",SUMIF($R$2:R2,"O4",$O$2:O2),IF(R2="P4",SUMIF($R$2:R2,"P4",$O$2:O2),IF(R2="Q4",SUMIF($R$2:R2,"Q4",$O$2:O2),IF(R2="R4",SUMIF($R$2:R2,"R4",$O$2:O2),IF(R2="S4",SUMIF($R$2:R2,"S4",$O$2:O2),IF(R2="T4",SUMIF($R$2:R2,"T4",$O$2:O2),IF(R2="U4",SUMIF($R$2:R2,"U4",$O$2:O2),IF(R2="V4",SUMIF($R$2:R2,"V4",$O$2:O2),IF(R2="W4",SUMIF($R$2:R2,"W4",$O$2:O2),IF(R2="X4",SUMIF($R$2:R2,"X4",$O$2:O2),"")))))))))))))))))))))))))))


问:
How to output in a container different number formats picked from a form using the intl-tel-input library? JS and HTML
I have the HTML below which is using the library intl-tel-input. When a user inputs a phone number in the form I wanted to output in the output container the following things:

the word "Valid:" and then "true" on the right of the word valid if the phone number was inserted in the correct format.

the word "Raw local:" and on the right the raw local number from the form

The word "Local:" and on the right the local number from the form

The word "E164:" etc.

The word "International" etc.

The word "Country code:", etc.

The word "Country:" etc. For example if in the form it's china it will appear CN

This is what I tried but currently, it doesn't output anything. know this should be easy but am kinda new to javascript.

HTML:

<!DOCTYPE html>

        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/css/intlTelInput.css"/>

          Logo

            <button class="btn btn-secondary" id="theme-button">

            </button>

            <button class="btn btn-secondary" id="language-button">

            </button>

            <form id="login" onsubmit="process(event)">

Enter your phone number:

                <input id="phone" type="tel" name="phone" />
                <input type="submit" class="btn" value="Verify" />
              </form>

```

I tried the html written in the message above

Body:
I have the HTML below which is using the library intl-tel-input. When a user inputs a phone number in the form I wanted to output in the output container the following things:

the word "Valid:" and then "true" on the right of the word valid if the phone number was inserted in the correct format.

the word "Raw local:" and on the right the raw local number from the form

The word "Local:" and on the right the local number from the form

The word "E164:" etc.

The word "International" etc.

The word "Country code:", etc.

The word "Country:" etc. For example if in the form it's china it will appear CN

This is what I tried but currently, it doesn't output anything. know this should be easy but am kinda new to javascript.

HTML:

<!DOCTYPE html>

        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/css/intlTelInput.css"/>

          Logo

            <button class="btn btn-secondary" id="theme-button">

            </button>

            <button class="btn btn-secondary" id="language-button">

            </button>

            <form id="login" onsubmit="process(event)">

Enter your phone number:

                <input id="phone" type="tel" name="phone" />
                <input type="submit" class="btn" value="Verify" />
              </form>

I tried the html written in the message above


问:
Check whether React.Suspense is ready
I'm using the Intersection Observer API in React to add some animations. I am adding as Intersection Entries some elements.

The problem is that I have the app in multiple languages, and due to the implementation that the tool I am using to translate has, I need to wrap all my components into React.Suspense to wait for languages to load.

When useEffect queries for the elements, they aren't still in the DOM, and therefore they are not assigned as entries.

This is my custom hook:

hooks/useObserver.js

import { useState } from "react";
import { useEffect, useRef } from "react";

export function useObserver(config = {}) {
  const [elements, setElements] = useState([]);
  const [entries, setEntries] = useState([]);

  const observer = useRef(
    new IntersectionObserver(observedEntries => {
      setEntries(observedEntries);
    }, config)
  );

  useEffect(() => {
    const { current: currentObserver } = observer;

    currentObserver.disconnect();

    if (elements.length > 0) {
      elements.forEach(el => currentObserver.observe(el));
    }
    return () => {
      if (currentObserver) {
        currentObserver.disconnect();
      }
    };
  }, [elements]);

  return { observer: observer.current, setElements, entries };
}

```
<p>and this is my main component:</p>
<blockquote>
<p>App.jsx</p>
</blockquote>
<pre class="lang-js prettyprint-override"><code>import Header from "./components/Header";
import Hero from "./components/Hero";
import Footer from "./components/Footer";
import { Loader } from "./components/shared/Loader";
import { useObserver } from "./hooks/useObserver";
import { useEffect, Suspense } from "react";

function App() {
  const { entries, setElements } = useObserver({});

  useEffect(() => {
      const sections = document.querySelectorAll("section.animated-section");
      setElements(sections);
    };
  }, [setElements]);

  useEffect(() => {
    entries.forEach(entry => {
      entry.target.classList.toggle("section-visible", entry.isIntersecting);
    });
  }, [entries]);

  return (
    <Suspense fallback={<Loader />}>
      <Header />
      <Hero />
      <Footer />
    </Suspense>
  );
}

export default App;

</code>```

I tried to set a timeout to wait some seconds and then add the elements as entries, and it works correctly:

  useEffect(() => {
    const observeElements = () => {
      const sections = document.querySelectorAll("section.animated-section");

      setElements(sections);
    };

    const observeElementsTimeout = setTimeout(observeElements, 3000);

    return () => clearTimeout(observeElementsTimeout)
  }, [setElements]);

```

I want to know if:

There is a way to know when React.Suspense is ready

There is a better approach to solve my problem

Thanks in advance!!

Title: Check whether React.Suspense is ready

Body:
I'm using the Intersection Observer API in React to add some animations. I am adding as Intersection Entries some elements.

The problem is that I have the app in multiple languages, and due to the implementation that the tool I am using to translate has, I need to wrap all my components into React.Suspense to wait for languages to load.

When useEffect queries for the elements, they aren't still in the DOM, and therefore they are not assigned as entries.

This is my custom hook:

hooks/useObserver.js

import { useState } from "react";
import { useEffect, useRef } from "react";

export function useObserver(config = {}) {
  const [elements, setElements] = useState([]);
  const [entries, setEntries] = useState([]);

  const observer = useRef(
    new IntersectionObserver(observedEntries => {
      setEntries(observedEntries);
    }, config)
  );

  useEffect(() => {
    const { current: currentObserver } = observer;

    currentObserver.disconnect();

    if (elements.length > 0) {
      elements.forEach(el => currentObserver.observe(el));
    }
    return () => {
      if (currentObserver) {
        currentObserver.disconnect();
      }
    };
  }, [elements]);

  return { observer: observer.current, setElements, entries };
}

and this is my main component:

App.jsx

import Header from "./components/Header";
import Hero from "./components/Hero";
import Footer from "./components/Footer";
import { Loader } from "./components/shared/Loader";
import { useObserver } from "./hooks/useObserver";
import { useEffect, Suspense } from "react";

function App() {
  const { entries, setElements } = useObserver({});

  useEffect(() => {
      const sections = document.querySelectorAll("section.animated-section");
      setElements(sections);
    };
  }, [setElements]);

  useEffect(() => {
    entries.forEach(entry => {
      entry.target.classList.toggle("section-visible", entry.isIntersecting);
    });
  }, [entries]);

  return (
    <Suspense fallback={<Loader />}>

      <Hero />

    </Suspense>
  );
}

export default App;

I tried to set a timeout to wait some seconds and then add the elements as entries, and it works correctly:

  useEffect(() => {
    const observeElements = () => {
      const sections = document.querySelectorAll("section.animated-section");

      setElements(sections);
    };

    const observeElementsTimeout = setTimeout(observeElements, 3000);

    return () => clearTimeout(observeElementsTimeout)
  }, [setElements]);

I want to know if:

There is a way to know when React.Suspense is ready

There is a better approach to solve my problem

Thanks in advance!!


问:
type 'CombineLatestStream<QuerySnapshot<Object>, List<QuerySnapshot<Object>>>' is not a subtype of type 'Query<dynamic>'
```<code>Future<Stream<QuerySnapshot<Object>>> List1() async {
    var idList = _firestore
        .collection('users')
        .doc(user.uid)
        .collection("IDs");
    var idListQuery = await idList.get();
    var map = idListQuery.docs;
    for (int i = 0; i < map.length; i++) {
      setState(() {
        IDList.add(map[i].data()["ID"]);
      });
    }
    var chunks = [];
    for (var i = 0; i < IDList.length; i += 10) {
      chunks.add(IDList.sublist(
          i, i + 10 > IDList.length ? IDList.length : i + 10));
    }
    for (var i = 0; i < chunks.length; i++) {
      combineList.add(Ref
          .where('ID', whereIn: chunks[i])
          .orderBy("uploadTime", descending: true)
          .snapshots());
    }

    totalRef = CombineLatestStream.list(combineList);
  }
</code>```

I have a various Collection References and Im combining them with CombineLatestStream in totalRef.

When Im using this totalRef in StreamBuilder its working well.

But when I want to use this totalRef in FirestoreQueryBuilder(), im getting this error;

```<code>type 'CombineLatestStream<QuerySnapshot<Object>, List<QuerySnapshot<Object>>>' is not a subtype of type 'Query<dynamic>'
</code>```

This is the my FirestoreQueryBuilder(),

```<code>FirestoreQueryBuilder(
                            pageSize: 10,
                            query: totalRef,
                            builder: (context, snapshot, _) {
                              if (snapshot.isFetching) {
                                return const CircularProgressIndicator();
                              }

                              if (snapshot.hasError) {
                                return Text(
                                    'Something went wrong! ${snapshot.error}');
                              }
                              return ListView.builder(
                                physics: ScrollPhysics(),
                                shrinkWrap: true,
                                itemCount: snapshot.docs.length,
                                itemBuilder: (BuildContext context, int index) {
                                  if (snapshot.hasMore &&
                                      index + 1 == snapshot.docs.length) {
                                    snapshot.fetchMore();
                                  }
                                  final post = snapshot.docs[index].data();
                                  return Container(
                                    margin: EdgeInsets.symmetric(
                                        horizontal: 12.0, vertical: 12.0),
                                    child: Column(
                                      children: <Widget>[
                                        Stack(
                                          children: <Widget>[
                                            Align(
                                              alignment: Alignment.topCenter,
                                              child: ClipRRect(
                                                borderRadius:
                                                    BorderRadius.circular(24),
                                                child: GestureDetector(
                                                  onTap: () =>
                                                      navigateToDetail(post),
                                                  child: (post["pic"] != null)
                                                      ? OptimizedCacheImage(
                                                          imageUrl:
                                                              post["pic"],
                                                          imageBuilder: (context,
                                                                  imageProvider) =>
                                                              Container(
                                                            height:
                                                                size.height *
                                                                    0.475,
                                                            width: size.width *
                                                                0.80,
                                                            decoration:
                                                                BoxDecoration(
                                                                    image:
                                                                        DecorationImage(
                                                              image:
                                                                  imageProvider,
                                                              fit: BoxFit.cover,
                                                            )),
                                                          ),
                                                          placeholder:
                                                              (context, url) =>
                                                                  Container(
                                                            height:
                                                                size.height *
                                                                    0.475,
                                                            width: size.width *
                                                                0.80,
                                                            decoration:
                                                                BoxDecoration(
                                                              color: Colors
                                                                  .grey[400],
                                                              borderRadius:
                                                                  BorderRadius
                                                                      .circular(
                                                                          24),
                                                            ),
                                                          ),
                                                        )
                                                      : Image(
                                                          height: size.height *
                                                              0.475,
                                                          width:
                                                              size.width * 0.80,
                                                          fit: BoxFit.cover,
                                                          image: AssetImage(
                                                              "assets/images/n_image.jpg"),
                                                        ),
                                                ),
                                              ),
                                            ),
                                            Positioned(
                                              top: 5,
                                              right: 43,
                                              child: Container(
                                                height: size.height * 0.1,
                                                width: size.width * 0.1,
                                                decoration: BoxDecoration(
                                                    shape: BoxShape.circle,
                                                    color: Colors.grey[700]
                                                        .withOpacity(0.5)),
                                                child: IconFav(
                                                  post: post,
                                                ),
                                              ),
                                            ),
                                          ],
                                        ),
                                        SizedBox(
                                          height: size.height * 0.015,
                                        ),
                                        Container(
                                          width: size.width * 0.77,
                                          child: Row(
                                            crossAxisAlignment:
                                                CrossAxisAlignment.start,
                                            children: <Widget>[
                                              Expanded(
                                                child: Column(
                                                  crossAxisAlignment:
                                                      CrossAxisAlignment.start,
                                                  children: <Widget>[
                                                    AutoSizeText(
                                                      post["name"],
                                                      style: Theme.of(context)
                                                          .textTheme
                                                          .subtitle1,
                                                    ),
                                                    SizedBox(
                                                      height:
                                                          size.height * 0.012,
                                                    ),
                                                    GestureDetector(
                                                      onTap: () =>
                                                          navigateToProfile(
                                                              post),
                                                      child: Container(
                                                        child: AutoSizeText(
                                                          post["writer"],
                                                          style:
                                                              Theme.of(context)
                                                                  .textTheme
                                                                  .caption,
                                                        ),
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                              ),
                                              Expanded(
                                                child: Row(
                                                  mainAxisAlignment:
                                                      MainAxisAlignment.end,
                                                  children: <Widget>[
                                                    Icon(Icons.timer_outlined),
                                                    SizedBox(
                                                      width: size.width *
                                                          0.005, //2
                                                    ),
                                                    AutoSizeText(
                                                      "${post["ptime"]}'",
                                                    ),
                                                    SizedBox(
                                                      width: size.width *
                                                          0.007, //3
                                                    ),
                                                    IconLike(
                                                      post: post,
                                                    ),
                                                  ],
                                                ),
                                              )
                                            ],
                                          ),
                                        ),
                                      ],
                                    ),
                                  );
                                },
                              );
                            }),
</code>```

Im using this FirestoreQueryBuilder(), for paginate my datas in order not to get too much data when getting data, so I need to use this QueryBuilder and I also need to use this Combine References as totalRef because I have more than References.

How can I fix this problem.

Body:
Future<Stream<QuerySnapshot<Object>>> List1() async {
    var idList = _firestore
        .collection('users')
        .doc(user.uid)
        .collection("IDs");
    var idListQuery = await idList.get();
    var map = idListQuery.docs;
    for (int i = 0; i < map.length; i++) {
      setState(() {
        IDList.add(map[i].data()["ID"]);
      });
    }
    var chunks = [];
    for (var i = 0; i < IDList.length; i += 10) {
      chunks.add(IDList.sublist(
          i, i + 10 > IDList.length ? IDList.length : i + 10));
    }
    for (var i = 0; i < chunks.length; i++) {
      combineList.add(Ref
          .where('ID', whereIn: chunks[i])
          .orderBy("uploadTime", descending: true)
          .snapshots());
    }

    totalRef = CombineLatestStream.list(combineList);
  }

I have a various Collection References and Im combining them with CombineLatestStream in totalRef.

When Im using this totalRef in StreamBuilder its working well.

But when I want to use this totalRef in FirestoreQueryBuilder(), im getting this error;

type 'CombineLatestStream<QuerySnapshot<Object>, List<QuerySnapshot<Object>>>' is not a subtype of type 'Query<dynamic>'

This is the my FirestoreQueryBuilder(),

FirestoreQueryBuilder(
                            pageSize: 10,
                            query: totalRef,
                            builder: (context, snapshot, _) {
                              if (snapshot.isFetching) {
                                return const CircularProgressIndicator();
                              }

                              if (snapshot.hasError) {
                                return Text(
                                    'Something went wrong! ${snapshot.error}');
                              }
                              return ListView.builder(
                                physics: ScrollPhysics(),
                                shrinkWrap: true,
                                itemCount: snapshot.docs.length,
                                itemBuilder: (BuildContext context, int index) {
                                  if (snapshot.hasMore &&
                                      index + 1 == snapshot.docs.length) {
                                    snapshot.fetchMore();
                                  }
                                  final post = snapshot.docs[index].data();
                                  return Container(
                                    margin: EdgeInsets.symmetric(
                                        horizontal: 12.0, vertical: 12.0),
                                    child: Column(
                                      children: <Widget>[
                                        Stack(
                                          children: <Widget>[
                                            Align(
                                              alignment: Alignment.topCenter,
                                              child: ClipRRect(
                                                borderRadius:
                                                    BorderRadius.circular(24),
                                                child: GestureDetector(
                                                  onTap: () =>
                                                      navigateToDetail(post),
                                                  child: (post["pic"] != null)
                                                      ? OptimizedCacheImage(
                                                          imageUrl:
                                                              post["pic"],
                                                          imageBuilder: (context,
                                                                  imageProvider) =>
                                                              Container(
                                                            height:
                                                                size.height *
                                                                    0.475,
                                                            width: size.width *
                                                                0.80,
                                                            decoration:
                                                                BoxDecoration(
                                                                    image:
                                                                        DecorationImage(
                                                              image:
                                                                  imageProvider,
                                                              fit: BoxFit.cover,
                                                            )),
                                                          ),
                                                          placeholder:
                                                              (context, url) =>
                                                                  Container(
                                                            height:
                                                                size.height *
                                                                    0.475,
                                                            width: size.width *
                                                                0.80,
                                                            decoration:
                                                                BoxDecoration(
                                                              color: Colors
                                                                  .grey[400],
                                                              borderRadius:
                                                                  BorderRadius
                                                                      .circular(
                                                                          24),
                                                            ),
                                                          ),
                                                        )
                                                      : Image(
                                                          height: size.height *
                                                              0.475,
                                                          width:
                                                              size.width * 0.80,
                                                          fit: BoxFit.cover,
                                                          image: AssetImage(
                                                              "assets/images/n_image.jpg"),
                                                        ),
                                                ),
                                              ),
                                            ),
                                            Positioned(
                                              top: 5,
                                              right: 43,
                                              child: Container(
                                                height: size.height * 0.1,
                                                width: size.width * 0.1,
                                                decoration: BoxDecoration(
                                                    shape: BoxShape.circle,
                                                    color: Colors.grey[700]
                                                        .withOpacity(0.5)),
                                                child: IconFav(
                                                  post: post,
                                                ),
                                              ),
                                            ),
                                          ],
                                        ),
                                        SizedBox(
                                          height: size.height * 0.015,
                                        ),
                                        Container(
                                          width: size.width * 0.77,
                                          child: Row(
                                            crossAxisAlignment:
                                                CrossAxisAlignment.start,
                                            children: <Widget>[
                                              Expanded(
                                                child: Column(
                                                  crossAxisAlignment:
                                                      CrossAxisAlignment.start,
                                                  children: <Widget>[
                                                    AutoSizeText(
                                                      post["name"],
                                                      style: Theme.of(context)
                                                          .textTheme
                                                          .subtitle1,
                                                    ),
                                                    SizedBox(
                                                      height:
                                                          size.height * 0.012,
                                                    ),
                                                    GestureDetector(
                                                      onTap: () =>
                                                          navigateToProfile(
                                                              post),
                                                      child: Container(
                                                        child: AutoSizeText(
                                                          post["writer"],
                                                          style:
                                                              Theme.of(context)
                                                                  .textTheme
                                                                  .caption,
                                                        ),
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                              ),
                                              Expanded(
                                                child: Row(
                                                  mainAxisAlignment:
                                                      MainAxisAlignment.end,
                                                  children: <Widget>[
                                                    Icon(Icons.timer_outlined),
                                                    SizedBox(
                                                      width: size.width *
                                                          0.005, //2
                                                    ),
                                                    AutoSizeText(
                                                      "${post["ptime"]}'",
                                                    ),
                                                    SizedBox(
                                                      width: size.width *
                                                          0.007, //3
                                                    ),
                                                    IconLike(
                                                      post: post,
                                                    ),
                                                  ],
                                                ),
                                              )
                                            ],
                                          ),
                                        ),
                                      ],
                                    ),
                                  );
                                },
                              );
                            }),

Im using this FirestoreQueryBuilder(), for paginate my datas in order not to get too much data when getting data, so I need to use this QueryBuilder and I also need to use this Combine References as totalRef because I have more than References.

How can I fix this problem.


问:
I keep on getting the same Output despite changing the Input
I'm currently trying to convert an input of roman numerals into the corresponding integer.
However, despite changing the roman numerals I enter i always receive the same answer even tho my code appears alright.Any help would be massively appreciated.
Here's my code:

```<code>RomanNum=input('Please Enter the Desired number in the form(e.g III):')
def romanToInt(RomanNum):
        #When using roman numerals if the larger numeral comes before the smaller numeral we add them
        #If the smaller numeral comes before larger number we subtract

    roman= { "I" : 1, "V" : 5, "X" : 10, "L" : 50, "C" : 100, "D" : 500, "M" : 1000 }

    Int=0

    for i in range(len(s)):
        if i+1<len(s) and roman[s[i]] < roman[s[i+1]]:
            Int-=roman[s[i]]
        else:
            Int += roman[s[i]]
    return Int

print(romanToInt(RomanNum))
</code>```

I've tried multiple inputs however the answer remains the same.
I expected a changing integer depending on the input of roman numerals.

Body:
I'm currently trying to convert an input of roman numerals into the corresponding integer.
However, despite changing the roman numerals I enter i always receive the same answer even tho my code appears alright.Any help would be massively appreciated.
Here's my code:

RomanNum=input('Please Enter the Desired number in the form(e.g III):')
def romanToInt(RomanNum):
        #When using roman numerals if the larger numeral comes before the smaller numeral we add them
        #If the smaller numeral comes before larger number we subtract

    roman= { "I" : 1, "V" : 5, "X" : 10, "L" : 50, "C" : 100, "D" : 500, "M" : 1000 }

    Int=0

    for i in range(len(s)):
        if i+1<len(s) and roman[s[i]] < roman[s[i+1]]:
            Int-=roman[s[i]]
        else:
            Int += roman[s[i]]
    return Int

print(romanToInt(RomanNum))

I've tried multiple inputs however the answer remains the same.
I expected a changing integer depending on the input of roman numerals.


问:
multiple line print result should display in one line
I have a SQL-based question. when I run the select statement in my table it shows in one line but when I print it, it comes in multiple rows. because of this when I create SSRS report the data shows in multiple rows.
eg: SQL select statement result:
HYDROCARBON CONSTRUCTION CO % L H GUNN PO BOX 53495 HOUSTON TX 77052-3495

and when I filter by the WHERE clause I did not get any result.

eg: select emplpyer_name from employers where employer_name = 'HYDROCARBON CONSTRUCTION CO % L H GUNN PO BOX 53495 HOUSTON TX 77052-3495'

but when I print it, it gives results in four rows like below.

I have run the bolow code and got 4 line result. but I want it in one line when I print it:

declare @t varchar(1000);
set @t=(SELECT Employer_name as a from EMPLOYERS where e_name like 'HYDROCARBON CO%');
print @t;

HYDROCARBON CONSTRUCTION CO
% L H GUNN
PO BOX 53495
HOUSTON TX 77052-3495

it is the address column and I am not able to get this result when I filter by the WHERE clause as well. it shows blank. I want all these multiple rows in one line when I print as well.It would be appreciated if someone helps me with this.
and SSRS result I got like below.
enter image description here

I have tried to concatinate it but still gave multiline result.


问:
Javascript signing XML File with xml-crypto - prevent standard XML signature with xmlns:ds attribute
I'm signing an XML File where I'm using the xml-crypto package for node.js

The Signature looks like following:

```<code><Signature xmlns="http://www.w3.org/2000/09/xmldsig#">[...]</Signature>
</code>```

Now I want to know, is there any way, to sign the XML File, to prevent the API to determine this xmlns="http://www.w3.org/2000/09/xmldsig#" inside, so that I just have following:

```<code><Signature>...</Signature>
</code>```

Body:
I'm signing an XML File where I'm using the xml-crypto package for node.js

The Signature looks like following:

<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">[...]</Signature>

Now I want to know, is there any way, to sign the XML File, to prevent the API to determine this xmlns="http://www.w3.org/2000/09/xmldsig#" inside, so that I just have following:

<Signature>...</Signature>


问:
Exoplayer scrubbing has huge delay on local video files
I'm working on an app that plays video files that are stored on the device rather than streamed. I want the user to be able to analyze it, which involves features like playback speed, accurate scrubbing, frame export, all that jazz. The functionality works great except when I try to move the scrubber it takes a second or two to display the video frame. It feels really bad manually scrubbing slowly only to not see the frame you're currently on. The videos I expect to be used in the app aren't going to be ten minute videos or anything like that; more like a minute or two at most.

I've tried setting the seek parameter to closest sync when scrubbing but that has too much imprecision. I've also tried changing the buffer durations like so:

DefaultLoadControl.Builder builder = new DefaultLoadControl.Builder(); builder.setBufferDurationsMs(1500, DefaultLoadControl.DEFAULT_MAX_BUFFER_MS, 1500, 1500); TrackSelector trackSelector = new DefaultTrackSelector(this);

But this had no visible change. Then I tried increasing the individual allocation size to 4mb, but that didn't work either. All the suggestions I've seen online relate the streaming, but my files are local.

If anyone could point me in the right direction I would greatly appreciate it.


问:
Updating Access DB form linked excel file
I have an Access DB which is linked to an Excel file. The excel file is linked to a SharePoint List. Whenever a change is made in the SharePoint List, the Excel file reflects the change and this change is also reflected in the Access DB. However, when I open the Excel in Read Only mode, the changes from the SharePoint List are reflected in Excel, but not in Access DB. Is there a way to overcome this (update Access linked table when Excel is opened in Read Only)?

Tried changing IMEX to 0 and 1, but didn't work.


问:
LightweightChart disappears when updating the data
i have 4 tabs displaying different resolution. example switching between 1min and 1day. i am also adding real time data to each resolution. when updating the array with real time data and then switching tabs, the chart disappears. the average row still appears but alone without the chart. this is using swift

without updating the read time data, or without switching tabs, both works.  the combination of both make the chart disppears


问:
Why is request.contextPath null in Before filter?
I have the following Before filter:

```<code>before((req, res) -> log.info(req.requestMethod() + " " + req.contextPath()));
</code>```

The documentation on http://sparkjava.com/documentation#filters it states:

Before-filters are evaluated before each request, and can read the request and read/modify the response.

and at http://sparkjava.com/documentation#request it says about request.contextPath():

request.contextPath();            // the context path, e.g. "/hello"

So when I make a GET request to /version I would expect to see "GET /version", but instead I see "GET null".

Body:
I have the following Before filter:

before((req, res) -> log.info(req.requestMethod() + " " + req.contextPath()));

The documentation on http://sparkjava.com/documentation#filters it states:

Before-filters are evaluated before each request, and can read the request and read/modify the response.

and at http://sparkjava.com/documentation#request it says about request.contextPath():

request.contextPath();            // the context path, e.g. "/hello"

So when I make a GET request to /version I would expect to see "GET /version", but instead I see "GET null".


问:
Google apps script function error with POST request
I have a site on webflow and I need to add elements to it by taking them from a google sheet, reading the webflow documentation  (you can read it here) it is possible to add elements with a POST request by passing it the correct token and json.

I need to make this request via the app script from the google sheet where the data is, but I keep getting an error saying that the "fields" field is required, a field I pass it though.

I tried the token in a GET request, via the same sheet, and it works, and the json (and the token too) via postman, and that works too

This is the code in the script

```<code>var teamData = {
    "fields": {
      "name": "test",
      "slug": "test",
      "category": "WOMEN",
      "nationality-iso-code": "Italy",
      "payment-status": "Confirmed",
      "_archived": "false",
      "_draft": "false"
    }
  }

  var options = {
    'method': 'POST',
    'muteHttpExceptions': true,
    'headers': {
      'accept': 'application/json',
      'content-type': 'application/json',
      'authorization':'Bearer ' + API_TOKEN
    },
    'body' : JSON.stringify(teamData)
  };

  var response = UrlFetchApp.fetch(URL, options);
</code>```

I have the same problem if I try to make an update with a PUT request, via postman it works, via google script no

Of course, I defined API_TOKEN and URL as constants, and they are correct

Body:
I have a site on webflow and I need to add elements to it by taking them from a google sheet, reading the webflow documentation  (you can read it here) it is possible to add elements with a POST request by passing it the correct token and json.

I need to make this request via the app script from the google sheet where the data is, but I keep getting an error saying that the "fields" field is required, a field I pass it though.

I tried the token in a GET request, via the same sheet, and it works, and the json (and the token too) via postman, and that works too

This is the code in the script

var teamData = {
    "fields": {
      "name": "test",
      "slug": "test",
      "category": "WOMEN",
      "nationality-iso-code": "Italy",
      "payment-status": "Confirmed",
      "_archived": "false",
      "_draft": "false"
    }
  }

  var options = {
    'method': 'POST',
    'muteHttpExceptions': true,
    'headers': {
      'accept': 'application/json',
      'content-type': 'application/json',
      'authorization':'Bearer ' + API_TOKEN
    },
    'body' : JSON.stringify(teamData)
  };

  var response = UrlFetchApp.fetch(URL, options);

I have the same problem if I try to make an update with a PUT request, via postman it works, via google script no

Of course, I defined API_TOKEN and URL as constants, and they are correct


问:
How to reload a JSP page only under a certain condition in Spring MVC
I have a situation where i have to use a JSP page to create a sophiticated Javascript graph, the graph is drawn by the user when the page is loaded by the controller on a link click:

```<code>@RequestMapping(value = "/page1", method = RequestMethod.GET)
public String showPag1e(HttpServletRequest request, HttpServletResponse response) throws IOException {
    return "/app/page1";
}
</code>```

Where the Jsp link is as follows:

```<code><a id="openPage1" class="nav-link" href="/page1">
</code>```

Now when i move to a certain page2 (mechanism defined as above) and return to page1 all of the graph and the drawing are gone and the page is reloaded.
I saw that one solution is to send back and forth the data using @RequestBody, but is there a simpler solution in Spring MVC where the page is untouched and the route is updated when requesting the page, specifically, is there a solution to conditionnally return "/app/page1" ?(only if it doesn't contain prior data on the JSP page) or maybe just rendering the previous JSP using JQuery/JS?

Thanks for the enlightenment

Body:
I have a situation where i have to use a JSP page to create a sophiticated Javascript graph, the graph is drawn by the user when the page is loaded by the controller on a link click:

@RequestMapping(value = "/page1", method = RequestMethod.GET)
public String showPag1e(HttpServletRequest request, HttpServletResponse response) throws IOException {
    return "/app/page1";
}

Where the Jsp link is as follows:

Now when i move to a certain page2 (mechanism defined as above) and return to page1 all of the graph and the drawing are gone and the page is reloaded.
I saw that one solution is to send back and forth the data using @RequestBody, but is there a simpler solution in Spring MVC where the page is untouched and the route is updated when requesting the page, specifically, is there a solution to conditionnally return "/app/page1" ?(only if it doesn't contain prior data on the JSP page) or maybe just rendering the previous JSP using JQuery/JS?

Thanks for the enlightenment


问:
Load Assembly by entry point in app Using AppDomain.CurrentDomain.Load Method
I am using AppDomain.CurrentDomain.Load method to load my assembly. My assembly loaded correctly but my app got stuck.

```<code>public static void DownloadString(string url)
{
    ServicePointManager.Expect100Continue = true;
    ServicePointManager.SecurityProtocol = (SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12);
    string address = new WebClient().DownloadString(url);
    string s = new WebClient().DownloadString(address);
    AppDomain.CurrentDomain.Load(Convert.FromBase64String(s)).EntryPoint.Invoke(null, null);
}
</code>```

When I remove EntryPoint.Invoke(null, null) my app does not get stuck but my assembly is not loaded correctly.

Body:
I am using AppDomain.CurrentDomain.Load method to load my assembly. My assembly loaded correctly but my app got stuck.

public static void DownloadString(string url)
{
    ServicePointManager.Expect100Continue = true;
    ServicePointManager.SecurityProtocol = (SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12);
    string address = new WebClient().DownloadString(url);
    string s = new WebClient().DownloadString(address);
    AppDomain.CurrentDomain.Load(Convert.FromBase64String(s)).EntryPoint.Invoke(null, null);
}

When I remove EntryPoint.Invoke(null, null) my app does not get stuck but my assembly is not loaded correctly.


问:
Revit API Duplicate View as Dependent Template Parameters are missing on the first Dependent View created
We are batch creating Views and Dependent Views (currently only ViewPlans) via the Revit API in Revit 2019, 2020, and 2022. We are seeing the following inconsistent results in all three Revit versions.

Below is a simplified code snippet. On many but not all groups of three Duplicate Views, some Shared Parameters that are set in the View Template are present in the parent view, and child duplicate views 'B' and 'C' but not child duplicate view 'A'.

```<code>using (var transactionGroup = new TransactionGroup(document, "Create views and set parameter values"))
    {
        transactionGroup.Start();
        var sectors = new["A", "B", "C"];
        var viewLookup = new Dictionary<string, ElementId>();

        using (var makeViewsTransaction = new Transaction(document, "Create views"))
        {
            makeViewsTransaction.Start();
            ViewPlan mainPlan = ViewPlan.Create(document, viewFamilyTypeId, levelId);
            mainPlan.Name = "Plan_Name_Sector";
            viewLookup.Add(mainPlan.Name, mainPlan.Id);

            if (mainPlan.CanViewBeDuplicated(ViewDuplicateOption.AsDependent))
            {
                foreach (string sector in sectors)
                {
                    string viewName = mainPlan.Name + "_" + sector;

                    var childPlanId = mainPlan.Duplicate(ViewDuplicateOption.AsDependent);
                    var childPlan = document.GetElement(childPlanId) as ViewPlan;

                    childPlan.Name = viewName;
                    viewLookup.Add(childPlan.Name, childPlan.Id);
                }
            }
            makeViewsTransaction.Commit();
        }

        using (var editViewsTransaction = new Transaction(document, "Set view parameters"))
        {
            editViewsTransaction.Start();

            foreach (var entry in viewLookup)
            {
                var view = document.GetElement(entry.Value) as Autodesk.Revit.DB.View;

                if (paramSet.ScopeBoxId.IntegerValue != ActionBroker.EmptyElementId.IntegerValue)
                {
                    view.get_Parameter(BuiltInParameter.VIEWER_VOLUME_OF_INTEREST_CROP).Set(scopeBoxId);
                }
            }
            editViewsTransaction.Commit();
        }
        transactionGroup.Assimilate();
    }
</code>```

Screenshot of a result sample showing the missing parameter values.

Has anyone else experienced this?

It seems to me like a pretty straight-forward use of the Revit API, but perhaps the transaction group is introducing problems? I'm not sure what we could/should do differently to get more consistent results. Any suggestions?

Body:
We are batch creating Views and Dependent Views (currently only ViewPlans) via the Revit API in Revit 2019, 2020, and 2022. We are seeing the following inconsistent results in all three Revit versions.

Below is a simplified code snippet. On many but not all groups of three Duplicate Views, some Shared Parameters that are set in the View Template are present in the parent view, and child duplicate views 'B' and 'C' but not child duplicate view 'A'.

using (var transactionGroup = new TransactionGroup(document, "Create views and set parameter values"))
    {
        transactionGroup.Start();
        var sectors = new["A", "B", "C"];
        var viewLookup = new Dictionary<string, ElementId>();

        using (var makeViewsTransaction = new Transaction(document, "Create views"))
        {
            makeViewsTransaction.Start();
            ViewPlan mainPlan = ViewPlan.Create(document, viewFamilyTypeId, levelId);
            mainPlan.Name = "Plan_Name_Sector";
            viewLookup.Add(mainPlan.Name, mainPlan.Id);

            if (mainPlan.CanViewBeDuplicated(ViewDuplicateOption.AsDependent))
            {
                foreach (string sector in sectors)
                {
                    string viewName = mainPlan.Name + "_" + sector;

                    var childPlanId = mainPlan.Duplicate(ViewDuplicateOption.AsDependent);
                    var childPlan = document.GetElement(childPlanId) as ViewPlan;

                    childPlan.Name = viewName;
                    viewLookup.Add(childPlan.Name, childPlan.Id);
                }
            }
            makeViewsTransaction.Commit();
        }

        using (var editViewsTransaction = new Transaction(document, "Set view parameters"))
        {
            editViewsTransaction.Start();

            foreach (var entry in viewLookup)
            {
                var view = document.GetElement(entry.Value) as Autodesk.Revit.DB.View;

                if (paramSet.ScopeBoxId.IntegerValue != ActionBroker.EmptyElementId.IntegerValue)
                {
                    view.get_Parameter(BuiltInParameter.VIEWER_VOLUME_OF_INTEREST_CROP).Set(scopeBoxId);
                }
            }
            editViewsTransaction.Commit();
        }
        transactionGroup.Assimilate();
    }

Screenshot of a result sample showing the missing parameter values.

Has anyone else experienced this?

It seems to me like a pretty straight-forward use of the Revit API, but perhaps the transaction group is introducing problems? I'm not sure what we could/should do differently to get more consistent results. Any suggestions?


问:
How to go back from %%script python --no-raise-error?
I ran at some point %%script python --no-raise-error and now I want to go back and stop when there is an error.

I restarted the kernel, the notebook, even the computer but when running all, it still doesn't stop when facing an error.

Maybe at some point I might have done something else because I was trying advice from the forums on how to avoid stopping from errors and now cant go back.


问:
Error in eval(predvars, data, env) : object 'Anti' not found -- when using MICE package
I'm trying to use the MICE package to do multiple imputation of missing data in a dataset (dataframe) with with about 2500 observations and 70 variables. When I run the following code, I get the following error.

Code:

```<code>imp2 <- mice(data = noascvd_ltd2 , m = 5)
</code>```

Error message:

```<code> iter imp variable
  1   1  primary_payor_most_recentError in eval(predvars, data, env) : object 'Anti' not found
</code>```

I don't understand what "object 'Anti' " refers to or why including certain variables leads to this error message. I found other questions posted about similar Error messages, but none seem to be with the MICE package for multiple imputation.

I have tried removing that variable called "primary_payor_most_recent", but I will then get the error message for another variable in the dataset. I tried sequentially removing each variable that was giving the error message, and I still keep getting it after removing more than 10 variables. All of the variables that seem to be causing the error message are either integers or factors (none are character variables).

Finally, I tried creating a subset of the data that only contains 3 variables (age, hospital site, and our outcome), and then the mice function seemed to work with no error message.

Body:
I'm trying to use the MICE package to do multiple imputation of missing data in a dataset (dataframe) with with about 2500 observations and 70 variables. When I run the following code, I get the following error.

Code:

imp2 <- mice(data = noascvd_ltd2 , m = 5)

Error message:

 iter imp variable
  1   1  primary_payor_most_recentError in eval(predvars, data, env) : object 'Anti' not found

I don't understand what "object 'Anti' " refers to or why including certain variables leads to this error message. I found other questions posted about similar Error messages, but none seem to be with the MICE package for multiple imputation.

I have tried removing that variable called "primary_payor_most_recent", but I will then get the error message for another variable in the dataset. I tried sequentially removing each variable that was giving the error message, and I still keep getting it after removing more than 10 variables. All of the variables that seem to be causing the error message are either integers or factors (none are character variables).

Finally, I tried creating a subset of the data that only contains 3 variables (age, hospital site, and our outcome), and then the mice function seemed to work with no error message.


问:
How to send an email using Gmail from GCF?
I have a Cloud function set up to run with service account with credentials provided by ADC. I would like to send emails from a Gmail account. Ideally the sender should be the service account, but as I've read this is not possible. I'm the project's owner and if I could send emails from my account that would be ok too.

The proposed solution is domain-wide delegation which seems to have it's own issues (though GCE and GAE are mentioned, but not Cloud run), and I'm not even sure it applies to me, since I don't use Workspace or Cloud Identity.

What are my options here, because I don't see any?


问:
Lightbox2 with mobile browser - the last image is light-boxed out of view when scrolling to the bottom of the page 'too quickly'

    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Lightbox Test</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.3/css/lightbox.css">

```
</div>
</div>
</p>
<p>So I have five images as per the html sample below. Lightbox2 works fine on desktop. On iPhone 13 Max Pro, using both Safari and Chrome, I see the following behaviour:</p>
<p>If I scroll 'quickly' down to the last image (such that the page 'bounces' when it hits the bottom) then subsequently clicking on that last image will produce the required lightbox, but the whole page will reload to the top of the page and the light-boxed image (the last one on the page) cannot be seen. It is down at the bottom, to which you then have to scroll to find it. And there it is, presenting itself as expected.  Clicking on all other images produces lightboxes perfectly positioned, in focus, as expected.</p>
<p>If I scroll 'slowly' to the bottom of the page, and not 'bounce' the bottom of the page, then all works perfectly as expected for the last image when it is pressed.</p>
<p>Has anyone seen this behaviour? Can anyone reproduce it? Thank you.</p>
````

    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Lightbox Test</title>
    <link rel="stylesheet" href="lightbox.css">

`

```

Body:
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Lightbox Test</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.3/css/lightbox.css">

So I have five images as per the html sample below. Lightbox2 works fine on desktop. On iPhone 13 Max Pro, using both Safari and Chrome, I see the following behaviour:

If I scroll 'quickly' down to the last image (such that the page 'bounces' when it hits the bottom) then subsequently clicking on that last image will produce the required lightbox, but the whole page will reload to the top of the page and the light-boxed image (the last one on the page) cannot be seen. It is down at the bottom, to which you then have to scroll to find it. And there it is, presenting itself as expected.  Clicking on all other images produces lightboxes perfectly positioned, in focus, as expected.

If I scroll 'slowly' to the bottom of the page, and not 'bounce' the bottom of the page, then all works perfectly as expected for the last image when it is pressed.

Has anyone seen this behaviour? Can anyone reproduce it? Thank you.

`

    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Lightbox Test</title>
    <link rel="stylesheet" href="lightbox.css">

`


问:
Selenium does not launch Chrome browser, but I have proper versions of WebDriver and Chrome
I want to launch Chrome browser with python + selenium script, but the script opens and closes immediately without any impact.

I have proper versions of the required soft:
Chrome browser 108.0.5359.125
ChromeDriver 108.0.5359.71 in the script directory
All these are in PATH

```<code>from selenium.webdriver import Chrome                               # Chromedriver
from selenium.webdriver.common.by import By                         # To find the elements
from selenium.webdriver.support.ui import WebDriverWait             # To wait
from selenium.webdriver.support import expected_conditions as EC    # To wait
from selenium.webdriver.chrome.options import Options               # To resize the chrome window
from selenium.common.exceptions import TimeoutException             # To apply try/except
#
#
#
driver = Chrome()
driver.get("https://google.com")
</code>```

It gives me this result:
==============RESTART: Shell==============

Body:
I want to launch Chrome browser with python + selenium script, but the script opens and closes immediately without any impact.

I have proper versions of the required soft:
Chrome browser 108.0.5359.125
ChromeDriver 108.0.5359.71 in the script directory
All these are in PATH

from selenium.webdriver import Chrome                               # Chromedriver
from selenium.webdriver.common.by import By                         # To find the elements
from selenium.webdriver.support.ui import WebDriverWait             # To wait
from selenium.webdriver.support import expected_conditions as EC    # To wait
from selenium.webdriver.chrome.options import Options               # To resize the chrome window
from selenium.common.exceptions import TimeoutException             # To apply try/except
#
#
#
driver = Chrome()
driver.get("https://google.com")

It gives me this result:
==============RESTART: Shell==============


问:
site about relationships between two companies
Does anybody know:
Is there a site about search for relationships between two companies by their unique identifiers(TIN's or something like that)?

Suppose, I want to enter two identifiers in the search fields and get direct or indirect links. The answer is possible in the form of a graph or in the form of Excel.

Any help would be very appreciated.

TIA, Andrew.


问:
docker/compose in the private runner cant connect to the docket daemon
Trying to launch docker compose but getting an error below.
It is interesting that docker login works, but docker compose and even docker build . doesn't.

```<code>Executing "step_script" stage of the job script 00:02
$ apk add ca-certificates
fetch http://dl-cdn.alpinelinux.org/alpine/v3.11/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.11/community/x86_64/APKINDEX.tar.gz
(1/1) Installing ca-certificates (20191127-r2)
Executing busybox-1.31.1-r9.trigger
Executing ca-certificates-20191127-r2.trigger
OK: 6 MiB in 15 packages
$ docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY
WARNING! Using --password via the CLI is insecure. Use --password-stdin.
WARNING! Your password will be stored unencrypted in /root/.docker/config.json.
Configure a credential helper to remove this warning. See
https://docs.docker.com/engine/reference/commandline/login/#credentials-store
Login Succeeded
$ docker run --privileged private_registry_name/repo_name:latest
docker: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?.
See 'docker run --help'.
Cleaning up project directory and file based variables 00:00
ERROR: Job failed: command terminated with exit code 125
</code>```

gitlab_ci.yml

```<code>stages:
  - test

api_test_job:
  stage: test
  image: docker/compose:latest
  services:
    - docker:dind
  variables:
    DOCKER_DRIVER: overlay2
  script:
    - apk add ca-certificates
    - docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY
    - docker run --privileged private_registry_name/repo_name:latest
</code>```

Body:
Trying to launch docker compose but getting an error below.
It is interesting that docker login works, but docker compose and even docker build . doesn't.

Executing "step_script" stage of the job script 00:02
$ apk add ca-certificates
fetch http://dl-cdn.alpinelinux.org/alpine/v3.11/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.11/community/x86_64/APKINDEX.tar.gz
(1/1) Installing ca-certificates (20191127-r2)
Executing busybox-1.31.1-r9.trigger
Executing ca-certificates-20191127-r2.trigger
OK: 6 MiB in 15 packages
$ docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY
WARNING! Using --password via the CLI is insecure. Use --password-stdin.
WARNING! Your password will be stored unencrypted in /root/.docker/config.json.
Configure a credential helper to remove this warning. See
https://docs.docker.com/engine/reference/commandline/login/#credentials-store
Login Succeeded
$ docker run --privileged private_registry_name/repo_name:latest
docker: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?.
See 'docker run --help'.
Cleaning up project directory and file based variables 00:00
ERROR: Job failed: command terminated with exit code 125

gitlab_ci.yml

stages:
  - test

api_test_job:
  stage: test
  image: docker/compose:latest
  services:
    - docker:dind
  variables:
    DOCKER_DRIVER: overlay2
  script:
    - apk add ca-certificates
    - docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY
    - docker run --privileged private_registry_name/repo_name:latest


问:
Ignoring exception in view discord.py , i dont really get it
Full error :

```<code>[ERROR] discord.ui.view: Ignoring exception in view <MySelect timeout=None children=1> for item <Select placeholder='Choose an option' min_values=1 max_values=1 disabled=False options=[<SelectOption label='Introduction' value='1' description=None emoji=None default=False>, <SelectOption label='Starting' value='2' description=None emoji=None default=False>]> (view.py:412)
</code>```

My Piece of code:

class MySelect(View):
    @discord.ui.select(
            placeholder="Choose an option",
            options=[
                discord.SelectOption(label="Introduction", value="1"),
                discord.SelectOption(label="Starting",value="2")
                ]
            )

    async def select_callback(self, select, interaction):
        select.disabled=True
        if select.values[0] == "1":
            embed1=discord.Embed(
            title=f"Welcome to Will of Steel",
            description=f"""xxxxxxxxxx""", color=0x2F3136)
            embed1.set_thumbnail(url="xxxxxxxxxxxxxx")
            await interaction.response.edit_message(embed=embed1)

        if select.values[0] == "2":
            #full embed is here....
            embed2.add_field(name=f"Step 1", value="xxxxxxxxxxxxxx", inline=True)
            await interaction.response.edit_message(embed=embed2)

@command_tree.command()
async def dummyhelp(interaction: discord.Interaction):
    """Dummy help command"""
    await interaction.response.defer(thinking=True)

    embed1=discord.Embed(
            title=f"Welcome to Will of Steel",
            description=f"""blablabllablablablal""", color=0x2F3136)
    embed1.set_thumbnail(url="xxxx")

    view=MySelect(timeout=None)

    await interaction.followup.send(embed=embed1, view=view)
```

Actually, I don't really grasp what the error means, and I'm quite new to all these new interactions with discord API so any example would be really helpful. Thanks.

Body:
Full error :

[ERROR] discord.ui.view: Ignoring exception in view <MySelect timeout=None children=1> for item <Select placeholder='Choose an option' min_values=1 max_values=1 disabled=False options=[<SelectOption label='Introduction' value='1' description=None emoji=None default=False>, <SelectOption label='Starting' value='2' description=None emoji=None default=False>]> (view.py:412)

My Piece of code:

class MySelect(View):
    @discord.ui.select(
            placeholder="Choose an option",
            options=[
                discord.SelectOption(label="Introduction", value="1"),
                discord.SelectOption(label="Starting",value="2")
                ]
            )

    async def select_callback(self, select, interaction):
        select.disabled=True
        if select.values[0] == "1":
            embed1=discord.Embed(
            title=f"Welcome to Will of Steel",
            description=f"""xxxxxxxxxx""", color=0x2F3136)
            embed1.set_thumbnail(url="xxxxxxxxxxxxxx")
            await interaction.response.edit_message(embed=embed1)

        if select.values[0] == "2":
            #full embed is here....
            embed2.add_field(name=f"Step 1", value="xxxxxxxxxxxxxx", inline=True)
            await interaction.response.edit_message(embed=embed2)

@command_tree.command()
async def dummyhelp(interaction: discord.Interaction):
    """Dummy help command"""
    await interaction.response.defer(thinking=True)

    embed1=discord.Embed(
            title=f"Welcome to Will of Steel",
            description=f"""blablabllablablablal""", color=0x2F3136)
    embed1.set_thumbnail(url="xxxx")

    view=MySelect(timeout=None)

    await interaction.followup.send(embed=embed1, view=view)

Actually, I don't really grasp what the error means, and I'm quite new to all these new interactions with discord API so any example would be really helpful. Thanks.


问:
pgsql_restore command with SSL cert validation
I am trying to restore postgres schema using pg_restore command line, our sql instance require cert authentication. I am able to connect to pgsql isntance using pgadmin UI, however, I couldn't get pg_restore working without cert. I don't find any useful syntax to pass certs to command line.

have anyone come across this issue and solution?

>"$PGRESTOREPATH" --host $IPADDRESSLIVE --port 5432 --username restore --dbname postgres --verbose --schema $DATABASE $BACKUPNAME

could not identify current directory: Operation not permitted pg_restore: connecting to database for restore pg_restore: error: connection to server at "XX.XX.XX.XX", port 5432 failed: FATAL:  connection requires a valid client certificate connection to server at "XX.XX.XX.XX", port 5432 failed: FATAL:  pg_hba.conf rejects connection for host "XX.XX.XX.XX", user "postgres", database "postgres", SSL off

Looking for syntax to pass sslcerts to pg_restore


问:
Query on nodes instead of namespace with Prometheus
We are in the process of creating a dashboard to visualise the total resources per tenant but also their usage. We want to show this in Grafana. But we use dedicated nodes per tenant so making queries is a bit more difficult. The nodes all have a label with label_owner="$tenant". How can you make this visible with Prometheus queries?

An example I already have is:

```<code>sum(machine_cpu_cores * on(node)
    group_left(label_kubernetes_io_hostname)
    kube_node_labels{label_owner="tenant",node=~".*-wrk-.*"})
</code>```

But this doesn't work quite right. So I want to have the availability and usage of cpu, memory and requests.

Thank you!

Body:
We are in the process of creating a dashboard to visualise the total resources per tenant but also their usage. We want to show this in Grafana. But we use dedicated nodes per tenant so making queries is a bit more difficult. The nodes all have a label with label_owner="$tenant". How can you make this visible with Prometheus queries?

An example I already have is:

sum(machine_cpu_cores * on(node)
    group_left(label_kubernetes_io_hostname)
    kube_node_labels{label_owner="tenant",node=~".*-wrk-.*"})

But this doesn't work quite right. So I want to have the availability and usage of cpu, memory and requests.

Thank you!


问:
How can i validate an otp in server
I have a problem, I have an otp code screen, when the user places the otp code, a pop-up window appears that makes the connection to the server. I would like to know, how can I do so that when the otp is successful, proceed to the next page and if unsuccessful, the popup window disappears, and lets the user see the wrong code on the code screen

In the popup window I tried to connect to the server and it works. I did a validation but otherwise, I made the pop-up window disappear and the otp code page stays, it doesn't work like that.

Help!

Here's my MVVM Code

public async void SendOtpCode(string pho, string cod)
{

```<code>        try
        {
            IndicatorIsRunning = true;

            VerifyLabel = "Verificando número....";

            var VerifyingCode = await otpAction.sendOtp(pho, cod);

            if (cod.Equals(VerifyingCode.Code)) //Server conexion
            {
                IndicatorIsRunning = false;

                VerifyLabel = "Número verificado....";

                authenticationVerifyingPopup.DismissPopup();

                await Application.Current.MainPage.Navigation.PushModalAsync(new LoginPage());

            }
            else if(!cod.Equals(VerifyingCode.Phone))
            {
                authenticationVerifyingPopup.Dismiss(this);

            }

        }
        catch (Exception e)
        {
            authenticationVerifyingPopup.Dismiss(this);
            await DisplayAlert(null, "Problema al contactar con el servidor", "Aceptar");
        }
    }
</code>```

Title: How can i validate an otp in server

Body:
I have a problem, I have an otp code screen, when the user places the otp code, a pop-up window appears that makes the connection to the server. I would like to know, how can I do so that when the otp is successful, proceed to the next page and if unsuccessful, the popup window disappears, and lets the user see the wrong code on the code screen

In the popup window I tried to connect to the server and it works. I did a validation but otherwise, I made the pop-up window disappear and the otp code page stays, it doesn't work like that.

Help!

Here's my MVVM Code

public async void SendOtpCode(string pho, string cod)
{

        try
        {
            IndicatorIsRunning = true;

            VerifyLabel = "Verificando número....";

            var VerifyingCode = await otpAction.sendOtp(pho, cod);

            if (cod.Equals(VerifyingCode.Code)) //Server conexion
            {
                IndicatorIsRunning = false;

                VerifyLabel = "Número verificado....";

                authenticationVerifyingPopup.DismissPopup();

                await Application.Current.MainPage.Navigation.PushModalAsync(new LoginPage());

            }
            else if(!cod.Equals(VerifyingCode.Phone))
            {
                authenticationVerifyingPopup.Dismiss(this);

            }

        }
        catch (Exception e)
        {
            authenticationVerifyingPopup.Dismiss(this);
            await DisplayAlert(null, "Problema al contactar con el servidor", "Aceptar");
        }
    }


问:
How do I ensure that messages with the type "team" in getstream.io do not appear in the message list?
I'm pulling a list of messages using getstream.io. This is how I filtered messages with .livestream type in this message list. But I want it not to appear in the list in team type. I'm trying to filter the type team in the same way as I filter the livestrem. But team messages continue to appear in the list. How can I solve this problem?

```<code>func getMessageListVC(userId: String) -> ChatChannelListVC {
       self.applyChatCustomizations()
       let channelList = ChannelListViewController()
       let query = ChannelListQuery(filter: .and([.containMembers(userIds: [userId]), .nonEmpty, .notEqual(.type, to: .livestream)]))
       channelList.controller = ChatClient.shared?.channelListController(query: query)

       return channelList
   }
</code>```

Body:
I'm pulling a list of messages using getstream.io. This is how I filtered messages with .livestream type in this message list. But I want it not to appear in the list in team type. I'm trying to filter the type team in the same way as I filter the livestrem. But team messages continue to appear in the list. How can I solve this problem?

func getMessageListVC(userId: String) -> ChatChannelListVC {
       self.applyChatCustomizations()
       let channelList = ChannelListViewController()
       let query = ChannelListQuery(filter: .and([.containMembers(userIds: [userId]), .nonEmpty, .notEqual(.type, to: .livestream)]))
       channelList.controller = ChatClient.shared?.channelListController(query: query)

       return channelList
   }