问:
ValueError: No gradients provided for any variable (TFCamemBERT)
Currently I am working on Named Entity Recognition in the medical domain using Camembert, precisely using the model: TFCamembert.

However I have some problems with the fine-tuning of the model for my task as I am using a private dataset not available on Hugging Face.

The data is divided into text files and annotation files. The text file contains for example:

```<code>Le cas présenté concerne un homme âgé de 61 ans (71 kg, 172 cm, soit un indice de masse corporelle de 23,9 kg/m²) admissible à une transplantation pulmonaire en raison d’une insuffisance respiratoire chronique terminale sur emphysème post-tabagique, sous oxygénothérapie continue (1 L/min) et ventilation non invasive nocturne. Il présente, comme principaux antécédents, une dyslipidémie, une hypertension artérielle et un tabagisme sevré estimé à 21 paquets-années (facteurs de risque cardiovasculaires). Le bilan préopératoire a révélé une hypertension artérielle pulmonaire essentiellement postcapillaire conduisant à l’ajout du périndopril (2 mg par jour) et du furosémide (40 mg par jour). La mise en évidence d’un Elispot (enzyme-linked immunospot) positif pour la tuberculose a motivé l’introduction d’un traitement prophylactique par l’association rifampicine-isoniazide (600-300 mg par jour) pour une durée de trois mois.
Deux mois après le bilan préopératoire, le patient a bénéficié d’une transplantation mono-pulmonaire gauche sans dysfonction primaire du greffon5,6. Le donneur et le receveur présentaient tous deux un statut sérologique positif pour cytomegalovirus (CMV) et Epstein Barr Virus (EBV). Une sérologie positive de la toxoplasmose a été mise en évidence uniquement chez le receveur. Le traitement immunosuppresseur d’induction associait la méthylprednisolone (500 mg à jour 0 et 375 mg à jour +1 post-transplantation) et le basiliximab, anticorps monoclonal dirigé contre l’interleukine-2 (20 mg à jour 0 et jour +4 posttransplantation). À partir de jour +2 post-transplantation, l’immunosuppression a été maintenue par une trithérapie par voie orale comprenant le tacrolimus à une posologie initiale de 5 mg par jour, le mofétil mycophénolate (MMF) 2000 mg par jour et la prednisone 20 mg par jour. Les traitements associés sont présentés dans le tableau I.
L’évolution est marquée par la survenue, au jour +5 posttransplantation, d’une dégradation respiratoire sur œdème pulmonaire gauche de reperfusion, avec possible participation cardiogénique. Le rejet aigu de grade III, évoqué par la présence d’infiltrats lymphocytaires aux biopsies transbronchiques, a été confirmé par l’anatomopathologie.
</code>```

While the annotation file looks like:

```<code>T1 genre 28 33 homme
T2 age 41 47 61 ans
A1 genre T1 masculin
T3 origine 127 326 une transplantation pulmonaire en raison d’une insuffisance respiratoire chronique terminale sur emphysème post-tabagique, sous oxygénothérapie continue (1 L/min) et ventilation non invasive nocturne
T4 issue 1962 2104 une dégradation respiratoire sur œdème pulmonaire gauche de reperfusion, avec possible participation cardiogénique. Le rejet aigu de grade III
A2 issue T4 détérioration
</code>```

More details about the prepossessing of the data can be found in this notebook.

The things is that the internal loss of my model does not work, if I run the training of the model without declaring a loss, it does not work, I have to define a loss to be able to run the training!

Here is my train_data converted to Tensor slice dataset.

```<code>train_label_encodings = tf.convert_to_tensor(train_label_encodings, dtype=tf.int32)
train_label_encodings.data

train_dataset = tf.data.Dataset.from_tensor_slices((
    dict(train_text_encodings.data),
    train_label_encodings.data
))
train_dataset
</code>```
```<code><TensorSliceDataset shapes: ({input_ids: (512,), offset_mapping: (512, 2)}, (512,)), types: ({input_ids: tf.int32, offset_mapping: tf.int32}, tf.int32)>
</code>```

I define the model:

```<code># Import the model and define an optimizer
from transformers import TFAutoModelForTokenClassification, TFCamembertModel, create_optimizer
import tensorflow as tf

num_train_steps = len(train_dataset) * 5
optimizer, lr_schedule = create_optimizer(
    init_lr = 5e-6,
    num_train_steps = num_train_steps,
    weight_decay_rate = 0.01,
    num_warmup_steps = 0
)

metric = tf.keras.metrics.SparseCategoricalAccuracy('accuracy')

model = TFAutoModelForTokenClassification.from_pretrained(model_id, num_labels=len(unique_labels), label2id=label2id, id2label=id2label)

model.compile(optimizer=optimizer, metrics=['accuracy'])
</code>```

Here is the summary of the model:

```<code>Model: "tf_camembert_for_token_classification_2"
_________________________________________________________________
 Layer (type)                Output Shape              Param #
=================================================================
 roberta (TFRobertaMainLayer  multiple                 110031360
 )

 dropout_113 (Dropout)       multiple                  0

 classifier (Dense)          multiple                  25377

=================================================================
Total params: 110,056,737
Trainable params: 110,056,737
Non-trainable params: 0
_________________________________________________________________
</code>```

When I try to launch the training, I get the following error:

```<code>import os
from tensorflow.keras.callbacks import TensorBoard

callbacks = []
callbacks.append(TensorBoard(log_dir=os.path.join(output_dir,"logs")))

model.fit(
    train_dataset,
    callbacks = callbacks,
    epochs = 3,
)
</code>```
```<code>Epoch 1/3
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-71-54e2d25b9415> in <module>()
      8     train_dataset,
      9     callbacks = callbacks,
---> 10     epochs = 3,
     11 )

1 frames
/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/func_graph.py in autograph_handler(*args, **kwargs)
   1127           except Exception as e:  # pylint:disable=broad-except
   1128             if hasattr(e, "ag_error_metadata"):
-> 1129               raise e.ag_error_metadata.to_exception(e)
   1130             else:
   1131               raise

ValueError: in user code:

    File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 878, in train_function  *
        return step_function(self, iterator)
    File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 867, in step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 860, in run_step  **
        outputs = model.train_step(data)
    File "/usr/local/lib/python3.7/dist-packages/transformers/modeling_tf_utils.py", line 911, in train_step
        self.optimizer.minimize(loss, self.trainable_variables, tape=tape)
    File "/usr/local/lib/python3.7/dist-packages/keras/optimizer_v2/optimizer_v2.py", line 532, in minimize
        return self.apply_gradients(grads_and_vars, name=name)
    File "/usr/local/lib/python3.7/dist-packages/transformers/optimization_tf.py", line 232, in apply_gradients
        return super(AdamWeightDecay, self).apply_gradients(zip(grads, tvars), name=name, **kwargs)
    File "/usr/local/lib/python3.7/dist-packages/keras/optimizer_v2/optimizer_v2.py", line 633, in apply_gradients
        grads_and_vars = optimizer_utils.filter_empty_gradients(grads_and_vars)
    File "/usr/local/lib/python3.7/dist-packages/keras/optimizer_v2/utils.py", line 73, in filter_empty_gradients
        raise ValueError(f"No gradients provided for any variable: {variable}. "

    ValueError: No gradients provided for any variable: (['tf_camembert_for_token_classification_2/roberta/encoder/layer_._0/attention/self/query/kernel:0', 'tf_camembert_for_token_classification_2/roberta/encoder/layer_._0/attention/self/query/bias:0', 'tf_camembert_for_token_classification_2/roberta/encoder/layer_._0/attention/self/key/kernel:0', 'tf_camembert_for_token_classification_2/roberta/encoder/layer_._0/attention/self/key/bias:0', 'tf_camembert_for_token_classification_2/roberta/encoder/layer_._0/attention/self/value/kernel:0', 'tf_camembert_for_token_classification_2/roberta/encoder/layer_._0/attention/self/value/bias:0', 'tf_camembert_for_token_classification_2/roberta/encoder/layer_._0/attention/output/dense/kernel:0', 'tf_camembert_for_token_classification_2/roberta/encoder/layer_._0/attention/output/dense/bias:0', 'tf_camembert_for_token_classification_2/roberta/encoder/layer_._0/attention/output/LayerNorm/gamma:0', 'tf_camembert_for_token_classification_2/roberta/encoder/layer_._0/attention/output/LayerNorm/beta:0', 'tf_camembert_for_token_classification_2/roberta/encoder/layer_._0/intermediate/dense/kernel:0', 'tf_camembert_for_token_classification_2/roberta/encoder/layer_._0/intermediate/dense/bias:0', 'tf_camembert_for_token_classification_2/roberta/encoder/layer_._0/output/dense/kernel:0', 'tf_camembert_for_token_classification_2/roberta/encoder/layer_._0/output/dense/bias:0', 'tf_camembert_for_token_classification_2/roberta/encoder/layer_._0/output/La...
</code>```

Any clues to solve this gradient issue? Thanks in advance!

答:
Try transforming your data into the correct format, before feeding it to model.fit:

def map_func(x, y):
  return {'input_ids': x['input_ids'], 'attention_mask': x['attention_mask'], 'labels':y}

train_dataset = train_dataset.map(map_func)
```

The model seems to run after this step.

Body:
Currently I am working on Named Entity Recognition in the medical domain using Camembert, precisely using the model: TFCamembert.

However I have some problems with the fine-tuning of the model for my task as I am using a private dataset not available on Hugging Face.

The data is divided into text files and annotation files. The text file contains for example:

Le cas présenté concerne un homme âgé de 61 ans (71 kg, 172 cm, soit un indice de masse corporelle de 23,9 kg/m²) admissible à une transplantation pulmonaire en raison d’une insuffisance respiratoire chronique terminale sur emphysème post-tabagique, sous oxygénothérapie continue (1 L/min) et ventilation non invasive nocturne. Il présente, comme principaux antécédents, une dyslipidémie, une hypertension artérielle et un tabagisme sevré estimé à 21 paquets-années (facteurs de risque cardiovasculaires). Le bilan préopératoire a révélé une hypertension artérielle pulmonaire essentiellement postcapillaire conduisant à l’ajout du périndopril (2 mg par jour) et du furosémide (40 mg par jour). La mise en évidence d’un Elispot (enzyme-linked immunospot) positif pour la tuberculose a motivé l’introduction d’un traitement prophylactique par l’association rifampicine-isoniazide (600-300 mg par jour) pour une durée de trois mois.
Deux mois après le bilan préopératoire, le patient a bénéficié d’une transplantation mono-pulmonaire gauche sans dysfonction primaire du greffon5,6. Le donneur et le receveur présentaient tous deux un statut sérologique positif pour cytomegalovirus (CMV) et Epstein Barr Virus (EBV). Une sérologie positive de la toxoplasmose a été mise en évidence uniquement chez le receveur. Le traitement immunosuppresseur d’induction associait la méthylprednisolone (500 mg à jour 0 et 375 mg à jour +1 post-transplantation) et le basiliximab, anticorps monoclonal dirigé contre l’interleukine-2 (20 mg à jour 0 et jour +4 posttransplantation). À partir de jour +2 post-transplantation, l’immunosuppression a été maintenue par une trithérapie par voie orale comprenant le tacrolimus à une posologie initiale de 5 mg par jour, le mofétil mycophénolate (MMF) 2000 mg par jour et la prednisone 20 mg par jour. Les traitements associés sont présentés dans le tableau I.
L’évolution est marquée par la survenue, au jour +5 posttransplantation, d’une dégradation respiratoire sur œdème pulmonaire gauche de reperfusion, avec possible participation cardiogénique. Le rejet aigu de grade III, évoqué par la présence d’infiltrats lymphocytaires aux biopsies transbronchiques, a été confirmé par l’anatomopathologie.

While the annotation file looks like:

T1 genre 28 33 homme
T2 age 41 47 61 ans
A1 genre T1 masculin
T3 origine 127 326 une transplantation pulmonaire en raison d’une insuffisance respiratoire chronique terminale sur emphysème post-tabagique, sous oxygénothérapie continue (1 L/min) et ventilation non invasive nocturne
T4 issue 1962 2104 une dégradation respiratoire sur œdème pulmonaire gauche de reperfusion, avec possible participation cardiogénique. Le rejet aigu de grade III
A2 issue T4 détérioration

More details about the prepossessing of the data can be found in this notebook.

The things is that the internal loss of my model does not work, if I run the training of the model without declaring a loss, it does not work, I have to define a loss to be able to run the training!

Here is my train_data converted to Tensor slice dataset.

train_label_encodings = tf.convert_to_tensor(train_label_encodings, dtype=tf.int32)
train_label_encodings.data

train_dataset = tf.data.Dataset.from_tensor_slices((
    dict(train_text_encodings.data),
    train_label_encodings.data
))
train_dataset

<TensorSliceDataset shapes: ({input_ids: (512,), offset_mapping: (512, 2)}, (512,)), types: ({input_ids: tf.int32, offset_mapping: tf.int32}, tf.int32)>

I define the model:

# Import the model and define an optimizer
from transformers import TFAutoModelForTokenClassification, TFCamembertModel, create_optimizer
import tensorflow as tf

num_train_steps = len(train_dataset) * 5
optimizer, lr_schedule = create_optimizer(
    init_lr = 5e-6,
    num_train_steps = num_train_steps,
    weight_decay_rate = 0.01,
    num_warmup_steps = 0
)

metric = tf.keras.metrics.SparseCategoricalAccuracy('accuracy')

model = TFAutoModelForTokenClassification.from_pretrained(model_id, num_labels=len(unique_labels), label2id=label2id, id2label=id2label)

model.compile(optimizer=optimizer, metrics=['accuracy'])

Here is the summary of the model:

Model: "tf_camembert_for_token_classification_2"
_________________________________________________________________
 Layer (type)                Output Shape              Param #
=================================================================
 roberta (TFRobertaMainLayer  multiple                 110031360
 )

 dropout_113 (Dropout)       multiple                  0

 classifier (Dense)          multiple                  25377

=================================================================
Total params: 110,056,737
Trainable params: 110,056,737
Non-trainable params: 0
_________________________________________________________________

When I try to launch the training, I get the following error:

import os
from tensorflow.keras.callbacks import TensorBoard

callbacks = []
callbacks.append(TensorBoard(log_dir=os.path.join(output_dir,"logs")))

model.fit(
    train_dataset,
    callbacks = callbacks,
    epochs = 3,
)

Epoch 1/3
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-71-54e2d25b9415> in <module>()
      8     train_dataset,
      9     callbacks = callbacks,
---> 10     epochs = 3,
     11 )

1 frames
/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/func_graph.py in autograph_handler(*args, **kwargs)
   1127           except Exception as e:  # pylint:disable=broad-except
   1128             if hasattr(e, "ag_error_metadata"):
-> 1129               raise e.ag_error_metadata.to_exception(e)
   1130             else:
   1131               raise

ValueError: in user code:

    File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 878, in train_function  *
        return step_function(self, iterator)
    File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 867, in step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 860, in run_step  **
        outputs = model.train_step(data)
    File "/usr/local/lib/python3.7/dist-packages/transformers/modeling_tf_utils.py", line 911, in train_step
        self.optimizer.minimize(loss, self.trainable_variables, tape=tape)
    File "/usr/local/lib/python3.7/dist-packages/keras/optimizer_v2/optimizer_v2.py", line 532, in minimize
        return self.apply_gradients(grads_and_vars, name=name)
    File "/usr/local/lib/python3.7/dist-packages/transformers/optimization_tf.py", line 232, in apply_gradients
        return super(AdamWeightDecay, self).apply_gradients(zip(grads, tvars), name=name, **kwargs)
    File "/usr/local/lib/python3.7/dist-packages/keras/optimizer_v2/optimizer_v2.py", line 633, in apply_gradients
        grads_and_vars = optimizer_utils.filter_empty_gradients(grads_and_vars)
    File "/usr/local/lib/python3.7/dist-packages/keras/optimizer_v2/utils.py", line 73, in filter_empty_gradients
        raise ValueError(f"No gradients provided for any variable: {variable}. "

    ValueError: No gradients provided for any variable: (['tf_camembert_for_token_classification_2/roberta/encoder/layer_._0/attention/self/query/kernel:0', 'tf_camembert_for_token_classification_2/roberta/encoder/layer_._0/attention/self/query/bias:0', 'tf_camembert_for_token_classification_2/roberta/encoder/layer_._0/attention/self/key/kernel:0', 'tf_camembert_for_token_classification_2/roberta/encoder/layer_._0/attention/self/key/bias:0', 'tf_camembert_for_token_classification_2/roberta/encoder/layer_._0/attention/self/value/kernel:0', 'tf_camembert_for_token_classification_2/roberta/encoder/layer_._0/attention/self/value/bias:0', 'tf_camembert_for_token_classification_2/roberta/encoder/layer_._0/attention/output/dense/kernel:0', 'tf_camembert_for_token_classification_2/roberta/encoder/layer_._0/attention/output/dense/bias:0', 'tf_camembert_for_token_classification_2/roberta/encoder/layer_._0/attention/output/LayerNorm/gamma:0', 'tf_camembert_for_token_classification_2/roberta/encoder/layer_._0/attention/output/LayerNorm/beta:0', 'tf_camembert_for_token_classification_2/roberta/encoder/layer_._0/intermediate/dense/kernel:0', 'tf_camembert_for_token_classification_2/roberta/encoder/layer_._0/intermediate/dense/bias:0', 'tf_camembert_for_token_classification_2/roberta/encoder/layer_._0/output/dense/kernel:0', 'tf_camembert_for_token_classification_2/roberta/encoder/layer_._0/output/dense/bias:0', 'tf_camembert_for_token_classification_2/roberta/encoder/layer_._0/output/La...

Any clues to solve this gradient issue? Thanks in advance!

Body:
Try transforming your data into the correct format, before feeding it to model.fit:

def map_func(x, y):
  return {'input_ids': x['input_ids'], 'attention_mask': x['attention_mask'], 'labels':y}

train_dataset = train_dataset.map(map_func)

The model seems to run after this step.


来源: stackexchange

问:
C++ BitField class with variadic template and parameters pack
I'm trying to implement a BitField template class for C++11/14, my base idea is:

```<code>template <typename T, size_t... Bits>
class BitField
{
    public:

        BitField();

    private:

        T value;
};

template <typename T, size_t... Bits>
BitField<T, Bits...>::BitField()
{
}
</code>```

and then as an example instantiate it like this:

```<code>BitField<uint8_t, 2, 3, 3> bitfield;
</code>```

where 2, 3, 3 are the sizes of the 3 bitfields, offsets come consequently (please let's ignore bit order by now).

Of course this is just a skeleton to be filled with appropriate setters and getters methods, now my question is: how can I get Bits values in the constructor to check if their sum fits the type, possibly at compile time?

More in general, can this be a good approach for this problem? I say other solutions but for many reasons I don't like them too much.

Thanks, Matteo

答:
You can check size with (C++17)

```<code>static_assert(sizeof(T) == (Bits + ...));
</code>```

Before fold-expression of C++17, there are workaround more verbose.

Create a function

```<code>template <std::size_t... Bits>
constexpr std::size_t sum()
{
    const std::size_t numbers[] = {Bits...};
    // std::accumulate in constexpr only since C++20
    std::size_t res = 0;

    for (auto number : numbers) {
        res += number;
    }
    return res;
}
</code>```

and then

```<code>static_assert(sizeof(T) == sum<Bits...>());
</code>```

You can even use lambda instead of helper function if wanted.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to implement a BitField template class for C++11/14, my base idea is:

template <typename T, size_t... Bits>
class BitField
{
    public:

        BitField();

    private:

        T value;
};

template <typename T, size_t... Bits>
BitField<T, Bits...>::BitField()
{
}

and then as an example instantiate it like this:

BitField<uint8_t, 2, 3, 3> bitfield;

where 2, 3, 3 are the sizes of the 3 bitfields, offsets come consequently (please let's ignore bit order by now).

Of course this is just a skeleton to be filled with appropriate setters and getters methods, now my question is: how can I get Bits values in the constructor to check if their sum fits the type, possibly at compile time?

More in general, can this be a good approach for this problem? I say other solutions but for many reasons I don't like them too much.

Thanks, Matteo

Body:
You can check size with (C++17)

static_assert(sizeof(T) == (Bits + ...));

Before fold-expression of C++17, there are workaround more verbose.

Create a function

template <std::size_t... Bits>
constexpr std::size_t sum()
{
    const std::size_t numbers[] = {Bits...};
    // std::accumulate in constexpr only since C++20
    std::size_t res = 0;

    for (auto number : numbers) {
        res += number;
    }
    return res;
}

and then

static_assert(sizeof(T) == sum<Bits...>());

You can even use lambda instead of helper function if wanted.


问:
how to load the SQL tables data into ignite cache in table format?
Loading sql table data into ignite cache but its getting loaded in key value pairs but i would need to load in table format, can you please advise?
Sample code snippet:

IgniteCache<Integer, BinaryObject> binaryCache = ignite.createCache(cacheName).withKeepBinary();
BinaryObjectBuilder builder = ignite.binary().builder(cacheName);
builder.setField(columnsName, sourceResultSet.getString(values)); } binaryCache.put(resultSetRowCount, builder.build()); }

答:
Ignite is a key-value database with SQL support. It's entirely valid to load data into a table using the key-value API and query it using SQL.

You need to define the table structure when you create your cache. Since you don't to use model classes/annotations, you'll need to use query entities.

Example from the documentation:

```<code>class Person implements Serializable {
    private long id;

    private String name;

    private int age;

    private float salary;
}

public static void main(String[] args) {
    Ignite ignite = Ignition.start();
    CacheConfiguration<Long, Person> personCacheCfg = new CacheConfiguration<Long, Person>();
    personCacheCfg.setName("Person");

    QueryEntity queryEntity = new QueryEntity(Long.class, Person.class)
            .addQueryField("id", Long.class.getName(), null).addQueryField("age", Integer.class.getName(), null)
            .addQueryField("salary", Float.class.getName(), null)
            .addQueryField("name", String.class.getName(), null);

    queryEntity.setIndexes(Arrays.asList(new QueryIndex("id"), new QueryIndex("salary", false)));

    personCacheCfg.setQueryEntities(Arrays.asList(queryEntity));

    IgniteCache<Long, Person> cache = ignite.createCache(personCacheCfg);
}
</code>```

Body:
Ignite is a key-value database with SQL support. It's entirely valid to load data into a table using the key-value API and query it using SQL.

You need to define the table structure when you create your cache. Since you don't to use model classes/annotations, you'll need to use query entities.

Example from the documentation:

class Person implements Serializable {
    private long id;

    private String name;

    private int age;

    private float salary;
}

public static void main(String[] args) {
    Ignite ignite = Ignition.start();
    CacheConfiguration<Long, Person> personCacheCfg = new CacheConfiguration<Long, Person>();
    personCacheCfg.setName("Person");

    QueryEntity queryEntity = new QueryEntity(Long.class, Person.class)
            .addQueryField("id", Long.class.getName(), null).addQueryField("age", Integer.class.getName(), null)
            .addQueryField("salary", Float.class.getName(), null)
            .addQueryField("name", String.class.getName(), null);

    queryEntity.setIndexes(Arrays.asList(new QueryIndex("id"), new QueryIndex("salary", false)));

    personCacheCfg.setQueryEntities(Arrays.asList(queryEntity));

    IgniteCache<Long, Person> cache = ignite.createCache(personCacheCfg);
}


问:
I need information about Informatica
I need some information about the Informatica ETL tool. I am a rookie with that, so could you please recommend where can I get some tutorials to get started. Can I download the tool, and if so where can I download it? What are the alternatives to Informatica?</p>

答: Try Oracle Business Intelligence Application (OBIA). They supply you with a numerous BI Aplpications, including PowerCenter. Used to be free of charge fon non-productive environments</p>

ContentLicense: CC BY-SA 2.5

Title: I need information about Informatica

ContentLicense: CC BY-SA 3.0


问:
Numbering a nested list in a single ol list
I have an ordered list with some li tags in it. I want the The li tags with  .sub-item class to be nested li tags. Is there a way I can reset numbering for the li tags having class? The list is as below:

```<code><ol>
  <li>One</li>
  <li>Two</li>
  <li>THree</li>
  <li class="sub-item">Sub three 1</li>
  <li class="sub-item">Sub three 2</li>
  <li>Four</li>
</ol>
</code>```

Currently I get which makes sense:

```<code>  1 One
  2 Two
  3 Three
  4 Sub Three 1
  5 Sub three 2
  6 Four
</code>```

However using the class 'sub-item' I want this desired behaviour

```<code>  1 One
  2 Two
  3. Three
     a Sub three 1
     b Sub Three 2
  4 Four
</code>```

I can not change the html part of the code, only can write css. Adding nested ol tags will not work in this case as I can not modify the html.

答:
This will work.

.sub-item {
    list-style-type: lower-alpha;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ol>
    <li>One</li>
    <li>Two</li>
    <li>THree
        <ol>
            <li class="sub-item">Sub three 1</li>
            <li class="sub-item">Sub three 2</li>
        </ol>
    </li>
    <li>Four</li>
</ol></code>```

Body:
I have an ordered list with some li tags in it. I want the The li tags with  .sub-item class to be nested li tags. Is there a way I can reset numbering for the li tags having class? The list is as below:

One

Two

THree

Sub three 1

Sub three 2

Four

Currently I get which makes sense:

  1 One
  2 Two
  3 Three
  4 Sub Three 1
  5 Sub three 2
  6 Four

However using the class 'sub-item' I want this desired behaviour

  1 One
  2 Two
  3. Three
     a Sub three 1
     b Sub Three 2
  4 Four

I can not change the html part of the code, only can write css. Adding nested ol tags will not work in this case as I can not modify the html.

Body:
This will work.

.sub-item {
    list-style-type: lower-alpha;
}

<ol>
    <li>One</li>
    <li>Two</li>
    <li>THree
        <ol>
            <li class="sub-item">Sub three 1</li>
            <li class="sub-item">Sub three 2</li>
        </ol>
    </li>
    <li>Four</li>
</ol>


问:
How to unmarshal escaped string
I have a dumb question regarding JSON string unmarshalling in Go

Here's the code:

```<code>package main

import (
    "bytes"
    "encoding/json"
    "fmt"
)

func main() {
    s := "{\"just_a_key\":\"Some text \"some quoted text\"\"}"
    fmt.Println(s)
    buf := bytes.NewBufferString(s)
    data := make(map[string]string)

    err := json.Unmarshal(buf.Bytes(), &data)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(data)
}
</code>```

The output:

```<code>{"just_a_key":"Some text "some quoted text""}
invalid character 's' after object key:value pair
</code>```

Seems like unmarshaller really hates '\"' sequence. How can I fix the issue?

答:
Your input is not valid JSON. To have a double quote inside a JSON string, you have to escape it. Use the \" sequence for a double quote character.

But since you're using an interpreted Go string literal to specify the JSON text, the \" sequence also have to be escaped according to the Go interpreted rules, where a backslash is \\ and the double quote is \", so the JSON \" sequence must appear as \\\" in a Go interpreted string literal:

```<code>s := "{\"just_a_key\":\"Some text \\\"some quoted text\\\"\"}"
</code>```

With this change output is (try it on the Go Playground):

```<code>{"just_a_key":"Some text \"some quoted text\""}
map[just_a_key:Some text "some quoted text"]
</code>```

It's much easier and cleaner if you use raw string literal (where no Go escaping is needed, just the JSON escaping):

```<code>s := `{"just_a_key":"Some text \"some quoted text\""}`
</code>```

This will output the same. Try this one on the Go Playground.

Title: How to unmarshal escaped string

Body:
I have a dumb question regarding JSON string unmarshalling in Go

Here's the code:

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
)

func main() {
    s := "{\"just_a_key\":\"Some text \"some quoted text\"\"}"
    fmt.Println(s)
    buf := bytes.NewBufferString(s)
    data := make(map[string]string)

    err := json.Unmarshal(buf.Bytes(), &data)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(data)
}

The output:

{"just_a_key":"Some text "some quoted text""}
invalid character 's' after object key:value pair

Seems like unmarshaller really hates '\"' sequence. How can I fix the issue?

Body:
Your input is not valid JSON. To have a double quote inside a JSON string, you have to escape it. Use the \" sequence for a double quote character.

But since you're using an interpreted Go string literal to specify the JSON text, the \" sequence also have to be escaped according to the Go interpreted rules, where a backslash is \\ and the double quote is \", so the JSON \" sequence must appear as \\\" in a Go interpreted string literal:

s := "{\"just_a_key\":\"Some text \\\"some quoted text\\\"\"}"

With this change output is (try it on the Go Playground):

{"just_a_key":"Some text \"some quoted text\""}
map[just_a_key:Some text "some quoted text"]

It's much easier and cleaner if you use raw string literal (where no Go escaping is needed, just the JSON escaping):

s := `{"just_a_key":"Some text \"some quoted text\""}`

This will output the same. Try this one on the Go Playground.


问:
Popup Display once in homepage
Hi i have a popup script for blogger but ,i dont want it again to be apperaed once again when returning to homepage when he seen it before like it should present only once for the user</p>
```<code>  <b:if cond='data:blog.url == data:blog.homepageUrl'>
  <div class='popup-overlay'>
  <div class='popup-container'>
    <div class='popup-close'>+</div>
    <b> <h2 class='popup-title'>Welcome to Free Community!</h2></b>
    <p class='popup-description'>
     Hi,
   Thank you for Visiting up for our Website. We appreciate your interest.
   We will do our best to Bring you More Fun Videos for GTA 5 ,Thank You!
    </p>

    </div>
    </div>
    <script>
    const popupOverlay = document.querySelector(".popup-overlay");
   const popupClose = document.querySelector(".popup-close");

   popupClose.addEventListener("click", () => {
   popupOverlay.style.display = "none";
    });

   setTimeout(() => {
   popupOverlay.style.display = "block";
   }, 3000);
   </script>
   </b:if>
</code>```

答:
You can use the localStorage to have the user's browser save a value that will tell you if the user has already visited your site.

To save the value do localStorage["key"] = "value".

Show the popup only if localStorage["key"] != "value".

The full logic would be:

```<code>if (localStorage["key"] != "value") {
  // show popup
  localStorage["key"] == "value";
}
</code>```

Title: Popup Display once in homepage

Body:
Hi i have a popup script for blogger but ,i dont want it again to be apperaed once again when returning to homepage when he seen it before like it should present only once for the user

+

Welcome to Free Community!

     Hi,
   Thank you for Visiting up for our Website. We appreciate your interest.
   We will do our best to Bring you More Fun Videos for GTA 5 ,Thank You!

Body:
You can use the localStorage to have the user's browser save a value that will tell you if the user has already visited your site.

To save the value do localStorage["key"] = "value".

Show the popup only if localStorage["key"] != "value".

The full logic would be:

if (localStorage["key"] != "value") {
  // show popup
  localStorage["key"] == "value";
}


问:
JSON.stringify() array bizarreness with Prototype.js
I'm trying to figure out what's gone wrong with my json serializing, have the current version of my app with and old one and am finding some surprising differences in the way JSON.stringify() works (Using the JSON library from json.org).

In the old version of my app:

```<code> JSON.stringify({"a":[1,2]})
</code>```

gives me this;

```<code>"{\"a\":[1,2]}"
</code>```

in the new version,

```<code> JSON.stringify({"a":[1,2]})
</code>```

gives me this;

```<code>"{\"a\":\"[1, 2]\"}"
</code>```

any idea what could have changed to make the same library put quotes around the array brackets in the new version?

答:
Here's how I'm dealing with it.</p>

```<code>var methodCallString =  Object.toJSON? Object.toJSON(options.jsonMethodCall) :  JSON.stringify(options.jsonMethodCall);
</code>```

OwnerDisplayName: morgancodes

Body:
I'm trying to figure out what's gone wrong with my json serializing, have the current version of my app with and old one and am finding some surprising differences in the way JSON.stringify() works (Using the JSON library from json.org).

In the old version of my app:

 JSON.stringify({"a":[1,2]})

gives me this;

"{\"a\":[1,2]}"

in the new version,

 JSON.stringify({"a":[1,2]})

gives me this;

"{\"a\":\"[1, 2]\"}"

any idea what could have changed to make the same library put quotes around the array brackets in the new version?

LastEditorDisplayName: Matthew Crumley

Body:
Here's how I'm dealing with it.

var methodCallString =  Object.toJSON? Object.toJSON(options.jsonMethodCall) :  JSON.stringify(options.jsonMethodCall);


问:
MSBUILD web deploy package zip file does not inherit permissions from parent folder
I'm creating a zip file from msbuild using the package target.  It creates it fine and the folder I'm putting it in has permissions for a user that allows that user to have full control of the folder.  However, when I remove the zip file, then run msbuild to create the zip file again the zip file has lost the permissions for that user.

So then I am using a certain user to programatically deploy the package file and that user no longer has permissions.

How can I force that zip file to inherit the permissions from the parent folder so I don't have to manually add the permissions back to the zip file each time msbuild creates it?

答:
Turns out there isn't a specific way to tell the Package target to set the permissions.  So the workaround is to set the permissions yourself after the Package target.

Here is how I did it.  The regular expression part is to pull the name of the project file out of the project file path we have in our build script.  That name matches up to the .\Output\Packages\ folder that is created.  I then call cacls inside an exec command to set the permissions on every file in that directory for the user I specify.

```<code>  <Target Name="Package">
    <MSBuild Projects="@(PackageProject)" Targets="Package" Properties="Platform=$(Platform);
                                                                           Configuration=$(Configuration);
                                                                           DeployOnBuild=true;
                                                                           DeployTarget=Package;
                                       PackageLocation=$(PackageOutputDir)\$([System.Text.RegularExpressions.Regex]::Split($(ProjectName), '(.*\\)([a-z,A-Z,0-9,_,-]+)(\.\*proj;)')[2])\$([System.Text.RegularExpressions.Regex]::Split($(ProjectName), '(.*\\)([a-z,A-Z,0-9,_,-]+)(\.\*proj;)')[2]).zip;
                                       PackageAsSingleFile=true;
                                       ExcludeFilesFromDeployment=Web.config;
                                       _PackageTempDir=$(PackageOutputDir)\temp;">
    </MSBuild>
    <Exec Command="echo y| cacls $(PackageOutputDir)\$([System.Text.RegularExpressions.Regex]::Split($(ProjectName), '(.*\\)([a-z,A-Z,0-9,_,-]+)(\.\*proj;)')[2])\* /G NetworkService:F"/>
  </Target>
</code>```

Body:
Turns out there isn't a specific way to tell the Package target to set the permissions.  So the workaround is to set the permissions yourself after the Package target.

Here is how I did it.  The regular expression part is to pull the name of the project file out of the project file path we have in our build script.  That name matches up to the .\Output\Packages\ folder that is created.  I then call cacls inside an exec command to set the permissions on every file in that directory for the user I specify.

  <Target Name="Package">
    <MSBuild Projects="@(PackageProject)" Targets="Package" Properties="Platform=$(Platform);
                                                                           Configuration=$(Configuration);
                                                                           DeployOnBuild=true;
                                                                           DeployTarget=Package;
                                       PackageLocation=$(PackageOutputDir)\$([System.Text.RegularExpressions.Regex]::Split($(ProjectName), '(.*\\)([a-z,A-Z,0-9,_,-]+)(\.\*proj;)')[2])\$([System.Text.RegularExpressions.Regex]::Split($(ProjectName), '(.*\\)([a-z,A-Z,0-9,_,-]+)(\.\*proj;)')[2]).zip;
                                       PackageAsSingleFile=true;
                                       ExcludeFilesFromDeployment=Web.config;
                                       _PackageTempDir=$(PackageOutputDir)\temp;">
    </MSBuild>
    <Exec Command="echo y| cacls $(PackageOutputDir)\$([System.Text.RegularExpressions.Regex]::Split($(ProjectName), '(.*\\)([a-z,A-Z,0-9,_,-]+)(\.\*proj;)')[2])\* /G NetworkService:F"/>
  </Target>


问:
How to copy a file between docker containers?
I have two different docker containers, each of them runs a PHP application. The problem that I have to solve is copy a list of files (using the PHP copy command) from container 1 to container 2.

Eg:

```<code>copy('var/www/html/uploads/test.jpg', 'var/www/html/site/uploads/test.jpg');
</code>```

Now, the container 1 doesn't have access to container 2 which is site.

What is the best way to fix this?

答:
Use a shared volume to transfer data. So mount

```<code>-v filetransfer:/var/www/html/transfer
or
--mount type=volume,source=filetransfer,destination=/var/www/html/transfer
</code>```

to both containers. If both containers running different non-root users you have to ensure file permissions are set accordingly.
If you want to avoid file corruption use :ro (read-only) for all but one containers or ensure that by code.

Other comments:

docker cp is used to copy files from host to container or vice versa.

Building a REST-API for copying a single file is in my opinion a little bit over-engineered, as long as you're using the same host.

Body:
I have two different docker containers, each of them runs a PHP application. The problem that I have to solve is copy a list of files (using the PHP copy command) from container 1 to container 2.

Eg:

copy('var/www/html/uploads/test.jpg', 'var/www/html/site/uploads/test.jpg');

Now, the container 1 doesn't have access to container 2 which is site.

What is the best way to fix this?

Body:
Use a shared volume to transfer data. So mount

-v filetransfer:/var/www/html/transfer
or
--mount type=volume,source=filetransfer,destination=/var/www/html/transfer

to both containers. If both containers running different non-root users you have to ensure file permissions are set accordingly.
If you want to avoid file corruption use :ro (read-only) for all but one containers or ensure that by code.

Other comments:

docker cp is used to copy files from host to container or vice versa.

Building a REST-API for copying a single file is in my opinion a little bit over-engineered, as long as you're using the same host.


问:
Accessing a dynamically created multi dimensional array with pointers arithmetic
I would like to understand how does it works to scan a dynamically allocated two-dimensional array using pointers arithmetics?

I can't figurate why in my example pointer arithmetic isn't returning the same results as using array indexing.

Here is my implementation:

```<code>    #include <iostream>
    using namespace std;

void init_matrix(int ** m, int size);
void print_matrix(int ** m, int size);
void print_matrix_pointers(int ** m, int size);

int main (){
    srand (time(NULL));
    int size = 3;
    int ** dynamic_matrix = new int * [size];
    for (int i = 0; i < 10; i++) {
        dynamic_matrix[i] = new int [size];
    }
    init_matrix(dynamic_matrix, size);

    cout << "Dynamic matrix accessed using square brackets ([i][j]): " << endl;
    print_matrix(dynamic_matrix, size);

    cout << "Dynamic matrix accessed using pointers arithmetics: " << endl;
    print_matrix_pointers(dynamic_matrix, size);

    return 0;

}

void init_matrix(int ** m, int size) {
    for (int i = 0; i < size; i++){
        for (int j = 0; j < size; j++){
            m[i][j] = rand()%10;
        }
    }
}

void print_matrix(int ** m, int size){
    for (int i = 0; i < size; i++){
        for (int j = 0; j < size; j++){
            cout << m[i][j] << " ";
        }
        cout << endl;
    }
}

void print_matrix_pointers(int ** m, int size){
    for (int i = 0; i < size; i++){
        for (int j = 0; j < size; j++){
            cout << *(*m + (i * size) + j) << " "; //
        }
        cout << endl;
    }
    cout << endl;
}
</code>```

For instance if size was 3 I would get this output.

Dynamic matrix accessed using array indexing ([i][j]):

3 3 4

9 5 9

4 9 4

Dynamic matrix accessed using pointers arithmetics:

3 3 4

32735 9 5

9 32735 4

答:
Two typos in your code:

```<code>int size = 3;
int ** dynamic_matrix = new int * [size];
for (int i = 0; i < 10; i++) {
    dynamic_matrix[i] = new int [size];
}
</code>```

size is 3 but you write 10 elements. That is undefined behavior.

Then you are advancing the pointer wrongly.

```<code>void print_matrix_pointers(int ** m, int size){
    for (int i = 0; i < size; i++){
        for (int j = 0; j < size; j++){
            cout << *( *(m + i) + j) << " "; //
        }
        cout << endl;
    }
    cout << endl;
}
</code>```

m points to an array of pointers to int. You have to increment m by i to get to the i-th row. Then you want to access the jth element of the array pointed to by m[i], hence you have to first dereference m+i then add j to get the address of jth element.

Body:
I would like to understand how does it works to scan a dynamically allocated two-dimensional array using pointers arithmetics?

I can't figurate why in my example pointer arithmetic isn't returning the same results as using array indexing.

Here is my implementation:

    #include <iostream>
    using namespace std;

void init_matrix(int ** m, int size);
void print_matrix(int ** m, int size);
void print_matrix_pointers(int ** m, int size);

int main (){
    srand (time(NULL));
    int size = 3;
    int ** dynamic_matrix = new int * [size];
    for (int i = 0; i < 10; i++) {
        dynamic_matrix[i] = new int [size];
    }
    init_matrix(dynamic_matrix, size);

    cout << "Dynamic matrix accessed using square brackets ([i][j]): " << endl;
    print_matrix(dynamic_matrix, size);

    cout << "Dynamic matrix accessed using pointers arithmetics: " << endl;
    print_matrix_pointers(dynamic_matrix, size);

    return 0;

}

void init_matrix(int ** m, int size) {
    for (int i = 0; i < size; i++){
        for (int j = 0; j < size; j++){
            m[i][j] = rand()%10;
        }
    }
}

void print_matrix(int ** m, int size){
    for (int i = 0; i < size; i++){
        for (int j = 0; j < size; j++){
            cout << m[i][j] << " ";
        }
        cout << endl;
    }
}

void print_matrix_pointers(int ** m, int size){
    for (int i = 0; i < size; i++){
        for (int j = 0; j < size; j++){
            cout << *(*m + (i * size) + j) << " "; //
        }
        cout << endl;
    }
    cout << endl;
}

For instance if size was 3 I would get this output.

Dynamic matrix accessed using array indexing ([i][j]):

3 3 4

9 5 9

4 9 4

Dynamic matrix accessed using pointers arithmetics:

3 3 4

32735 9 5

9 32735 4

Body:
Two typos in your code:

int size = 3;
int ** dynamic_matrix = new int * [size];
for (int i = 0; i < 10; i++) {
    dynamic_matrix[i] = new int [size];
}

size is 3 but you write 10 elements. That is undefined behavior.

Then you are advancing the pointer wrongly.

void print_matrix_pointers(int ** m, int size){
    for (int i = 0; i < size; i++){
        for (int j = 0; j < size; j++){
            cout << *( *(m + i) + j) << " "; //
        }
        cout << endl;
    }
    cout << endl;
}

m points to an array of pointers to int. You have to increment m by i to get to the i-th row. Then you want to access the jth element of the array pointed to by m[i], hence you have to first dereference m+i then add j to get the address of jth element.


问:
NGINX Error; 1 rewrite or internal redirection cycle while internally redirecting to "/index.html"
```<code>2021/02/23 18:50:45 [error] 3476#3476: *1 rewrite or internal redirection cycle while internally redirecting to "/index.html", client: 192.168.0.50, server: _, request: "GET /search HTTP/1.1", host: "192.168.0.94", referrer: "http://192.168.0.94/"
</code>```

I am trying to make a website using node.js as I want to implement other apps in the future. I am able to get sub-directories on my PC, but when I try to use on anything, I get this error.

Here's my config:

```<code>server {
    listen 80;
    server_name _;

    error_log /var/log/nginx/personalsite.error.log;

    root /var/www/html/;
    index search.html;

    location / {
        proxy_pass http://localhost:3000;
        try_files $uri $uri/ =404;
    }

    location ^~ /search/ {
        alias /var/www/html/views/;
    }

    location ^~ /results/ {
        alias /var/www/html/views/;
    }

}
</code>```

And my app.js:

const express = require('express');
const path = require('path');

// Init App
const app = express();

// Load View Engine
app.use('/css', express.static(path.join(__dirname, 'css')));
app.use('/js', express.static(path.join(__dirname, 'js')));

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// Web Routes
app.engine('html', require('ejs').renderFile);
app.use(express.urlencoded({extended: true}));

app.get('/', (req, res) => {
    res.render('index.html');
});

app.get('/search', (req, res) => {
    res.render('search.html');
});

app.get('/results', (req, res) => {
    res.render('results.html');
});

app.get('/found', (req, res) => {
    res.render('found.html');
});

app.get('/player', (req, res) => {
    res.render('player.html');
});

// Start Server
app.listen('3000', () => {
    console.log('Listening on port 3000!');
});
```

If you know why this is the issue that would help me massivley, thanks!

答:
Try to replace

```<code>try_files $uri $uri/ =404;
</code>```

to

```<code> try_files $uri $uri/ index.html;
</code>```

Read more on Nginx rewrite or internal redirection cycle while internally redirecting to "/index.html"

Body:
2021/02/23 18:50:45 [error] 3476#3476: *1 rewrite or internal redirection cycle while internally redirecting to "/index.html", client: 192.168.0.50, server: _, request: "GET /search HTTP/1.1", host: "192.168.0.94", referrer: "http://192.168.0.94/"

I am trying to make a website using node.js as I want to implement other apps in the future. I am able to get sub-directories on my PC, but when I try to use on anything, I get this error.

Here's my config:

server {
    listen 80;
    server_name _;

    error_log /var/log/nginx/personalsite.error.log;

    root /var/www/html/;
    index search.html;

    location / {
        proxy_pass http://localhost:3000;
        try_files $uri $uri/ =404;
    }

    location ^~ /search/ {
        alias /var/www/html/views/;
    }

    location ^~ /results/ {
        alias /var/www/html/views/;
    }

}

And my app.js:

const express = require('express');
const path = require('path');

// Init App
const app = express();

// Load View Engine
app.use('/css', express.static(path.join(__dirname, 'css')));
app.use('/js', express.static(path.join(__dirname, 'js')));

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// Web Routes
app.engine('html', require('ejs').renderFile);
app.use(express.urlencoded({extended: true}));

app.get('/', (req, res) => {
    res.render('index.html');
});

app.get('/search', (req, res) => {
    res.render('search.html');
});

app.get('/results', (req, res) => {
    res.render('results.html');
});

app.get('/found', (req, res) => {
    res.render('found.html');
});

app.get('/player', (req, res) => {
    res.render('player.html');
});

// Start Server
app.listen('3000', () => {
    console.log('Listening on port 3000!');
});

If you know why this is the issue that would help me massivley, thanks!

Body:
Try to replace

try_files $uri $uri/ =404;

to

 try_files $uri $uri/ index.html;

Read more on Nginx rewrite or internal redirection cycle while internally redirecting to "/index.html"


问:
why we need to pass Boolean value to the method
I have confusion on below code i.e why we need to pass Boolean value to the method and what it returns?</p>

```<code>RefreshLookupList(false);
private void RefreshLookupList(bool forExport)

    {
        grdLists.Rows.Clear();
        grdLists.DataSource = Lists.GetListItems(cboListType.SelectedValue);
        grdLists.DataBind();

        lblCount.InnerText = "Lookups: " + grdLists.Rows.Count.ToString();
    }
</code>```

答: The forExport variable is never used so is effectively redundant. This method may have been re-factored and the method variable not removed. </p>

Body:
I have confusion on below code i.e why we need to pass Boolean value to the method and what it returns?

RefreshLookupList(false);
private void RefreshLookupList(bool forExport)

    {
        grdLists.Rows.Clear();
        grdLists.DataSource = Lists.GetListItems(cboListType.SelectedValue);
        grdLists.DataBind();

        lblCount.InnerText = "Lookups: " + grdLists.Rows.Count.ToString();
    }


问:
pip won't install channels_redis
for working with Django channels I need to install "channels_redis".
while installing "channels_redis" I face this error, any thought?

by the way, I'm on windows and it showed me an error of C++ first and after installing Microsoft visual studio build tools vanished, and now this.

```<code>  ERROR: Command errored out with exit status 1:
   command: 'E:\Programming projects\Django\channels\chat_launch01\venv\Scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0]
 = '"'"'C:\\Users\\KaNi\\AppData\\Local\\Temp\\pip-install-dt2d0_z3\\hiredis_a7d15f1044b343288a4bc87864c6418e\\setup.py'"'"'; __file__='"'"'C:\\
Users\\KaNi\\AppData\\Local\\Temp\\pip-install-dt2d0_z3\\hiredis_a7d15f1044b343288a4bc87864c6418e\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"
'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d
 'C:\Users\KaNi\AppData\Local\Temp\pip-wheel-m0bnautd'
       cwd: C:\Users\KaNi\AppData\Local\Temp\pip-install-dt2d0_z3\hiredis_a7d15f1044b343288a4bc87864c6418e\
  Complete output (23 lines):
  C:\Users\KaNi\AppData\Local\Temp\pip-install-dt2d0_z3\hiredis_a7d15f1044b343288a4bc87864c6418e\setup.py:7: DeprecationWarning: the imp module
is deprecated in favour of importlib; see the module's documentation for alternative uses
    import sys, imp, os, glob, io
  E:\Programming projects\Django\channels\chat_launch01\venv\lib\site-packages\setuptools\dist.py:642: UserWarning: Usage of dash-separated 'des
cription-file' will not be supported in future versions. Please use the underscore name 'description_file' instead
    warnings.warn(
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build\lib.win-amd64-3.9
  creating build\lib.win-amd64-3.9\hiredis
  copying hiredis\version.py -> build\lib.win-amd64-3.9\hiredis
  copying hiredis\__init__.py -> build\lib.win-amd64-3.9\hiredis
  running build_ext
  building 'hiredis.hiredis' extension
  creating build\temp.win-amd64-3.9
  creating build\temp.win-amd64-3.9\Release
  creating build\temp.win-amd64-3.9\Release\src
  creating build\temp.win-amd64-3.9\Release\vendor
  creating build\temp.win-amd64-3.9\Release\vendor\hiredis
  d:\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.28.29910\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Ivendor -IE:\
Programming projects\Django\channels\chat_launch01\venv\include -Ic:\users\kani\appdata\local\programs\python\python39\include -Ic:\users\kani\a
ppdata\local\programs\python\python39\include -Id:\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.28.29910\include -IC:\Program Files
(x86)\Windows Kits\10\include\10.0.10240.0\ucrt /Tcsrc\hiredis.c /Fobuild\temp.win-amd64-3.9\Release\src\hiredis.obj
  hiredis.c
  c:\users\kani\appdata\local\programs\python\python39\include\pyconfig.h(200): fatal error C1083: Cannot open include file: 'basetsd.h': No suc
h file or directory
  error: command 'd:\\Microsoft Visual Studio\\2019\\BuildTools\\VC\\Tools\\MSVC\\14.28.29910\\bin\\HostX86\\x64\\cl.exe' failed with exit code
2
  ----------------------------------------
  ERROR: Failed building wheel for hiredis
</code>```

答:
The issue comes when in your windows system you are trying to install channels_redis in venv Python environment and not in the main system,

Try to install and run the project outside any virtual environment i.e into the main system.

Title: pip won't install channels_redis

Body:
for working with Django channels I need to install "channels_redis".
while installing "channels_redis" I face this error, any thought?

by the way, I'm on windows and it showed me an error of C++ first and after installing Microsoft visual studio build tools vanished, and now this.

  ERROR: Command errored out with exit status 1:
   command: 'E:\Programming projects\Django\channels\chat_launch01\venv\Scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0]
 = '"'"'C:\\Users\\KaNi\\AppData\\Local\\Temp\\pip-install-dt2d0_z3\\hiredis_a7d15f1044b343288a4bc87864c6418e\\setup.py'"'"'; __file__='"'"'C:\\
Users\\KaNi\\AppData\\Local\\Temp\\pip-install-dt2d0_z3\\hiredis_a7d15f1044b343288a4bc87864c6418e\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"
'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d
 'C:\Users\KaNi\AppData\Local\Temp\pip-wheel-m0bnautd'
       cwd: C:\Users\KaNi\AppData\Local\Temp\pip-install-dt2d0_z3\hiredis_a7d15f1044b343288a4bc87864c6418e\
  Complete output (23 lines):
  C:\Users\KaNi\AppData\Local\Temp\pip-install-dt2d0_z3\hiredis_a7d15f1044b343288a4bc87864c6418e\setup.py:7: DeprecationWarning: the imp module
is deprecated in favour of importlib; see the module's documentation for alternative uses
    import sys, imp, os, glob, io
  E:\Programming projects\Django\channels\chat_launch01\venv\lib\site-packages\setuptools\dist.py:642: UserWarning: Usage of dash-separated 'des
cription-file' will not be supported in future versions. Please use the underscore name 'description_file' instead
    warnings.warn(
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build\lib.win-amd64-3.9
  creating build\lib.win-amd64-3.9\hiredis
  copying hiredis\version.py -> build\lib.win-amd64-3.9\hiredis
  copying hiredis\__init__.py -> build\lib.win-amd64-3.9\hiredis
  running build_ext
  building 'hiredis.hiredis' extension
  creating build\temp.win-amd64-3.9
  creating build\temp.win-amd64-3.9\Release
  creating build\temp.win-amd64-3.9\Release\src
  creating build\temp.win-amd64-3.9\Release\vendor
  creating build\temp.win-amd64-3.9\Release\vendor\hiredis
  d:\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.28.29910\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Ivendor -IE:\
Programming projects\Django\channels\chat_launch01\venv\include -Ic:\users\kani\appdata\local\programs\python\python39\include -Ic:\users\kani\a
ppdata\local\programs\python\python39\include -Id:\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.28.29910\include -IC:\Program Files
(x86)\Windows Kits\10\include\10.0.10240.0\ucrt /Tcsrc\hiredis.c /Fobuild\temp.win-amd64-3.9\Release\src\hiredis.obj
  hiredis.c
  c:\users\kani\appdata\local\programs\python\python39\include\pyconfig.h(200): fatal error C1083: Cannot open include file: 'basetsd.h': No suc
h file or directory
  error: command 'd:\\Microsoft Visual Studio\\2019\\BuildTools\\VC\\Tools\\MSVC\\14.28.29910\\bin\\HostX86\\x64\\cl.exe' failed with exit code
2
  ----------------------------------------
  ERROR: Failed building wheel for hiredis


答:
You can nest lists inside other lists, you can mix ordered and unordered list through nesting. Use start attribute to change the starting number.

```<code>    <ol>
      <li>One</li>
      <li>Two</li>
      <li>Three</li>
        <ol start='5'>
          <li>Five</li>
          <li>Six</li>
          <li>Seven</li>
        </ol>
      <li>Four</li>
    </ol>
</code>```

Title: Numbering a nested list in a single ol list

Body:
I have an ordered list with some li tags in it. I want the The li tags with  .sub-item class to be nested li tags. Is there a way I can reset numbering for the li tags having class? The list is as below:

One

Two

THree

Sub three 1

Sub three 2

Four

Currently I get which makes sense:

  1 One
  2 Two
  3 Three
  4 Sub Three 1
  5 Sub three 2
  6 Four

However using the class 'sub-item' I want this desired behaviour

  1 One
  2 Two
  3. Three
     a Sub three 1
     b Sub Three 2
  4 Four

I can not change the html part of the code, only can write css. Adding nested ol tags will not work in this case as I can not modify the html.

Body:
You can nest lists inside other lists, you can mix ordered and unordered list through nesting. Use start attribute to change the starting number.

    <ol>
      <li>One</li>
      <li>Two</li>
      <li>Three</li>
        <ol start='5'>
          <li>Five</li>
          <li>Six</li>
          <li>Seven</li>
        </ol>
      <li>Four</li>
    </ol>


问:
C2D messages to IoT Hub with Java
Is there any possibility to send Cloud2Device message to an IoT Hub with Java by using MQTT as protocol?

I use ServiceClient from library: https://github.com/Azure/azure-iot-sdk-java/blob/main/service/iot-service-client/src/main/java/com/microsoft/azure/sdk/iot/service/ServiceClient.java and there it's impossible using MQTT, only AMQPS.

答:
You can receive Cloud2Device messages on your device, using the Device SDK, if you are connected over MQTT, AMQP or HTTPS.

In order to connect to your IoTHub from your solution back end, using the Service SDK to send cloud-to-device messages to a single device you will need to use AMQP or AMQP over Websockets.

Service endpoints. Each IoT hub exposes a set of endpoints for your solution back end to communicate with your devices. With one
exception, these endpoints are only exposed using the AMQP and AMQP
over WebSockets protocols.

Ref: Reference - IoT Hub endpoints

Title: C2D messages to IoT Hub with Java


问:
MVVM Flutter approach when there is a condition to display a view
Currently I have NonMVVM pattern like this,

and I'm trying to adapt to MVVM pattern, but I cant wrap my brain around how to properly approach this.

If I have a condition for my views, should I keep it inside the views class, or should I move this into viewModel class?

```<code>  Container(

    child: PageView(
      controller: pageController,
      onPageChanged: (int page) {
        setState(() {
          pageIndex = page;
          switch (pageIndex) {
            case 0:
              pageTitle = 'Home Page';
              break;
            case 1:
              pageTitle = 'User Page';
              break;
            case 2:
              pageTitle = 'Announcement Page';
              break;
            default:
              pageTitle = '';
          }
        });
      },
      children:
          (userLoggedIn)
              ? <Widget>[
                  Center(
                    child:  HomePage(),
                  ),
                  Center(
                    child: UserPage(),
                  ),
                  Center(
                    child: AnnouncementPage(),
                  ),
                ]
              : <Widget>[
                  Center(
                    child:  HomePage(),
                  ),
                  Center(
                    child: AnnouncementPage(),
                  ),
                ],
    ),
  ),
</code>```

答:
Better to use state management techniques like:

Provider, or
GetX

Body:
Currently I have NonMVVM pattern like this,

and I'm trying to adapt to MVVM pattern, but I cant wrap my brain around how to properly approach this.

If I have a condition for my views, should I keep it inside the views class, or should I move this into viewModel class?

  Container(

    child: PageView(
      controller: pageController,
      onPageChanged: (int page) {
        setState(() {
          pageIndex = page;
          switch (pageIndex) {
            case 0:
              pageTitle = 'Home Page';
              break;
            case 1:
              pageTitle = 'User Page';
              break;
            case 2:
              pageTitle = 'Announcement Page';
              break;
            default:
              pageTitle = '';
          }
        });
      },
      children:
          (userLoggedIn)
              ? <Widget>[
                  Center(
                    child:  HomePage(),
                  ),
                  Center(
                    child: UserPage(),
                  ),
                  Center(
                    child: AnnouncementPage(),
                  ),
                ]
              : <Widget>[
                  Center(
                    child:  HomePage(),
                  ),
                  Center(
                    child: AnnouncementPage(),
                  ),
                ],
    ),
  ),


问:
jquery picture selector
Does anyone have an example of a jquery based photo selector?  This is something you see in small photo albums.

I have the following code:

```<code><div><img class="bigpicture" src="1.jpg"></img></div>
<div>
    <img class="smallpicture" src="1.jpg"></img>
    <img class="smallpicture" src="2.jpg"></img>
    <img class="smallpicture" src="3.jpg"></img>
    <img class="smallpicture" src="4.jpg"></img>
    <img class="smallpicture" src="5.jpg"></img>
    <img class="smallpicture" src="6.jpg"></img>
</div>
</code>```

The behavior I'm looking for is when the users hovers over any of the smaller pictures, it updates the bigger picture with the one that was just hovered.

Any thoughts?

Thanks

答:
```<code>$('.smallpicture').hover(function(){
   $('.bigpicture').attr('src', $(this).attr('src')+"?timestamp=" + new Date().getTime());
});
</code>```

timestamp is needed to dynamically update your big image.

Title: jquery picture selector

Body:
Does anyone have an example of a jquery based photo selector?  This is something you see in small photo albums.

I have the following code:

The behavior I'm looking for is when the users hovers over any of the smaller pictures, it updates the bigger picture with the one that was just hovered.

Any thoughts?

Thanks

Body:
$('.smallpicture').hover(function(){
   $('.bigpicture').attr('src', $(this).attr('src')+"?timestamp=" + new Date().getTime());
});

timestamp is needed to dynamically update your big image.


问:
Handlebars - Nest objects in #each
I use express-handlebars with Node JS and I am trying to display informations from the array games on my HTML page using #each. But handlebars won't display the values inside my object. Even if it is not a nested object.

But if I only write {{this}}, it displays all the object like if it was a string. And if I do {{this.time}}, nothing is displayed.

I'm using Node JS v14.18.1, express v4.17.2 and express-handlebars v6.0.2.

Thank you in advance for your help !

    getHomePage: async (req, res) => {
        try {
            const games = await gameModel.find().sort({time: -1}).limit(3).populate('user');
            res.render('home', {title: 'Hello world', games});
        } catch (error) {
            console.error(error);
            res.status(500).json({error});
        }
    }
```
<pre class="lang-html prettyprint-override"><code>        <table>
            <thead>
                <th>Position</th>
                <th>Score</th>
                <th>Nom</th>
            </thead>
            <tbody>
                {{#each games}}

                    <tr>
                        <td>#{{@index}}</td>
                        <td>{{this}}</td>
                        <td>{{this.time}}</td>
                    </tr>

                {{/each}}
            </tbody>
        </table>
</code>```

答:
I thought the problem came from Handlebars or NodeJS. But it came from my MongoDB request.

I resolved it by adding .lean() at the end of my Mongo request. By default, Mongo returns a document, not a javascript object. So we have to "convert" it to a javascript to allow handlebars to display it:

gameModel.find().sort({time: -1}).limit(3).populate('user').lean()
```

Title: Handlebars - Nest objects in #each

Body:
I use express-handlebars with Node JS and I am trying to display informations from the array games on my HTML page using #each. But handlebars won't display the values inside my object. Even if it is not a nested object.

But if I only write {{this}}, it displays all the object like if it was a string. And if I do {{this.time}}, nothing is displayed.

I'm using Node JS v14.18.1, express v4.17.2 and express-handlebars v6.0.2.

Thank you in advance for your help !

    getHomePage: async (req, res) => {
        try {
            const games = await gameModel.find().sort({time: -1}).limit(3).populate('user');
            res.render('home', {title: 'Hello world', games});
        } catch (error) {
            console.error(error);
            res.status(500).json({error});
        }
    }

                Position
                Score
                Nom

                {{#each games}}

                        #{{@index}}
                        {{this}}
                        {{this.time}}

                {{/each}}


问:
AWS Lambda: upload code from amazon S3 location
I have configured AWS pipeline to deploy my latest nodeJS code as zip file to S3.
Instead of going to AWS Lambda and choosing the "upload from Amazon S3 location" option,
is there a way to make my lambda service to take the latest code once it is written to S3, so that it will automatically update its function code when you update the zip file?</p>

答:
I have used this link to configure my AWS Code Build yaml in deploy time and the latest source code uploaded as zip file in S3 was taken by AWS Lambda.

https://docs.aws.amazon.com/cli/latest/reference/lambda/update-function-code.html

sample command used in my yaml is given below

```<code>- aws lambda update-function-code --function-name my-function --s3-bucket my-s3-bucket --s3-key sourceFileName.zip
</code>```

Body:
I have used this link to configure my AWS Code Build yaml in deploy time and the latest source code uploaded as zip file in S3 was taken by AWS Lambda.

https://docs.aws.amazon.com/cli/latest/reference/lambda/update-function-code.html

sample command used in my yaml is given below

- aws lambda update-function-code --function-name my-function --s3-bucket my-s3-bucket --s3-key sourceFileName.zip


问:
Working Directory for local github actions in subdirectory
I'm trying to keep multiple github actions in the same monorepo using subdirectories, and run them like:

workflow.yml

```<code>// [...]
jobs:
  run_my_script:
    runs-on: ubuntu-latest
    steps:
      - name: Check out current repo
        uses: actions/checkout@v2
      - uses: ./my_action2
        with:
          my_input_var: "david"
</code>```

./my_action2/action.yml

```<code>// [...]
runs:
  using: "composite"
  steps:
    # Checkout files in this repo
    - name: Checkout
      uses: actions/checkout@v1

    - name: Run myscript
      run: python myscript.py "${{ inputs.my_input_var }}" # location: ./my_action2/myscript.py
      shell: bash
</code>```

The problem I'm having is that my action uses a python script in it's subdirectory, but the uses: action appears to run from the GITHUB_WORKING_DIR of the workflow and not the directory of the action itself.

```<code>python: can't open file 'myscript.py': [Errno 2] No such file or directory
</code>```

I've looked through most of the working-directory questions surrounding github actions, but I'm still stumped.

I've also tried adding working-directory: ./my_action2 to the job's defaults: but it looks like it's not propagating to run: commands within the uses: step.

My workaround in the meantime has been to add an input for myaction2_working_directory in the workflow, and then add working-directory: ${{ inputs.myaction2_working_directory }} to every run: command in the action. This seems inelegant and repetitive. Is there a better way to do this?

答:
I had similar problem and for my composite actions I just added a first step as:

run: cd  ${{ inputs.working_directory }}

and then all next steps are running in it.
I couldn't find a better way and having working-directory copy pasted was also something I didn't like.

Body:
I'm trying to keep multiple github actions in the same monorepo using subdirectories, and run them like:

workflow.yml

// [...]
jobs:
  run_my_script:
    runs-on: ubuntu-latest
    steps:
      - name: Check out current repo
        uses: actions/checkout@v2
      - uses: ./my_action2
        with:
          my_input_var: "david"

./my_action2/action.yml

// [...]
runs:
  using: "composite"
  steps:
    # Checkout files in this repo
    - name: Checkout
      uses: actions/checkout@v1

    - name: Run myscript
      run: python myscript.py "${{ inputs.my_input_var }}" # location: ./my_action2/myscript.py
      shell: bash

The problem I'm having is that my action uses a python script in it's subdirectory, but the uses: action appears to run from the GITHUB_WORKING_DIR of the workflow and not the directory of the action itself.

python: can't open file 'myscript.py': [Errno 2] No such file or directory

I've looked through most of the working-directory questions surrounding github actions, but I'm still stumped.

I've also tried adding working-directory: ./my_action2 to the job's defaults: but it looks like it's not propagating to run: commands within the uses: step.

My workaround in the meantime has been to add an input for myaction2_working_directory in the workflow, and then add working-directory: ${{ inputs.myaction2_working_directory }} to every run: command in the action. This seems inelegant and repetitive. Is there a better way to do this?


问:
Format character prefix onto data in Bigquery
I have a query where I am trying to add a prefix to week numbers.
Right now, the query puts out the week numbers as (1,2,3,4...) Is there a way where I can add "Wk" to the beginning of the week number for the entire row? (ex: Wk 1)
'''FORMAT_TIMESTAMP('%m-%d-%Y', CAST( ttl.insert_timestamp AS DATE)) AS Cycle_Time,
EXTRACT(ISOWEEK FROM ttl.insert_timestamp) AS Week,
FROM tableName ttl'''

答:
You might be looking for</p>
```<code>CONCAT("Wk ", CAST(EXTRACT(ISOWEEK FROM ttl.insert_timestamp) AS STRING)) AS Week
</code>```

Body:
You might be looking for

CONCAT("Wk ", CAST(EXTRACT(ISOWEEK FROM ttl.insert_timestamp) AS STRING)) AS Week


问:
Qt 6.2: Menus Truncated initially on Windows
In my Qt 6.2.0 application menus are truncated on initial display after starting the program on Windows 10. On the Mac the problem did not occur yet.

This only happens once per Menu (once per Edit, once per Mode etc...) - but not for all Menus. It seems not to depend on the size of the Menu. Its always the last entry that will be truncated and in all cases the second last entry is a separator.
If i choose the menu a second time it will be fully displayed:

If menus are rebuilt in response to a language change the problem occurs once again per menu.#

Is this a known problem or has anyone else seen this?
How can i avoid this?

答:
I found a better fix:

QGuiApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::Floor);
```


问:
Android ,Interface ,new Instance
i have a problem with a newInstance call using Reflection in Android.

My Interface:

```<code>public interface IGiver {
    public int getNr();
}
</code>```

My Class to call Reflection:

```<code>public class NrGiver implements IGiver {
    int i = 10;
    @Override
    public int getNr() {
        return i;
    }
}
</code>```

The way i try to call getNr:

```<code>String packageName = "de.package";
String className = "de.package.NrGiver";

String apkName = getPackageManager().getApplicationInfo(packageName, 0).sourceDir;
            PathClassLoader myClassLoader =
                new dalvik.system.PathClassLoader(
                            apkName,
                        ClassLoader.getSystemClassLoader());
Class c =  Class.forName(className);
IGiver giver = (IGiver) c.newInstance();
</code>```

The last line wont work it cause an Error and my App stops.
I know it fault of newInstance, but i want to work on the IGiver object.

Pls Help me.

My Solution:

Hey guys finally i got the chicken.

I found an other way. this time i also used newInstance, but this time its worked.
My solution:

```<code>Class c =  Class.forName(className);
Method methode = c.getDeclaredMethod("getNr");
Object i = methode.invoke(c.newInstance(), new Object[]{});
</code>```

And this what i wanted to do.
I have an NrGiver.class somewhere on my Phone. And it implements the Interface IGiver. So it can be loaded into my App dynamically. I need the Integer from the class NrGiver. So i can make my code generic. I tried to Cast the Object to my Interface, but it failed.

So i found an other way to invoke the method of a class.

Thx for help

答:
```<code>String className = "de.package.NrGiver";//line 1
Class c =  Class.forName(className);//line 2
IGiver giver = (IGiver) c.newInstance();//line3
</code>```

in line 2 forName is trying to find a class but the String is representing a Interface, so the classLoader does not find the class and it throws an exception. adding on to it, in line 3 you are trying to get an Instance of Interface which does't exist in the java world.. i mean to say Interfaces cannot be instanciated and they do not have constructors..

Title: Android ,Interface ,new Instance

Body:
i have a problem with a newInstance call using Reflection in Android.

My Interface:

public interface IGiver {
    public int getNr();
}

My Class to call Reflection:

public class NrGiver implements IGiver {
    int i = 10;
    @Override
    public int getNr() {
        return i;
    }
}

The way i try to call getNr:

String packageName = "de.package";
String className = "de.package.NrGiver";

String apkName = getPackageManager().getApplicationInfo(packageName, 0).sourceDir;
            PathClassLoader myClassLoader =
                new dalvik.system.PathClassLoader(
                            apkName,
                        ClassLoader.getSystemClassLoader());
Class c =  Class.forName(className);
IGiver giver = (IGiver) c.newInstance();

The last line wont work it cause an Error and my App stops.
I know it fault of newInstance, but i want to work on the IGiver object.

Pls Help me.

My Solution:

Hey guys finally i got the chicken.

I found an other way. this time i also used newInstance, but this time its worked.
My solution:

Class c =  Class.forName(className);
Method methode = c.getDeclaredMethod("getNr");
Object i = methode.invoke(c.newInstance(), new Object[]{});

And this what i wanted to do.
I have an NrGiver.class somewhere on my Phone. And it implements the Interface IGiver. So it can be loaded into my App dynamically. I need the Integer from the class NrGiver. So i can make my code generic. I tried to Cast the Object to my Interface, but it failed.

So i found an other way to invoke the method of a class.

Thx for help

Body:
String className = "de.package.NrGiver";//line 1
Class c =  Class.forName(className);//line 2
IGiver giver = (IGiver) c.newInstance();//line3

in line 2 forName is trying to find a class but the String is representing a Interface, so the classLoader does not find the class and it throws an exception. adding on to it, in line 3 you are trying to get an Instance of Interface which does't exist in the java world.. i mean to say Interfaces cannot be instanciated and they do not have constructors..


问:
Numbering a nested list in a single ol list
I have an ordered list with some li tags in it. I want the The li tags with  .sub-item class to be nested li tags. Is there a way I can reset numbering for the li tags having class? The list is as below:

```<code><ol>
  <li>One</li>
  <li>Two</li>
  <li>THree</li>
  <li class="sub-item">Sub three 1</li>
  <li class="sub-item">Sub three 2</li>
  <li>Four</li>
</ol>
</code>```

Currently I get which makes sense:

```<code>  1 One
  2 Two
  3 Three
  4 Sub Three 1
  5 Sub three 2
  6 Four
</code>```

However using the class 'sub-item' I want this desired behaviour

```<code>  1 One
  2 Two
  3. Three
     a Sub three 1
     b Sub Three 2
  4 Four
</code>```

I can not change the html part of the code, only can write css. Adding nested ol tags will not work in this case as I can not modify the html.

答:
If you can't change your HTML markup, you can simulate nested numbering on a single list with CSS counters.

You need to remove the default list-style-type and add the counter with pseudo elements.

.sub-item elements can have their own counter (sub-counter in the following example) that doesn't affect the one set on all the
 elements (main-counter in the following example) :

ol {
  counter-reset: main-counter, sub-counter;
  list-style-type:none;
  padding:0;
}
li {
  counter-increment: main-counter;
  counter-reset: sub-counter;
}
li::before {
  content: counter(main-counter) ". ";
}
li.sub-item {
  counter-increment: sub-counter;
  padding-left:1em;
  counter-reset: none;
}
li.sub-item::before {
  content: counter(sub-counter, lower-alpha) ". ";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ol>
  <li>One</li>
  <li>Two</li>
  <li>THree</li>
  <li class="sub-item">Sub three 1</li>
  <li class="sub-item">Sub three 2</li>
  <li>Four</li>
  <li>Five</li>
  <li>Six</li>
  <li>Seven</li>
  <li class="sub-item">Sub three 1</li>
  <li class="sub-item">Sub three 2</li>
  <li>Eight</li>
</ol></code>```

Note that is you need several nested sections, you need to reset the sub-counter on elements without the .sub-item class with the counter-reset property.

Body:
If you can't change your HTML markup, you can simulate nested numbering on a single list with CSS counters.

You need to remove the default list-style-type and add the counter with pseudo elements.

.sub-item elements can have their own counter (sub-counter in the following example) that doesn't affect the one set on all the <li> elements (main-counter in the following example) :

ol {
  counter-reset: main-counter, sub-counter;
  list-style-type:none;
  padding:0;
}
li {
  counter-increment: main-counter;
  counter-reset: sub-counter;
}
li::before {
  content: counter(main-counter) ". ";
}
li.sub-item {
  counter-increment: sub-counter;
  padding-left:1em;
  counter-reset: none;
}
li.sub-item::before {
  content: counter(sub-counter, lower-alpha) ". ";
}

<ol>
  <li>One</li>
  <li>Two</li>
  <li>THree</li>
  <li class="sub-item">Sub three 1</li>
  <li class="sub-item">Sub three 2</li>
  <li>Four</li>
  <li>Five</li>
  <li>Six</li>
  <li>Seven</li>
  <li class="sub-item">Sub three 1</li>
  <li class="sub-item">Sub three 2</li>
  <li>Eight</li>
</ol>

Note that is you need several nested sections, you need to reset the sub-counter on elements without the .sub-item class with the counter-reset property.


问:
LazyInitializationException in a Spring Transaction
In a Spring Boot project I am working at I added the Hibernate ORM plugin to enable lazy loading for @Lob fields in my entity, this didn't work out of the box for DB2. The lazy loading works, when I retrieve the object the lob field isn't loaded yet. But now a new problem occurs, when I do want to get the blob field I get a LazyInitializationException. Now I did some debugging and Google searches. I tried to add @Transactional to the method and to the classes, I also tried multiple propagation options, but nothing works.

I also tried to load the object directly using the EntityManager, but that also gives the same exception:

```<code>Object object = entityManager.find(Object.class, id);
object.getLobField();
</code>```

The full exception that is thrown is:

```<code>org.hibernate.LazyInitializationException: Unable to perform requested lazy initialization [package.Object.lobField] - no session and settings disallow loading outside the Session
</code>```

答:
You need to activate in your application.yml

```<code>spring:
  jpa:
    properties:
      hibernate:
        enable_lazy_load_no_trans: true
</code>```

This will allow lazy loading to work outside the session that created the object that has properties that are lazy loaded.

Reference: https://www.baeldung.com/hibernate-lazy-loading-workaround, Solve Hibernate Lazy-Init issue with hibernate.enable_lazy_load_no_trans and https://vladmihalcea.com/the-hibernate-enable_lazy_load_no_trans-anti-pattern/

Body:
In a Spring Boot project I am working at I added the Hibernate ORM plugin to enable lazy loading for @Lob fields in my entity, this didn't work out of the box for DB2. The lazy loading works, when I retrieve the object the lob field isn't loaded yet. But now a new problem occurs, when I do want to get the blob field I get a LazyInitializationException. Now I did some debugging and Google searches. I tried to add @Transactional to the method and to the classes, I also tried multiple propagation options, but nothing works.

I also tried to load the object directly using the EntityManager, but that also gives the same exception:

Object object = entityManager.find(Object.class, id);
object.getLobField();

The full exception that is thrown is:

org.hibernate.LazyInitializationException: Unable to perform requested lazy initialization [package.Object.lobField] - no session and settings disallow loading outside the Session

Body:
You need to activate in your application.yml

spring:
  jpa:
    properties:
      hibernate:
        enable_lazy_load_no_trans: true

This will allow lazy loading to work outside the session that created the object that has properties that are lazy loaded.

Reference: https://www.baeldung.com/hibernate-lazy-loading-workaround, Solve Hibernate Lazy-Init issue with hibernate.enable_lazy_load_no_trans and https://vladmihalcea.com/the-hibernate-enable_lazy_load_no_trans-anti-pattern/


问:
How to add and validate custom fields into checkout block in WooCommerce Block plugin?
I am trying to add custom field within WooCommerce Checkout Block, so I added a forced Inner Block by following this document.And it all works pretty good, But whenever I click place order the custom field that I added is not get validated.
How can I validate the custom inner blocks?

could someone help me with this. thanks.

答:
WooCommerce blocks are only compatibile with some extensions. Such as Payment Gateways,Product Add-Ons etc. And some of the extensions that are known to be currently incompatible with Cart & Checkout blocks are Checkout Field Editor,Checkout Addons, Cart Add-ons, Amazon Pay etc.

WooCommerce itself mentioned that the extensibility interfaces for the cart and checkout blocks are still being developed, So they suggest us to keep using the shortcode based checkout for now.

WooCommerce block extensibility


问:
How do I fix the "Serves images with low resolution" warning in lighthouse in Next.js?
I displayed the svg logo using the Next.js Image tag.

import Image from "next/Image"

export default function Home() {
  return (

      <Image width={32} height={32} src="/logo.svg"></Image>

  )
}
```

Then when I used lighthouse to get a report on the page,
I got a warning saying "Serves images with low resolution".

Also, if you try setting both the width and height to 1024px,
this warning will disappear. How can I get rid of this warning even with 32px?

答:
This looks to be a bug and can be safely ignored (and a good one to report in the Lighthouse repository).

Other than changing the image dimensions to be larger on screen (which obviously is not something you are likely to want to do as it will affect the design) there is no course of action you could take to rectify this.

The bug is that it is treating a SVG like a raster image and treating it like it has a resolution.

Perhaps if you really want to fix it you could regenerate the SVG with a viewbox that is larger and scale the SVG accordingly. This will have no impact on the SVG itself but could remove the error if it bothers you.

Also something to note, this will not affect your score, this is a "diagnostic" suggestion meant to help you identify potential problems, not an item that is weighted in the scoring.

Body:
I displayed the svg logo using the Next.js Image tag.

import Image from "next/Image"

export default function Home() {
  return (

      <Image width={32} height={32} src="/logo.svg"></Image>

  )
}

Then when I used lighthouse to get a report on the page,
I got a warning saying "Serves images with low resolution".

Also, if you try setting both the width and height to 1024px,
this warning will disappear. How can I get rid of this warning even with 32px?


问:
[Jenkin][MacServer] Jenkin not accessible remotely
I setup Jenkin on Mac-server and able to do build locally for both iOS and Android source code.

I am facing issue while accessing the Jenkin's on remote machine(Same Mac server) from home. Mac-Server is ping-able from Home but Jenkin's is not accessible.

We found out that to able to access the Jenkin's we always need to enable screen sharing. Login to screen sharing is not needed just connecting(IP Address of remote mac server) enables Jenkin's to be accessible.

System Details below

Mac server OS version : macOS Big Sur 11.2.3

Jenkins version: 2.319.2

Jenkins installed via Homebrew

Any support/guidance will be highly appreciated.

答: Have you tried to turn off the firewall of Mac</p>


问:
Deserialized object type get value throw null reference
i have a json response from ajax and i am trying to deserialize it as object type(not a defined model class) and access its properties value. deserializer works fine but when try to get the value i get the null reference error.

```<code>// on break point i can clearly see the object properties and values and its not null
var tankJsonObj = JsonConvert.DeserializeObject<object>(tankJson);

//here from GetValue i get the null refernce error
var test = tankJsonObj.GetType().GetProperty("tankName").GetValue(tankJsonObj, null).ToString();
</code>```

i tried the test data

```<code>var tankJsonObj = new { tankName = "xx" };
var test = tankJsonObj.GetType().GetProperty("tankName").GetValue(tankJsonObj, null).ToString();
</code>```

and it works fine. i cant understand why the object that initiated by deserializer which is not null throwing the error on getting the property value.

答:
The first GetValue() parameter needs to be tankJsonObj because from that object the values will be read.

Changed code:

```<code>var tankJsonObj = new { tankName = "xx" };
var test = tankJsonObj.GetType().GetProperty("tankName").GetValue(tankJsonObj, null).ToString();
Console.WriteLine(test); // "xx"
</code>```

Working demo: https://dotnetfiddle.net/tOtRUf

However when deserializing to object, only properties that object supports will be deserialized, and there are... none! As a result all properties inside the JSON will be ignored.

A simple workaround is to instead use JObject as the target type (in the Newtonsoft.Json.Linq namespace). This behaves somewhat like a Dictionary of keys and values, and will accept any property. The resulting code is very simple, it doesn't even need reflection:

```<code>var tankJsonObj = JsonConvert.DeserializeObject<JObject>("{ tankName: \"xx\" }");
var test = tankJsonObj.GetValue("tankName")?.ToString();
Console.WriteLine(test); // "xx"
</code>```

Body:
i have a json response from ajax and i am trying to deserialize it as object type(not a defined model class) and access its properties value. deserializer works fine but when try to get the value i get the null reference error.

// on break point i can clearly see the object properties and values and its not null
var tankJsonObj = JsonConvert.DeserializeObject<object>(tankJson);

//here from GetValue i get the null refernce error
var test = tankJsonObj.GetType().GetProperty("tankName").GetValue(tankJsonObj, null).ToString();

i tried the test data

var tankJsonObj = new { tankName = "xx" };
var test = tankJsonObj.GetType().GetProperty("tankName").GetValue(tankJsonObj, null).ToString();

and it works fine. i cant understand why the object that initiated by deserializer which is not null throwing the error on getting the property value.

Body:
The first GetValue() parameter needs to be tankJsonObj because from that object the values will be read.

Changed code:

var tankJsonObj = new { tankName = "xx" };
var test = tankJsonObj.GetType().GetProperty("tankName").GetValue(tankJsonObj, null).ToString();
Console.WriteLine(test); // "xx"

Working demo: https://dotnetfiddle.net/tOtRUf

However when deserializing to object, only properties that object supports will be deserialized, and there are... none! As a result all properties inside the JSON will be ignored.

A simple workaround is to instead use JObject as the target type (in the Newtonsoft.Json.Linq namespace). This behaves somewhat like a Dictionary of keys and values, and will accept any property. The resulting code is very simple, it doesn't even need reflection:

var tankJsonObj = JsonConvert.DeserializeObject<JObject>("{ tankName: \"xx\" }");
var test = tankJsonObj.GetValue("tankName")?.ToString();
Console.WriteLine(test); // "xx"


问:
Python, sum of decimals
I want to split a string of letters into a bunch of triplets and assign numbers to each triplet and then find the sum of the numbers. I managed to code till the number assigning part. But not able to generate the sum.Lot of errors popping up. Please help. P.S. I am a biologist and know nothing about coding.
This is my partial code:

gene_code = "abcdef"

split_strings = []
n  = 3
for index in range(0, len(gene_code), n):
    split_strings.append(gene_code[index : index + n])
print(split_strings)
import re
gene_code = gene_code.replace('abc','1.2,')
gene_code = gene_code.replace('def','2.3,')

print(gene_code)
```
<p>the output is as follows</p>
```['abc', 'def']
1.2,2.3,
```

Now I want to get the sum of these numbers. Please help?

答:
You could create a dictionary of replacements.  Note that the replacements need to be written as numbers, not as strings, to be able to do calculations.  Once you have a list of numbers, you can call sum(list_of_numbers).

Here is some example code:

gene_code = "abcdef"
split_strings = [gene_code[i:i + 3] for i in range(0, len(gene_code), 3)]
replacements = {'abc': 1.2, 'def': 2.3}
numbers = [replacements[s] for s in split_strings]
print(sum(numbers))
```
<p>If some strings don't have a replacement, this code will give an error. You could add a test and replace those numbers with zero instead:</p>
```numbers = [0 if not s in replacements else replacements[s]
           for s in split_strings]
```
<p>Note that the above code uses list comprehension. That way, a loop such as:</p>
```new_list = []
for item in old_list:
   new_list.append(func(item))
```
<p>can be written as</p>
```new_list = [func(item) for item in old_list]
```
<p>Once you're used to that notation, you'll notice it's easier to read and easier to maintain. It gets especially useful when you'd be working with lists of lists.</p>
<p>To read from file:</p>
<pre class="lang-py prettyprint-override"><code>replacements = {'abc': 1.2, 'def': 2.3}
with open("gene_codes.txt") as file:
    for gene_code in file.readlines():
        gene_code = gene_code.strip()
        # print(gene_code)
        split_strings = [gene_code[i:i + 3] for i in range(0, len(gene_code), 3)]
        numbers = [0 if not s in replacements else replacements[s]
                   for s in split_strings]
        print(sum(numbers))
</code>```

Title: Python, sum of decimals

Body:
I want to split a string of letters into a bunch of triplets and assign numbers to each triplet and then find the sum of the numbers. I managed to code till the number assigning part. But not able to generate the sum.Lot of errors popping up. Please help. P.S. I am a biologist and know nothing about coding.
This is my partial code:

gene_code = "abcdef"

split_strings = []
n  = 3
for index in range(0, len(gene_code), n):
    split_strings.append(gene_code[index : index + n])
print(split_strings)
import re
gene_code = gene_code.replace('abc','1.2,')
gene_code = gene_code.replace('def','2.3,')

print(gene_code)

the output is as follows

['abc', 'def']
1.2,2.3,

Now I want to get the sum of these numbers. Please help?

Body:
You could create a dictionary of replacements.  Note that the replacements need to be written as numbers, not as strings, to be able to do calculations.  Once you have a list of numbers, you can call sum(list_of_numbers).

Here is some example code:

gene_code = "abcdef"
split_strings = [gene_code[i:i + 3] for i in range(0, len(gene_code), 3)]
replacements = {'abc': 1.2, 'def': 2.3}
numbers = [replacements[s] for s in split_strings]
print(sum(numbers))

If some strings don't have a replacement, this code will give an error. You could add a test and replace those numbers with zero instead:

numbers = [0 if not s in replacements else replacements[s]
           for s in split_strings]

Note that the above code uses list comprehension. That way, a loop such as:

new_list = []
for item in old_list:
   new_list.append(func(item))

can be written as

new_list = [func(item) for item in old_list]

Once you're used to that notation, you'll notice it's easier to read and easier to maintain. It gets especially useful when you'd be working with lists of lists.

To read from file:

replacements = {'abc': 1.2, 'def': 2.3}
with open("gene_codes.txt") as file:
    for gene_code in file.readlines():
        gene_code = gene_code.strip()
        # print(gene_code)
        split_strings = [gene_code[i:i + 3] for i in range(0, len(gene_code), 3)]
        numbers = [0 if not s in replacements else replacements[s]
                   for s in split_strings]
        print(sum(numbers))


问:
How can I make a textbox readonly using spring security role?
I'm just a new to Spring security.

Today I just wonder how can I make a textbox as readonly depends on account's role?

For example, If account's role is not Admin I want to make textbox as readonly.

I tried this code for it, but It didn't work.

```<code><sec:authorize access="hasAnyRole('ROLE_ADMIN')">
    <input type="text" id="userID">
</sec:authorize>
</code>```

Thanks for your help.

答:
Make sure you have the Thymeleaf Spring Security 5 dependency:

```<code>implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5'
</code>```

Then you can show different inputs based on the users role:

    <input type="text" id="userID">

    <input type="text" id="userID" readonly="readonly">

```

Body:
I'm just a new to Spring security.

Today I just wonder how can I make a textbox as readonly depends on account's role?

For example, If account's role is not Admin I want to make textbox as readonly.

I tried this code for it, but It didn't work.

<sec:authorize access="hasAnyRole('ROLE_ADMIN')">
    <input type="text" id="userID">
</sec:authorize>

Thanks for your help.

Body:
Make sure you have the Thymeleaf Spring Security 5 dependency:

implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5'

Then you can show different inputs based on the users role:

<span sec:authorize="hasRole('ADMIN')">
    <input type="text" id="userID">
</span>
<span sec:authorize="!hasRole('ADMIN')">
    <input type="text" id="userID" readonly="readonly">
</span>