问:
Neural Network - Vector Centric Python implementation
Hello I try to use a vector-centric Neural Network with one input node, one output node and two hidden layer with 3 nodes each to fit a very easy x**2 function. - Just to verify its functionality. Therefore I use the code below. As result I get the orange line, the blue line is the true line.

As you can see something is not working. I have tried to change the number of iterations together with the value of the learning rate but no success. If I plot the Loss over the iterations, I get the following picture for 100 Iterations:

I have not added bias yet but I think this easy function should be fit-able without extra bias nodes. Additionally I assume the failure in the code most likely to be in the "Calculate the Gradients with respect to the weights" part of the code...

So in principal I have two questions:

Is there any basic failure in my code such that the code CAN not work

If not, why does my model fail to fit the easy data

Thanks for help in advance!

Here comes the code - It is ready to play:

```<code>class Neural_Net:
    """
    """
    def __init__(self, activation_function, learning_rate, runs):
        self.activation_function = activation_function
        self.X_train = np.linspace(0,1,1000)
        self.y_train = self.X_train**2
        plt.plot(self.X_train, self.y_train)
        self.y_pred = None
        self.W_input = np.random.randn(1, 3)
        self.Partials_W_input = np.random.randn(1, 3)
        self.W_hidden = np.random.randn(3,3)
        self.Partials_W_hidden = np.random.randn(3,3)
        self.W_output = np.random.randn(3,1)
        self.Partials_W_output = np.random.randn(3,1)
        self.Activations = np.ones((3,2))
        self.Partials = np.ones((3,2))
        self.Output_Gradient = None
        self.Loss = 0
        self.learning_rate = learning_rate
        self.runs = runs
        self.Losses = []
        self.i = 0

    def apply_activation_function(self, activation_vector):
            return 1/(1+np.exp(-activation_vector))

    def forward_pass(self, training_instance):
        for layer in range(len(self.Activations[0])):
            # For the first layer between X and the first hidden layer
            pre_activation_first = self.W_input.T @ training_instance.reshape(1,1)
                # print('pre activation: ', pre_activation)
                # Apply the activation function
                self.Activations[:,0] = self.apply_activation_function(pre_activation_first).ravel()
            else:
                pre_activation_hidden = self.W_hidden.T @ self.Activations[:, layer-1]
                self.Activations[:, layer] = self.apply_activation_function(pre_activation_hidden)
                # print('Activations: ', self.Activations)
        output = self.W_output.T @ self.Activations[:, -1]
        # print('output: ', output)
        return output

    def backpropagation(self, y_true, training_instance):
        if self.activation_function == 'linear':
            # Calculate the ouput gradient
            self.Output_Gradient = -(y_true-self.y_pred)
            # print('Output Gradient: ', self.Output_Gradient)

            # Calculate the partial gradients of the Error with respect to the pre acitvation values in the nodes
            self.Partials[:, 1] = self.Activations[:, 1]*(1-self.Activations[:, 1])*(self.W_output @ self.Output_Gradient)
            self.Partials[:, 0] = self.Activations[:, 0]*(1-self.Activations[:, 0])*(self.W_hidden @ self.Partials[:, 1])
            # print('Partials: ', self.Partials)

            # Calculate the Gradients with respect to the weights
            self.Partials_W_output = self.Output_Gradient * self.Activations[:, -1]
            # print('Partials_W_output: ', self.Partials_W_output)
            self.Partials_W_hidden = self.Partials[:, -1].reshape(3,1) * self.Activations[:, 0].reshape(1,3)
            # print('Partials_W_hidden: ',self.Partials_W_hidden)
            self.Partials_W_input = (self.Partials[:, 0].reshape(3,1) * training_instance.T).T
            # print('Partials_W_input: ', self.Partials_W_input)

    def weight_update(self, training_instance, learning_rate):

        # Output Layer weights
        w_output_old = self.W_output.copy()
        self.W_output = w_output_old - learning_rate*self.Output_Gradient

        # Hidden Layer weights
        w_hidden_old = self.W_hidden.copy()
        self.W_hidden = w_hidden_old - learning_rate * self.W_hidden
        # print('W_hidden new: ', self.W_hidden)

        # Input Layer weights
        w_input_old = self.W_input.copy()
        self.W_input = w_input_old - learning_rate * self.W_input
        # print('W_input new: ', self.W_input)

    def train_model(self):
        for _ in range(self.runs):
            for instance in range(len(self.X_train)):
                # forward pass
                self.y_pred = self.forward_pass(self.X_train[instance])

                # Calculate loss
                self.Loss = self.calc_loss(self.y_pred, self.y_train[instance])
                # print('Loss: ', self.Loss)

                # Calculate backpropagation
                self.backpropagation(self.y_train[instance], self.X_train[instance])

                # Update weights
                self.weight_update(self.X_train[instance], self.learning_rate)

        # print(self.Losses)
        # plt.plot(range(len(self.Losses)), self.Losses)
        # plt.show()

        # Make predictions on training data to check if the model is basically able to fit the training data
        predictions = []
        for i in np.linspace(0,1,1000):
            predictions.append(self.make_prediction(i))
        plt.plot(np.linspace(0,1,1000), predictions)

    def make_prediction(self, X_new):
        return self.forward_pass(X_new)

    def calc_loss(self, y_pred, y_true):
        loss = (1/2)*(y_true-y_pred)**2
        self.Losses.append(loss[0])
        return (1/2)*(y_true-y_pred)**2

    def accuracy(self):
        pass

Neural_Net('linear', 0.0001, 10).train_model()
</code>```

答:
I have solved the issue:
First I have mixed up some dimensions which I have corrected. Though, the true issue has been the weight update where I have tried to update the weights with e.g.

```<code>self.W_hidden = w_hidden_old - learning_rate * self.W_hidden
</code>```

but this is wrong since the learning rate has to be multiplied with the partial of the error with respect to the weights and not with the weights matrix itself. So the correct way is:

```<code>self.W_hidden = w_hidden_old - learning_rate * self.Partials_W_hidden
</code>```

After that I receive the following result and loss curve:

The final code is:

```<code>class Neural_Net:
    """
    """
    def __init__(self, activation_function, learning_rate, runs):
        self.activation_function = activation_function

        self.Data = pd.read_csv(r"U:\19_035_Machine_Learning_Workshop\2_Workshopinhalt\Weitere\Neural Networks\AirQualityUCI\AirQualityUCI.csv", sep=';', decimal=b',').iloc[:, :-2].dropna()
        self.X_train = np.linspace(0,5,1000)
        self.y_train = np.sin(self.X_train)
        plt.plot(self.X_train, self.y_train)
        self.y_pred = None
        self.W_input = np.random.randn(1, 3)
        self.Partials_W_input = np.random.randn(1, 3)
        self.W_hidden = np.random.randn(3,3)
        self.Partials_W_hidden = np.random.randn(3,3)
        self.W_output = np.random.randn(3,1)
        self.Partials_W_output = np.random.randn(3,1)
        self.Activations = np.zeros((3,2))
        self.Partials = np.zeros((3,2))
        self.Output_Gradient = None
        self.Loss = 0
        self.learning_rate = learning_rate
        self.runs = runs
        self.Losses = []
        self.i = 0

    def apply_activation_function(self, activation_vector):
        # print('activation: ', 1/(1+np.exp(-activation_vector)))
        return 1/(1+np.exp(-activation_vector))

    def forward_pass(self, training_instance):
        for layer in range(len(self.Activations[0])):
            # For the first layer between X and the first hidden layer
            if layer == 0:
                pre_activation_first = self.W_input.T @ training_instance.reshape(1,1)
                # print('pre activation: ', pre_activation)
                # Apply the activation function
                self.Activations[:,0] = self.apply_activation_function(pre_activation_first).ravel()
            else:
                pre_activation_hidden = self.W_hidden.T @ self.Activations[:, layer-1]
                self.Activations[:, layer] = self.apply_activation_function(pre_activation_hidden)
                # print('Activations: ', self.Activations)
        output = self.W_output.T @ self.Activations[:, -1].reshape(-1,1)
        # print('output: ', output)
        return output

    def backpropagation(self, y_true, training_instance):
        if self.activation_function == 'sigmoid':
            pass
        if self.activation_function == 'linear':
            # Calculate the ouput gradient
            self.Output_Gradient = -(y_true-self.y_pred)
            # print('Output Gradient: ', self.Output_Gradient)

            # Calculate the partial gradients of the Error with respect to the pre acitvation values in the nodes
            self.Partials[:, 1] = ((self.Activations[:, 1]*(1-self.Activations[:, 1])).reshape(-1,1)*(self.W_output @ self.Output_Gradient)).ravel()
            self.Partials[:, 0] = self.Activations[:, 0]*(1-self.Activations[:, 0])*(self.W_hidden @ self.Partials[:, 1])
            # print('Partials: ', self.Partials)

            # Calculate the Gradients with respect to the weights
            self.Partials_W_output = self.Output_Gradient * self.Activations[:, -1]
            # print('Partials_W_output: ', self.Partials_W_output)
            self.Partials_W_hidden = self.Partials[:, -1].reshape(3,1) * self.Activations[:, 0].reshape(1,3)
            # print('Partials_W_hidden: ',self.Partials_W_hidden)
            self.Partials_W_input = (self.Partials[:, 0].reshape(3,1) * training_instance.T).T
            # print('Partials_W_input: ', self.Partials_W_input)

    def weight_update(self, training_instance, learning_rate):

        # Output Layer weights
        w_output_old = self.W_output.copy()
        self.W_output = w_output_old - learning_rate*self.Partials_W_output.reshape(-1,1)

        # Hidden Layer weights
        w_hidden_old = self.W_hidden.copy()
        self.W_hidden = w_hidden_old - learning_rate * self.Partials_W_hidden
        # print('W_hidden new: ', self.W_hidden)

        # Input Layer weights
        w_input_old = self.W_input.copy()
        self.W_input = w_input_old - learning_rate * self.Partials_W_input
        # print('W_input new: ', self.W_input)

    def train_model(self):
        # print('Initially predicted Value: ', self.make_prediction(self.X_test[0]))
        # print('True value: ', self.y_test[0])
        for _ in range(self.runs):
            for instance in range(len(self.X_train)):
                # forward pass
                self.y_pred = self.forward_pass(self.X_train[instance])

                # Calculate loss
                self.Loss = self.calc_loss(self.y_pred, self.y_train[instance])
                # print('Loss: ', self.Loss)

                # Calculate backpropagation
                self.backpropagation(self.y_train[instance], self.X_train[instance])

                # Update weights
                self.weight_update(self.X_train[instance], self.learning_rate)

        # print(self.Losses)
        # plt.plot(range(len(self.Losses)), self.Losses)
        # plt.show()

        # Make predictions
        predictions = []
        for i in np.linspace(0,5,1000):
            predictions.append(self.make_prediction(i)[0])
        plt.plot(np.linspace(0,5,1000), predictions)

    def make_prediction(self, X_new):
        return self.forward_pass(X_new)

    def calc_loss(self, y_pred, y_true):
        loss = (1/2)*(y_true-y_pred)**2
        self.Losses.append(loss[0])
        return (1/2)*(y_true-y_pred)**2

    def accuracy(self):
        pass

Neural_Net('linear', 0.1, 1500).train_model()
</code>```

To optimize the code we have to add bias in the input an hidden layer.

Body:
Hello I try to use a vector-centric Neural Network with one input node, one output node and two hidden layer with 3 nodes each to fit a very easy x**2 function. - Just to verify its functionality. Therefore I use the code below. As result I get the orange line, the blue line is the true line.

As you can see something is not working. I have tried to change the number of iterations together with the value of the learning rate but no success. If I plot the Loss over the iterations, I get the following picture for 100 Iterations:

I have not added bias yet but I think this easy function should be fit-able without extra bias nodes. Additionally I assume the failure in the code most likely to be in the "Calculate the Gradients with respect to the weights" part of the code...

So in principal I have two questions:

Is there any basic failure in my code such that the code CAN not work

If not, why does my model fail to fit the easy data

Thanks for help in advance!

Here comes the code - It is ready to play:

class Neural_Net:
    """
    """
    def __init__(self, activation_function, learning_rate, runs):
        self.activation_function = activation_function
        self.X_train = np.linspace(0,1,1000)
        self.y_train = self.X_train**2
        plt.plot(self.X_train, self.y_train)
        self.y_pred = None
        self.W_input = np.random.randn(1, 3)
        self.Partials_W_input = np.random.randn(1, 3)
        self.W_hidden = np.random.randn(3,3)
        self.Partials_W_hidden = np.random.randn(3,3)
        self.W_output = np.random.randn(3,1)
        self.Partials_W_output = np.random.randn(3,1)
        self.Activations = np.ones((3,2))
        self.Partials = np.ones((3,2))
        self.Output_Gradient = None
        self.Loss = 0
        self.learning_rate = learning_rate
        self.runs = runs
        self.Losses = []
        self.i = 0

    def apply_activation_function(self, activation_vector):
            return 1/(1+np.exp(-activation_vector))

    def forward_pass(self, training_instance):
        for layer in range(len(self.Activations[0])):
            # For the first layer between X and the first hidden layer
            pre_activation_first = self.W_input.T @ training_instance.reshape(1,1)
                # print('pre activation: ', pre_activation)
                # Apply the activation function
                self.Activations[:,0] = self.apply_activation_function(pre_activation_first).ravel()
            else:
                pre_activation_hidden = self.W_hidden.T @ self.Activations[:, layer-1]
                self.Activations[:, layer] = self.apply_activation_function(pre_activation_hidden)
                # print('Activations: ', self.Activations)
        output = self.W_output.T @ self.Activations[:, -1]
        # print('output: ', output)
        return output

    def backpropagation(self, y_true, training_instance):
        if self.activation_function == 'linear':
            # Calculate the ouput gradient
            self.Output_Gradient = -(y_true-self.y_pred)
            # print('Output Gradient: ', self.Output_Gradient)

            # Calculate the partial gradients of the Error with respect to the pre acitvation values in the nodes
            self.Partials[:, 1] = self.Activations[:, 1]*(1-self.Activations[:, 1])*(self.W_output @ self.Output_Gradient)
            self.Partials[:, 0] = self.Activations[:, 0]*(1-self.Activations[:, 0])*(self.W_hidden @ self.Partials[:, 1])
            # print('Partials: ', self.Partials)

            # Calculate the Gradients with respect to the weights
            self.Partials_W_output = self.Output_Gradient * self.Activations[:, -1]
            # print('Partials_W_output: ', self.Partials_W_output)
            self.Partials_W_hidden = self.Partials[:, -1].reshape(3,1) * self.Activations[:, 0].reshape(1,3)
            # print('Partials_W_hidden: ',self.Partials_W_hidden)
            self.Partials_W_input = (self.Partials[:, 0].reshape(3,1) * training_instance.T).T
            # print('Partials_W_input: ', self.Partials_W_input)

    def weight_update(self, training_instance, learning_rate):

        # Output Layer weights
        w_output_old = self.W_output.copy()
        self.W_output = w_output_old - learning_rate*self.Output_Gradient

        # Hidden Layer weights
        w_hidden_old = self.W_hidden.copy()
        self.W_hidden = w_hidden_old - learning_rate * self.W_hidden
        # print('W_hidden new: ', self.W_hidden)

        # Input Layer weights
        w_input_old = self.W_input.copy()
        self.W_input = w_input_old - learning_rate * self.W_input
        # print('W_input new: ', self.W_input)

    def train_model(self):
        for _ in range(self.runs):
            for instance in range(len(self.X_train)):
                # forward pass
                self.y_pred = self.forward_pass(self.X_train[instance])

                # Calculate loss
                self.Loss = self.calc_loss(self.y_pred, self.y_train[instance])
                # print('Loss: ', self.Loss)

                # Calculate backpropagation
                self.backpropagation(self.y_train[instance], self.X_train[instance])

                # Update weights
                self.weight_update(self.X_train[instance], self.learning_rate)

        # print(self.Losses)
        # plt.plot(range(len(self.Losses)), self.Losses)
        # plt.show()

        # Make predictions on training data to check if the model is basically able to fit the training data
        predictions = []
        for i in np.linspace(0,1,1000):
            predictions.append(self.make_prediction(i))
        plt.plot(np.linspace(0,1,1000), predictions)

    def make_prediction(self, X_new):
        return self.forward_pass(X_new)

    def calc_loss(self, y_pred, y_true):
        loss = (1/2)*(y_true-y_pred)**2
        self.Losses.append(loss[0])
        return (1/2)*(y_true-y_pred)**2

    def accuracy(self):
        pass

Neural_Net('linear', 0.0001, 10).train_model()

Body:
I have solved the issue:
First I have mixed up some dimensions which I have corrected. Though, the true issue has been the weight update where I have tried to update the weights with e.g.

self.W_hidden = w_hidden_old - learning_rate * self.W_hidden

but this is wrong since the learning rate has to be multiplied with the partial of the error with respect to the weights and not with the weights matrix itself. So the correct way is:

self.W_hidden = w_hidden_old - learning_rate * self.Partials_W_hidden

After that I receive the following result and loss curve:

The final code is:

class Neural_Net:
    """
    """
    def __init__(self, activation_function, learning_rate, runs):
        self.activation_function = activation_function

        self.Data = pd.read_csv(r"U:\19_035_Machine_Learning_Workshop\2_Workshopinhalt\Weitere\Neural Networks\AirQualityUCI\AirQualityUCI.csv", sep=';', decimal=b',').iloc[:, :-2].dropna()
        self.X_train = np.linspace(0,5,1000)
        self.y_train = np.sin(self.X_train)
        plt.plot(self.X_train, self.y_train)
        self.y_pred = None
        self.W_input = np.random.randn(1, 3)
        self.Partials_W_input = np.random.randn(1, 3)
        self.W_hidden = np.random.randn(3,3)
        self.Partials_W_hidden = np.random.randn(3,3)
        self.W_output = np.random.randn(3,1)
        self.Partials_W_output = np.random.randn(3,1)
        self.Activations = np.zeros((3,2))
        self.Partials = np.zeros((3,2))
        self.Output_Gradient = None
        self.Loss = 0
        self.learning_rate = learning_rate
        self.runs = runs
        self.Losses = []
        self.i = 0

    def apply_activation_function(self, activation_vector):
        # print('activation: ', 1/(1+np.exp(-activation_vector)))
        return 1/(1+np.exp(-activation_vector))

    def forward_pass(self, training_instance):
        for layer in range(len(self.Activations[0])):
            # For the first layer between X and the first hidden layer
            if layer == 0:
                pre_activation_first = self.W_input.T @ training_instance.reshape(1,1)
                # print('pre activation: ', pre_activation)
                # Apply the activation function
                self.Activations[:,0] = self.apply_activation_function(pre_activation_first).ravel()
            else:
                pre_activation_hidden = self.W_hidden.T @ self.Activations[:, layer-1]
                self.Activations[:, layer] = self.apply_activation_function(pre_activation_hidden)
                # print('Activations: ', self.Activations)
        output = self.W_output.T @ self.Activations[:, -1].reshape(-1,1)
        # print('output: ', output)
        return output

    def backpropagation(self, y_true, training_instance):
        if self.activation_function == 'sigmoid':
            pass
        if self.activation_function == 'linear':
            # Calculate the ouput gradient
            self.Output_Gradient = -(y_true-self.y_pred)
            # print('Output Gradient: ', self.Output_Gradient)

            # Calculate the partial gradients of the Error with respect to the pre acitvation values in the nodes
            self.Partials[:, 1] = ((self.Activations[:, 1]*(1-self.Activations[:, 1])).reshape(-1,1)*(self.W_output @ self.Output_Gradient)).ravel()
            self.Partials[:, 0] = self.Activations[:, 0]*(1-self.Activations[:, 0])*(self.W_hidden @ self.Partials[:, 1])
            # print('Partials: ', self.Partials)

            # Calculate the Gradients with respect to the weights
            self.Partials_W_output = self.Output_Gradient * self.Activations[:, -1]
            # print('Partials_W_output: ', self.Partials_W_output)
            self.Partials_W_hidden = self.Partials[:, -1].reshape(3,1) * self.Activations[:, 0].reshape(1,3)
            # print('Partials_W_hidden: ',self.Partials_W_hidden)
            self.Partials_W_input = (self.Partials[:, 0].reshape(3,1) * training_instance.T).T
            # print('Partials_W_input: ', self.Partials_W_input)

    def weight_update(self, training_instance, learning_rate):

        # Output Layer weights
        w_output_old = self.W_output.copy()
        self.W_output = w_output_old - learning_rate*self.Partials_W_output.reshape(-1,1)

        # Hidden Layer weights
        w_hidden_old = self.W_hidden.copy()
        self.W_hidden = w_hidden_old - learning_rate * self.Partials_W_hidden
        # print('W_hidden new: ', self.W_hidden)

        # Input Layer weights
        w_input_old = self.W_input.copy()
        self.W_input = w_input_old - learning_rate * self.Partials_W_input
        # print('W_input new: ', self.W_input)

    def train_model(self):
        # print('Initially predicted Value: ', self.make_prediction(self.X_test[0]))
        # print('True value: ', self.y_test[0])
        for _ in range(self.runs):
            for instance in range(len(self.X_train)):
                # forward pass
                self.y_pred = self.forward_pass(self.X_train[instance])

                # Calculate loss
                self.Loss = self.calc_loss(self.y_pred, self.y_train[instance])
                # print('Loss: ', self.Loss)

                # Calculate backpropagation
                self.backpropagation(self.y_train[instance], self.X_train[instance])

                # Update weights
                self.weight_update(self.X_train[instance], self.learning_rate)

        # print(self.Losses)
        # plt.plot(range(len(self.Losses)), self.Losses)
        # plt.show()

        # Make predictions
        predictions = []
        for i in np.linspace(0,5,1000):
            predictions.append(self.make_prediction(i)[0])
        plt.plot(np.linspace(0,5,1000), predictions)

    def make_prediction(self, X_new):
        return self.forward_pass(X_new)

    def calc_loss(self, y_pred, y_true):
        loss = (1/2)*(y_true-y_pred)**2
        self.Losses.append(loss[0])
        return (1/2)*(y_true-y_pred)**2

    def accuracy(self):
        pass

Neural_Net('linear', 0.1, 1500).train_model()

To optimize the code we have to add bias in the input an hidden layer.


来源: stackexchange

问:
Flutter: create an Object from Type or String
I want to create an Object from an object type defined in Type or from an object name defined in String. The following example uses a String to hold the object type. But I think this is not that elegant - even with Type, this if block would increase dramatically for a lot of object types...

I didn't find a better solution for this yet. How can I create that object dynamically from the specified object type?

if (model == 'Event') {
  data = Event.fromMap(result);
}
else if (model == 'Content') {
  data = Content.fromMap(result);
}
else if (...) {
  // ...
}
```

答:
This is other approach.

class Event{
  Event.fromMap(_map){
    print('This is an event');
    print(_map);
  }
}

class Content{
  Content.fromMap(_map){
    print('This is a content');
    print(_map);
  }
}

Map<String, Function> types = {
  'Event' : (_map)=>Event.fromMap(_map),
  'Content' : (_map)=>Content.fromMap(_map),
};

void main() {
  var a = types['Event']({'test':'success_event'});
  print(a.runtimeType);
  var b = types['Content']({'test':'success_content'});
  print(b.runtimeType);
}
```

<p>Its a bit more scalable (since only depends on add the class constructor into the map).</p>

<p>The explanation:</p>

<pre class="lang-dart prettyprint-override"><code>class Event{
  Event.fromMap(_map){
    print('This is an event');
    print(_map);
  }
}

class Content{
  Content.fromMap(_map){
    print('This is a content');
    print(_map);
  }
}
</code>```

Here we are creating the test classes. nothing important.

Map<String, Function> types = {
  'Event' : (_map)=>Event.fromMap(_map),
  'Content' : (_map)=>Content.fromMap(_map),
};
```

<p>Here we are defining a <code>Map</code>. Why? Because it allows us to access some value through some key in constant time. In this case, the keys are the Strings 'Event', 'Content', but also can be types as you wanted. For simplicity, let them be Strings. The values are <code>Function</code>'s, in this example only getting as parameter a <code>_map</code> (because the Class constructors in the example require one parameter <code>_map</code>). So, if you need more types, only add the type and the function encapsulating the constructor for that type.</p>

<pre class="lang-dart prettyprint-override"><code>void main() {
  var a = types['Event']({'test':'success_event'});
  print(a.runtimeType);
  var b = types['Content']({'test':'success_content'});
  print(b.runtimeType);
}
</code>```

Finally you can instantiate the classes easily. Only with the type string and passing to the function the values you want (In this example a map with a key 'test').

In your example would be something like:

data = types[model](result);
```

ContentLicense: CC BY-SA 4.0

Body:
This is other approach.

class Event{
  Event.fromMap(_map){
    print('This is an event');
    print(_map);
  }
}

class Content{
  Content.fromMap(_map){
    print('This is a content');
    print(_map);
  }
}

Map<String, Function> types = {
  'Event' : (_map)=>Event.fromMap(_map),
  'Content' : (_map)=>Content.fromMap(_map),
};

void main() {
  var a = types['Event']({'test':'success_event'});
  print(a.runtimeType);
  var b = types['Content']({'test':'success_content'});
  print(b.runtimeType);
}

Its a bit more scalable (since only depends on add the class constructor into the map).

The explanation:

class Event{
  Event.fromMap(_map){
    print('This is an event');
    print(_map);
  }
}

class Content{
  Content.fromMap(_map){
    print('This is a content');
    print(_map);
  }
}

Here we are creating the test classes. nothing important.

Map<String, Function> types = {
  'Event' : (_map)=>Event.fromMap(_map),
  'Content' : (_map)=>Content.fromMap(_map),
};

Here we are defining a Map. Why? Because it allows us to access some value through some key in constant time. In this case, the keys are the Strings 'Event', 'Content', but also can be types as you wanted. For simplicity, let them be Strings. The values are Function's, in this example only getting as parameter a _map (because the Class constructors in the example require one parameter _map). So, if you need more types, only add the type and the function encapsulating the constructor for that type.

void main() {
  var a = types['Event']({'test':'success_event'});
  print(a.runtimeType);
  var b = types['Content']({'test':'success_content'});
  print(b.runtimeType);
}

Finally you can instantiate the classes easily. Only with the type string and passing to the function the values you want (In this example a map with a key 'test').

In your example would be something like:

data = types[model](result);


问:
Coredata is very slow; swift
i've made an iOS App tracking the gps route of the device.
The problem is, that coredata needs very long to save, when i am tracking more than 5 min.
I save an object called session and session have much location objects.
the location object is [ [latitude, longitude] ]

and the session object looks like [name: string, date: nsdate, average speed: double, high speed: double, driven kilometers: double, locations: [ [double, double] ] ]

so... it works, but after 5 min. it takes i think 2 or 3 minutes to save

答:
Updated for 2020...

Basically you pretty much have to use the "alternate context" which is nowadays provided by core data.

So core.container is "your" container ... very likely from your core data stack singleton.

So new data arrives for your birds of the world database ...

```<code>let pm = core.container.newBackgroundContext()
pm.perform {
    for oneBudgie in someNewData {
        ... create your new CDBudgie entity ...
        ... take EXTREME care to use "pm" throughout ...
        ... take EXTREME care to NEVER use .viewContext throughout ...
    }
}
</code>```

During the loop,

... exercise extreme caution that you do not use .viewContext inside that loop. Use only "pm" inside the loop. Be especially careful if you call other code.

Say for example you have a utility routine which "finds a certain item".

Or perhaps a utility routine which simply grabs the main user.

It's possible those utility routines simply use your usual main context, core.container.viewContext .

When you write such utility routines, it's natural to just use the main context, without thinking about it.

But. It's very easy to accidentally use such a utility routine, during your code, inside the loop.

If you do that, the app will crash instantly.

You must not accidentally use core.container.viewContext somewhere deep during the code inside the loop.

You can ONLY use "pm" for anything CoreData, within the loop or from any code whatsoever which is ultimately called, no matter how deeply nested, from within that loop.

After all the new items are created, it seems you do precisely this:

```<code>func bake() {
    self.performAndWait {
        if self.hasChanges {
            do {
                try self.save()
            }
            catch { print("bake disaster type 1 \(error)") }
        }

        // BUT SEE NOTES BELOW
        if core.container.viewContext.hasChanges {
            do {
                try core.container.viewContext.save()
            }
            catch { print("bake disaster type 2 \(error)") }
        }
        // BUT SEE NOTES BELOW

    }
}
</code>```

As far as I know. Nobody really knows, but that's as far as I know.

Hence,

```<code>let pm = core.container.newBackgroundContext()
pm.perform {
    for oneBudgie in someNewData {
        ... create your new CDBudgie entity ...
        ... be absolutely certain to only use 'pm' ...
    }
    pm.bake()
}
</code>```

However in practice today you need do NOTHING with the main context:

All the many examples of "...and then save the main context" are basically wrong today.

In reality today in 99.9999% of case you will be using .automaticallyMergesChangesFromParent = true which now works perfectly and smoothly.  (Example of how to do that.)

In the bake() example above, if you literally add a couple of print lines to check what happens in the second save, you will see that ...

...there is NEVER anything to be saved back on the main context!

Thus in practice your bake routine is this simple,

```<code>func bake() {
    self.performAndWait {
        if self.hasChanges {
            do {
                try self.save()
            }
            catch { print("bake disaster type 1 \(error)") }
        }
}
</code>```

And a final point...

Notice that the overall bake is actually called inside a performAndWait. But, the bake itself does the important save, inside a performAndWait.

I do know that it works extremely reliably that way.

The (very few people who discuss the issue) suggest the inner one is needed.

However: it seems to me that you do not need the inner performAndWait.

So conceivably bake is even simpler -

```<code>func bake() {
    if self.hasChanges {
        do {
            try self.save()
        }
        catch {
            print("woe \(error)")
        }
    }
}
</code>```

When I try that form of bake, it does seem to work well with no problems. But then, with Core Data you have to test for, well, years to find problems.

As I mention in a comment, I think there's about 2 places on the internet where this is explained, @AndyIbanez original answer above, and this updated version!

ContentLicense: CC BY-SA 3.0

Title: Coredata is very slow; swift

Body:
Updated for 2020...

Basically you pretty much have to use the "alternate context" which is nowadays provided by core data.

So core.container is "your" container ... very likely from your core data stack singleton.

So new data arrives for your birds of the world database ...

let pm = core.container.newBackgroundContext()
pm.perform {
    for oneBudgie in someNewData {
        ... create your new CDBudgie entity ...
        ... take EXTREME care to use "pm" throughout ...
        ... take EXTREME care to NEVER use .viewContext throughout ...
    }
}

During the loop,

... exercise extreme caution that you do not use .viewContext inside that loop. Use only "pm" inside the loop. Be especially careful if you call other code.

Say for example you have a utility routine which "finds a certain item".

Or perhaps a utility routine which simply grabs the main user.

It's possible those utility routines simply use your usual main context, core.container.viewContext .

When you write such utility routines, it's natural to just use the main context, without thinking about it.

But. It's very easy to accidentally use such a utility routine, during your code, inside the loop.

If you do that, the app will crash instantly.

You must not accidentally use core.container.viewContext somewhere deep during the code inside the loop.

You can ONLY use "pm" for anything CoreData, within the loop or from any code whatsoever which is ultimately called, no matter how deeply nested, from within that loop.

After all the new items are created, it seems you do precisely this:

func bake() {
    self.performAndWait {
        if self.hasChanges {
            do {
                try self.save()
            }
            catch { print("bake disaster type 1 \(error)") }
        }

        // BUT SEE NOTES BELOW
        if core.container.viewContext.hasChanges {
            do {
                try core.container.viewContext.save()
            }
            catch { print("bake disaster type 2 \(error)") }
        }
        // BUT SEE NOTES BELOW

    }
}

As far as I know. Nobody really knows, but that's as far as I know.

Hence,

let pm = core.container.newBackgroundContext()
pm.perform {
    for oneBudgie in someNewData {
        ... create your new CDBudgie entity ...
        ... be absolutely certain to only use 'pm' ...
    }
    pm.bake()
}

However in practice today you need do NOTHING with the main context:

All the many examples of "...and then save the main context" are basically wrong today.

In reality today in 99.9999% of case you will be using .automaticallyMergesChangesFromParent = true which now works perfectly and smoothly.  (Example of how to do that.)

In the bake() example above, if you literally add a couple of print lines to check what happens in the second save, you will see that ...

...there is NEVER anything to be saved back on the main context!

Thus in practice your bake routine is this simple,

func bake() {
    self.performAndWait {
        if self.hasChanges {
            do {
                try self.save()
            }
            catch { print("bake disaster type 1 \(error)") }
        }
}

And a final point...

Notice that the overall bake is actually called inside a performAndWait. But, the bake itself does the important save, inside a performAndWait.

I do know that it works extremely reliably that way.

The (very few people who discuss the issue) suggest the inner one is needed.

However: it seems to me that you do not need the inner performAndWait.

So conceivably bake is even simpler -

func bake() {
    if self.hasChanges {
        do {
            try self.save()
        }
        catch {
            print("woe \(error)")
        }
    }
}

When I try that form of bake, it does seem to work well with no problems. But then, with Core Data you have to test for, well, years to find problems.

As I mention in a comment, I think there's about 2 places on the internet where this is explained, @AndyIbanez original answer above, and this updated version!


问:
migrate .net core 2.2 to 3.1 issue
After installing .NET core SDK 3.1 and upgrading all my projects' SDK [in my solution] from .NET core SDK 2.2 to 3.1, and updating all packages such as extension to 3.1 version, I successfully built all projects in my solution.

But then I got this error:

C:\Program
  Files\dotnet\sdk\3.1.101\Sdks\Microsoft.NET.Sdk\targets\Microsoft.NET.Sdk.FrameworkReferenceResolution.targets(59,5):
  error NETSDK1083: The specified RuntimeIdentifier 'win7-64' is not
  recognized. C:\Program
  Files\dotnet\sdk\3.1.101\Sdks\Microsoft.NET.Sdk\targets\Microsoft.NET.Sdk.FrameworkReferenceResolution.targets(59,5):
  error NETSDK1083: The specified RuntimeIdentifier 'win7-86' is not
  recognized.

This is my WebApi.csproj:

```<code><Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup Label="Globals">
    <SccProjectName>SAK</SccProjectName>
    <SccProvider>SAK</SccProvider>
    <SccAuxPath>SAK</SccAuxPath>
    <SccLocalPath>SAK</SccLocalPath>
  </PropertyGroup>

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

  <PropertyGroup>
    <RuntimeIdentifiers>win7-64;win7-86;ubuntu.16.04-x64;win10-x64;osx.10.11-x64</RuntimeIdentifiers>
  </PropertyGroup>

  <PropertyGroup>
    <GenerateDocumentationFile>true</GenerateDocumentationFile>
    <LangVersion>7.1</LangVersion>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <NoWarn>1591</NoWarn>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
    <NoWarn>1701;1702;1591</NoWarn>
  </PropertyGroup>

  <ItemGroup>
    <None Remove="swagger.css" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="xxxxxx" Version="x.x.x" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\xxxx.csproj" />
  </ItemGroup>

</Project>

</code>```

答:
as @Neil  said

Remove the whole 'runtimeIdentifiers' section, you only need it if you are doing cross-platform work.

this way solved my problem.

Title: migrate .net core 2.2 to 3.1 issue

Body:
After installing .NET core SDK 3.1 and upgrading all my projects' SDK [in my solution] from .NET core SDK 2.2 to 3.1, and updating all packages such as extension to 3.1 version, I successfully built all projects in my solution.

But then I got this error:

C:\Program
  Files\dotnet\sdk\3.1.101\Sdks\Microsoft.NET.Sdk\targets\Microsoft.NET.Sdk.FrameworkReferenceResolution.targets(59,5):
  error NETSDK1083: The specified RuntimeIdentifier 'win7-64' is not
  recognized. C:\Program
  Files\dotnet\sdk\3.1.101\Sdks\Microsoft.NET.Sdk\targets\Microsoft.NET.Sdk.FrameworkReferenceResolution.targets(59,5):
  error NETSDK1083: The specified RuntimeIdentifier 'win7-86' is not
  recognized.

This is my WebApi.csproj:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup Label="Globals">
    <SccProjectName>SAK</SccProjectName>
    <SccProvider>SAK</SccProvider>
    <SccAuxPath>SAK</SccAuxPath>
    <SccLocalPath>SAK</SccLocalPath>
  </PropertyGroup>

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

  <PropertyGroup>
    <RuntimeIdentifiers>win7-64;win7-86;ubuntu.16.04-x64;win10-x64;osx.10.11-x64</RuntimeIdentifiers>
  </PropertyGroup>

  <PropertyGroup>
    <GenerateDocumentationFile>true</GenerateDocumentationFile>
    <LangVersion>7.1</LangVersion>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <NoWarn>1591</NoWarn>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
    <NoWarn>1701;1702;1591</NoWarn>
  </PropertyGroup>

  <ItemGroup>
    <None Remove="swagger.css" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="xxxxxx" Version="x.x.x" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\xxxx.csproj" />
  </ItemGroup>

</Project>


问:
HostPath assign persistentVolume to the specific work node in cluster
Using kubeadm to create a cluster, I have a master and work node.

Now I want to share a persistentVolume in the work node, which will be bound with Postgres pod.

Expecting the code will create persistentVolume in the path /postgres of work node, but it seems the hostPath will not work in a cluster, how should I assign this property to the specific node?

```<code>kind: PersistentVolume
apiVersion: v1
metadata:
  name: pv-postgres
  labels:
    type: local
spec:
  capacity:
    storage: 2Gi
  accessModes:
    - ReadWriteOnce
  hostPath:
    path: "/postgres"
---
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: pvc-postgres
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 1Gi
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: postgres
spec:
  selector:
    matchLabels:
      app: postgres
  replicas: 1
  strategy: {}
  template:
    metadata:
      labels:
        app: postgres
    spec:
      dnsPolicy: ClusterFirstWithHostNet
      hostNetwork: true
      volumes:
      - name: vol-postgres
        persistentVolumeClaim:
          claimName: pvc-postgres
      containers:
      - name: postgres
        image: postgres:12
        imagePullPolicy: Always
        env:
        - name: DB_USER
          value: postgres
        - name: DB_PASS
          value: postgres
        - name: DB_NAME
          value: postgres
        ports:
        - name: postgres
          containerPort: 5432
        volumeMounts:
        - mountPath: "/postgres"
          name: vol-postgres
        livenessProbe:
          exec:
            command:
            - pg_isready
            - -h
            - localhost
            - -U
            - postgres
          initialDelaySeconds: 30
          timeoutSeconds: 5
        readinessProbe:
          exec:
            command:
            - pg_isready
            - -h
            - localhost
            - -U
            - postgres
          initialDelaySeconds: 5
          timeoutSeconds: 1
---
apiVersion: v1
kind: Service
metadata:
  name: postgres
spec:
  ports:
  - name: postgres
    port: 5432
    targetPort: postgres
  selector:
    app: postgres
</code>```

答: There are ways to achieve it. You can mount your volume into a NAS or create a storage cluster using disks and create a persistent volume and persistent volume claim for that. If your use-case is to have persistence in local storage then you can create a local-storage storageclass in one of your cluster nodes and that volume space can be used by any pod in your cluster. To create a local-storage storageclass, refer this (https://kubernetes.io/blog/2019/04/04/kubernetes-1.14-local-persistent-volumes-ga/)</p>

Body:
Using kubeadm to create a cluster, I have a master and work node.

Now I want to share a persistentVolume in the work node, which will be bound with Postgres pod.

Expecting the code will create persistentVolume in the path /postgres of work node, but it seems the hostPath will not work in a cluster, how should I assign this property to the specific node?

kind: PersistentVolume
apiVersion: v1
metadata:
  name: pv-postgres
  labels:
    type: local
spec:
  capacity:
    storage: 2Gi
  accessModes:
    - ReadWriteOnce
  hostPath:
    path: "/postgres"
---
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: pvc-postgres
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 1Gi
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: postgres
spec:
  selector:
    matchLabels:
      app: postgres
  replicas: 1
  strategy: {}
  template:
    metadata:
      labels:
        app: postgres
    spec:
      dnsPolicy: ClusterFirstWithHostNet
      hostNetwork: true
      volumes:
      - name: vol-postgres
        persistentVolumeClaim:
          claimName: pvc-postgres
      containers:
      - name: postgres
        image: postgres:12
        imagePullPolicy: Always
        env:
        - name: DB_USER
          value: postgres
        - name: DB_PASS
          value: postgres
        - name: DB_NAME
          value: postgres
        ports:
        - name: postgres
          containerPort: 5432
        volumeMounts:
        - mountPath: "/postgres"
          name: vol-postgres
        livenessProbe:
          exec:
            command:
            - pg_isready
            - -h
            - localhost
            - -U
            - postgres
          initialDelaySeconds: 30
          timeoutSeconds: 5
        readinessProbe:
          exec:
            command:
            - pg_isready
            - -h
            - localhost
            - -U
            - postgres
          initialDelaySeconds: 5
          timeoutSeconds: 1
---
apiVersion: v1
kind: Service
metadata:
  name: postgres
spec:
  ports:
  - name: postgres
    port: 5432
    targetPort: postgres
  selector:
    app: postgres


问:
I have got problem clicking on hidden element
I have got a problem with my code because I am not able to click on a hidden element can someone help me?

The first picture is while hovering over and second it without hover

```<code># webdriver
browser = webdriver.Chrome(r'C:\Users\Admin\PycharmProjects\untitled\chromedriver.exe')

#zmazat prvý inzerat
[enter image description here][2]browser.get('https://www.bazos.sk/moje-inzeraty.php?mail=&telefon=0944668585&Submit=Vyp%C3%ADsa%C5%A5+inzer%C3%A1ty')

element_to_hover_over =         browser.find_element_by_xpath('/html/body/div/table/tbody/tr/td[2]/span/table/tbody/tr[1]/td[1]')
hover = ActionChains(browser).move_to_element(element_to_hover_over)
hover.perform()

zmazat = browser.find_element_by_xpath("//*[contains(text(), 'Zmazať/Upraviť/Topovať')]")
time.sleep(1)
browser.execute_script("arguments[0].click();", zmazat);
</code>```

答:
for the element "zmazat" try this xpath
e.g.</p>

```<code>zmazat = browser.find_element_by_xpath("//a[contains(text(), 'Zmazať/Upraviť/Topovať') and @class='akce']")
</code>```

Body:
I have got a problem with my code because I am not able to click on a hidden element can someone help me?

The first picture is while hovering over and second it without hover

# webdriver
browser = webdriver.Chrome(r'C:\Users\Admin\PycharmProjects\untitled\chromedriver.exe')

#zmazat prvý inzerat
[enter image description here][2]browser.get('https://www.bazos.sk/moje-inzeraty.php?mail=&telefon=0944668585&Submit=Vyp%C3%ADsa%C5%A5+inzer%C3%A1ty')

element_to_hover_over =         browser.find_element_by_xpath('/html/body/div/table/tbody/tr/td[2]/span/table/tbody/tr[1]/td[1]')
hover = ActionChains(browser).move_to_element(element_to_hover_over)
hover.perform()

zmazat = browser.find_element_by_xpath("//*[contains(text(), 'Zmazať/Upraviť/Topovať')]")
time.sleep(1)
browser.execute_script("arguments[0].click();", zmazat);

Body:
for the element "zmazat" try this xpath
e.g.

zmazat = browser.find_element_by_xpath("//a[contains(text(), 'Zmazať/Upraviť/Topovať') and @class='akce']")


问:
What is the purpose of the .git file in a submodule directory?
What is the purpose of the .git file in a submodule directory?

The submodule is mapped to the public directory which is build with Hugo. This is pushed to a Github pages site.

When I run hugo --cleanDestinationDir

What happens if this gets deleted? Can this be recreated within the build in Travis CI?

答:
The .git file is a gitfile:

A plain file .git at the root of a working tree that points at the directory that is the real repository.

https://git-scm.com/docs/gitglossary

This file contains

```<code>gitdir: <path>
</code>```

with the path to the parent .git directory.

This mechanism is often used for a working tree of a submodule checkout, to allow you in the containing superproject to git checkout a branch that does not have the submodule. The checkout has to remove the entire submodule working tree, without losing the submodule repository.

https://git-scm.com/docs/gitrepository-layout

Body:
The .git file is a gitfile:

A plain file .git at the root of a working tree that points at the directory that is the real repository.

https://git-scm.com/docs/gitglossary

This file contains

gitdir: <path>

with the path to the parent .git directory.

This mechanism is often used for a working tree of a submodule checkout, to allow you in the containing superproject to git checkout a branch that does not have the submodule. The checkout has to remove the entire submodule working tree, without losing the submodule repository.

https://git-scm.com/docs/gitrepository-layout


问:
iPhone not appearing in Develop menu in Safari
On my "Develop" menu, in Safari, the iPhone no longer appears after updating Safari to the latest version, making it impossible to inspect and debug sites and apps.

I restarted the iPhone, killed and relaunched Safari, restarted my Mac too, but the issue is still there. Affects both Safari mobile and phonegap applications.

Anyone experienced the same problem?

答: I've tried with the reset of Privacy and Location but it didn't work. What worked for me was disabling the hotspot from the phone. With the hotspot active Safari doesn't shows the iPhone in the developer menu.</p>


问:
router - move all files in public folder
I wish to move all files out of public folder except "index.php" & "assets." I'm slowly updating to a custom MVC for my small project: I've moved functions, config & classes etc. - it's just the old spaghetti PHP files left. I want to move them all before I start breaking them down into models, views etc.

I would prefer core PHP and not to use symfony if any one can help.

So, instead of all files been on same level as "index.php" everything would route to new folder with all the files and new "index2.php" - so I've used a simple way that works on some level but there are 30 files, and I do not wish to write each one out if there's a better way.

htaccess:

```<code>RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php [QSA,L]
</code>```

index.php:

```<code><?php
$request = $_SERVER['REQUEST_URI'];

switch ($request) {
    case '/' :
        require __DIR__ . '/app/memberlist.php';
        break;
    case '' :
        require __DIR__ . '/app/memberlist.php';
        break;
    case '/staff' :
        require __DIR__ . '/app/staff.php';
        break;
    default:
        http_response_code(404);
        require __DIR__ . 'app/pdointro.php';
        break;

}
</code>```

Also there are some paths in the file I don't know how to add like:

```<code>header("Location: account-details.php?id=$id");
</code>```

and:

```<code><a href='account.php?action=edit_settings&do=edit'>edit</a>
</code>```

答:
Nice you choose front controller design pattern. I think you could create an array with all your php files dynamically and then make a comparison with REQUEST_URI.

Take a look at php docs:

https://www.php.net/manual/fr/class.recursivedirectoryiterator.php

https://www.php.net/manual/fr/class.recursiveiteratoriterator.php

https://www.php.net/manual/fr/class.recursivecallbackfilteriterator.php (to add filter)

Example below :

```<code>$files = [];

$dirIterator = new \RecursiveDirectoryIterator(
    'your_php_project_root_dir',
    \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::KEY_AS_PATHNAME |
    \FilesystemIterator::CURRENT_AS_SELF
);

$fileIterator = new \RecursiveIteratorIterator($dirIterator);

foreach($fileIterator as $file) {
    $filePath = $file->getPathName();
    $fileExt = $file->getExtension();
    $fileName = $file->getFileName();
    $fileSubPath = $file->getSubPath();
    $isFile = $file->isFile();

    // here you can filter, make condition and then add php files to your array.
    // $files[$fileName]
}

if ($path = \array_search($_SERVER['REQUEST_URI'], $files)) {
    require($path);
}

exit;
</code>```

This is an idea of what you could do.

Body:
I wish to move all files out of public folder except "index.php" & "assets." I'm slowly updating to a custom MVC for my small project: I've moved functions, config & classes etc. - it's just the old spaghetti PHP files left. I want to move them all before I start breaking them down into models, views etc.

I would prefer core PHP and not to use symfony if any one can help.

So, instead of all files been on same level as "index.php" everything would route to new folder with all the files and new "index2.php" - so I've used a simple way that works on some level but there are 30 files, and I do not wish to write each one out if there's a better way.

htaccess:

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php [QSA,L]

index.php:

<?php
$request = $_SERVER['REQUEST_URI'];

switch ($request) {
    case '/' :
        require __DIR__ . '/app/memberlist.php';
        break;
    case '' :
        require __DIR__ . '/app/memberlist.php';
        break;
    case '/staff' :
        require __DIR__ . '/app/staff.php';
        break;
    default:
        http_response_code(404);
        require __DIR__ . 'app/pdointro.php';
        break;

}

Also there are some paths in the file I don't know how to add like:

header("Location: account-details.php?id=$id");

and:

edit

Body:
Nice you choose front controller design pattern. I think you could create an array with all your php files dynamically and then make a comparison with REQUEST_URI.

Take a look at php docs:

https://www.php.net/manual/fr/class.recursivedirectoryiterator.php

https://www.php.net/manual/fr/class.recursiveiteratoriterator.php

https://www.php.net/manual/fr/class.recursivecallbackfilteriterator.php (to add filter)

Example below :

$files = [];

$dirIterator = new \RecursiveDirectoryIterator(
    'your_php_project_root_dir',
    \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::KEY_AS_PATHNAME |
    \FilesystemIterator::CURRENT_AS_SELF
);

$fileIterator = new \RecursiveIteratorIterator($dirIterator);

foreach($fileIterator as $file) {
    $filePath = $file->getPathName();
    $fileExt = $file->getExtension();
    $fileName = $file->getFileName();
    $fileSubPath = $file->getSubPath();
    $isFile = $file->isFile();

    // here you can filter, make condition and then add php files to your array.
    // $files[$fileName]
}

if ($path = \array_search($_SERVER['REQUEST_URI'], $files)) {
    require($path);
}

exit;

This is an idea of what you could do.


问:
React Native adb reverse ENOENT
I am trying to get React-Native to work with Android V4.2.2 (Genymotion) but I am unable to test the app on the Emulator. When I ran react-native run-android, I get this error Could not run adb reverse: spawnSync

Here is a log

```<code>JS server already running.
Running ~/Library/Android/sdk/platform-tools/adb reverse tcp:8081 tcp:8081
Could not run adb reverse: spawnSync ~/Library/Android/sdk/platform-tools/adb ENOENT
Building and installing the app on the device (cd android && ./gradlew installDebug...

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':app'.
> The SDK directory '~/Library/Android/sdk' does not exist.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 3.785 secs
Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment:
https://facebook.github.io/react-native/docs/android-setup.html
</code>```

NOTE: In the log it saids SDK directory does not exist, I have double check that I do have the SDK installed in that directory.

I found my android emulator when executing adb devices

```<code>List of devices attached
192.168.56.101:5555 device
</code>```

I have tried the following steps from Stack Overflow post, but still no luck
https://stackoverflow.com/a/38536290/4540216

答:
I solved this error with installing adb

On Linux

```<code>sudo apt-get install android-tools-adb
</code>```

Title: React Native adb reverse ENOENT

Body:
I am trying to get React-Native to work with Android V4.2.2 (Genymotion) but I am unable to test the app on the Emulator. When I ran react-native run-android, I get this error Could not run adb reverse: spawnSync

Here is a log

JS server already running.
Running ~/Library/Android/sdk/platform-tools/adb reverse tcp:8081 tcp:8081
Could not run adb reverse: spawnSync ~/Library/Android/sdk/platform-tools/adb ENOENT
Building and installing the app on the device (cd android && ./gradlew installDebug...

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':app'.
> The SDK directory '~/Library/Android/sdk' does not exist.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 3.785 secs
Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment:
https://facebook.github.io/react-native/docs/android-setup.html

NOTE: In the log it saids SDK directory does not exist, I have double check that I do have the SDK installed in that directory.

I found my android emulator when executing adb devices

List of devices attached
192.168.56.101:5555 device

I have tried the following steps from Stack Overflow post, but still no luck
https://stackoverflow.com/a/38536290/4540216

Body:
I solved this error with installing adb

On Linux

sudo apt-get install android-tools-adb


问:
How to put nodes into parent node?
I would like to add a parent node with attribute and put nodes inside of this parent node. I have the following xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<foo>
   <row>
      <PHONE_NUM>124</PHONE_NUM>
      <PHONE_ORDER>1</PHONE_ORDER>
   </row>
   <row>
      <PHONE_NUM>123</PHONE_NUM>
      <PHONE_ORDER>2</PHONE_ORDER>
   </row>
   <row>
      <PHONE_NUM>181</PHONE_NUM>
      <PHONE_ORDER>3</PHONE_ORDER>
   </row>
</foo>
</code>```

I've tried this approach:

```<code>var xmlString = @"<?xml version=""1.0"" encoding=""UTF-8""?>
    <foo>
       <row>
          <PHONE_NUM>124</PHONE_NUM>
          <PHONE_ORDER>1</PHONE_ORDER>
       </row>
       <row>
          <PHONE_NUM>123</PHONE_NUM>
          <PHONE_ORDER>2</PHONE_ORDER>
       </row>
       <row>
          <PHONE_NUM>181</PHONE_NUM>
          <PHONE_ORDER>3</PHONE_ORDER>
       </row>
    </foo>";

var report = XDocument.Parse(xmlString);
var newdoc = new XDocument();
newdoc.Add(new XElement("testsuites"));
newdoc.Root.Add(report.Root);
</code>```

But the above code generates is withoud id and order books has become a root :

```<code><books>
  <foo>
      <row>
          <PHONE_NUM>124</PHONE_NUM>
          <PHONE_ORDER>1</PHONE_ORDER>
      </row>
      <row>
          <PHONE_NUM>123</PHONE_NUM>
          <PHONE_ORDER>2</PHONE_ORDER>
      </row>
      <row>
          <PHONE_NUM>181</PHONE_NUM>
          <PHONE_ORDER>3</PHONE_ORDER>
      </row>
      </foo>
  </books>
</code>```

What I am trying to achieve is:

```<code><?xml version=""1.0"" encoding=""UTF-8""?>
<foo>
    <books id=""1"">
       <row>
          <PHONE_NUM>124</PHONE_NUM>
          <PHONE_ORDER>1</PHONE_ORDER>
       </row>
       <row>
          <PHONE_NUM>123</PHONE_NUM>
          <PHONE_ORDER>2</PHONE_ORDER>
       </row>
       <row>
          <PHONE_NUM>181</PHONE_NUM>
          <PHONE_ORDER>3</PHONE_ORDER>
       </row>
    </books>
</foo>
</code>```

If it is possible, it would be great if XmlDocument class will be used. Any help would be greatly appreciated.

答:
Here's about what you want to do, using the XDocument class. It's simply a matter of creating new nodes and modifying existing nodes with your specification:

```<code>var report = XDocument.Parse(xmlString);
report.Root.Name = XName.Get("books", report.Root.Name.NamespaceName);
report.Root.Add(new XAttribute("id", 1));
var newDoc = new XDocument();
var newRoot = new XElement("foo");
newRoot.Add(report.Root);
newDoc.Add(newRoot);
</code>```

Title: How to put nodes into parent node?

Body:
I would like to add a parent node with attribute and put nodes inside of this parent node. I have the following xml:

<?xml version="1.0" encoding="UTF-8"?>
<foo>
   <row>
      <PHONE_NUM>124</PHONE_NUM>
      <PHONE_ORDER>1</PHONE_ORDER>
   </row>
   <row>
      <PHONE_NUM>123</PHONE_NUM>
      <PHONE_ORDER>2</PHONE_ORDER>
   </row>
   <row>
      <PHONE_NUM>181</PHONE_NUM>
      <PHONE_ORDER>3</PHONE_ORDER>
   </row>
</foo>

I've tried this approach:

var xmlString = @"<?xml version=""1.0"" encoding=""UTF-8""?>
    <foo>
       <row>
          <PHONE_NUM>124</PHONE_NUM>
          <PHONE_ORDER>1</PHONE_ORDER>
       </row>
       <row>
          <PHONE_NUM>123</PHONE_NUM>
          <PHONE_ORDER>2</PHONE_ORDER>
       </row>
       <row>
          <PHONE_NUM>181</PHONE_NUM>
          <PHONE_ORDER>3</PHONE_ORDER>
       </row>
    </foo>";

var report = XDocument.Parse(xmlString);
var newdoc = new XDocument();
newdoc.Add(new XElement("testsuites"));
newdoc.Root.Add(report.Root);

But the above code generates is withoud id and order books has become a root :

<books>
  <foo>
      <row>
          <PHONE_NUM>124</PHONE_NUM>
          <PHONE_ORDER>1</PHONE_ORDER>
      </row>
      <row>
          <PHONE_NUM>123</PHONE_NUM>
          <PHONE_ORDER>2</PHONE_ORDER>
      </row>
      <row>
          <PHONE_NUM>181</PHONE_NUM>
          <PHONE_ORDER>3</PHONE_ORDER>
      </row>
      </foo>
  </books>

What I am trying to achieve is:

<?xml version=""1.0"" encoding=""UTF-8""?>
<foo>
    <books id=""1"">
       <row>
          <PHONE_NUM>124</PHONE_NUM>
          <PHONE_ORDER>1</PHONE_ORDER>
       </row>
       <row>
          <PHONE_NUM>123</PHONE_NUM>
          <PHONE_ORDER>2</PHONE_ORDER>
       </row>
       <row>
          <PHONE_NUM>181</PHONE_NUM>
          <PHONE_ORDER>3</PHONE_ORDER>
       </row>
    </books>
</foo>

If it is possible, it would be great if XmlDocument class will be used. Any help would be greatly appreciated.

Body:
Here's about what you want to do, using the XDocument class. It's simply a matter of creating new nodes and modifying existing nodes with your specification:

var report = XDocument.Parse(xmlString);
report.Root.Name = XName.Get("books", report.Root.Name.NamespaceName);
report.Root.Add(new XAttribute("id", 1));
var newDoc = new XDocument();
var newRoot = new XElement("foo");
newRoot.Add(report.Root);
newDoc.Add(newRoot);


问:
Pandas: create a Dataframe from lists with similar-size lists inside
I am trying to construct a Dataframe from lists, which have similar-size lists inside.

In the example below I have 3 lists (with similar-size lists inside), which I want to use to construct an specific Dataframe.

Here are the lists:

```<code>list_type = [['A1', 'A2'], ['A2'], ['A1', 'A3', 'A4']]

list_xx = [['1', '5'], ['3'], ['2', '7', '3']]

list_date = [['Jan', 'Jan'], ['Feb'], ['Mar', 'Mar', 'Mar']]
</code>```

And the Dataframe I want to construct is:

   date type    xx
0   Jan   A1     1
1   Jan   A2     5
2   Feb   A2     3
3   Mar   A1     2
4   Mar   A3     7
5   Mar   A4     3
```

As you can see, the structure of the Dateframe is based on the inner-lists.

I would really value an efficient way of doing this in Python.

答:
An alternative would be to flatten the lists first with itertools.chain.from_iterable, instead of concatenating DataFrames as in this answer.

```<code>import itertools
import pandas as pd

list_type = [['A1', 'A2'], ['A2'], ['A1', 'A3', 'A4']]
list_xx = [['1', '5'], ['3'], ['2', '7', '3']]
list_date = [['Jan', 'Jan'], ['Feb'], ['Mar', 'Mar', 'Mar']]

df = pd.DataFrame({
    "date": itertools.chain.from_iterable(list_date),
    "type": itertools.chain.from_iterable(list_type),
    "xx": itertools.chain.from_iterable(list_xx)
})
</code>```

This gives your desired output. I would expect this to be more efficient than building and concatenating sub DataFrames, but haven't explicitly tested the two.

Body:
I am trying to construct a Dataframe from lists, which have similar-size lists inside.

In the example below I have 3 lists (with similar-size lists inside), which I want to use to construct an specific Dataframe.

Here are the lists:

list_type = [['A1', 'A2'], ['A2'], ['A1', 'A3', 'A4']]

list_xx = [['1', '5'], ['3'], ['2', '7', '3']]

list_date = [['Jan', 'Jan'], ['Feb'], ['Mar', 'Mar', 'Mar']]

And the Dataframe I want to construct is:

   date type    xx
0   Jan   A1     1
1   Jan   A2     5
2   Feb   A2     3
3   Mar   A1     2
4   Mar   A3     7
5   Mar   A4     3

As you can see, the structure of the Dateframe is based on the inner-lists.

I would really value an efficient way of doing this in Python.

Body:
An alternative would be to flatten the lists first with itertools.chain.from_iterable, instead of concatenating DataFrames as in this answer.

import itertools
import pandas as pd

list_type = [['A1', 'A2'], ['A2'], ['A1', 'A3', 'A4']]
list_xx = [['1', '5'], ['3'], ['2', '7', '3']]
list_date = [['Jan', 'Jan'], ['Feb'], ['Mar', 'Mar', 'Mar']]

df = pd.DataFrame({
    "date": itertools.chain.from_iterable(list_date),
    "type": itertools.chain.from_iterable(list_type),
    "xx": itertools.chain.from_iterable(list_xx)
})

This gives your desired output. I would expect this to be more efficient than building and concatenating sub DataFrames, but haven't explicitly tested the two.


问:
Spring Data JPA - Named query ignoring null parameters
I have the following repository:

```<code>@Repository
public interface EntityRepository extends JpaRepository<Entity, Long> {

    List<Entity> findAllByFirstId(Long firstId);
    List<Entity> findAllBySecondId(Long secondId);
    List<Entity> findAllByFirstIdAndSecondId(Long firstId, Long secondId);
}
</code>```

The constructor implementing an interface generated with io.swagger:swagger-codegen-maven-plugin uses Optional<Long> as optional request parameters (the underlying service uses also the same parameters):

```<code>ResponseEntity<List<Entity>> entities(Optional<Long> firstId, Optional<Long> secondId);
</code>```

I would like to filter the entities based on the parameters firstId and secondId which are never nulls at the database but can be passed through the constructor (the parameter for searching is optional).

The problem comes with the named queries when the null is passed as the parameter is optional, the JpaReposotory uses the null as a criterion for the searching in the database. That's what I don't want - I want to ignore the filtering based on this parameter as long as it is null.

My workaround solution based on Optional is:

```<code>public List<Entity> entities(Optional<Long> firstId, Optional<Long> secondId) {

    return firstId
        .or(() -> secondId)
        .map(value -> {
            if (firstId.isEmpty()) {
                return entityRepository.findAllBySecondId(value);
            }
            if (secondId.isEmpty()) {
                return entityRepository.findAllByFirstId(value);
            }
            return entityRepository.findAllByFirstIdAndSecondId(
            firstId.get(), secondId.get());
        })
        .orElse(entityRepository.findAll())
        .stream()
        .map(...)     // Mapping between DTO and entity. For sake of brevity
                      // I used the same onject Entity for both controler and repository
                      // as long as it not related to the question

        .collect(Collectors.toList());
}
</code>```

This issue has been already asked: Spring Data - ignore parameter if it has a null value and a ticket created DATAJPA-209.

As long as the question is almost 3 years old and the ticket dates back to 2012, I would like to ask if there exists a more comfortable and universal way to avoid the overhead of handling the Optional and duplicating the repository methods. The solution for 2 such parameters looks acceptable, however I'd like to implement the very same filtering for 4-5 parameters.

答:
The io.swagger:swagger-codegen-maven-plugin generates them as
  Optional since I request them as not required (required: false by
  default). I might generate them as boxed types, such as Long, …

It’s probably partly a matter of taste. If it were me and I could, I’d go for the version without Optional. I don’t think they contribute anything useful here.

```<code>public List<Entity> entities(Long firstId, Long secondId) {

    List<Dto> dtos;
    if (firstId == null) {
        if (secondId == null) {
            dtos = entityRepository.findAll();
        } else {
            dtos = entityRepository.findAllBySecondId(secondId);
        }
    } else {
        if (secondId == null) {
            dtos = entityRepository.findAllByFirstId(firstId);
        } else {
            dtos = entityRepository.findAllByFirstIdAndSecondId(firstId, secondId);
        }
    }

    return dtos.stream()
        .map(...)
        .collect(Collectors.toList());
}
</code>```

The Optional class was designed to be used for return values that may be absent, not really for anything else, so I have read. I think there are rare situations where I’d use them for something else, but this is not one of them.

Body:
I have the following repository:

@Repository
public interface EntityRepository extends JpaRepository<Entity, Long> {

    List<Entity> findAllByFirstId(Long firstId);
    List<Entity> findAllBySecondId(Long secondId);
    List<Entity> findAllByFirstIdAndSecondId(Long firstId, Long secondId);
}

The constructor implementing an interface generated with io.swagger:swagger-codegen-maven-plugin uses Optional<Long> as optional request parameters (the underlying service uses also the same parameters):

ResponseEntity<List<Entity>> entities(Optional<Long> firstId, Optional<Long> secondId);

I would like to filter the entities based on the parameters firstId and secondId which are never nulls at the database but can be passed through the constructor (the parameter for searching is optional).

The problem comes with the named queries when the null is passed as the parameter is optional, the JpaReposotory uses the null as a criterion for the searching in the database. That's what I don't want - I want to ignore the filtering based on this parameter as long as it is null.

My workaround solution based on Optional is:

public List<Entity> entities(Optional<Long> firstId, Optional<Long> secondId) {

    return firstId
        .or(() -> secondId)
        .map(value -> {
            if (firstId.isEmpty()) {
                return entityRepository.findAllBySecondId(value);
            }
            if (secondId.isEmpty()) {
                return entityRepository.findAllByFirstId(value);
            }
            return entityRepository.findAllByFirstIdAndSecondId(
            firstId.get(), secondId.get());
        })
        .orElse(entityRepository.findAll())
        .stream()
        .map(...)     // Mapping between DTO and entity. For sake of brevity
                      // I used the same onject Entity for both controler and repository
                      // as long as it not related to the question

        .collect(Collectors.toList());
}

This issue has been already asked: Spring Data - ignore parameter if it has a null value and a ticket created DATAJPA-209.

As long as the question is almost 3 years old and the ticket dates back to 2012, I would like to ask if there exists a more comfortable and universal way to avoid the overhead of handling the Optional and duplicating the repository methods. The solution for 2 such parameters looks acceptable, however I'd like to implement the very same filtering for 4-5 parameters.

Body:
The io.swagger:swagger-codegen-maven-plugin generates them as
  Optional since I request them as not required (required: false by
  default). I might generate them as boxed types, such as Long, …

It’s probably partly a matter of taste. If it were me and I could, I’d go for the version without Optional. I don’t think they contribute anything useful here.

public List<Entity> entities(Long firstId, Long secondId) {

    List<Dto> dtos;
    if (firstId == null) {
        if (secondId == null) {
            dtos = entityRepository.findAll();
        } else {
            dtos = entityRepository.findAllBySecondId(secondId);
        }
    } else {
        if (secondId == null) {
            dtos = entityRepository.findAllByFirstId(firstId);
        } else {
            dtos = entityRepository.findAllByFirstIdAndSecondId(firstId, secondId);
        }
    }

    return dtos.stream()
        .map(...)
        .collect(Collectors.toList());
}

The Optional class was designed to be used for return values that may be absent, not really for anything else, so I have read. I think there are rare situations where I’d use them for something else, but this is not one of them.


问:
How to allow an empty foreign key in Django?
I'm very new to Django so this may be the dumbest question ever.
I have 2 models set up in django; 'Class' and 'Profile'.

The 'Profile' class has a foreign key that references 'Class'. When creating a profile on the front end I am unable to leave the form blank as ("Profile.group" must be a "Class" instance.). I want to be able to create a profile that doesn't have to belong to a class.

```<code>class Class(models.Model):
    class_name = models.CharField(max_length=5)
    # a few other things that don't matter

    def __str__(self):
        return self.class_name

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    # a few other things that don't matter
    group = models.ForeignKey(Class, on_delete=models.SET_NULL, null=True, blank=True)
</code>```

and in form.py

```<code>class ProfileRegisterForm(forms.ModelForm):
    # a few other things
    group = forms.CharField(max_length=5, required=False)
</code>```

If there is anything important that I've missed out please let me know, it's my first time posting here so I don't know what the standard is.

答:
I want to be able to create a profile that doesn't have to belong to a class.

That is already the case. By making the field nullable, you can just pass None to it, and then it does not relate to any class.

The group in your form however, should not be a CharField, but a ModelChoiceField. The way you communicate with the user is determined by the widget you attach to it. You can for example use a widget that implements a search bar, for example with django-select2 [Django-doc], or django-autocomplete-light [Django-doc]. django-autocomplete-lightweight allows to fetch the records through AJAX, making the burden on the render engine less.

For example we can install django-select2 in the virtual environment with:

```<code>pip install <b>django_select2</b></code>```

Next in the ProfileRegisterForm we, can specifyh the widget as:

```<code>from django_select2.forms import <b>Select2Widget</b>
from app.models import Class

class ProfileRegisterForm(forms.ModelForm):
    group = <b>forms.ModelChoiceField(</b>
        queryset=Class.objects.all(), <b>widget=Select2Widget</b>
    <b>)</b>

    class Meta:
        model = Profile</code>```

Body:
I'm very new to Django so this may be the dumbest question ever.
I have 2 models set up in django; 'Class' and 'Profile'.

The 'Profile' class has a foreign key that references 'Class'. When creating a profile on the front end I am unable to leave the form blank as ("Profile.group" must be a "Class" instance.). I want to be able to create a profile that doesn't have to belong to a class.

class Class(models.Model):
    class_name = models.CharField(max_length=5)
    # a few other things that don't matter

    def __str__(self):
        return self.class_name

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    # a few other things that don't matter
    group = models.ForeignKey(Class, on_delete=models.SET_NULL, null=True, blank=True)

and in form.py

class ProfileRegisterForm(forms.ModelForm):
    # a few other things
    group = forms.CharField(max_length=5, required=False)

If there is anything important that I've missed out please let me know, it's my first time posting here so I don't know what the standard is.

Body:
I want to be able to create a profile that doesn't have to belong to a class.

That is already the case. By making the field nullable, you can just pass None to it, and then it does not relate to any class.

The group in your form however, should not be a CharField, but a ModelChoiceField. The way you communicate with the user is determined by the widget you attach to it. You can for example use a widget that implements a search bar, for example with django-select2 [Django-doc], or django-autocomplete-light [Django-doc]. django-autocomplete-lightweight allows to fetch the records through AJAX, making the burden on the render engine less.

For example we can install django-select2 in the virtual environment with:

pip install django_select2

Next in the ProfileRegisterForm we, can specifyh the widget as:

from django_select2.forms import Select2Widget
from app.models import Class

class ProfileRegisterForm(forms.ModelForm):
    group = forms.ModelChoiceField(
        queryset=Class.objects.all(), widget=Select2Widget
    )

    class Meta:
        model = Profile


问:
run-length encoding using C++
I have a text file with a string which I'd like to encode.

Let's say it is: aaahhhhiii kkkjjhh ikl wwwwwweeeett

and here is the code:

```<code>void Encode(std::string &inputstring, std::string &outputstring)
{
    for (int i = 0; i < inputstring.length(); i++) {
        int count = 1;
        while (inputstring[i] == inputstring[i+1]) {
            count++;
            i++;
        }
        if(count <= 1) {
            //std::cout << inputstring[i] << "";
            outputstring += inputstring[i];
            outputstring += "";
        } else {
            //std::cout << inputstring[i] << count;
            outputstring += inputstring[i];
            outputstring += count;
        }
    }
}
</code>```

output should be: 3a4h3i 3k2j2h ikl 6w4e2t

Characters or white spaces with less (or equal) than one character get just printed out - no change.

So far so good and code is working.. actually.

When I use std::cout in if and else - then it is showing me the output like above. So perfect.

BUT, I'd like to hand over the result to the parameters (std::string &outputstring) and print the result in the main method.

But it is printing ONLY the if statement not else statement.

Can someone help me with this matter?

答: Your problem was with the line outputstring += count;. An integer is interpreted as a character code when assigning it to a  string. You don't want the character with the character code count, but you want to convert the number count to a string, so you should use outputstring += std::to_string(count);

Title: run-length encoding using C++

Body:
I have a text file with a string which I'd like to encode.

Let's say it is: aaahhhhiii kkkjjhh ikl wwwwwweeeett

and here is the code:

void Encode(std::string &inputstring, std::string &outputstring)
{
    for (int i = 0; i < inputstring.length(); i++) {
        int count = 1;
        while (inputstring[i] == inputstring[i+1]) {
            count++;
            i++;
        }
        if(count <= 1) {
            //std::cout << inputstring[i] << "";
            outputstring += inputstring[i];
            outputstring += "";
        } else {
            //std::cout << inputstring[i] << count;
            outputstring += inputstring[i];
            outputstring += count;
        }
    }
}

output should be: 3a4h3i 3k2j2h ikl 6w4e2t

Characters or white spaces with less (or equal) than one character get just printed out - no change.

So far so good and code is working.. actually.

When I use std::cout in if and else - then it is showing me the output like above. So perfect.

BUT, I'd like to hand over the result to the parameters (std::string &outputstring) and print the result in the main method.

But it is printing ONLY the if statement not else statement.

Can someone help me with this matter?


问:
How to implement sklearn's Estimator interface for use in GridSearchCV pipeline?
So I have my own implementation of a Perceptron classifier, and would like to tune its hyperparameters using sklearn's GridSearchCV. I've been trying to write a wrapper around the model that implements Estimator (read through https://scikit-learn.org/stable/developers/develop.html) but when I run
GridSearchCV(wrapper, params).fit(X,y), I get the following error:

```<code>FitFailedWarning: Estimator fit failed. The score on this train-test partition for these parameters will be set to nan. Details:
AttributeError: 'NoneType' object has no attribute 'fit'

  FitFailedWarning)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\model_selection\_search.py", line 738, in fit
    **self.best_params_))
  File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\base.py", line 67, in clone
    % (repr(estimator), type(estimator)))
TypeError: Cannot clone object 'None' (type <class 'NoneType'>): it does not seem to be a scikit-learn estimator as it does not implement a 'get_params' methods.
</code>```

This error is identical to How to write a custom estimator in sklearn and use cross-validation on it? but I was already doing everything proposed in the top-rated comment.

I am positive that the model is correct. Here is code for the wrapper around the model:

```<code>from models import Perceptron, Softmax, SVM
from sklearn.model_selection import GridSearchCV

class Estimator():
    def __init__(self, alpha=0.5, epochs=100):
        self.alpha = alpha
        self.epochs = epochs
        self.model = Perceptron()

    def fit(self, X, y, **kwargs):
        self.alpha = kwargs['alpha']
        self.epochs = kwargs['epochs']
        self.model.alpha = kwargs['alpha']
        self.model.epochs = kwargs['epochs']
        self.model.train(X, y)

    def predict(self, X):
        return self.model.predict(X)

    def score(self, data, targets):
        return self.model.get_acc(self.predict(data), targets)

    def set_params(self, alpha, epochs):
        self.alpha = alpha
        self.epochs = epochs
        self.model.alpha = alpha
        self.model.epochs = epochs

    def get_params(self, deep=False):
        return {'alpha':self.alpha, 'epochs':self.epochs}

</code>```

答:
As explained in this section of the documentation, you should derive the class from BaseEstimator class Estimator(BaseEstimator): to avoid boilerplate and follow a fit predict structure. As @Shihab said in the comments, your fit function is missing a return self code line.

Also, in the get_params() I don't know if you are doing it on purpose, but the parameter deep in the documentation is also recommended to put it as deep=True by default. Please check it out.

Body:
So I have my own implementation of a Perceptron classifier, and would like to tune its hyperparameters using sklearn's GridSearchCV. I've been trying to write a wrapper around the model that implements Estimator (read through https://scikit-learn.org/stable/developers/develop.html) but when I run
GridSearchCV(wrapper, params).fit(X,y), I get the following error:

FitFailedWarning: Estimator fit failed. The score on this train-test partition for these parameters will be set to nan. Details:
AttributeError: 'NoneType' object has no attribute 'fit'

  FitFailedWarning)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\model_selection\_search.py", line 738, in fit
    **self.best_params_))
  File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\base.py", line 67, in clone
    % (repr(estimator), type(estimator)))
TypeError: Cannot clone object 'None' (type <class 'NoneType'>): it does not seem to be a scikit-learn estimator as it does not implement a 'get_params' methods.

This error is identical to How to write a custom estimator in sklearn and use cross-validation on it? but I was already doing everything proposed in the top-rated comment.

I am positive that the model is correct. Here is code for the wrapper around the model:

from models import Perceptron, Softmax, SVM
from sklearn.model_selection import GridSearchCV

class Estimator():
    def __init__(self, alpha=0.5, epochs=100):
        self.alpha = alpha
        self.epochs = epochs
        self.model = Perceptron()

    def fit(self, X, y, **kwargs):
        self.alpha = kwargs['alpha']
        self.epochs = kwargs['epochs']
        self.model.alpha = kwargs['alpha']
        self.model.epochs = kwargs['epochs']
        self.model.train(X, y)

    def predict(self, X):
        return self.model.predict(X)

    def score(self, data, targets):
        return self.model.get_acc(self.predict(data), targets)

    def set_params(self, alpha, epochs):
        self.alpha = alpha
        self.epochs = epochs
        self.model.alpha = alpha
        self.model.epochs = epochs

    def get_params(self, deep=False):
        return {'alpha':self.alpha, 'epochs':self.epochs}


问:
Append/Prepend space on outer tag
I would like to append/prepend a space on the outer tags.

I tried the following:

var $elem = $('', {
  'data-function': "addSynonym",
  'data-options': '[ test1, test2, test3]',
  'html': $('', {
    'text': 'test4',
    'css': {
      backgroundColor: 'yellow'
    }
  })
});

$elem.append(" ")
$elem.prepend(" ");

console.log($elem[0]);
console.log($elem[0].innerHTML);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

As you can see only the inner tag has the spaces.

However, I would like to have it on the outer tag. Like the following:

```<code> <span data-function="addSynonym" data-options="[ test1, test2, test3]"><span style="background-color: yellow;">test4</span></span>

</code>```

Any suggestions how to do this?

I appreciate your replies!

答:
In jQuery, insertBefore/before and insertAfter/after are the methods used to insert elements before or after the target element.

  is not element, though, so you have to create a text node:

```<code>const textNode = ' '
$('.some-element').before(textNode)
$('.some-element').after(textNode)
</code>```

See example:

https://jsfiddle.net/yq1jfd5z/1/

Title: Append/Prepend space on outer tag

Body:
I would like to append/prepend a space on the outer tags.

I tried the following:

var $elem = $('', {
  'data-function': "addSynonym",
  'data-options': '[ test1, test2, test3]',
  'html': $('', {
    'text': 'test4',
    'css': {
      backgroundColor: 'yellow'
    }
  })
});

$elem.append(" ")
$elem.prepend(" ");

console.log($elem[0]);
console.log($elem[0].innerHTML);

As you can see only the inner tag has the spaces.

However, I would like to have it on the outer tag. Like the following:

 test4

Any suggestions how to do this?

I appreciate your replies!

Body:
In jQuery, insertBefore/before and insertAfter/after are the methods used to insert elements before or after the target element.

&nbsp; is not element, though, so you have to create a text node:

const textNode = '&nbsp;'
$('.some-element').before(textNode)
$('.some-element').after(textNode)

See example:

https://jsfiddle.net/yq1jfd5z/1/


问:
Check for proper list in Common Lisp
Is there a standard function in Common Lisp that can check against improper lists (i.e. circular and dotted lists) without signaling an error? list-length can check against circular lists (it returns nil for them), but signals type-error when given a dotted list.

Scheme's list? traverses the whole list to make sure it is not dotted or circular; Common Lisp's listp only checks that it's given nil or a cons cell.

Here's the simplest I could come up with:

```<code>(defun proper-list-p (x)
  (not (null (handler-case (list-length x) (type-error () nil)))))
</code>```

Since several implementations have been suggested and many unexpected problems have been found, here's a test suite for aspiring proper-list-p writers:

```<code>(defun circular (xs)
  (let ((xs (copy-list xs)))
    (setf (cdr (last xs)) xs)
    xs))

(assert (eql t (proper-list-p '())))
(assert (eql t (proper-list-p '(1))))
(assert (eql t (proper-list-p '(1 2))))
(assert (eql t (proper-list-p '(1 2 3))))

(assert (not (proper-list-p 1)))
(assert (not (proper-list-p '(1 . 2))))
(assert (not (proper-list-p '(1 2 . 3))))
(assert (not (proper-list-p '(1 2 3 . 4))))

(assert (not (proper-list-p (circular '(1)))))
(assert (not (proper-list-p (circular '(1 2)))))
(assert (not (proper-list-p (circular '(1 2 3)))))
(assert (not (proper-list-p (list* 1 (circular '(2))))))
(assert (not (proper-list-p (list* 1 2 (circular '(3 4))))))
</code>```

答:
There is no standard function to do this, perhaps because such a function was seen as rather expensive if it was to be correct, but, really, this just seems like am omission from the language to me.

A minimal (not very performant) implementation, which does not rely on handling errors (Python people think that's a reasonable way to program, I don't, although this is a stylistic choice), is, I think

```<code>(defun proper-list-p (l)
  (typecase l
    (null t)
    (cons
     (loop for tail = l then (cdr tail)
           for seen = (list tail) then (push tail seen)
           do (cond ((null tail)
                     (return t))
                    ((not (consp tail))
                     (return nil))
                    ((member tail (rest seen))
                     (return nil)))))))
</code>```

This takes time quadratic in the length of l, and conses proportional to the length of l.  You can obviously do better using an hashtable for the occurs check, and you can use a tortoise-&-hare algorithm do avoid the occurs check (but I'm not sure what the complexity of that is off the top of my head).

I am sure there are much better functions than this in libraries.  In particular Alexandria has one.

While thinking about this question, I also wrote this function:

```<code>(defun classify-list (l)
  "Classify a possible list, returning four values.

The first value is a symbol which is
- NULL if the list is empty;
- LIST if the list is a proper list;
- CYCLIC-LIST if it contains a cycle;
- IMPROPER-LIST if it does not end with nil;
- NIL if it is not a list.

The second value is the total number of conses in the list (following
CDRs only).  It will be 0 for an empty list or non-list.

The third value is the cons at which the cycle in the list begins, or
NIL if there is no cycle or the list isn't a list.

The fourth value is the number if conses in the cycle, or 0 if there is no cycle.

Note that you can deduce the length of the leading element of the list
by subtracting the total number of conses from the number of conses in
the cycle: you can then use NTHCDR to pull out the cycle."
  ;; This is written as a tail recursion, I know people don't like
  ;; that in CL, but I wrote it for me.
  (typecase l
    (null (values 'null 0 nil 0 0))
    (cons
     (let ((table (make-hash-table)))
       (labels ((walk (tail previous-tail n)
                  (typecase tail
                    (null
                     (values 'list n nil 0))
                    (cons
                     (let ((m (gethash tail table nil)))
                       (if m
                           (values 'cyclic-list n tail (- n m))
                         (progn
                           (setf (gethash tail table) n)
                           (walk (cdr tail) tail (1+ n))))))
                    (t
                     (values 'improper-list n previous-tail 0)))))
         (walk l nil 0))))
    (t (values nil 0 nil 0))))
</code>```

This can be used to get a bunch of information about a list: how long it is, if it is proper, if not if it's cyclic, and where the cycle is.  Beware that in the cases of cyclic lists this will return circular structure as its third value.  I believe that you need to use an occurs check to do this – tortoise & hare will tell you if a list is cyclic, but not where the cycle starts.

Title: Check for proper list in Common Lisp

Body:
Is there a standard function in Common Lisp that can check against improper lists (i.e. circular and dotted lists) without signaling an error? list-length can check against circular lists (it returns nil for them), but signals type-error when given a dotted list.

Scheme's list? traverses the whole list to make sure it is not dotted or circular; Common Lisp's listp only checks that it's given nil or a cons cell.

Here's the simplest I could come up with:

(defun proper-list-p (x)
  (not (null (handler-case (list-length x) (type-error () nil)))))

Since several implementations have been suggested and many unexpected problems have been found, here's a test suite for aspiring proper-list-p writers:

(defun circular (xs)
  (let ((xs (copy-list xs)))
    (setf (cdr (last xs)) xs)
    xs))

(assert (eql t (proper-list-p '())))
(assert (eql t (proper-list-p '(1))))
(assert (eql t (proper-list-p '(1 2))))
(assert (eql t (proper-list-p '(1 2 3))))

(assert (not (proper-list-p 1)))
(assert (not (proper-list-p '(1 . 2))))
(assert (not (proper-list-p '(1 2 . 3))))
(assert (not (proper-list-p '(1 2 3 . 4))))

(assert (not (proper-list-p (circular '(1)))))
(assert (not (proper-list-p (circular '(1 2)))))
(assert (not (proper-list-p (circular '(1 2 3)))))
(assert (not (proper-list-p (list* 1 (circular '(2))))))
(assert (not (proper-list-p (list* 1 2 (circular '(3 4))))))

Body:
There is no standard function to do this, perhaps because such a function was seen as rather expensive if it was to be correct, but, really, this just seems like am omission from the language to me.

A minimal (not very performant) implementation, which does not rely on handling errors (Python people think that's a reasonable way to program, I don't, although this is a stylistic choice), is, I think

(defun proper-list-p (l)
  (typecase l
    (null t)
    (cons
     (loop for tail = l then (cdr tail)
           for seen = (list tail) then (push tail seen)
           do (cond ((null tail)
                     (return t))
                    ((not (consp tail))
                     (return nil))
                    ((member tail (rest seen))
                     (return nil)))))))

This takes time quadratic in the length of l, and conses proportional to the length of l.  You can obviously do better using an hashtable for the occurs check, and you can use a tortoise-&-hare algorithm do avoid the occurs check (but I'm not sure what the complexity of that is off the top of my head).

I am sure there are much better functions than this in libraries.  In particular Alexandria has one.

While thinking about this question, I also wrote this function:

(defun classify-list (l)
  "Classify a possible list, returning four values.

The first value is a symbol which is
- NULL if the list is empty;
- LIST if the list is a proper list;
- CYCLIC-LIST if it contains a cycle;
- IMPROPER-LIST if it does not end with nil;
- NIL if it is not a list.

The second value is the total number of conses in the list (following
CDRs only).  It will be 0 for an empty list or non-list.

The third value is the cons at which the cycle in the list begins, or
NIL if there is no cycle or the list isn't a list.

The fourth value is the number if conses in the cycle, or 0 if there is no cycle.

Note that you can deduce the length of the leading element of the list
by subtracting the total number of conses from the number of conses in
the cycle: you can then use NTHCDR to pull out the cycle."
  ;; This is written as a tail recursion, I know people don't like
  ;; that in CL, but I wrote it for me.
  (typecase l
    (null (values 'null 0 nil 0 0))
    (cons
     (let ((table (make-hash-table)))
       (labels ((walk (tail previous-tail n)
                  (typecase tail
                    (null
                     (values 'list n nil 0))
                    (cons
                     (let ((m (gethash tail table nil)))
                       (if m
                           (values 'cyclic-list n tail (- n m))
                         (progn
                           (setf (gethash tail table) n)
                           (walk (cdr tail) tail (1+ n))))))
                    (t
                     (values 'improper-list n previous-tail 0)))))
         (walk l nil 0))))
    (t (values nil 0 nil 0))))

This can be used to get a bunch of information about a list: how long it is, if it is proper, if not if it's cyclic, and where the cycle is.  Beware that in the cases of cyclic lists this will return circular structure as its third value.  I believe that you need to use an occurs check to do this – tortoise & hare will tell you if a list is cyclic, but not where the cycle starts.