问:
In Keras, how to get 3D input and 3D output for LSTM layers
In my original setting, I got

```<code>X1 = (1200,40,1)
y1 = (1200,10)
</code>```

Then, I work perfectly with my codes:

```<code>model = Sequential()
model.add(LSTM(12, input_shape=(40, 1), return_sequences=True))
model.add(LSTM(12, return_sequences=True))
model.add(LSTM(6, return_sequences=False))
model.add((Dense(10)))
</code>```

Now, I further got another time series data same sizes as X1 and y1. i.e.,

```<code>X2 = (1200,40,1)
y2 = (1200,10)
</code>```

Now, I stack X1, X2 and y1, y2 as 3D arrays:

```<code>X_stack = (1200,40,2)
y_stack = (1200,10,2)
</code>```

Then, I try to modify my keras code like:

```<code>model = Sequential()
model.add(LSTM(12, input_shape=(40, 2), return_sequences=True))
model.add(LSTM(12, return_sequences=True))
model.add(LSTM(6, return_sequences=False))
model.add((Dense((10,2))))
</code>```

I want my code work directly with the 3D arrays X_stack and y_stack without reshaping them as 2D arrays. Would you give me a hand on how to modify the settings? Thank you.

答:
I am assuming that you will need to share the parameters for each array that you stack.

If you were stacking entirely new features, then there wouldn't be an associated target with each one.

If you were stacking completely different examples, then you would not be using 3D arrays, and would just be appending them to the end like normal.

Solution

To solve this problem, I would leverage the TimeDistributed wrapper from Keras.

LSTM layers expect a shape (j, k) where j is the number of time steps, and k is the number of features. Since you want to keep your array as 3D for the input and output, you will want to stack on a different dimension than the feature dimension.

Quick side note:

I think it’s important to note the difference between the approaches. Stacking on the feature dimension gives you multiple features for the same time steps. In that case you would want to use the same LSTM layers and not go this route. Because you want a 3D input and a 3D output, I am proposing that you create a new dimension to stack on which will allow you to apply the same LSTM layers independently.

TimeDistributed:

This wrapper applies a layer to each array at the 1 index.
By stacking your X1 and X2 arrays on the 1 index, and using the TimeDistributed wrapper, you are applying LSTM layers independently to each array that you stack. Notice below that the original and updated model summaries have the exact same number of parameters.

Implementation Steps:

The first step is to reshape the input of (40, 2) into (2, 40, 1). This gives you the equivalent of 2 x (40, 1) array inputs. You can either do this in the model like I’ve done, or when building your dataset and update the input shape.

By adding the extra dimension (..., 1) to the end, we are keeping the data in a format that the LSTM would understand if it was just looking at one of the arrays that we stacked at a time. Notice how your original input_shape is (40, 1) for instance.

Then wrap each layer in the TimeDistributed wrapper.

And finally, reshape the y output to match your data by swapping (2, 10) to (10, 2).

Code

```<code>from tensorflow.python.keras import Sequential
from tensorflow.python.keras.layers import LSTM, Dense, TimeDistributed, InputLayer, Reshape
from tensorflow.python.keras import backend
import numpy as np

# Original Model
model = Sequential()
model.add(LSTM(12, input_shape=(40, 1), return_sequences=True))
model.add(LSTM(12, return_sequences=True))
model.add(LSTM(6, return_sequences=False))
model.add((Dense(10)))

model.summary()
</code>```

Original Model Summary

```<code>_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
lstm (LSTM)                  (None, 40, 12)            672
_________________________________________________________________
lstm_1 (LSTM)                (None, 40, 12)            1200
_________________________________________________________________
lstm_2 (LSTM)                (None, 6)                 456
_________________________________________________________________
dense (Dense)                (None, 10)                70
=================================================================
Total params: 2,398
Trainable params: 2,398
Non-trainable params: 0
_________________________________________________________________
</code>```

Apply TimeDistributed Wrapper

```<code>model = Sequential()
model.add(InputLayer(input_shape=(40, 2)))
model.add(Reshape(target_shape=(2, 40, 1)))
model.add(TimeDistributed(LSTM(12, return_sequences=True)))
model.add(TimeDistributed(LSTM(12, return_sequences=True)))
model.add(TimeDistributed(LSTM(6, return_sequences=False)))
model.add(TimeDistributed(Dense(10)))
model.add(Reshape(target_shape=(10, 2)))

model.summary()
</code>```

Updated Model Summary

```<code>_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
reshape (Reshape)            (None, 2, 40, 1)          0
_________________________________________________________________
time_distributed (TimeDistri (None, 2, 40, 12)         672
_________________________________________________________________
time_distributed_1 (TimeDist (None, 2, 40, 12)         1200
_________________________________________________________________
time_distributed_2 (TimeDist (None, 2, 6)              456
_________________________________________________________________
time_distributed_3 (TimeDist (None, 2, 10)             70
_________________________________________________________________
reshape_1 (Reshape)          (None, 10, 2)             0
=================================================================
Total params: 2,398
Trainable params: 2,398
Non-trainable params: 0
_________________________________________________________________
</code>```

Body:
In my original setting, I got

X1 = (1200,40,1)
y1 = (1200,10)

Then, I work perfectly with my codes:

model = Sequential()
model.add(LSTM(12, input_shape=(40, 1), return_sequences=True))
model.add(LSTM(12, return_sequences=True))
model.add(LSTM(6, return_sequences=False))
model.add((Dense(10)))

Now, I further got another time series data same sizes as X1 and y1. i.e.,

X2 = (1200,40,1)
y2 = (1200,10)

Now, I stack X1, X2 and y1, y2 as 3D arrays:

X_stack = (1200,40,2)
y_stack = (1200,10,2)

Then, I try to modify my keras code like:

model = Sequential()
model.add(LSTM(12, input_shape=(40, 2), return_sequences=True))
model.add(LSTM(12, return_sequences=True))
model.add(LSTM(6, return_sequences=False))
model.add((Dense((10,2))))

I want my code work directly with the 3D arrays X_stack and y_stack without reshaping them as 2D arrays. Would you give me a hand on how to modify the settings? Thank you.

Body:
I am assuming that you will need to share the parameters for each array that you stack.

If you were stacking entirely new features, then there wouldn't be an associated target with each one.

If you were stacking completely different examples, then you would not be using 3D arrays, and would just be appending them to the end like normal.

Solution

To solve this problem, I would leverage the TimeDistributed wrapper from Keras.

LSTM layers expect a shape (j, k) where j is the number of time steps, and k is the number of features. Since you want to keep your array as 3D for the input and output, you will want to stack on a different dimension than the feature dimension.

Quick side note:

I think it’s important to note the difference between the approaches. Stacking on the feature dimension gives you multiple features for the same time steps. In that case you would want to use the same LSTM layers and not go this route. Because you want a 3D input and a 3D output, I am proposing that you create a new dimension to stack on which will allow you to apply the same LSTM layers independently.

TimeDistributed:

This wrapper applies a layer to each array at the 1 index.
By stacking your X1 and X2 arrays on the 1 index, and using the TimeDistributed wrapper, you are applying LSTM layers independently to each array that you stack. Notice below that the original and updated model summaries have the exact same number of parameters.

Implementation Steps:

The first step is to reshape the input of (40, 2) into (2, 40, 1). This gives you the equivalent of 2 x (40, 1) array inputs. You can either do this in the model like I’ve done, or when building your dataset and update the input shape.

By adding the extra dimension (..., 1) to the end, we are keeping the data in a format that the LSTM would understand if it was just looking at one of the arrays that we stacked at a time. Notice how your original input_shape is (40, 1) for instance.

Then wrap each layer in the TimeDistributed wrapper.

And finally, reshape the y output to match your data by swapping (2, 10) to (10, 2).

Code

from tensorflow.python.keras import Sequential
from tensorflow.python.keras.layers import LSTM, Dense, TimeDistributed, InputLayer, Reshape
from tensorflow.python.keras import backend
import numpy as np

# Original Model
model = Sequential()
model.add(LSTM(12, input_shape=(40, 1), return_sequences=True))
model.add(LSTM(12, return_sequences=True))
model.add(LSTM(6, return_sequences=False))
model.add((Dense(10)))

model.summary()

Original Model Summary

_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
lstm (LSTM)                  (None, 40, 12)            672
_________________________________________________________________
lstm_1 (LSTM)                (None, 40, 12)            1200
_________________________________________________________________
lstm_2 (LSTM)                (None, 6)                 456
_________________________________________________________________
dense (Dense)                (None, 10)                70
=================================================================
Total params: 2,398
Trainable params: 2,398
Non-trainable params: 0
_________________________________________________________________

Apply TimeDistributed Wrapper

model = Sequential()
model.add(InputLayer(input_shape=(40, 2)))
model.add(Reshape(target_shape=(2, 40, 1)))
model.add(TimeDistributed(LSTM(12, return_sequences=True)))
model.add(TimeDistributed(LSTM(12, return_sequences=True)))
model.add(TimeDistributed(LSTM(6, return_sequences=False)))
model.add(TimeDistributed(Dense(10)))
model.add(Reshape(target_shape=(10, 2)))

model.summary()

Updated Model Summary

_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
reshape (Reshape)            (None, 2, 40, 1)          0
_________________________________________________________________
time_distributed (TimeDistri (None, 2, 40, 12)         672
_________________________________________________________________
time_distributed_1 (TimeDist (None, 2, 40, 12)         1200
_________________________________________________________________
time_distributed_2 (TimeDist (None, 2, 6)              456
_________________________________________________________________
time_distributed_3 (TimeDist (None, 2, 10)             70
_________________________________________________________________
reshape_1 (Reshape)          (None, 10, 2)             0
=================================================================
Total params: 2,398
Trainable params: 2,398
Non-trainable params: 0
_________________________________________________________________


来源: stackexchange

问:
How is the sintaxis to use ignore_dup_key?
I am trying to ignore duplicates when I insert rows in a many to many relationship table, but all the examples that I find is modifying the key in the table.

I would like to know if there is some way to set this only for the inserts that I want to do, something like that:

```<code>insert into Table(IDA, IDB) VALUES(1,2) ignore_dup_key = ON;
</code>```

Thanks.

答:
I've just edited this answer after @Alvaro Garcia Comment

```<code>insert into Table(IDA, IDB)
SELECT T.IDA, T.IDB
FROM (SELECT 1 as IDA, 2 as IDB) T
LEFT JOIN Table T2 ON T.IDA = T2.IDA AND T.IDB = T2.IDB
WHERE T2.IDA is null
</code>```

before I was just checking existence and then insert.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to ignore duplicates when I insert rows in a many to many relationship table, but all the examples that I find is modifying the key in the table.

I would like to know if there is some way to set this only for the inserts that I want to do, something like that:

insert into Table(IDA, IDB) VALUES(1,2) ignore_dup_key = ON;

Thanks.

Body:
I've just edited this answer after @Alvaro Garcia Comment

insert into Table(IDA, IDB)
SELECT T.IDA, T.IDB
FROM (SELECT 1 as IDA, 2 as IDB) T
LEFT JOIN Table T2 ON T.IDA = T2.IDA AND T.IDB = T2.IDB
WHERE T2.IDA is null

before I was just checking existence and then insert.


问:
Check if image:tag combination already exists on docker hub
As part of a bash script, I want to check if a particularly docker image:tag combination exists on docker hub. Also, it will be a private repository.

i.e. the pseudocode would be like:

```<code>tag = something
if image:tag already exists on docker hub:
    Do nothing
else
    Build and push docker image with that tag
</code>```

答:
Have you tried something like that, simply trying to pull the tag and deciding to push or not according to the return code?</p>

```<code>#! /bin/bash

if docker pull hello-world:linux > /dev/null; then
  echo "already exist -> do not push"
else
  echo "does not exist -> push"
fi
</code>```

ContentLicense: CC BY-SA 3.0

Body:
As part of a bash script, I want to check if a particularly docker image:tag combination exists on docker hub. Also, it will be a private repository.

i.e. the pseudocode would be like:

tag = something
if image:tag already exists on docker hub:
    Do nothing
else
    Build and push docker image with that tag

Body:
Have you tried something like that, simply trying to pull the tag and deciding to push or not according to the return code?

#! /bin/bash

if docker pull hello-world:linux > /dev/null; then
  echo "already exist -> do not push"
else
  echo "does not exist -> push"
fi


问:
R Simmer - "Number of keys and values don't match"
I am trying to simulate a JSQ(d) (join-shortest-queue of d sampled queues) system but am having trouble executing my code. In this case, let us assume d=2. I wish to have job size determined upon arrival (the value of "X") as well as the selection of which 2 queues will be sampled and "JSQ-ed" (this could be done perhaps differently, though for my purposes beyond this minimal working example, these must be determined upon arrival).

```<code>library(simmer)
set.seed(1337)

sim <- simmer("sim")

queues <- vector(length=1000)
for (i in 1:1000) {
  queues[i] <- paste0("q_",i)
}

queueing_system <- trajectory() %>%
  set_attribute("X", function() rexp(1)) %>%
  set_attribute("d", function() sample(1000,2)) %>%
  select(function() queues[get_attribute(sim, "d")], policy="shortest-queue") %>%
  seize_selected()%>%
  timeout(function() get_attribute(sim, "X")*(rpois(1, 1)+1)) %>%
  release_selected()

for (i in 1:1000) {
  sim %>%
    add_resource(queues[i], 1)
}
sim %>%
  add_generator("path", queueing_system, function() rexp(1,1)) %>%
  run(400) %>%
  now()
</code>```

I receive

```<code>Error: 'path0' at 0.15 in [SetAttribute]->SetAttribute->[Select]:
 number of keys and values don't match
</code>```

What seems to be the issue and how might I go about fixing this?

答:
Attributes store a single value. Why don't you sample directly in the select activity? I.e.,

queueing_system <- trajectory() %>%
  set_attribute("X", function() rexp(1)) %>%
  select(function() queues[sample(1000, 2)], policy="shortest-queue") %>%
  seize_selected()%>%
  timeout(function() get_attribute(sim, "X")*(rpois(1, 1)+1)) %>%
  release_selected()
```

I would call rexp(1) in place too, instead of defining X.

Body:
I am trying to simulate a JSQ(d) (join-shortest-queue of d sampled queues) system but am having trouble executing my code. In this case, let us assume d=2. I wish to have job size determined upon arrival (the value of "X") as well as the selection of which 2 queues will be sampled and "JSQ-ed" (this could be done perhaps differently, though for my purposes beyond this minimal working example, these must be determined upon arrival).

library(simmer)
set.seed(1337)

sim <- simmer("sim")

queues <- vector(length=1000)
for (i in 1:1000) {
  queues[i] <- paste0("q_",i)
}

queueing_system <- trajectory() %>%
  set_attribute("X", function() rexp(1)) %>%
  set_attribute("d", function() sample(1000,2)) %>%
  select(function() queues[get_attribute(sim, "d")], policy="shortest-queue") %>%
  seize_selected()%>%
  timeout(function() get_attribute(sim, "X")*(rpois(1, 1)+1)) %>%
  release_selected()

for (i in 1:1000) {
  sim %>%
    add_resource(queues[i], 1)
}
sim %>%
  add_generator("path", queueing_system, function() rexp(1,1)) %>%
  run(400) %>%
  now()

I receive

Error: 'path0' at 0.15 in [SetAttribute]->SetAttribute->[Select]:
 number of keys and values don't match

What seems to be the issue and how might I go about fixing this?

Body:
Attributes store a single value. Why don't you sample directly in the select activity? I.e.,

queueing_system <- trajectory() %>%
  set_attribute("X", function() rexp(1)) %>%
  select(function() queues[sample(1000, 2)], policy="shortest-queue") %>%
  seize_selected()%>%
  timeout(function() get_attribute(sim, "X")*(rpois(1, 1)+1)) %>%
  release_selected()

I would call rexp(1) in place too, instead of defining X.


问:
ServiceStack: Installing 'ServiceStack.HttpClient' in a Blazor project adds hundreds of dependencies?
I am doing some testing with Blazor, and since its C# I thought I could add the ServiceStack.HttpClient to use when talking to the backend.

However, when I saw that dependencies that NuGet was about to install, I got a bit scared, so I just wanted to check if this is normal and expected. We're talking about hundreds of added references.

Does this seem reasonable? runtime.fedora...Cryptography...?

答:
Most of these are transitive dependencies of ASP.NET Core dependencies.

You can view the list of dependencies of each package on NuGet:

ServiceStack.HttpClient:

```<code>ServiceStack.Client (>= 5.5.0)
ServiceStack.Interfaces (>= 5.5.0)
ServiceStack.Text (>= 5.5.0)
System.Collections.Specialized (>= 4.3.0)
System.Net.Requests (>= 4.3.0)
System.ServiceModel.Primitives (>= 4.5.3)
System.Xml.XmlSerializer (>= 4.3.0)
</code>```

ServiceStack.Client:

```<code>ServiceStack.Interfaces (>= 5.5.0)
ServiceStack.Text (>= 5.5.0)
System.Collections.Specialized (>= 4.3.0)
System.Memory (>= 4.5.2)
System.Net.Requests (>= 4.3.0)
System.ServiceModel.Primitives (>= 4.5.3)
System.Xml.XmlSerializer (>= 4.3.0)
</code>```

ServiceStack.Text:

```<code>Microsoft.CSharp (>= 4.5.0)
System.Memory (>= 4.5.2)
System.Runtime (>= 4.3.0)
</code>```

ServiceStack.Interfaces:

```<code>System.Runtime.Serialization.Primitives (>= 4.3.0)
</code>```

Body:
Most of these are transitive dependencies of ASP.NET Core dependencies.

You can view the list of dependencies of each package on NuGet:

ServiceStack.HttpClient:

ServiceStack.Client (>= 5.5.0)
ServiceStack.Interfaces (>= 5.5.0)
ServiceStack.Text (>= 5.5.0)
System.Collections.Specialized (>= 4.3.0)
System.Net.Requests (>= 4.3.0)
System.ServiceModel.Primitives (>= 4.5.3)
System.Xml.XmlSerializer (>= 4.3.0)

ServiceStack.Client:

ServiceStack.Interfaces (>= 5.5.0)
ServiceStack.Text (>= 5.5.0)
System.Collections.Specialized (>= 4.3.0)
System.Memory (>= 4.5.2)
System.Net.Requests (>= 4.3.0)
System.ServiceModel.Primitives (>= 4.5.3)
System.Xml.XmlSerializer (>= 4.3.0)

ServiceStack.Text:

Microsoft.CSharp (>= 4.5.0)
System.Memory (>= 4.5.2)
System.Runtime (>= 4.3.0)

ServiceStack.Interfaces:

System.Runtime.Serialization.Primitives (>= 4.3.0)


问:
Valgrind found 3 memory leaks but I can't figure out where they are
I tried to implement the basic String class by myself and it's working fine, but Valgrind says there are 3 memory leaks and I can't figure out where and why. I really tried to delete everything after it isn't used anymore (I have started using Valgrind today).
Now I'm really concerned about my basic C/C++ memory management knowledge. I made a comment to the places in the code where Valgrind found a leak (//VALGRIND). I've also uploaded a screenshot of this error message
click to see the screenshot.

EDIT: I have updated the screenshot, so you can see the full output.

StringT.h

template<typename char_type = char>
class StringT {
public:

 explicit StringT(const char_type *str) {
        if (str != nullptr) {
            size_t len = strlen(str);
            m_str = new char_type[len + 1]; //VALGRIND: 6 bytes in 1 blocks are definitely lost in loss record 1 of 3
            strcpy(m_str, str);
        }
    }

   ~StringT() {
        delete [] m_str;
    }

StringT(const StringT & other) {
        size_t len = 0;
        if (other.m_str) len = strlen(other.m_str);
        m_str = new char_type[len + 1]; //VALGRIND: 6 bytes in 1 blocks are definitely lost in loss record 2 of 3
        strcpy(m_str, other.m_str);
    }

    StringT(StringT && other) noexcept {
        m_str = other.m_str;
        other.m_str = nullptr;
    }

     StringT & operator+=(const StringT &other) {
        if (other.m_str == nullptr) //when other str is empty just return current Str
            return *this;

        const size_t mysize{m_str ? strlen(m_str) : 0}; // check if not null then call strlen
        const size_t osize{other.m_str ? strlen(other.m_str) : 0};

        char *newStr = new char_type[osize + mysize + 1]; //VALGRIND: 11 bytes in 1 blocks are definitely lost in loss record 3 of 3
        newStr[0] = '\0'; //strcat searches for '\0', so newStr has to be a valid String

        if (m_str) strcat(newStr, m_str);
        if (other.m_str) strcat(newStr, other.m_str);

        delete[] m_str; //delete old string
        m_str = newStr; //set member to new concatenated str

        return *this;
    }

    size_t length() const {
        if (!m_str) return 0;
        return strlen(m_str);
    }

    friend
    std::ostream &operator<<(std::ostream &out, StringT<> &other) {
        if (other.m_str) out << other.m_str;
        return out;
    }

private:
    char_type *m_str{nullptr};
};
```

<p>main.cpp</p>

<pre class="lang-cpp prettyprint-override"><code>int main() {

    const char *cArr = "Hello";
    const char *cArr2 = "World";
    StringT<char> hello(cArr);
    StringT<char> world(cArr2);
    StringT<char> emptyStr;

    std::cout << "hello: " << hello << std::endl;
    std::cout << "world: " << world << std::endl;
    std::cout << "emptyStr: " << emptyStr << std::endl;

    StringT<char> hCopy(hello);
    StringT<char> wMove(std::move(world));

    std::cout << "hCopy: " << hello << std::endl;
    std::cout << "hCopy: " << hCopy << std::endl;
    std::cout << "world: " << world << std::endl;
    std::cout<<  "wMove: " << wMove << std::endl;
    std::cout<<  "lenMove: " << wMove.length() << std::endl;
    std::cout<<  "lenEmptyStr: " << emptyStr.length() << std::endl;

    hello += wMove;
    std::cout<<  "hello += world: " << hello << std::endl;

    return 0;
}

</code>```

答:
Your delete is here:

```<code>StringT() {
    delete [] m_str;
}
</code>```

But that's a constructor, not a destructor.

Body:
I tried to implement the basic String class by myself and it's working fine, but Valgrind says there are 3 memory leaks and I can't figure out where and why. I really tried to delete everything after it isn't used anymore (I have started using Valgrind today).
Now I'm really concerned about my basic C/C++ memory management knowledge. I made a comment to the places in the code where Valgrind found a leak (//VALGRIND). I've also uploaded a screenshot of this error message
click to see the screenshot.

EDIT: I have updated the screenshot, so you can see the full output.

StringT.h

template<typename char_type = char>
class StringT {
public:

 explicit StringT(const char_type *str) {
        if (str != nullptr) {
            size_t len = strlen(str);
            m_str = new char_type[len + 1]; //VALGRIND: 6 bytes in 1 blocks are definitely lost in loss record 1 of 3
            strcpy(m_str, str);
        }
    }

   ~StringT() {
        delete [] m_str;
    }

StringT(const StringT & other) {
        size_t len = 0;
        if (other.m_str) len = strlen(other.m_str);
        m_str = new char_type[len + 1]; //VALGRIND: 6 bytes in 1 blocks are definitely lost in loss record 2 of 3
        strcpy(m_str, other.m_str);
    }

    StringT(StringT && other) noexcept {
        m_str = other.m_str;
        other.m_str = nullptr;
    }

     StringT & operator+=(const StringT &other) {
        if (other.m_str == nullptr) //when other str is empty just return current Str
            return *this;

        const size_t mysize{m_str ? strlen(m_str) : 0}; // check if not null then call strlen
        const size_t osize{other.m_str ? strlen(other.m_str) : 0};

        char *newStr = new char_type[osize + mysize + 1]; //VALGRIND: 11 bytes in 1 blocks are definitely lost in loss record 3 of 3
        newStr[0] = '\0'; //strcat searches for '\0', so newStr has to be a valid String

        if (m_str) strcat(newStr, m_str);
        if (other.m_str) strcat(newStr, other.m_str);

        delete[] m_str; //delete old string
        m_str = newStr; //set member to new concatenated str

        return *this;
    }

    size_t length() const {
        if (!m_str) return 0;
        return strlen(m_str);
    }

    friend
    std::ostream &operator<<(std::ostream &out, StringT<> &other) {
        if (other.m_str) out << other.m_str;
        return out;
    }

private:
    char_type *m_str{nullptr};
};

main.cpp

int main() {

    const char *cArr = "Hello";
    const char *cArr2 = "World";
    StringT<char> hello(cArr);
    StringT<char> world(cArr2);
    StringT<char> emptyStr;

    std::cout << "hello: " << hello << std::endl;
    std::cout << "world: " << world << std::endl;
    std::cout << "emptyStr: " << emptyStr << std::endl;

    StringT<char> hCopy(hello);
    StringT<char> wMove(std::move(world));

    std::cout << "hCopy: " << hello << std::endl;
    std::cout << "hCopy: " << hCopy << std::endl;
    std::cout << "world: " << world << std::endl;
    std::cout<<  "wMove: " << wMove << std::endl;
    std::cout<<  "lenMove: " << wMove.length() << std::endl;
    std::cout<<  "lenEmptyStr: " << emptyStr.length() << std::endl;

    hello += wMove;
    std::cout<<  "hello += world: " << hello << std::endl;

    return 0;
}

Body:
Your delete is here:

StringT() {
    delete [] m_str;
}

But that's a constructor, not a destructor.


问:
AWS IAM CDK: tagging and creating access key for a user
I'm trying to use AWS CDK to create a user with minimal permissions through a custom policy, but I'm stuck with tagging that user and creating its access keys.

Below there's my code:

```<code>public class Sample extends App {
    public static void main(final String[] args) {
            App app = new App();
            new UserStack(app, "user-stack");
            app.run();
    }

    public static class UserStack extends Stack {
        // Not able to add Tag and Create Access Key
        public UserStack(final App parent, final String name) {
            super(parent, name);

            PolicyStatement statement = new PolicyStatement(PolicyStatementEffect.Allow);
            statement.addResource("*");
            statement.addAction("lambda:UpdateFunctionCode");

            User user = new User(this, "LambdaDeployer", UserProps.builder().withUserName("lambda-deployer").withPath("/").build());
            user.addToPolicy(statement);

            Tag tag = new Tag("Project", "devops");
            // how to tag the user ??

            new CfnOutput(this, "LambdaDeployerOutputAccessKey", CfnOutputProps.builder().withValue("AWS::IAM::AccessKey").build());
            new CfnOutput(this, "LambdaDeployerOutputSecretAccessKey", CfnOutputProps.builder().withValue("AWS::IAM::SecretAccessKey").build());
        }
    }
}
</code>```

答:
You'll probably have to use a Custom Resource in order to call the TagUser API, since adding tags to a User is not available natively in CloudFormation.

You can use a new feature in the CDK to help you author your Custom Resource: https://github.com/awslabs/aws-cdk/pull/1850

Body:
I'm trying to use AWS CDK to create a user with minimal permissions through a custom policy, but I'm stuck with tagging that user and creating its access keys.

Below there's my code:

public class Sample extends App {
    public static void main(final String[] args) {
            App app = new App();
            new UserStack(app, "user-stack");
            app.run();
    }

    public static class UserStack extends Stack {
        // Not able to add Tag and Create Access Key
        public UserStack(final App parent, final String name) {
            super(parent, name);

            PolicyStatement statement = new PolicyStatement(PolicyStatementEffect.Allow);
            statement.addResource("*");
            statement.addAction("lambda:UpdateFunctionCode");

            User user = new User(this, "LambdaDeployer", UserProps.builder().withUserName("lambda-deployer").withPath("/").build());
            user.addToPolicy(statement);

            Tag tag = new Tag("Project", "devops");
            // how to tag the user ??

            new CfnOutput(this, "LambdaDeployerOutputAccessKey", CfnOutputProps.builder().withValue("AWS::IAM::AccessKey").build());
            new CfnOutput(this, "LambdaDeployerOutputSecretAccessKey", CfnOutputProps.builder().withValue("AWS::IAM::SecretAccessKey").build());
        }
    }
}


问:
bootstrap 4 tabs with buttons with active class not working
i have a small issue concerning my bootstrap 4 tabs:

My intention is too switch between buttons like this example: https://codepen.io/anon/pen/vwQamK but with bootstrap.

```<code>  <div id="tab" class="btn-group btn-group-justified" data-toggle="buttons">
    <a href="#prices" class="btn btn-primary active" data-toggle="tab">
      <input type="radio" />Prices
    </a>
    <a href="#features" class="btn btn-default" data-toggle="tab">
      <input type="radio" />Features
    </a>
  </div>

  <div class="tab-content">
    <div class="tab-pane active" id="prices">Prices content</div>
    <div class="tab-pane" id="features">Features Content</div>
  </div>
</code>```

Currently the toggle between the tab content is not working!

Here is my codepen:

https://codepen.io/user1010/pen/mYQvVo

答:
It looks like instead of being inputs that you can just use the text and it switches between content.</p>

```<code>  <div id="tab" class="btn-group btn-group-justified" data-toggle="buttons">
    <a href="#prices" class="btn btn-primary active" data-toggle="tab">
      Prices
    </a>
    <a href="#features" class="btn btn-default" data-toggle="tab">
      Features
    </a>
  </div>

  <div class="tab-content">
    <div class="tab-pane active" id="prices">Prices content</div>
    <div class="tab-pane" id="features">Features Content</div>
  </div>
</code>```

Body:
i have a small issue concerning my bootstrap 4 tabs:

My intention is too switch between buttons like this example: https://codepen.io/anon/pen/vwQamK but with bootstrap.

      <input type="radio" />Prices

      <input type="radio" />Features

Prices content

Features Content

Currently the toggle between the tab content is not working!

Here is my codepen:

https://codepen.io/user1010/pen/mYQvVo

Body:
It looks like instead of being inputs that you can just use the text and it switches between content.

  <div id="tab" class="btn-group btn-group-justified" data-toggle="buttons">
    <a href="#prices" class="btn btn-primary active" data-toggle="tab">
      Prices
    </a>
    <a href="#features" class="btn btn-default" data-toggle="tab">
      Features
    </a>
  </div>

  <div class="tab-content">
    <div class="tab-pane active" id="prices">Prices content</div>
    <div class="tab-pane" id="features">Features Content</div>
  </div>


问:
Using images to style scroll bars?
Can anyone recommend the best solution for using images to style scroll bar?  I guess a decent cross-browser solution would involve a merge of JQuery/javascrip and CSS?

Thanks
Paul

答:
Have a look here:
http://www.net-kit.com/jquery-custom-scrollbar-plugins/

Many very good solutions. Always remember to think as you're users would do. In my oppinion animated / designed scrollbars can ruin the beauty about scrolling, because of delay or lag.

Title: Using images to style scroll bars?


问:
How to configure multiple I/O Expander PCF8574a in a device tree?
I am currently adding an I/O Expander PCF8574a in my device tree am335x-boneblack.dts. I have two I/O expander, one at 0x38 and another at 0x39.

The code below works fine for a single expander but if I add PCF8574a with address 0x39 in the similar manner, it shows an error.

```<code>&i2c1 {
    pinctrl-names = "default";
    pinctrl-0 = <&i2c1_pins_default>;
    status = "okay";
    clock-frequency = <400000>;

pcf8574a: pcf8574a@38 {
    compatible = "nxp,pcf8574a";
    reg = <0x38>;
    gpio-controller;
    #gpio-cells = <2>;
};
</code>```

};

Error log :

"Duplicate label 'pcf8574a' on /ocp/i2c@4802a000/pcf8574a@39 and /ocp/i2c@4802a000/pcf8574a@38"
  which I completely understand.

But I dont know how to add another node or say sub node to make this work. Any suggestions?

答:
have you tried this</p>

```<code>&i2c1 {
    pinctrl-names = "default";
    pinctrl-0 = <&i2c1_pins_default>;
    status = "okay";
    clock-frequency = <400000>;

pcf8574a_38: pcf8574a@38 {
    compatible = "nxp,pcf8574a";
    reg = <0x38>;
    gpio-controller;
    #gpio-cells = <2>;
};
pcf8574a_39: pcf8574a@39 {
    compatible = "nxp,pcf8574a";
    reg = <0x39>;
    gpio-controller;
    #gpio-cells = <2>;
};
};
</code>```

Body:
I am currently adding an I/O Expander PCF8574a in my device tree am335x-boneblack.dts. I have two I/O expander, one at 0x38 and another at 0x39.

The code below works fine for a single expander but if I add PCF8574a with address 0x39 in the similar manner, it shows an error.

&i2c1 {
    pinctrl-names = "default";
    pinctrl-0 = <&i2c1_pins_default>;
    status = "okay";
    clock-frequency = <400000>;

pcf8574a: pcf8574a@38 {
    compatible = "nxp,pcf8574a";
    reg = <0x38>;
    gpio-controller;
    #gpio-cells = <2>;
};

};

Error log :

"Duplicate label 'pcf8574a' on /ocp/i2c@4802a000/pcf8574a@39 and /ocp/i2c@4802a000/pcf8574a@38"
  which I completely understand.

But I dont know how to add another node or say sub node to make this work. Any suggestions?

Body:
have you tried this

&i2c1 {
    pinctrl-names = "default";
    pinctrl-0 = <&i2c1_pins_default>;
    status = "okay";
    clock-frequency = <400000>;

pcf8574a_38: pcf8574a@38 {
    compatible = "nxp,pcf8574a";
    reg = <0x38>;
    gpio-controller;
    #gpio-cells = <2>;
};
pcf8574a_39: pcf8574a@39 {
    compatible = "nxp,pcf8574a";
    reg = <0x39>;
    gpio-controller;
    #gpio-cells = <2>;
};
};


问:
Duplicates in javascript fix
In an arrangement I am adding the id that is currently in the for cycle, going through a query, but I do not want duplicate values to be added, as I can know that an id has already been added to the array in order to put a conditional and not add it, or what is the best way to do it

let values = []
values.push({
    "id": id
});```

答:
You need to check existing value by using find method in array, and then push the value if it does not exist

let values = []

function pushId(id) {
  if (!values.find(value => value.id === id)) {
    values.push({
      id: id
    })
  }
}

pushId(1);
pushId(1);
pushId(2);

console.log(values)```

Title: Duplicates in javascript fix


问:
Input focus in nested navigation in Flutter
I'm trying to create a master detail tablet view layout in Flutter and running into a bug or something.

Pseudo layout

```<code>Scaffold
-- Column
---- Navigator => Container => Input (works)
---- Container => Input (no focus)
</code>```

Gist

I created a gist to illustrate the problem:
https://gist.github.com/markmooibroek/3459f73bbd89deefeb488060f5bfd87e

Video

And a video that shows the bugged behaviour. The second input (below) is not getting focussed properly.

https://user-images.githubusercontent.com/1412238/58686402-0507e700-837f-11e9-977d-c16e7a858f27.gif

答:
This happens when you're using nested MaterialApps. A workaround could be to use FocusScope and a FocusScopeNode. This would allow you to gain focus in other MaterialApps that overlap your main one. This is also the case when using a TextField on an Overlay widget.

So wrap things like shown:

```<code>FocusScope(
   node : FocusScopeNode(),
   child : return Container(
              color: Colors.green,
              child: Center(
                child: TextFormField(
                  controller: controller,
                  decoration: InputDecoration(hintText: "Input"),
                ),
              ),
            );
)
</code>```

This should allow you to gain focus in that screen.

Body:
I'm trying to create a master detail tablet view layout in Flutter and running into a bug or something.

Pseudo layout

Scaffold
-- Column
---- Navigator => Container => Input (works)
---- Container => Input (no focus)

Gist

I created a gist to illustrate the problem:
https://gist.github.com/markmooibroek/3459f73bbd89deefeb488060f5bfd87e

Video

And a video that shows the bugged behaviour. The second input (below) is not getting focussed properly.

https://user-images.githubusercontent.com/1412238/58686402-0507e700-837f-11e9-977d-c16e7a858f27.gif

Body:
This happens when you're using nested MaterialApps. A workaround could be to use FocusScope and a FocusScopeNode. This would allow you to gain focus in other MaterialApps that overlap your main one. This is also the case when using a TextField on an Overlay widget.

So wrap things like shown:

FocusScope(
   node : FocusScopeNode(),
   child : return Container(
              color: Colors.green,
              child: Center(
                child: TextFormField(
                  controller: controller,
                  decoration: InputDecoration(hintText: "Input"),
                ),
              ),
            );
)

This should allow you to gain focus in that screen.


问:
Is there a Swifty way to unwrap optionals with string interpolation?
I'm building a RESTful API query using values collected from the user. Some of those values might not be supplied, so I'm using optionals.  There are Double, Int and String values.  The code I'm using seems clunky.  Is there a cleaner, Swifty way to write this block of code?

'''Swift

```<code>let baseURL = "http......"

// Start with required parms
let format = "?format=\(parms.format)"
let endTime = "&endtime=\(parms.endDate)"

// now for optionals
let startTime = parms.startDate != nil ? "&starttime=\(parms.startDate!)" : ""

// Sorted by
let orderby = parms.orderby != nil ? "&orderby=\(parms.orderby!)" : ""
// parts.limit is Int?
let limit = parms.limit != nil ? "&limit=\(parms.limit!)" : ""

var strURL: String
strURL = "\(baseURL)\(format)\(startTime)\(endTime)\(orderby)\(limit)"
</code>```

'''

I'm getting the result I need. E.g., if the user does not provide a StartDate parameter, it is not referenced in the query string.

'''
https://.....?format=geojson&endtime=2019-05-31&orderby=magnitude&minmagnitude=5&limit=2000
'''

but I have this feeling of missing the point of Swift Optionals

答:
In Swift 5 you can extend String.StringInterpolation and write custom interpolations. Read More

```<code>extension String.StringInterpolation {
    public mutating func appendInterpolation<T>(if value: T?, _ literal: StringLiteralType) {
        if let value = value {
            appendInterpolation(literal+"\(value)")
        }
    }
}
</code>```

Now instead of

```<code>let startTime = parms.startDate != nil ? "&starttime=\(parms.startDate!)" : ""
</code>```

You can use

```<code>let startTime = "\(if: parms.startDate, "&starttime=")"
</code>```

Usage

```<code>var startTime = "\(if: parms.startDate, "&starttime=")"
print(startTime)//""
parms.startDate = "mytime"
startTime = "\(if: parms.startDate, "&starttime=")"
print(startTime)//"""&starttime=mytime"
</code>```

Body:
I'm building a RESTful API query using values collected from the user. Some of those values might not be supplied, so I'm using optionals.  There are Double, Int and String values.  The code I'm using seems clunky.  Is there a cleaner, Swifty way to write this block of code?

'''Swift

let baseURL = "http......"

// Start with required parms
let format = "?format=\(parms.format)"
let endTime = "&endtime=\(parms.endDate)"

// now for optionals
let startTime = parms.startDate != nil ? "&starttime=\(parms.startDate!)" : ""

// Sorted by
let orderby = parms.orderby != nil ? "&orderby=\(parms.orderby!)" : ""
// parts.limit is Int?
let limit = parms.limit != nil ? "&limit=\(parms.limit!)" : ""

var strURL: String
strURL = "\(baseURL)\(format)\(startTime)\(endTime)\(orderby)\(limit)"

'''

I'm getting the result I need. E.g., if the user does not provide a StartDate parameter, it is not referenced in the query string.

'''
https://.....?format=geojson&endtime=2019-05-31&orderby=magnitude&minmagnitude=5&limit=2000
'''

but I have this feeling of missing the point of Swift Optionals

Body:
In Swift 5 you can extend String.StringInterpolation and write custom interpolations. Read More

extension String.StringInterpolation {
    public mutating func appendInterpolation<T>(if value: T?, _ literal: StringLiteralType) {
        if let value = value {
            appendInterpolation(literal+"\(value)")
        }
    }
}

Now instead of

let startTime = parms.startDate != nil ? "&starttime=\(parms.startDate!)" : ""

You can use

let startTime = "\(if: parms.startDate, "&starttime=")"

Usage

var startTime = "\(if: parms.startDate, "&starttime=")"
print(startTime)//""
parms.startDate = "mytime"
startTime = "\(if: parms.startDate, "&starttime=")"
print(startTime)//"""&starttime=mytime"


问:
"pip install selenium" not working // using python 3 // windows 10
I cannot install selenium. I have python 3.7 and window 10.

These are some of the things i have tried and the outcome:

C:\Users\dani>pip install selenium
'pip' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\dani>sudo pip install selenium
'sudo' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\dani>pip3 install selenium
'pip3' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\dani>conda install selenium
'conda' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\dani>pip install -U selenium
'pip' is not recognized as an internal or external command,
operable program or batch file.

答:
Install pip

Step 1. Check the python version

Step2. Download get-pip.py to a folder on your computer.

Step3. Install pip by following command python3.7 get-pip.py or python3 get-pip.py


问:
Swift Declare a protocol equatable
I have a protocol:

```<code>protocol CustomProtocol {
   var title: String { get }
   var subtitle: String { get }
}
</code>```

Then i have 2 objects, that conform this procotol. And i want to compare them, so i would like to CustomProtocol to be Equatable.

```<code>protocol CustomProtocol: Equatable {
   var title: String { get }
   var subtitle: String { get }
    static func ==(lhs: Self, rhs: Self) -> Bool
}

extension CustomProtocol {
    static func ==(lhs: Self, rhs: Self) -> Bool {
        return lhs.title == rhs.title
    }
}
</code>```

But after that change i get "Protocol CustomProtocol can only be used  as a generic constraint because it has Self or associated type requeriments.
The only way i can think to solve this is to have a third property like a hash that depends on the others and compare this property.

Here you have a sample playground with the actual code.

答:
The problem is the rhs parameter is not the same type of the lhs. They just conform to the same protocol.

You could solve that by using a generic type as the second parameter.

exension CustomProtocol {
    static func ==<T: CustomProtocol>(lhs: Self, rhs: T) -> Bool {
        return lhs.title == rhs.title
    }
}
```

Title: Swift Declare a protocol equatable

Body:
I have a protocol:

protocol CustomProtocol {
   var title: String { get }
   var subtitle: String { get }
}

Then i have 2 objects, that conform this procotol. And i want to compare them, so i would like to CustomProtocol to be Equatable.

protocol CustomProtocol: Equatable {
   var title: String { get }
   var subtitle: String { get }
    static func ==(lhs: Self, rhs: Self) -> Bool
}

extension CustomProtocol {
    static func ==(lhs: Self, rhs: Self) -> Bool {
        return lhs.title == rhs.title
    }
}

But after that change i get "Protocol CustomProtocol can only be used  as a generic constraint because it has Self or associated type requeriments.
The only way i can think to solve this is to have a third property like a hash that depends on the others and compare this property.

Here you have a sample playground with the actual code.


问:
Files with different headers to copy data in azure dwh table
I am new to the Azure Data Warehouse and Azure Data factory V2.

I Have a folder With 10 files in azure blob, Each file is having different headers but there will be a common 5 headers in all files.

Things I have tried,

Created 10 linked servers to the files and using copy data task moved the data to the specific tables.
But I required only 5 columns from those tables

Question

Is there any way that I can have a table with 5 columns and a dynamic file connection to load data from 5 files.

Example:
File1 : 10 headers
File2 : 11 headers
File3 : 7 headers
.
.
.
.
File10 : 15 headers

There will be a common of 5 columns in these files and that data has to be loaded common Table with 5 columns.

答:
When you create external tables in Azure SQL Data Warehouse with Polybase, they can either point to an individual file or a set of files as long as they in the same folder and in the same format.

Individual file

```<code>WTIH (
    DATA_SOURCE = yourDataSource,
    LOCATION = N'/input/file1.txt',
    FILE_FORMAT = yourFileFormat,
    ...
    etc
</code>```

Folder

```<code>WTIH (
    DATA_SOURCE = yourDataSource,
    LOCATION = N'/input/',
    FILE_FORMAT = yourFileFormat,
    ...
    etc
</code>```

So what you could do is create an external table for each file.  The external tables are only metadata structures, the data doesn't actually exist in the database.
These tables must include all columns for each table.  Then create a UNION statement over the five tables, selecting the five columns only and use a CTAS to import the data into the database:

```<code>CREATE TABLE dbo.yourTable
WITH
(
    DISTRIBUTION = ROUND_ROBIN,
    CLUSTERED COLUMNSTORE INDEX
)
AS
SELECT col1, col2, col3, col4, col5
FROM externalTable1

UNION ALL

SELECT col1, col2, col3, col4, col5
FROM externalTable2

UNION ALL

SELECT col1, col2, col3, col4, col5
FROM externalTable3

etc
....
</code>```

I probably would not use Data Factory as Polybase can do most of the work for you.

Body:
When you create external tables in Azure SQL Data Warehouse with Polybase, they can either point to an individual file or a set of files as long as they in the same folder and in the same format.

Individual file

WTIH (
    DATA_SOURCE = yourDataSource,
    LOCATION = N'/input/file1.txt',
    FILE_FORMAT = yourFileFormat,
    ...
    etc

Folder

WTIH (
    DATA_SOURCE = yourDataSource,
    LOCATION = N'/input/',
    FILE_FORMAT = yourFileFormat,
    ...
    etc

So what you could do is create an external table for each file.  The external tables are only metadata structures, the data doesn't actually exist in the database.
These tables must include all columns for each table.  Then create a UNION statement over the five tables, selecting the five columns only and use a CTAS to import the data into the database:

CREATE TABLE dbo.yourTable
WITH
(
    DISTRIBUTION = ROUND_ROBIN,
    CLUSTERED COLUMNSTORE INDEX
)
AS
SELECT col1, col2, col3, col4, col5
FROM externalTable1

UNION ALL

SELECT col1, col2, col3, col4, col5
FROM externalTable2

UNION ALL

SELECT col1, col2, col3, col4, col5
FROM externalTable3

etc
....

I probably would not use Data Factory as Polybase can do most of the work for you.


问:
How can I set a global show delay for v-b-tooltips?
The show delay of a Bootstrap Vue tooltip can be set adding a .dXXX modifier, like so:

```<code><b-button v-b-tooltip.d300 title="Tooltip content">Hover Me</b-button>
</code>```

Is there a way to configure the default show delay globally?  I'd like to add a small delay to all tooltips by default.

答:
After some investigation:

Is there a way to configure the default show delay globally?

Not currently.  However, I've submitted a PR to add this feature: https://github.com/bootstrap-vue/bootstrap-vue/pull/3426

Once merged, the delay of both tooltips and popovers can be customized globally like so:

import Vue from 'vue';
import BVConfig from 'bootstrap-vue/es/bv-config';
import BootstrapVue from 'bootstrap-vue';

Vue.use(BVConfig, {
  BTooltip: {
    delay: {
      show: 400,
      hide: 100,
    },
  },
  BPopover: {
    delay: 1000,
  },
});

Vue.use(BootstrapVue);
```

Body:
The show delay of a Bootstrap Vue tooltip can be set adding a .dXXX modifier, like so:

Hover Me

Is there a way to configure the default show delay globally?  I'd like to add a small delay to all tooltips by default.


问:
ASP.NET Core MVC scheduled task
I need to run a scheduled task on every new day in asp.net mvc core application.
Can I do it, and how?!

thnx

答: Generally if you don't want to use azure or any other service you can create a new project. Some kind of a rule engine. The scheduled task will be stored on an DB (for example SQL Server) and then the application will read this task and run the logic. So generally it's better to have a different a different application to  handle scheduled tasks (like cleaning files, emails etc). This type of solution allows you to easilly scale your logic to multiple type of task and apply rules. For example sending email based on various rules you have decided  </p>

Title: ASP.NET Core MVC scheduled task


问:
Clion unable to parse template
I created the following file template in Clion, but when I tried to create a file it said "Unable to parse template". What could be wrong?</p>

```<code>#include <bits/stdc++.h>

using namespace std;

#define endl "\n"

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    return 0;
}
</code>```

答:
Template format requires #[[ and #]] at beginning and end of the file respectively.
More information jetbrains.com/help/clion/using-file-and-code-templates.html

Thanks @john

Title: Clion unable to parse template

Body:
I created the following file template in Clion, but when I tried to create a file it said "Unable to parse template". What could be wrong?

#include <bits/stdc++.h>

using namespace std;

#define endl "\n"

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    return 0;
}


问:
Javafx SimpleStringProperty deserialization throw IllegalStateException: unread block data
Im developing an application using javafx. I have to save my data in a file. Im using serialization, but since im using SimpleStringProperty i have a problem.
SimpleStringProperty  isn't serializable so i created the two methods writeObject and readObject. The write method works well (i think, it write in the file) but the read one dont. When i read the save file i got

```<code>java.lang.IllegalStateException: unread block data throwed.
</code>```

Here is the class diagram of my data. What i try to save is Employee.

```<code>    private void writeObject(ObjectOutputStream s) throws IOException
    {
        s.defaultWriteObject();
        s.writeInt(id);
        s.writeUTF(firstname.get());
        s.writeUTF(lastname.get());
        s.writeUTF(phoneNumber.get());
        s.writeBoolean(gender.get());
    }

    private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException
    {
        id = s.readInt();
        firstname.set(s.readUTF());
        lastname.set(s.readUTF());
        phoneNumber.set(s.readUTF());
        gender.set(s.readBoolean());
    }
</code>```

Do you have an idea of what could the problem be ?

```<code>java.lang.IllegalStateException: unread block data
at java.io.ObjectInputStream$BlockDataInputStream.setBlockDataMode(ObjectInputStream.java:2783)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1605)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2287)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2211)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2069)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1573)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:431)
at java.util.ArrayList.readObject(ArrayList.java:797)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1170)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2178)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2069)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1573)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:431)
at sample.Main.loadData(Main.java:61)
at sample.Main.start(Main.java:27)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$161(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$174(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
at java.lang.Thread.run(Thread.java:748)
</code>```

答: Ok, what i was missing is that when calling readObject, the object isn't initialized, so readObject acts like a constructor. All SimpleProperties where null and firstname.set(s.readUTF()); was throwing a null pointer exception.

Body:
Im developing an application using javafx. I have to save my data in a file. Im using serialization, but since im using SimpleStringProperty i have a problem.
SimpleStringProperty  isn't serializable so i created the two methods writeObject and readObject. The write method works well (i think, it write in the file) but the read one dont. When i read the save file i got

java.lang.IllegalStateException: unread block data throwed.

Here is the class diagram of my data. What i try to save is Employee.

    private void writeObject(ObjectOutputStream s) throws IOException
    {
        s.defaultWriteObject();
        s.writeInt(id);
        s.writeUTF(firstname.get());
        s.writeUTF(lastname.get());
        s.writeUTF(phoneNumber.get());
        s.writeBoolean(gender.get());
    }

    private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException
    {
        id = s.readInt();
        firstname.set(s.readUTF());
        lastname.set(s.readUTF());
        phoneNumber.set(s.readUTF());
        gender.set(s.readBoolean());
    }

Do you have an idea of what could the problem be ?

java.lang.IllegalStateException: unread block data
at java.io.ObjectInputStream$BlockDataInputStream.setBlockDataMode(ObjectInputStream.java:2783)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1605)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2287)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2211)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2069)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1573)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:431)
at java.util.ArrayList.readObject(ArrayList.java:797)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1170)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2178)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2069)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1573)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:431)
at sample.Main.loadData(Main.java:61)
at sample.Main.start(Main.java:27)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$161(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$174(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
at java.lang.Thread.run(Thread.java:748)


问:
Why storage class attribute is missing for boto3 s3 object?
When running retrieval of Storage Class

```<code>import boto3

s3 = boto3.resource('s3')
key = s3.Object('bucket_name','key')
print key.storage_class
</code>```

it returns None

答:
Per AWS documentation:
S3 returns x-amz-storage-class header for all objects except Standard storage class.
https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectGET.html

I'm using the following to get storage class variable:

```<code>import boto3

session = boto3.session.Session(profile_name='dev')
s3_resource = session.resource('s3', region_name=region)
obj_meta = s3_resource.Object(bucket, key_object)

obj_storage_class = 'STANDARD' if obj_meta.storage_class is None else str(obj_meta.storage_class)
</code>```

Body:
When running retrieval of Storage Class

import boto3

s3 = boto3.resource('s3')
key = s3.Object('bucket_name','key')
print key.storage_class

it returns None

Body:
Per AWS documentation:
S3 returns x-amz-storage-class header for all objects except Standard storage class.
https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectGET.html

I'm using the following to get storage class variable:

import boto3

session = boto3.session.Session(profile_name='dev')
s3_resource = session.resource('s3', region_name=region)
obj_meta = s3_resource.Object(bucket, key_object)

obj_storage_class = 'STANDARD' if obj_meta.storage_class is None else str(obj_meta.storage_class)


问:
Display subchildren by signed user
Hello I am new in firebase and I need help with display subchildren of firebase which contain the same userID as signed user

 here is users and edu1 full show of user
I need display just subchildren of signed user

and here is my code
 private FirebaseAuth fAuth;

```<code>private DatabaseReference fNotesDatabase;
ArrayAdapter adapter;
ListView listView;
ArrayList<String> arraylist = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_education);
    fAuth = FirebaseAuth.getInstance();
    listView = findViewById(R.id.listview);
    fNotesDatabase = FirebaseDatabase.getInstance().getReference().child("Notes").child("education");

    fNotesDatabase.addListenerForSingleValueEvent(new ValueEventListener(){
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            for(DataSnapshot datas: dataSnapshot.getChildren()){
                String values = datas.getKey();
                arraylist.add(values);
                adapter = new ArrayAdapter(Education.this, android.R.layout.simple_list_item_single_choice, arraylist);
                listView.setAdapter(adapter);

            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
</code>```

答:
You seem to have a data structure like /Education/Notes/$uid. So to just read the notes of the currently signed in user, do:

```<code>fNotesDatabase = FirebaseDatabase.getInstance().getReference().child("Notes").child("education");
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();

fNotesDatabase.child(uid).addListenerForSingleValueEvent(new ValueEventListener(){
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        ...
</code>```

Title: Display subchildren by signed user

Body:
Hello I am new in firebase and I need help with display subchildren of firebase which contain the same userID as signed user

 here is users and edu1 full show of user
I need display just subchildren of signed user

and here is my code
 private FirebaseAuth fAuth;

private DatabaseReference fNotesDatabase;
ArrayAdapter adapter;
ListView listView;
ArrayList<String> arraylist = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_education);
    fAuth = FirebaseAuth.getInstance();
    listView = findViewById(R.id.listview);
    fNotesDatabase = FirebaseDatabase.getInstance().getReference().child("Notes").child("education");

    fNotesDatabase.addListenerForSingleValueEvent(new ValueEventListener(){
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            for(DataSnapshot datas: dataSnapshot.getChildren()){
                String values = datas.getKey();
                arraylist.add(values);
                adapter = new ArrayAdapter(Education.this, android.R.layout.simple_list_item_single_choice, arraylist);
                listView.setAdapter(adapter);

            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

Body:
You seem to have a data structure like /Education/Notes/$uid. So to just read the notes of the currently signed in user, do:

fNotesDatabase = FirebaseDatabase.getInstance().getReference().child("Notes").child("education");
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();

fNotesDatabase.child(uid).addListenerForSingleValueEvent(new ValueEventListener(){
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        ...


问:
Java Optionals: Return value or do something and continue the loop
In a loop I have code similar to this

```<code>    for (Id id : ids) {
        Item item = itemRepo.findbyId(id);

        if(item == null) {
            Log.error("No item by id");
            continue;
        }

        // bla bla bla
    }
</code>```

What is the best way to rewrite this using Optionals ?

I tried to rewrite and wanted to use ifPresentOrElse to make code shorter but for the method ifPresentOrElse() is written

When we have an Optional instance, often we want to execute a specific action on the underlying value of it. On the other hand, if the Optional is empty we want to log it or track that fact by incrementing some metric.

Hence, I just can not return value if it is there.
Any suggestions?.

Thank you.

UPDATE: I'm sorry, forgot to mention that I need solution with optional as repository function getById has changed and it returns Optional as result.

答:
I don't think an Optional is needed here, a simple else works

```<code>for (Id id : ids) {
    Item item = itemRepo.findbyId(id);

    if(item == null) {
        Log.error("No item by id");
    } else {
        // bla bla bla
    }
}
</code>```

Body:
In a loop I have code similar to this

    for (Id id : ids) {
        Item item = itemRepo.findbyId(id);

        if(item == null) {
            Log.error("No item by id");
            continue;
        }

        // bla bla bla
    }

What is the best way to rewrite this using Optionals ?

I tried to rewrite and wanted to use ifPresentOrElse to make code shorter but for the method ifPresentOrElse() is written

When we have an Optional instance, often we want to execute a specific action on the underlying value of it. On the other hand, if the Optional is empty we want to log it or track that fact by incrementing some metric.

Hence, I just can not return value if it is there.
Any suggestions?.

Thank you.

UPDATE: I'm sorry, forgot to mention that I need solution with optional as repository function getById has changed and it returns Optional as result.

Body:
I don't think an Optional is needed here, a simple else works

for (Id id : ids) {
    Item item = itemRepo.findbyId(id);

    if(item == null) {
        Log.error("No item by id");
    } else {
        // bla bla bla
    }
}


问:
Mongodb user permission read only issue
I have an issue with permissions in Mongodb

```<code>> use test
switched to db test
> db.createUser(
...   {
...     user: "tester",
...     pwd: "123456",
...     roles: [ { role: "readWrite", db: "test" },
...              { role: "read", db: "TestHPO" } ]
...   }
... );
Successfully added user: {
        "user" : "tester",
        "roles" : [
                {
                        "role" : "readWrite",
                        "db" : "test"
                },
                {
                        "role" : "read",
                        "db" : "TestHPO"
                }
        ]
}
> db.auth("tester", "123456" )
1
> use TestHPO
switched to db TestHPO
> db.createCollection("mycollection");
{ "ok" : 1 }
</code>```

The test user has only read permission on TestHPO databases but can create and drop the collection in the above example.

This should be read-only which means just find, where is the issue with my code?

答:
Update/create config file for mongo db with below auth properties:
security:
   authorization: enabled
setParameter:
   authenticationMechanisms: MONGODB-CR

Restart the mongodb with --auth & --config:
mongod --auth --config C:\data\conf\mongod.conf

If the username or password contains a colon (:) or an at-sign (@) then it must be urlencoded otherwise throws exception.

Title: Mongodb user permission read only issue

Body:
I have an issue with permissions in Mongodb

> use test
switched to db test
> db.createUser(
...   {
...     user: "tester",
...     pwd: "123456",
...     roles: [ { role: "readWrite", db: "test" },
...              { role: "read", db: "TestHPO" } ]
...   }
... );
Successfully added user: {
        "user" : "tester",
        "roles" : [
                {
                        "role" : "readWrite",
                        "db" : "test"
                },
                {
                        "role" : "read",
                        "db" : "TestHPO"
                }
        ]
}
> db.auth("tester", "123456" )
1
> use TestHPO
switched to db TestHPO
> db.createCollection("mycollection");
{ "ok" : 1 }

The test user has only read permission on TestHPO databases but can create and drop the collection in the above example.

This should be read-only which means just find, where is the issue with my code?


问:
CSVLogger does not work for model.evaluate process for keras
I want to log the evaluate result to a file with tensorflow 2.0 (keras). I use the callback method. It works well for model.fit but seems not work for model.evaluate.
this is my code:

```<code>csv_logger = CSVLogger(logfile, append=True, separator=';')
model.fit(train_dataset, epochs=50, callbacks=[csv_logger]) // works
model.evaluate(test_dataset, callbacks=[csv_logger]) // not work
</code>```

Am I do the wrong way to log evaluate result to file?

答:
This is expected behaviour. CSVLogger implements callback methods only for training.
For evaluate, on_test_begin(), on_test_batch_begin(), on_test_batch_end() and on_test_end() callback methods are invoked by the keras training module which are not implemented by CSVLogger and hence no csv files are created when used with model.evaluate().

https://github.com/tensorflow/tensorflow/blob/v2.0.0-alpha0/tensorflow/python/keras/callbacks.py#L1514

A custom CSV callback could be implemented like this:

```<code>class MyCSVLogger(Callback):
    def __init__(self, filename):
        self.filename = filename
        print(filename)

    def on_test_begin(self, logs=None):
        # open csv file
        print('test begin')

    def on_test_batch_begin(self, batch, logs=None):
        pass

    def on_test_batch_end(self, batch, logs=None):
        # write the contents of the dictionary logs to csv file
        # sample content of logs {'batch': 0, 'size': 2, 'loss': -0.0, 'accuracy': 1.0}
        print(logs)

    def on_test_end(self, logs=None):
        # close csv file
        print('test end')

csv_logger = MyCSVLogger('abc.csv')
model.evaluate(X_eval,y_eval, callbacks=[csv_logger])
</code>```

Body:
I want to log the evaluate result to a file with tensorflow 2.0 (keras). I use the callback method. It works well for model.fit but seems not work for model.evaluate.
this is my code:

csv_logger = CSVLogger(logfile, append=True, separator=';')
model.fit(train_dataset, epochs=50, callbacks=[csv_logger]) // works
model.evaluate(test_dataset, callbacks=[csv_logger]) // not work

Am I do the wrong way to log evaluate result to file?

Body:
This is expected behaviour. CSVLogger implements callback methods only for training.
For evaluate, on_test_begin(), on_test_batch_begin(), on_test_batch_end() and on_test_end() callback methods are invoked by the keras training module which are not implemented by CSVLogger and hence no csv files are created when used with model.evaluate().

https://github.com/tensorflow/tensorflow/blob/v2.0.0-alpha0/tensorflow/python/keras/callbacks.py#L1514

A custom CSV callback could be implemented like this:

class MyCSVLogger(Callback):
    def __init__(self, filename):
        self.filename = filename
        print(filename)

    def on_test_begin(self, logs=None):
        # open csv file
        print('test begin')

    def on_test_batch_begin(self, batch, logs=None):
        pass

    def on_test_batch_end(self, batch, logs=None):
        # write the contents of the dictionary logs to csv file
        # sample content of logs {'batch': 0, 'size': 2, 'loss': -0.0, 'accuracy': 1.0}
        print(logs)

    def on_test_end(self, logs=None):
        # close csv file
        print('test end')

csv_logger = MyCSVLogger('abc.csv')
model.evaluate(X_eval,y_eval, callbacks=[csv_logger])


问:
Are non-generic collections in .NET obsolete?
Put differently:

Is there a good reason to choose a loosely-typed collection over a type-safe one (HashTable vs. Dictionary)? Are they still there only for compatibility?

As far as I understand, generic collections not only are type-safe, but their performance is better.

Here's a comprehensive article on the topic: An Extensive Examination of Data Structures Using C# 2.0.

答:
I wouldn't jump and say that are obsolete or are going to be removed anytime soon.
It's true that you should avoid using non-generic collections unless you have a reason not not use a generic version. Thousands of lines of legacy (not so legacy) code is still floating around (and will be for years) that support non-generic collections such as ArrayLists. Since these were the only collections in .NET 1.0 and 1.1, it has been widely used (and abused) throughout the year.

I still occasionally have to interact with an old O/R mapper written in .NET 1.1 that returns IList objects. I have a method that does the conversion to a generic List<>, which is not efficient, but that's the way it is.

And if you need to store different objects in the same array (weird but possible) you will need a non-generic collection. The penalty of Boxing and Unboxing is something you'll have to pay anyway.

Don't be afraid to use them if you feel that you have to.

OwnerDisplayName: guillermooo

LastEditorDisplayName: guillermooo

OwnerDisplayName: Martín Marconcini

ContentLicense: CC BY-SA 2.5


问:
Why does this fail in Firefox and Chrome?
This is a common piece of JavaScript used to show a customer splash screen in Silverlight:

```<code>function onSourceDownloadProgressChanged(sender, eventArgs) {
            var myHost = document.getElementById("Xaml1");
            var rectBar = myHost.content.findName("rectBar");
            var rectBorder = myHost.content.findName("rectBorder");
            if (eventArgs.progress)
                rectBar.Width = eventArgs.progress * rectBorder.Width;
            else
                rectBar.Width = eventArgs.get_progress() * rectBorder.Width;
        }
</code>```

For some reason, Firefox and Chrome get errors on this line:

```<code>var rectBar = myHost.content.findName("rectBar");
</code>```

They complain that "myHost is null".

This works fine in Internet Explorer, but in Firefox and Chrome the progress bar is never updated because of this error.

The key portion it is traversing looks like this:

```<code><div id="silverlightControlHost">
        <object id="xaml1" data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
          <param name="source" value="ClientBin/MyApp.xap"/>
          <param name="onError" value="onSilverlightError" />
          <param name="background" value="white" />
          <param name="minRuntimeVersion" value="4.0.50826.0" />
          <param name="autoUpgrade" value="true" />
          <param name="splashscreensource" value="ClientBin/SplashScreen.xaml" />
          <param name="onSourceDownloadProgressChanged" value="onSourceDownloadProgressChanged" />
          <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50826.0" style="text-decoration:none">
              <img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none"/>
          </a>
        </object><iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;width:0px;border:0px"></iframe></div>
</code>```

答: Because it's xaml1, not Xaml1, and Internet Explorer is too lazy to care about your typo.

Body:
This is a common piece of JavaScript used to show a customer splash screen in Silverlight:

function onSourceDownloadProgressChanged(sender, eventArgs) {
            var myHost = document.getElementById("Xaml1");
            var rectBar = myHost.content.findName("rectBar");
            var rectBorder = myHost.content.findName("rectBorder");
            if (eventArgs.progress)
                rectBar.Width = eventArgs.progress * rectBorder.Width;
            else
                rectBar.Width = eventArgs.get_progress() * rectBorder.Width;
        }

For some reason, Firefox and Chrome get errors on this line:

var rectBar = myHost.content.findName("rectBar");

They complain that "myHost is null".

This works fine in Internet Explorer, but in Firefox and Chrome the progress bar is never updated because of this error.

The key portion it is traversing looks like this:

        <object id="xaml1" data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
          <param name="source" value="ClientBin/MyApp.xap"/>
          <param name="onError" value="onSilverlightError" />
          <param name="background" value="white" />
          <param name="minRuntimeVersion" value="4.0.50826.0" />
          <param name="autoUpgrade" value="true" />
          <param name="splashscreensource" value="ClientBin/SplashScreen.xaml" />
          <param name="onSourceDownloadProgressChanged" value="onSourceDownloadProgressChanged" />

        </object>


问:
TextInputLayout hint color not changing after upgrading android support library to 28.0.0
After upgrading the android support library in my project to 28.0.0, I can't change the hint color of a custom TextInput

I have tried changing the color by using a drawable depending of states, changing the textColor attribute, changing the textColorHint attribute... None of them are working, but if change other hint attributes, such as text size, it works.

This situation only occurs when the EditText is not editable

My current hint style:

```<code><style name="TextInputHint" parent="@android:style/TextAppearance">
        <item name="android:textColor">@drawable/textinput_hint_color</item>
        <item name="android:textSize">@dimen/textSize14</item>
        <item name="android:gravity">top</item>
        <item name="android:maxLines">4</item>
        <item name="android:inputType">textMultiLine</item>
        <item name="android:scrollbars">vertical</item>
    </style>
</code>```

And the drawable

```<code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/northTexasGreen" android:state_focused="true"/>
    <item android:color="@color/lightSlateGray" android:state_focused="false"/>
</selector>
</code>```

答:
Below code is working on 28.0.0</p>

```<code>   <android.support.design.widget.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:hintTextAppearance="@style/TextInputHint">

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Checking hint color"
            android:padding="10dp"
            android:textSize="14sp" />
    </android.support.design.widget.TextInputLayout>

<style name="TextInputHint" parent="@android:style/TextAppearance">
    <item name="android:textColor">@drawable/textinput_hint_color</item>
    <item name="android:textSize">@dimen/textSize14</item>
    <item name="android:gravity">top</item>
    <item name="android:maxLines">4</item>
    <item name="android:inputType">textMultiLine</item>
    <item name="android:scrollbars">vertical</item>
</style>

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/northTexasGreen" android:state_focused="true"/>
<item android:color="@color/lightSlateGray" android:state_focused="false"/>
</selector>
</code>```

Body:
After upgrading the android support library in my project to 28.0.0, I can't change the hint color of a custom TextInput

I have tried changing the color by using a drawable depending of states, changing the textColor attribute, changing the textColorHint attribute... None of them are working, but if change other hint attributes, such as text size, it works.

This situation only occurs when the EditText is not editable

My current hint style:

And the drawable

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/northTexasGreen" android:state_focused="true"/>
    <item android:color="@color/lightSlateGray" android:state_focused="false"/>
</selector>

Body:
Below code is working on 28.0.0

   <android.support.design.widget.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:hintTextAppearance="@style/TextInputHint">

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Checking hint color"
            android:padding="10dp"
            android:textSize="14sp" />
    </android.support.design.widget.TextInputLayout>

<style name="TextInputHint" parent="@android:style/TextAppearance">
    <item name="android:textColor">@drawable/textinput_hint_color</item>
    <item name="android:textSize">@dimen/textSize14</item>
    <item name="android:gravity">top</item>
    <item name="android:maxLines">4</item>
    <item name="android:inputType">textMultiLine</item>
    <item name="android:scrollbars">vertical</item>
</style>

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/northTexasGreen" android:state_focused="true"/>
<item android:color="@color/lightSlateGray" android:state_focused="false"/>
</selector>


问:
Problem with using updated values from config file in Codeigniter on autoloading
I use input form in admin dashboard for changing values in custom config file that is loaded in codeigniter over autoloading. I have issue that after submiting(saving), form  values are saved in config file but they are not updated in $this->config->item.

After sending form data to controller and successful saving in config file page is reloaded. Right(updated) values appear in input fields only after one more reload. If config file is loaded only in current controller (not over autoloading) it works ok, but it is needed in many controllers and models. How do I resolve this issue?

答:
As far as i know the data loaded in autoloader is loaded before controller execution. So if you change the data in a called controller it will always differ until reload.

I would recommend handling the data either in a database table or manage it manually in a file (outsource file operation in a library).


问:
Grails Hosting on EC2 Amazon Linux Instance
I have successfully uploaded and deployed my grails application on amazon elastic beanstalk with Tomcat 8 and Java 8 on linux ec2 and web app is up and running. It works well when doing REST API calls to and from RDS database. I have a api to upload file to the server from mobile app and from web app frontend. When running this grails app in localhost its works great for this api and uploads files successfully to user.home/{myapplicationDirectory}/somefile path in my Windows OS. But after running this app in elastic beanstalk and trying to upload image from mobile gives NPE as FileNotFoundException

```<code>FileNotFoundException occurred when processing request: [POST] /api/images/add
/usr/share/tomcat8/sdpl/images/260519011919.zip (No such file or directory)
Stacktrace follows:

java.io.FileNotFoundException: /usr/share/tomcat8/sdpl/images/260519011919.zip (No such file or directory)
    at java.io.FileOutputStream.open(FileOutputStream.java:270)
</code>```

I have a service to get application data storage directory with this method

```<code> def String getApplicationPath() {
        return System.getProperty("user.home") + File.separator + "images" + File.separator;
    }
</code>```

答:
Hi as I don't see your full application I don't want to be too presumptuous but as you're using AWS Beanstalk you should consider local file storage to always be a temporary storage.  Your server could be terminate and restarted by beanstalk if it stops responding or fails any health checks.
You have other options available, again I don't know if you considered them and have a good reason for using the local file system so forgive me if that's the case,  though if not, you could use S3 for the storage of images,  then you don't have to worry about disk space, and the images could automatically be then served via AWS's CDN - Cloudfront, thus also reducing load on your app.

Alternatively, when you really want to store these images in the filesystem, you can look at using EFS,  the Elastic File System.  Your EBS instance could mount the filesystem on startup so it will be always available whenever your instance(s) start.

I didn't suggest using a standard EBS volume, as you can only ever attach a volume to a single instance,  if you used EFS, you don't have to worry about space and it can be mounted to multiple instances so is a little more flexible.

Body:
I have successfully uploaded and deployed my grails application on amazon elastic beanstalk with Tomcat 8 and Java 8 on linux ec2 and web app is up and running. It works well when doing REST API calls to and from RDS database. I have a api to upload file to the server from mobile app and from web app frontend. When running this grails app in localhost its works great for this api and uploads files successfully to user.home/{myapplicationDirectory}/somefile path in my Windows OS. But after running this app in elastic beanstalk and trying to upload image from mobile gives NPE as FileNotFoundException

FileNotFoundException occurred when processing request: [POST] /api/images/add
/usr/share/tomcat8/sdpl/images/260519011919.zip (No such file or directory)
Stacktrace follows:

java.io.FileNotFoundException: /usr/share/tomcat8/sdpl/images/260519011919.zip (No such file or directory)
    at java.io.FileOutputStream.open(FileOutputStream.java:270)

I have a service to get application data storage directory with this method

 def String getApplicationPath() {
        return System.getProperty("user.home") + File.separator + "images" + File.separator;
    }


问:
how three loops are getting executed
I have a problem with this line of code:

```<code>res = [[int(i) for i in sub] for i in test_list for sub in i]
</code>```

When this line will execute int(i) will get 24 in the first iteration and then this 24 is converted into [2,4] as shown in the output listed below.
How 24 can get converted into [2,4] which is a list? To get converted into a list, numbers should be iterable, shouldn't they?

```<code>   test_list = [['24'], ['45'], ['78'], ['40']]
   print("The original list : " + str(test_list))
   res = [[int(i) for i in sub] for i in test_list for sub in i]
   print("The list after conversion : " + str(res))
</code>```

Output is:

```<code>     The original list : [['24'], ['45'], ['78'], ['40']]
     The list after conversion : [[2, 4], [4, 5], [7, 8], [4, 0]]
</code>```

答:
Given

```<code>res = [[int(i) for i in sub] for i in test_list for sub in i]
</code>```

The list comprehension is equivalent to:

```<code>test_list = [['24'], ['45'], ['78'], ['40']]
res = []
for i in test_list: #so, i is similar to ['24'] initially
    for sub in i: #so, sub would be similar to a string '24' initially
        temp = [int(i) for i in sub] #iterate through string 1 character at a time. convert to str.
        res.append(temp)
</code>```

If you notice, i have deliberately left 1 list comprehension inside. It can be expanded further but with a caveat. The i variable does not refer to the i variable outside, because comprehensions come with their own scopes that do not leak.

The entire code would be equivalent to:

```<code>res = []
for i in test_list:
    for sub in i:
        temp = []
        for i_ in sub: #using i_ just to elaborate it is a different value
            temp.append(int(i_))
        res.append(temp)
</code>```

Output:

```<code>[[2, 4], [4, 5], [7, 8], [4, 0]]
</code>```

Title: how three loops are getting executed

Body:
I have a problem with this line of code:

res = [[int(i) for i in sub] for i in test_list for sub in i]

When this line will execute int(i) will get 24 in the first iteration and then this 24 is converted into [2,4] as shown in the output listed below.
How 24 can get converted into [2,4] which is a list? To get converted into a list, numbers should be iterable, shouldn't they?

   test_list = [['24'], ['45'], ['78'], ['40']]
   print("The original list : " + str(test_list))
   res = [[int(i) for i in sub] for i in test_list for sub in i]
   print("The list after conversion : " + str(res))

Output is:

     The original list : [['24'], ['45'], ['78'], ['40']]
     The list after conversion : [[2, 4], [4, 5], [7, 8], [4, 0]]

Body:
Given

res = [[int(i) for i in sub] for i in test_list for sub in i]

The list comprehension is equivalent to:

test_list = [['24'], ['45'], ['78'], ['40']]
res = []
for i in test_list: #so, i is similar to ['24'] initially
    for sub in i: #so, sub would be similar to a string '24' initially
        temp = [int(i) for i in sub] #iterate through string 1 character at a time. convert to str.
        res.append(temp)

If you notice, i have deliberately left 1 list comprehension inside. It can be expanded further but with a caveat. The i variable does not refer to the i variable outside, because comprehensions come with their own scopes that do not leak.

The entire code would be equivalent to:

res = []
for i in test_list:
    for sub in i:
        temp = []
        for i_ in sub: #using i_ just to elaborate it is a different value
            temp.append(int(i_))
        res.append(temp)

Output:

[[2, 4], [4, 5], [7, 8], [4, 0]]


问:
Can hashcodes be compared with <= => signs?
I've come across a piece of code in dart

```<code>id.hashCode <= peerId.hashCode
</code>```

I understand the check == But how does a less than or greater than work with hashcodes. The console just prints out different numbers. What do these number represent to make them comparable by <= and >=

**EDIT:- Adding Context to Question **
The use case is to facilitate 2 users writing to the same node in firestore by hashing the users Firebase uid'sand creating a string like this

```<code>if (currentId.hashCode <= peerId.hashCode) {
    groupChatId = '$currentId-$peerId';
} else {
    groupChatId = '$peerId-$currentId';
}
</code>```

Just making use of the fact the hashcode is an integer and unique

答:
A hashcode in flutter is really just an integer. So when you compare a hash code to a hashcode with < or > what you are doing is comparing whether the integer value of one hash code is larger than the other. I can't think of any actual use for this as hashcodes are typically used to verify that an object is exactly what you want.

Depending on the implementation of calculating the hashcode there could be some meaning to one hashcode being larger than another but I can't think of any real world use cases that would benefit from using a hashcode rather than the specific property you would want to compare.

Body:
I've come across a piece of code in dart

id.hashCode <= peerId.hashCode

I understand the check == But how does a less than or greater than work with hashcodes. The console just prints out different numbers. What do these number represent to make them comparable by <= and >=

**EDIT:- Adding Context to Question **
The use case is to facilitate 2 users writing to the same node in firestore by hashing the users Firebase uid'sand creating a string like this

if (currentId.hashCode <= peerId.hashCode) {
    groupChatId = '$currentId-$peerId';
} else {
    groupChatId = '$peerId-$currentId';
}

Just making use of the fact the hashcode is an integer and unique


问:
Save current date
I need some help in saving the current date. Is there any way to save the current date and time in which that activity is executed?

This is my code so far to declare the current date and time:

```<code>private String currentDateTimeString =
DateFormat.getDateTimeInstance().format(new Date());
</code>```

答:
Best way to store time is in milliseconds format.

```<code>long currentTimeMillis = System.currentTimeMillis();
</code>```

And then while showing convert it to any format you want.

Light weight data can be stored in SharedPreference.

EDIT:

Shared Preference Tutorial

Title: Save current date

Body:
I need some help in saving the current date. Is there any way to save the current date and time in which that activity is executed?

This is my code so far to declare the current date and time:

private String currentDateTimeString =
DateFormat.getDateTimeInstance().format(new Date());

Body:
Best way to store time is in milliseconds format.

long currentTimeMillis = System.currentTimeMillis();

And then while showing convert it to any format you want.

Light weight data can be stored in SharedPreference.

EDIT:

Shared Preference Tutorial


问:
Deploying .Net Core to Linux WebApps on Azure with DevOps
I have a build/release for a .Net Core WebApp that works on windows machines perfectly, however I want to be able to deploy the same codebase to Linux. I set up a build and release and am using the "Web App on Linux" to deploy to my Linux WebApp. I also made sure that the Runtime Stack(s) on BOTH the Build and on the WebApp are set to use .Net Core 2.2:

The builds and the release run perfectly, however once the deployment is complete the website goes to a 404 (replacing the default Azure startup HTML page). I've FTP'd into the WebApp and see that the files are deployed to the machine, however I see that there are multiple "wwwroot" folders:

The top "wwwroot" folder does contain the DLLs for my application so that is a good sign:

Curiously I can get to the static files from my app such as the CSS, JS or the favicon if I navigate to /wwwroot/(filename)

I am pretty sure I have everything set up properly so I am hitting a wall on things to try. I've never had issues like this deploying to Windows WebApps so I am sure there is a setting or something that I am unaware of or is missing from the documentation.

For further details on this issue here is my BUILD:

...and my RELEASE setup:

答:
I had a similar issue and the issue came down to how VS was publishing the zip vs Dev Ops. If you return to the Azure portal you will need to add a startup command specifying where your main DLL is located.

https://learn.microsoft.com/en-us/azure/app-service/containers/app-service-linux-faq#built-in-images


答:
When you do a list comprehension, the output is a list. The input can be any iterable - here, you're using a string - but the output is always a list. So when you do

```<code>[int(i) for i in '24']
</code>```

you're looking at

```<code>[int('2'), int('4')]
</code>```

which resolves to

```<code>[2, 4]
</code>```

If your goal is to get the integer values from this list:

```<code>test_list = [['24'], ['45'], ['78'], ['40']]
</code>```

the better way to go about it is to have just one for loop / list comprehension, not three. No need to iterate through the inner "lists" - if they're only one element, you can just resolve that manually:

```<code>res = [int(num[0]) for num in test_list]  # num == ['24'], so num[0] == '24'
# res == [24, 45, 78, 40]
</code>```

Title: how three loops are getting executed

Body:
When you do a list comprehension, the output is a list. The input can be any iterable - here, you're using a string - but the output is always a list. So when you do

[int(i) for i in '24']

you're looking at

[int('2'), int('4')]

which resolves to

[2, 4]

If your goal is to get the integer values from this list:

test_list = [['24'], ['45'], ['78'], ['40']]

the better way to go about it is to have just one for loop / list comprehension, not three. No need to iterate through the inner "lists" - if they're only one element, you can just resolve that manually:

res = [int(num[0]) for num in test_list]  # num == ['24'], so num[0] == '24'
# res == [24, 45, 78, 40]


问:
How can I pass JSON data into a Nunjucks template?
I want to use Nunjucks templates but want to pass in my own JSON data to be used on the templates.

The documentation here is pretty sparse.

https://mozilla.github.io/nunjucks/templating.html

Thank you.

答:
Found this gem here in 2019, but thought it'll be helpful for people like me, who have searched but didn't find anything.

First, create a template part with expected arguments in a macro

```<code>{% macro render(secTitle, secSubtitle) %}
    <h4 class="heading">
        {{ secTitle | safe }}, {{ secSubtitle | safe }}
    </h4>
{% endmacro %}
</code>```

Save it as [yourname].tpl - in this case heading.tpl

Then, import this block and use a function specified in macro above (render() in this case)

```<code>{% block heading %}
    {% import "components/heading.tpl" as heading with context %}
    {{ heading.render(
        secTitle='Hello there',
        secSubtitle='General Kenobi'
    ) }}
{% endblock %}
</code>```

This will result in:

```<code><h4 class="heading">
    Hello there, General Kenobi
</h4>
</code>```

Please notice | safe after strings in a component - this means it'll output the string with HTML formatting (eg.
 will create a new line instead of outputting
 in text).

Body:
Found this gem here in 2019, but thought it'll be helpful for people like me, who have searched but didn't find anything.

First, create a template part with expected arguments in a macro

{% macro render(secTitle, secSubtitle) %}
    <h4 class="heading">
        {{ secTitle | safe }}, {{ secSubtitle | safe }}
    </h4>
{% endmacro %}

Save it as [yourname].tpl - in this case heading.tpl

Then, import this block and use a function specified in macro above (render() in this case)

{% block heading %}
    {% import "components/heading.tpl" as heading with context %}
    {{ heading.render(
        secTitle='Hello there',
        secSubtitle='General Kenobi'
    ) }}
{% endblock %}

This will result in:

<h4 class="heading">
    Hello there, General Kenobi
</h4>

Please notice | safe after strings in a component - this means it'll output the string with HTML formatting (eg. <br> will create a new line instead of outputting <br> in text).