问:
KeyError when trying to fine tuning Bert for text classification
I am trying to fine tune Bert for text classification on my dataset and I am getting the following error:

```<code>KeyError: 'Indexing with integers (to access backend Encoding for a given batch index) is not available when using Python based tokenizers'

</code>```

Here is the full error:

```<code>1/1 * Epoch (train):   0% 0/613 [00:00<?, ?it/s]Traceback (most recent call last):
  File "train.py", line 47, in <module>
    runner.train(
  File "/usr/local/lib/python3.8/dist-packages/catalyst/runners/runner.py", line 377, in train
    self.run()
  File "/usr/local/lib/python3.8/dist-packages/catalyst/core/runner.py", line 422, in run
    self._run_event("on_exception")
  File "/usr/local/lib/python3.8/dist-packages/catalyst/core/runner.py", line 365, in _run_event
    getattr(self, event)(self)
  File "/usr/local/lib/python3.8/dist-packages/catalyst/core/runner.py", line 357, in on_exception
    raise self.exception
  File "/usr/local/lib/python3.8/dist-packages/catalyst/core/runner.py", line 419, in run
    self._run()
  File "/usr/local/lib/python3.8/dist-packages/catalyst/core/runner.py", line 410, in _run
    self.engine.spawn(self._run_local)
  File "/usr/local/lib/python3.8/dist-packages/catalyst/core/engine.py", line 59, in spawn
    return fn(*args, **kwargs)
  File "/usr/local/lib/python3.8/dist-packages/catalyst/core/runner.py", line 405, in _run_local
    self._run_experiment()
  File "/usr/local/lib/python3.8/dist-packages/catalyst/core/runner.py", line 399, in _run_experiment
    self._run_epoch()
  File "/usr/local/lib/python3.8/dist-packages/catalyst/core/runner.py", line 391, in _run_epoch
    self._run_loader()
  File "/usr/local/lib/python3.8/dist-packages/catalyst/core/runner.py", line 384, in _run_loader
    self._run_event("on_batch_start")
  File "/usr/local/lib/python3.8/dist-packages/catalyst/core/runner.py", line 361, in _run_event
    getattr(self, event)(self)
  File "/usr/local/lib/python3.8/dist-packages/catalyst/runners/supervised.py", line 150, in on_batch_start
    super().on_batch_start(runner)
  File "/usr/local/lib/python3.8/dist-packages/catalyst/core/runner.py", line 321, in on_batch_start
    self.batch_size = len(self.batch[0])
  File "/usr/local/lib/python3.8/dist-packages/transformers/tokenization_utils_base.py", line 241, in __getitem__
    raise KeyError(
KeyError: 'Indexing with integers (to access backend Encoding for a given batch index) is not available when using Python based tokenizers'
</code>```

The code I am using for data preparation:

```<code>import logging
from pathlib import Path
from typing import List, Mapping, Tuple

import pandas as pd
import torch
from catalyst.utils import set_global_seed
from torch.utils.data import DataLoader, Dataset
from transformers import AutoTokenizer

class TextClassificationDataset(Dataset):
    """
    Wrapper around Torch Dataset to perform text classification
    """

    def __init__(
        self,
        texts: List[str],
        labels: List[str] = None,
        label_dict: Mapping[str, int] = None,
        max_seq_length: int = 512,
        model_name: str = "GroNLP/hateBERT",
    ):
        """
        Args:
            texts (List[str]): a list with texts to classify or to train the
                classifier on
            labels List[str]: a list with classification labels (optional)
            label_dict (dict): a dictionary mapping class names to class ids,
                to be passed to the validation data (optional)
            max_seq_length (int): maximal sequence length in tokens,
                texts will be stripped to this length
            model_name (str): transformer model name, needed to perform
                appropriate tokenization

        """

        self.texts = texts
        self.labels = labels
        self.label_dict = label_dict
        self.max_seq_length = max_seq_length

        if self.label_dict is None and labels is not None:
            # {'class1': 0, 'class2': 1, 'class3': 2, ...}
            # no easily handle unknown target values
            self.label_dict = dict(zip(sorted(set(labels)), range(len(set(labels)))))

        self.tokenizer = AutoTokenizer.from_pretrained(model_name)
        # suppresses tokenizer warnings
        logging.getLogger("transformers.tokenization_utils").setLevel(logging.FATAL)

    def __len__(self) -> int:
        """
        Returns:
            int: length of the dataset
        """
        return len(self.texts)

    def __getitem__(self, index) -> Mapping[str, torch.Tensor]:
        """Gets element of the dataset

        Args:
            index (int): index of the element in the dataset
        Returns:
            Single element by index
        """

        # encoding the text
        x = self.texts[index]

        # a dictionary with `input_ids` and `attention_mask` as keys
        output_dict = self.tokenizer.encode_plus(
            x,
            add_special_tokens=True,
            padding="max_length",
            max_length=self.max_seq_length,
            return_tensors="pt",
            truncation=True,
            return_attention_mask=True,
        )

        # for Catalyst, there needs to be a key called features
        output_dict["features"] = output_dict["input_ids"].squeeze(0)
        del output_dict["input_ids"]

        # encoding target
        if self.labels is not None:
            y = self.labels[index]
            y_encoded = torch.Tensor([self.label_dict.get(y, -1)]).long().squeeze(0)
            output_dict["targets"] = y_encoded

        return output_dict
</code>```

What is the problem?

I know questions about similar error have been already asked but they were not of much help in solving this problem.

Body:
I am trying to fine tune Bert for text classification on my dataset and I am getting the following error:

KeyError: 'Indexing with integers (to access backend Encoding for a given batch index) is not available when using Python based tokenizers'

Here is the full error:

1/1 * Epoch (train):   0% 0/613 [00:00<?, ?it/s]Traceback (most recent call last):
  File "train.py", line 47, in <module>
    runner.train(
  File "/usr/local/lib/python3.8/dist-packages/catalyst/runners/runner.py", line 377, in train
    self.run()
  File "/usr/local/lib/python3.8/dist-packages/catalyst/core/runner.py", line 422, in run
    self._run_event("on_exception")
  File "/usr/local/lib/python3.8/dist-packages/catalyst/core/runner.py", line 365, in _run_event
    getattr(self, event)(self)
  File "/usr/local/lib/python3.8/dist-packages/catalyst/core/runner.py", line 357, in on_exception
    raise self.exception
  File "/usr/local/lib/python3.8/dist-packages/catalyst/core/runner.py", line 419, in run
    self._run()
  File "/usr/local/lib/python3.8/dist-packages/catalyst/core/runner.py", line 410, in _run
    self.engine.spawn(self._run_local)
  File "/usr/local/lib/python3.8/dist-packages/catalyst/core/engine.py", line 59, in spawn
    return fn(*args, **kwargs)
  File "/usr/local/lib/python3.8/dist-packages/catalyst/core/runner.py", line 405, in _run_local
    self._run_experiment()
  File "/usr/local/lib/python3.8/dist-packages/catalyst/core/runner.py", line 399, in _run_experiment
    self._run_epoch()
  File "/usr/local/lib/python3.8/dist-packages/catalyst/core/runner.py", line 391, in _run_epoch
    self._run_loader()
  File "/usr/local/lib/python3.8/dist-packages/catalyst/core/runner.py", line 384, in _run_loader
    self._run_event("on_batch_start")
  File "/usr/local/lib/python3.8/dist-packages/catalyst/core/runner.py", line 361, in _run_event
    getattr(self, event)(self)
  File "/usr/local/lib/python3.8/dist-packages/catalyst/runners/supervised.py", line 150, in on_batch_start
    super().on_batch_start(runner)
  File "/usr/local/lib/python3.8/dist-packages/catalyst/core/runner.py", line 321, in on_batch_start
    self.batch_size = len(self.batch[0])
  File "/usr/local/lib/python3.8/dist-packages/transformers/tokenization_utils_base.py", line 241, in __getitem__
    raise KeyError(
KeyError: 'Indexing with integers (to access backend Encoding for a given batch index) is not available when using Python based tokenizers'

The code I am using for data preparation:

import logging
from pathlib import Path
from typing import List, Mapping, Tuple

import pandas as pd
import torch
from catalyst.utils import set_global_seed
from torch.utils.data import DataLoader, Dataset
from transformers import AutoTokenizer

class TextClassificationDataset(Dataset):
    """
    Wrapper around Torch Dataset to perform text classification
    """

    def __init__(
        self,
        texts: List[str],
        labels: List[str] = None,
        label_dict: Mapping[str, int] = None,
        max_seq_length: int = 512,
        model_name: str = "GroNLP/hateBERT",
    ):
        """
        Args:
            texts (List[str]): a list with texts to classify or to train the
                classifier on
            labels List[str]: a list with classification labels (optional)
            label_dict (dict): a dictionary mapping class names to class ids,
                to be passed to the validation data (optional)
            max_seq_length (int): maximal sequence length in tokens,
                texts will be stripped to this length
            model_name (str): transformer model name, needed to perform
                appropriate tokenization

        """

        self.texts = texts
        self.labels = labels
        self.label_dict = label_dict
        self.max_seq_length = max_seq_length

        if self.label_dict is None and labels is not None:
            # {'class1': 0, 'class2': 1, 'class3': 2, ...}
            # no easily handle unknown target values
            self.label_dict = dict(zip(sorted(set(labels)), range(len(set(labels)))))

        self.tokenizer = AutoTokenizer.from_pretrained(model_name)
        # suppresses tokenizer warnings
        logging.getLogger("transformers.tokenization_utils").setLevel(logging.FATAL)

    def __len__(self) -> int:
        """
        Returns:
            int: length of the dataset
        """
        return len(self.texts)

    def __getitem__(self, index) -> Mapping[str, torch.Tensor]:
        """Gets element of the dataset

        Args:
            index (int): index of the element in the dataset
        Returns:
            Single element by index
        """

        # encoding the text
        x = self.texts[index]

        # a dictionary with `input_ids` and `attention_mask` as keys
        output_dict = self.tokenizer.encode_plus(
            x,
            add_special_tokens=True,
            padding="max_length",
            max_length=self.max_seq_length,
            return_tensors="pt",
            truncation=True,
            return_attention_mask=True,
        )

        # for Catalyst, there needs to be a key called features
        output_dict["features"] = output_dict["input_ids"].squeeze(0)
        del output_dict["input_ids"]

        # encoding target
        if self.labels is not None:
            y = self.labels[index]
            y_encoded = torch.Tensor([self.label_dict.get(y, -1)]).long().squeeze(0)
            output_dict["targets"] = y_encoded

        return output_dict

What is the problem?

I know questions about similar error have been already asked but they were not of much help in solving this problem.


来源: stackexchange

问:
Use an existing type definition in a zod definition?
in lib.dom.ts there is a type definition:

```<code>type RTCSdpType = "answer" | "offer" | "pranswer" | "rollback";
</code>```

I want to create a type definition with zod, where the type references the RTCSdpType definition. Is this possible to do?

```<code>const MyType = z.object({
    t: RTCSdpType, // <--- ERROR: 'RTCSdpType' only refers to a type, but is being used as a value here.
})
</code>```

ContentLicense: CC BY-SA 4.0

Body:
in lib.dom.ts there is a type definition:

type RTCSdpType = "answer" | "offer" | "pranswer" | "rollback";

I want to create a type definition with zod, where the type references the RTCSdpType definition. Is this possible to do?

const MyType = z.object({
    t: RTCSdpType, // <--- ERROR: 'RTCSdpType' only refers to a type, but is being used as a value here.
})


问:
Rails Product model with a Recipe of other products, through join table
I have a model called Product, that represents items. What I now need is for Products to have a "Recipe" that represents a list of other products with a quantity. Basically, a Product will have many of self with X amount of it. I was thinking that creating a new table that has a recipe_id and a supply_id with an amount column would do. But I'm having trouble with the association syntax.
My new model would be:

create_table :recipe_supplies do |t|
    t.integer :supply_id
    t.integer :recipe_id
    t.decimal :amount, default: 0
end

class RecipeSupplies < ActiveRecord::Base
    belongs_to :recipe, class_name: 'Product'
    belongs_to :supply, class_name: 'Product'
end

```
<p>And so my Product model would have:</p>
<pre class="lang-ruby prettyprint-override"><code>class Product < ActiveRecord::Base
  has_many :recipe_supplies, class_name: 'RecipeSupply', foreign_key: 'recipe_id'
  has_many :supplies, through: :recipe_supplies

end
</code>```

What I need is to be able to do @product.recipe_supplies, to check supply(product) amount, but also  have an easy way of getting the supplies, like @product.supplies and get all products marked as supplies. What I can't figure out is how to do a @product.recipe, to get the recipes where @product is a supply. Or maybe there is a better way of doing this, any help is appreciated. I have the feeling I'm not on the best/most efficient path here.

2.6.5 :006 > @product.recipe_supplies
  RecipeSupply Exists (0.4ms)  SELECT  1 AS one FROM "recipe_supplies" WHERE "recipe_supplies"."recipe_id" = $1 LIMIT $2  [["recipe_id", 109], ["LIMIT", 1]]
  RecipeSupply Load (0.2ms)  SELECT "recipe_supplies".* FROM "recipe_supplies" WHERE "recipe_supplies"."recipe_id" = $1  [["recipe_id", 109]]
[
    [0] #<RecipeSupply> {
               :id => 1,
        :supply_id => 1,
        :recipe_id => 109,
           :amount => 10.5
    },
    [1] #<RecipeSupply> {
               :id => 2,
        :supply_id => 2,
        :recipe_id => 109,
           :amount => 22.3
    }
]
2.6.5 :007 > @product.supplies
  Product Exists (0.6ms)  SELECT  1 AS one FROM "products" INNER JOIN "recipe_supplies" ON "products"."id" = "recipe_supplies"."supply_id" WHERE "recipe_supplies"."recipe_id" = $1 LIMIT $2  [["recipe_id", 109], ["LIMIT", 1]]
  Product Load (0.3ms)  SELECT "products".* FROM "products" INNER JOIN "recipe_supplies" ON "products"."id" = "recipe_supplies"."supply_id" WHERE "recipe_supplies"."recipe_id" = $1  [["recipe_id", 109]]
[
    [0] #<Product> {
                                 :id => 1,
                               ...
    },
    [1] #<Product> {
                                 :id => 2,
                               ...
    }
]
```
```

```

Body:
I have a model called Product, that represents items. What I now need is for Products to have a "Recipe" that represents a list of other products with a quantity. Basically, a Product will have many of self with X amount of it. I was thinking that creating a new table that has a recipe_id and a supply_id with an amount column would do. But I'm having trouble with the association syntax.
My new model would be:

create_table :recipe_supplies do |t|
    t.integer :supply_id
    t.integer :recipe_id
    t.decimal :amount, default: 0
end

class RecipeSupplies < ActiveRecord::Base
    belongs_to :recipe, class_name: 'Product'
    belongs_to :supply, class_name: 'Product'
end

And so my Product model would have:

class Product < ActiveRecord::Base
  has_many :recipe_supplies, class_name: 'RecipeSupply', foreign_key: 'recipe_id'
  has_many :supplies, through: :recipe_supplies

end

What I need is to be able to do @product.recipe_supplies, to check supply(product) amount, but also  have an easy way of getting the supplies, like @product.supplies and get all products marked as supplies. What I can't figure out is how to do a @product.recipe, to get the recipes where @product is a supply. Or maybe there is a better way of doing this, any help is appreciated. I have the feeling I'm not on the best/most efficient path here.

2.6.5 :006 > @product.recipe_supplies
  RecipeSupply Exists (0.4ms)  SELECT  1 AS one FROM "recipe_supplies" WHERE "recipe_supplies"."recipe_id" = $1 LIMIT $2  [["recipe_id", 109], ["LIMIT", 1]]
  RecipeSupply Load (0.2ms)  SELECT "recipe_supplies".* FROM "recipe_supplies" WHERE "recipe_supplies"."recipe_id" = $1  [["recipe_id", 109]]
[
    [0] #<RecipeSupply> {
               :id => 1,
        :supply_id => 1,
        :recipe_id => 109,
           :amount => 10.5
    },
    [1] #<RecipeSupply> {
               :id => 2,
        :supply_id => 2,
        :recipe_id => 109,
           :amount => 22.3
    }
]
2.6.5 :007 > @product.supplies
  Product Exists (0.6ms)  SELECT  1 AS one FROM "products" INNER JOIN "recipe_supplies" ON "products"."id" = "recipe_supplies"."supply_id" WHERE "recipe_supplies"."recipe_id" = $1 LIMIT $2  [["recipe_id", 109], ["LIMIT", 1]]
  Product Load (0.3ms)  SELECT "products".* FROM "products" INNER JOIN "recipe_supplies" ON "products"."id" = "recipe_supplies"."supply_id" WHERE "recipe_supplies"."recipe_id" = $1  [["recipe_id", 109]]
[
    [0] #<Product> {
                                 :id => 1,
                               ...
    },
    [1] #<Product> {
                                 :id => 2,
                               ...
    }
]


问:
Creating Index ,PK, tables at runtime using FireDAC (no SQL script)
I am trying do same with FireDac as following SQL:

```<code>CREATE TABLE [Franchises]([Franchise] TEXT(100) PRIMARY KEY ASC NOT NULL UNIQUE);
CREATE UNIQUE INDEX [IFran] ON [Franchises]([Franchise] ASC);
</code>```

But i don't see index in SQLite Expert, property UNIQUE, PK. And why FireDac create table and column name in UPPERCASE?

I used code:

```<code>procedure TDataModule1.DataModuleCreate(Sender: TObject);
var
allTables:TStrings;
Table: TFDTable;
DBExists:Boolean;
begin
FDConnection1.Params.Database:= pathINI+baseTableDB;
  DBExists:=FileExists(FDConnection1.Params.Database);
  FDConnection1.Params.Values['CreateDatabase']:=BoolToStr(not DBExists,True);
  FDConnection1.Params.DriverID:='SQLite';
  FDConnection1.Connected:= True;

  allTables := TStringList.Create;
  FDConnection1.GetTableNames('', '', '', allTables, [osMy, osOther, osSystem],[tkView, tkTable, tkTempTable, tkLocalTable]);

  if allTables.IndexOf('Franchises')=-1 then
  begin
   Table := TFDTable.Create(nil);
    try
      Table.Connection := FDConnection1;
      Table.TableName := 'Franchises';
      Table.FieldDefs.Add('Franchise', ftString, 100, True);
      { define primary key index }
//      Table.IndexDefs.Add('IFran', 'Franchise',[ixPrimary]);
      Table.AddIndex('IFran', 'Franchise', '', [soPrimary,soUnique,soNoCase]);

      Table.IndexesActive:=True;
      Table.IndexName:='IFran';
      Table.CreateTable(False,[tpTable, tpPrimaryKey, tpIndexes]);
    finally
      Table.Free;
    end;
  end;
  allTables.Free;

  FDTable1.Connection:=FDConnection1;
  FDTable1.TableName:='Franchises';
  FDTable1.Open;
end;
</code>```

Body:
I am trying do same with FireDac as following SQL:

CREATE TABLE [Franchises]([Franchise] TEXT(100) PRIMARY KEY ASC NOT NULL UNIQUE);
CREATE UNIQUE INDEX [IFran] ON [Franchises]([Franchise] ASC);

But i don't see index in SQLite Expert, property UNIQUE, PK. And why FireDac create table and column name in UPPERCASE?

I used code:

procedure TDataModule1.DataModuleCreate(Sender: TObject);
var
allTables:TStrings;
Table: TFDTable;
DBExists:Boolean;
begin
FDConnection1.Params.Database:= pathINI+baseTableDB;
  DBExists:=FileExists(FDConnection1.Params.Database);
  FDConnection1.Params.Values['CreateDatabase']:=BoolToStr(not DBExists,True);
  FDConnection1.Params.DriverID:='SQLite';
  FDConnection1.Connected:= True;

  allTables := TStringList.Create;
  FDConnection1.GetTableNames('', '', '', allTables, [osMy, osOther, osSystem],[tkView, tkTable, tkTempTable, tkLocalTable]);

  if allTables.IndexOf('Franchises')=-1 then
  begin
   Table := TFDTable.Create(nil);
    try
      Table.Connection := FDConnection1;
      Table.TableName := 'Franchises';
      Table.FieldDefs.Add('Franchise', ftString, 100, True);
      { define primary key index }
//      Table.IndexDefs.Add('IFran', 'Franchise',[ixPrimary]);
      Table.AddIndex('IFran', 'Franchise', '', [soPrimary,soUnique,soNoCase]);

      Table.IndexesActive:=True;
      Table.IndexName:='IFran';
      Table.CreateTable(False,[tpTable, tpPrimaryKey, tpIndexes]);
    finally
      Table.Free;
    end;
  end;
  allTables.Free;

  FDTable1.Connection:=FDConnection1;
  FDTable1.TableName:='Franchises';
  FDTable1.Open;
end;


问:
Eleventy / Nunjucks: minify JS with terser within minified HTML
I try to minify partial HTML in which I minify some JS using terser (using a jsmin filter as showed in 11ty docs):

<!doctype html>
<meta charset="utf-8"><title></title>
{% set html %}

        Bar

{% endset %}
{{ html | htmlmin | safe }}

```
<p>But since the terser process is asynchronous, it throws an error in 11ty (<em>callback is not a function</em>, and <code><script>[object Promise]</script></code> in the generated file).</p>
<p>Same problem if I try to minify all the HTML using an 11ty <em>transform</em> (as suggested in their docs: <em>Minify HTML Output</em> – and removing all the <code>{% set html %}</code> / <code>{{ html | … }}</code> tags): it throws some similar Promise errors (<em>Having trouble writing template … Cannot read properties of undefined … at async Promise.all</em>)</p>
<p>Problem solved if I move the script part outside of the Nunjucks set declaration:</p>
<pre class="lang-html prettyprint-override"><code><!doctype html>
<html lang="fr"><head><meta charset="utf-8"><title></title></head>
{% set html %}
<body>
    <div class="foo">
        Bar
    </div>
{% endset %}
{{ html | htmlmin | safe }}
    <script>{% set js %}
        var foo = 'foo',
            bar = 'bar';
    {% endset %}{{ js | jsmin | safe }}</script>
</body>
</html>
</code>```

But that's not what I want.

Trying to make terser synchronous seems to need some more npm packages so I'm hoping there's an easier way before trying it.

Edit: tried to use html-minifier-terser instead of html-minifier, with this code for the htmlmin filter:

const TerserHTML = require('html-minifier-terser');
…
eleventyConfig.addNunjucksAsyncFilter('htmlmin', async function(code, callback) {
    try {
        let minified = await TerserHTML.minify(code, {
            removeComments: true,
            collapseWhitespace: true
        });
        callback(null, minified);
    } catch (err) {
        console.error('Terser HTML error: ', err);
        callback(null, code);
    }
});
```

→ same issue

Body:
I try to minify partial HTML in which I minify some JS using terser (using a jsmin filter as showed in 11ty docs):

<!doctype html>
<meta charset="utf-8"><title></title>
{% set html %}

        Bar

{% endset %}
{{ html | htmlmin | safe }}

But since the terser process is asynchronous, it throws an error in 11ty (callback is not a function, and  in the generated file).

Same problem if I try to minify all the HTML using an 11ty transform (as suggested in their docs: Minify HTML Output – and removing all the {% set html %} / {{ html | … }} tags): it throws some similar Promise errors (Having trouble writing template … Cannot read properties of undefined … at async Promise.all)

Problem solved if I move the script part outside of the Nunjucks set declaration:

<!doctype html>
<meta charset="utf-8"><title></title>
{% set html %}

        Bar

{% endset %}
{{ html | htmlmin | safe }}

But that's not what I want.

Trying to make terser synchronous seems to need some more npm packages so I'm hoping there's an easier way before trying it.

Edit: tried to use html-minifier-terser instead of html-minifier, with this code for the htmlmin filter:

const TerserHTML = require('html-minifier-terser');
…
eleventyConfig.addNunjucksAsyncFilter('htmlmin', async function(code, callback) {
    try {
        let minified = await TerserHTML.minify(code, {
            removeComments: true,
            collapseWhitespace: true
        });
        callback(null, minified);
    } catch (err) {
        console.error('Terser HTML error: ', err);
        callback(null, code);
    }
});

→ same issue


问:
Platform or Library for Document generation based on templates
I have been searching a Platform or Library for Document generation based on templates, prefered in Java or Open Source.

I like docmosis but I haven't already tested and I want to know different opinions / Suggestions

Thanks,


问:
Cannot use UIAlertController inside a prototype cell in tableView
I have a tableView with a prototype cell. Inside this prototype cell I have a button which I want to use to report a comment.

I tried to use an example UIAlertController but it gives me the following error.

```<code>Value of tableViewCell has no member present.
</code>```

And also this error:

```<code>"nil" requires a contextual type.
</code>```

I used the code below also somewhere else and it worked fine.

What exactly did I do wrong here? I already googled the error types but don't find anything that could help me.

```<code>func displayAlert() {
           // Declare Alert message
           let dialogMessage = UIAlertController(title: "Test", message: "Test", preferredStyle: .alert)

           // Create OK button with action handler
           let ok = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
               print("Ok button tapped")
               self.deleteRecord()
           })

           //Add OK and Cancel button to dialog message
           dialogMessage.addAction(ok)

           // Present dialog message to user
           self.present(dialogMessage, animated: true, completion: nil)

       }
    func deleteRecord()
        {
            print("Delete record function called")
        }
</code>```

Body:
I have a tableView with a prototype cell. Inside this prototype cell I have a button which I want to use to report a comment.

I tried to use an example UIAlertController but it gives me the following error.

Value of tableViewCell has no member present.

And also this error:

"nil" requires a contextual type.

I used the code below also somewhere else and it worked fine.

What exactly did I do wrong here? I already googled the error types but don't find anything that could help me.

func displayAlert() {
           // Declare Alert message
           let dialogMessage = UIAlertController(title: "Test", message: "Test", preferredStyle: .alert)

           // Create OK button with action handler
           let ok = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
               print("Ok button tapped")
               self.deleteRecord()
           })

           //Add OK and Cancel button to dialog message
           dialogMessage.addAction(ok)

           // Present dialog message to user
           self.present(dialogMessage, animated: true, completion: nil)

       }
    func deleteRecord()
        {
            print("Delete record function called")
        }


问:
how to create API documentation from the war file
I m a newbie in coding , please help me I have an api code and I have to generate the documentation , can you help me to do it.
Thank you

I tried to generate the documentation with swagger editor but I think I didn't understand well how to do it


问:
GLSurfaceView floating on top of the dashboard layout
Im creating a transparent sub-glsurfaceview on a layout (making zorderontop(true)) and placing it in a scrollview.

In my parent viewgroup which is a relative layout, at the top im having a dashboard and below that the scrollview containg the glsurfaceview.

When Im scrolling the view the surfaceview moves on the top of the dashboard but I want my glsurfaceview go below that dashboard.

If I make my zorderontop(false) the background is not transparent. how to achieve it?

please someone help me.

Thanks a lot in advance.

ContentLicense: CC BY-SA 3.0


问:
How do I insert a Spacer() between items in a loop with a map?
The following is a code snippet that loops data:

```<code>BottomNavigation(
         modifiers = modifiers
     ) {
         val navigationItems = listOf(
             NavigationItem(
                 title = stringResource(R. string. menu_home),
                 icon = Icons. Default. Home,
                 screen = Screen. Home
             ),
             NavigationItem(
                 title = stringResource(R.string.menu_cart),
                 icon = Icons. Default. ShoppingCart,
                 screen = Screen. Cart
             ),
             NavigationItem(
                 title = stringResource(R.string.menu_profile),
                 icon = Icons. Default. AccountCircle,
                 screen = Screen. Profile
             ),
         )
         BottomNavigation {
             navigationItems. map { items ->
                 BottomNavigationItem(
                     icons = {
                         Icon(
                             imageVector = item. icon,
                             contentDescription = item. title
                         )
                     },
                     label = { Text(item. title) },
                     selected = true,
                     onClick = {}
                 )
             }
         }
     }
</code>```

My question is, if I have a similar case study but there is a distance between each item that is looped, in this case I want to insert a Spacer(modifier = Modifier.height(16.dp)) how can I insert it in the loop? ??

Body:
The following is a code snippet that loops data:

BottomNavigation(
         modifiers = modifiers
     ) {
         val navigationItems = listOf(
             NavigationItem(
                 title = stringResource(R. string. menu_home),
                 icon = Icons. Default. Home,
                 screen = Screen. Home
             ),
             NavigationItem(
                 title = stringResource(R.string.menu_cart),
                 icon = Icons. Default. ShoppingCart,
                 screen = Screen. Cart
             ),
             NavigationItem(
                 title = stringResource(R.string.menu_profile),
                 icon = Icons. Default. AccountCircle,
                 screen = Screen. Profile
             ),
         )
         BottomNavigation {
             navigationItems. map { items ->
                 BottomNavigationItem(
                     icons = {
                         Icon(
                             imageVector = item. icon,
                             contentDescription = item. title
                         )
                     },
                     label = { Text(item. title) },
                     selected = true,
                     onClick = {}
                 )
             }
         }
     }

My question is, if I have a similar case study but there is a distance between each item that is looped, in this case I want to insert a Spacer(modifier = Modifier.height(16.dp)) how can I insert it in the loop? ??


问:
Symfony 4 with session in redis (SncRedis). How to disable reset of ttl on each request?
I use session's handling in redis via SncRedisBundle.

I figured out that session key's ttl is discarding on each request to it's initial value (it is 3600 in the example). How can I disable it?

framework.yaml:

```<code>session:
    handler_id: snc_redis.session.handler
    cookie_lifetime: 3600
</code>```

snc_redis.yaml

```<code>snc_redis:
    clients:
        ...
        session:
            type: predis
            ...
    session:
        client: session
</code>```

I know that I can explicitly set ttl by snc_redis.session.ttl, but it has no changes to the reset of ttl.

Why is this a problem?

There can be a client (or bot) that logs in to the system, and repeatedly pings the server to indefinitely extend its session lifetime. The cookie expires is only respected by the browser, but it doesn't prevent the client from spamming the API with cURL requests. Each request resets the TTL and postpones the time until the session is actually destroyed from the cache.

Reproduce:

Login.

Check session key's ttl. It should be 3600 at the beginning.

Refresh page.

Check session key's ttl. It should be lower than 3600, but it is reset to 3600 again.

Body:
I use session's handling in redis via SncRedisBundle.

I figured out that session key's ttl is discarding on each request to it's initial value (it is 3600 in the example). How can I disable it?

framework.yaml:

session:
    handler_id: snc_redis.session.handler
    cookie_lifetime: 3600

snc_redis.yaml

snc_redis:
    clients:
        ...
        session:
            type: predis
            ...
    session:
        client: session

I know that I can explicitly set ttl by snc_redis.session.ttl, but it has no changes to the reset of ttl.

Why is this a problem?

There can be a client (or bot) that logs in to the system, and repeatedly pings the server to indefinitely extend its session lifetime. The cookie expires is only respected by the browser, but it doesn't prevent the client from spamming the API with cURL requests. Each request resets the TTL and postpones the time until the session is actually destroyed from the cache.

Reproduce:

Login.

Check session key's ttl. It should be 3600 at the beginning.

Refresh page.

Check session key's ttl. It should be lower than 3600, but it is reset to 3600 again.


问:
How to programmatically specify that operator/provider supports early media in Android?
I am working on an application which manages configuration for specific provider. It is a carrier app: https://source.android.com/docs/core/connect/uicc .

The idea is to provide to Android some indication that the operator of the SIM card supports early media (https://www.sharetechnote.com/html/IMS_SIP_EarlyMedia.html).

I have tried to check the CarrierConfigManager (https://developer.android.com/reference/android/telephony/CarrierConfigManager). There are a lot of SIP configurations there, especially in https://developer.android.com/reference/android/telephony/CarrierConfigManager.Ims?hl=en. However, there seems to be no configuration key for early media. I have tried to find some things related to the SIP early media in the docs in general, but could not find something useful.


问:
FlatMap get previous value in chain
I have a situation where i am using flatmap to transform a sequencial third party webservices calls (first get1 and second get2) to prepare a flux of responses (get2) to process with another method in subscribe.

```<code>Flux<String> max = Flux.fromIterable(markets)
                .flatMap(market -> apiService.get1(market, value, entry))
                .flatMap(response -> {
                        String maxValue = mapper.readTree(response).get("MaxValue").asText();
                        return apiService.get2(maxValue);
                 });
</code>```

this works but when i subscribe the stream flux i am interest in send the market value that used on first flatmap to relay as a parameter method of processMaxValues()

```<code>max.log().subscribe(response -> processMaxValues(response, market));
</code>```

What is the best way to implment that ?

Title: FlatMap get previous value in chain

Body:
I have a situation where i am using flatmap to transform a sequencial third party webservices calls (first get1 and second get2) to prepare a flux of responses (get2) to process with another method in subscribe.

Flux<String> max = Flux.fromIterable(markets)
                .flatMap(market -> apiService.get1(market, value, entry))
                .flatMap(response -> {
                        String maxValue = mapper.readTree(response).get("MaxValue").asText();
                        return apiService.get2(maxValue);
                 });

this works but when i subscribe the stream flux i am interest in send the market value that used on first flatmap to relay as a parameter method of processMaxValues()

max.log().subscribe(response -> processMaxValues(response, market));

What is the best way to implment that ?


问:
Not found ffmpeg when try run in scratch image
I have built a Golang image using alpine, my code has functions that need to convert videos using ffmpeg.
My problem is when I try to run ffmpeg on a scratch image, I try to copy the binaries but it doesn't work when my code tries to run ffmpeg.

```<code>
FROM mwader/static-ffmpeg:5.1 as FFmpeg
FROM golang:alpine AS builder

# Add dependencies
RUN apk add git
RUN apk --no-cache add tzdata
RUN apk add --no-cache ffmpeg

# Set necessary environmet variables needed for our image
ENV GO111MODULE=on \
    CGO_ENABLED=0 \
    GOOS=linux \
    GOARCH=amd64

# Move to working directory /build
WORKDIR /build

# Copy and download dependency using go mod
COPY go.mod .
COPY go.sum .
RUN go mod download

# Copy the code into the container
COPY . .

# Build the application
RUN go build -o main .

# Move to /dist directory as the place for resulting binary folder
WORKDIR /dist

# Copy binary from build to main folder
RUN cp /build/main .
RUN cp /build/dev.env .

# Build a small image
FROM scratch

#Copy from builder bin
COPY --from=builder /dist/main /
COPY --from=builder /build/dev.env .
COPY --from=builder /usr/share/zoneinfo /usr/share/zoneinfo
COPY --from=FFmpeg /ffmpeg /usr/local/bin/
COPY --from=FFmpeg /ffprobe /usr/local/bin/

#Set Timezone
ENV TZ="America/Montevideo"

# Copy certificates
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/

# Expose port out container
EXPOSE 8080

# Command to run
CMD ["/main"]
</code>```

I expect run ffmpeg into scratch image.

Body:
I have built a Golang image using alpine, my code has functions that need to convert videos using ffmpeg.
My problem is when I try to run ffmpeg on a scratch image, I try to copy the binaries but it doesn't work when my code tries to run ffmpeg.

FROM mwader/static-ffmpeg:5.1 as FFmpeg
FROM golang:alpine AS builder

# Add dependencies
RUN apk add git
RUN apk --no-cache add tzdata
RUN apk add --no-cache ffmpeg

# Set necessary environmet variables needed for our image
ENV GO111MODULE=on \
    CGO_ENABLED=0 \
    GOOS=linux \
    GOARCH=amd64

# Move to working directory /build
WORKDIR /build

# Copy and download dependency using go mod
COPY go.mod .
COPY go.sum .
RUN go mod download

# Copy the code into the container
COPY . .

# Build the application
RUN go build -o main .

# Move to /dist directory as the place for resulting binary folder
WORKDIR /dist

# Copy binary from build to main folder
RUN cp /build/main .
RUN cp /build/dev.env .

# Build a small image
FROM scratch

#Copy from builder bin
COPY --from=builder /dist/main /
COPY --from=builder /build/dev.env .
COPY --from=builder /usr/share/zoneinfo /usr/share/zoneinfo
COPY --from=FFmpeg /ffmpeg /usr/local/bin/
COPY --from=FFmpeg /ffprobe /usr/local/bin/

#Set Timezone
ENV TZ="America/Montevideo"

# Copy certificates
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/

# Expose port out container
EXPOSE 8080

# Command to run
CMD ["/main"]

I expect run ffmpeg into scratch image.


问:
Performances issues while decrypting data on my next.js app
I've been struggling with my app last days.

while communicating with the API all data (shown or not by the app) could be seen throught the requests console, so i decided to encrypt the data send by the API, and decrypt the encrypted data in the app directly, so the request doesn't have the "clear version" displayed.

apparently no problems to encrypt, but even tho decrypting works, it freezes the app for a decent time each time new data arrives, i've been tryng async, but it doesn't change anything.

(the data is an array filled with objects)

Here is the code of the update function :

const fetchData = (setter) => {
 const encrypter = new Cryptr(process.env.NEXT_PUBLIC_ENCRYPT_KEY);

 fetch(process.env.NEXT_PUBLIC_DATA_FETCHING_URL)
   .then((response) => response.text())
   .then((data) => {
     const decryptData = new Promise((resolve, reject) => {
       try {
         console.info('Decrypting...');
         let decryptedData = encrypter.decrypt(data);
         console.info('Parsing...');
         let parsedData = JSON.parse(decryptedData);
         console.info('Data parsed !');
         resolve(parsedData);
       } catch {
         reject('ERROR DURING DATA DECRYPTION');
       }
     })
       .then((parsedData) => setter(parsedData))
       .catch((err) => console.error(err));
   });
};
```

As you can see, i'm usingthe cryptr module (6.0.3), the app is running on next.js (12.2.5).
I tested many things, including the freeze provenance, but it seems like it's the decryption (not the parse or the setter())

PS: The js setter() function is the setter of the state that contains data from the server.

Is there a way to handle those unwanted freezes ?
Thanks for helping me with this

Body:
I've been struggling with my app last days.

while communicating with the API all data (shown or not by the app) could be seen throught the requests console, so i decided to encrypt the data send by the API, and decrypt the encrypted data in the app directly, so the request doesn't have the "clear version" displayed.

apparently no problems to encrypt, but even tho decrypting works, it freezes the app for a decent time each time new data arrives, i've been tryng async, but it doesn't change anything.

(the data is an array filled with objects)

Here is the code of the update function :

const fetchData = (setter) => {
 const encrypter = new Cryptr(process.env.NEXT_PUBLIC_ENCRYPT_KEY);

 fetch(process.env.NEXT_PUBLIC_DATA_FETCHING_URL)
   .then((response) => response.text())
   .then((data) => {
     const decryptData = new Promise((resolve, reject) => {
       try {
         console.info('Decrypting...');
         let decryptedData = encrypter.decrypt(data);
         console.info('Parsing...');
         let parsedData = JSON.parse(decryptedData);
         console.info('Data parsed !');
         resolve(parsedData);
       } catch {
         reject('ERROR DURING DATA DECRYPTION');
       }
     })
       .then((parsedData) => setter(parsedData))
       .catch((err) => console.error(err));
   });
};

As you can see, i'm usingthe cryptr module (6.0.3), the app is running on next.js (12.2.5).
I tested many things, including the freeze provenance, but it seems like it's the decryption (not the parse or the setter())

PS: The js setter() function is the setter of the state that contains data from the server.

Is there a way to handle those unwanted freezes ?
Thanks for helping me with this


问:
How to reset the virtual scroll height in angular 14+
In angular, I've implemented virtual infinite scroll. The issue I'm having is that when I try to reset the data after scrolling, it resets, but the scroll bar still displays how far I scrolled.

View in Stack blitz

How to replicate:

When you click the link, data will load inside the viewport.

By repeatedly scrolling, the view port will be updated with fresh data.

notice the scroll bar after clicking the clear button.


问:
Monte Media video recording limited to 60 minutes
The "maxRecordingTime" is set to 60 minutes in the "ScreenRecorder.java" program.
Line 204: private long maxRecordingTime = 60 * 60 * 1000;
How to increase that beyond one hour?
Or do I have to override the whole thing?

References:
https://github.com/sbtqa/monte-media/blob/master/src/main/ru/sbtqa/monte/screenrecorder/ScreenRecorder.java
https://github.com/wrandelshofer/MonteMedia

The ScreenRecorder object is imported with "import static org.monte.media. ... ".


问:
Trying to compile clangs module example results in segmentation fault
When trying to compile the minimal working example for C++20 modules (taken from here) the resulting binary results in a segmentation fault.

This is my code:

// Hello.cppm
module;
#include <iostream>
export module Hello;
export void hello() {
  std::cout << "Hello World!" << std::endl;
}
```
<pre class="lang-cpp prettyprint-override"><code>// use.cpp
import Hello;
int main() {
  hello();
  return 0;
}
</code>```

I compiled everything using the following commands:

$ clang --version
clang version 14.0.6
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin
$ clang++ -std=c++20 --precompile Hello.cppm -o Hello.pcm
$ clang++ -std=c++20 use.cpp -fprebuilt-module-path=. Hello.pcm -o Hello.out
```
<p><code>LLDB</code> outputs the following:</p>
```$ lldb ./Hello.out
(lldb) target create "./Hello.out"
Current executable set to '/home/cwd/Hello.out' (x86_64).
(lldb) run
Process 160768 launched: '/home/cwd/Hello.out' (x86_64)
Process 160768 stopped
* thread #1, name = 'Hello.out', stop reason = signal SIGSEGV: invalid address (fault address: 0xffffffffffffffe8)
    frame #0: 0x00007ffff7e8168a libstdc++.so.6`std::ostream::sentry::sentry(this=0x00007fffffffd3d0, __os=0x00007ffff7f7b480) at ostream.tcc:51:19
(lldb) step
Process 160768 exited with status = 11 (0x0000000b)
```

EDIT: I forgot to mention that I'm compiling with clang 14 on Linux.

Body:
When trying to compile the minimal working example for C++20 modules (taken from here) the resulting binary results in a segmentation fault.

This is my code:

// Hello.cppm
module;
#include <iostream>
export module Hello;
export void hello() {
  std::cout << "Hello World!" << std::endl;
}

// use.cpp
import Hello;
int main() {
  hello();
  return 0;
}

I compiled everything using the following commands:

$ clang --version
clang version 14.0.6
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin
$ clang++ -std=c++20 --precompile Hello.cppm -o Hello.pcm
$ clang++ -std=c++20 use.cpp -fprebuilt-module-path=. Hello.pcm -o Hello.out

LLDB outputs the following:

$ lldb ./Hello.out
(lldb) target create "./Hello.out"
Current executable set to '/home/cwd/Hello.out' (x86_64).
(lldb) run
Process 160768 launched: '/home/cwd/Hello.out' (x86_64)
Process 160768 stopped
* thread #1, name = 'Hello.out', stop reason = signal SIGSEGV: invalid address (fault address: 0xffffffffffffffe8)
    frame #0: 0x00007ffff7e8168a libstdc++.so.6`std::ostream::sentry::sentry(this=0x00007fffffffd3d0, __os=0x00007ffff7f7b480) at ostream.tcc:51:19
(lldb) step
Process 160768 exited with status = 11 (0x0000000b)

EDIT: I forgot to mention that I'm compiling with clang 14 on Linux.


问:
createUserwithEmailAndPassword is not a function on react
i tried to connect my firebase auth with react and it successfully deployed, but when i look into the console i get an error  and i use firebase 9.15.0

any help would be appreciated

this is for index.js

```<code>import React from "react";
import { useState } from "react";
import Typography from "@mui/material/Typography";
import TextField from '@mui/material/TextField';
import Button from '@mui/material/Button';
import { auth } from "../../firebase";

function Home() {
    const [form, setForm] = useState({
        email: '',
        password: '',
    });

    const handleChange = event => setForm(oldForm => ({
        ...oldForm,
        [event.target.name]: event.target.value
    }))

    const handleSignup = async () => {
        await auth.createUserwithEmailAndPassword(form.email, form.password)
    };

    console.log(auth.currentUser);

  return ( <><Typography>Home</Typography>
<TextField value={form.email} name="email" onChange={handleChange} label="Email" />
<TextField type="password" value={form.password} name="password" onChange={handleChange} label="Password" />
<Button onClick={handleSignup}>Sign Up</Button>
</>
)
}

export default Home;
</code>```

this is my firebase.js

```<code>import app from 'firebase/compat/app';
import 'firebase/compat/firestore'
import 'firebase/compat/auth'

const firebaseConfig = {
  apiKey: "xxxx",
  authDomain: "xxxx",
  projectId: "xxxx",
  storageBucket: "xxxx",
  messagingSenderId: "xxxx",
  appId: "xxxx",
  measurementId: "xxxx"
  };

  const firebase = app.initializeApp(firebaseConfig)
  const firestore = firebase.firestore()
  const auth = firebase.auth()

  export { firebase, firestore, auth};
</code>```

trying to solve but still getting error

Body:
i tried to connect my firebase auth with react and it successfully deployed, but when i look into the console i get an error  and i use firebase 9.15.0

any help would be appreciated

this is for index.js

import React from "react";
import { useState } from "react";
import Typography from "@mui/material/Typography";
import TextField from '@mui/material/TextField';
import Button from '@mui/material/Button';
import { auth } from "../../firebase";

function Home() {
    const [form, setForm] = useState({
        email: '',
        password: '',
    });

    const handleChange = event => setForm(oldForm => ({
        ...oldForm,
        [event.target.name]: event.target.value
    }))

    const handleSignup = async () => {
        await auth.createUserwithEmailAndPassword(form.email, form.password)
    };

    console.log(auth.currentUser);

  return ( <><Typography>Home</Typography>
<TextField value={form.email} name="email" onChange={handleChange} label="Email" />
<TextField type="password" value={form.password} name="password" onChange={handleChange} label="Password" />
<Button onClick={handleSignup}>Sign Up</Button>
</>
)
}

export default Home;

this is my firebase.js

import app from 'firebase/compat/app';
import 'firebase/compat/firestore'
import 'firebase/compat/auth'

const firebaseConfig = {
  apiKey: "xxxx",
  authDomain: "xxxx",
  projectId: "xxxx",
  storageBucket: "xxxx",
  messagingSenderId: "xxxx",
  appId: "xxxx",
  measurementId: "xxxx"
  };

  const firebase = app.initializeApp(firebaseConfig)
  const firestore = firebase.firestore()
  const auth = firebase.auth()

  export { firebase, firestore, auth};

trying to solve but still getting error


问:
In a quarto book, document language works for html rendering, but not for pdfs
I am writing a quarto book in Spanish. So I would like, for example, that quarto uses the word "Figura" in Spanish instead of word "Figure" in English when rendering the document.

The lang document option does the job when I render a html file:

```<code>---
title: "Mi título"
lang: es
format: html
---

![Cat](fig.png)
</code>```

but it does not work when I render a pdf:

```<code>---
title: "Mi título"
lang: es
format: pdf
---

![Cat](fig.png)
</code>```

In the pdf file a figure is referred as "Figure" instead of "Figura".

This problem does not occur when a quarto document is created in a RStudio project. It occurs only for quarto book projects.

I tried to include this code "lang: es" in the _quarto.yml file of the quarto book project, but it produces an error. Any idea about what could be the problem?

Body:
I am writing a quarto book in Spanish. So I would like, for example, that quarto uses the word "Figura" in Spanish instead of word "Figure" in English when rendering the document.

The lang document option does the job when I render a html file:

---
title: "Mi título"
lang: es
format: html
---

![Cat](fig.png)

but it does not work when I render a pdf:

---
title: "Mi título"
lang: es
format: pdf
---

![Cat](fig.png)

In the pdf file a figure is referred as "Figure" instead of "Figura".

This problem does not occur when a quarto document is created in a RStudio project. It occurs only for quarto book projects.

I tried to include this code "lang: es" in the _quarto.yml file of the quarto book project, but it produces an error. Any idea about what could be the problem?


问:
How to add custom scroll behaviour to page using Javascript
I was wondering if anybody knows how to achieve a scrolling effect as seen on this page:
https://plastic.design/

I don't know what this effect is called and don't even know how to describe it, which makes it pretty hard to google it.

edit:
this question has been marked as a duplicate of How to do an infinite scroll in plain Javascript. These question do not ask for the same functionality – one asks for an infinite scroll, mine simply asks about some sort of a delayed scrolling behaviour.


问:
How to get color text using the IMPORTXML?
I am monitoring prices on the website, and for this particular one, they communicate promotions changing the price color to red (#ed1c24).

How can I find the XPath that returns me to the color of the text?

product example - https://www.rimi.ee/epood/en/products/alcohol/cocktails-mixed-drinks/muu-alk-jook-g-n-red-orange-5-5-vol-1-5l/p/1363682

How can I get the color of the field using the IMPORTXML?


问:
How to create a fully type-safe NestJS package with dynamic objects in TypeScript?
I am currently working on a personal project to provide easy access to different storage providers through a NestJS package. I want the package to be fully type-safe but I am experiencing difficulty achieving this.

This is an abstraction of the current code.

// local.driver.ts

interface LocalOptions {
  path: string;
}

export class LocalDriver {
  constructor(private options: LocalOptions) {}

  get() {}
}
```
<pre class="lang-js prettyprint-override"><code>// s3.driver.ts

interface S3Options {
  key: string;
  secret: string;
  region: string;
  bucket: string;
}

export class S3Driver {
  constructor(private options: S3Options) {}

  get() {}
}
</code>```

// storage.service.ts

const drivers = {
  local: LocalDriver,
  s3: S3Driver,
};

type DriverTypes = keyof typeof drivers;
type Drivers = typeof drivers[DriverTypes];

type Disk = {
  [Driver in DriverTypes]: {
    type: Driver;
    properties: ConstructorParameters<typeof drivers[Driver]>[0];
  };
}[DriverTypes];

export type StorageOptions = {
  disks: {
    [disk: string]: Disk;
  };
};

@Injectable()
export class StorageService {
  private static diskDrivers: { [disk: string]: Drivers };
  private static options: StorageOptions;

  constructor(@Inject(STORAGE_OPTIONS) options: StorageOptions) {
    StorageService.options = options;
  }

  static disk(disk: keyof typeof StorageService.options.disks) {
    return StorageService.getDriver(disk);
  }

  private static getDriver(
    disk: keyof typeof StorageService.options.disks,
  ): Drivers {
    const diskDriver = StorageService.diskDrivers[disk];
    if (diskDriver) return diskDriver;
    const driver = StorageService.newDriver(disk);
    StorageService.diskDrivers[disk] = driver;
    return driver;
  }

  private static newDriver(
    disk: keyof typeof StorageService.options.disks,
  ): Drivers {
    const driverConfig = StorageService.options.disks[disk];
    const Driver = drivers[driverConfig.type];
    return new Driver(driverConfig.properties);
                                    // ^ Argument of type 'LocalOptions | S3Options' is not assignable to parameter of type 'LocalOptions & S3Options'.
  }
}
```
<p>This is how I register the package in NestJS. When using a specific type, only its options are allowed and will be suggested. E.g. using type <code>s3</code>, only the S3 options are allowed in the IDE (this is currently working).</p>
<pre class="lang-js prettyprint-override"><code>// app.module.ts

@Module({
  imports: [
    StorageModule.register({
      disks: {
        invoices: {
          type: 's3',
          properties: {
            region: process.env.AWS_REGION,
            key: process.env.AWS_KEY,
            secret: process.env.AWS_SECRET,
            bucket: 'invoices',
          },
        },
        images: {
          type: 'local',
          properties: {
            path: '/images',
          },
        },
      },
    }),
  ],
})
export class AppModule {}
</code>```

I now want to use the disks but I'm not receiving any suggestions, warnings or errors.

```<code>StorageService.disk('').get();
                  // ^ This should suggest and only allow `invoices` and `images`.
</code>```

Is there a way to achieve this functionality?

Body:
I am currently working on a personal project to provide easy access to different storage providers through a NestJS package. I want the package to be fully type-safe but I am experiencing difficulty achieving this.

This is an abstraction of the current code.

// local.driver.ts

interface LocalOptions {
  path: string;
}

export class LocalDriver {
  constructor(private options: LocalOptions) {}

  get() {}
}

// s3.driver.ts

interface S3Options {
  key: string;
  secret: string;
  region: string;
  bucket: string;
}

export class S3Driver {
  constructor(private options: S3Options) {}

  get() {}
}

// storage.service.ts

const drivers = {
  local: LocalDriver,
  s3: S3Driver,
};

type DriverTypes = keyof typeof drivers;
type Drivers = typeof drivers[DriverTypes];

type Disk = {
  [Driver in DriverTypes]: {
    type: Driver;
    properties: ConstructorParameters<typeof drivers[Driver]>[0];
  };
}[DriverTypes];

export type StorageOptions = {
  disks: {
    [disk: string]: Disk;
  };
};

@Injectable()
export class StorageService {
  private static diskDrivers: { [disk: string]: Drivers };
  private static options: StorageOptions;

  constructor(@Inject(STORAGE_OPTIONS) options: StorageOptions) {
    StorageService.options = options;
  }

  static disk(disk: keyof typeof StorageService.options.disks) {
    return StorageService.getDriver(disk);
  }

  private static getDriver(
    disk: keyof typeof StorageService.options.disks,
  ): Drivers {
    const diskDriver = StorageService.diskDrivers[disk];
    if (diskDriver) return diskDriver;
    const driver = StorageService.newDriver(disk);
    StorageService.diskDrivers[disk] = driver;
    return driver;
  }

  private static newDriver(
    disk: keyof typeof StorageService.options.disks,
  ): Drivers {
    const driverConfig = StorageService.options.disks[disk];
    const Driver = drivers[driverConfig.type];
    return new Driver(driverConfig.properties);
                                    // ^ Argument of type 'LocalOptions | S3Options' is not assignable to parameter of type 'LocalOptions & S3Options'.
  }
}

This is how I register the package in NestJS. When using a specific type, only its options are allowed and will be suggested. E.g. using type s3, only the S3 options are allowed in the IDE (this is currently working).

// app.module.ts

@Module({
  imports: [
    StorageModule.register({
      disks: {
        invoices: {
          type: 's3',
          properties: {
            region: process.env.AWS_REGION,
            key: process.env.AWS_KEY,
            secret: process.env.AWS_SECRET,
            bucket: 'invoices',
          },
        },
        images: {
          type: 'local',
          properties: {
            path: '/images',
          },
        },
      },
    }),
  ],
})
export class AppModule {}

I now want to use the disks but I'm not receiving any suggestions, warnings or errors.

StorageService.disk('').get();
                  // ^ This should suggest and only allow `invoices` and `images`.

Is there a way to achieve this functionality?


问:
How can I make the water fill the whole text and once its full to restart from beginning?
I would like to make the water fill the whole text and once its full make it restart from beginning.

I've created a fiddle: https://jsfiddle.net/6jxsz0pc/

I'm gonna leave the code here anyway, thank you!

My idea was doing the effect restart approximately every 2 minutes or something like that.

Is there something that I can add or edit to get what I want? thank you so much!

```<code><section>
        <br><br><br>
    <div class="contentDepurazione">

        <h2 id="contatoreDepurazione" ></h2>
        <h2 id="contatoreDepurazione2"></h2>
    </div>
</section>

<style>@import url("https://fonts.googleapis.com/css?family=Poppins:100,200,300,400,500,600,700,800,900");

h2 {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: "Poppins", sans-serif;
}

.contentDepurazione h2 {
    color: red;
    font-size: 55px;
    top:40px;
    position: absolute;
    left:50%;
    margin-left:auto;
    margin-right:auto;
    transform: translate(-50%, -50%);
}
@media screen and (max-width: 600px) {

    .contentDepurazione h2 {

    color: red;
    font-size: 25px;
    top:40px;
    position: absolute;
    left:50%;
    margin-left:auto;
    margin-right:auto;
    transform: translate(-50%, -50%);

}

}

.contentDepurazione h2:nth-child(1) {
    color: transparent;
-webkit-text-stroke: 1px #1d68b2;
}

.contentDepurazione h2:nth-child(2) {
    color: #007fff;
    animation: animate 4s ease-in-out infinite;
}

@keyframes animate {
    0%,
    100% {
        clip-path: polygon(
            0% 55%,
            20% 44%,
            33% 50%,
            94% 60%,
            80% 61%,
            84% 59%,
            100% 52%,
            100% 100%,
            0% 100%
        );
    }

    50% {
        clip-path: polygon(
            0% 60%,
            15% 65%,
            34% 66%,
            51% 62%,
            67% 50%,
            84% 45%,
            100% 46%,
            100% 100%,
            0% 100%
        );
    }
}

</style>

<script>function diff_secondsDepurazione(dt2Depurazione, dt1Depurazione) //Secondi
 {

 dt1Depurazione = new Date();
 dt2Depurazione = new Date("December 15, 2022 12:42:00");

  var diffDepurazione =(dt2Depurazione.getTime() - dt1Depurazione.getTime()) / 1000;

 //per ore   diff /= (60 * 60);
 //per minuti
// diffVapore /= (60 * 1);
// diffDepurazione /= (60 * 60)*24;

 return Math.abs(Math.round(diffDepurazione));

 }

function printDepurazione()
{
var dt1Depurazione,dt2Depurazione;
var contatoreDepurazione=122500000 ;

contatoreDepurazione=contatoreDepurazione+(diff_secondsDepurazione(dt1Depurazione, dt2Depurazione)*0.2);
document.getElementById("contatoreDepurazione").innerHTML=contatoreDepurazione;
document.getElementById("contatoreDepurazione2").innerHTML=contatoreDepurazione;

}

setInterval(printDepurazione, 1000);</script>
</code>```


问:
Moveit OMPL disable Info logging
I want to know how I can disable the "[ INFO]" Logging for my MoveIt OMPL Pipeline as it spams my terminal and I need some other warnings I can't really get to.
It seems like they changed something in the packages lately as I didn't change anything about my code but it spammed my whole screen all of a suudden.

this is my move_group.launch file:

```<code><launch>

  <!-- GDB Debug Option -->
  <arg name="debug" default="false" />
  <arg unless="$(arg debug)" name="launch_prefix" value="" />
  <arg     if="$(arg debug)" name="launch_prefix"
           value="gdb -x $(find ur5e-rg2_moveit_config)/launch/gdb_settings.gdb --ex run --args" />

  <!-- Verbose Mode Option -->
  <arg name="info" default="$(arg debug)" />
  <arg unless="$(arg info)" name="command_args" value="" />
  <arg     if="$(arg info)" name="command_args" value="--debug" />

  <!-- move_group settings -->
  <arg name="pipeline" default="ompl" />
  <arg name="allow_trajectory_execution" default="true"/>
  <arg name="fake_execution" default="false"/>
  <arg name="execution_type" default="interpolate"/> <!-- set to 'last point' to skip intermediate trajectory in fake execution -->
  <arg name="max_safe_path_cost" default="1"/>
  <arg name="jiggle_fraction" default="0.05" />
  <arg name="publish_monitored_planning_scene" default="true"/>

  <arg name="capabilities" default=""/>
  <arg name="disable_capabilities" default=""/>
  <!-- load these non-default MoveGroup capabilities (space seperated) -->
  <!--
  <arg name="capabilities" value="
                a_package/AwsomeMotionPlanningCapability
                another_package/GraspPlanningPipeline
                " />
  -->

  <!-- inhibit these default MoveGroup capabilities (space seperated) -->
  <!--
  <arg name="disable_capabilities" value="
                move_group/MoveGroupKinematicsService
                move_group/ClearOctomapService
                " />
  -->

  <arg name="load_robot_description" default="true" />
  <!-- load URDF, SRDF and joint_limits configuration -->
  <include file="$(find ur5e-rg2_moveit_config)/launch/planning_context.launch">
    <arg name="load_robot_description" value="$(arg load_robot_description)" />
  </include>

  <!-- Planning Pipelines -->
  <group ns="move_group/planning_pipelines">

    <!-- OMPL -->
    <include ns="ompl" file="$(find ur5e-rg2_moveit_config)/launch/planning_pipeline.launch.xml">
      <arg name="pipeline" value="ompl" />
    </include>

    <!-- CHOMP -->
    <include ns="chomp" file="$(find ur5e-rg2_moveit_config)/launch/planning_pipeline.launch.xml">
      <arg name="pipeline" value="chomp" />
    </include>

    <!-- Pilz Industrial Motion-->
    <include ns="pilz_industrial_motion_planner" file="$(find moveit_resources_prbt_moveit_config)/launch/planning_pipeline.launch.xml">
      <arg name="pipeline" value="pilz_industrial_motion_planner" />
    </include>

    <!-- Support custom planning pipeline -->
    <include if="$(eval arg('pipeline') not in ['ompl', 'chomp', 'pilz_industrial_motion_planner'])"
         file="$(find ur5e-rg2_moveit_config)/launch/planning_pipeline.launch.xml">
      <arg name="pipeline" value="$(arg pipeline)" />
    </include>
  </group>

  <!-- Trajectory Execution Functionality -->
  <include ns="move_group" file="$(find ur5e-rg2_moveit_config)/launch/trajectory_execution.launch.xml" if="$(arg allow_trajectory_execution)">
    <arg name="moveit_manage_controllers" value="true" />
    <arg name="moveit_controller_manager" value="ur5e-rg2" unless="$(arg fake_execution)"/>
    <arg name="moveit_controller_manager" value="fake" if="$(arg fake_execution)"/>
    <arg name="execution_type" value="$(arg execution_type)" />
  </include>

  <!-- Sensors Functionality -->
  <include ns="move_group" file="$(find ur5e-rg2_moveit_config)/launch/sensor_manager.launch.xml" if="$(arg allow_trajectory_execution)">
    <arg name="moveit_sensor_manager" value="ur5e-rg2" />
  </include>

  <!-- Start the actual move_group node/action server -->
  <node name="move_group" launch-prefix="$(arg launch_prefix)" pkg="moveit_ros_move_group" type="move_group" respawn="false" output="screen" args="$(arg command_args)">
    <!-- Set the display variable, in case OpenGL code is used internally -->
    <env name="DISPLAY" value="$(optenv DISPLAY :0)" />

    <param name="allow_trajectory_execution" value="$(arg allow_trajectory_execution)"/>
    <param name="max_safe_path_cost" value="$(arg max_safe_path_cost)"/>
    <param name="jiggle_fraction" value="$(arg jiggle_fraction)" />
    <param name="default_planning_pipeline" value="$(arg pipeline)" />
    <param name="capabilities" value="$(arg capabilities)" />
    <param name="disable_capabilities" value="$(arg disable_capabilities)" />

    <!-- Publish the planning scene of the physical robot so that rviz plugin can know actual robot -->
    <param name="planning_scene_monitor/publish_planning_scene" value="$(arg publish_monitored_planning_scene)" />
    <param name="planning_scene_monitor/publish_geometry_updates" value="$(arg publish_monitored_planning_scene)" />
    <param name="planning_scene_monitor/publish_state_updates" value="$(arg publish_monitored_planning_scene)" />
    <param name="planning_scene_monitor/publish_transforms_updates" value="$(arg publish_monitored_planning_scene)" />
  </node>

</launch>
</code>```

and I call it with:

```<code> <include file="$(find ur5e-rg2_moveit_config)/launch/move_group.launch" if="$(arg sim)">
    <arg name="allow_trajectory_execution" value="true"/>
    <arg name="fake_execution" value="true"/>
    <arg name="execution_type" value="$(arg execution_type)"/>
    <arg name="info" value="false"/>
    <arg name="debug" value="false"/>
    <arg name="pipeline" value="$(arg pipeline)"/>
    <arg name="load_robot_description" value="true"/>
  </include>
</code>```

But it still gives me infos like

```<code>[ INFO] [1672325791.029486426]: Stereo is NOT SUPPORTED
[ INFO] [1672325791.029630843]: OpenGL device: virgl (Apple M1 Pro (Compat))
[ INFO] [1672325791.029683884]: OpenGl version: 3.1 (GLSL 1.4).
[ INFO] [1672325794.416828292]: Loading robot model 'ur5e-rg2'...
[ INFO] [1672325794.600401765]: Starting planning scene monitor
[ INFO] [1672325794.601532390]: Listening to '/move_group/monitored_planning_scene'
[ INFO] [1672325794.864384678]: Constructing new MoveGroup connection for group 'manipulator' in namespace ''
[ INFO] [1672325796.045110033]: Ready to take commands for planning group manipulator.
</code>```

What am I missing?

I am using Ubuntu 20.05 on arm64 with ros noetic latest version.

Title: Moveit OMPL disable Info logging

Body:
I want to know how I can disable the "[ INFO]" Logging for my MoveIt OMPL Pipeline as it spams my terminal and I need some other warnings I can't really get to.
It seems like they changed something in the packages lately as I didn't change anything about my code but it spammed my whole screen all of a suudden.

this is my move_group.launch file:

<launch>

  <arg name="debug" default="false" />
  <arg unless="$(arg debug)" name="launch_prefix" value="" />
  <arg     if="$(arg debug)" name="launch_prefix"
           value="gdb -x $(find ur5e-rg2_moveit_config)/launch/gdb_settings.gdb --ex run --args" />

  <arg name="info" default="$(arg debug)" />
  <arg unless="$(arg info)" name="command_args" value="" />
  <arg     if="$(arg info)" name="command_args" value="--debug" />

  <arg name="pipeline" default="ompl" />
  <arg name="allow_trajectory_execution" default="true"/>
  <arg name="fake_execution" default="false"/>
  <arg name="execution_type" default="interpolate"/>
  <arg name="max_safe_path_cost" default="1"/>
  <arg name="jiggle_fraction" default="0.05" />
  <arg name="publish_monitored_planning_scene" default="true"/>

  <arg name="capabilities" default=""/>
  <arg name="disable_capabilities" default=""/>

  <arg name="load_robot_description" default="true" />

  <include file="$(find ur5e-rg2_moveit_config)/launch/planning_context.launch">
    <arg name="load_robot_description" value="$(arg load_robot_description)" />
  </include>

  <group ns="move_group/planning_pipelines">

    <include ns="ompl" file="$(find ur5e-rg2_moveit_config)/launch/planning_pipeline.launch.xml">
      <arg name="pipeline" value="ompl" />
    </include>

    <include ns="chomp" file="$(find ur5e-rg2_moveit_config)/launch/planning_pipeline.launch.xml">
      <arg name="pipeline" value="chomp" />
    </include>

    <include ns="pilz_industrial_motion_planner" file="$(find moveit_resources_prbt_moveit_config)/launch/planning_pipeline.launch.xml">
      <arg name="pipeline" value="pilz_industrial_motion_planner" />
    </include>

    <include if="$(eval arg('pipeline') not in ['ompl', 'chomp', 'pilz_industrial_motion_planner'])"
         file="$(find ur5e-rg2_moveit_config)/launch/planning_pipeline.launch.xml">
      <arg name="pipeline" value="$(arg pipeline)" />
    </include>
  </group>

  <include ns="move_group" file="$(find ur5e-rg2_moveit_config)/launch/trajectory_execution.launch.xml" if="$(arg allow_trajectory_execution)">
    <arg name="moveit_manage_controllers" value="true" />
    <arg name="moveit_controller_manager" value="ur5e-rg2" unless="$(arg fake_execution)"/>
    <arg name="moveit_controller_manager" value="fake" if="$(arg fake_execution)"/>
    <arg name="execution_type" value="$(arg execution_type)" />
  </include>

  <include ns="move_group" file="$(find ur5e-rg2_moveit_config)/launch/sensor_manager.launch.xml" if="$(arg allow_trajectory_execution)">
    <arg name="moveit_sensor_manager" value="ur5e-rg2" />
  </include>

  <node name="move_group" launch-prefix="$(arg launch_prefix)" pkg="moveit_ros_move_group" type="move_group" respawn="false" output="screen" args="$(arg command_args)">

    <env name="DISPLAY" value="$(optenv DISPLAY :0)" />

    <param name="allow_trajectory_execution" value="$(arg allow_trajectory_execution)"/>
    <param name="max_safe_path_cost" value="$(arg max_safe_path_cost)"/>
    <param name="jiggle_fraction" value="$(arg jiggle_fraction)" />
    <param name="default_planning_pipeline" value="$(arg pipeline)" />
    <param name="capabilities" value="$(arg capabilities)" />
    <param name="disable_capabilities" value="$(arg disable_capabilities)" />

    <param name="planning_scene_monitor/publish_planning_scene" value="$(arg publish_monitored_planning_scene)" />
    <param name="planning_scene_monitor/publish_geometry_updates" value="$(arg publish_monitored_planning_scene)" />
    <param name="planning_scene_monitor/publish_state_updates" value="$(arg publish_monitored_planning_scene)" />
    <param name="planning_scene_monitor/publish_transforms_updates" value="$(arg publish_monitored_planning_scene)" />
  </node>

</launch>

and I call it with:

 <include file="$(find ur5e-rg2_moveit_config)/launch/move_group.launch" if="$(arg sim)">
    <arg name="allow_trajectory_execution" value="true"/>
    <arg name="fake_execution" value="true"/>
    <arg name="execution_type" value="$(arg execution_type)"/>
    <arg name="info" value="false"/>
    <arg name="debug" value="false"/>
    <arg name="pipeline" value="$(arg pipeline)"/>
    <arg name="load_robot_description" value="true"/>
  </include>

But it still gives me infos like

[ INFO] [1672325791.029486426]: Stereo is NOT SUPPORTED
[ INFO] [1672325791.029630843]: OpenGL device: virgl (Apple M1 Pro (Compat))
[ INFO] [1672325791.029683884]: OpenGl version: 3.1 (GLSL 1.4).
[ INFO] [1672325794.416828292]: Loading robot model 'ur5e-rg2'...
[ INFO] [1672325794.600401765]: Starting planning scene monitor
[ INFO] [1672325794.601532390]: Listening to '/move_group/monitored_planning_scene'
[ INFO] [1672325794.864384678]: Constructing new MoveGroup connection for group 'manipulator' in namespace ''
[ INFO] [1672325796.045110033]: Ready to take commands for planning group manipulator.

What am I missing?

I am using Ubuntu 20.05 on arm64 with ros noetic latest version.


问:
SourceLink and Azure DevOps
Have I got it right that AzureDevOps doesn't support snupkg therefore you have to use the PublishSymbols task which only works on Agent.OS -equals Windows_NT?

```<code>- task: PowerShell@2
  displayName: 'dotnet pack'
  condition: ne(variables['projectsToPack'], '')
  inputs:
    targetType: 'inline'
    script: |
        $packVersionSuffix = '$(packVersionSuffix)'
        $bo = '$(Build.ArtifactStagingDirectory)' # 'artifact' (sic).

        $projectsToPack = '$(projectsToPack)'.Split(';')
        $projectsToPush = '$(projectsToPush)'.Split(';')

        foreach( $csproj in Get-ChildItem -Recurse -Filter *.csproj ) {
            if($projectsToPack.Contains($csproj.Name)) {
                $outputDirectory = "$bo\pack"
                if( -Not $projectsToPush.Contains($csproj.Name)) {
                    $outputDirectory = "$bo\pack_no_push"
                }

                $csprojFullName = $csproj.FullName
                if('$(packVersionSuffix)' -ne '')
                {
                    dotnet pack --no-restore --no-build --configuration $(buildConfiguration) --include-source --include-symbols --version-suffix "$packVersionSuffix" --output "$outputDirectory" "$csprojFullName"
                }
                else {
                    dotnet pack --no-restore --no-build --configuration $(buildConfiguration) --include-source --include-symbols --output "$outputDirectory" "$csprojFullName" # Fuck knows why .FullName not only isn't needed but moreover doesn't work.
                }
                # -p:SymbolPackageFormat=snupkg
            }
        }

        if (Test-Path "$bo\pack_no_push") {
            Remove-Item -Force -Recurse "$bo\pack_no_push"
        }

- task: NuGetCommand@2
  displayName: 'Push packages'
  condition: and( succeeded(), ne(variables['projectsToPush'], ''), ne(variables['Build.SourceBranchName'], 'merge')) # Don't push a package for PR builds.
  inputs:
    command: 'push'
    packagesToPush: '$(Build.ArtifactStagingDirectory)/pack/**/*.symbols.nupkg'
    nuGetFeedType: 'internal'
    publishVstsFeed: 'Company'
    allowPackageConflicts: false
    #skipDuplicates isn't supported :( Hence all the faff with projectsToPush.

- task: PowerShell@2
  displayName: 'Windows_NT for PublishSymbols@2'
  condition: and( succeeded(), ne(variables['projectsToPush'], ''), ne(variables['Build.SourceBranchName'], 'merge'), ne(variables['Agent.OS'], 'Windows_NT'))
  inputs:
    targetType: 'inline'
    script: |
          echo "Task 'PublishSymbols@2' requires Agent.OS -equals Windows_NT (add this demand to your job)."
          exit 1

- task: PublishSymbols@2
  displayName: 'Push symbols'
  condition: and( succeeded(), ne(variables['projectsToPush'], ''), ne(variables['Build.SourceBranchName'], 'merge')) # Don't push a package for PR builds.
  inputs:
    SearchPattern: '**/bin/**/*.pdb' # Includes pakcages that haven't been published, but 'should be' identical to previous symbols.
    SymbolServerType: 'TeamServices'
    IndexSources: false # Not needed when using SourceLink https://learn.microsoft.com/en-us/azure/devops/pipelines/artifacts/symbols?view=azure-devops&viewFallbackFrom=vsts
</code>```

Title: SourceLink and Azure DevOps

Body:
Have I got it right that AzureDevOps doesn't support snupkg therefore you have to use the PublishSymbols task which only works on Agent.OS -equals Windows_NT?

- task: PowerShell@2
  displayName: 'dotnet pack'
  condition: ne(variables['projectsToPack'], '')
  inputs:
    targetType: 'inline'
    script: |
        $packVersionSuffix = '$(packVersionSuffix)'
        $bo = '$(Build.ArtifactStagingDirectory)' # 'artifact' (sic).

        $projectsToPack = '$(projectsToPack)'.Split(';')
        $projectsToPush = '$(projectsToPush)'.Split(';')

        foreach( $csproj in Get-ChildItem -Recurse -Filter *.csproj ) {
            if($projectsToPack.Contains($csproj.Name)) {
                $outputDirectory = "$bo\pack"
                if( -Not $projectsToPush.Contains($csproj.Name)) {
                    $outputDirectory = "$bo\pack_no_push"
                }

                $csprojFullName = $csproj.FullName
                if('$(packVersionSuffix)' -ne '')
                {
                    dotnet pack --no-restore --no-build --configuration $(buildConfiguration) --include-source --include-symbols --version-suffix "$packVersionSuffix" --output "$outputDirectory" "$csprojFullName"
                }
                else {
                    dotnet pack --no-restore --no-build --configuration $(buildConfiguration) --include-source --include-symbols --output "$outputDirectory" "$csprojFullName" # Fuck knows why .FullName not only isn't needed but moreover doesn't work.
                }
                # -p:SymbolPackageFormat=snupkg
            }
        }

        if (Test-Path "$bo\pack_no_push") {
            Remove-Item -Force -Recurse "$bo\pack_no_push"
        }

- task: NuGetCommand@2
  displayName: 'Push packages'
  condition: and( succeeded(), ne(variables['projectsToPush'], ''), ne(variables['Build.SourceBranchName'], 'merge')) # Don't push a package for PR builds.
  inputs:
    command: 'push'
    packagesToPush: '$(Build.ArtifactStagingDirectory)/pack/**/*.symbols.nupkg'
    nuGetFeedType: 'internal'
    publishVstsFeed: 'Company'
    allowPackageConflicts: false
    #skipDuplicates isn't supported :( Hence all the faff with projectsToPush.

- task: PowerShell@2
  displayName: 'Windows_NT for PublishSymbols@2'
  condition: and( succeeded(), ne(variables['projectsToPush'], ''), ne(variables['Build.SourceBranchName'], 'merge'), ne(variables['Agent.OS'], 'Windows_NT'))
  inputs:
    targetType: 'inline'
    script: |
          echo "Task 'PublishSymbols@2' requires Agent.OS -equals Windows_NT (add this demand to your job)."
          exit 1

- task: PublishSymbols@2
  displayName: 'Push symbols'
  condition: and( succeeded(), ne(variables['projectsToPush'], ''), ne(variables['Build.SourceBranchName'], 'merge')) # Don't push a package for PR builds.
  inputs:
    SearchPattern: '**/bin/**/*.pdb' # Includes pakcages that haven't been published, but 'should be' identical to previous symbols.
    SymbolServerType: 'TeamServices'
    IndexSources: false # Not needed when using SourceLink https://learn.microsoft.com/en-us/azure/devops/pipelines/artifacts/symbols?view=azure-devops&viewFallbackFrom=vsts


问:
How do I use usbrply library to get the time at which the microphone has started working?
I want the time at which the microphone that I am using has started recording audio. I found out about usbrply but I don't know how to use it. If anyone has any other suggestions please help me.

I have tried to use the library usbrply but there is like one example on how to use it and it's by the creator.


问:
Merge scoket.io function inside the other one when data is inserted it should be called automatically
I need to move it inside the get Images function after first sql syntax such that it will be called right after the data is inserted in the database
Here is the code snippet all i need is insert this io statement but wheni set. It says cannot set headers after they are sent to the clients</p>
```<code>io.on('connection', (socket) => {
  console.log("hiiii")
})

///////////////////////////////////////////////////////
loginrouter.options("/getImages", cors());
loginrouter.get('/getImages',cors(),(req,res)=>{

  var array = fs.readFileSync('log.txt').toString().split("\n");
 for(i in array) {
    var sql = "INSERT into images (urls) values ('"+array[i]+"')";
    connection.query(sql, function (err, result) {
      if (!err) {

        var sql = " SELECT urls FROM `images`";
        connection.query(sql, function(err, result) {
          if (!err) {

            res.send(result)
          }
        });
      }

      })
  }

})
</code>```

Body:
I need to move it inside the get Images function after first sql syntax such that it will be called right after the data is inserted in the database
Here is the code snippet all i need is insert this io statement but wheni set. It says cannot set headers after they are sent to the clients

io.on('connection', (socket) => {
  console.log("hiiii")
})

///////////////////////////////////////////////////////
loginrouter.options("/getImages", cors());
loginrouter.get('/getImages',cors(),(req,res)=>{

  var array = fs.readFileSync('log.txt').toString().split("\n");
 for(i in array) {
    var sql = "INSERT into images (urls) values ('"+array[i]+"')";
    connection.query(sql, function (err, result) {
      if (!err) {

        var sql = " SELECT urls FROM `images`";
        connection.query(sql, function(err, result) {
          if (!err) {

            res.send(result)
          }
        });
      }

      })
  }

})


问:
React-Native - Email Input with suggestions - iOS 16
How is it possible to add a suggestion to email fields? I tried with "textContentType" and read some answers posted in the internet, but without a solution.

I use React-Native 0.70.6 and iOS 16


问:
Runner not picking up on the yml file
```<code>name: ci-cd

on: [push]
jobs:
  build:
    runs-on: self-hosted
    steps:
      - uses: actions/checkout@v2
      - name: Set up JDK 1.8
        uses: actions/setup-java@v1
        with:
          java-version: 1.8
      - name: Build with Maven
        run:
          cd Backend/hellopeople
          mvn test
      - name: Upload artifact
        uses: actions/upload-artifact@v2
        with:
          name: artifact
          path: Backend/target/*.jar

</code>```

this is my yml file for some reason even if I push my code the runner doesnt try to build it

is there an issue with my runner or is it my yml file?

Title: Runner not picking up on the yml file

Body:
name: ci-cd

on: [push]
jobs:
  build:
    runs-on: self-hosted
    steps:
      - uses: actions/checkout@v2
      - name: Set up JDK 1.8
        uses: actions/setup-java@v1
        with:
          java-version: 1.8
      - name: Build with Maven
        run:
          cd Backend/hellopeople
          mvn test
      - name: Upload artifact
        uses: actions/upload-artifact@v2
        with:
          name: artifact
          path: Backend/target/*.jar

this is my yml file for some reason even if I push my code the runner doesnt try to build it

is there an issue with my runner or is it my yml file?


问:
Telegram Bot eventlistener bug
I was trying to code a telegram bot. The bot is a language translation bot. It starts the process when a user clicks on \translate.

Now the issue is:
`

```<code>bot.command("translate", (ctx) => {
  // type in any text the bot will detect the language and translate to your target language
  const outerContext = ctx;
  ctx.reply("Type in any text to translate");

  // get the text from the user
  bot.on("text", async (ctx) => {
    const text = ctx.message.text;
    // get the language code by awaiting on the detect function
    const language = await api.detect(text);
    console.log(language);
    const detectedLanguage = Object.keys(languageCodeMapping).find(
      (key) => languageCodeMapping[key] === language
    );

    ctx.reply(`The detected language is ${detectedLanguage}`);
    ctx.reply("Choose the target language", {
      reply_markup: {
        keyboard: [
          ["english", "chinese", "french", "german", "italian"],
          ["japanese", "korean", "portuguese", "russian", "spanish"],
          ["amharic", "hindi", "arabic", "turkish", "greek"],
        ],
        one_time_keyboard: true,
      },
    });
    bot.on("text", async (ctx) => {
      const targetLanguage = ctx.message.text;
      const translated = await api.translate(
        language,
        languageCodeMapping[targetLanguage],
        text
      );
      ctx.reply(`${translated}`);
    });
  });
});
</code>```

Once the prompt enters the choose target language prompt it keeps on looping inside of there prompting the user to do the same thing again and again. BTW I am using the telegraf module to build this bot.

I tried using different even listeners like bot.hears() but the issue still persists. I am expecting the bot to move on to the next prompt and give the answer to the user.

Title: Telegram Bot eventlistener bug

Body:
I was trying to code a telegram bot. The bot is a language translation bot. It starts the process when a user clicks on \translate.

Now the issue is:
`

bot.command("translate", (ctx) => {
  // type in any text the bot will detect the language and translate to your target language
  const outerContext = ctx;
  ctx.reply("Type in any text to translate");

  // get the text from the user
  bot.on("text", async (ctx) => {
    const text = ctx.message.text;
    // get the language code by awaiting on the detect function
    const language = await api.detect(text);
    console.log(language);
    const detectedLanguage = Object.keys(languageCodeMapping).find(
      (key) => languageCodeMapping[key] === language
    );

    ctx.reply(`The detected language is ${detectedLanguage}`);
    ctx.reply("Choose the target language", {
      reply_markup: {
        keyboard: [
          ["english", "chinese", "french", "german", "italian"],
          ["japanese", "korean", "portuguese", "russian", "spanish"],
          ["amharic", "hindi", "arabic", "turkish", "greek"],
        ],
        one_time_keyboard: true,
      },
    });
    bot.on("text", async (ctx) => {
      const targetLanguage = ctx.message.text;
      const translated = await api.translate(
        language,
        languageCodeMapping[targetLanguage],
        text
      );
      ctx.reply(`${translated}`);
    });
  });
});

Once the prompt enters the choose target language prompt it keeps on looping inside of there prompting the user to do the same thing again and again. BTW I am using the telegraf module to build this bot.

I tried using different even listeners like bot.hears() but the issue still persists. I am expecting the bot to move on to the next prompt and give the answer to the user.


问:
Error with Wagtail URLs for media files: subclasses of Storage must provide a url() method

I am using Wagtail in a project and have a problem with both wagtailimages.Image and wagtaildocs.Document fields. When using DRF to access the URL data I get a "subclasses of Storage must provide a url() method" error. My configuration is that I have to use Bunny.net for storing media files. In order to do that, I use a library called django-bunny-storage (https://pypi.org/project/django-bunny-storage/) that works well with non Wagtail projects.
This is my simplified model in which I removed all other fields:

```<code>class Content(models.Model):
    illustration = models.ForeignKey(
    'wagtailimages.Image',
    null=True,
    blank=True,
    on_delete=models.SET_NULL,
    related_name="+",
    )
    uuid = models.CharField(max_length=255, primary_key=True, default=uuid.uuid4, editable=False)
    document = models.ForeignKey(
        'wagtaildocs.Document',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="+",
    )
    panels = [
        ImageChooserPanel('illustration'),
        DocumentChooserPanel('document'),
    ]

</code>```

As per django-bunny-storage I also had to modify the template context_processors array

```<code>TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.media'

            ],
        },
    },
]

</code>```

I created a small modelserializer for Content that always returns this same error when I try to access the url of the Document or the Image field.

```<code>from wagtail.images.models import Image, AbstractImage, AbstractRendition
from wagtail.documents.models import Document

class ImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = Image
        fields = (('file'),)

class DocumentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Document
        fields = (('file'),)

class ContentSerializer(serializers.ModelSerializer):
    illustration = ImageSerializer(read_only=True)
    document = DocumentSerializer(read_only=True)
    pk=serializers.UUIDField()

    class Meta:
        model = Content
        fields = '_all_'

</code>```

Any idea what it might be?
Many thanks

Body:
I am using Wagtail in a project and have a problem with both wagtailimages.Image and wagtaildocs.Document fields. When using DRF to access the URL data I get a "subclasses of Storage must provide a url() method" error. My configuration is that I have to use Bunny.net for storing media files. In order to do that, I use a library called django-bunny-storage (https://pypi.org/project/django-bunny-storage/) that works well with non Wagtail projects.
This is my simplified model in which I removed all other fields:

class Content(models.Model):
    illustration = models.ForeignKey(
    'wagtailimages.Image',
    null=True,
    blank=True,
    on_delete=models.SET_NULL,
    related_name="+",
    )
    uuid = models.CharField(max_length=255, primary_key=True, default=uuid.uuid4, editable=False)
    document = models.ForeignKey(
        'wagtaildocs.Document',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="+",
    )
    panels = [
        ImageChooserPanel('illustration'),
        DocumentChooserPanel('document'),
    ]

As per django-bunny-storage I also had to modify the template context_processors array

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.media'

            ],
        },
    },
]

I created a small modelserializer for Content that always returns this same error when I try to access the url of the Document or the Image field.

from wagtail.images.models import Image, AbstractImage, AbstractRendition
from wagtail.documents.models import Document

class ImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = Image
        fields = (('file'),)

class DocumentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Document
        fields = (('file'),)

class ContentSerializer(serializers.ModelSerializer):
    illustration = ImageSerializer(read_only=True)
    document = DocumentSerializer(read_only=True)
    pk=serializers.UUIDField()

    class Meta:
        model = Content
        fields = '_all_'

Any idea what it might be?
Many thanks