问:
Keras ValueError: Dimensions must be equal issue
Even after applying the suggestions in answer and comments, it looks like the dimension mismatch issue persists. This is exact code and data file to replicate as well: https://drive.google.com/drive/folders/1q67s0VhB-O7J8OtIhU2jmj7Kc4LxL3sf?usp=sharing

How can this be corrected!? Latest code, model summary, functions used and error I get is below

```<code>type_ae=='dcor'
#Wrappers for keras
def custom_loss1(y_true,y_pred):
    dcor = -1*distance_correlation(y_true,encoded_layer)
    return dcor

def custom_loss2(y_true,y_pred):
    recon_loss = losses.categorical_crossentropy(y_true, y_pred)
    return recon_loss

input_layer =  Input(shape=(64,64,1))

encoded_layer = Conv2D(filters = 128, kernel_size = (5,5),padding = 'same',activation ='relu',
                       input_shape = (64,64,1))(input_layer)
encoded_layer = MaxPool2D(pool_size=(2,2))(encoded_layer)
encoded_layer = Dropout(0.25)(encoded_layer)
encoded_layer = (Conv2D(filters = 64, kernel_size = (3,3),padding = 'same',activation ='relu'))(encoded_layer)
encoded_layer = (MaxPool2D(pool_size=(2,2)))(encoded_layer)
encoded_layer = (Dropout(0.25))(encoded_layer)

encoded_layer = (Conv2D(filters = 64, kernel_size = (3,3),padding = 'same',activation ='relu'))(encoded_layer)
encoded_layer = (MaxPool2D(pool_size=(2,2)))(encoded_layer)
encoded_layer = (Dropout(0.25))(encoded_layer)
encoded_layer = Conv2D(filters = 1, kernel_size = (3,3),padding = 'same',activation ='relu',
                       input_shape = (64,64,1),strides=1)(encoded_layer)
encoded_layer = ZeroPadding2D(padding=(28, 28), data_format=None)(encoded_layer)

decoded_imag = Conv2D(8, (2, 2), activation='relu', padding='same')(encoded_layer)
decoded_imag = UpSampling2D((2, 2))(decoded_imag)
decoded_imag = Conv2D(8, (3, 3), activation='relu', padding='same')(decoded_imag)
decoded_imag = UpSampling2D((2, 2))(decoded_imag)
decoded_imag = Conv2D(16, (3, 3), activation='relu', padding='same')(decoded_imag)
decoded_imag = UpSampling2D((2, 2))(decoded_imag)
decoded_imag = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(decoded_imag)
flat_layer = Flatten()(decoded_imag)
dense_layer = Dense(256,activation = "relu")(flat_layer)
dense_layer = Dense(64,activation = "relu")(dense_layer)
dense_layer = Dense(32,activation = "relu")(dense_layer)
output_layer = Dense(9, activation = "softmax")(dense_layer)
autoencoder = Model(input_layer, [encoded_layer,output_layer])
autoencoder.summary()
autoencoder.compile(optimizer='adadelta', loss=[custom_loss1,custom_loss2])
autoencoder.fit(x_train,[x_train, y_train],batch_size=32,epochs=3,shuffle=True,
                validation_data=(x_val, [x_val,y_val]))
</code>```

The data is of dimensions:

```<code>x_train.shape:  (4000, 64, 64, 1)
x_val.shape:  (1000, 64, 64, 1)
y_train.shape:  (4000, 9)
y_val.shape:  (1000, 9)
</code>```

losses look like:

```<code>def custom_loss1(y_true,y_pred):
    dcor = -1*distance_correlation(y_true,encoded_layer)
    return dcor

def custom_loss2(y_true,y_pred):
    recon_loss = losses.categorical_crossentropy(y_true, y_pred)
    return recon_loss
</code>```

The correlation function is based on tensors as follows:

```<code>def distance_correlation(y_true,y_pred):
    pred_r = tf.reduce_sum(y_pred*y_pred,1)
    pred_r = tf.reshape(pred_r,[-1,1])
    pred_d = pred_r - 2*tf.matmul(y_pred,tf.transpose(y_pred))+tf.transpose(pred_r)
    true_r = tf.reduce_sum(y_true*y_true,1)
    true_r = tf.reshape(true_r,[-1,1])
    true_d = true_r - 2*tf.matmul(y_true,tf.transpose(y_true))+tf.transpose(true_r)
    concord = 1-tf.matmul(y_true,tf.transpose(y_true))
    #print(pred_d)
    #print(tf.reshape(tf.reduce_mean(pred_d,1),[-1,1]))
    #print(tf.reshape(tf.reduce_mean(pred_d,0),[1,-1]))
    #print(tf.reduce_mean(pred_d))
    tf.check_numerics(pred_d,'pred_d has NaN')
    tf.check_numerics(true_d,'true_d has NaN')
    A = pred_d - tf.reshape(tf.reduce_mean(pred_d,1),[-1,1]) - tf.reshape(tf.reduce_mean(pred_d,0),[1,-1]) + tf.reduce_mean(pred_d)
    B = true_d - tf.reshape(tf.reduce_mean(true_d,1),[-1,1]) - tf.reshape(tf.reduce_mean(true_d,0),[1,-1]) + tf.reduce_mean(true_d)
    #dcor = -tf.reduce_sum(concord*pred_d)/tf.reduce_sum((1-concord)*pred_d)
    dcor = -tf.log(tf.reduce_mean(A*B))+tf.log(tf.sqrt(tf.reduce_mean(A*A)*tf.reduce_mean(B*B)))#-tf.reduce_sum(concord*pred_d)/tf.reduce_sum((1-concord)*pred_d)
    #print(dcor.shape)
    #tf.Print(dcor,[dcor])
    #dcor = tf.tile([dcor],batch_size)
    return (dcor)
</code>```

model summary looks like:

```<code>_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input_5 (InputLayer)         (None, 64, 64, 1)         0
_________________________________________________________________
conv2d_30 (Conv2D)           (None, 64, 64, 128)       3328
_________________________________________________________________
max_pooling2d_13 (MaxPooling (None, 32, 32, 128)       0
_________________________________________________________________
dropout_13 (Dropout)         (None, 32, 32, 128)       0
_________________________________________________________________
conv2d_31 (Conv2D)           (None, 32, 32, 64)        73792
_________________________________________________________________
max_pooling2d_14 (MaxPooling (None, 16, 16, 64)        0
_________________________________________________________________
dropout_14 (Dropout)         (None, 16, 16, 64)        0
_________________________________________________________________
conv2d_32 (Conv2D)           (None, 16, 16, 64)        36928
_________________________________________________________________
max_pooling2d_15 (MaxPooling (None, 8, 8, 64)          0
_________________________________________________________________
dropout_15 (Dropout)         (None, 8, 8, 64)          0
_________________________________________________________________
conv2d_33 (Conv2D)           (None, 8, 8, 1)           577
_________________________________________________________________
zero_padding2d_5 (ZeroPaddin (None, 64, 64, 1)         0
_________________________________________________________________
conv2d_34 (Conv2D)           (None, 64, 64, 8)         40
_________________________________________________________________
up_sampling2d_10 (UpSampling (None, 128, 128, 8)       0
_________________________________________________________________
conv2d_35 (Conv2D)           (None, 128, 128, 8)       584
_________________________________________________________________
up_sampling2d_11 (UpSampling (None, 256, 256, 8)       0
_________________________________________________________________
conv2d_36 (Conv2D)           (None, 256, 256, 16)      1168
_________________________________________________________________
up_sampling2d_12 (UpSampling (None, 512, 512, 16)      0
_________________________________________________________________
conv2d_37 (Conv2D)           (None, 512, 512, 1)       145
_________________________________________________________________
flatten_4 (Flatten)          (None, 262144)            0
_________________________________________________________________
dense_13 (Dense)             (None, 256)               67109120
_________________________________________________________________
dense_14 (Dense)             (None, 64)                16448
_________________________________________________________________
dense_15 (Dense)             (None, 32)                2080
_________________________________________________________________
dense_16 (Dense)             (None, 9)                 297
=================================================================
Total params: 67,244,507
Trainable params: 67,244,507
Non-trainable params: 0
_________________________________________________________________
</code>```

This is the error:

```<code>InvalidArgumentError                      Traceback (most recent call last)
~/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/ops.py in _create_c_op(graph, node_def, inputs, control_inputs)
   1658   try:
-> 1659     c_op = c_api.TF_FinishOperation(op_desc)
   1660   except errors.InvalidArgumentError as e:

InvalidArgumentError: Dimensions must be equal, but are 1 and 64 for 'loss_1/zero_padding2d_5_loss/MatMul' (op: 'BatchMatMul') with input shapes: [?,64,64,1], [1,64,64,?].

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-11-0e924885fc6b> in <module>
     40 autoencoder = Model(input_layer, [encoded_layer,output_layer])
     41 autoencoder.summary()
---> 42 autoencoder.compile(optimizer='adadelta', loss=[custom_loss1,custom_loss2])
     43 autoencoder.fit(x_train,[x_train, y_train],batch_size=32,epochs=3,shuffle=True,
     44                 validation_data=(x_val, [x_val,y_val]))

~/anaconda3/lib/python3.6/site-packages/keras/engine/training.py in compile(self, optimizer, loss, metrics, loss_weights, sample_weight_mode, weighted_metrics, target_tensors, **kwargs)
    340                 with K.name_scope(self.output_names[i] + '_loss'):
    341                     output_loss = weighted_loss(y_true, y_pred,
--> 342                                                 sample_weight, mask)
    343                 if len(self.outputs) > 1:
    344                     self.metrics_tensors.append(output_loss)

~/anaconda3/lib/python3.6/site-packages/keras/engine/training_utils.py in weighted(y_true, y_pred, weights, mask)
    402         """
    403         # score_array has ndim >= 2
--> 404         score_array = fn(y_true, y_pred)
    405         if mask is not None:
    406             # Cast the mask to floatX to avoid float64 upcasting in Theano

<ipython-input-11-0e924885fc6b> in custom_loss1(y_true, y_pred)
      2 #Wrappers for keras
      3 def custom_loss1(y_true,y_pred):
----> 4         dcor = -1*distance_correlation(y_true,encoded_layer)
      5         return dcor
      6

<ipython-input-6-f282528532cc> in distance_correlation(y_true, y_pred)
      2     pred_r = tf.reduce_sum(y_pred*y_pred,1)
      3     pred_r = tf.reshape(pred_r,[-1,1])
----> 4     pred_d = pred_r - 2*tf.matmul(y_pred,tf.transpose(y_pred))+tf.transpose(pred_r)
      5     true_r = tf.reduce_sum(y_true*y_true,1)
      6     true_r = tf.reshape(true_r,[-1,1])

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/ops/math_ops.py in matmul(a, b, transpose_a, transpose_b, adjoint_a, adjoint_b, a_is_sparse, b_is_sparse, name)
   2415         adjoint_b = True
   2416       return gen_math_ops.batch_mat_mul(
-> 2417           a, b, adj_x=adjoint_a, adj_y=adjoint_b, name=name)
   2418
   2419     # Neither matmul nor sparse_matmul support adjoint, so we conjugate

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/ops/gen_math_ops.py in batch_mat_mul(x, y, adj_x, adj_y, name)
   1421   adj_y = _execute.make_bool(adj_y, "adj_y")
   1422   _, _, _op = _op_def_lib._apply_op_helper(
-> 1423         "BatchMatMul", x=x, y=y, adj_x=adj_x, adj_y=adj_y, name=name)
   1424   _result = _op.outputs[:]
   1425   _inputs_flat = _op.inputs

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py in _apply_op_helper(self, op_type_name, name, **keywords)
    786         op = g.create_op(op_type_name, inputs, output_types, name=scope,
    787                          input_types=input_types, attrs=attr_protos,
--> 788                          op_def=op_def)
    789       return output_structure, op_def.is_stateful, op
    790

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py in new_func(*args, **kwargs)
    505                 'in a future version' if date is None else ('after %s' % date),
    506                 instructions)
--> 507       return func(*args, **kwargs)
    508
    509     doc = _add_deprecated_arg_notice_to_docstring(

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/ops.py in create_op(***failed resolving arguments***)
   3298           input_types=input_types,
   3299           original_op=self._default_original_op,
-> 3300           op_def=op_def)
   3301       self._create_op_helper(ret, compute_device=compute_device)
   3302     return ret

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/ops.py in __init__(self, node_def, g, inputs, output_types, control_inputs, input_types, original_op, op_def)
   1821           op_def, inputs, node_def.attr)
   1822       self._c_op = _create_c_op(self._graph, node_def, grouped_inputs,
-> 1823                                 control_input_ops)
   1824
   1825     # Initialize self._outputs.

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/ops.py in _create_c_op(graph, node_def, inputs, control_inputs)
   1660   except errors.InvalidArgumentError as e:
   1661     # Convert to ValueError for backwards compatibility.
-> 1662     raise ValueError(str(e))
   1663
   1664   return c_op

ValueError: Dimensions must be equal, but are 1 and 64 for 'loss_1/zero_padding2d_5_loss/MatMul' (op: 'BatchMatMul') with input shapes: [?,64,64,1], [1,64,64,?].
</code>```

答:
The intention is to use the original image in custom_loss1 and the scalar label values in custom_loss2. I think the working code by @mujjiga in his answer is almost correct. I suggest one slight modification.

In model.compile() pass the input tensor in the loss which needs it. Keep the other one same. model.fit() just passes the labels.

```<code>model.compile(optimizer='adadelta', loss=[custom_loss1(input_layer), custom_loss2])
mode.fit(x_train, y_train)
</code>```

Inside the custom loss functions:

```<code>def custom_loss1(input):
    def loss1(y_true, y_pred):
        return tf.norm(input - y_pred) # use your custom loss 1
    return loss1

def custom_loss2(y_true, y_pred):
    return categorical_crossentropy(y_true, y_pred) # use your custom loss 2
</code>```

Try this with simple in-built Keras loss functions first. If that works well, look into your custom loss functions.

Body:
Even after applying the suggestions in answer and comments, it looks like the dimension mismatch issue persists. This is exact code and data file to replicate as well: https://drive.google.com/drive/folders/1q67s0VhB-O7J8OtIhU2jmj7Kc4LxL3sf?usp=sharing

How can this be corrected!? Latest code, model summary, functions used and error I get is below

type_ae=='dcor'
#Wrappers for keras
def custom_loss1(y_true,y_pred):
    dcor = -1*distance_correlation(y_true,encoded_layer)
    return dcor

def custom_loss2(y_true,y_pred):
    recon_loss = losses.categorical_crossentropy(y_true, y_pred)
    return recon_loss

input_layer =  Input(shape=(64,64,1))

encoded_layer = Conv2D(filters = 128, kernel_size = (5,5),padding = 'same',activation ='relu',
                       input_shape = (64,64,1))(input_layer)
encoded_layer = MaxPool2D(pool_size=(2,2))(encoded_layer)
encoded_layer = Dropout(0.25)(encoded_layer)
encoded_layer = (Conv2D(filters = 64, kernel_size = (3,3),padding = 'same',activation ='relu'))(encoded_layer)
encoded_layer = (MaxPool2D(pool_size=(2,2)))(encoded_layer)
encoded_layer = (Dropout(0.25))(encoded_layer)

encoded_layer = (Conv2D(filters = 64, kernel_size = (3,3),padding = 'same',activation ='relu'))(encoded_layer)
encoded_layer = (MaxPool2D(pool_size=(2,2)))(encoded_layer)
encoded_layer = (Dropout(0.25))(encoded_layer)
encoded_layer = Conv2D(filters = 1, kernel_size = (3,3),padding = 'same',activation ='relu',
                       input_shape = (64,64,1),strides=1)(encoded_layer)
encoded_layer = ZeroPadding2D(padding=(28, 28), data_format=None)(encoded_layer)

decoded_imag = Conv2D(8, (2, 2), activation='relu', padding='same')(encoded_layer)
decoded_imag = UpSampling2D((2, 2))(decoded_imag)
decoded_imag = Conv2D(8, (3, 3), activation='relu', padding='same')(decoded_imag)
decoded_imag = UpSampling2D((2, 2))(decoded_imag)
decoded_imag = Conv2D(16, (3, 3), activation='relu', padding='same')(decoded_imag)
decoded_imag = UpSampling2D((2, 2))(decoded_imag)
decoded_imag = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(decoded_imag)
flat_layer = Flatten()(decoded_imag)
dense_layer = Dense(256,activation = "relu")(flat_layer)
dense_layer = Dense(64,activation = "relu")(dense_layer)
dense_layer = Dense(32,activation = "relu")(dense_layer)
output_layer = Dense(9, activation = "softmax")(dense_layer)
autoencoder = Model(input_layer, [encoded_layer,output_layer])
autoencoder.summary()
autoencoder.compile(optimizer='adadelta', loss=[custom_loss1,custom_loss2])
autoencoder.fit(x_train,[x_train, y_train],batch_size=32,epochs=3,shuffle=True,
                validation_data=(x_val, [x_val,y_val]))

The data is of dimensions:

x_train.shape:  (4000, 64, 64, 1)
x_val.shape:  (1000, 64, 64, 1)
y_train.shape:  (4000, 9)
y_val.shape:  (1000, 9)

losses look like:

def custom_loss1(y_true,y_pred):
    dcor = -1*distance_correlation(y_true,encoded_layer)
    return dcor

def custom_loss2(y_true,y_pred):
    recon_loss = losses.categorical_crossentropy(y_true, y_pred)
    return recon_loss

The correlation function is based on tensors as follows:

def distance_correlation(y_true,y_pred):
    pred_r = tf.reduce_sum(y_pred*y_pred,1)
    pred_r = tf.reshape(pred_r,[-1,1])
    pred_d = pred_r - 2*tf.matmul(y_pred,tf.transpose(y_pred))+tf.transpose(pred_r)
    true_r = tf.reduce_sum(y_true*y_true,1)
    true_r = tf.reshape(true_r,[-1,1])
    true_d = true_r - 2*tf.matmul(y_true,tf.transpose(y_true))+tf.transpose(true_r)
    concord = 1-tf.matmul(y_true,tf.transpose(y_true))
    #print(pred_d)
    #print(tf.reshape(tf.reduce_mean(pred_d,1),[-1,1]))
    #print(tf.reshape(tf.reduce_mean(pred_d,0),[1,-1]))
    #print(tf.reduce_mean(pred_d))
    tf.check_numerics(pred_d,'pred_d has NaN')
    tf.check_numerics(true_d,'true_d has NaN')
    A = pred_d - tf.reshape(tf.reduce_mean(pred_d,1),[-1,1]) - tf.reshape(tf.reduce_mean(pred_d,0),[1,-1]) + tf.reduce_mean(pred_d)
    B = true_d - tf.reshape(tf.reduce_mean(true_d,1),[-1,1]) - tf.reshape(tf.reduce_mean(true_d,0),[1,-1]) + tf.reduce_mean(true_d)
    #dcor = -tf.reduce_sum(concord*pred_d)/tf.reduce_sum((1-concord)*pred_d)
    dcor = -tf.log(tf.reduce_mean(A*B))+tf.log(tf.sqrt(tf.reduce_mean(A*A)*tf.reduce_mean(B*B)))#-tf.reduce_sum(concord*pred_d)/tf.reduce_sum((1-concord)*pred_d)
    #print(dcor.shape)
    #tf.Print(dcor,[dcor])
    #dcor = tf.tile([dcor],batch_size)
    return (dcor)

model summary looks like:

_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input_5 (InputLayer)         (None, 64, 64, 1)         0
_________________________________________________________________
conv2d_30 (Conv2D)           (None, 64, 64, 128)       3328
_________________________________________________________________
max_pooling2d_13 (MaxPooling (None, 32, 32, 128)       0
_________________________________________________________________
dropout_13 (Dropout)         (None, 32, 32, 128)       0
_________________________________________________________________
conv2d_31 (Conv2D)           (None, 32, 32, 64)        73792
_________________________________________________________________
max_pooling2d_14 (MaxPooling (None, 16, 16, 64)        0
_________________________________________________________________
dropout_14 (Dropout)         (None, 16, 16, 64)        0
_________________________________________________________________
conv2d_32 (Conv2D)           (None, 16, 16, 64)        36928
_________________________________________________________________
max_pooling2d_15 (MaxPooling (None, 8, 8, 64)          0
_________________________________________________________________
dropout_15 (Dropout)         (None, 8, 8, 64)          0
_________________________________________________________________
conv2d_33 (Conv2D)           (None, 8, 8, 1)           577
_________________________________________________________________
zero_padding2d_5 (ZeroPaddin (None, 64, 64, 1)         0
_________________________________________________________________
conv2d_34 (Conv2D)           (None, 64, 64, 8)         40
_________________________________________________________________
up_sampling2d_10 (UpSampling (None, 128, 128, 8)       0
_________________________________________________________________
conv2d_35 (Conv2D)           (None, 128, 128, 8)       584
_________________________________________________________________
up_sampling2d_11 (UpSampling (None, 256, 256, 8)       0
_________________________________________________________________
conv2d_36 (Conv2D)           (None, 256, 256, 16)      1168
_________________________________________________________________
up_sampling2d_12 (UpSampling (None, 512, 512, 16)      0
_________________________________________________________________
conv2d_37 (Conv2D)           (None, 512, 512, 1)       145
_________________________________________________________________
flatten_4 (Flatten)          (None, 262144)            0
_________________________________________________________________
dense_13 (Dense)             (None, 256)               67109120
_________________________________________________________________
dense_14 (Dense)             (None, 64)                16448
_________________________________________________________________
dense_15 (Dense)             (None, 32)                2080
_________________________________________________________________
dense_16 (Dense)             (None, 9)                 297
=================================================================
Total params: 67,244,507
Trainable params: 67,244,507
Non-trainable params: 0
_________________________________________________________________

This is the error:

InvalidArgumentError                      Traceback (most recent call last)
~/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/ops.py in _create_c_op(graph, node_def, inputs, control_inputs)
   1658   try:
-> 1659     c_op = c_api.TF_FinishOperation(op_desc)
   1660   except errors.InvalidArgumentError as e:

InvalidArgumentError: Dimensions must be equal, but are 1 and 64 for 'loss_1/zero_padding2d_5_loss/MatMul' (op: 'BatchMatMul') with input shapes: [?,64,64,1], [1,64,64,?].

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-11-0e924885fc6b> in <module>
     40 autoencoder = Model(input_layer, [encoded_layer,output_layer])
     41 autoencoder.summary()
---> 42 autoencoder.compile(optimizer='adadelta', loss=[custom_loss1,custom_loss2])
     43 autoencoder.fit(x_train,[x_train, y_train],batch_size=32,epochs=3,shuffle=True,
     44                 validation_data=(x_val, [x_val,y_val]))

~/anaconda3/lib/python3.6/site-packages/keras/engine/training.py in compile(self, optimizer, loss, metrics, loss_weights, sample_weight_mode, weighted_metrics, target_tensors, **kwargs)
    340                 with K.name_scope(self.output_names[i] + '_loss'):
    341                     output_loss = weighted_loss(y_true, y_pred,
--> 342                                                 sample_weight, mask)
    343                 if len(self.outputs) > 1:
    344                     self.metrics_tensors.append(output_loss)

~/anaconda3/lib/python3.6/site-packages/keras/engine/training_utils.py in weighted(y_true, y_pred, weights, mask)
    402         """
    403         # score_array has ndim >= 2
--> 404         score_array = fn(y_true, y_pred)
    405         if mask is not None:
    406             # Cast the mask to floatX to avoid float64 upcasting in Theano

<ipython-input-11-0e924885fc6b> in custom_loss1(y_true, y_pred)
      2 #Wrappers for keras
      3 def custom_loss1(y_true,y_pred):
----> 4         dcor = -1*distance_correlation(y_true,encoded_layer)
      5         return dcor
      6

<ipython-input-6-f282528532cc> in distance_correlation(y_true, y_pred)
      2     pred_r = tf.reduce_sum(y_pred*y_pred,1)
      3     pred_r = tf.reshape(pred_r,[-1,1])
----> 4     pred_d = pred_r - 2*tf.matmul(y_pred,tf.transpose(y_pred))+tf.transpose(pred_r)
      5     true_r = tf.reduce_sum(y_true*y_true,1)
      6     true_r = tf.reshape(true_r,[-1,1])

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/ops/math_ops.py in matmul(a, b, transpose_a, transpose_b, adjoint_a, adjoint_b, a_is_sparse, b_is_sparse, name)
   2415         adjoint_b = True
   2416       return gen_math_ops.batch_mat_mul(
-> 2417           a, b, adj_x=adjoint_a, adj_y=adjoint_b, name=name)
   2418
   2419     # Neither matmul nor sparse_matmul support adjoint, so we conjugate

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/ops/gen_math_ops.py in batch_mat_mul(x, y, adj_x, adj_y, name)
   1421   adj_y = _execute.make_bool(adj_y, "adj_y")
   1422   _, _, _op = _op_def_lib._apply_op_helper(
-> 1423         "BatchMatMul", x=x, y=y, adj_x=adj_x, adj_y=adj_y, name=name)
   1424   _result = _op.outputs[:]
   1425   _inputs_flat = _op.inputs

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py in _apply_op_helper(self, op_type_name, name, **keywords)
    786         op = g.create_op(op_type_name, inputs, output_types, name=scope,
    787                          input_types=input_types, attrs=attr_protos,
--> 788                          op_def=op_def)
    789       return output_structure, op_def.is_stateful, op
    790

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py in new_func(*args, **kwargs)
    505                 'in a future version' if date is None else ('after %s' % date),
    506                 instructions)
--> 507       return func(*args, **kwargs)
    508
    509     doc = _add_deprecated_arg_notice_to_docstring(

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/ops.py in create_op(***failed resolving arguments***)
   3298           input_types=input_types,
   3299           original_op=self._default_original_op,
-> 3300           op_def=op_def)
   3301       self._create_op_helper(ret, compute_device=compute_device)
   3302     return ret

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/ops.py in __init__(self, node_def, g, inputs, output_types, control_inputs, input_types, original_op, op_def)
   1821           op_def, inputs, node_def.attr)
   1822       self._c_op = _create_c_op(self._graph, node_def, grouped_inputs,
-> 1823                                 control_input_ops)
   1824
   1825     # Initialize self._outputs.

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/ops.py in _create_c_op(graph, node_def, inputs, control_inputs)
   1660   except errors.InvalidArgumentError as e:
   1661     # Convert to ValueError for backwards compatibility.
-> 1662     raise ValueError(str(e))
   1663
   1664   return c_op

ValueError: Dimensions must be equal, but are 1 and 64 for 'loss_1/zero_padding2d_5_loss/MatMul' (op: 'BatchMatMul') with input shapes: [?,64,64,1], [1,64,64,?].

Body:
The intention is to use the original image in custom_loss1 and the scalar label values in custom_loss2. I think the working code by @mujjiga in his answer is almost correct. I suggest one slight modification.

In model.compile() pass the input tensor in the loss which needs it. Keep the other one same. model.fit() just passes the labels.

model.compile(optimizer='adadelta', loss=[custom_loss1(input_layer), custom_loss2])
mode.fit(x_train, y_train)

Inside the custom loss functions:

def custom_loss1(input):
    def loss1(y_true, y_pred):
        return tf.norm(input - y_pred) # use your custom loss 1
    return loss1

def custom_loss2(y_true, y_pred):
    return categorical_crossentropy(y_true, y_pred) # use your custom loss 2

Try this with simple in-built Keras loss functions first. If that works well, look into your custom loss functions.


来源: stackexchange

问:
I am loading videos in AVPlayer in collection view but it repeats some cells data
I am loading videos in AVPlayer in collection view. Some cells repeat data. How to resolve this issue?</p>

```<code> func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell:homecollCell = self.collectionview.dequeueReusableCell(withReuseIdentifier: "homecollCell", for: indexPath) as! homecollCell
    //cell.player?.pause()

    let obj = self.friends_array[indexPath.row] as! Home

    cell.img.sd_setImage(with: URL(string:self.appDelegate.imgbaseUrl!+obj.thum), placeholderImage: UIImage(named: ""))

    let url = URL.init(string: self.appDelegate.imgbaseUrl!+obj.video_url)

    let screenSize: CGRect = UIScreen.main.bounds
    cell.playerItem = AVPlayerItem(url: url!)
    //cell.player!.replaceCurrentItem(with: cell.playerItem)
    cell.player = AVPlayer(playerItem: cell.playerItem!)
    cell.playerLayer = AVPlayerLayer(player: cell.player!)
    cell.playerLayer!.frame = CGRect(x:0,y:0,width:screenSize.width,height: screenSize.height)
    cell.playerLayer!.videoGravity = AVLayerVideoGravity.resizeAspectFill
    cell.playerView.layer.addSublayer(cell.playerLayer!)

    cell.player?.play()
</code>```

答:
Cells are reusable so you have to remove or discard the changes what you have done on other cells using prepareForReuse(). Simply like this. Call this inside cell.

```<code>override func prepareForReuse() {
     super.prepareForReuse()
     self.label.text = nil
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am loading videos in AVPlayer in collection view. Some cells repeat data. How to resolve this issue?

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell:homecollCell = self.collectionview.dequeueReusableCell(withReuseIdentifier: "homecollCell", for: indexPath) as! homecollCell
    //cell.player?.pause()

    let obj = self.friends_array[indexPath.row] as! Home

    cell.img.sd_setImage(with: URL(string:self.appDelegate.imgbaseUrl!+obj.thum), placeholderImage: UIImage(named: ""))

    let url = URL.init(string: self.appDelegate.imgbaseUrl!+obj.video_url)

    let screenSize: CGRect = UIScreen.main.bounds
    cell.playerItem = AVPlayerItem(url: url!)
    //cell.player!.replaceCurrentItem(with: cell.playerItem)
    cell.player = AVPlayer(playerItem: cell.playerItem!)
    cell.playerLayer = AVPlayerLayer(player: cell.player!)
    cell.playerLayer!.frame = CGRect(x:0,y:0,width:screenSize.width,height: screenSize.height)
    cell.playerLayer!.videoGravity = AVLayerVideoGravity.resizeAspectFill
    cell.playerView.layer.addSublayer(cell.playerLayer!)

    cell.player?.play()

Body:
Cells are reusable so you have to remove or discard the changes what you have done on other cells using prepareForReuse(). Simply like this. Call this inside cell.

override func prepareForReuse() {
     super.prepareForReuse()
     self.label.text = nil
}


问:
Code executing both if and else statements together how do i fix?
the code is running to match username with password and if both correct redirecting to another page but that and the else statements both run

Code:

```<code>if (isset($_POST['Login'])) {
    $IncorrectDetails = 0;
    $Username=$_REQUEST['Username'];
    $Password=$_REQUEST['Password'];

    echo "<p> $Username  $Password</p>";

    $myfile = fopen("bin\Account Details.txt", "r") or die("Unable to open file!");
    //reads raw file
    $string = fread($myfile,filesize("bin\Account Details.txt"));
    //turns the string to array
    $a = explode(',', $string);

    foreach ($a as $result) {
        $b = explode('. ', $result);
        $AccountDetails[trim($b[0])] = trim($b[1]);
    }

    //closes file
    fclose($myfile);
    print_r($AccountDetails);

    foreach ($AccountDetails as $StoredUsername => $StoredPassword) {
        if ($StoredUsername == $Username){
            if ($StoredPassword == $Password) {
                header('Location: Main.php');
            }
            else {
                $IncorrectDetails = 1;
            }
        }
        else {
            $IncorrectDetails = 1;
        }
    }

    if ($IncorrectDetails == 1){
        echo "<script type='text/javascript'>alert('Incorrect login details');</script>";
    }
}
</code>```

its expected to come up with a popup when incorrect and redirect when correct

答:
That's beacuse the redirection is not instantaneus, php code still being processed.
So, just after header('Location: Main.php'); do exit; to stop at all your script in that point, and let the redirection works.

```<code>header('Location: Main.php');
exit;
</code>```

Also, you musn't print anything before the header() instruction (remove print_r()).

Body:
the code is running to match username with password and if both correct redirecting to another page but that and the else statements both run

Code:

if (isset($_POST['Login'])) {
    $IncorrectDetails = 0;
    $Username=$_REQUEST['Username'];
    $Password=$_REQUEST['Password'];

    echo "
 $Username  $Password
";

    $myfile = fopen("bin\Account Details.txt", "r") or die("Unable to open file!");
    //reads raw file
    $string = fread($myfile,filesize("bin\Account Details.txt"));
    //turns the string to array
    $a = explode(',', $string);

    foreach ($a as $result) {
        $b = explode('. ', $result);
        $AccountDetails[trim($b[0])] = trim($b[1]);
    }

    //closes file
    fclose($myfile);
    print_r($AccountDetails);

    foreach ($AccountDetails as $StoredUsername => $StoredPassword) {
        if ($StoredUsername == $Username){
            if ($StoredPassword == $Password) {
                header('Location: Main.php');
            }
            else {
                $IncorrectDetails = 1;
            }
        }
        else {
            $IncorrectDetails = 1;
        }
    }

    if ($IncorrectDetails == 1){
        echo "";
    }
}

its expected to come up with a popup when incorrect and redirect when correct

Body:
That's beacuse the redirection is not instantaneus, php code still being processed.
So, just after header('Location: Main.php'); do exit; to stop at all your script in that point, and let the redirection works.

header('Location: Main.php');
exit;

Also, you musn't print anything before the header() instruction (remove print_r()).


问:
Convert a .xlsx file to .xls without losing data using Python
There was a need to convert the .xlsx file to .xls.

Existing types of solutions using opepyxl and win32.com lead to data loss, some formulary dependencies implemented in .xlsx formats.

Is there any module converting lossless formats to .xlsx to .xls?

Or maybe there is an advanced library for working with .xlsx files?

答:
You can try:

```<code>import openpyxl
import os

# get files
os.chdir(os.path.abspath(os.path.dirname(__file__)))
pdir = <<folder path in xlsx files are>>
filelist = [filename for filename in pdir.iterdir() if filename.suffix == '.xlsx']

for filename in filelist:
    print(filename.name)

for infile in filelist:
    workbook = openpyxl.load_workbook(infile)
    outfile = f"{infile.name.split('.')[0]}.xls"
    workbook.save(outfile)
</code>```

Source: https://python-forum.io/Thread-how-to-convert-xlsx-to-xls

Body:
You can try:

import openpyxl
import os

# get files
os.chdir(os.path.abspath(os.path.dirname(__file__)))
pdir = <<folder path in xlsx files are>>
filelist = [filename for filename in pdir.iterdir() if filename.suffix == '.xlsx']

for filename in filelist:
    print(filename.name)

for infile in filelist:
    workbook = openpyxl.load_workbook(infile)
    outfile = f"{infile.name.split('.')[0]}.xls"
    workbook.save(outfile)

Source: https://python-forum.io/Thread-how-to-convert-xlsx-to-xls


问:
How to reload code when HTTP server is running?
When starting an http server using HTTP.serve there is apparently no way to reload the code that is actually handling the HTTP request.
In the example below I would like to have the modifications in my_httphandler taken into account without having to restart the server.
For the moment I need to stop the server from the REPL by pressing CTRL+C twice and then run the script again.

Is there a workaround ?

```<code>module MyModule

using HTTP
using Mux
using JSON
using Sockets

function my_httphandler(req::HTTP.Request)
    return HTTP.Response(200, "Hello world")
end

const MY_ROUTER = HTTP.Router()
HTTP.@register(MY_ROUTER, "GET", "/*", my_httphandler)

HTTP.serve(MY_ROUTER, Sockets.localhost, 8081)

end
</code>```

答:
When using HTTP.jl: just add @async before HTTP.serve

```<code>module MyModule

using HTTP
using Sockets

function my_httphandler(req::HTTP.Request)
    return HTTP.Response(200, "Hello world")
end

const MY_ROUTER = HTTP.Router()
HTTP.@register(MY_ROUTER, "GET", "/*", my_httphandler)

@async HTTP.serve(MY_ROUTER, Sockets.localhost, 8081)

end # module
</code>```

When using Mux.jl: nothing to do, the server is started in the background

```<code>using Mux

function sayhellotome(name)
  return("hello " * name * "!!!")
end

@app test = (
  Mux.defaults,

  route("/sayhello/:user", req -> begin
    sayhellotome(req[:params][:user])

  end),

  Mux.notfound())

Mux.serve(test, 8082)
</code>```

Body:
When starting an http server using HTTP.serve there is apparently no way to reload the code that is actually handling the HTTP request.
In the example below I would like to have the modifications in my_httphandler taken into account without having to restart the server.
For the moment I need to stop the server from the REPL by pressing CTRL+C twice and then run the script again.

Is there a workaround ?

module MyModule

using HTTP
using Mux
using JSON
using Sockets

function my_httphandler(req::HTTP.Request)
    return HTTP.Response(200, "Hello world")
end

const MY_ROUTER = HTTP.Router()
HTTP.@register(MY_ROUTER, "GET", "/*", my_httphandler)

HTTP.serve(MY_ROUTER, Sockets.localhost, 8081)

end

Body:
When using HTTP.jl: just add @async before HTTP.serve

module MyModule

using HTTP
using Sockets

function my_httphandler(req::HTTP.Request)
    return HTTP.Response(200, "Hello world")
end

const MY_ROUTER = HTTP.Router()
HTTP.@register(MY_ROUTER, "GET", "/*", my_httphandler)

@async HTTP.serve(MY_ROUTER, Sockets.localhost, 8081)

end # module

When using Mux.jl: nothing to do, the server is started in the background

using Mux

function sayhellotome(name)
  return("hello " * name * "!!!")
end

@app test = (
  Mux.defaults,

  route("/sayhello/:user", req -> begin
    sayhellotome(req[:params][:user])

  end),

  Mux.notfound())

Mux.serve(test, 8082)


问:
OpenLayers not loading GeoJSON layer data
Please i want to display a layer from GeoJSON file with openlayers 5.3.0 but the result (the vectorLayer variable) show a blank page, only Tile layer is visible. What am i missing?

When using this sample json, I can see the created point in map using the same code.

```<code>    {
      "type": "FeatureCollection",
      "features": [
        {
          "type": "Feature",
          "properties": {
              "name": "Null Island"
          },
           "geometry": {
             "type": "Point",
             "coordinates": [0, 0]
           }
         }
       ]
    }
</code>```

The code I'm using:

```<code>    <script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>
    new ol.Map({
      target: 'map',
      layers: [
              new ol.layer.Tile({
              source: new ol.source.OSM()
      }),
      new ol.layer.Vector({
                          source: new ol.source.Vector({
                          format: new ol.format.GeoJSON(),
                          url: 'Geologia.json'
                          })
      })

      ],
      view: new ol.View({
                       center: [0, 0],
                       zoom: 3
      })
    });
</code>```

I got no error message. The file is upload in a public github repo (https://github.com/tiagoferneda/files/blob/master/Geologia.json)

答:
That will be zone 22 south.  You will need to include proj4 in your page and define the projection, and make that the data projection of the format for your source:</p>

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.5.0/proj4.js"></script>

    proj4.defs('EPSG:32722', '+proj=utm +zone=22 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs ');
    ol.proj.proj4.register(proj4);

    new ol.Map({
      target: 'map',
      layers: [
              new ol.layer.Tile({
              source: new ol.source.OSM()
      }),
      new ol.layer.Vector({
                          source: new ol.source.Vector({
                          format: new ol.format.GeoJSON({dataProjection: 'EPSG:32722'}),
                          url: 'https://raw.githubusercontent.com/tiagoferneda/files/master/Geologia.json'
                          })
      })

      ],
      view: new ol.View({
                       center: ol.proj.fromLonLat([-49, -27]),
                       zoom: 10
      })
    });
</code>```

Body:
Please i want to display a layer from GeoJSON file with openlayers 5.3.0 but the result (the vectorLayer variable) show a blank page, only Tile layer is visible. What am i missing?

When using this sample json, I can see the created point in map using the same code.

    {
      "type": "FeatureCollection",
      "features": [
        {
          "type": "Feature",
          "properties": {
              "name": "Null Island"
          },
           "geometry": {
             "type": "Point",
             "coordinates": [0, 0]
           }
         }
       ]
    }

The code I'm using:

    new ol.Map({
      target: 'map',
      layers: [
              new ol.layer.Tile({
              source: new ol.source.OSM()
      }),
      new ol.layer.Vector({
                          source: new ol.source.Vector({
                          format: new ol.format.GeoJSON(),
                          url: 'Geologia.json'
                          })
      })

      ],
      view: new ol.View({
                       center: [0, 0],
                       zoom: 3
      })
    });

I got no error message. The file is upload in a public github repo (https://github.com/tiagoferneda/files/blob/master/Geologia.json)

Body:
That will be zone 22 south.  You will need to include proj4 in your page and define the projection, and make that the data projection of the format for your source:

<script src="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.5.0/proj4.js"></script>

    proj4.defs('EPSG:32722', '+proj=utm +zone=22 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs ');
    ol.proj.proj4.register(proj4);

    new ol.Map({
      target: 'map',
      layers: [
              new ol.layer.Tile({
              source: new ol.source.OSM()
      }),
      new ol.layer.Vector({
                          source: new ol.source.Vector({
                          format: new ol.format.GeoJSON({dataProjection: 'EPSG:32722'}),
                          url: 'https://raw.githubusercontent.com/tiagoferneda/files/master/Geologia.json'
                          })
      })

      ],
      view: new ol.View({
                       center: ol.proj.fromLonLat([-49, -27]),
                       zoom: 10
      })
    });


问:
Config Server: native property source is ignored
This is my bootstrap.yml content file:

```<code>server.port: 8888

spring:
  application:
    name: configserver

  profiles:
    active: native, git, vault

  cloud:
    config:
      enabled: false
      server:
        native:
          searchLocations: classpath:config/
          # searchLocations: file://${native_location}
          order: 3
        git:
          uri: file:///home/jcabre/projects/wsec-sccs/server/repo
          order: 2
        vault:
          host: ${vault_server_host:localhost}
          port: ${vault_server_port:8200}
          scheme: ${vault_server_scheme:https}
          backend: ${vault_backend:configserver}
          profileSeparator: /
          order: 1
</code>```

As you can see I've stand up three backends: native, git, vault.

So classpath:/config/application.yml content:

```<code>foo: FROM NATIVE APPLICATION
</code>```

/home/jcabre/projects/wsec-sccs/server/repo/application.yml content:

```<code>foo: FROM GIT
</code>```

And Vault:

```<code>$ vault kv get configserver/configclient/
=== Data ===
Key    Value
---    -----
foo    FROM VAULT

$vault kv get configserver/configclient/dev
=== Data ===
Key    Value
---    -----
foo    FROM DEV VAULT
</code>```

When I try to get foo config key using curl:

```<code>$ curl -sS -X GET http://localhost:8888/configclient/default -H "X-Config-Token: ${vault_token}" | jq .
{
  "name": "configclient",
  "profiles": [
    "default"
  ],
  "label": null,
  "version": null,
  "state": null,
  "propertySources": [
    {
      "name": "vault:configclient",
      "source": {
        "foo": "FROM VAULT"
      }
    },
    {
      "name": "file:///home/jcabre/projects/wsec-sccs/server/repo/application.yml",
      "source": {
        "foo": "FROM GIT APPLICATION"
      }
    }
  ]
}
</code>```

I only get git and vault property sources, but it doesn't send me native.

How can this be happening?

Any ideas?

答:
Not sure if you ever got an answer to this, but I had a similar problem (no native profile when Vault was enabled) so I looked through the code (latest in GitHub).

It would appear that the NativeEnvironmentRepository is only enabled if the native profile is present AND no other environment repositories are configured. So it doesn't look like you are able to do what you want in the question.

Body:
This is my bootstrap.yml content file:

server.port: 8888

spring:
  application:
    name: configserver

  profiles:
    active: native, git, vault

  cloud:
    config:
      enabled: false
      server:
        native:
          searchLocations: classpath:config/
          # searchLocations: file://${native_location}
          order: 3
        git:
          uri: file:///home/jcabre/projects/wsec-sccs/server/repo
          order: 2
        vault:
          host: ${vault_server_host:localhost}
          port: ${vault_server_port:8200}
          scheme: ${vault_server_scheme:https}
          backend: ${vault_backend:configserver}
          profileSeparator: /
          order: 1

As you can see I've stand up three backends: native, git, vault.

So classpath:/config/application.yml content:

foo: FROM NATIVE APPLICATION

/home/jcabre/projects/wsec-sccs/server/repo/application.yml content:

foo: FROM GIT

And Vault:

$ vault kv get configserver/configclient/
=== Data ===
Key    Value
---    -----
foo    FROM VAULT

$vault kv get configserver/configclient/dev
=== Data ===
Key    Value
---    -----
foo    FROM DEV VAULT

When I try to get foo config key using curl:

$ curl -sS -X GET http://localhost:8888/configclient/default -H "X-Config-Token: ${vault_token}" | jq .
{
  "name": "configclient",
  "profiles": [
    "default"
  ],
  "label": null,
  "version": null,
  "state": null,
  "propertySources": [
    {
      "name": "vault:configclient",
      "source": {
        "foo": "FROM VAULT"
      }
    },
    {
      "name": "file:///home/jcabre/projects/wsec-sccs/server/repo/application.yml",
      "source": {
        "foo": "FROM GIT APPLICATION"
      }
    }
  ]
}

I only get git and vault property sources, but it doesn't send me native.

How can this be happening?

Any ideas?


问:
Is there a shortcut to hide the side bar in Visual Studio Code?
It'd be handy if there was a keyboard shortcut for hiding and showing the sidebar. Sublime has cmd+k+b and it's a quick way of gaining some screen real estate when you need it. Anybody know if this exists or if the user can add it manually to VS Code?

答:
Mac users,

⌘ + B or
⌘ + 0 - Worked Perfectly

ContentLicense: CC BY-SA 3.0


问:
Windows x64 RabbitMQ install error with Erlang environment var (ERLANG_HOME)
I'm ask/answering this question because it hung me up & it's likely someone else will have the same problem.

Install of RabbitMQ x64 v2.8.6 on Windows Server 2008 x64.

After Erlang install using default install location to C:\Program Files\erl5.9.2, I'm attempting to start the server via running the rabbitmq-service.bat. Fail:

```<code>Please either set ERLANG_HOME to point to your Erlang installation
or place the RabbitMQ server distribution in the Erlang lib folder.
</code>```

Problem is the .bat file does not have the correct subpath. with 5.9.2 (R15B02) version of erlang. My ERLANG_HOME directory is set correctly, but the script does not use it correctly for this version of Erlang, which, it appears to this Erlang noob to have a new subdirectory called "erts-5.9.2" which is causing the problems. Maybe someone intimate with these scripts can describe how to make this work correctly without the hack workaround I'm about to describe?

答: Just to share an up-to-date answer as of 2019: On Windows Server 2019, after setting up the environment variable, a restart is required to solve the problem. </p>

Body:
I'm ask/answering this question because it hung me up & it's likely someone else will have the same problem.

Install of RabbitMQ x64 v2.8.6 on Windows Server 2008 x64.

After Erlang install using default install location to C:\Program Files\erl5.9.2, I'm attempting to start the server via running the rabbitmq-service.bat. Fail:

Please either set ERLANG_HOME to point to your Erlang installation
or place the RabbitMQ server distribution in the Erlang lib folder.

Problem is the .bat file does not have the correct subpath. with 5.9.2 (R15B02) version of erlang. My ERLANG_HOME directory is set correctly, but the script does not use it correctly for this version of Erlang, which, it appears to this Erlang noob to have a new subdirectory called "erts-5.9.2" which is causing the problems. Maybe someone intimate with these scripts can describe how to make this work correctly without the hack workaround I'm about to describe?


问:
Run a block of Script after every img element on page
I run a WordPress blog. I want that for every  tag on a single post page, I will have a script placed directly after it as though I was using the ::after in CSS.

I know for CSS I could do the below to display "read more" after all my  tags

img::before {
  content: "read more -";
}
```

But in my case "read more" is a script, an advertisement script specifically.

How do get my script code to display after all images on my webpages?

答:
You need a single script.

In the script you will use a selector to target all the images you wish to target.

If you want to select literally every single image on the page, you can use:

```<code>document.getElementsByTagName('img');
</code>```

If you want to select every image which has a specific class, you can use:

```<code>document.getElementsByClassName('my-image');
</code>```

If  you want to select every image which appears in a certain context, you can use something like:

```<code>document.querySelectorAll('.post img');
</code>```

etc.

Body:
I run a WordPress blog. I want that for every  tag on a single post page, I will have a script placed directly after it as though I was using the ::after in CSS.

I know for CSS I could do the below to display "read more" after all my  tags

img::before {
  content: "read more -";
}

But in my case "read more" is a script, an advertisement script specifically.

How do get my script code to display after all images on my webpages?

Body:
You need a single script.

In the script you will use a selector to target all the images you wish to target.

If you want to select literally every single image on the page, you can use:

document.getElementsByTagName('img');

If you want to select every image which has a specific class, you can use:

document.getElementsByClassName('my-image');

If  you want to select every image which appears in a certain context, you can use something like:

document.querySelectorAll('.post img');

etc.


问:
Redis cli delete multiple keys
I have installed Redis in centos and I have multiple keys of redis like this,

```<code>Product:<id>:<url>
</code>```

How can I delete all Product:*:*  with CLI ?

Redis version : 3.2.4 [ Latest I guess ]

Thanks!

答:
```<code>-n <db>            Database number
</code>```

shell: redis-cli -n 1 --scan --pattern prefix:* | xargs redis-cli -n 1 del

Title: Redis cli delete multiple keys

Body:
I have installed Redis in centos and I have multiple keys of redis like this,

Product:<id>:<url>

How can I delete all Product:*:*  with CLI ?

Redis version : 3.2.4 [ Latest I guess ]

Thanks!

Body:
-n <db>            Database number

shell: redis-cli -n 1 --scan --pattern prefix:* | xargs redis-cli -n 1 del


问:
How can I set an Excel Pivot Table to show just Rank 1 via VBA?
I have a list of Objects and I want to see the most used object. I know I could write a formula for this, if there was only 1 object which had the most use, but sometimes the results are tied and we can have 2, 3, 4... objects all used the same amount of times.

Therefore I believe a Pivot, using Ranking, could be the best way to present the results - as long as I can filter on all Objects with RANK 1.

However, I can't seem to work out how to get the Pivot to just display RANK 1 results.
For example, below is the data source;

```<code>Object
Pencil
Pencil
Pencil
Paper
Paper
Paper
Ruler
Ruler
Rubber
</code>```

When put into a Pivot you would get:

```<code>Object  Vol.  Rank
Pencil  3     1
Paper   3     1
Ruler   2     2
Rubber  1     3
</code>```

How do I get the Pivot to only display RANK 1.
And how would I write this in Excel VBA?

答:
You can apply a filter "Top 1 Count" to the PivotField like this:</p>

```<code>With ActiveSheet.PivotTables(1)
    .PivotFields("Object").PivotFilters.Add2 _
        Type:=xlTopCount, _
        Value1:=1, _
        DataField:=.DataFields(1)
End With
</code>```

Body:
I have a list of Objects and I want to see the most used object. I know I could write a formula for this, if there was only 1 object which had the most use, but sometimes the results are tied and we can have 2, 3, 4... objects all used the same amount of times.

Therefore I believe a Pivot, using Ranking, could be the best way to present the results - as long as I can filter on all Objects with RANK 1.

However, I can't seem to work out how to get the Pivot to just display RANK 1 results.
For example, below is the data source;

Object
Pencil
Pencil
Pencil
Paper
Paper
Paper
Ruler
Ruler
Rubber

When put into a Pivot you would get:

Object  Vol.  Rank
Pencil  3     1
Paper   3     1
Ruler   2     2
Rubber  1     3

How do I get the Pivot to only display RANK 1.
And how would I write this in Excel VBA?

Body:
You can apply a filter "Top 1 Count" to the PivotField like this:

With ActiveSheet.PivotTables(1)
    .PivotFields("Object").PivotFilters.Add2 _
        Type:=xlTopCount, _
        Value1:=1, _
        DataField:=.DataFields(1)
End With


问:
How to display custom names in image galleries (toast message)
I am looking for a way to show a toast messages in your average android gallery. BUT...I want to set custom names for each image that displays when the image is selected. How can i do this?</p>

答:
You could add a listener to your gallery

```<code>setOnItemSelectedListener(new OnItemSelectedListener() {
</code>```

when a item is selected this method

```<code>@Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
</code>```

which is a method from the OnItemSelectedListener class is going to get called, the position relates to the selected item in your gallery that you could use to display any information about that item using a Toast message. Hope this helps.

ContentLicense: CC BY-SA 2.5

Body:
You could add a listener to your gallery

setOnItemSelectedListener(new OnItemSelectedListener() {

when a item is selected this method

@Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

which is a method from the OnItemSelectedListener class is going to get called, the position relates to the selected item in your gallery that you could use to display any information about that item using a Toast message. Hope this helps.


问:
Laravel 5.8.11 getting 419 page expired all forms affected
Started with Laravel 5.5 upgraded to 5.8 (current version 5.8.11). The problem is that when I test locally everything works as it should, when I upload my project to my hosting (dedicated server / shared hosting tried on both) I get a 419 page expired but this is not unique to login all forms are affected and give 419 page expired.

5.5 -> 5.6

```<code>update dependency: "fideloper/proxy": "^4.0", updated all other dependencies to latest versions
update php unit: 7
removed php artisan optimize from composer.json
</code>```

5.6 -> 5.6.30
no changes

5.6 -> 5.7
update laravel/framework dependency to 5.7 in composer.json
changed assets dir

```<code>From resources/assets/js/* to resources/js/*
From resources/assets/sass/* to resources/sass/*
</code>```

update mix.js

```<code>mix.js('resources/js/app.js', 'public/js')
.sass('resources/sass/app.scss', 'public/css');
</code>```

5.7 -> 5.8
Update laravel/framework dependency to 5.8 in composer.json

Created fresh 5.8 installation and moved files to it, currently moving only the files I have edited for created (making 2 versions 5.5 and 5.8) but this will take some time.

Generated new app key (no change)
Set default session domain to my domain (no change)
Tested on Firefox and chrome + incognito mode to see if cached session are a problem

Ran following commands:

```<code>composer dump-autolaod
php artisan cache:clear
php artisan config:cache
php artisan route:cache
</code>```

All forms have csrf_field(), also present in head

What might be causing this issue?

答:
This is usually caused by the session not being able to store or due to old cookies being stored.

So make sure the proper permission is given to the storage directory where sessions are stored.

If you're using file-based sessions. The can be verified with

is_writable(config('session.files'))

You can follow the solutions provided in this other question raised, it is for Laravel 5.5 though.

"The page has expired due to inactivity" - Laravel 5.5

Body:
Started with Laravel 5.5 upgraded to 5.8 (current version 5.8.11). The problem is that when I test locally everything works as it should, when I upload my project to my hosting (dedicated server / shared hosting tried on both) I get a 419 page expired but this is not unique to login all forms are affected and give 419 page expired.

5.5 -> 5.6

update dependency: "fideloper/proxy": "^4.0", updated all other dependencies to latest versions
update php unit: 7
removed php artisan optimize from composer.json

5.6 -> 5.6.30
no changes

5.6 -> 5.7
update laravel/framework dependency to 5.7 in composer.json
changed assets dir

From resources/assets/js/* to resources/js/*
From resources/assets/sass/* to resources/sass/*

update mix.js

mix.js('resources/js/app.js', 'public/js')
.sass('resources/sass/app.scss', 'public/css');

5.7 -> 5.8
Update laravel/framework dependency to 5.8 in composer.json

Created fresh 5.8 installation and moved files to it, currently moving only the files I have edited for created (making 2 versions 5.5 and 5.8) but this will take some time.

Generated new app key (no change)
Set default session domain to my domain (no change)
Tested on Firefox and chrome + incognito mode to see if cached session are a problem

Ran following commands:

composer dump-autolaod
php artisan cache:clear
php artisan config:cache
php artisan route:cache

All forms have csrf_field(), also present in head

What might be causing this issue?


问:
Will I lose data while removing the corrupted parquet file writen by spark-structured-streaming?
I use spark-structured-streaming as consumer to get the data from kafka, following the guide refer to
https://spark.apache.org/docs/latest/structured-streaming-kafka-integration.html

Then save the data to hdfs as parquet file.

Here is my question:
the program is running well but some containers fail rarely(but it did happpend) result in some corrupted parquet files. it will cause the error like [is not a Parquet file (too small length: 4)] or [.parquet is not a Parquet file. expected magic number at tail [80, 65, 82, 49] but found [56, 52, 53, 51]]
when reading them.
I have to move them to other dirs and make sure the query from hive works well. But I'm not sure whether lead to data lost because of the move.

I know spark-structured-streaming use checkpoint to recovey but as some data have writen as parquet, I'm not sure whether the offset is mark as commited.

答:
I did a very basic exercise of loading a txt file into the file directory that is read by Spark structured streaming. The writestream of structured stream was writing to a parquet file. After loading two files I see that the metadata generated by spark has a mention of both the files. So, if you remove one of them (including the metadata file that is created with the file sink), the read of parquet file fails from HDFS with the exception (File not found).

```<code>scala> val ParquetDF1 = spark.read.parquet("/user/root/sink2")
19/05/29 09:57:27 WARN scheduler.TaskSetManager: Lost task 0.0 in stage 13.0 (TID 19, quickstart.cloudera, executor 2): org.apache.spark.SparkException: Exception thrown in awaitResult:
        at org.apache.spark.util.ThreadUtils$.awaitResult(ThreadUtils.scala:226)
        at org.apache.spark.util.ThreadUtils$.parmap(ThreadUtils.scala:290)
        at org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat$.readParquetFootersInParallel(ParquetFileFormat.scala:537)
        at org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat$$anonfun$9.apply(ParquetFileFormat.scala:610)
        at org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat$$anonfun$9.apply(ParquetFileFormat.scala:602)

Caused by: org.apache.hadoop.ipc.RemoteException(java.io.FileNotFoundException): File does not exist: /user/root/sink2/part-00000-454836ef-f7bc-444e-9a6b-e81e640a196d-c000.snappy.parquet
        at org.apache.hadoop.hdfs.server.namenode.INodeFile.valueOf(INodeFile.java:66)
        at org.apache.hadoop.hdfs.server.namenode.INodeFile.valueOf(INodeFile.java:56)
        at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.getBlockLocationsInt(FSNamesystem.java:2092)
        at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.getBlockLocations(FSNamesystem.java:2062)
        at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.getBlockLocations(FSNamesystem.java:1975)
</code>```

The only difference here is- You are using Hive and I am directly building the Parquet dataframe from HDFS.

Body:
I did a very basic exercise of loading a txt file into the file directory that is read by Spark structured streaming. The writestream of structured stream was writing to a parquet file. After loading two files I see that the metadata generated by spark has a mention of both the files. So, if you remove one of them (including the metadata file that is created with the file sink), the read of parquet file fails from HDFS with the exception (File not found).

scala> val ParquetDF1 = spark.read.parquet("/user/root/sink2")
19/05/29 09:57:27 WARN scheduler.TaskSetManager: Lost task 0.0 in stage 13.0 (TID 19, quickstart.cloudera, executor 2): org.apache.spark.SparkException: Exception thrown in awaitResult:
        at org.apache.spark.util.ThreadUtils$.awaitResult(ThreadUtils.scala:226)
        at org.apache.spark.util.ThreadUtils$.parmap(ThreadUtils.scala:290)
        at org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat$.readParquetFootersInParallel(ParquetFileFormat.scala:537)
        at org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat$$anonfun$9.apply(ParquetFileFormat.scala:610)
        at org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat$$anonfun$9.apply(ParquetFileFormat.scala:602)

Caused by: org.apache.hadoop.ipc.RemoteException(java.io.FileNotFoundException): File does not exist: /user/root/sink2/part-00000-454836ef-f7bc-444e-9a6b-e81e640a196d-c000.snappy.parquet
        at org.apache.hadoop.hdfs.server.namenode.INodeFile.valueOf(INodeFile.java:66)
        at org.apache.hadoop.hdfs.server.namenode.INodeFile.valueOf(INodeFile.java:56)
        at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.getBlockLocationsInt(FSNamesystem.java:2092)
        at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.getBlockLocations(FSNamesystem.java:2062)
        at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.getBlockLocations(FSNamesystem.java:1975)

The only difference here is- You are using Hive and I am directly building the Parquet dataframe from HDFS.


问:
How can I use yarn to add a package from github that uses typescript and has not been compiled?
I have a git clone of an npm package which i have modified that works perfectly when I use yarn link <project name> to add it to a project locally. However, when I push it to GitHub and use yarn add <repo url>#<branch> in the same project instead of yarn link, I get a compilation error indicating that the typescript/ES6 has not compiled:

```<code> SyntaxError Plugin: Unexpected token *
</code>```

Which relates to this line in the package I am adding:

```<code>import * as path from 'path'
</code>```

How can I get yarn add to compile the typescript/ES6 on the fly from the GitHub version just like yarn link does with the local version?

I'd rather not build it and commit the result to git as that adds an extra compilation step every time, which I or others might forget.

Also for clarity: I'm not building and pushing to npm as it's a fork of a package that I don't own.

答:
yarn add does not "compile typescript/ES6 on the fly", it just links proper folders. When yarn add-ing from github, you can always import from repo's src directory:

import * as repo from 'repo/src';
```

Body:
I have a git clone of an npm package which i have modified that works perfectly when I use yarn link <project name> to add it to a project locally. However, when I push it to GitHub and use yarn add <repo url>#<branch> in the same project instead of yarn link, I get a compilation error indicating that the typescript/ES6 has not compiled:

 SyntaxError Plugin: Unexpected token *

Which relates to this line in the package I am adding:

import * as path from 'path'

How can I get yarn add to compile the typescript/ES6 on the fly from the GitHub version just like yarn link does with the local version?

I'd rather not build it and commit the result to git as that adds an extra compilation step every time, which I or others might forget.

Also for clarity: I'm not building and pushing to npm as it's a fork of a package that I don't own.


问:
async/await running on single thread
I have a console application where in some instances a user interface needs to be presented. This user interface needs to remain responsive as it will contain a loading gif, progress bar, cancel button etc. I have the following sample code:

```<code>class Program
{
    static void Main(string[] args)
    {
        DoWork().GetAwaiter().GetResult();
    }

    private static async Task DoWork()
    {
        TestForm form = new TestForm();
        form.Show();

        string s = await Task.Run(() =>
        {
            System.Threading.Thread.Sleep(5000);
            return "Plop";
        });

        if (s == "Plop")
        {
            form.Close();
        }
    }
}
</code>```

I would expect from the code above for the TestForm to be displayed for approximately 5 seconds before being closed due to the value of the string being "Plop", however all that happens is the Task is run and the if statement is never reached. Furthermore the UI of the TestForm does not remain responsive. What is wrong with this code?

答:
So I've managed to hack together a dirty solution for this. It is not a clean solution so I'm still open to suggestions but for what I need it works fine

```<code>private static void DoWork()
    {
        TestForm form = new TestForm();

        Task formTask = Task.Run(() => form.ShowDialog());

        Task<string> testTask = Task.Run(() =>
        {
            for (int i = 1; i < 10; i++)
            {
                Thread.Sleep(1000);
                Console.WriteLine(i.ToString());
            }

            Console.WriteLine("Background task finished");
            return "Plop";
        });
        Console.WriteLine("Waiting for background task");

        testTask.Wait();

        if (testTask.Result == "Plop")
        {
            Dispatcher.CurrentDispatcher.InvokeAsync(() => form.Close());
        }

        Console.WriteLine("App finished");
    }
</code>```

This outputs 'Waiting for background task' first, followed by the number count of the Task and then outputs 'Background task finished' when the long process is complete, as well as closes the responsive UI form

Title: async/await running on single thread

Body:
I have a console application where in some instances a user interface needs to be presented. This user interface needs to remain responsive as it will contain a loading gif, progress bar, cancel button etc. I have the following sample code:

class Program
{
    static void Main(string[] args)
    {
        DoWork().GetAwaiter().GetResult();
    }

    private static async Task DoWork()
    {
        TestForm form = new TestForm();
        form.Show();

        string s = await Task.Run(() =>
        {
            System.Threading.Thread.Sleep(5000);
            return "Plop";
        });

        if (s == "Plop")
        {
            form.Close();
        }
    }
}

I would expect from the code above for the TestForm to be displayed for approximately 5 seconds before being closed due to the value of the string being "Plop", however all that happens is the Task is run and the if statement is never reached. Furthermore the UI of the TestForm does not remain responsive. What is wrong with this code?

Body:
So I've managed to hack together a dirty solution for this. It is not a clean solution so I'm still open to suggestions but for what I need it works fine

private static void DoWork()
    {
        TestForm form = new TestForm();

        Task formTask = Task.Run(() => form.ShowDialog());

        Task<string> testTask = Task.Run(() =>
        {
            for (int i = 1; i < 10; i++)
            {
                Thread.Sleep(1000);
                Console.WriteLine(i.ToString());
            }

            Console.WriteLine("Background task finished");
            return "Plop";
        });
        Console.WriteLine("Waiting for background task");

        testTask.Wait();

        if (testTask.Result == "Plop")
        {
            Dispatcher.CurrentDispatcher.InvokeAsync(() => form.Close());
        }

        Console.WriteLine("App finished");
    }

This outputs 'Waiting for background task' first, followed by the number count of the Task and then outputs 'Background task finished' when the long process is complete, as well as closes the responsive UI form


问:
Python installing OPCUA package
Hey guys i have this problem:

I have to install OPCUA package for python. I have already installed opcua with
pip install opcua. But I have this problem:

In my Python code:
from opcua import Client,ua

i get this:
Traceback (most recent call last):
  File "mytry.py", line 1, in
    from opcua import Client,ua
ModuleNotFoundError: No module named 'opcua'

i tried to do this in the cmd and i thought i have to install crypthography so i wrote the command: pip install cryptography

But then i get this message:
Command "python setup.py egg_info" failed with error code 1 in C:\Users\Mikail\AppData\Local\Temp\pip-install-h1su9k_x\cffi\

Can anyone help me? I am new in Python and OPCUA

Note: i have a windows 10 OS

答:
Looks like you didn't install opcua correctly.

Try to use pip list to check is it installed.

You can get examples from https://github.com/FreeOpcUa/python-opcua, and go to examples folder.

```<code>$ python server-minimal.py
</code>```

Open another terminal

```<code>$ python client-minimal.py

Objects node is:  Node(TwoByteNodeId(i=84))
Children of root are:  [Node(NumericNodeId(i=85)), Node(NumericNodeId(i=86)),
Node(NumericNodeId(i=87))]
myvar is:  Node(NumericNodeId(ns=2;i=2))
myobj is:  Node(NumericNodeId(ns=2;i=1))
</code>```

crypthography is just for security, it's not necessary to install.

If crypthography is not installed, you will get a message,

```<code>cryptography is not installed, use of crypto disabled
</code>```

Title: Python installing OPCUA package

Body:
Looks like you didn't install opcua correctly.

Try to use pip list to check is it installed.

You can get examples from https://github.com/FreeOpcUa/python-opcua, and go to examples folder.

$ python server-minimal.py

Open another terminal

$ python client-minimal.py

Objects node is:  Node(TwoByteNodeId(i=84))
Children of root are:  [Node(NumericNodeId(i=85)), Node(NumericNodeId(i=86)),
Node(NumericNodeId(i=87))]
myvar is:  Node(NumericNodeId(ns=2;i=2))
myobj is:  Node(NumericNodeId(ns=2;i=1))

crypthography is just for security, it's not necessary to install.

If crypthography is not installed, you will get a message,

cryptography is not installed, use of crypto disabled


问:
Responsive text size in tables
Could someone let me know which element controls the text size in tables?

I am trying to get a table driven by bootstrap 3 (table.borderless) to be responsive.  So that as the screen shrinks the text within the table reduces in size.

I have managed to get this working with  and normal elements of HTML, but its not 'shrinking' the table text for some reason....

I have the <meta name="viewport" content="width=device-width, initial-scale=1"> line in there to.

答:
Added,

```<code>@media (max-width: 576px) {
    html { font-size: 0.7rem; }
    th { font-size: 1rem; }
}
@media (min-width: 768px) {
    html { font-size: 0.8rem; }
    th { font-size: 1rem; }

}
@media (min-width: 992px) {
    html { font-size: 0.8rem; }
    th { font-size: 1rem; }
}
@media (min-width: 1200px) {
    html { font-size: 0.8rem; }
    th { font-size: 1rem; }
}
</code>```

Which then obviously makes the whole thing responsive, as long as a number of the other styles are rem sized.

Title: Responsive text size in tables

Body:
Added,

@media (max-width: 576px) {
    html { font-size: 0.7rem; }
    th { font-size: 1rem; }
}
@media (min-width: 768px) {
    html { font-size: 0.8rem; }
    th { font-size: 1rem; }

}
@media (min-width: 992px) {
    html { font-size: 0.8rem; }
    th { font-size: 1rem; }
}
@media (min-width: 1200px) {
    html { font-size: 0.8rem; }
    th { font-size: 1rem; }
}

Which then obviously makes the whole thing responsive, as long as a number of the other styles are rem sized.


问:
What is the use of overriding the finalize() method of Object class?
As far as I know , in java if we want to manually call the garbage collector we can do System.gc().

1.What are the operations that we do inside our overriden finalize() method?

2.Is it required to override the finalize() method if we want to manually call the JVM garbage collector?

答:
For very rare cases it may be useful or necessary to implement finalize for freeing allocated resources. This method is always called when an instance is destroyed finally.

May be helpful if you work with native code and need to free allocated resources in the native code area.

But use it with care, because implementing finally will slow down the garbage collector dramatically and kill performance.


问:
JSX adjacent on react.js
the code below is divided into two parts one deals with the management of the head the other "body" when I execute the code the exception below is raised, how can I solve the error?
I can't figure out what the error below is due to, the error is on the parsing of react

Error:

```<code>  Line 48:  Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?

         <Link rel="stylesheet" type="text/css" href="css/main.css" />
     </HeadProvider>
</code>```

Code:

```<code>import * as React from 'react';
import { Button, Form, FormGroup, FormControl, ControlLabel } from "react-bootstrap";
import logo from './logo.svg';
import { HeadProvider, Title, Link, Meta } from 'react-head';

import './Home.css';

class Home extends Component {
  ...

  render() {
    return (
      <HeadProvider>
        <Meta charset="UTF-8" />
        <Meta name="viewport" content="width=device-width, initial-scale=1" />
        <Link rel="icon" type="image/png" href="images/icons/favicon.ico" />
        <Link rel="stylesheet" type="text/css" href="vendor/bootstrap/css/bootstrap.min.css" />
        <Link rel="stylesheet" type="text/css" href="fonts/font-awesome-4.7.0/css/font-awesome.min.css" />
        <Link rel="stylesheet" type="text/css" href="fonts/iconic/css/material-design-iconic-font.min.css" />
        <Link rel="stylesheet" type="text/css" href="vendor/animate/animate.css" />
        <Link rel="stylesheet" type="text/css" href="vendor/css-hamburgers/hamburgers.min.css" />
        <Link rel="stylesheet" type="text/css" href="vendor/animsition/css/animsition.min.css" />
        <Link rel="stylesheet" type="text/css" href="vendor/select2/select2.min.css" />
        <Link rel="stylesheet" type="text/css" href="vendor/daterangepicker/daterangepicker.css" />
        <Link rel="stylesheet" type="text/css" href="css/util.css" />
        <Link rel="stylesheet" type="text/css" href="css/main.css" />
      </HeadProvider>
        <div className="Login">
          <Form onSubmit={this.handleSubmit}>
            <Form.Group controlId="email" bsSize="large">
              <label> Email: </label>
              <Form.Control
                autoFocus
                type="email"
                value={this.state.email}
                onChange={this.handleChange}
              />

            </Form.Group>
            <br></br>
            <Form.Group controlId="password" bsSize="large">
              <label> Password: </label>
              <Form.Control
                value={this.state.password}
                onChange={this.handleChange}
                type="password"
              />
            </Form.Group>
            <Button
              block
              bsSize="large"
              disabled={!this.validateForm()}
              type="submit"
            >
              Login
              </Button>
          </Form>
        </div>
    );
  }
}

export default Home;
</code>```

答:
You need to wrap all your render into something, for exemple a Fragment or a div</p>

```<code>return (
      <Fragment>
      <HeadProvider>
        <Meta charset="UTF-8" />
        <Meta name="viewport" content="width=device-width, initial-scale=1" />
        <Link rel="icon" type="image/png" href="images/icons/favicon.ico" />
        <Link rel="stylesheet" type="text/css" href="vendor/bootstrap/css/bootstrap.min.css" />
        <Link rel="stylesheet" type="text/css" href="fonts/font-awesome-4.7.0/css/font-awesome.min.css" />
        <Link rel="stylesheet" type="text/css" href="fonts/iconic/css/material-design-iconic-font.min.css" />
        <Link rel="stylesheet" type="text/css" href="vendor/animate/animate.css" />
        <Link rel="stylesheet" type="text/css" href="vendor/css-hamburgers/hamburgers.min.css" />
        <Link rel="stylesheet" type="text/css" href="vendor/animsition/css/animsition.min.css" />
        <Link rel="stylesheet" type="text/css" href="vendor/select2/select2.min.css" />
        <Link rel="stylesheet" type="text/css" href="vendor/daterangepicker/daterangepicker.css" />
        <Link rel="stylesheet" type="text/css" href="css/util.css" />
        <Link rel="stylesheet" type="text/css" href="css/main.css" />
      </HeadProvider>
        <div className="Login">
          <Form onSubmit={this.handleSubmit}>
            <Form.Group controlId="email" bsSize="large">
              <label> Email: </label>
              <Form.Control
                autoFocus
                type="email"
                value={this.state.email}
                onChange={this.handleChange}
              />

            </Form.Group>
            <br></br>
            <Form.Group controlId="password" bsSize="large">
              <label> Password: </label>
              <Form.Control
                value={this.state.password}
                onChange={this.handleChange}
                type="password"
              />
            </Form.Group>
            <Button
              block
              bsSize="large"
              disabled={!this.validateForm()}
              type="submit"
            >
              Login
              </Button>
          </Form>
        </div>
        </Fragment>
    );
</code>```

Title: JSX adjacent on react.js

Body:
the code below is divided into two parts one deals with the management of the head the other "body" when I execute the code the exception below is raised, how can I solve the error?
I can't figure out what the error below is due to, the error is on the parsing of react

Error:

  Line 48:  Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?

         <Link rel="stylesheet" type="text/css" href="css/main.css" />
     </HeadProvider>

Code:

import * as React from 'react';
import { Button, Form, FormGroup, FormControl, ControlLabel } from "react-bootstrap";
import logo from './logo.svg';
import { HeadProvider, Title, Link, Meta } from 'react-head';

import './Home.css';

class Home extends Component {
  ...

  render() {
    return (
      <HeadProvider>
        <Meta charset="UTF-8" />
        <Meta name="viewport" content="width=device-width, initial-scale=1" />
        <Link rel="icon" type="image/png" href="images/icons/favicon.ico" />
        <Link rel="stylesheet" type="text/css" href="vendor/bootstrap/css/bootstrap.min.css" />
        <Link rel="stylesheet" type="text/css" href="fonts/font-awesome-4.7.0/css/font-awesome.min.css" />
        <Link rel="stylesheet" type="text/css" href="fonts/iconic/css/material-design-iconic-font.min.css" />
        <Link rel="stylesheet" type="text/css" href="vendor/animate/animate.css" />
        <Link rel="stylesheet" type="text/css" href="vendor/css-hamburgers/hamburgers.min.css" />
        <Link rel="stylesheet" type="text/css" href="vendor/animsition/css/animsition.min.css" />
        <Link rel="stylesheet" type="text/css" href="vendor/select2/select2.min.css" />
        <Link rel="stylesheet" type="text/css" href="vendor/daterangepicker/daterangepicker.css" />
        <Link rel="stylesheet" type="text/css" href="css/util.css" />
        <Link rel="stylesheet" type="text/css" href="css/main.css" />
      </HeadProvider>

          <Form onSubmit={this.handleSubmit}>
            <Form.Group controlId="email" bsSize="large">
               Email:
              <Form.Control
                autoFocus
                type="email"
                value={this.state.email}
                onChange={this.handleChange}
              />

            </Form.Group>

            <Form.Group controlId="password" bsSize="large">
               Password:
              <Form.Control
                value={this.state.password}
                onChange={this.handleChange}
                type="password"
              />
            </Form.Group>
            <Button
              block
              bsSize="large"
              disabled={!this.validateForm()}
              type="submit"
            >
              Login
              </Button>
          </Form>

    );
  }
}

export default Home;

Body:
You need to wrap all your render into something, for exemple a Fragment or a div

return (
      <Fragment>
      <HeadProvider>
        <Meta charset="UTF-8" />
        <Meta name="viewport" content="width=device-width, initial-scale=1" />
        <Link rel="icon" type="image/png" href="images/icons/favicon.ico" />
        <Link rel="stylesheet" type="text/css" href="vendor/bootstrap/css/bootstrap.min.css" />
        <Link rel="stylesheet" type="text/css" href="fonts/font-awesome-4.7.0/css/font-awesome.min.css" />
        <Link rel="stylesheet" type="text/css" href="fonts/iconic/css/material-design-iconic-font.min.css" />
        <Link rel="stylesheet" type="text/css" href="vendor/animate/animate.css" />
        <Link rel="stylesheet" type="text/css" href="vendor/css-hamburgers/hamburgers.min.css" />
        <Link rel="stylesheet" type="text/css" href="vendor/animsition/css/animsition.min.css" />
        <Link rel="stylesheet" type="text/css" href="vendor/select2/select2.min.css" />
        <Link rel="stylesheet" type="text/css" href="vendor/daterangepicker/daterangepicker.css" />
        <Link rel="stylesheet" type="text/css" href="css/util.css" />
        <Link rel="stylesheet" type="text/css" href="css/main.css" />
      </HeadProvider>
        <div className="Login">
          <Form onSubmit={this.handleSubmit}>
            <Form.Group controlId="email" bsSize="large">
              <label> Email: </label>
              <Form.Control
                autoFocus
                type="email"
                value={this.state.email}
                onChange={this.handleChange}
              />

            </Form.Group>
            <br></br>
            <Form.Group controlId="password" bsSize="large">
              <label> Password: </label>
              <Form.Control
                value={this.state.password}
                onChange={this.handleChange}
                type="password"
              />
            </Form.Group>
            <Button
              block
              bsSize="large"
              disabled={!this.validateForm()}
              type="submit"
            >
              Login
              </Button>
          </Form>
        </div>
        </Fragment>
    );


问:
not able to fetch text data from web url using javascript
I need to extract text data from web url (http://www.africau.edu/images/default/sample.pdf)

I used two node_module.

1) crawler-Request

```<code>  it('Read Pdf Data using crawler',function(){
        const crawler = require('crawler-request');
        function response_text_size(response){
            response["size"] = response.text.length;
            return response;
        }
        crawler("http://www.africau.edu/images/default/sample.pdf",response_text_size).then(function(response){
            // handle response

            console.log("Reponse =" + response.size);
        });

    });
</code>```

What happen for this it will not print anything on console.

2) pfd2json/pdfparser

```<code>it('Read Data from url',function(){
        var request = require('request');
        var pdf = require('pfd2json/pdfparser');
        var fs = require('fs');
        var pdfUrl = "http://www.africau.edu/images/default/sample.pdf";
        let databuffer = fs.readFileSync(pdfUrl);
        pdf(databuffer).then(function(data){
            var arr:Array<String> = data.text;
            var n = arr.includes('Thursday 02 May');
            console.log("Print Array " + n);
        });

    });
</code>```

Failed: ENOENT: no such file or directory, open 'http://www.africau.edu/images/default/sample.pdf'

I am able to access data from local path but not able to extract it from url.

答:
The issue here is that you are using the fs module (File System) to read a file on a distant server.

You also mistyped the pdf2json module, which should give you an error ?

You did require the request module. This module will make it possible to access that distant file. Here's one way to do this :

```<code>it('Read Data from url', function () {
    var request = require('request');
    var PDFParser = require('pdf2json');

    var pdfUrl = 'http://unec.edu.az/application/uploads/2014/12/pdf-sample.pdf';

    var pdfParser = new PDFParser(this, 1);

    // executed if the parser fails for any reason
    pdfParser.on("pdfParser_dataError", errData => console.error(errData.parserError));
    // executed when the parser finished
    pdfParser.on("pdfParser_dataReady", pdfData => console.log(pdfParser.getRawTextContent()));

    // request to get the pdf's file content then call the pdf parser on the retrieved buffer
    request({ url: pdfUrl, encoding: null }, (error, response, body) => pdfParser.parseBuffer(body));
});
</code>```

This will make it possible to load the distant .pdf file in your program.

I'd recommend looking at the pdf2json documentation if you want to do more. This will simply output the textual content of the .pdf file when the parser has completed reading data.

Body:
I need to extract text data from web url (http://www.africau.edu/images/default/sample.pdf)

I used two node_module.

1) crawler-Request

  it('Read Pdf Data using crawler',function(){
        const crawler = require('crawler-request');
        function response_text_size(response){
            response["size"] = response.text.length;
            return response;
        }
        crawler("http://www.africau.edu/images/default/sample.pdf",response_text_size).then(function(response){
            // handle response

            console.log("Reponse =" + response.size);
        });

    });

What happen for this it will not print anything on console.

2) pfd2json/pdfparser

it('Read Data from url',function(){
        var request = require('request');
        var pdf = require('pfd2json/pdfparser');
        var fs = require('fs');
        var pdfUrl = "http://www.africau.edu/images/default/sample.pdf";
        let databuffer = fs.readFileSync(pdfUrl);
        pdf(databuffer).then(function(data){
            var arr:Array<String> = data.text;
            var n = arr.includes('Thursday 02 May');
            console.log("Print Array " + n);
        });

    });

Failed: ENOENT: no such file or directory, open 'http://www.africau.edu/images/default/sample.pdf'

I am able to access data from local path but not able to extract it from url.

Body:
The issue here is that you are using the fs module (File System) to read a file on a distant server.

You also mistyped the pdf2json module, which should give you an error ?

You did require the request module. This module will make it possible to access that distant file. Here's one way to do this :

it('Read Data from url', function () {
    var request = require('request');
    var PDFParser = require('pdf2json');

    var pdfUrl = 'http://unec.edu.az/application/uploads/2014/12/pdf-sample.pdf';

    var pdfParser = new PDFParser(this, 1);

    // executed if the parser fails for any reason
    pdfParser.on("pdfParser_dataError", errData => console.error(errData.parserError));
    // executed when the parser finished
    pdfParser.on("pdfParser_dataReady", pdfData => console.log(pdfParser.getRawTextContent()));

    // request to get the pdf's file content then call the pdf parser on the retrieved buffer
    request({ url: pdfUrl, encoding: null }, (error, response, body) => pdfParser.parseBuffer(body));
});

This will make it possible to load the distant .pdf file in your program.

I'd recommend looking at the pdf2json documentation if you want to do more. This will simply output the textual content of the .pdf file when the parser has completed reading data.


问:
Rendering String as HTML in android webview
I have a String that I need to render in Webview, but facing issues.
The String is as follows.

```<code>History
            Riots and political conflicts of the 1960s

--------Line Feed1----------------

              The LAPD Metropolitan Division's "D" Platoon is one of the world's most prominent SWAT units and was the second SWAT team established in the United States, after that of the Philadelphia Police Department in 1964.[2]
According to the Historical Dictionary of Law Enforcement, the term "SWAT" was used as an acronym for the "Special Weapons and Tactics" established as a 100-man specialized unit in 1964 by the Philadelphia Police Department in response to an alarming increase in bank robberies.

--------Line Feed2----------------

                  The purpose of this unit was to react quickly and decisively to bank robberies while they were in progress, by utilizing a large number of specially trained officers who had at their disposal a great amount of firepower. The tactic worked and was later soon to resolve other types of incidents involving heavily armed criminals.[2][3] Los Angeles Police Department (LAPD) Inspector Daryl Gates has said that he first envisioned "SWAT" as an acronym for "Special Weapons Attack Team" in 1967, but later accepted "Special Weapons and Tactics" on the advice of his deputy chief, Edward M. Davis.[4]

<p> </p>
<p><span><img src="https://upload.wikimedia.org/wikipedia/commons/1/19/Flag_of_Andorra.svg" border="0" alt="" /></span></p>
<p> </p>
</code>```

Approach 1:
When I pass above String to webview using (str is the String mentioned above)

```<code>webview.loadDataWithBaseURL(null,str,"text/html","utf-8",null)
</code>```

The result is as indicated in Figure A below. The problem here is that the Line feed characters(\n) and whitespaces are removed by the webview.

Approach 2:
When I pass above String to webview using

```<code>webview.loadDataWithBaseURL(null,Html.toHtml(SpannableString(str)),"text/html","utf-8",null)
</code>```

The result is as indicated in Figure B below. The problem here is that the Line feed characters(\n) and whitespaces are shown properly but the HTML is also shown as plain text.

Approach 3:
When I pass above String to webview using

```<code> webview.loadDataWithBaseURL(null,str.replace("\n",<br/>"),"text/html","utf-8",null)
</code>```

The result is as indicated in Figure C below. The problem here is that the Line feed characters(\n) and HTML are rendered properly, but the whitespaces at the start of paragraphs are not shown.

My requirement is to achieve it as shown in Figure D below

What would be the optimum solution to achieve the desired result.
I have created a sample application here for reference.

答:
Have you the hand on the HTML string ? If yes, you should move your text content in a
 tag and add a padding left instead of whitespaces.

Like explains here : https://stackoverflow.com/a/1571662/6809926

Body:
I have a String that I need to render in Webview, but facing issues.
The String is as follows.

History
            Riots and political conflicts of the 1960s

--------Line Feed1----------------

              The LAPD Metropolitan Division's "D" Platoon is one of the world's most prominent SWAT units and was the second SWAT team established in the United States, after that of the Philadelphia Police Department in 1964.[2]
According to the Historical Dictionary of Law Enforcement, the term "SWAT" was used as an acronym for the "Special Weapons and Tactics" established as a 100-man specialized unit in 1964 by the Philadelphia Police Department in response to an alarming increase in bank robberies.

--------Line Feed2----------------

                  The purpose of this unit was to react quickly and decisively to bank robberies while they were in progress, by utilizing a large number of specially trained officers who had at their disposal a great amount of firepower. The tactic worked and was later soon to resolve other types of incidents involving heavily armed criminals.[2][3] Los Angeles Police Department (LAPD) Inspector Daryl Gates has said that he first envisioned "SWAT" as an acronym for "Special Weapons Attack Team" in 1967, but later accepted "Special Weapons and Tactics" on the advice of his deputy chief, Edward M. Davis.[4]

Approach 1:
When I pass above String to webview using (str is the String mentioned above)

webview.loadDataWithBaseURL(null,str,"text/html","utf-8",null)

The result is as indicated in Figure A below. The problem here is that the Line feed characters(\n) and whitespaces are removed by the webview.

Approach 2:
When I pass above String to webview using

webview.loadDataWithBaseURL(null,Html.toHtml(SpannableString(str)),"text/html","utf-8",null)

The result is as indicated in Figure B below. The problem here is that the Line feed characters(\n) and whitespaces are shown properly but the HTML is also shown as plain text.

Approach 3:
When I pass above String to webview using

 webview.loadDataWithBaseURL(null,str.replace("\n",
"),"text/html","utf-8",null)

The result is as indicated in Figure C below. The problem here is that the Line feed characters(\n) and HTML are rendered properly, but the whitespaces at the start of paragraphs are not shown.

My requirement is to achieve it as shown in Figure D below

What would be the optimum solution to achieve the desired result.
I have created a sample application here for reference.

Body:
Have you the hand on the HTML string ? If yes, you should move your text content in a <p> tag and add a padding left instead of whitespaces.

Like explains here : https://stackoverflow.com/a/1571662/6809926


问:
How to fix 'Access denied - error 403' in a SharePoint-based flow
I'm trying to use the Sharepoint -> Get File Content action in Power Automate, but I'm getting a 403 error - Access Denied. I am using the same login for SPO and Power Automate. I have (for now) hard-coded a file to fetch - I can definitely browse to it, but for some reason I get the error in Power Automate. Is there another permission that I need to be granted to access the same file via Power Automate that I might be missing?

I have tried Get File Content with several different files, and they all give the same result. In each case, I can manually browse to the site/library/folder where the file is and download it, using the same login.

答:
Have you made some changes on the sharepoint permissions?

Have you recreate a new connection to sharepoint in flow connections?

In many cases, an error code of 403 appears in a flow fail because of an authentication error. If you have this type of error, you can usually fix an authentication error by updating the connection,please make sure you have update the connection.

You could refer to link below

https://learn.microsoft.com/en-us/flow/fix-flow-failures

If you have updated the connection and the issue still exists,I afraid that there is some permissions setted in the sharepoint forbid you to access the sharepoint.

Please take a try to contact with the sharepoint administrator to see if you have been access denied in sharepoint.