问:
ValueError: No gradients provided for any variable: ['conv2d/kernel:0', 'conv2d/bias:0', 'conv2d_1/kernel:0', 'conv2d_1/bias:0',
System information
Colab tensorflow 2.2.0

Describe the current behavior:
I faced this error when i tried to solve my own data issues, which is multiple label semantic segmentations.

Below is the code

```<code>import tensorflow as tf
import tensorflow.keras.backend as K

IMG_WIDTH = 512
IMG_HEIGHT = 512
IMG_CHANNELS = 3

# batch_shape=(512,512,3)
# inputs = Input(batch_shape=(4, 512, 512, 3))
#Build the model
inputs = tf.keras.layers.Input((IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS))
#s = tf.keras.layers.Lambda(lambda x: x / 255)(inputs)

#Contraction path
c1 = tf.keras.layers.Conv2D(16, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(inputs)
c1 = tf.keras.layers.Dropout(0.1)(c1)
c1 = tf.keras.layers.Conv2D(16, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(c1)
p1 = tf.keras.layers.MaxPooling2D((2, 2))(c1)

c2 = tf.keras.layers.Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(p1)
c2 = tf.keras.layers.Dropout(0.1)(c2)
c2 = tf.keras.layers.Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(c2)
p2 = tf.keras.layers.MaxPooling2D((2, 2))(c2)

c3 = tf.keras.layers.Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(p2)
c3 = tf.keras.layers.Dropout(0.2)(c3)
c3 = tf.keras.layers.Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(c3)
p3 = tf.keras.layers.MaxPooling2D((2, 2))(c3)

c4 = tf.keras.layers.Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(p3)
c4 = tf.keras.layers.Dropout(0.2)(c4)
c4 = tf.keras.layers.Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(c4)
p4 = tf.keras.layers.MaxPooling2D(pool_size=(2, 2))(c4)

c5 = tf.keras.layers.Conv2D(256, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(p4)
c5 = tf.keras.layers.Dropout(0.3)(c5)
c5 = tf.keras.layers.Conv2D(256, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(c5)

#Expansive path
u6 = tf.keras.layers.Conv2DTranspose(128, (2, 2), strides=(2, 2), padding='same')(c5)
u6 = tf.keras.layers.concatenate([u6, c4])
c6 = tf.keras.layers.Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(u6)
c6 = tf.keras.layers.Dropout(0.2)(c6)
c6 = tf.keras.layers.Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(c6)

u7 = tf.keras.layers.Conv2DTranspose(64, (2, 2), strides=(2, 2), padding='same')(c6)
u7 = tf.keras.layers.concatenate([u7, c3])
c7 = tf.keras.layers.Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(u7)
c7 = tf.keras.layers.Dropout(0.2)(c7)
c7 = tf.keras.layers.Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(c7)

u8 = tf.keras.layers.Conv2DTranspose(32, (2, 2), strides=(2, 2), padding='same')(c7)
u8 = tf.keras.layers.concatenate([u8, c2])
c8 = tf.keras.layers.Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(u8)
c8 = tf.keras.layers.Dropout(0.1)(c8)
c8 = tf.keras.layers.Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(c8)

u9 = tf.keras.layers.Conv2DTranspose(16, (2, 2), strides=(2, 2), padding='same')(c8)
u9 = tf.keras.layers.concatenate([u9, c1], axis=3)
c9 = tf.keras.layers.Conv2D(16, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(u9)
c9 = tf.keras.layers.Dropout(0.1)(c9)
c9 = tf.keras.layers.Conv2D(16, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(c9)

outputs = tf.keras.layers.Conv2D(6, (1, 1), activation='softmax')(c9)

model = tf.keras.Model(inputs=[inputs], outputs=[outputs])

# define optomizer
optim = tf.keras.optimizers.Adam()

def dice_coef(y_true, y_pred):
    y_true_f = K.flatten(y_true)
    y_pred_f = K.flatten(y_pred)
    intersection = K.sum(y_true_f * y_pred_f)
    return (2. * intersection + smooth) / (K.sum(y_true_f*y_true_f) + K.sum(y_pred_f*y_pred_f) + smooth)

def dice_coef_loss(y_true, y_pred):
    return 1.-dice_coef(y_true, y_pred)

smooth = 1.
loss= tf.keras.losses.CategoricalCrossentropy()

model.compile(optim, loss, metrics=[dice_coef,'accuracy'])

#model.compile(optim, metrics, loss)
model.summary()

#SET UP FOR DATA TRAINING

BATCH_SIZE = 4
CLASSES = ['0', '1','2','3','4','5']
LR = 0.0001
EPOCHS = 40
n_classes = len(CLASSES)

# Dataset for train images
train_dataset = Dataset(
    x_train_dir,
    y_train_dir,
    classes=CLASSES,
    augmentation=get_training_augmentation(),
    preprocessing=get_preprocessing(),
    with_shape_assert= True,
)

# Dataset for validation images
valid_dataset = Dataset(
    x_valid_dir,
    y_valid_dir,
    classes=CLASSES,
    augmentation=get_validation_augmentation(),
    preprocessing=get_preprocessing(),
    with_shape_assert= True,
)

train_dataloader = Dataloader(train_dataset, batch_size=BATCH_SIZE, shuffle=True)
valid_dataloader = Dataloader(valid_dataset, batch_size=4, shuffle=False)

# check shapes for errors
assert train_dataloader[0][0].shape == (BATCH_SIZE, 512, 512, 3)
assert train_dataloader[0][1].shape == (BATCH_SIZE, 512, 512, n_classes)

# define callbacks for learning rate scheduling and best checkpoints saving
callbacks = [
    tf.keras.callbacks.ModelCheckpoint('./best_model.h5', save_weights_only=False, save_best_only=True, mode='min'),
    tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=10)
]
results_2704 = model.fit(
    train_dataloader,
    steps_per_epoch=len(train_dataloader),
    epochs=EPOCHS,
    validation_data=valid_dataloader,
    callbacks=callbacks,
    validation_steps=len(valid_dataloader),verbose=1
)

</code>```

This will give the error:

ValueError: No gradients provided for any variable: ['conv2d/kernel:0', 'conv2d/bias:0', 'conv2d_1/kernel:0', 'conv2d_1/bias:0', 'conv2d_2/kernel:0', 'conv2d_2/bias:0', 'conv2d_3/kernel:0', 'conv2d_3/bias:0', 'conv2d_4/kernel:0', 'conv2d_4/bias:0', 'conv2d_5/kernel:0', 'conv2d_5/bias:0', 'conv2d_6/kernel:0', 'conv2d_6/bias:0', 'conv2d_7/kernel:0', 'conv2d_7/bias:0', 'conv2d_8/kernel:0', 'conv2d_8/bias:0', 'conv2d_9/kernel:0', 'conv2d_9/bias:0', 'conv2d_transpose/kernel:0', 'conv2d_transpose/bias:0', 'conv2d_10/kernel:0', 'conv2d_10/bias:0', 'conv2d_11/kernel:0', 'conv2d_11/bias:0', 'conv2d_transpose_1/kernel:0', 'conv2d_transpose_1/bias:0', 'conv2d_12/kernel:0', 'conv2d_12/bias:0', 'conv2d_13/kernel:0', 'conv2d_13/bias:0', 'conv2d_transpose_2/kernel:0', 'conv2d_transpose_2/bias:0', 'conv2d_14/kernel:0', 'conv2d_14/bias:0', 'conv2d_15/kernel:0', 'conv2d_15/bias:0', 'conv2d_transpose_3/kernel:0', 'conv2d_transpose_3/bias:0', 'conv2d_16/kernel:0', 'conv2d_16/bias:0', 'conv2d_17/kernel:0', 'conv2d_17/bias:0', 'conv2d_18/kernel:0', 'conv2d_18/bias:0'].

I know it is maybe due to the dead gradients and I have been trying to solve this problem while also posted on Tensorflow github for a month but till now i still do not figure out the solution. So I post here to seek for the help of other Tensorflow experts who may give me some hints while waiting for updating from Tensorflow support person. I searched around and I knew that using tf.GradientTape() may help solve the issue but I myself still could not figure out the right way.

Really looking forward to any advise. Thank you very much

答:
You get this error when you pass only the training data and missed to pass the labels in model.fit(). I was able to recreate your error using below code. You can download the dataset I am using in the program from here.

Code to recreate the issue -

```<code>%tensorflow_version 2.x
# MLP for Pima Indians Dataset saved to single file
import numpy as np
from numpy import loadtxt
import tensorflow as tf
print(tf.__version__)
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense

# load pima indians dataset
dataset = np.loadtxt("/content/pima-indians-diabetes.csv", delimiter=",")

# split into input (X) and output (Y) variables
X = dataset[:,0:8]
Y = dataset[:,8]

# define model
model = Sequential()
model.add(Dense(12, input_dim=8, activation='relu'))
model.add(Dense(8, activation='relu'))
model.add(Dense(1, activation='sigmoid'))

# compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

# Model Summary
#model.summary()

# Fit the model
model.fit(X, epochs=150, batch_size=10, verbose=0)
</code>```

Output -

```<code>2.2.0
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-4-7ddca8f2992e> in <module>()
     28
     29 # Fit the model
---> 30 model.fit(X, epochs=150, batch_size=10, verbose=0)

10 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)
    966           except Exception as e:  # pylint:disable=broad-except
    967             if hasattr(e, "ag_error_metadata"):
--> 968               raise e.ag_error_metadata.to_exception(e)
    969             else:
    970               raise

ValueError: in user code:

    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:571 train_function  *
        outputs = self.distribute_strategy.run(
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:951 run  **
        return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:2290 call_for_each_replica
        return self._call_for_each_replica(fn, args, kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:2649 _call_for_each_replica
        return fn(*args, **kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:541 train_step  **
        self.trainable_variables)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:1804 _minimize
        trainable_variables))
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:521 _aggregate_gradients
        filtered_grads_and_vars = _filter_grads(grads_and_vars)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:1219 _filter_grads
        ([v.name for _, v in grads_and_vars],))

    ValueError: No gradients provided for any variable: ['dense_5/kernel:0', 'dense_5/bias:0', 'dense_6/kernel:0', 'dense_6/bias:0', 'dense_7/kernel:0', 'dense_7/bias:0'].
</code>```

Solution - Pass the training labels in model.fit() and your error will be fixed.

Modified,

```<code>model.fit(X , epochs=150, batch_size=10, verbose=0)
</code>```

to

```<code>model.fit(X , Y, epochs=150, batch_size=10, verbose=0)
</code>```

Code -

```<code>%tensorflow_version 2.x
# MLP for Pima Indians Dataset saved to single file
import numpy as np
from numpy import loadtxt
import tensorflow as tf
print(tf.__version__)
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense

# load pima indians dataset
dataset = np.loadtxt("/content/pima-indians-diabetes.csv", delimiter=",")

# split into input (X) and output (Y) variables
X = dataset[:,0:8]
Y = dataset[:,8]

# define model
model = Sequential()
model.add(Dense(12, input_dim=8, activation='relu'))
model.add(Dense(8, activation='relu'))
model.add(Dense(1, activation='sigmoid'))

# compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

# Model Summary
#model.summary()

# Fit the model
model.fit(X , Y, epochs=150, batch_size=10, verbose=0)
</code>```

Output -

```<code>2.2.0
<tensorflow.python.keras.callbacks.History at 0x7f9208433eb8>
</code>```

Hope this answers your question. Happy Learning.

Body:
System information
Colab tensorflow 2.2.0

Describe the current behavior:
I faced this error when i tried to solve my own data issues, which is multiple label semantic segmentations.

Below is the code

import tensorflow as tf
import tensorflow.keras.backend as K

IMG_WIDTH = 512
IMG_HEIGHT = 512
IMG_CHANNELS = 3

# batch_shape=(512,512,3)
# inputs = Input(batch_shape=(4, 512, 512, 3))
#Build the model
inputs = tf.keras.layers.Input((IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS))
#s = tf.keras.layers.Lambda(lambda x: x / 255)(inputs)

#Contraction path
c1 = tf.keras.layers.Conv2D(16, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(inputs)
c1 = tf.keras.layers.Dropout(0.1)(c1)
c1 = tf.keras.layers.Conv2D(16, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(c1)
p1 = tf.keras.layers.MaxPooling2D((2, 2))(c1)

c2 = tf.keras.layers.Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(p1)
c2 = tf.keras.layers.Dropout(0.1)(c2)
c2 = tf.keras.layers.Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(c2)
p2 = tf.keras.layers.MaxPooling2D((2, 2))(c2)

c3 = tf.keras.layers.Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(p2)
c3 = tf.keras.layers.Dropout(0.2)(c3)
c3 = tf.keras.layers.Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(c3)
p3 = tf.keras.layers.MaxPooling2D((2, 2))(c3)

c4 = tf.keras.layers.Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(p3)
c4 = tf.keras.layers.Dropout(0.2)(c4)
c4 = tf.keras.layers.Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(c4)
p4 = tf.keras.layers.MaxPooling2D(pool_size=(2, 2))(c4)

c5 = tf.keras.layers.Conv2D(256, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(p4)
c5 = tf.keras.layers.Dropout(0.3)(c5)
c5 = tf.keras.layers.Conv2D(256, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(c5)

#Expansive path
u6 = tf.keras.layers.Conv2DTranspose(128, (2, 2), strides=(2, 2), padding='same')(c5)
u6 = tf.keras.layers.concatenate([u6, c4])
c6 = tf.keras.layers.Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(u6)
c6 = tf.keras.layers.Dropout(0.2)(c6)
c6 = tf.keras.layers.Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(c6)

u7 = tf.keras.layers.Conv2DTranspose(64, (2, 2), strides=(2, 2), padding='same')(c6)
u7 = tf.keras.layers.concatenate([u7, c3])
c7 = tf.keras.layers.Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(u7)
c7 = tf.keras.layers.Dropout(0.2)(c7)
c7 = tf.keras.layers.Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(c7)

u8 = tf.keras.layers.Conv2DTranspose(32, (2, 2), strides=(2, 2), padding='same')(c7)
u8 = tf.keras.layers.concatenate([u8, c2])
c8 = tf.keras.layers.Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(u8)
c8 = tf.keras.layers.Dropout(0.1)(c8)
c8 = tf.keras.layers.Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(c8)

u9 = tf.keras.layers.Conv2DTranspose(16, (2, 2), strides=(2, 2), padding='same')(c8)
u9 = tf.keras.layers.concatenate([u9, c1], axis=3)
c9 = tf.keras.layers.Conv2D(16, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(u9)
c9 = tf.keras.layers.Dropout(0.1)(c9)
c9 = tf.keras.layers.Conv2D(16, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(c9)

outputs = tf.keras.layers.Conv2D(6, (1, 1), activation='softmax')(c9)

model = tf.keras.Model(inputs=[inputs], outputs=[outputs])

# define optomizer
optim = tf.keras.optimizers.Adam()

def dice_coef(y_true, y_pred):
    y_true_f = K.flatten(y_true)
    y_pred_f = K.flatten(y_pred)
    intersection = K.sum(y_true_f * y_pred_f)
    return (2. * intersection + smooth) / (K.sum(y_true_f*y_true_f) + K.sum(y_pred_f*y_pred_f) + smooth)

def dice_coef_loss(y_true, y_pred):
    return 1.-dice_coef(y_true, y_pred)

smooth = 1.
loss= tf.keras.losses.CategoricalCrossentropy()

model.compile(optim, loss, metrics=[dice_coef,'accuracy'])

#model.compile(optim, metrics, loss)
model.summary()

#SET UP FOR DATA TRAINING

BATCH_SIZE = 4
CLASSES = ['0', '1','2','3','4','5']
LR = 0.0001
EPOCHS = 40
n_classes = len(CLASSES)

# Dataset for train images
train_dataset = Dataset(
    x_train_dir,
    y_train_dir,
    classes=CLASSES,
    augmentation=get_training_augmentation(),
    preprocessing=get_preprocessing(),
    with_shape_assert= True,
)

# Dataset for validation images
valid_dataset = Dataset(
    x_valid_dir,
    y_valid_dir,
    classes=CLASSES,
    augmentation=get_validation_augmentation(),
    preprocessing=get_preprocessing(),
    with_shape_assert= True,
)

train_dataloader = Dataloader(train_dataset, batch_size=BATCH_SIZE, shuffle=True)
valid_dataloader = Dataloader(valid_dataset, batch_size=4, shuffle=False)

# check shapes for errors
assert train_dataloader[0][0].shape == (BATCH_SIZE, 512, 512, 3)
assert train_dataloader[0][1].shape == (BATCH_SIZE, 512, 512, n_classes)

# define callbacks for learning rate scheduling and best checkpoints saving
callbacks = [
    tf.keras.callbacks.ModelCheckpoint('./best_model.h5', save_weights_only=False, save_best_only=True, mode='min'),
    tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=10)
]
results_2704 = model.fit(
    train_dataloader,
    steps_per_epoch=len(train_dataloader),
    epochs=EPOCHS,
    validation_data=valid_dataloader,
    callbacks=callbacks,
    validation_steps=len(valid_dataloader),verbose=1
)

This will give the error:

ValueError: No gradients provided for any variable: ['conv2d/kernel:0', 'conv2d/bias:0', 'conv2d_1/kernel:0', 'conv2d_1/bias:0', 'conv2d_2/kernel:0', 'conv2d_2/bias:0', 'conv2d_3/kernel:0', 'conv2d_3/bias:0', 'conv2d_4/kernel:0', 'conv2d_4/bias:0', 'conv2d_5/kernel:0', 'conv2d_5/bias:0', 'conv2d_6/kernel:0', 'conv2d_6/bias:0', 'conv2d_7/kernel:0', 'conv2d_7/bias:0', 'conv2d_8/kernel:0', 'conv2d_8/bias:0', 'conv2d_9/kernel:0', 'conv2d_9/bias:0', 'conv2d_transpose/kernel:0', 'conv2d_transpose/bias:0', 'conv2d_10/kernel:0', 'conv2d_10/bias:0', 'conv2d_11/kernel:0', 'conv2d_11/bias:0', 'conv2d_transpose_1/kernel:0', 'conv2d_transpose_1/bias:0', 'conv2d_12/kernel:0', 'conv2d_12/bias:0', 'conv2d_13/kernel:0', 'conv2d_13/bias:0', 'conv2d_transpose_2/kernel:0', 'conv2d_transpose_2/bias:0', 'conv2d_14/kernel:0', 'conv2d_14/bias:0', 'conv2d_15/kernel:0', 'conv2d_15/bias:0', 'conv2d_transpose_3/kernel:0', 'conv2d_transpose_3/bias:0', 'conv2d_16/kernel:0', 'conv2d_16/bias:0', 'conv2d_17/kernel:0', 'conv2d_17/bias:0', 'conv2d_18/kernel:0', 'conv2d_18/bias:0'].

I know it is maybe due to the dead gradients and I have been trying to solve this problem while also posted on Tensorflow github for a month but till now i still do not figure out the solution. So I post here to seek for the help of other Tensorflow experts who may give me some hints while waiting for updating from Tensorflow support person. I searched around and I knew that using tf.GradientTape() may help solve the issue but I myself still could not figure out the right way.

Really looking forward to any advise. Thank you very much

Body:
You get this error when you pass only the training data and missed to pass the labels in model.fit(). I was able to recreate your error using below code. You can download the dataset I am using in the program from here.

Code to recreate the issue -

%tensorflow_version 2.x
# MLP for Pima Indians Dataset saved to single file
import numpy as np
from numpy import loadtxt
import tensorflow as tf
print(tf.__version__)
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense

# load pima indians dataset
dataset = np.loadtxt("/content/pima-indians-diabetes.csv", delimiter=",")

# split into input (X) and output (Y) variables
X = dataset[:,0:8]
Y = dataset[:,8]

# define model
model = Sequential()
model.add(Dense(12, input_dim=8, activation='relu'))
model.add(Dense(8, activation='relu'))
model.add(Dense(1, activation='sigmoid'))

# compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

# Model Summary
#model.summary()

# Fit the model
model.fit(X, epochs=150, batch_size=10, verbose=0)

Output -

2.2.0
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-4-7ddca8f2992e> in <module>()
     28
     29 # Fit the model
---> 30 model.fit(X, epochs=150, batch_size=10, verbose=0)

10 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)
    966           except Exception as e:  # pylint:disable=broad-except
    967             if hasattr(e, "ag_error_metadata"):
--> 968               raise e.ag_error_metadata.to_exception(e)
    969             else:
    970               raise

ValueError: in user code:

    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:571 train_function  *
        outputs = self.distribute_strategy.run(
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:951 run  **
        return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:2290 call_for_each_replica
        return self._call_for_each_replica(fn, args, kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:2649 _call_for_each_replica
        return fn(*args, **kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:541 train_step  **
        self.trainable_variables)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:1804 _minimize
        trainable_variables))
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:521 _aggregate_gradients
        filtered_grads_and_vars = _filter_grads(grads_and_vars)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:1219 _filter_grads
        ([v.name for _, v in grads_and_vars],))

    ValueError: No gradients provided for any variable: ['dense_5/kernel:0', 'dense_5/bias:0', 'dense_6/kernel:0', 'dense_6/bias:0', 'dense_7/kernel:0', 'dense_7/bias:0'].

Solution - Pass the training labels in model.fit() and your error will be fixed.

Modified,

model.fit(X , epochs=150, batch_size=10, verbose=0)

to

model.fit(X , Y, epochs=150, batch_size=10, verbose=0)

Code -

%tensorflow_version 2.x
# MLP for Pima Indians Dataset saved to single file
import numpy as np
from numpy import loadtxt
import tensorflow as tf
print(tf.__version__)
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense

# load pima indians dataset
dataset = np.loadtxt("/content/pima-indians-diabetes.csv", delimiter=",")

# split into input (X) and output (Y) variables
X = dataset[:,0:8]
Y = dataset[:,8]

# define model
model = Sequential()
model.add(Dense(12, input_dim=8, activation='relu'))
model.add(Dense(8, activation='relu'))
model.add(Dense(1, activation='sigmoid'))

# compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

# Model Summary
#model.summary()

# Fit the model
model.fit(X , Y, epochs=150, batch_size=10, verbose=0)

Output -

2.2.0
<tensorflow.python.keras.callbacks.History at 0x7f9208433eb8>

Hope this answers your question. Happy Learning.


来源: stackexchange

问:
In an arm32 image-based container, readdir returns EOVERFLOW when directory is empty
Upon calling readdir function in a C program within an arm32-based container executing on x64-based Ubuntu 19.10 host, the call returns EOVERFLOW for empty directories (e.g., /mnt, /media) instead of returning 0.

Have others observed this issue?  Is this a configuration issue?  If so, how can it be fixed?

Versions:

Guest: debian:buster- backports@sha256:8f27850df2144df1598b5c76b213616ecaab08e804a6d84ddace1455d8cbd9f0

Host: Ubuntu 19.10, amd64, Docker version: 19.03.6-0ubuntu1~19.10.1

Qemu version: 1:4.0+dfsg-0ubuntu9.6

Repro steps:

Build an image named crystal-for-buster-armhf:v1 based on Debian Buster for arm32 using the Dockerfile and build.sh script available here.

Start a container based on this image.

Compile and build the below program.

Execute the resulting executable with a directory name as a command line argument.

#define _POSIX_SOURCE
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
#undef _POSIX_SOURCE
#include <stdio.h>

main(int argc, char* argv[]) {
  DIR *dir;
  struct dirent *entry;

  if ((dir = opendir(argv[1])) == NULL)
    perror("opendir() error");
  else {
    puts("contents:");
    while (1) {
      errno = 0;
      entry = readdir(dir);
      if (entry == NULL) {
        printf("Errno: %d   EOVERFLOW: %d\n", errno, EOVERFLOW);
        break;
      }
      printf("  %s\n", entry->d_name);
    }
    closedir(dir);
  }
}
```

答: If you're using glibc (most Linux-based systems), you need to compile with -D_FILE_OFFSET_BITS=64. The default is still 32-bit off_t, and with it 32-bit ino_t, and in such a configuration, readdir, stat, etc. will fail with EOVERFLOW if the inode number does not fit in 32 bits. Many modern filesystems always have inode numbers that don't fit in 32 bits.

ContentLicense: CC BY-SA 4.0


问:
Filtering the dataFrame based on when condition
Hi i am trying to filter the dataframe based on when condition and then apply schema if it matches else leave it as it is.

```<code>val schema = ArrayType(StructType(StructField("packQty",FloatType,true):: StructField("gtin",StringType,true) :: Nil))

+--------------+---------+-----------+-----+--------------------------------------+
|orderupcnumber|enrichqty|allocoutqty|allocatedqty|gtins
|
+--------------+---------+-----------+--------------------------------------------+
|5203754   |15.0     |1.0        |5.0         |[{"packQty":120.0,"gtin":"00052000042276"}]|
|5203754   |15.0     |1.0        |2.0         |[{"packQty":120.0,"gtin":"00052000042276"}|
|5243700   |25.0     |1.0        |2.0         |na
|
+--------------+---------+-----------+------------+-------------------------------+
</code>```

i am tryin to add a column based on schema if the gtins column is not "na" if it is  i am adding 0, but it is throwing the error saying

```<code> df.withColumn("jsonData",when($"gtins"=!="na",from_json($"gtins",schema)).otherwise(0))

 Exception in thread "main" org.apache.spark.sql.AnalysisException: cannot resolve 'CASE
 WHEN contains(`gtins`, 'na') THEN 0 ELSE jsontostructs(`gtins`) END' due to data type
 mismatch: THEN and ELSE expressions should all be same type or coercible to a common type;;

 df.select($"orderupcnumber",$"enrichqty",$"allocoutqty",$"allocatedqty",explode($"jsonData").as("jsonData"))

 +--------------+---------+-----------+-----+--------------+
 |orderupcnumber|enrichqty|allocoutqty|allocatedqty|gtins|JsonData
 +--------------+---------+-----------+--------------------+
 |5203754   |15.0|1.0|5.0|[{"packQty":120.0,"gtin":"00052000042276”}]|[120.0, 00052000042276]
 |5203754   |15.0|1.0 |2.0|[{"packQty":120.0,"gtin":"00052000042276”}|[120.0,00052000042276]
 |5243700   |25.0 |1.0|2.0  |na  |null
 +--------------+---------+-----------+------------+----+

 df.select($"orderupcnumber",$"enrichqty",$"allocoutqty",$"allocatedqty",$"jsonData.packQty".as("packQty"),$"jsonData.gtin".as("gtin")
</code>```

this select is only selecting data where jsonData is not null

```<code>+---------+-----------+------------+-------+--------------+
 orderupcnumber |enrichqty|allocoutqty|allocatedqty|packQty|gtin  |
 +-----------+------------+----------------+------------+
 5203754|15.0     |1.0        |5.0         |120.0  |00052000042276|
 5203754|15.0     |1.0        |5.0         |144.0  |00052000042283|
 5243700|25.0     |1.0        |5.0         |  | |
 +-----------+------------+----------------+------------+----------
</code>```

how can i include one with null as well.

Body:
Hi i am trying to filter the dataframe based on when condition and then apply schema if it matches else leave it as it is.

val schema = ArrayType(StructType(StructField("packQty",FloatType,true):: StructField("gtin",StringType,true) :: Nil))

+--------------+---------+-----------+-----+--------------------------------------+
|orderupcnumber|enrichqty|allocoutqty|allocatedqty|gtins
|
+--------------+---------+-----------+--------------------------------------------+
|5203754   |15.0     |1.0        |5.0         |[{"packQty":120.0,"gtin":"00052000042276"}]|
|5203754   |15.0     |1.0        |2.0         |[{"packQty":120.0,"gtin":"00052000042276"}|
|5243700   |25.0     |1.0        |2.0         |na
|
+--------------+---------+-----------+------------+-------------------------------+

i am tryin to add a column based on schema if the gtins column is not "na" if it is  i am adding 0, but it is throwing the error saying

 df.withColumn("jsonData",when($"gtins"=!="na",from_json($"gtins",schema)).otherwise(0))

 Exception in thread "main" org.apache.spark.sql.AnalysisException: cannot resolve 'CASE
 WHEN contains(`gtins`, 'na') THEN 0 ELSE jsontostructs(`gtins`) END' due to data type
 mismatch: THEN and ELSE expressions should all be same type or coercible to a common type;;

 df.select($"orderupcnumber",$"enrichqty",$"allocoutqty",$"allocatedqty",explode($"jsonData").as("jsonData"))

 +--------------+---------+-----------+-----+--------------+
 |orderupcnumber|enrichqty|allocoutqty|allocatedqty|gtins|JsonData
 +--------------+---------+-----------+--------------------+
 |5203754   |15.0|1.0|5.0|[{"packQty":120.0,"gtin":"00052000042276”}]|[120.0, 00052000042276]
 |5203754   |15.0|1.0 |2.0|[{"packQty":120.0,"gtin":"00052000042276”}|[120.0,00052000042276]
 |5243700   |25.0 |1.0|2.0  |na  |null
 +--------------+---------+-----------+------------+----+

 df.select($"orderupcnumber",$"enrichqty",$"allocoutqty",$"allocatedqty",$"jsonData.packQty".as("packQty"),$"jsonData.gtin".as("gtin")

this select is only selecting data where jsonData is not null

+---------+-----------+------------+-------+--------------+
 orderupcnumber |enrichqty|allocoutqty|allocatedqty|packQty|gtin  |
 +-----------+------------+----------------+------------+
 5203754|15.0     |1.0        |5.0         |120.0  |00052000042276|
 5203754|15.0     |1.0        |5.0         |144.0  |00052000042283|
 5243700|25.0     |1.0        |5.0         |  | |
 +-----------+------------+----------------+------------+----------

how can i include one with null as well.

Body:
If your input data looks something like below where the multiple gtins are in a array of strings, then you can explode it first and then apply the schema and withColumn accordingly:

+--------------+---------+-----------+------------+--------------------------------------------------------------------------------------+
|orderupcnumber|enrichqty|allocoutqty|allocatedqty|gtins                                                                                |
+--------------+---------+-----------+------------+--------------------------------------------------------------------------------------+
|5243754       |15.0     |1.0        |5.0         |[{"packQty":120.0,"gtin":"00052000042276"}, {"packQty":250.0,"gtin":"00052000012345"}]|
|5243700       |25.0     |1.0        |2.0         |[na]                                                                                |
+--------------+---------+-----------+------------+--------------------------------------------------------------------------------------+

Then use below::

val schema = StructType(StructField("packQty",FloatType,true):: StructField("gtin",StringType,true) :: Nil)

df.withColumn("gtins",explode($"gtins")).withColumn("jsonData",from_json($"gtins",schema)).withColumn("packQty",$"jsonData.packQty").withColumn("gtin",$"jsondata.gtin").show(false)

+--------------+---------+-----------+------------+-----------------------------------------+-----------------------+-------+--------------+
|orderupcnumber|enrichqty|allocoutqty|allocatedqty|gtins                                    |jsonData               |packQty|gtin          |
+--------------+---------+-----------+------------+-----------------------------------------+-----------------------+-------+--------------+
|5243754       |15.0     |1.0        |5.0         |{"packQty":120.0,"gtin":"00052000042276"}|[120.0, 00052000042276]|120.0  |00052000042276|
|5243754       |15.0     |1.0        |5.0         |{"packQty":250.0,"gtin":"00052000012345"}|[250.0, 00052000012345]|250.0  |00052000012345|
|5243700       |25.0     |1.0        |2.0         |na                                       |null                   |null   |null          |
+--------------+---------+-----------+------------+-----------------------------------------+-----------------------+-------+--------------+


问:
Table with 100% width with equal size columns
I have to dynamically create a table with a variable number of columns, determined at runtime.

Can somebody tell me if it's possible to have a html table with equal size columns that are fully stretched?

答:
```<code>table {
    width: 100%;

    th, td {
        width: 1%;
    }
}
</code>```

SCSS syntax

Body:
table {
    width: 100%;

    th, td {
        width: 1%;
    }
}

SCSS syntax


问:
UWP - FolderPicker Commit Button disabled inside initial folder
I have an FolderPicker in my UWP app, implemented like this:

```<code>    var folderPicker = new FolderPicker
    {
        SuggestedStartLocation = PickerLocationId.PicturesLibrary,
    };
    folderPicker.FileTypeFilter.Add("*");
    StorageFolder targetFolder = await folderPicker.PickSingleFolderAsync();
</code>```

When the folder picker opens, the explorer shows the content of the picture library, but the library/folder is itself not yet selected and the Commit Button is disabled and cannot be selected. The users has to navigate one level up to select the picture library folder and then he can click the button.

Is there a way around this? I want the user to be able to simply confirm that the picture library is the desired target destination and he just needs to approve this by pressing the commit button instead.

答:
Currently UWP's FolderPicker does not provide a setting to select the initial folder.

SuggestedStartLocation is to provide an initial starting location, but the newly created FolderPicker itself will not select the folder at startup. If there is no folder selected, the submit button will be disabled, which also causes the user to click the picture library folder for confirmation.

If you need to call the picture library folder, you don't need to use FolderPicker, but use KnowFolders:

var pictureFolder = KnownFolders.PicturesLibrary;
```

The premise is that you need to check Pictures Library in Package.appxmanifest > Capability.

Thanks.

Body:
I have an FolderPicker in my UWP app, implemented like this:

    var folderPicker = new FolderPicker
    {
        SuggestedStartLocation = PickerLocationId.PicturesLibrary,
    };
    folderPicker.FileTypeFilter.Add("*");
    StorageFolder targetFolder = await folderPicker.PickSingleFolderAsync();

When the folder picker opens, the explorer shows the content of the picture library, but the library/folder is itself not yet selected and the Commit Button is disabled and cannot be selected. The users has to navigate one level up to select the picture library folder and then he can click the button.

Is there a way around this? I want the user to be able to simply confirm that the picture library is the desired target destination and he just needs to approve this by pressing the commit button instead.

Body:
Currently UWP's FolderPicker does not provide a setting to select the initial folder.

SuggestedStartLocation is to provide an initial starting location, but the newly created FolderPicker itself will not select the folder at startup. If there is no folder selected, the submit button will be disabled, which also causes the user to click the picture library folder for confirmation.

If you need to call the picture library folder, you don't need to use FolderPicker, but use KnowFolders:

var pictureFolder = KnownFolders.PicturesLibrary;

The premise is that you need to check Pictures Library in Package.appxmanifest > Capability.

Thanks.


问:
Xamarin forms TabbedPage icons are tiny
Using a TabbedPage with five tabs, though the issue is the same with only two, I see the rendered icons being very small, as shown in this image, using some placeholder graphics.

I have tried images at all pixel resolutions from 32x32 to 512x512 and they all render the same size. You would expect an option to set this, but when looking for solutions, it seems to always boil down to making custom renderes. I have not seen anyone complaining about tiny icons, though, but generally more complex issues, so I am still hoping for a generalized forms solution.

In the screenshot (android on device) I use a master detail page to give a toolbar and left menu, but the issue is the same when I have a clean TabbedPage on its own.

The definition of the TabbedPage is trivial, so I doubt there is any issue there

```<code><?xml version="1.0" encoding="utf-8" ?>
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
            xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
            xmlns:d="http://xamarin.com/schemas/2014/forms/design"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            mc:Ignorable="d"
            xmlns:views="clr-namespace:CloudDash.Views"
            x:Class="CloudDash.Views.TabPage">

    <TabbedPage.Children>
        <views:ThermalingPage IconImageSource="fly.png"/>
        <views:DataPage IconImageSource="fly.png"/>
        <views:FlightPage IconImageSource="fly.png"/>
        <views:RoutePage IconImageSource="fly.png"/>
        <views:AwarenessPage IconImageSource="fly.png"/>
    </TabbedPage.Children>

</TabbedPage>
</code>```

答:
If you want to make the icon to bigger, you have to make a custom renderer to achieve it.
Here is running screenshot.

In the Android folder. create a custom renderer MyTabbedPageRenderer.cs.

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.Content.Res;
using Android.OS;
using Android.Runtime;
using Android.Support.Design.Widget;
using Android.Support.V4.View;
using Android.Views;
using Android.Widget;
using App22.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using Xamarin.Forms.Platform.Android.AppCompat;

[assembly: ExportRenderer(typeof(TabbedPage), typeof(MyTabbedPageRenderer))]
namespace App22.Droid
{
     public class MyTabbedPageRenderer:TabbedPageRenderer
    {
        public MyTabbedPageRenderer(Context context) : base(context)
       {

       }

        protected override void SetTabIcon(TabLayout.Tab tab, FileImageSource icon)
        {
            base.SetTabIcon(tab, icon);
            tab.SetCustomView(Resource.Layout.Custom_tab_layou);

            var imageview = tab.CustomView.FindViewById<ImageView>(Resource.Id.icon);

            imageview.SetBackgroundDrawable(tab.Icon);

        }
    }
}
</code>```

Create a Custom_tab_layou.xml in layout folder.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="61dp">
     <ImageView
        android:id="@+id/icon"
        android:layout_width="38dp"
        android:layout_height="38dp"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="4dp"
        android:layout_marginBottom="4dp" />

</LinearLayout>
</code>```

In the IOS, you can refer to this thread:

https://forums.xamarin.com/discussion/44069/tab-bar-icon-sizing

You also could make a feature request in xamarin part of github page, PG will see it.

https://github.com/xamarin/Xamarin.Forms/issues

Title: Xamarin forms TabbedPage icons are tiny

Body:
Using a TabbedPage with five tabs, though the issue is the same with only two, I see the rendered icons being very small, as shown in this image, using some placeholder graphics.

I have tried images at all pixel resolutions from 32x32 to 512x512 and they all render the same size. You would expect an option to set this, but when looking for solutions, it seems to always boil down to making custom renderes. I have not seen anyone complaining about tiny icons, though, but generally more complex issues, so I am still hoping for a generalized forms solution.

In the screenshot (android on device) I use a master detail page to give a toolbar and left menu, but the issue is the same when I have a clean TabbedPage on its own.

The definition of the TabbedPage is trivial, so I doubt there is any issue there

<?xml version="1.0" encoding="utf-8" ?>
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
            xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
            xmlns:d="http://xamarin.com/schemas/2014/forms/design"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            mc:Ignorable="d"
            xmlns:views="clr-namespace:CloudDash.Views"
            x:Class="CloudDash.Views.TabPage">

    <TabbedPage.Children>
        <views:ThermalingPage IconImageSource="fly.png"/>
        <views:DataPage IconImageSource="fly.png"/>
        <views:FlightPage IconImageSource="fly.png"/>
        <views:RoutePage IconImageSource="fly.png"/>
        <views:AwarenessPage IconImageSource="fly.png"/>
    </TabbedPage.Children>

</TabbedPage>

Body:
If you want to make the icon to bigger, you have to make a custom renderer to achieve it.
Here is running screenshot.

In the Android folder. create a custom renderer MyTabbedPageRenderer.cs.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.Content.Res;
using Android.OS;
using Android.Runtime;
using Android.Support.Design.Widget;
using Android.Support.V4.View;
using Android.Views;
using Android.Widget;
using App22.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using Xamarin.Forms.Platform.Android.AppCompat;

[assembly: ExportRenderer(typeof(TabbedPage), typeof(MyTabbedPageRenderer))]
namespace App22.Droid
{
     public class MyTabbedPageRenderer:TabbedPageRenderer
    {
        public MyTabbedPageRenderer(Context context) : base(context)
       {

       }

        protected override void SetTabIcon(TabLayout.Tab tab, FileImageSource icon)
        {
            base.SetTabIcon(tab, icon);
            tab.SetCustomView(Resource.Layout.Custom_tab_layou);

            var imageview = tab.CustomView.FindViewById<ImageView>(Resource.Id.icon);

            imageview.SetBackgroundDrawable(tab.Icon);

        }
    }
}

Create a Custom_tab_layou.xml in layout folder.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="61dp">
     <ImageView
        android:id="@+id/icon"
        android:layout_width="38dp"
        android:layout_height="38dp"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="4dp"
        android:layout_marginBottom="4dp" />

</LinearLayout>

In the IOS, you can refer to this thread:

https://forums.xamarin.com/discussion/44069/tab-bar-icon-sizing

You also could make a feature request in xamarin part of github page, PG will see it.

https://github.com/xamarin/Xamarin.Forms/issues


问:
Flutter: setState((){} fails to redraw DropdownButton value
I am new to flutter, and am trying to code mobile game. So far I have been able to manage through previous questions on forums, youtube tutorials and example apps. However I have hit a wall that I cannot solve.

Many of the features in my UI are supposed to change based on user behavior but do not update, I am using this DropdownButton as my example but it is a problem I am having elsewhere in the code as well. When the user makes a selection from the DropdownButton it should update the value of the button, but instead only the hint is displayed. I have been able to determine through print statements that the selection is registered.

Based on what I have learned so far I suspect that the issue entails my widget's statefulness or lack thereof. I found a few similar questions which suggested using a StatefulBuilder, however when I tried to implement it the code had errors or else duplicated my entire ListTile group. I also saw suggestions about creating a stateful widget instead but the instructions were too vague for me to follow and implement without errors. I am including snippets of the code below, I am hesitant to paste the whole thing because the app is nearly 2000 lines at this point. Please let me know if any further information or code is needed.
this is the problematic code, see below for the code in context.

```<code>        DropdownButton(
          value: skillChoice,
          items: listDrop,
          hint: Text("Choose Skill"),
          onChanged: (value) {
            setState(() {
              skillChoice = value;
            });
          },
        ),
</code>```
```<code>void main() => runApp(MyApp());
class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Hunters Guild',
      theme: ThemeData(
        primaryColor: Colors.grey,
      ),
      home: Main(),
    );
  }
}
final List<Combatant> _combatants = List<Combatant>();
//combatant is a class that holds stats like HP which may change during a battle
//they also have a Fighter and a Monster and one of those will be null and the other useful
//depending if faction = "good" or "evil
//I am aware that this may not be the most elegant implementation but that is a problem for another day.

class MainState extends State<Main> {
  final List<Fighter> _squad = List<Fighter>();
//Fighter is a class which stores info like HP, name, skills, etc for game character,
//this List is populated in the page previous to _fight
//where the user picks which characters they are using in a given battle
void _fight(Quest theQuest){
    for(Fighter guy in _squad){
      _combatants.add(Combatant("good", guy, null));
    }
    _combatants.add(Combatant("evil", null, theQuest.boss));
//quests are a class which store a boss Monster, later on I will add other things like rewards and prerequisites
final tiles = _combatants.map((Combatant comba){ //this structure is from the build your first app codelab
      List<DropdownMenuItem<String>> listDrop = [];
      String skillChoice = null;
      if (comba.faction == "good"){
        for (Skill skill in comba.guy.skills){
          listDrop.add((DropdownMenuItem(child: Text(skill.name), value: skill.name)));
        }
      }
      else if (comba.faction == "evil"){
        for (Skill skill in comba.boss.skills){
          listDrop.add((DropdownMenuItem(child: Text(skill.name), value: skill.name)));
        }
      }
//^this code populates each ListTile (one for each combatant) with a drop down button of all their combat skills
      return ListTile(

        leading: comba.port,
        title: Text(comba.info),
        onTap: () {
          if(comba.faction == "good"){
            _fighterFightInfo(comba.guy, theQuest.boss); //separate page with more detailed info, not finished
          }
          else{
            _monsterFightInfo(theQuest.boss); //same but for monsters
          }
        },
        trailing: Row(
          mainAxisSize: MainAxisSize.min,
          children: [

            DropdownButton( //HERE IS WHERE THE ERROR LIES
              value: skillChoice,
              items: listDrop,
              hint: Text("Choose Skill"),
              onChanged: (value) {
                setState(() {
                  skillChoice = value;
                });
              },
            ),
            IconButton(icon: Icon(Icons.check), onPressed: (){
//eventually this button will be used to execute the user's skill choice
            })
          ],
        ),
        subtitle: Text(comba.hp.toString()),
      );
    },
    );
    Navigator.of(context).push(
      MaterialPageRoute<void>(
        builder: (BuildContext context) {
//I have tried moving most of the above code into here,
//and also implementing StatelessBuilders here and other places in the below code to no effect
          final divided = ListTile.divideTiles(
            context: context,
            tiles: tiles,
          ).toList();
          return Scaffold(
            appBar: AppBar(
              title: Text("Slay "+theQuest.boss.name+"  "+theQuest.boss.level.toString()+"  "+theQuest.boss.type.name, style: TextStyle(fontSize: 14),),
              leading: IconButton(icon: Icon(Icons.arrow_back), onPressed: () {
                _squadSelect(theQuest);
              }),
            ),
            body: ListView(children: divided),
          );
        },
      ),
    );
  }
//there are a lot more methods here which I haven't included
 @override

  Widget build(BuildContext context) {
//I can show this if you need it but there's a lot of UI building on the main page
//Also might not be the most efficiently implemented
//what you need to know is that there are buttons which call _fight and go to that page
}
class Main extends StatefulWidget {
  @override
  MainState createState() => MainState();
}

</code>```

Thank you for any help or advice you can offer.

答:
Its a bit difficult to understand what is going on here, so if possible add the problem areas in a new widget and post it here.

In any case, for now it seems your skillShare variable is local, so every time you are setting state it does not update. Try something like this:

```<code>class MainState extends State<Main> {
String skillShare = ""; //i.e make skillShare a global variable
final List<Fighter> _squad = List<Fighter>();
</code>```

Body:
I am new to flutter, and am trying to code mobile game. So far I have been able to manage through previous questions on forums, youtube tutorials and example apps. However I have hit a wall that I cannot solve.

Many of the features in my UI are supposed to change based on user behavior but do not update, I am using this DropdownButton as my example but it is a problem I am having elsewhere in the code as well. When the user makes a selection from the DropdownButton it should update the value of the button, but instead only the hint is displayed. I have been able to determine through print statements that the selection is registered.

Based on what I have learned so far I suspect that the issue entails my widget's statefulness or lack thereof. I found a few similar questions which suggested using a StatefulBuilder, however when I tried to implement it the code had errors or else duplicated my entire ListTile group. I also saw suggestions about creating a stateful widget instead but the instructions were too vague for me to follow and implement without errors. I am including snippets of the code below, I am hesitant to paste the whole thing because the app is nearly 2000 lines at this point. Please let me know if any further information or code is needed.
this is the problematic code, see below for the code in context.

        DropdownButton(
          value: skillChoice,
          items: listDrop,
          hint: Text("Choose Skill"),
          onChanged: (value) {
            setState(() {
              skillChoice = value;
            });
          },
        ),

void main() => runApp(MyApp());
class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Hunters Guild',
      theme: ThemeData(
        primaryColor: Colors.grey,
      ),
      home: Main(),
    );
  }
}
final List<Combatant> _combatants = List<Combatant>();
//combatant is a class that holds stats like HP which may change during a battle
//they also have a Fighter and a Monster and one of those will be null and the other useful
//depending if faction = "good" or "evil
//I am aware that this may not be the most elegant implementation but that is a problem for another day.

class MainState extends State {
  final List<Fighter> _squad = List<Fighter>();
//Fighter is a class which stores info like HP, name, skills, etc for game character,
//this List is populated in the page previous to _fight
//where the user picks which characters they are using in a given battle
void _fight(Quest theQuest){
    for(Fighter guy in _squad){
      _combatants.add(Combatant("good", guy, null));
    }
    _combatants.add(Combatant("evil", null, theQuest.boss));
//quests are a class which store a boss Monster, later on I will add other things like rewards and prerequisites
final tiles = _combatants.map((Combatant comba){ //this structure is from the build your first app codelab
      List<DropdownMenuItem<String>> listDrop = [];
      String skillChoice = null;
      if (comba.faction == "good"){
        for (Skill skill in comba.guy.skills){
          listDrop.add((DropdownMenuItem(child: Text(skill.name), value: skill.name)));
        }
      }
      else if (comba.faction == "evil"){
        for (Skill skill in comba.boss.skills){
          listDrop.add((DropdownMenuItem(child: Text(skill.name), value: skill.name)));
        }
      }
//^this code populates each ListTile (one for each combatant) with a drop down button of all their combat skills
      return ListTile(

        leading: comba.port,
        title: Text(comba.info),
        onTap: () {
          if(comba.faction == "good"){
            _fighterFightInfo(comba.guy, theQuest.boss); //separate page with more detailed info, not finished
          }
          else{
            _monsterFightInfo(theQuest.boss); //same but for monsters
          }
        },
        trailing: Row(
          mainAxisSize: MainAxisSize.min,
          children: [

            DropdownButton( //HERE IS WHERE THE ERROR LIES
              value: skillChoice,
              items: listDrop,
              hint: Text("Choose Skill"),
              onChanged: (value) {
                setState(() {
                  skillChoice = value;
                });
              },
            ),
            IconButton(icon: Icon(Icons.check), onPressed: (){
//eventually this button will be used to execute the user's skill choice
            })
          ],
        ),
        subtitle: Text(comba.hp.toString()),
      );
    },
    );
    Navigator.of(context).push(
      MaterialPageRoute<void>(
        builder: (BuildContext context) {
//I have tried moving most of the above code into here,
//and also implementing StatelessBuilders here and other places in the below code to no effect
          final divided = ListTile.divideTiles(
            context: context,
            tiles: tiles,
          ).toList();
          return Scaffold(
            appBar: AppBar(
              title: Text("Slay "+theQuest.boss.name+"  "+theQuest.boss.level.toString()+"  "+theQuest.boss.type.name, style: TextStyle(fontSize: 14),),
              leading: IconButton(icon: Icon(Icons.arrow_back), onPressed: () {
                _squadSelect(theQuest);
              }),
            ),
            body: ListView(children: divided),
          );
        },
      ),
    );
  }
//there are a lot more methods here which I haven't included
 @override

  Widget build(BuildContext context) {
//I can show this if you need it but there's a lot of UI building on the main page
//Also might not be the most efficiently implemented
//what you need to know is that there are buttons which call _fight and go to that page
}
class Main extends StatefulWidget {
  @override
  MainState createState() => MainState();
}

Thank you for any help or advice you can offer.

Body:
Its a bit difficult to understand what is going on here, so if possible add the problem areas in a new widget and post it here.

In any case, for now it seems your skillShare variable is local, so every time you are setting state it does not update. Try something like this:

class MainState extends State<Main> {
String skillShare = ""; //i.e make skillShare a global variable
final List<Fighter> _squad = List<Fighter>();


问:
converting a value to datetime in load csv in cypher
I'm trying to load csv file into neo4j using this query:

```<code>:auto

USING PERIODIC COMMIT
LOAD CSV WITH HEADERS FROM 'file:///test.csv' AS row
MERGE (news:newsID {newsID: row.id})
  ON CREATE SET
  news.title = row.title,
  news.creation_date = row.creation_date,
  news.content = row.content;
</code>```

I want to convert creation_date to datetime

I can do that using something like:

```<code>WITH apoc.date.parse("2019-3-8 12:10:11", "ms", "yyyy-MM-dd HH:mm:ss") AS ms
RETURN datetime({epochmillis: ms}) as cdate
</code>```

But I can not use it in the LOAD CSV set part.

How can I convert a field using apoc.date.parse and datetime in LOAD CSV ?

答:
Neo4j can automatically parse a wide variety of string formats to temporal instants (like datetime). You just have to use a supported string format.

Although your example string ("2019-3-8 12:10:11") is not supported, replacing the space character between the date and time with a "T" would work.

For example, try this:

```<code>RETURN datetime("2019-3-8T12:10:11");
</code>```

So, provided your creation_date property values had a supported format, this would work:

```<code>:auto
USING PERIODIC COMMIT
LOAD CSV WITH HEADERS FROM 'file:///test.csv' AS row
MERGE (news:newsID {newsID: row.id})
  ON CREATE SET
  news.title = row.title,
  news.creation_date = datetime(row.creation_date),
  news.content = row.content;
</code>```

Or, if you want to keep your existing CSV file, and assuming its creation_date strings only have a single space character, you can do this:

```<code>:auto
USING PERIODIC COMMIT
LOAD CSV WITH HEADERS FROM 'file:///test.csv' AS row
MERGE (news:newsID {newsID: row.id})
  ON CREATE SET
  news.title = row.title,
  news.creation_date = datetime(REPLACE(row.creation_date, ' ', 'T')),
  news.content = row.content;
</code>```

Body:
I'm trying to load csv file into neo4j using this query:

:auto

USING PERIODIC COMMIT
LOAD CSV WITH HEADERS FROM 'file:///test.csv' AS row
MERGE (news:newsID {newsID: row.id})
  ON CREATE SET
  news.title = row.title,
  news.creation_date = row.creation_date,
  news.content = row.content;

I want to convert creation_date to datetime

I can do that using something like:

WITH apoc.date.parse("2019-3-8 12:10:11", "ms", "yyyy-MM-dd HH:mm:ss") AS ms
RETURN datetime({epochmillis: ms}) as cdate

But I can not use it in the LOAD CSV set part.

How can I convert a field using apoc.date.parse and datetime in LOAD CSV ?

Body:
Neo4j can automatically parse a wide variety of string formats to temporal instants (like datetime). You just have to use a supported string format.

Although your example string ("2019-3-8 12:10:11") is not supported, replacing the space character between the date and time with a "T" would work.

For example, try this:

RETURN datetime("2019-3-8T12:10:11");

So, provided your creation_date property values had a supported format, this would work:

:auto
USING PERIODIC COMMIT
LOAD CSV WITH HEADERS FROM 'file:///test.csv' AS row
MERGE (news:newsID {newsID: row.id})
  ON CREATE SET
  news.title = row.title,
  news.creation_date = datetime(row.creation_date),
  news.content = row.content;

Or, if you want to keep your existing CSV file, and assuming its creation_date strings only have a single space character, you can do this:

:auto
USING PERIODIC COMMIT
LOAD CSV WITH HEADERS FROM 'file:///test.csv' AS row
MERGE (news:newsID {newsID: row.id})
  ON CREATE SET
  news.title = row.title,
  news.creation_date = datetime(REPLACE(row.creation_date, ' ', 'T')),
  news.content = row.content;


问:
Aerospike Test Environment
I'm planning on stubbing out a namespace, but what is the current state of deleting a whole namespace? Would I have to list out all the keys that exists, and manually go through and delete them? If so, what API call would that be to list all sets, and then keys?</p>

答: If the size of your test environment is fairly small, your best bet is to store data in ram and restart the service for each run.</p>

Title: Aerospike Test Environment


问:
Difficulty Manipulating QSlider in a QGridLayout
I'm trying to create a dynamic QSlider that accepts a QVector of integer values and maps them underneath the QSlider relative to what position they represent.

Here's a screenshot of what I have now:
My Slider http://dev.kyleswebspace.com/images/QInteractiveSlider.jpg

As you can see, the ticks don't line up with their values. This is one of the issues.

The main issue I'm struggling with though, is that no matter what I change my PADDING value to (see qinteractiveslider.h), the QSlider in my widget remains the same size in relation to the grid of values.

Why isn't my QGridLayout's arguments
providing the correct amount of
padding?

How can I enforce these margins on
the QSlider?

Is there a better way of positioning
these labels? I'm open to
suggestions.

Here is the code:

qinteractiveslider.h

```<code>#ifndef QINTERACTIVESLIDER_H
#define QINTERACTIVESLIDER_H

#include <QtGui/QGridLayout>
#include <QtGui/QLabel>
#include <QtGui/QSlider>
#include <QtGui/QWidget>

class QInteractiveSlider : public QWidget
 {
     Q_OBJECT

public:
    QInteractiveSlider(QVector<int>* values, int min, int max, QWidget *parent = 0, Qt::WFlags flags = 0);
    ~QInteractiveSlider();

private:
    static const int GRID_WIDTH = 10000;
    static const int PADDING = GRID_WIDTH / 3;

    QGridLayout* m_layout;
    QSlider* m_slider;
    QVector<int>* m_values;
};
</code>```

qinteractiveslider.cpp

```<code>#include "qinteractiveslider.h"

QInteractiveSlider::QInteractiveSlider(QVector<int>* values, int min, int max, QWidget *parent, Qt::WFlags flags)
    : QWidget(parent, flags)
{
    m_layout = new QGridLayout();
    m_layout->setSpacing(0);

    m_slider = new QSlider(Qt::Horizontal);
    m_slider->setTickInterval(25);
    m_slider->setTickPosition(QSlider::TicksBelow);

    m_layout->addWidget(m_slider, 0, PADDING, 1, GRID_WIDTH - PADDING, Qt::AlignBottom);

    //populate bottom row with labels
    QVector<int>::Iterator iterator = values->begin();
    while(iterator != values->end()) {
        //place the label at the relative position under the slider
        int columnIndex = ((double)*iterator / (double)max) * (double)GRID_WIDTH;
        QString labelString = QString::number(*iterator);
        QLabel* label = new QLabel(labelString);
        m_layout->addWidget(label, 1, columnIndex, 1, 1, Qt::AlignTop);

        iterator++;
    }

    this->setLayout(m_layout);
}

QInteractiveSlider::~QInteractiveSlider()
{

}
</code>```

main.cpp

```<code>#include "qinteractiveslider.h"
#include <QtGui/QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QVector<int>* testVector = new QVector<int>();
    testVector->append(0);
    testVector->append(50);
    testVector->append(25);
    testVector->append(100);

    QInteractiveSlider* w = new QInteractiveSlider(testVector, 0, 100);
    w->show();

    return a.exec();
}
</code>```

答:
I cannot directly answer the 1st and 2nd questions.
Displaying numbers separately is a bad idea. Since now you have to know where to manually display the numbers. This is not very portable and breaks encapsulation. It also might not scale properly to changing QSlider sizes.
Since QSlider doesn't give an option of displaying numbers under ticks , you should either extend QSlider and rewrite the paint() function or use QWT. http://qwt.sourceforge.net/class_qwt_slider.html</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to create a dynamic QSlider that accepts a QVector of integer values and maps them underneath the QSlider relative to what position they represent.

Here's a screenshot of what I have now:
My Slider http://dev.kyleswebspace.com/images/QInteractiveSlider.jpg

As you can see, the ticks don't line up with their values. This is one of the issues.

The main issue I'm struggling with though, is that no matter what I change my PADDING value to (see qinteractiveslider.h), the QSlider in my widget remains the same size in relation to the grid of values.

Why isn't my QGridLayout's arguments
providing the correct amount of
padding?

How can I enforce these margins on
the QSlider?

Is there a better way of positioning
these labels? I'm open to
suggestions.

Here is the code:

qinteractiveslider.h

#ifndef QINTERACTIVESLIDER_H
#define QINTERACTIVESLIDER_H

#include <QtGui/QGridLayout>
#include <QtGui/QLabel>
#include <QtGui/QSlider>
#include <QtGui/QWidget>

class QInteractiveSlider : public QWidget
 {
     Q_OBJECT

public:
    QInteractiveSlider(QVector<int>* values, int min, int max, QWidget *parent = 0, Qt::WFlags flags = 0);
    ~QInteractiveSlider();

private:
    static const int GRID_WIDTH = 10000;
    static const int PADDING = GRID_WIDTH / 3;

    QGridLayout* m_layout;
    QSlider* m_slider;
    QVector<int>* m_values;
};

qinteractiveslider.cpp

#include "qinteractiveslider.h"

QInteractiveSlider::QInteractiveSlider(QVector<int>* values, int min, int max, QWidget *parent, Qt::WFlags flags)
    : QWidget(parent, flags)
{
    m_layout = new QGridLayout();
    m_layout->setSpacing(0);

    m_slider = new QSlider(Qt::Horizontal);
    m_slider->setTickInterval(25);
    m_slider->setTickPosition(QSlider::TicksBelow);

    m_layout->addWidget(m_slider, 0, PADDING, 1, GRID_WIDTH - PADDING, Qt::AlignBottom);

    //populate bottom row with labels
    QVector<int>::Iterator iterator = values->begin();
    while(iterator != values->end()) {
        //place the label at the relative position under the slider
        int columnIndex = ((double)*iterator / (double)max) * (double)GRID_WIDTH;
        QString labelString = QString::number(*iterator);
        QLabel* label = new QLabel(labelString);
        m_layout->addWidget(label, 1, columnIndex, 1, 1, Qt::AlignTop);

        iterator++;
    }

    this->setLayout(m_layout);
}

QInteractiveSlider::~QInteractiveSlider()
{

}

main.cpp

#include "qinteractiveslider.h"
#include <QtGui/QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QVector<int>* testVector = new QVector<int>();
    testVector->append(0);
    testVector->append(50);
    testVector->append(25);
    testVector->append(100);

    QInteractiveSlider* w = new QInteractiveSlider(testVector, 0, 100);
    w->show();

    return a.exec();
}


问:
Hosting Multiple Asp.net Core projects under one domain
My solution has different shared projects(Class Library) and 3 Asp.net Core Web Applications. I have published and hosted one of the project and its working fine with  https://example.com/home/Index.
How can i host other 2 projects , in  such a way that i can access them by https://example.com/WebApp2/home/Index and https://example.com/WebApp2/home/Index. I tried configuring them as virtual directories but getting HTTP Error 404.0 - Not Found.</p>

答:
You can create different applications under your web site in IIS and then deploy different ASP.NET core projects to the different applications.

More information about how to create application you can refer to this link:
application


问:
How to set the opacity of a tileset in spritekit tilemap?
I have a code to define the PhysicsBody for everysingle tiles in tilemap like below:

```<code>func setUpSceneWithMap(map: SKTileMapNode) {

        let tileMap = map
        tileMap.setScale(0.4)

        let startingLocation: CGPoint = tileMap.position
        let tileSize = tileMap.tileSize

        let halfWidth = CGFloat(tileMap.numberOfColumns) / 2.0 * tileSize.width * 0.4
        let halfHeight = CGFloat(tileMap.numberOfRows) / 2.0 * tileSize.height * 0.4

        for col in 0..<tileMap.numberOfColumns {

            for row in 0..<tileMap.numberOfRows {

                if  tileMap.tileDefinition(atColumn: col, row: row) != nil {

                    // defining different types of tile
                    let tileDefinition = tileMap.tileDefinition(atColumn: col, row: row)
                    ...
                    let isTrapTile = tileDefinition?.userData?["isTraps"] as? Bool

                    let x = CGFloat(col) * (tileSize.width) * 0.4 - halfWidth
                    let y = CGFloat(row) * (tileSize.height) * 0.4 - halfHeight

                    let rect = CGRect(x: 0, y: 0, width: tileSize.width * 0.4 , height: tileSize.height * 0.4)
                    let tileNode = SKShapeNode(rect: rect)

                    tileNode.position = CGPoint(x: x + startingLocation.x, y: y + startingLocation.y)
                    tileNode.zPosition = 1
                    tileNode.physicsBody = SKPhysicsBody(edgeLoopFrom: rect)

                    // Create the 4 checkpoint-tiles at the center of the maze
                    ...
                    // Create the wall tile
                    ...
                    // Create the trap tile
                    if (isTrapTile ?? false) {
                        tileNode.physicsBody?.categoryBitMask = gamePhysics.Trap
                        tileNode.physicsBody?.collisionBitMask = 0
                        tileNode.physicsBody?.contactTestBitMask = gamePhysics.Player
                        tileNode.physicsBody?.isDynamic = false
                    }

                    self.addChild(tileNode)

                }
            }
        }
    }
</code>```

There are 3 different tile sets in my tilemap: Wall, CheckPoint and Trap. With the code above, i have assigned a Spritenode with physicsbody to all of them. Now, i want my Trap tile to be invisible so the Player cannot see it. What is the most efficient way to achieve it?

答:
You would use myNode.alpha = CGFloat;. This only affects nodes that inherit from SKNode.

According to the Apple Documentation on myNode.alpha value:

The default value is 1.0.

The SKNode class does not perform drawing, but many of its subclasses do. When a node or any of its descendants are drawn, the alpha component of each pixel is multiplied by the node’s alpha property and then clamped to the range 0.0-1.0. This modified alpha value is used to blend the pixel into the framebuffer

Basically, the alpha value affects how the sprite is rendered in the frame drawing.

In your case, you would set myTrapTileNode.alpha = 0.0; because you want it to be completely transparent.

Body:
I have a code to define the PhysicsBody for everysingle tiles in tilemap like below:

func setUpSceneWithMap(map: SKTileMapNode) {

        let tileMap = map
        tileMap.setScale(0.4)

        let startingLocation: CGPoint = tileMap.position
        let tileSize = tileMap.tileSize

        let halfWidth = CGFloat(tileMap.numberOfColumns) / 2.0 * tileSize.width * 0.4
        let halfHeight = CGFloat(tileMap.numberOfRows) / 2.0 * tileSize.height * 0.4

        for col in 0..<tileMap.numberOfColumns {

            for row in 0..<tileMap.numberOfRows {

                if  tileMap.tileDefinition(atColumn: col, row: row) != nil {

                    // defining different types of tile
                    let tileDefinition = tileMap.tileDefinition(atColumn: col, row: row)
                    ...
                    let isTrapTile = tileDefinition?.userData?["isTraps"] as? Bool

                    let x = CGFloat(col) * (tileSize.width) * 0.4 - halfWidth
                    let y = CGFloat(row) * (tileSize.height) * 0.4 - halfHeight

                    let rect = CGRect(x: 0, y: 0, width: tileSize.width * 0.4 , height: tileSize.height * 0.4)
                    let tileNode = SKShapeNode(rect: rect)

                    tileNode.position = CGPoint(x: x + startingLocation.x, y: y + startingLocation.y)
                    tileNode.zPosition = 1
                    tileNode.physicsBody = SKPhysicsBody(edgeLoopFrom: rect)

                    // Create the 4 checkpoint-tiles at the center of the maze
                    ...
                    // Create the wall tile
                    ...
                    // Create the trap tile
                    if (isTrapTile ?? false) {
                        tileNode.physicsBody?.categoryBitMask = gamePhysics.Trap
                        tileNode.physicsBody?.collisionBitMask = 0
                        tileNode.physicsBody?.contactTestBitMask = gamePhysics.Player
                        tileNode.physicsBody?.isDynamic = false
                    }

                    self.addChild(tileNode)

                }
            }
        }
    }

There are 3 different tile sets in my tilemap: Wall, CheckPoint and Trap. With the code above, i have assigned a Spritenode with physicsbody to all of them. Now, i want my Trap tile to be invisible so the Player cannot see it. What is the most efficient way to achieve it?


问:
Node server not reachable from outside
I am playing with a small node server application.I have hosted it in AWS Lightsail's ubuntu instance. It is reachable from local browser like http://localhost:4201/

but when I try to access it from remote, it is unreachable.

In aws instance's network config I have opened traffic for all ports

I have cleared all rules from iptables as well. I am able to reach http port 80 and ping successfully. But no luck with node server, what am I missing? Is there a special way to enable traffic to node server?

答:
I debugged it, basically in server.ts

I had bound it to localhost so it won't accept request from outside

```<code>app.listen(4201, '127.0.0.1', function () {
    console.log('Server Listening on 0.0.0.0:4201');
});
</code>```

changed it to 0.0.0.0

```<code>app.listen(4201, '0.0.0.0', function () {
    console.log('Server Listening on 0.0.0.0:4201');
});
</code>```

And now it is accessible from everywhere.

Title: Node server not reachable from outside

Body:
I debugged it, basically in server.ts

I had bound it to localhost so it won't accept request from outside

app.listen(4201, '127.0.0.1', function () {
    console.log('Server Listening on 0.0.0.0:4201');
});

changed it to 0.0.0.0

app.listen(4201, '0.0.0.0', function () {
    console.log('Server Listening on 0.0.0.0:4201');
});

And now it is accessible from everywhere.


问:
How do I change currency symbol on django-oscar dashboard?
As the title explains, I want to change the default currency on Django-oscar dashboard. It's showing it as £ and I need R which is South Africa. I have changed my settings.py to South African timezone(johannesburg) and I have added the i18n path. I read that the frontend will check the users local language to set the currency but I know my browser is all set to South African locale.

in settings.py I have also added the following which I could be doing wrong:

```<code>OSCAR_CURRENCY_LOCALE = 'ZAR'

OSCAR_CURRENCY_FORMAT = {
    'ZAR': {
        'format': u'R #,##',
    }
}
</code>```

I'm not sure if this is the correct way to do it or not but the frontend still shows me £ every time.

Django-oscar 2.0.4, Python 3.7.4, Django 2.2.12

答:
I read that the frontend will check the users local language to set the currency.

No, it won't do that. Currency is completely separate from language, and has to be set explicitly by you in code. If you are operating a site only in ZAR you just need to set OSCAR_DEFAULT_CURRENCY:

```<code>OSCAR_DEFAULT_CURRENCY = 'ZAR'
</code>```

Which will then be used with the custom format you've specified. You will also need to make sure that your stock record prices are using ZAR.

Body:
As the title explains, I want to change the default currency on Django-oscar dashboard. It's showing it as £ and I need R which is South Africa. I have changed my settings.py to South African timezone(johannesburg) and I have added the i18n path. I read that the frontend will check the users local language to set the currency but I know my browser is all set to South African locale.

in settings.py I have also added the following which I could be doing wrong:

OSCAR_CURRENCY_LOCALE = 'ZAR'

OSCAR_CURRENCY_FORMAT = {
    'ZAR': {
        'format': u'R #,##',
    }
}

I'm not sure if this is the correct way to do it or not but the frontend still shows me £ every time.

Django-oscar 2.0.4, Python 3.7.4, Django 2.2.12

Body:
I read that the frontend will check the users local language to set the currency.

No, it won't do that. Currency is completely separate from language, and has to be set explicitly by you in code. If you are operating a site only in ZAR you just need to set OSCAR_DEFAULT_CURRENCY:

OSCAR_DEFAULT_CURRENCY = 'ZAR'

Which will then be used with the custom format you've specified. You will also need to make sure that your stock record prices are using ZAR.


问:
make query to display greatest data in access
I have a table in access:

```<code> id | holiday
-----|----------
2020 | 40
2020 | 39
4644 | 23
4644 | 22
</code>```

I want my query  to display the greatest value for holiday

something like this:

```<code>  id | holiday
-----|----------
2020 | 40
4644 | 23
</code>```

any ideas would be highly appreciated. Perhaps using sql in acccess?

答:
That's a basic aggregation query:</p>

```<code>select id, max(holiday) max_holiday
from mytable
group by id
</code>```

Body:
I have a table in access:

 id | holiday
-----|----------
2020 | 40
2020 | 39
4644 | 23
4644 | 22

I want my query  to display the greatest value for holiday

something like this:

  id | holiday
-----|----------
2020 | 40
4644 | 23

any ideas would be highly appreciated. Perhaps using sql in acccess?

Body:
That's a basic aggregation query:

select id, max(holiday) max_holiday
from mytable
group by id


问:
Why is not operator giving different result but using = giving correct answer
```<code> static int count = 0;

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    count = 0;
    int n = sc.nextInt();
    int arr[][] = new int[n][n];
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
        arr[i][j] = sc.nextInt();
      }
    }
    for (int i = 0; i < n ; i++) {
      row(arr, n, i);
      column(arr, n, i);
    }
    System.out.println(count);
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
        System.out.print(arr[i][j] + " ");
      }
    }
  }

  static void row(int arr[][], int n, int row) {
    int x, y, min, yHold = 0;

    for (x = 0; x < n; x++) {
      boolean yes = false;
      min = arr[row][x];

      for (y = row; y < n; y++) {
        if (arr[y][x] < min) {
          min = arr[y][x];
          yHold = y;
          yes = true;
        }
      }
      if (yes) {
        int temp = arr[row][x];
        arr[row][x] = min;
        arr[yHold][x] = temp;
        count++;
      }
    }
</code>```

If I replace yes=true with yes=!yes, the output becomes different. Please help, can't seem to figure it out.
The part of the problem the function row is taking are of is:

If we are at ith row, then we have to work with each column at a time
  from 0 to n−1 of this row. For any jth column, swap A[i][j] with the
  minimum of all the elements which are present in a column with index j
  and rows from indices i to n−1.

答: The problem is that the statement can be executed multiple times. In the case of yes = true, the result will always be that yes becomes true. But with yes = !yes, the result is that yes will flip flop between true and false.

Body:
 static int count = 0;

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    count = 0;
    int n = sc.nextInt();
    int arr[][] = new int[n][n];
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
        arr[i][j] = sc.nextInt();
      }
    }
    for (int i = 0; i < n ; i++) {
      row(arr, n, i);
      column(arr, n, i);
    }
    System.out.println(count);
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
        System.out.print(arr[i][j] + " ");
      }
    }
  }

  static void row(int arr[][], int n, int row) {
    int x, y, min, yHold = 0;

    for (x = 0; x < n; x++) {
      boolean yes = false;
      min = arr[row][x];

      for (y = row; y < n; y++) {
        if (arr[y][x] < min) {
          min = arr[y][x];
          yHold = y;
          yes = true;
        }
      }
      if (yes) {
        int temp = arr[row][x];
        arr[row][x] = min;
        arr[yHold][x] = temp;
        count++;
      }
    }

If I replace yes=true with yes=!yes, the output becomes different. Please help, can't seem to figure it out.
The part of the problem the function row is taking are of is:

If we are at ith row, then we have to work with each column at a time
  from 0 to n−1 of this row. For any jth column, swap A[i][j] with the
  minimum of all the elements which are present in a column with index j
  and rows from indices i to n−1.


问:
Sending PUT data using Fetch API in React.js
My GET routes are working fine, but seems to not be able to get my data to my PUT route.  This first file, the method called "saveOverTemplate", is supposed to take the content of my component, and send it to my PUT route to be updated in my database. If I console.log the data in the "saveOverTemplate" method, it is exactly as expected.  And, when I click the button, the first console.log shows that I did indeed reach the method. However when I try to log the data, it just shows as "undefined".  Can anyone see what I'm missing in how I'm sending the data over?

```<code>//My React Component

import React, { Component } from 'react';
import { Editor } from '@tinymce/tinymce-react';

let policyContent = '';

class TinyEditor extends Component {
    constructor(props) {
        super(props);

        this.state = { content: '' };

        this.handleEditorChange = this.handleEditorChange.bind(this);
        this.handleClick = this.handleClick.bind(this);
        this.saveOverTemplate = this.saveOverTemplate.bind(this);

    }

    componentDidMount() {
        console.log(`Component did mount`);
        fetch(`/api/policy`)
            .then(res => res.json())
            .then((result) => {
                console.log(result);
                policyContent = result;
                this.setState({ content: policyContent[0].contents });
            });
    }

    handleEditorChange(content, editor) {
        this.setState({ content });
    }

    handleClick(e) {
        e.preventDefault();
        console.log(`Button was clicked.`);
        console.log(this.state.content);
        this.setVariables('Company}}', 'Variable');
    }

    setVariables(search, replaceWith){
        const result = this.state.content.split(search).join(replaceWith);
        this.setState({content: result});
    }

    saveOverTemplate(e) {
        e.preventDefault();
        let data = this.state.content
        console.log(data);
        fetch(`/api/policy/update`, {
            method: 'PUT',
            body: JSON.stringify({content: this.state.content})
        })
        .then(res => res.json())
        .then(data => console.log(data))
        .catch(err => console.log(err));
    }

    render() {
        return (
            <div>
                <div className="container">
                    <Editor
                        apiKey='yf9eajz93s3akrlb24b8ja9xcszddbxx22x4ug8c2q5boxw3'
                        className="mceEditor"
                        id='myTextArea'
                        init={{
                            height: 500,
                            editor_selector: 'mceEditor',
                            menubar: false,
                            browser_spellcheck: true,
                            contextmenu: true,
                            branding: false,
                            plugins: [
                                'advlist autolink lists link image charmap print preview anchor',
                                'searchreplace visualblocks code fullscreen',
                                'insertdatetime media table paste code help wordcount'
                            ],
                            toolbar:
                                'undo redo | formatselect | bold italic backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | help'
                        }}
                        onEditorChange={this.handleEditorChange}
                        value={this.state.content}
                    />
                    <button onClick={this.handleClick}>Save</button>
                    <button onClick={this.saveOverTemplate}>Save Over Template</button>
                    <div dangerouslySetInnerHTML={{__html: this.state.content}}></div>
                </div>
            </div>
        )
    }
}

export default TinyEditor;
</code>```

Then this is the file that has my routes, where I can't seem to bring in the data correctly in my PUT method.  Please help!

```<code>const express = require('express');
const bodyParser = require ('body-parser');
const mysql = require('mysql2');

const connection = mysql.createPool({
    host        : 'localhost',
    user        : 'root',
    password    : '',
    database    : 'book'
});

const app = express();
app.use(bodyParser.urlencoded({ extended: false}));

// Creating a GET route that returns data from the 'users' table.
app.get('/api/policy/all', function (req, res) {
    // Connecting to the database.
    connection.getConnection(function (err, connection) {

        // Executing the MySQL query (select all data from the 'handbook' table).
        connection.query("SELECT * FROM handbook", function (error, results, fields) {
            // If some error occurs, we throw an error.
            if (error) throw error;

            // Getting the 'response' from the database and sending it to our route. This is were the data is.
            res.json(results);
        });
    });
});

app.get('/api/policy', function (req, res) {
    // Connecting to the database.
    connection.getConnection(function (err, connection) {

        // Executing the MySQL query (select all data from the 'handbook' table).
        connection.query("SELECT contents FROM handbook WHERE policy = 'Benefits' ", function (error, results, fields) {
            // If some error occurs, we throw an error.
            if (error) throw error;

            // Getting the 'response' from the database and sending it to our route. This is were the data is.
            res.json(results);
        });
    });
});

app.put('/api/policy/update', function(req, res) {
    console.log('It is getting to the route');
    const data = req.body.content;
    console.log(data);
    // connection.getConnection(function(err, connection) {
    //     connection.query("UPDATE handbook SET contents= WHERE policy = 'Benfits'", function(error, results, fields){
    //         if(error) throw error;
    //         res.json(results);
    //         console.log(`Has been put`);
    //     });
    // });
});

// Starting our server.
app.listen(3001, () => {
    console.log('Go to http://localhost:3001/policy so you can see the data.');
});

</code>```

答:
Don't forget to include headers when using fetch:

```<code>saveOverTemplate(e) {
        e.preventDefault();
        let content = this.state.content
        console.log(content);
        fetch(`/api/policy/update`, {
            method: 'PUT',
            body: JSON.stringify({content}),
            headers: {"Content-Type": "application/json"}
        })
        .then(res => res.json())
        .then(data => console.log(data))
        .catch(err => console.log(err));
    }
</code>```

Documentation:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Body:
My GET routes are working fine, but seems to not be able to get my data to my PUT route.  This first file, the method called "saveOverTemplate", is supposed to take the content of my component, and send it to my PUT route to be updated in my database. If I console.log the data in the "saveOverTemplate" method, it is exactly as expected.  And, when I click the button, the first console.log shows that I did indeed reach the method. However when I try to log the data, it just shows as "undefined".  Can anyone see what I'm missing in how I'm sending the data over?

//My React Component

import React, { Component } from 'react';
import { Editor } from '@tinymce/tinymce-react';

let policyContent = '';

class TinyEditor extends Component {
    constructor(props) {
        super(props);

        this.state = { content: '' };

        this.handleEditorChange = this.handleEditorChange.bind(this);
        this.handleClick = this.handleClick.bind(this);
        this.saveOverTemplate = this.saveOverTemplate.bind(this);

    }

    componentDidMount() {
        console.log(`Component did mount`);
        fetch(`/api/policy`)
            .then(res => res.json())
            .then((result) => {
                console.log(result);
                policyContent = result;
                this.setState({ content: policyContent[0].contents });
            });
    }

    handleEditorChange(content, editor) {
        this.setState({ content });
    }

    handleClick(e) {
        e.preventDefault();
        console.log(`Button was clicked.`);
        console.log(this.state.content);
        this.setVariables('Company}}', 'Variable');
    }

    setVariables(search, replaceWith){
        const result = this.state.content.split(search).join(replaceWith);
        this.setState({content: result});
    }

    saveOverTemplate(e) {
        e.preventDefault();
        let data = this.state.content
        console.log(data);
        fetch(`/api/policy/update`, {
            method: 'PUT',
            body: JSON.stringify({content: this.state.content})
        })
        .then(res => res.json())
        .then(data => console.log(data))
        .catch(err => console.log(err));
    }

    render() {
        return (

                    <Editor
                        apiKey='yf9eajz93s3akrlb24b8ja9xcszddbxx22x4ug8c2q5boxw3'
                        className="mceEditor"
                        id='myTextArea'
                        init={{
                            height: 500,
                            editor_selector: 'mceEditor',
                            menubar: false,
                            browser_spellcheck: true,
                            contextmenu: true,
                            branding: false,
                            plugins: [
                                'advlist autolink lists link image charmap print preview anchor',
                                'searchreplace visualblocks code fullscreen',
                                'insertdatetime media table paste code help wordcount'
                            ],
                            toolbar:
                                'undo redo | formatselect | bold italic backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | help'
                        }}
                        onEditorChange={this.handleEditorChange}
                        value={this.state.content}
                    />
                    <button onClick={this.handleClick}>Save</button>
                    <button onClick={this.saveOverTemplate}>Save Over Template</button>

        )
    }
}

export default TinyEditor;

Then this is the file that has my routes, where I can't seem to bring in the data correctly in my PUT method.  Please help!

const express = require('express');
const bodyParser = require ('body-parser');
const mysql = require('mysql2');

const connection = mysql.createPool({
    host        : 'localhost',
    user        : 'root',
    password    : '',
    database    : 'book'
});

const app = express();
app.use(bodyParser.urlencoded({ extended: false}));

// Creating a GET route that returns data from the 'users' table.
app.get('/api/policy/all', function (req, res) {
    // Connecting to the database.
    connection.getConnection(function (err, connection) {

        // Executing the MySQL query (select all data from the 'handbook' table).
        connection.query("SELECT * FROM handbook", function (error, results, fields) {
            // If some error occurs, we throw an error.
            if (error) throw error;

            // Getting the 'response' from the database and sending it to our route. This is were the data is.
            res.json(results);
        });
    });
});

app.get('/api/policy', function (req, res) {
    // Connecting to the database.
    connection.getConnection(function (err, connection) {

        // Executing the MySQL query (select all data from the 'handbook' table).
        connection.query("SELECT contents FROM handbook WHERE policy = 'Benefits' ", function (error, results, fields) {
            // If some error occurs, we throw an error.
            if (error) throw error;

            // Getting the 'response' from the database and sending it to our route. This is were the data is.
            res.json(results);
        });
    });
});

app.put('/api/policy/update', function(req, res) {
    console.log('It is getting to the route');
    const data = req.body.content;
    console.log(data);
    // connection.getConnection(function(err, connection) {
    //     connection.query("UPDATE handbook SET contents= WHERE policy = 'Benfits'", function(error, results, fields){
    //         if(error) throw error;
    //         res.json(results);
    //         console.log(`Has been put`);
    //     });
    // });
});

// Starting our server.
app.listen(3001, () => {
    console.log('Go to http://localhost:3001/policy so you can see the data.');
});

Body:
Don't forget to include headers when using fetch:

saveOverTemplate(e) {
        e.preventDefault();
        let content = this.state.content
        console.log(content);
        fetch(`/api/policy/update`, {
            method: 'PUT',
            body: JSON.stringify({content}),
            headers: {"Content-Type": "application/json"}
        })
        .then(res => res.json())
        .then(data => console.log(data))
        .catch(err => console.log(err));
    }

Documentation:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch


问:
How to use absolute path for templateUrl and styleUrls? - Angular 6
I have an angular application which contains multiple components. Recently one of the requirements of the application changed, which meant I had to convert all existing relative Urls to absolute.

So far everything went smoothly as planned, until I came across the templateUrl and styleUrls in the components. One example of the components is shown below with it's absolute path. Unfortunately when I try to input the absolute path instead of the relative for both these properties it gives me an error (also attached). I tried looking onto various issues on github as well as a few examples on stackoverflow and stackexchange, but I can't get them to work for me

src/app/views/login/login.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { OauthService } from 'src/app/services/oauth/oauth.service';
import { LoggerService } from 'src/app/services/logger/logger.service';
import { ToastrService } from 'ngx-toastr';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
/*
methods and properties etc etc
.
.
.
*/
</code>```

Here is the heirarchy of my application for reference:

The tsconfig.json for this application (contains the baseUrl):

```<code>{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  }
}
</code>```

The error I receive when I try to run the application on my browser while using absolute path for these two properties:

答:
This is a year old question, but I just manage to make it work with just '/'.

e.g.: templateUrl: '/src/app/common/templates/enquiry-page/enquiry-page.html',

I'm running on Angular 8.

Body:
I have an angular application which contains multiple components. Recently one of the requirements of the application changed, which meant I had to convert all existing relative Urls to absolute.

So far everything went smoothly as planned, until I came across the templateUrl and styleUrls in the components. One example of the components is shown below with it's absolute path. Unfortunately when I try to input the absolute path instead of the relative for both these properties it gives me an error (also attached). I tried looking onto various issues on github as well as a few examples on stackoverflow and stackexchange, but I can't get them to work for me

src/app/views/login/login.component.ts

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { OauthService } from 'src/app/services/oauth/oauth.service';
import { LoggerService } from 'src/app/services/logger/logger.service';
import { ToastrService } from 'ngx-toastr';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
/*
methods and properties etc etc
.
.
.
*/

Here is the heirarchy of my application for reference:

The tsconfig.json for this application (contains the baseUrl):

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  }
}

The error I receive when I try to run the application on my browser while using absolute path for these two properties: