问:
How to use matrix-shaped inputs for dense layer in keras?
To build a regression/forecast model I'd like to take a matrix of sensor-readings (rows~sensors, columns~timepoints) and predict a future trend for these sensors.

Example implementation

```<code># install.packages(c("keras", "tensorflow"))
library(keras)
library(tensorflow)

#' Prepare some training data mapping matrices to other smaller matrices where the response entries correspond to basic math
n = 1000000
nb = 10
mx = matrix(rnorm(6 * n, 0, 1), nrow = n, byrow = TRUE)
my = matrix(0, nrow = n, ncol = 3)
eps = 0.01

for (i in 1 : n) {
    x1 = mx[i, 1]; x2 = mx[i, 2]; x3 = mx[i, 3]; x4 = mx[i, 4]; x5 = mx[i, 5]; x6 = mx[i, 6];
    s1 = x1 * x1;   s2 = x2 * x2;   s3 = x3 * x3;   s4 = x4 * x4;   s5 = x5 * x5;   s6 = x6 * x6;
    zz = rnorm(1, 0, 1)

    my[i, 1] = (x1 + x2 + x3 + x4 + x5 + x6 + eps * zz)
    my[i, 2] = (s1 + s2 + eps * zz * zz)
    my[i, 3] = (x1 * s1 + s2 + x5 * s5 + x6 * s6 + eps * zz)
}

#' Recast into tf types
x_train = tf$constant(mx, shape = as.integer(c(n / nb, nb, 6)))
# FLATTENING the input would work WOULD WORK:
# x_train = tf$constant(mx, shape = as.integer(c(n / nb, nb, 6)))
y_train = tf$constant(my, shape = as.integer(c(n / nb, nb, 3)))

#' Build the model
inputShape = dim(x_train)[- 1]
outputShape = dim(y_train)[- 1]

model1 = keras_model_sequential() %>%
    layer_dense(units = 64, activation = "relu", input_shape = inputShape) %>%
    layer_dense(units = 256, activation = "relu") %>%
    layer_dense(units = prod(outputShape)) %>%
    layer_reshape(outputShape) %>%
    compile(loss = "mse", optimizer = "adam", metrics = list("mean_absolute_error", "mean_squared_error"))

model1 %>% summary
fit(model1, x_train, y_train, epochs = 3, validation_split = 0.2, verbose = 1)

model2 = keras_model_sequential() %>%
## tbd layer_input  --> layer_rehsape --> layer_dense (which seems to work best with non-matrix valued inputs
    layer_dense(units = 64, activation = "relu", input_shape = inputShape) %>%
    layer_dense(units = 256, activation = "relu") %>%
    layer_dense(units = outputShape[2]) %>%
# layer_dense(units = prod(outputShape)) %>%
# layer_reshape(outputShape) %>%
    compile(loss = "mse", optimizer = "adam", metrics = list("mean_absolute_error", "mean_squared_error"))

model2 %>% summary

fit(model2, x_train, y_train, epochs = 3, validation_split = 0.2, verbose = 1)
</code>```

Summary of model1 is

```<code>> model1 %>% summary
Model: "sequential_42"
________________________________________________________________________________
Layer (type)                        Output Shape                    Param #
================================================================================
dense_126 (Dense)                   (None, 10, 64)                  448
________________________________________________________________________________
dense_127 (Dense)                   (None, 10, 256)                 16640
________________________________________________________________________________
dense_128 (Dense)                   (None, 10, 30)                  7710
________________________________________________________________________________
reshape_29 (Reshape)                (None, 10, 3)                   0
================================================================================
Total params: 24,798
Trainable params: 24,798
Non-trainable params: 0
________________________________________________________________________________
</code>```

Shape of mode2 is

```<code>> model2 %>% summary
Model: "sequential_43"
________________________________________________________________________________
Layer (type)                        Output Shape                    Param #
================================================================================
dense_129 (Dense)                   (None, 10, 64)                  448
________________________________________________________________________________
dense_130 (Dense)                   (None, 10, 256)                 16640
________________________________________________________________________________
dense_131 (Dense)                   (None, 10, 3)                   771
================================================================================
Total params: 17,859
Trainable params: 17,859
Non-trainable params: 0
________________________________________________________________________________
</code>```

Although both models have the same input and output shape, model1 fails to train with with

```<code>Error in py_call_impl(callable, dots$args, dots$keywords) :
  ValueError: in user code:

    C:\Users\brandl\AppData\Local\r-miniconda\envs\r-reticulate\lib\site-packages\tensorflow\python\keras\engine\training.py:571 train_function  *
        outputs = self.distribute_strategy.run(
    C:\Users\brandl\AppData\Local\r-miniconda\envs\r-reticulate\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:951 run  **
        return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    C:\Users\brandl\AppData\Local\r-miniconda\envs\r-reticulate\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:2290 call_for_each_replica
        return self._call_for_each_replica(fn, args, kwargs)
    C:\Users\brandl\AppData\Local\r-miniconda\envs\r-reticulate\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:2649 _call_for_each_replica
        return fn(*args, **kwargs)
    C:\Users\brandl\AppData\Local\r-miniconda\envs\r-reticulate\lib\site-packages\tensorflow\python\keras\engine\training.py:531 train_s
</code>```

By flattening the input it works (see the commented line where x_train is defined). However,  I wonder why we can't use matrix-shaped input value here for the dense layer (or how to do so correctly)?

Note: The example is written using https://keras.rstudio.com/ but since it's a rather 1:1 wrapper API, I'd happy with a python answer as well.

答:
According to the Dense docs (https://www.tensorflow.org/api_docs/python/tf/keras/layers/Dense):

If the input to the layer has a rank greater than 2, then Dense computes the dot product between the inputs and the kernel along the last axis of the inputs and axis 1 of the kernel (using tf.tensordot)

Therefore, if the input tensor has a shape (a,b,c) and the Dense layer has d units, the output tensor has a shape (a,b,d). If you pass your tensor through multiple Dense layers, only the last dimension will change.

Now, if the code runs with a flattened x, a potential problem is the shape mismatch. Indeed, y_train seems to not have the same dimensions as the output of the network.

According to this

```<code>x_train = tf$constant(mx, shape = as.integer(c(n / nb, nb, 6)))
y_train = tf$constant(my, shape = as.integer(c(n / nb, nb, 3)))
</code>```

x_train and y_train have identical dimensions except for the last one. Then, for the predictions and y_train to have the same dimensions, your model should end with sth like

```<code>layer_dense(units = outputShape[3]) %>%
</code>```

instead of

```<code>layer_dense(units = prod(outputShape)) %>%
layer_reshape(outputShape) %>%
</code>```

That's just the technical side though. Not sure if conceptually it is what you are after.

Body:
To build a regression/forecast model I'd like to take a matrix of sensor-readings (rows~sensors, columns~timepoints) and predict a future trend for these sensors.

Example implementation

# install.packages(c("keras", "tensorflow"))
library(keras)
library(tensorflow)

#' Prepare some training data mapping matrices to other smaller matrices where the response entries correspond to basic math
n = 1000000
nb = 10
mx = matrix(rnorm(6 * n, 0, 1), nrow = n, byrow = TRUE)
my = matrix(0, nrow = n, ncol = 3)
eps = 0.01

for (i in 1 : n) {
    x1 = mx[i, 1]; x2 = mx[i, 2]; x3 = mx[i, 3]; x4 = mx[i, 4]; x5 = mx[i, 5]; x6 = mx[i, 6];
    s1 = x1 * x1;   s2 = x2 * x2;   s3 = x3 * x3;   s4 = x4 * x4;   s5 = x5 * x5;   s6 = x6 * x6;
    zz = rnorm(1, 0, 1)

    my[i, 1] = (x1 + x2 + x3 + x4 + x5 + x6 + eps * zz)
    my[i, 2] = (s1 + s2 + eps * zz * zz)
    my[i, 3] = (x1 * s1 + s2 + x5 * s5 + x6 * s6 + eps * zz)
}

#' Recast into tf types
x_train = tf$constant(mx, shape = as.integer(c(n / nb, nb, 6)))
# FLATTENING the input would work WOULD WORK:
# x_train = tf$constant(mx, shape = as.integer(c(n / nb, nb, 6)))
y_train = tf$constant(my, shape = as.integer(c(n / nb, nb, 3)))

#' Build the model
inputShape = dim(x_train)[- 1]
outputShape = dim(y_train)[- 1]

model1 = keras_model_sequential() %>%
    layer_dense(units = 64, activation = "relu", input_shape = inputShape) %>%
    layer_dense(units = 256, activation = "relu") %>%
    layer_dense(units = prod(outputShape)) %>%
    layer_reshape(outputShape) %>%
    compile(loss = "mse", optimizer = "adam", metrics = list("mean_absolute_error", "mean_squared_error"))

model1 %>% summary
fit(model1, x_train, y_train, epochs = 3, validation_split = 0.2, verbose = 1)

model2 = keras_model_sequential() %>%
## tbd layer_input  --> layer_rehsape --> layer_dense (which seems to work best with non-matrix valued inputs
    layer_dense(units = 64, activation = "relu", input_shape = inputShape) %>%
    layer_dense(units = 256, activation = "relu") %>%
    layer_dense(units = outputShape[2]) %>%
# layer_dense(units = prod(outputShape)) %>%
# layer_reshape(outputShape) %>%
    compile(loss = "mse", optimizer = "adam", metrics = list("mean_absolute_error", "mean_squared_error"))

model2 %>% summary

fit(model2, x_train, y_train, epochs = 3, validation_split = 0.2, verbose = 1)

Summary of model1 is

> model1 %>% summary
Model: "sequential_42"
________________________________________________________________________________
Layer (type)                        Output Shape                    Param #
================================================================================
dense_126 (Dense)                   (None, 10, 64)                  448
________________________________________________________________________________
dense_127 (Dense)                   (None, 10, 256)                 16640
________________________________________________________________________________
dense_128 (Dense)                   (None, 10, 30)                  7710
________________________________________________________________________________
reshape_29 (Reshape)                (None, 10, 3)                   0
================================================================================
Total params: 24,798
Trainable params: 24,798
Non-trainable params: 0
________________________________________________________________________________

Shape of mode2 is

> model2 %>% summary
Model: "sequential_43"
________________________________________________________________________________
Layer (type)                        Output Shape                    Param #
================================================================================
dense_129 (Dense)                   (None, 10, 64)                  448
________________________________________________________________________________
dense_130 (Dense)                   (None, 10, 256)                 16640
________________________________________________________________________________
dense_131 (Dense)                   (None, 10, 3)                   771
================================================================================
Total params: 17,859
Trainable params: 17,859
Non-trainable params: 0
________________________________________________________________________________

Although both models have the same input and output shape, model1 fails to train with with

Error in py_call_impl(callable, dots$args, dots$keywords) :
  ValueError: in user code:

    C:\Users\brandl\AppData\Local\r-miniconda\envs\r-reticulate\lib\site-packages\tensorflow\python\keras\engine\training.py:571 train_function  *
        outputs = self.distribute_strategy.run(
    C:\Users\brandl\AppData\Local\r-miniconda\envs\r-reticulate\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:951 run  **
        return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    C:\Users\brandl\AppData\Local\r-miniconda\envs\r-reticulate\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:2290 call_for_each_replica
        return self._call_for_each_replica(fn, args, kwargs)
    C:\Users\brandl\AppData\Local\r-miniconda\envs\r-reticulate\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:2649 _call_for_each_replica
        return fn(*args, **kwargs)
    C:\Users\brandl\AppData\Local\r-miniconda\envs\r-reticulate\lib\site-packages\tensorflow\python\keras\engine\training.py:531 train_s

By flattening the input it works (see the commented line where x_train is defined). However,  I wonder why we can't use matrix-shaped input value here for the dense layer (or how to do so correctly)?

Note: The example is written using https://keras.rstudio.com/ but since it's a rather 1:1 wrapper API, I'd happy with a python answer as well.

Body:
According to the Dense docs (https://www.tensorflow.org/api_docs/python/tf/keras/layers/Dense):

If the input to the layer has a rank greater than 2, then Dense computes the dot product between the inputs and the kernel along the last axis of the inputs and axis 1 of the kernel (using tf.tensordot)

Therefore, if the input tensor has a shape (a,b,c) and the Dense layer has d units, the output tensor has a shape (a,b,d). If you pass your tensor through multiple Dense layers, only the last dimension will change.

Now, if the code runs with a flattened x, a potential problem is the shape mismatch. Indeed, y_train seems to not have the same dimensions as the output of the network.

According to this

x_train = tf$constant(mx, shape = as.integer(c(n / nb, nb, 6)))
y_train = tf$constant(my, shape = as.integer(c(n / nb, nb, 3)))

x_train and y_train have identical dimensions except for the last one. Then, for the predictions and y_train to have the same dimensions, your model should end with sth like

layer_dense(units = outputShape[3]) %>%

instead of

layer_dense(units = prod(outputShape)) %>%
layer_reshape(outputShape) %>%

That's just the technical side though. Not sure if conceptually it is what you are after.


来源: stackexchange

答:
To strip out the csv fields you asked for to the output -

```<code>$: sed -En '/ loss: [.0-9]+ - accuracy: [.0-9]+ /{ s/^.* loss: ([.0-9]+) - accuracy: ([.0-9]+) .*$/\1,\2/; p; }' the.log
0.3430,0.8753
0.0849,0.9739
0.0742,0.9791
0.0565,0.9841
0.0409,0.9881
</code>```

Plenty of ways to improve the robustness and flexibility of this, but it works on the sample provided.

ContentLicense: CC BY-SA 4.0

Title: How to parse a text file using regex

Body:
I'm trying to parse some log files to get some numbers out and into a CSV file. The log files have a lot of log messages but below is an excerpt of the lines that need to parse.

I'm trying to get the loss and accuracy numbers out of this text file below into a CSV. Any recommendations for bash or python tricks?

1500/1500 [==============================] - 1802s 1s/step - loss: 0.3430 - accuracy: 0.8753 - val_loss: 0.1110 - val_accuracy: 0.9670
Epoch 00002: saving model to /root/data-cache/data/tmp/models/ota-cfo-10k_20200527-001913_02_0.069291627_0.98.h5
1500/1500 [==============================] - 1679s 1s/step - loss: 0.0849 - accuracy: 0.9739 - val_loss: 0.0693 - val_accuracy: 0.9807
Epoch 00003: saving model to /root/data-cache/data/tmp/models/ota-cfo-10k_20200527-001913_03_0.055876694_0.98.h5
1500/1500 [==============================] - 1674s 1s/step - loss: 0.0742 - accuracy: 0.9791 - val_loss: 0.0559 - val_accuracy: 0.9845
Epoch 00004: saving model to /root/data-cache/data/tmp/models/ota-cfo-10k_20200527-001913_04_0.053867317_0.99.h5
1500/1500 [==============================] - 1671s 1s/step - loss: 0.0565 - accuracy: 0.9841 - val_loss: 0.0539 - val_accuracy: 0.9850
Epoch 00005: saving model to /root/data-cache/data/tmp/models/ota-cfo-10k_20200527-001913_05_0.053266536_0.99.h5
1500/1500 [==============================] - 1675s 1s/step - loss: 0.0409 - accuracy: 0.9881 - val_loss: 0.0533 - val_accuracy: 0.9855

Here is what I tried in python:

import re
text = r"""00 [==============================] - 1802s 1s/step - loss: 0.3430 - accuracy: 0.8753 - val_loss: 0.1110 - val_accuracy: 0.9670
Epoch 00002: saving model to /root/data-cache/data/tmp/models/ota-cfo-10k_20200527-001913_02_0.069291627_0.98.h5
1500/1500 [==============================] - 1679s 1s/step - loss: 0.0849 - accuracy: 0.9739 - val_loss: 0.0693 - val_accuracy: 0.9807
Epoch 00003: saving model to /root/data-cache/data/tmp/models/ota-cfo-10k_20200527-001913_03_0.055876694_0.98.h5
1500/1500 [==============================] - 1674s 1s/step - loss: 0.0742 - accuracy: 0.9791 - val_loss: 0.0559 - val_accuracy: 0.9845
Epoch 00004: saving model to /root/data-cache/data/tmp/models/ota-cfo-10k_20200527-001913_04_0.053867317_0.99.h5
1500/1500 [==============================] - 1671s 1s/step - loss: 0.0565 - accuracy: 0.9841 - val_loss: 0.0539 - val_accuracy: 0.9850
Epoch 00005: saving model to /root/data-cache/data/tmp/models/ota-cfo-10k_20200527-001913_05_0.053266536_0.99.h5"""
regular_exp = re.compile(r'^.*val_accuracy.*$', re.M)
for match in regular_exp.finditer(text)
   print(match)

Body:
To strip out the csv fields you asked for to the output -

$: sed -En '/ loss: [.0-9]+ - accuracy: [.0-9]+ /{ s/^.* loss: ([.0-9]+) - accuracy: ([.0-9]+) .*$/\1,\2/; p; }' the.log
0.3430,0.8753
0.0849,0.9739
0.0742,0.9791
0.0565,0.9841
0.0409,0.9881

Plenty of ways to improve the robustness and flexibility of this, but it works on the sample provided.


问:
Checking if float is equivalent to an integer value in python
In Python 3, I am checking whether a given value is triangular, that is, it can be represented as n * (n + 1) / 2 for some positive integer n.

Can I just write:

```<code>import math

def is_triangular1(x):
    num = (1 / 2) * (math.sqrt(8 * x + 1) - 1)
    return int(num) == num
</code>```

Or do I need to do check within a tolerance instead?

```<code>epsilon = 0.000000000001
def is_triangular2(x):
    num = (1 / 2) * (math.sqrt(8 * x + 1) - 1)
    return abs(int(num) - num) < epsilon
</code>```

I checked that both of the functions return same results for x up to 1,000,000. But I am not sure if generally speaking int(x) == x will always correctly determine whether a number is integer, because of the cases when for example 5 is represented as 4.99999999999997 etc.

As far as I know, the second way is the correct one if I do it in C, but I am not sure about Python 3.

答:
Both your implementations have problems.  It actually can happen that you end up with something like 4.999999999999997, so using int() is not an option.

I'd go for a completely different approach:  First assume that your number is triangular, and compute what n would be in that case.  In that first step, you can round generously, since it's only necessary to get the result right if the number actually is triangular.  Next, compute n * (n + 1) / 2 for this n, and compare the result to x.  Now, you are comparing two integers, so there are no inaccuracies left.

The computation of n can be simplified by expanding

```<code>(1/2) * (math.sqrt(8*x+1)-1) = math.sqrt(2 * x + 0.25) - 0.5
</code>```

and utilizing that

```<code>round(y - 0.5) = int(y)
</code>```

for positive y.

```<code>def is_triangular(x):
    n = int(math.sqrt(2 * x))
    return x == n * (n + 1) / 2
</code>```

Body:
In Python 3, I am checking whether a given value is triangular, that is, it can be represented as n * (n + 1) / 2 for some positive integer n.

Can I just write:

import math

def is_triangular1(x):
    num = (1 / 2) * (math.sqrt(8 * x + 1) - 1)
    return int(num) == num

Or do I need to do check within a tolerance instead?

epsilon = 0.000000000001
def is_triangular2(x):
    num = (1 / 2) * (math.sqrt(8 * x + 1) - 1)
    return abs(int(num) - num) < epsilon

I checked that both of the functions return same results for x up to 1,000,000. But I am not sure if generally speaking int(x) == x will always correctly determine whether a number is integer, because of the cases when for example 5 is represented as 4.99999999999997 etc.

As far as I know, the second way is the correct one if I do it in C, but I am not sure about Python 3.

Body:
Both your implementations have problems.  It actually can happen that you end up with something like 4.999999999999997, so using int() is not an option.

I'd go for a completely different approach:  First assume that your number is triangular, and compute what n would be in that case.  In that first step, you can round generously, since it's only necessary to get the result right if the number actually is triangular.  Next, compute n * (n + 1) / 2 for this n, and compare the result to x.  Now, you are comparing two integers, so there are no inaccuracies left.

The computation of n can be simplified by expanding

(1/2) * (math.sqrt(8*x+1)-1) = math.sqrt(2 * x + 0.25) - 0.5

and utilizing that

round(y - 0.5) = int(y)

for positive y.

def is_triangular(x):
    n = int(math.sqrt(2 * x))
    return x == n * (n + 1) / 2

ContentLicense: CC BY-SA 3.0


问:
XML namespace location after canonical form
Does turning XML into its Canonical involve the process of moving common/repeated XML namespaces in an XML document into a parent XML node?

The W3 XML specification for the C14N11 transform in section 4 and the subsets of it briefly goes over this, but it's hard to digest.

Am I correct in reading the specification that duplicate namespaces are propagated up?

For example:

```<code><Message xmlns="urn:abc">
    <head:CreatedDate xmlns:head="urn:iso:std:iso:20022:tech:xsd:head.001.001.01">2020-05-28T00:00:00</head:CreatedDate >
    <head:Two xmlns:head="urn:iso:std:iso:20022:tech:xsd:head.001.001.01"></head:Two>
</Message>
</code>```

Would turn into:

```<code><Message xmlns="urn:abc" xmlns:head="urn:iso:std:iso:20022:tech:xsd:head.001.001.01">
    <head:CreatedDate>2020-05-28T00:00:00</head:CreatedDate>
    <head:Two></head:Two>
</Message>
</code>```

After XML is in its Canonical form?

答:
None of this has anything to do with schemas. Schemas and namespaces are quite different things.

There's nothing in the C14N spec that says namespace declarations should be propagated upwards. All it says is that if the same namespace is present on a parent element and a child element, the one on the child is discarded.

Body:
Does turning XML into its Canonical involve the process of moving common/repeated XML namespaces in an XML document into a parent XML node?

The W3 XML specification for the C14N11 transform in section 4 and the subsets of it briefly goes over this, but it's hard to digest.

Am I correct in reading the specification that duplicate namespaces are propagated up?

For example:

<Message xmlns="urn:abc">
    2020-05-28T00:00:00

</Message>

Would turn into:

<Message xmlns="urn:abc" xmlns:head="urn:iso:std:iso:20022:tech:xsd:head.001.001.01">
    2020-05-28T00:00:00

</Message>

After XML is in its Canonical form?


问:
Not able to display a dicom image using cornerstone.js
I'm trying to display a Dicom Image using the cornerstone library. I have used the jsminimal example code from https://github.com/cornerstonejs/cornerstone/blob/master/example/jsminimal/index.html. The js files I've included are cornerstone.js and exampleImageIdLoader.js taken from the same link above.

```<code><!DOCTYPE HTML>
<html>
    <head>
        <link href="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body>
        <div class="container">

            <h1>
                jsminimal/index.html
            </h1>

            <h3>This is an example of the minimal use of cornerstone driven by javascript</h3>

            <br>
            <br>

            <h3>In this example, javascript is used to image enable a div.</h3>

            <br>
            <br>

            <div id="dicomImage" style="width:512px;height:512px">
            </div>
        </div>
    </body>
    <script src="cornerstone.js"></script>
    <script>window.cornerstone || document.write('<script src="https://unpkg.com/cornerstone-core@2.3.0">\x3C/script>')</script>

    <script src="exampleImageIdLoader.js"></script>
    <script>
    const imageId = 'vhf.151.dcm';
    const element = document.getElementById('dicomImage');
    cornerstone.enable(element);
    cornerstone.loadImage(imageId).then(function(image) {
        cornerstone.displayImage(element, image);
    });
</script>
</html>
</code>```

The errors I'm facing are :

Error: loadImageFromImageLoader: no image loader for imageId cornerstone.js:3361:11

loadImageFromImageLoader file:/absolute path to cornerstone.js/cornerstone.js:3361

loadImage file:/absolute path to cornerstone.js>/cornerstone.js:3402

 file:/absolute path to the html file/imageViewer.html:35

答:
Try to insert cornerstoneWADOImageLoader.

Documentation: https://github.com/cornerstonejs/cornerstoneWADOImageLoader

Body:
I'm trying to display a Dicom Image using the cornerstone library. I have used the jsminimal example code from https://github.com/cornerstonejs/cornerstone/blob/master/example/jsminimal/index.html. The js files I've included are cornerstone.js and exampleImageIdLoader.js taken from the same link above.

<!DOCTYPE HTML>

        <link href="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">

                jsminimal/index.html

This is an example of the minimal use of cornerstone driven by javascript

In this example, javascript is used to image enable a div.

The errors I'm facing are :

Error: loadImageFromImageLoader: no image loader for imageId cornerstone.js:3361:11

loadImageFromImageLoader file:/absolute path to cornerstone.js/cornerstone.js:3361

loadImage file:/absolute path to cornerstone.js>/cornerstone.js:3402

 file:/absolute path to the html file/imageViewer.html:35


问:
Vb.Net Web application with webform page add webapi 2.2

I have web application project in Vb.Net

I want to add web api to my project

Visual studio 2019 with .Net 4.7.2

but when  I run the application it throws an error :

Line 27:  Line 28:         ' Code that runs on application startup
  Line 29:         GlobalConfiguration.Configuration(AddressOf
  AppStart.WebApiConfig.Register) Line 30:

  ''GlobalConfiguration.Configuration(Register)

output :

Microsoft (R) Visual Basic Compiler version 14.8.3761 for Visual Basic
  2012 Copyright (c) Microsoft Corporation.  All rights reserved.

This compiler is provided as part of the Microsoft (R) .NET Framework,
  but only supports language versions up to Visual Basic 2012, which is
  no longer the latest version. For compilers that support newer
  versions of the Visual Basic programming language, see
  http://go.microsoft.com/fwlink/?LinkID=533241

C:project\webapp\global.asax(29) : error BC30545: Property access must
  assign to the property or use its value.

```<code>    GlobalConfiguration.Configuration(AddressOf AppStart.WebApiConfig.Register)
</code>```

I've downloaded all the packages from nuget:

Microsoft.asp.net.wabapi

Microsoft.asp.net.wabapi.clinet

Microsoft.asp.net.wabapi.Core

Microsoft.asp.net.wabapi.selfHost

global.asax

```<code>Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)

        ' Code that runs on application startup
        GlobalConfiguration.Configuration(AddressOf AppStart.WebApiConfig.Register)

End Sub
</code>```

webapiconfig class

```<code>Imports System.Web.Http

Namespace AppStart

    Public Class WebApiConfig

        Public Shared Sub Register(configuration As HttpConfiguration)

            '// Web API routes
            configuration.MapHttpAttributeRoutes()

            configuration.
                          Routes.
                          MapHttpRoute(
                                      "API Default",
                                      "webapi/{controller}/{id}",
                                       New With {Key .id = RouteParameter.Optional}
                          )
        End Sub

    End Class

End Namespace
</code>```

webconfig

```<code><system.webServer>
      <validation validateIntegratedModeConfiguration="false" />
      <handlers>

        <!--webapi-->
        <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
        <remove name="OPTIONSVerbHandler" />
        <remove name="TRACEVerbHandler" />
        <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
        <!-- end web api -->

</handlers>
<system.webServer>
</code>```

Thank you in advance for any help

答:
The only thing I did was to update the web.config:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
</code>```

by removing xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
</code>```

It looks like this line led to this error:

```<code>Microsoft (R) Visual Basic Compiler version 14.8.3761
for Visual Basic 2012 Copyright (c) Microsoft Corporation.
All rights reserved.
which is no longer the latest version.
For compilers that support newer versions of the Visual Basic programming language, see
</code>```

Body:
I have web application project in Vb.Net

I want to add web api to my project

Visual studio 2019 with .Net 4.7.2

but when  I run the application it throws an error :

Line 27:  Line 28:         ' Code that runs on application startup
  Line 29:         GlobalConfiguration.Configuration(AddressOf
  AppStart.WebApiConfig.Register) Line 30:

  ''GlobalConfiguration.Configuration(Register)

output :

Microsoft (R) Visual Basic Compiler version 14.8.3761 for Visual Basic
  2012 Copyright (c) Microsoft Corporation.  All rights reserved.

This compiler is provided as part of the Microsoft (R) .NET Framework,
  but only supports language versions up to Visual Basic 2012, which is
  no longer the latest version. For compilers that support newer
  versions of the Visual Basic programming language, see
  http://go.microsoft.com/fwlink/?LinkID=533241

C:project\webapp\global.asax(29) : error BC30545: Property access must
  assign to the property or use its value.

    GlobalConfiguration.Configuration(AddressOf AppStart.WebApiConfig.Register)

I've downloaded all the packages from nuget:

Microsoft.asp.net.wabapi

Microsoft.asp.net.wabapi.clinet

Microsoft.asp.net.wabapi.Core

Microsoft.asp.net.wabapi.selfHost

global.asax

Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)

        ' Code that runs on application startup
        GlobalConfiguration.Configuration(AddressOf AppStart.WebApiConfig.Register)

End Sub

webapiconfig class

Imports System.Web.Http

Namespace AppStart

    Public Class WebApiConfig

        Public Shared Sub Register(configuration As HttpConfiguration)

            '// Web API routes
            configuration.MapHttpAttributeRoutes()

            configuration.
                          Routes.
                          MapHttpRoute(
                                      "API Default",
                                      "webapi/{controller}/{id}",
                                       New With {Key .id = RouteParameter.Optional}
                          )
        End Sub

    End Class

End Namespace

webconfig

<system.webServer>
      <validation validateIntegratedModeConfiguration="false" />
      <handlers>

        <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
        <remove name="OPTIONSVerbHandler" />
        <remove name="TRACEVerbHandler" />
        <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

</handlers>
<system.webServer>

Thank you in advance for any help

Body:
The only thing I did was to update the web.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">

by removing xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"

<?xml version="1.0" encoding="utf-8"?>
<configuration>

It looks like this line led to this error:

Microsoft (R) Visual Basic Compiler version 14.8.3761
for Visual Basic 2012 Copyright (c) Microsoft Corporation.
All rights reserved.
which is no longer the latest version.
For compilers that support newer versions of the Visual Basic programming language, see


问:
HTML Validation: Why is it not valid to put an interactive element inside an interactive element?
Disclaimer: I understand that it is not valid HTML. I am trying to understand why is it not allowed?

W3C suggests that an interactive element like button or a mustn't contain another interactive element.

I could find a lot of resources mentioning this rule and some workarounds, also some resources related to how this impacts accessibility and screenreaders, but almost all of those resources talk about the fact that this is a requirement but do not explain why.

https://adrianroselli.com/2016/12/be-wary-of-nesting-roles.html

https://codepen.io/vloux/pen/wXGyOv

Nesting  inside <button> doesn't work in Firefox

https://github.com/dequelabs/axe-core/issues/601

I wasn't really able to find an explanation for why is it not allowed? does it lead to any usability problems?

This is a related question:
Why should interactive element not be used within an anchor?

The accepted answer is satisfactory but is not enough to make this rule a requirement. The described situation can be avoided using proper event handling.

Also, if nested interactive content is invalid, how are we supposed to have something like this:

A card which is clickable as a whole, and also has a clickable secondary CTA inside it.
I know a workaround would be to have a primary and secondary CTA inside the card, but shouldn't the above be allowed as well?

Here is a fiddle:
https://jsfiddle.net/t9qbwas5/2/

```<code><button type="button" class="card">
  The card itself is the primary CTA.
  <br/>
  <br/>
  some important content to read through.
  some important content to read through.
  some important content to read through.
  <div class="cta">
   Secondary CTA
  </div>
</button>

.cta {
  padding: 4px;
  background: #00a9a9;
  color: white;
  width: 80px;
  margin: auto;
  margin-top: 8px;
  margin-bottom: 8px;
}

.card {
  width: 200px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
}
</code>```

In the above example, I am achieving this by using a clickable div inside the button, but that is not semantic (?) and also functionality wise, it is an interactive element inside another one. I am trying to understand that even if I use this workaround, is it fundamentally wrong to have nested interactive elements? is it a bad design/usability practice?

答:
The answer is actually quite simple in principle. When you click on the interactive element inside another interactive element which function should you trigger?

In your example if I click on Secondary CTA should it fire the function for secondary CTA or should it fire the function for the card?

The fiddle below should demonstrate the problem, tab into the first button and press enter, then tab into the CTA and press Enter.

Obviously you could work around this but I think it demonstates the point.

$('.card').on('click', function(){
    console.log("card");
});
$('.cta').on('click', function(){
    console.log("cta");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.cta {
  padding: 4px;
  background: #00a9a9;
  color: white;
  width: 80px;
  margin: auto;
  margin-top: 8px;
  margin-bottom: 8px;
}

.card {
  width: 200px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
}</code>```

<button type="button" class="card">
  The card itself is the primary CTA.

  some important content to read through.
  some important content to read through.
  some important content to read through.

   Secondary CTA

</button>```

This principle then continues through to Screen Readers and other Augmentative and alternative communication (AAC) devices.

Should they take into account the parent element when describing the child element? Should they allow the use of Space to activate if you nest a checkbox within a <button>, should Enter then affect only the button or both?

Body:
Disclaimer: I understand that it is not valid HTML. I am trying to understand why is it not allowed?

W3C suggests that an interactive element like button or a mustn't contain another interactive element.

I could find a lot of resources mentioning this rule and some workarounds, also some resources related to how this impacts accessibility and screenreaders, but almost all of those resources talk about the fact that this is a requirement but do not explain why.

https://adrianroselli.com/2016/12/be-wary-of-nesting-roles.html

https://codepen.io/vloux/pen/wXGyOv

Nesting  inside <button> doesn't work in Firefox

https://github.com/dequelabs/axe-core/issues/601

I wasn't really able to find an explanation for why is it not allowed? does it lead to any usability problems?

This is a related question:
Why should interactive element not be used within an anchor?

The accepted answer is satisfactory but is not enough to make this rule a requirement. The described situation can be avoided using proper event handling.

Also, if nested interactive content is invalid, how are we supposed to have something like this:

A card which is clickable as a whole, and also has a clickable secondary CTA inside it.
I know a workaround would be to have a primary and secondary CTA inside the card, but shouldn't the above be allowed as well?

Here is a fiddle:
https://jsfiddle.net/t9qbwas5/2/

<button type="button" class="card">
  The card itself is the primary CTA.

  some important content to read through.
  some important content to read through.
  some important content to read through.

   Secondary CTA

</button>

.cta {
  padding: 4px;
  background: #00a9a9;
  color: white;
  width: 80px;
  margin: auto;
  margin-top: 8px;
  margin-bottom: 8px;
}

.card {
  width: 200px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
}

In the above example, I am achieving this by using a clickable div inside the button, but that is not semantic (?) and also functionality wise, it is an interactive element inside another one. I am trying to understand that even if I use this workaround, is it fundamentally wrong to have nested interactive elements? is it a bad design/usability practice?

Body:
The answer is actually quite simple in principle. When you click on the interactive element inside another interactive element which function should you trigger?

In your example if I click on Secondary CTA should it fire the function for secondary CTA or should it fire the function for the card?

The fiddle below should demonstrate the problem, tab into the first button and press enter, then tab into the CTA and press Enter.

Obviously you could work around this but I think it demonstates the point.

$('.card').on('click', function(){
    console.log("card");
});
$('.cta').on('click', function(){
    console.log("cta");
});

.cta {
  padding: 4px;
  background: #00a9a9;
  color: white;
  width: 80px;
  margin: auto;
  margin-top: 8px;
  margin-bottom: 8px;
}

.card {
  width: 200px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="card">
  The card itself is the primary CTA.
  <br/>
  <br/>
  some important content to read through.
  some important content to read through.
  some important content to read through.
  <div class="cta" tabindex="0">
   Secondary CTA
  </div>
</button>

This principle then continues through to Screen Readers and other Augmentative and alternative communication (AAC) devices.

Should they take into account the parent element when describing the child element? Should they allow the use of Space to activate if you nest a checkbox within a <button>, should Enter then affect only the button or both?


问:
Log4Net log showing up in console window
I have the opposite problem as most people do with Log4net. I have a basic rolling log appender, I use the INFO, WARN and ERROR levels in my code behind. I have debug turned off in the app.config. It STILL pushes the log data to the console window in addition to the rolling log appender.

How do I stop this behavior? It makes looking at the console window a nightmare.

My config:

<log4net debug="false">
  <appender name="RollingFileAppender"
            type="log4net.Appender.RollingFileAppender">
    <file type="log4net.Util.PatternString"
          value="milliondollars.log"/>
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
    <rollingStyle value="Composite"/>
    <filter type="log4net.Filter.LevelRangeFilter">
      <acceptOnMatch value="true" />
      <levelMin value="INFO" />
      <levelMax value="FATAL" />
    </filter>
    <datePattern value="yyyyMMdd"/>
    <maxSizeRollBackups value="100"/>
    <maximumFileSize value="15MB"/>
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date %-5level %logger: %message%newline" />
    </layout>
  </appender>
  <root>
    <level value="ALL" />
    <appender-ref ref="RollingFileAppender" />
  </root>
</log4net>
```

答:
Well, seems like you don't want to give up any more details...

I can think of the folloiwng possible reasons:

You have console appender listed either under any <logger> or <root> section

You register console appender programmatically

You have a logger wrapper, that always runs Console.Write line before logging


问:
Why am I getting an error when trying to compare to dictionary values?
I'm supposed to:

Write a function, precipiation(d, a, b) that takes parameters:

d: Dictionary mapping a season to an amount of precipitation for that season.
a: One season
b: Another season

Your function should return True if the rainfall in season a was greater than it was in season b, and False otherwise. If the rainfall was equal, return False.

Your function should handle the following errors the following ways:

If either a or b is not a valid season in the dictionary, you should return an error message (as a string) formatted exactly as:
"Error: Key is not in Dictionary."

If the values for the rainfall in each season are not valid for comparison, that is, one of them is not a number, return an error message (as a string) formatted exactly as:
"Error: Invalid data types in Dictionary?"

You may assume that no test case will produce both types of errors (so you do not need to decide whether or not to return a Key Error or Invalid Type error when you encounter both). However, you should not make any assumptions about the seasons that exist--sometimes there may be a 'potato' season.

I wrote a function that is mostly correct

```<code>def precipitation(d, a, b):

    try:
        if d[a] > d[b]:
            return True
        else:
            return False

    except:
        if a not in d or b not in d:
            return ("Error: Key is not in Dictionary.")

        if d[a] not in (int) or d[b] not in (int):
            return ("Error: Invalid data types in Dictionary?")
</code>```

When I run this function with test case

```<code>precipitation({"Spring": 'cats', "Summer": 313, "Fall": 1457, "Winter": 354}, "Summer", "Spring") == 'Error: Invalid data types in Dictionary?'
</code>```

I get an error
 argument of type 'type' is not iterable

How can I fix this and what is causing the problem

答:
This is your problem:

```<code>if d[a] not in (int)
</code>```

int is not a container, it's a type, so d[a] can't be in it.*

Are you trying to make sure it's an integer? Then try isinstance():

```<code>if not isinstance(d[a], int) ...
</code>```

* You could write a metaclass that had a __contains__() method that let you treat types as containers and check for instance types in this way, which is actually a kind of interesting idea, but int does not do that.

Body:
I'm supposed to:

Write a function, precipiation(d, a, b) that takes parameters:

d: Dictionary mapping a season to an amount of precipitation for that season.
a: One season
b: Another season

Your function should return True if the rainfall in season a was greater than it was in season b, and False otherwise. If the rainfall was equal, return False.

Your function should handle the following errors the following ways:

If either a or b is not a valid season in the dictionary, you should return an error message (as a string) formatted exactly as:
"Error: Key is not in Dictionary."

If the values for the rainfall in each season are not valid for comparison, that is, one of them is not a number, return an error message (as a string) formatted exactly as:
"Error: Invalid data types in Dictionary?"

You may assume that no test case will produce both types of errors (so you do not need to decide whether or not to return a Key Error or Invalid Type error when you encounter both). However, you should not make any assumptions about the seasons that exist--sometimes there may be a 'potato' season.

I wrote a function that is mostly correct

def precipitation(d, a, b):

    try:
        if d[a] > d[b]:
            return True
        else:
            return False

    except:
        if a not in d or b not in d:
            return ("Error: Key is not in Dictionary.")

        if d[a] not in (int) or d[b] not in (int):
            return ("Error: Invalid data types in Dictionary?")

When I run this function with test case

precipitation({"Spring": 'cats', "Summer": 313, "Fall": 1457, "Winter": 354}, "Summer", "Spring") == 'Error: Invalid data types in Dictionary?'

I get an error
 argument of type 'type' is not iterable

How can I fix this and what is causing the problem

Body:
This is your problem:

if d[a] not in (int)

int is not a container, it's a type, so d[a] can't be in it.*

Are you trying to make sure it's an integer? Then try isinstance():

if not isinstance(d[a], int) ...

* You could write a metaclass that had a __contains__() method that let you treat types as containers and check for instance types in this way, which is actually a kind of interesting idea, but int does not do that.


问:
Train microsoft LUIS to differentiate don't want and want
Suppose we have an utterance like I don't want a car but I want a bike. We would have an entity list having 'Car and bike' to find out the model the user wants or not. However, how shall we determine entity for DON'T WANT and WANT. How do we know the user said he 'does not' want car, he 'wants' bike. Can we train Luis on negation and negatives?</p>

答: Not really except if you expect me two entities. The best way I would do it it is by splitting the sentence in two through words like and or but, then identify the intent for each and then detect if there is any negative entities</p>


问:
ASP.NET MVC Cannot redirect after HTTP headers
I am getting this warning in IIS can it be related to requesting cookies from the browser or how I am using Response.Redirect? From some research I see suggestion that I need to add Response.Buffer = true; Is that correct?

Code

```<code>    public ActionResult GetTemplateById(string TemplateId)
    {
        string loginUrl = ConfigurationManager.AppSettings["loginUrlCottTemplateId"];
        Request.Cookies.Add(new HttpCookie("ev", "sJlp+HNulad4GaX2RCjjlQ=="));
        if (Request.Cookies["customerguid"] != null)
        {
            HttpCookie cookie = Request.Cookies["customerguid"];
            string cookieValue = cookie.Value;
            cookieValue = cookieValue.Replace("%2D", "-");
        }
        else
        {
            Response.Redirect(loginUrl + TemplateId);

        }

        if (!AuthenticationRep.IsUserValid(Request))
        {
            return Redirect(storeProductLink);

        }
        var memoryStream = new System.IO.MemoryStream(fm.FileData);
        return new FileStreamResult(memoryStream, "application/pdf");
    }
</code>```

IIS exception

Exception message: Cannot redirect after HTTP headers have been sent.

Thread information:

  Thread ID: 213

  Thread account name: IIS APPPOOL.NET v4.5

  Is impersonating: False

Stack trace:

at System.Web.HttpResponse.Redirect(String url, Boolean endResponse, Boolean permanent)

答:
In your ASP.NET MVC application you are redirecting using Response.Redirect(someurl).

When used in an ASP.NET Web Forms application, any code after Response.Redirect(someurl) is never executed. However when you use the same in ASP.NET MVC the code execution will continue even after sending the redirect response. To know why, go through this.

Your code is trying to redirect two times in the same ActionResult, through -

```<code>Response.Redirect(loginUrl + TemplateId);
</code>```

and

```<code>return Redirect(storeProductLink);
</code>```

and I believe that is throwing this error.

Please change Response.Redirect(loginUrl + TemplateId) to return Redirect(loginUrl + TemplateId) and check if  this fixes your problem.

Body:
I am getting this warning in IIS can it be related to requesting cookies from the browser or how I am using Response.Redirect? From some research I see suggestion that I need to add Response.Buffer = true; Is that correct?

Code

    public ActionResult GetTemplateById(string TemplateId)
    {
        string loginUrl = ConfigurationManager.AppSettings["loginUrlCottTemplateId"];
        Request.Cookies.Add(new HttpCookie("ev", "sJlp+HNulad4GaX2RCjjlQ=="));
        if (Request.Cookies["customerguid"] != null)
        {
            HttpCookie cookie = Request.Cookies["customerguid"];
            string cookieValue = cookie.Value;
            cookieValue = cookieValue.Replace("%2D", "-");
        }
        else
        {
            Response.Redirect(loginUrl + TemplateId);

        }

        if (!AuthenticationRep.IsUserValid(Request))
        {
            return Redirect(storeProductLink);

        }
        var memoryStream = new System.IO.MemoryStream(fm.FileData);
        return new FileStreamResult(memoryStream, "application/pdf");
    }

IIS exception

Exception message: Cannot redirect after HTTP headers have been sent.

Thread information:

  Thread ID: 213

  Thread account name: IIS APPPOOL.NET v4.5

  Is impersonating: False

Stack trace:

at System.Web.HttpResponse.Redirect(String url, Boolean endResponse, Boolean permanent)

Body:
In your ASP.NET MVC application you are redirecting using Response.Redirect(someurl).

When used in an ASP.NET Web Forms application, any code after Response.Redirect(someurl) is never executed. However when you use the same in ASP.NET MVC the code execution will continue even after sending the redirect response. To know why, go through this.

Your code is trying to redirect two times in the same ActionResult, through -

Response.Redirect(loginUrl + TemplateId);

and

return Redirect(storeProductLink);

and I believe that is throwing this error.

Please change Response.Redirect(loginUrl + TemplateId) to return Redirect(loginUrl + TemplateId) and check if  this fixes your problem.


问:
Prolog - Whats the logic behind this
I tried to understand how this code works but i failed.
It concatenates two lists and then it reverses the result.

```<code>reverse(L, RL):- reverse(L, [], RL).
reverse([], RL, RL).
reverse([H|T], S, RL):- reverse(T, [H|S], RL).

concat([], L, L).
concat([H|T1], L2, [H|T]):- concat(T1, L2, T).

concat_reverse(L1,L2,L):-concat(L1,L2,LN),reverse(LN,L)
</code>```

My teacher told me to go to debug mode and trace the query to understand but it didnt helped.

here is an example

```<code>5 ?- trace,concat_reverse([1,3],[4,5],S).
   Call: (7) concat_reverse([1, 3], [4, 5], _G1444) ? creep
   Call: (8) concat([1, 3], [4, 5], _G1569) ? creep
   Call: (9) concat([3], [4, 5], _G1564) ? creep
   Call: (10) concat([], [4, 5], _G1567) ? creep
   Exit: (10) concat([], [4, 5], [4, 5]) ? creep
   Exit: (9) concat([3], [4, 5], [3, 4, 5]) ? creep
   Exit: (8) concat([1, 3], [4, 5], [1, 3, 4, 5]) ? creep
   Call: (8) reverse([1, 3, 4, 5], _G1444) ? creep
   Call: (9) reverse([1, 3, 4, 5], [], _G1444) ? creep
   Call: (10) reverse([3, 4, 5], [1], _G1444) ? creep
   Call: (11) reverse([4, 5], [3, 1], _G1444) ? creep
   Call: (12) reverse([5], [4, 3, 1], _G1444) ? creep
   Call: (13) reverse([], [5, 4, 3, 1], _G1444) ? creep
   Exit: (13) reverse([], [5, 4, 3, 1], [5, 4, 3, 1]) ? creep
   Exit: (12) reverse([5], [4, 3, 1], [5, 4, 3, 1]) ? creep
   Exit: (11) reverse([4, 5], [3, 1], [5, 4, 3, 1]) ? creep
   Exit: (10) reverse([3, 4, 5], [1], [5, 4, 3, 1]) ? creep
   Exit: (9) reverse([1, 3, 4, 5], [], [5, 4, 3, 1]) ? creep
   Exit: (8) reverse([1, 3, 4, 5], [5, 4, 3, 1]) ? creep
   Exit: (7) concat_reverse([1, 3], [4, 5], [5, 4, 3, 1]) ? creep
S = [5, 4, 3, 1].
</code>```

答:
```<code>
concat_reverse(L1,L2,L) :-
        concat_reverse(L1,L2,[],L).

concat_reverse([],[],L,L).
concat_reverse([],[B|R2],L3,L) :-
        concat_reverse([],R2,[B|L3],L).
concat_reverse([A|R1],L2,L3,L) :-
        concat_reverse(R1,L2,[A|L3],L).
</code>```

Title: Prolog - Whats the logic behind this

Body:
I tried to understand how this code works but i failed.
It concatenates two lists and then it reverses the result.

reverse(L, RL):- reverse(L, [], RL).
reverse([], RL, RL).
reverse([H|T], S, RL):- reverse(T, [H|S], RL).

concat([], L, L).
concat([H|T1], L2, [H|T]):- concat(T1, L2, T).

concat_reverse(L1,L2,L):-concat(L1,L2,LN),reverse(LN,L)

My teacher told me to go to debug mode and trace the query to understand but it didnt helped.

here is an example

5 ?- trace,concat_reverse([1,3],[4,5],S).
   Call: (7) concat_reverse([1, 3], [4, 5], _G1444) ? creep
   Call: (8) concat([1, 3], [4, 5], _G1569) ? creep
   Call: (9) concat([3], [4, 5], _G1564) ? creep
   Call: (10) concat([], [4, 5], _G1567) ? creep
   Exit: (10) concat([], [4, 5], [4, 5]) ? creep
   Exit: (9) concat([3], [4, 5], [3, 4, 5]) ? creep
   Exit: (8) concat([1, 3], [4, 5], [1, 3, 4, 5]) ? creep
   Call: (8) reverse([1, 3, 4, 5], _G1444) ? creep
   Call: (9) reverse([1, 3, 4, 5], [], _G1444) ? creep
   Call: (10) reverse([3, 4, 5], [1], _G1444) ? creep
   Call: (11) reverse([4, 5], [3, 1], _G1444) ? creep
   Call: (12) reverse([5], [4, 3, 1], _G1444) ? creep
   Call: (13) reverse([], [5, 4, 3, 1], _G1444) ? creep
   Exit: (13) reverse([], [5, 4, 3, 1], [5, 4, 3, 1]) ? creep
   Exit: (12) reverse([5], [4, 3, 1], [5, 4, 3, 1]) ? creep
   Exit: (11) reverse([4, 5], [3, 1], [5, 4, 3, 1]) ? creep
   Exit: (10) reverse([3, 4, 5], [1], [5, 4, 3, 1]) ? creep
   Exit: (9) reverse([1, 3, 4, 5], [], [5, 4, 3, 1]) ? creep
   Exit: (8) reverse([1, 3, 4, 5], [5, 4, 3, 1]) ? creep
   Exit: (7) concat_reverse([1, 3], [4, 5], [5, 4, 3, 1]) ? creep
S = [5, 4, 3, 1].


问:
How to delete data from firebase android
I faced an issue when I had to delete that data which user entered in here this photo. If the user entered enrollment number 60 then I have to delete all data from marks where the enrollment number is 60.

It deletes the data which user entered and it verifies that enrollment from marks and delete all data where enrollment is 66 it means delete that document or node.

I tried the following that did not work.

reff.child("Marks").removeValue().equals(et1);

答:
Try this code.</p>

```<code>int enrollmentId = Integer.parseInt( et1.getText().toString() );
reff.child("Marks").orderByChild("enrollment").equalTo(enrollmentId)
.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot)
                {
                    for (DataSnapshot ds : dataSnapshot.getChildren())
                    {
                        ds.getRef().removeValue();
                        Toast.makeText(context, "Deleted", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError)
                {
                    Toast.makeText(context, "Failed to delete", Toast.LENGTH_SHORT).show();
                }
                });
</code>```

Body:
Try this code.

int enrollmentId = Integer.parseInt( et1.getText().toString() );
reff.child("Marks").orderByChild("enrollment").equalTo(enrollmentId)
.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot)
                {
                    for (DataSnapshot ds : dataSnapshot.getChildren())
                    {
                        ds.getRef().removeValue();
                        Toast.makeText(context, "Deleted", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError)
                {
                    Toast.makeText(context, "Failed to delete", Toast.LENGTH_SHORT).show();
                }
                });


问:
How does .apply work on a Pandas DataFrame.groupby?
```<code>              Count
League  Result
EPL     H      16
        D      9
        A      10
Champ   H      67
        D      15
        A      57
        H      87
La Liga D      35
        A      40

</code>```

I have a breakdown of football results for different leagues and a count of how many times that result occurred.

I want to see the proportion of home wins, draws, away wins as a percentage of the total games played. I have seen a solution to this below:

```<code>df.groupby("League").apply(lambda g: (g/g.sum()*100)
</code>```

At first glance, this made sense, but what exactly is g here? I assumed it was the H, D or A count and then the g.sum() summed all of the H,D,A counts grouped by each division. But, if g is just a value, how are we calling the method g.sum()? What exactly is g here?

答:
We usually do transform

```<code>df.Count=df.Count*100/df.groupby(level=0)['Count'].transform('sum')
</code>```

g in your function is the dataframe

```<code>df.groupby(level=0).apply(lambda  x : type(x))
Out[607]:
League
Champ      <class 'pandas.core.frame.DataFrame'>
EPL        <class 'pandas.core.frame.DataFrame'>
La Liga    <class 'pandas.core.frame.DataFrame'>
dtype: object
</code>```

Body:
              Count
League  Result
EPL     H      16
        D      9
        A      10
Champ   H      67
        D      15
        A      57
        H      87
La Liga D      35
        A      40

I have a breakdown of football results for different leagues and a count of how many times that result occurred.

I want to see the proportion of home wins, draws, away wins as a percentage of the total games played. I have seen a solution to this below:

df.groupby("League").apply(lambda g: (g/g.sum()*100)

At first glance, this made sense, but what exactly is g here? I assumed it was the H, D or A count and then the g.sum() summed all of the H,D,A counts grouped by each division. But, if g is just a value, how are we calling the method g.sum()? What exactly is g here?

Body:
We usually do transform

df.Count=df.Count*100/df.groupby(level=0)['Count'].transform('sum')

g in your function is the dataframe

df.groupby(level=0).apply(lambda  x : type(x))
Out[607]:
League
Champ      <class 'pandas.core.frame.DataFrame'>
EPL        <class 'pandas.core.frame.DataFrame'>
La Liga    <class 'pandas.core.frame.DataFrame'>
dtype: object


答:
To check if a parameter is a specific type, use isinstance - in checks if a specific value is present in an iterable.

```<code>if not isinstance(d[a], int) or not isinstance(d[b], int):
    return ("Error: Invalid data types in Dictionary?")
</code>```

Title: Why am I getting an error when trying to compare to dictionary values?

Body:
To check if a parameter is a specific type, use isinstance - in checks if a specific value is present in an iterable.

if not isinstance(d[a], int) or not isinstance(d[b], int):
    return ("Error: Invalid data types in Dictionary?")


问:
Two data should output unique values in csv using python
I'm a new python student and having issues in my csv output, it has duplicates of the matched condition I've searched it all over the internet already and found none.

How do i make this output, any method will do fine.

```<code>Data 1:
sitename,
www.google.com,
www.facebook.com,
www.twitter.com,
www.amazon.com

Data 2
sitename, founding date
www.google.com, 09/14/1998
www.amazon.com, 07/05/1994

if data 1 == data2['founding date']:
    writer.writerow([Data1, Founding Date])
else:
    writer.writerow([Data1, ''])
</code>```

the Output should be:

```<code>sitename, Founding date
www.google.com, 09/14/1998
www.facebook.com,
www.twitter.com,
www.amazon.com, 07/05/1994
</code>```

My Output:

```<code>sitename, Founding date,
www.google.com
www.google.com, 09/14/1998
www.facebook.com,
www.twitter.com,
www.amazon.com
www.amazon.com, 07/05/1994
</code>```

Thanks in advance!

答:
You can try

```<code>data1 = '''
sitename,
www.google.com,
www.facebook.com,
www.twitter.com,
www.amazon.com
'''

data2 = '''
sitename, founding date
www.google.com, 09/14/1998
www.amazon.com, 07/05/1994
'''

data1_rows = list(filter(str, data1.split("\n")))
data2_dict = {i.split(',')[0].strip(): i.split(',')[1] for i in list(filter(str, data2.split("\n"))) if i.count(",") > 0}
for i in data1_rows:
    val = i.strip(",")
    if val in data2_dict:
        writer.writerow([val, data2_dict[val]])
    else:
        writer.writerow([i])
</code>```

This solution is parsing the data2 to dict and then iterate over data1 lines and checking if the value in data1 row has a key in the data2_dict if so it writes to the file the data1 line value with the respective line for data2 else only data1 row value.

Body:
I'm a new python student and having issues in my csv output, it has duplicates of the matched condition I've searched it all over the internet already and found none.

How do i make this output, any method will do fine.

Data 1:
sitename,
www.google.com,
www.facebook.com,
www.twitter.com,
www.amazon.com

Data 2
sitename, founding date
www.google.com, 09/14/1998
www.amazon.com, 07/05/1994

if data 1 == data2['founding date']:
    writer.writerow([Data1, Founding Date])
else:
    writer.writerow([Data1, ''])

the Output should be:

sitename, Founding date
www.google.com, 09/14/1998
www.facebook.com,
www.twitter.com,
www.amazon.com, 07/05/1994

My Output:

sitename, Founding date,
www.google.com
www.google.com, 09/14/1998
www.facebook.com,
www.twitter.com,
www.amazon.com
www.amazon.com, 07/05/1994

Thanks in advance!

Body:
You can try

data1 = '''
sitename,
www.google.com,
www.facebook.com,
www.twitter.com,
www.amazon.com
'''

data2 = '''
sitename, founding date
www.google.com, 09/14/1998
www.amazon.com, 07/05/1994
'''

data1_rows = list(filter(str, data1.split("\n")))
data2_dict = {i.split(',')[0].strip(): i.split(',')[1] for i in list(filter(str, data2.split("\n"))) if i.count(",") > 0}
for i in data1_rows:
    val = i.strip(",")
    if val in data2_dict:
        writer.writerow([val, data2_dict[val]])
    else:
        writer.writerow([i])

This solution is parsing the data2 to dict and then iterate over data1 lines and checking if the value in data1 row has a key in the data2_dict if so it writes to the file the data1 line value with the respective line for data2 else only data1 row value.


问:
Improve regex for capturing files in a directory, excluding dotfiles
I am looking to get all non dot-files in a folder with a particular extension. So far my regex is:

(?<=\/|^)(?<!\.)(\w+(?:\.mov|\.py|))$

Is there a way to improve the above regex? What might be some examples where this regex might not work?

答:
The \w+ will only match one or more letters, digits or _. It will not match the rest of the chars that may constitute a valid file name. Also, your (?<!\.) lookbehind is redundant because the previous lookbehind already excludes a dot at that position.

Besides, you do not have to repeat the comma pattern, you may use grouping for extensions only.

You may use

```<code>(?<=\/|^)([^\/]+)(\.(?:mov|py))$
</code>```

See this regex demo

(?<=\/|^) - / or start  of string allowed immediately on the left

([^\/]+) - Group 1: any one or more chars other than /

(\.(?:mov|py)) - Group 2: a . char and then either mov or py

$ - end of string/

Note you may also replace (?<=\/|^) with (?<![^\/]) in real code since it will work the same with standalone strings. It will mess the demo results at regex101.com because there, you test against a single multiline string (that is why I added \n to the negated character class there, too).

Body:
The \w+ will only match one or more letters, digits or _. It will not match the rest of the chars that may constitute a valid file name. Also, your (?<!\.) lookbehind is redundant because the previous lookbehind already excludes a dot at that position.

Besides, you do not have to repeat the comma pattern, you may use grouping for extensions only.

You may use

(?<=\/|^)([^\/]+)(\.(?:mov|py))$

See this regex demo

(?<=\/|^) - / or start  of string allowed immediately on the left

([^\/]+) - Group 1: any one or more chars other than /

(\.(?:mov|py)) - Group 2: a . char and then either mov or py

$ - end of string/

Note you may also replace (?<=\/|^) with (?<![^\/]) in real code since it will work the same with standalone strings. It will mess the demo results at regex101.com because there, you test against a single multiline string (that is why I added \n to the negated character class there, too).


问:
How to find the source video size using VMR9 renderless mode
My application uses VMR9 Renderless mode to play a WMV file.  I build a filter graph with IGraphBuilder::RenderFile and control playback with IMediaControl.  Everything plays okay, but I can't figure out how to determine the source video size.  Any ideas?

Note: This question was asked before in How can I adjust the video to a specified size in VMR9 renderless mode?. But the solution was to use Windowless mode instead of Renderless mode, which would require rewriting my code.

答:
You could use the MediaInfo project at http://mediainfo.sourceforge.net/hr/Download/Windows and through the CS wrapper included in the VCS2010 or VCS2008 folders get all the information about a video you need.

EDIT: Sorry I thought you were on managed. But in either case the MediaInfo can be used, so maybe it helps.


问:
how to update the base of a sub-branch
In our repository, we want to develop a feature and keep it in its branch(branchX) until finished. Multiple people are working on this one branch and have sub-branches of it. PRs from the sub-branches will get merged into branchX. Now, a feature from sub-branchA is finished and got merged, how can now all other sub-branches pull-in that change?

On branchB (that started before the feature from branchA got merged into branchX) I have tried git rebase branchX but it doesn't seem like it changes anything or pulls in any data. How can I get branchB updated with the commits from branchA that now got merged into branch X?

tree:

```<code>                      - branchA -
          - branchX -/           \- branchA (branchA got merged into branchX)
master - /           \
                      - branchB (how do I pull the changes that branchA introduced into branchB)?
</code>```

答:
You checkout branchB and then run:

```<code>git rebase branchA
</code>```

git rebase branchX should work as well. Perhaps you should add one of those ascii trees explaining where the branches are in relation to each other?

Title: how to update the base of a sub-branch

Body:
In our repository, we want to develop a feature and keep it in its branch(branchX) until finished. Multiple people are working on this one branch and have sub-branches of it. PRs from the sub-branches will get merged into branchX. Now, a feature from sub-branchA is finished and got merged, how can now all other sub-branches pull-in that change?

On branchB (that started before the feature from branchA got merged into branchX) I have tried git rebase branchX but it doesn't seem like it changes anything or pulls in any data. How can I get branchB updated with the commits from branchA that now got merged into branch X?

tree:

                      - branchA -
          - branchX -/           \- branchA (branchA got merged into branchX)
master - /           \
                      - branchB (how do I pull the changes that branchA introduced into branchB)?

Body:
You checkout branchB and then run:

git rebase branchA

git rebase branchX should work as well. Perhaps you should add one of those ascii trees explaining where the branches are in relation to each other?


问:
How to change datetime values into a separately formatted value
I have a data set, which unfortunately has sporadic DateTime values, rather than int or str.

How could I go about editing the values, by iterating through the database and replacing the 2019-05-03 00:00:00 into 5-3, for example?

I have tried a few for loops but to no avail. Is there a pandas shortcut?

```<code>,age,menopause,tumor-size,inv-nodes,node-caps,deg-malig,breast,breast-quad,irradiat,Class
0,40-49,premeno,15-19,0-2,yes,3,right,left_up,no,recurrence-events
1,50-59,ge40,15-19,0-2,no,1,right,central,no,no-recurrence-events
2,50-59,ge40,35-39,0-2,no,2,left,left_low,no,recurrence-events
3,40-49,premeno,35-39,0-2,yes,3,right,left_low,yes,no-recurrence-events
4,40-49,premeno,30-34,2019-05-03 00:00:00,yes,2,left,right_up,no,recurrence-events
5,50-59,premeno,25-29,2019-05-03 00:00:00,no,2,right,left_up,yes,no-recurrence-events
6,50-59,ge40,40-44,0-2,no,3,left,left_up,no,no-recurrence-events
7,40-49,premeno,2014-10-01 00:00:00,0-2,no,2,left,left_up,no,no-recurrence-events
8,40-49,premeno,0-4,0-2,no,2,right,right_low,no,no-recurrence-events
9,40-49,ge40,40-44,15-17,yes,2,right,left_up,yes,no-recurrence-events
10,50-59,premeno,25-29,0-2,no,2,left,left_low,no,no-recurrence-events
11,60-69,ge40,15-19,0-2,no,2,right,left_up,no,no-recurrence-events
12,50-59,ge40,30-34,0-2,no,1,right,central,no,no-recurrence-events
13,50-59,ge40,25-29,0-2,no,2,right,left_up,no,no-recurrence-events
14,40-49,premeno,25-29,0-2,no,2,left,left_low,yes,recurrence-events
15,30-39,premeno,20-24,0-2,no,3,left,central,no,no-recurrence-events
16,50-59,premeno,2014-10-01 00:00:00,2019-05-03 00:00:00,no,1,right,left_up,no,no-recurrence-events
17,60-69,ge40,15-19,0-2,no,2,right,left_up,no,no-recurrence-events
18,50-59,premeno,40-44,0-2,no,2,left,left_up,no,no-recurrence-events
19,50-59,ge40,20-24,0-2,no,3,left,left_up,no,no-recurrence-events
20,50-59,lt40,20-24,0-2,?,1,left,left_low,no,recurrence-events
21,60-69,ge40,40-44,2019-05-03 00:00:00,no,2,right,left_up,yes,no-recurrence-events
22,50-59,ge40,15-19,0-2,no,2,right,left_low,no,no-recurrence-events
23,40-49,premeno,2014-10-01 00:00:00,0-2,no,1,right,left_up,no,no-recurrence-events
24,30-39,premeno,15-19,2019-08-06 00:00:00,yes,3,left,left_low,yes,recurrence-events
25,50-59,ge40,20-24,2019-05-03 00:00:00,yes,2,right,left_up,no,no-recurrence-events
</code>```

答:
This will only work on linux/unix systems so you might be ok on mac.</p>

```<code> df.loc[df['inv-nodes'].str.contains(':'),'inv-nodes'] = df.loc[df['inv-nodes'].str.contains(':')]['inv-nodes'].apply(lambda x: pd.to_datetime(x).strftime('%-m-%-d'))
</code>```

Body:
I have a data set, which unfortunately has sporadic DateTime values, rather than int or str.

How could I go about editing the values, by iterating through the database and replacing the 2019-05-03 00:00:00 into 5-3, for example?

I have tried a few for loops but to no avail. Is there a pandas shortcut?

,age,menopause,tumor-size,inv-nodes,node-caps,deg-malig,breast,breast-quad,irradiat,Class
0,40-49,premeno,15-19,0-2,yes,3,right,left_up,no,recurrence-events
1,50-59,ge40,15-19,0-2,no,1,right,central,no,no-recurrence-events
2,50-59,ge40,35-39,0-2,no,2,left,left_low,no,recurrence-events
3,40-49,premeno,35-39,0-2,yes,3,right,left_low,yes,no-recurrence-events
4,40-49,premeno,30-34,2019-05-03 00:00:00,yes,2,left,right_up,no,recurrence-events
5,50-59,premeno,25-29,2019-05-03 00:00:00,no,2,right,left_up,yes,no-recurrence-events
6,50-59,ge40,40-44,0-2,no,3,left,left_up,no,no-recurrence-events
7,40-49,premeno,2014-10-01 00:00:00,0-2,no,2,left,left_up,no,no-recurrence-events
8,40-49,premeno,0-4,0-2,no,2,right,right_low,no,no-recurrence-events
9,40-49,ge40,40-44,15-17,yes,2,right,left_up,yes,no-recurrence-events
10,50-59,premeno,25-29,0-2,no,2,left,left_low,no,no-recurrence-events
11,60-69,ge40,15-19,0-2,no,2,right,left_up,no,no-recurrence-events
12,50-59,ge40,30-34,0-2,no,1,right,central,no,no-recurrence-events
13,50-59,ge40,25-29,0-2,no,2,right,left_up,no,no-recurrence-events
14,40-49,premeno,25-29,0-2,no,2,left,left_low,yes,recurrence-events
15,30-39,premeno,20-24,0-2,no,3,left,central,no,no-recurrence-events
16,50-59,premeno,2014-10-01 00:00:00,2019-05-03 00:00:00,no,1,right,left_up,no,no-recurrence-events
17,60-69,ge40,15-19,0-2,no,2,right,left_up,no,no-recurrence-events
18,50-59,premeno,40-44,0-2,no,2,left,left_up,no,no-recurrence-events
19,50-59,ge40,20-24,0-2,no,3,left,left_up,no,no-recurrence-events
20,50-59,lt40,20-24,0-2,?,1,left,left_low,no,recurrence-events
21,60-69,ge40,40-44,2019-05-03 00:00:00,no,2,right,left_up,yes,no-recurrence-events
22,50-59,ge40,15-19,0-2,no,2,right,left_low,no,no-recurrence-events
23,40-49,premeno,2014-10-01 00:00:00,0-2,no,1,right,left_up,no,no-recurrence-events
24,30-39,premeno,15-19,2019-08-06 00:00:00,yes,3,left,left_low,yes,recurrence-events
25,50-59,ge40,20-24,2019-05-03 00:00:00,yes,2,right,left_up,no,no-recurrence-events

Body:
This will only work on linux/unix systems so you might be ok on mac.

 df.loc[df['inv-nodes'].str.contains(':'),'inv-nodes'] = df.loc[df['inv-nodes'].str.contains(':')]['inv-nodes'].apply(lambda x: pd.to_datetime(x).strftime('%-m-%-d'))


问:
Can I use await async inside an async function?
I'm an a newbie studying promises and async/await and would like to know if it's possible to change this code:

```<code>async function waiting() {
   let a = await new Promise(r => setTimeout(() => r('A'), 1e3))
   let b = await new Promise(r => setTimeout(() => r('B'), 2e3))
   let c = await new Promise(r => setTimeout(() => r('C'), 3e3))
   console.log(a, b, c)
}

waiting()
</code>```

And use something like this:

let a = await async () => setTimeout(() =>  'A', 1e3)

or similiar.

Update:

I also tried this:

let a = await (() => setTimeout(() => 'A', 1e3))()

I want to achieve the same with a shortened syntax.

答:
Not with setTimeout as it doesn't return anything, but with real async methods you can use Promise.all

The Promise.all() method returns a single Promise that fulfills when
  all of the promises passed as an iterable have been fulfilled

```<code>let [a, b, c] = await Promise.all([methodA(), methodB(), methodC()]);
</code>```

Body:
I'm an a newbie studying promises and async/await and would like to know if it's possible to change this code:

async function waiting() {
   let a = await new Promise(r => setTimeout(() => r('A'), 1e3))
   let b = await new Promise(r => setTimeout(() => r('B'), 2e3))
   let c = await new Promise(r => setTimeout(() => r('C'), 3e3))
   console.log(a, b, c)
}

waiting()

And use something like this:

let a = await async () => setTimeout(() =>  'A', 1e3)

or similiar.

Update:

I also tried this:

let a = await (() => setTimeout(() => 'A', 1e3))()

I want to achieve the same with a shortened syntax.

Body:
Not with setTimeout as it doesn't return anything, but with real async methods you can use Promise.all

The Promise.all() method returns a single Promise that fulfills when
  all of the promises passed as an iterable have been fulfilled

let [a, b, c] = await Promise.all([methodA(), methodB(), methodC()]);


问:
Visualizing headcount data over a particular time period
I have a data visualization question that I would like to get some input on. I'm currently using python pandas to clean up a data set then subsequently uploading it in SISENSE for use. What I am trying to do is visualize active jobs grouped by week/month based on the start and end dates of particular assignments. For example, I have a set of jobs with the following start dates, organized in rows within a dataframe:

Job ID Start Date  End Date

Job 1  5/25/2020   6/7/2020

Job 2  5/25/2020   5/31/2020

For the week of 5/25/2020 I have two active jobs, and for the week of 6/1/2020 I have 1 active job. The visualization should look like a bar chart with the x axis being the week/time period and y axis being the count of active jobs.

How can I best organize this into a data frame and visualize it?

答:
You will need a custom SQL in Sisense elasticube to make this work easily. You will then join your dataframe table with the dim_dates ( excel file from the below link)

This is similar to scenario described here : https://support.sisense.com/hc/en-us/articles/230644208-Date-Dimension-File

You custom SQL will be something like this :

```<code>  Select JobID,
         CAST(startdate as date) as Startdate,
         CAST(enddate as date) as Enddate,
         C.RECORD_DATE AS week_start
  FROM JOB j
  JOIN tbl_Calendar C ON c.RECORD_DATE BETWEEN j.StartDate and j.EndDate
  WHERE DATENAME(DW,C.RECORD_DATE) = 'MONDAY'
</code>```

Then you can just create a column chart and drop the fields week_start( you can format in a few different ways) under categories section and drop the field count(JOBID) under values section.

Body:
You will need a custom SQL in Sisense elasticube to make this work easily. You will then join your dataframe table with the dim_dates ( excel file from the below link)

This is similar to scenario described here : https://support.sisense.com/hc/en-us/articles/230644208-Date-Dimension-File

You custom SQL will be something like this :

  Select JobID,
         CAST(startdate as date) as Startdate,
         CAST(enddate as date) as Enddate,
         C.RECORD_DATE AS week_start
  FROM JOB j
  JOIN tbl_Calendar C ON c.RECORD_DATE BETWEEN j.StartDate and j.EndDate
  WHERE DATENAME(DW,C.RECORD_DATE) = 'MONDAY'

Then you can just create a column chart and drop the fields week_start( you can format in a few different ways) under categories section and drop the field count(JOBID) under values section.


问:
Local variable 'k1' value is not used
i am trying to build a simple menu with some conditions in it but i kept getting the error "Local variable 'k1' value is not used" at the used lines. I tried changing it to global but nothing happens.</p>

```<code>def menu():

    print(" 1.Köşelerde ve Boyut Ortalarında Ast/8 kadar donatı \n 2. Köşelerde Ast/3, Boyut Ortalarında "
          "Ast/16 kadar donatı, \n 3.Karşılıklı Ast/2 kadar donatu \n 4.Tüm boyutlarda Ast/4 kadar donatı"
          "\n 5.Köşelere eşit dağılmış olarak k1=1")
    choice = input()

    if choice == "1":
        print("Asst/8 seçtiniz")
        if n > 1:
            k1 = 1.08
        else:
            k1 = 1.07 + 1.349*n - 3.994*n*n + 4.062*n*n*n - 1.406*n*n*n*n

    elif choice == "2":
        print("Ast/3 seçtiniz")
        if n > 1:
            k1 = 1.025
        else:
            k1 = 1.028 + 0.633*n - 1.868*n*n + 1.816*n*n*n - 0.584*n*n*n*n

    elif choice == "3":
        print("karşılıklı")
        if mk/mu > 0.4:
            print("Ast/2 formülleri için geçerlilik şartı sağlanmadı.")
        else:
            k1 = 1 + ((mk/mu) * (mk/mu))

    elif choice == "4":
        print("Ast/4 için")
        if n > 1:
            k1 = 1.12
        else:
            k1 = 1.137 + 1.233*n - 3.445*n*n + 3.083*n*n*n - 0.87*n*n*n*n
            print(k1)

    elif choice == "5":
        k1 = 1

    else:
        print("Listede olmayan bir seçeneği seçemezsiniz.")
        menu()

menu()
Astk1 = Ast * k1
print(Astk1)
</code>```

答:
This is a scoping issue: k1 is defined within the menu() function, so without any intervention, it will only be available within that function (local scope). You could define a global variable (frowned upon), or even better, have menu() return the value of k1. e.g.:

```<code># just change the end of your function:
    else:
        print("Listede olmayan bir seçeneği seçemezsiniz.")
        k1 = menu()   # if k1 wasn't set, call menu again and use its value

    return k1         # return the value you settled on

my_k1 = menu()
Astk1 = Ast * my_k1
print(Astk1)
</code>```

Hope that helps, Happy Coding!

Title: Local variable 'k1' value is not used

Body:
i am trying to build a simple menu with some conditions in it but i kept getting the error "Local variable 'k1' value is not used" at the used lines. I tried changing it to global but nothing happens.

def menu():

    print(" 1.Köşelerde ve Boyut Ortalarında Ast/8 kadar donatı \n 2. Köşelerde Ast/3, Boyut Ortalarında "
          "Ast/16 kadar donatı, \n 3.Karşılıklı Ast/2 kadar donatu \n 4.Tüm boyutlarda Ast/4 kadar donatı"
          "\n 5.Köşelere eşit dağılmış olarak k1=1")
    choice = input()

    if choice == "1":
        print("Asst/8 seçtiniz")
        if n > 1:
            k1 = 1.08
        else:
            k1 = 1.07 + 1.349*n - 3.994*n*n + 4.062*n*n*n - 1.406*n*n*n*n

    elif choice == "2":
        print("Ast/3 seçtiniz")
        if n > 1:
            k1 = 1.025
        else:
            k1 = 1.028 + 0.633*n - 1.868*n*n + 1.816*n*n*n - 0.584*n*n*n*n

    elif choice == "3":
        print("karşılıklı")
        if mk/mu > 0.4:
            print("Ast/2 formülleri için geçerlilik şartı sağlanmadı.")
        else:
            k1 = 1 + ((mk/mu) * (mk/mu))

    elif choice == "4":
        print("Ast/4 için")
        if n > 1:
            k1 = 1.12
        else:
            k1 = 1.137 + 1.233*n - 3.445*n*n + 3.083*n*n*n - 0.87*n*n*n*n
            print(k1)

    elif choice == "5":
        k1 = 1

    else:
        print("Listede olmayan bir seçeneği seçemezsiniz.")
        menu()

menu()
Astk1 = Ast * k1
print(Astk1)

Body:
This is a scoping issue: k1 is defined within the menu() function, so without any intervention, it will only be available within that function (local scope). You could define a global variable (frowned upon), or even better, have menu() return the value of k1. e.g.:

# just change the end of your function:
    else:
        print("Listede olmayan bir seçeneği seçemezsiniz.")
        k1 = menu()   # if k1 wasn't set, call menu again and use its value

    return k1         # return the value you settled on

my_k1 = menu()
Astk1 = Ast * my_k1
print(Astk1)

Hope that helps, Happy Coding!


问:
Arithmetic on a pointer to void error when compile a third party library
I'm trying to compile a third party library, but for some reason I'm getting an error. The library is likely compiled differently. I've read up on the error but I can't seem to figure out what the issue is! :(

```<code>struct sfo_entry {
    char* key;
    size_t size;
    size_t area;
    void* value;
    enum sfo_value_format format;
    struct sfo_entry* next;
    struct sfo_entry* prev;
};

struct sfo {
    struct sfo_entry* entries;
};

bool sfo_load_from_memory(struct sfo* sfo, const void* data, size_t data_size) {
    struct sfo_header* hdr;
    struct sfo_table_entry* entry_table;
    struct sfo_table_entry* entry;

    entry_table = (struct sfo_table_entry*)(data + sizeof(*hdr));

    // ...

    return true;
}
</code>```

The error is as follows:

```<code> sfo.cpp:150:47: error: arithmetic on a pointer to void
         entry_table = (struct sfo_table_entry*)(data + sizeof(*hdr));
                                                 ~~~~ ^
</code>```

答:
From the C Standard (6.2.5 Types)

19 The void type comprises an empty set of values; it is an incomplete
  object type that cannot be completed.

To perform the pointer arithmetic there is required the size of the pointed object.

Some compilers allows to use pointers to void in the pointer arithmetic setting the size of the pointed object equal to the sizeof( char ) that is to 1.

Body:
I'm trying to compile a third party library, but for some reason I'm getting an error. The library is likely compiled differently. I've read up on the error but I can't seem to figure out what the issue is! :(

struct sfo_entry {
    char* key;
    size_t size;
    size_t area;
    void* value;
    enum sfo_value_format format;
    struct sfo_entry* next;
    struct sfo_entry* prev;
};

struct sfo {
    struct sfo_entry* entries;
};

bool sfo_load_from_memory(struct sfo* sfo, const void* data, size_t data_size) {
    struct sfo_header* hdr;
    struct sfo_table_entry* entry_table;
    struct sfo_table_entry* entry;

    entry_table = (struct sfo_table_entry*)(data + sizeof(*hdr));

    // ...

    return true;
}

The error is as follows:

 sfo.cpp:150:47: error: arithmetic on a pointer to void
         entry_table = (struct sfo_table_entry*)(data + sizeof(*hdr));
                                                 ~~~~ ^


问:
GLM output trouble
So, i want to run a repeated measures GLM in RStudio, which I have done...for the most part.... However, Not all dates are showing up in my output (12/1/2015 is missing). Here is part of the output along with my model code so you can see what i mean:

```<code>CH4f1 <- glm(GC_CH4.flux~River*Site*Date*Hum.Hol, data = Rdata_w.o_OL_Date, family = gaussian)
 summary(CH4f1)

Call:
glm(formula = GC_CH4.flux ~ River * Site * Date * Hum.Hol, family = gaussian,
    data = Rdata_w.o_OL_Date)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-37.307   -2.655   -0.341    0.314  163.247

Coefficients:
                                 Estimate Std. Error t value Pr(>|t|)
(Intercept)                       15.5643    75.6869   0.206   0.8372
River                             -8.4098    55.1093  -0.153   0.8788
Site                              -3.4776    25.9063  -0.134   0.8933
Date12/1/2016                    112.5939    96.6623   1.165   0.2451
Date4/1/2016                     -15.4780    96.9954  -0.160   0.8733
Date4/1/2017                     -13.8752    94.5132  -0.147   0.8834
Date6/1/2016                      12.5824    93.8721   0.134   0.8935
Date6/1/2017                     -18.3304    94.5132  -0.194   0.8464
Date9/1/2016                     170.2484    95.5697   1.781   0.0759 .
Date9/1/2017                     -38.4031    96.7184  -0.397   0.6916
</code>```

How do I get 12/1/2015 to be one of the dates that shows up in my GLM output?

答:
The column Date is a factor, or is being convert to a factor by glm.

By default, glm uses the treatment contrast for factors, also called Dummy Encoding. This means that (Intercept) is the coefficient for the first level, 12/1/2015.

For the other dates, those coefficients are changes from 12/1/2015. For example, the intercept for 6/1/2017 is actually (Intercept) + Date6/1/2017 = 15.5643 + ( -18.3304).

I could give more specific help if you provided a reproducible example.

Title: GLM output trouble

Body:
So, i want to run a repeated measures GLM in RStudio, which I have done...for the most part.... However, Not all dates are showing up in my output (12/1/2015 is missing). Here is part of the output along with my model code so you can see what i mean:

CH4f1 <- glm(GC_CH4.flux~River*Site*Date*Hum.Hol, data = Rdata_w.o_OL_Date, family = gaussian)
 summary(CH4f1)

Call:
glm(formula = GC_CH4.flux ~ River * Site * Date * Hum.Hol, family = gaussian,
    data = Rdata_w.o_OL_Date)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-37.307   -2.655   -0.341    0.314  163.247

Coefficients:
                                 Estimate Std. Error t value Pr(>|t|)
(Intercept)                       15.5643    75.6869   0.206   0.8372
River                             -8.4098    55.1093  -0.153   0.8788
Site                              -3.4776    25.9063  -0.134   0.8933
Date12/1/2016                    112.5939    96.6623   1.165   0.2451
Date4/1/2016                     -15.4780    96.9954  -0.160   0.8733
Date4/1/2017                     -13.8752    94.5132  -0.147   0.8834
Date6/1/2016                      12.5824    93.8721   0.134   0.8935
Date6/1/2017                     -18.3304    94.5132  -0.194   0.8464
Date9/1/2016                     170.2484    95.5697   1.781   0.0759 .
Date9/1/2017                     -38.4031    96.7184  -0.397   0.6916

How do I get 12/1/2015 to be one of the dates that shows up in my GLM output?


问:
Delphi RAR Component requesting a password for archive
I want to the this RAR component: http://www.philippewechsler.ch/RARComponent.php

By Philippe Wechsler.

But I don't understand how can I request a password NOT for files in an archive but for an ARCHIVE?

It is written in the documentation that I don't understand how to use:

```<code>OnPasswordRequired(Sender: TObject; const HeaderPassword: Boolean;
const FileName: WideString;out NewPassword: Ansistring; out Cancel: Boolean);
</code>```

This event occurs if a password is required to continue.

HeaderPassword: if this is true, the password is required to open the archive.
Otherwise the password is needed to process a file.

FileName: the filename of the file that requires a password (either the archivename
or the filename of the file inside the archive)

NewPassword: the required password

Cancel: set this to true if you don’t know the correct password

How do I use this code?

答:
```<code>OnPasswordRequired(Sender: TObject; const HeaderPassword: Boolean;
const FileName: WideString;out NewPassword: Ansistring; out Cancel: Boolean);
</code>```

I'm not sure what the question is here... This is an event handler, and you assign it just as you would any other event handler: either by double-clicking the OnPasswordRequired event in the Object Inspector, or by connecting it via code:

```<code>implementation

  procedure TForm1.FormCreate(Sender: TObject);
  begin
    RARComp.OnPasswordRequired := RARPasswordRequired;
  end;

  procedure TForm1.RARPasswordRequired(Sender: TObject;
    const HeaderPassword: Boolean;
    const FileName: WideString;
    out NewPassword: Ansistring; out Cancel: Boolean);
  begin
    if HeaderPassword then  // need whole archive password
      NewPassword := YourWholeArchivePassword  // provide whole archive password
    else
      // Need individual file password. If you have a separate password for
      // each file, provide it as each file is provided in "filename" param.
      if FileName = TheFilenameYouHavePasswordFor then
        NewPassword := ThisFilesPassword
      else
        Cancel := True;
  end;
</code>```

I have no idea what the component name would be (I used RARComp, but I'm not familiar with this component); replace it with whatever is correct. There's surely a predefined type for the OnPasswordRequired event (like TPasswordRequiredEvent or something); again, I'm not familiar with the component.

To explain: The out parameters passed to the event handler are like var parameters, except they don't have to be initialized before being passed by the component. The fact they are out means they are output; you're expected to assign values to them. The two const parameters (HeaderPassword and FileName), on the other hand, can't be changed by you; they are values for your use in deciding how to set the two parameters you are allowed to change. The Sender will be the RARComp or whatever your component instance is called; it can be typecast if needed to access other information using syntax like TRARComponent(Sender) or (Sender as TRARComponent).

Again, I have no idea what the proper classname is for this component, or what your instance of it would be named. If the classname of the component is TRARComponent on the IDE's component palette, and you drop it on the form, it would be declared as RARComponent1: TRARComponent;, and you would use the name RARComponent1 and TRARComponent(Sender) where appropriate.

Body:
I want to the this RAR component: http://www.philippewechsler.ch/RARComponent.php

By Philippe Wechsler.

But I don't understand how can I request a password NOT for files in an archive but for an ARCHIVE?

It is written in the documentation that I don't understand how to use:

OnPasswordRequired(Sender: TObject; const HeaderPassword: Boolean;
const FileName: WideString;out NewPassword: Ansistring; out Cancel: Boolean);

This event occurs if a password is required to continue.

HeaderPassword: if this is true, the password is required to open the archive.
Otherwise the password is needed to process a file.

FileName: the filename of the file that requires a password (either the archivename
or the filename of the file inside the archive)

NewPassword: the required password

Cancel: set this to true if you don’t know the correct password

How do I use this code?

Body:
OnPasswordRequired(Sender: TObject; const HeaderPassword: Boolean;
const FileName: WideString;out NewPassword: Ansistring; out Cancel: Boolean);

I'm not sure what the question is here... This is an event handler, and you assign it just as you would any other event handler: either by double-clicking the OnPasswordRequired event in the Object Inspector, or by connecting it via code:

implementation

  procedure TForm1.FormCreate(Sender: TObject);
  begin
    RARComp.OnPasswordRequired := RARPasswordRequired;
  end;

  procedure TForm1.RARPasswordRequired(Sender: TObject;
    const HeaderPassword: Boolean;
    const FileName: WideString;
    out NewPassword: Ansistring; out Cancel: Boolean);
  begin
    if HeaderPassword then  // need whole archive password
      NewPassword := YourWholeArchivePassword  // provide whole archive password
    else
      // Need individual file password. If you have a separate password for
      // each file, provide it as each file is provided in "filename" param.
      if FileName = TheFilenameYouHavePasswordFor then
        NewPassword := ThisFilesPassword
      else
        Cancel := True;
  end;

I have no idea what the component name would be (I used RARComp, but I'm not familiar with this component); replace it with whatever is correct. There's surely a predefined type for the OnPasswordRequired event (like TPasswordRequiredEvent or something); again, I'm not familiar with the component.

To explain: The out parameters passed to the event handler are like var parameters, except they don't have to be initialized before being passed by the component. The fact they are out means they are output; you're expected to assign values to them. The two const parameters (HeaderPassword and FileName), on the other hand, can't be changed by you; they are values for your use in deciding how to set the two parameters you are allowed to change. The Sender will be the RARComp or whatever your component instance is called; it can be typecast if needed to access other information using syntax like TRARComponent(Sender) or (Sender as TRARComponent).

Again, I have no idea what the proper classname is for this component, or what your instance of it would be named. If the classname of the component is TRARComponent on the IDE's component palette, and you drop it on the form, it would be declared as RARComponent1: TRARComponent;, and you would use the name RARComponent1 and TRARComponent(Sender) where appropriate.