问:
How i can change column parameter of existing row in datatable?
I edited my question but it still close without response. So i took advise from messagebox and open another question with more information.

I had table in my librarian database app on Windows Form, And one of columns include parameter "amount'. How can i correctly increase it if there consilience in all other columns in addrow SQLcommand?

Here code:

```<code>        private void ConfimAddBookButtom_Click(object sender, EventArgs e)
        {
            string conString = "Data Source=Books.db;Version=3;";
            string name = AddBookNameTextBox.Text;
            string author = AddBookAuthorTextBox.Text;
            string genre = AddBookGenreTextBox.Text;
            int amount = 1;
            string SQLiteExpression = "insert into Books (BookName, AuthorName, Genre, Amount) values (@name, @author, @genre, @amount)";
            using (SQLiteConnection connection = new SQLiteConnection(conString))
            {
                connection.Open();
                SQLiteCommand command = new SQLiteCommand(SQLiteExpression, connection);
                SQLiteParameter nameParam = new SQLiteParameter("@name", name);
                SQLiteParameter authorParam = new SQLiteParameter("@author", author);
                SQLiteParameter genreParam = new SQLiteParameter("@genre", genre);
                SQLiteParameter amountParam = new SQLiteParameter("@amount", amount);
                command.Parameters.Add(nameParam); command.Parameters.Add(authorParam); command.Parameters.Add(genreParam); command.Parameters.Add(amountParam);
                int number = command.ExecuteNonQuery();
                connection.Close();
                MessageBox.Show("Book sucsessfuly added");
                this.Close();
            }
</code>```

As you can see. The row will be always added with amount equal 1. And i needed to increase amount in the exsisted row if other parameters are consilience.

UPD. I found solution for latest problem:

```<code>INSERT OR REPLACE INTO Books (Bookname, AuthorName, Genre, amount) VALUES ( @name, @author, @genre, @amount)....
</code>```

As you can see, for saving progress after closing a program, i needed add name of columns after "Books".

答:
I understand that you want to :

insert a row if there not already a row with the same BookName, AuthorName and Genre

otherwise update the existing row by increasing the amount by the specified value

If your version of SQLite is newer than 3.24.0, you can use an UPSERT

You need first to create a unique constraints on what define an existing row

```<code>CREATE UNIQUE INDEX uniquebook ON Books(BookName, AuthorName, Genre);
</code>```

You can then use queries like :

```<code>INSERT INTO Books (BookName, AuthorName, Genre, Amount)
VALUES (@name, @author, @genre, @amount)
ON CONFLIT(Bookname, AuthorName, Genre)
DO UPDATE SET amount = amount + @amount
</code>```

Edit :
With older version of SQlite :

```<code>INSERT OR REPLACE INTO Books (BookName, AuthorName, Genre, Amount)
VALUES (
  @name,
  @author,
  @genre,
  COALESCE((SELECT Amount FROM Books WHERE BookName = @name and AuthorName = @author AND Genre = @genre), 0) + @amount
);
</code>```

In this case the unique index is not mandatory (but still recommended for performance and data consistency reason)

Body:
I edited my question but it still close without response. So i took advise from messagebox and open another question with more information.

I had table in my librarian database app on Windows Form, And one of columns include parameter "amount'. How can i correctly increase it if there consilience in all other columns in addrow SQLcommand?

Here code:

        private void ConfimAddBookButtom_Click(object sender, EventArgs e)
        {
            string conString = "Data Source=Books.db;Version=3;";
            string name = AddBookNameTextBox.Text;
            string author = AddBookAuthorTextBox.Text;
            string genre = AddBookGenreTextBox.Text;
            int amount = 1;
            string SQLiteExpression = "insert into Books (BookName, AuthorName, Genre, Amount) values (@name, @author, @genre, @amount)";
            using (SQLiteConnection connection = new SQLiteConnection(conString))
            {
                connection.Open();
                SQLiteCommand command = new SQLiteCommand(SQLiteExpression, connection);
                SQLiteParameter nameParam = new SQLiteParameter("@name", name);
                SQLiteParameter authorParam = new SQLiteParameter("@author", author);
                SQLiteParameter genreParam = new SQLiteParameter("@genre", genre);
                SQLiteParameter amountParam = new SQLiteParameter("@amount", amount);
                command.Parameters.Add(nameParam); command.Parameters.Add(authorParam); command.Parameters.Add(genreParam); command.Parameters.Add(amountParam);
                int number = command.ExecuteNonQuery();
                connection.Close();
                MessageBox.Show("Book sucsessfuly added");
                this.Close();
            }

As you can see. The row will be always added with amount equal 1. And i needed to increase amount in the exsisted row if other parameters are consilience.

UPD. I found solution for latest problem:

INSERT OR REPLACE INTO Books (Bookname, AuthorName, Genre, amount) VALUES ( @name, @author, @genre, @amount)....

As you can see, for saving progress after closing a program, i needed add name of columns after "Books".

Body:
I understand that you want to :

insert a row if there not already a row with the same BookName, AuthorName and Genre

otherwise update the existing row by increasing the amount by the specified value

If your version of SQLite is newer than 3.24.0, you can use an UPSERT

You need first to create a unique constraints on what define an existing row

CREATE UNIQUE INDEX uniquebook ON Books(BookName, AuthorName, Genre);

You can then use queries like :

INSERT INTO Books (BookName, AuthorName, Genre, Amount)
VALUES (@name, @author, @genre, @amount)
ON CONFLIT(Bookname, AuthorName, Genre)
DO UPDATE SET amount = amount + @amount

Edit :
With older version of SQlite :

INSERT OR REPLACE INTO Books (BookName, AuthorName, Genre, Amount)
VALUES (
  @name,
  @author,
  @genre,
  COALESCE((SELECT Amount FROM Books WHERE BookName = @name and AuthorName = @author AND Genre = @genre), 0) + @amount
);

In this case the unique index is not mandatory (but still recommended for performance and data consistency reason)


来源: stackexchange

问:
ClickHouse: How to move data from tables with different partition keys?
I'm planning on doing a table redesign in ClickHouse to avoid some performance and deduplication/versioning issues while using ReplicatedReplacingMergeTree. Here, OPTIMIZE FINAL can be run to remove duplicates but can't be run continuously.

So we are planning to keep a table A, partitioned daily, with incoming data.
Then a table B, partitioned monthly, where historical data will be stored.
Queries will be directed to a MERGE table (not MergeTree) that will contain both.

And then, we'd set up an action to move the latest partition, from A to B, every day right after the end of the day.

However, moving partition as in MOVE PARTITION TO TABLE where it is stated that "Both tables must have the same partition key.", it is not possible.
An approach is to copy data from A's daily partition to B, and then detach/drop daily partition in A. However in the meantime we'll see duplicates.

What would be the best way to transfer this data from A to B with minimal impact? What other options would be?

答:
An approach is to copy data from A's daily partition to B, and then
  detach/drop daily partition in A. However in the meantime we'll see duplicates.

you can copy data to an intermediate/temporary table TB (the same structure / partitioning as B). Then drop partition in A, then move from TB to B

ContentLicense: CC BY-SA 4.0


问:
i-phone sending mail automatically

Possible Duplicate:

  How i send email from IPhone?

I want to send a predefined mail through my i-phone app.I know we can use MFMailComposeViewController.but i dont want to open a separate MFMailComposeView.when user click the send button mail should send automatically.thanks in advance.

答:
Unfortunately iOS does not allow sending emails without the user noticing.

What you can do instead is use a server that sends the email for you. Like so:

iPhone -> sends request to server that includes the recipient, body, subject of the email -> server will send the email for the user

Note that this means that the sender address is not the users one.

ContentLicense: CC BY-SA 3.0

Title: i-phone sending mail automatically


问:
I cant get all HTML with Python Requests
```<code>import requests as req

html = req.get(url)
texto = html.text
print(texto)
</code>```

I cant get all HTML with Python Requests, only gets a litle part from the html file.

答:
You need to add headers to your request to obtain a response like in your browser. Try:

```<code>import requests as req

headers = {
    'Host': 'servidor.aternos.me',
    'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Language': 'fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3',
    'Accept-Encoding': 'gzip, deflate, br',
    'Connection': 'keep-alive',
    'Cookie': 'axcaccess=e75a91ffeda624d3a1e24c1d9fb31734',
    'Upgrade-Insecure-Requests': '1'
}
url = 'https://servidor.aternos.me/'
html = req.get(url, headers=headers, timeout=10.)
print(html.status_code)
texto = html.text
print(texto)
</code>```

Body:
import requests as req

html = req.get(url)
texto = html.text
print(texto)

I cant get all HTML with Python Requests, only gets a litle part from the html file.

Body:
You need to add headers to your request to obtain a response like in your browser. Try:

import requests as req

headers = {
    'Host': 'servidor.aternos.me',
    'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Language': 'fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3',
    'Accept-Encoding': 'gzip, deflate, br',
    'Connection': 'keep-alive',
    'Cookie': 'axcaccess=e75a91ffeda624d3a1e24c1d9fb31734',
    'Upgrade-Insecure-Requests': '1'
}
url = 'https://servidor.aternos.me/'
html = req.get(url, headers=headers, timeout=10.)
print(html.status_code)
texto = html.text
print(texto)


问:
Javascript – use X amount of object variables in if statement
I'd like to make the following code more generic/page-independent so that I can use it for other projects too.

The code is checking if a certain value in the localCache exists and if the location.pathname has a certain string. If so, it should scroll to top etc.

Now it looks like this:

```<code>if (referrer == "home" && location.pathname == "projects"){
    window.scrollTo(0,0);
    localStorage.setItem('referrer', 'projects');
}
</code>```

I'd like to make more generic so that it's not depending on the exact amount of strings of the location.pathname and so that it can refer to an X amount of location.pathnames.

I tried to make an object out of the different strings like this:

```<code>let object = {
    homePage: "home",
    noScrollPages: {[
      "projects",
      "about",
      "info"
    ]}
}

if (referrer == homePage && (location.pathname == "/" + noScrollPages[0]) || location.pathname == "/" + noScrollPages[1] || location.pathname == "/" + noScrollPages[2]){
    window.scrollTo(0,0);
    localStorage.setItem("referrer", noScrollPages[0, 1, 2 or X, whichever resolves as true in the if statement]);
    console.log(localStorage.getItem("referrer"));
}
</code>```

So, basically I don't know how code it so that it doesn't rely on the explicit declaration of [0] or [1], because it could be X number of pages.

Thanks for any tips!

答:
Try Array#find():

let object = {
    homePage: "home",
    noScrollPages: [
      "projects",
      "about",
      "info"
    ]
}

// the matching page, or undefined if not found
const noScrollPage = object.noScrollPages.find(page => location.pathname === "/" + page);
if (referrer === homePage && noScrollPage) {
    window.scrollTo(0,0);
    localStorage.setItem("referrer", noScrollPage);
    console.log(localStorage.getItem("referrer"));
}
```

Body:
I'd like to make the following code more generic/page-independent so that I can use it for other projects too.

The code is checking if a certain value in the localCache exists and if the location.pathname has a certain string. If so, it should scroll to top etc.

Now it looks like this:

if (referrer == "home" && location.pathname == "projects"){
    window.scrollTo(0,0);
    localStorage.setItem('referrer', 'projects');
}

I'd like to make more generic so that it's not depending on the exact amount of strings of the location.pathname and so that it can refer to an X amount of location.pathnames.

I tried to make an object out of the different strings like this:

let object = {
    homePage: "home",
    noScrollPages: {[
      "projects",
      "about",
      "info"
    ]}
}

if (referrer == homePage && (location.pathname == "/" + noScrollPages[0]) || location.pathname == "/" + noScrollPages[1] || location.pathname == "/" + noScrollPages[2]){
    window.scrollTo(0,0);
    localStorage.setItem("referrer", noScrollPages[0, 1, 2 or X, whichever resolves as true in the if statement]);
    console.log(localStorage.getItem("referrer"));
}

So, basically I don't know how code it so that it doesn't rely on the explicit declaration of [0] or [1], because it could be X number of pages.

Thanks for any tips!


问:
Is it possitble to get SelectionIndex of DataGridTextColumn when its is in editing Mode(Not SelectedIndex) in WPF?
I paste formatted text array to data grid and it works fine. However, when the datagrid is editing mode I want to paste the clipboard data exactly where the cursor point is. By default datagrid's can paste any point of selection.

Is it possible to get the SelectionIndex of DataGridTextColumn when its in editing Mode(Not SelectedIndex) in WPF?

```<code>DataGridCellInfo cell1 = data_grid.SelectedCells[datagridColumn];
string text = Convert.ToString((cell1.Item as ChoiceList).Choice);
TextBox textBox = new TextBox();
textBox.Text = text+ data[0,0];
int ind = ((cell1.Item as ChoiceList).Id) - 1;
ChoiceListView[ind].Choice = textBox.Text;
</code>```

答:
I'm still not sure I fully understand, but I think you're looking for something like this:</p>

```<code>//Assuming datagridColumn is the index of the column you want

ChoiceList item = (ChoiceList)data_grid.SelectedItem;
if (item != null)
{
    DataGridRow row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromItem(item);
    TextBox tb = (TextBox)data_grid.Columns[datagridColumn].GetCellContent(row);
    tb.SelectedText = (string)data[0, 0];
}
</code>```

Body:
I paste formatted text array to data grid and it works fine. However, when the datagrid is editing mode I want to paste the clipboard data exactly where the cursor point is. By default datagrid's can paste any point of selection.

Is it possible to get the SelectionIndex of DataGridTextColumn when its in editing Mode(Not SelectedIndex) in WPF?

DataGridCellInfo cell1 = data_grid.SelectedCells[datagridColumn];
string text = Convert.ToString((cell1.Item as ChoiceList).Choice);
TextBox textBox = new TextBox();
textBox.Text = text+ data[0,0];
int ind = ((cell1.Item as ChoiceList).Id) - 1;
ChoiceListView[ind].Choice = textBox.Text;

Body:
I'm still not sure I fully understand, but I think you're looking for something like this:

//Assuming datagridColumn is the index of the column you want

ChoiceList item = (ChoiceList)data_grid.SelectedItem;
if (item != null)
{
    DataGridRow row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromItem(item);
    TextBox tb = (TextBox)data_grid.Columns[datagridColumn].GetCellContent(row);
    tb.SelectedText = (string)data[0, 0];
}


问:
Keras : problem with gradients, custom layer won't work in a sequential model
This is the error message I get with the code down below:

ValueError: No gradients provided for any variable: ['Variable:0'].

right after it goes through the whole layer's build(), in model.fit().

It prints the input and the scalar after going through build() and before raising the error, but the tensors are both empty:

```<code>Tensor("IteratorGetNext:0", shape=(None, 1), dtype=float32)
<tf.Variable 'Variable:0' shape=(1,) dtype=float>
</code>```

My goal was to write a (basic) custom layer and to insert it in a (basic) model.
My custom layer works properly on its own but I can't get the model to fit.
The layer take a tensor and multiply it by a scalar. I want my model to give me input*(scalar I chose early on).

Thus far I've gotten plenty of Error Warning about the dtype of various tensors (I had int32 instead of float32) so I wrote plenty of casts, and I had a model more complex but I stripped it to the bones to debug (it didn't help much…).

I tried with and without a "build()", with and without using "to_categorical" on the labels, with vector inputs and scalar inputs, and other probably insignificant stuff.

Here is the code of the layer:

from tensorflow.python.keras import layers
import tensorflow as tf
from tensorflow.python.ops import math_ops
from tensorflow.python.framework import tensor_shape
import h5py
import numpy as np

class MyBasicLayer(layers.Layer):
    def __init__(self, **kwargs):
        super().__init__(self)
        self._set_dtype_policy('float32')
        self.w = self.add_weight(shape=(1,), initializer='zeros', trainable=True)

    def build(self, input_shape):
        input_shape = tensor_shape.TensorShape(input_shape)
        if tensor_shape.dimension_value(input_shape[-1]) is None:
            raise ValueError('The last dimension of the inputs to `MyBasicLayer` should be defined. Found `None`.')
        super().build(input_shape)

    def call(self, inputs):
        print(inputs)
        print(self.w)
        return tf.math.multiply(tf.dtypes.cast(inputs,dtype='float32'),self.w)
```

<p>And here is the code of the model:</p>

<pre class="lang-py prettyprint-override"><code>import numpy as np
import tensorflow as tf
import os
from tensorflow.keras import Sequential
from my_basic_layer import MyBasicLayer
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.utils import to_categorical
from tensorflow.python.keras.layers import Activation
from tensorflow.keras import activations

k = 2.

# load the dataset
inset = np.array([[i] for i in range(40)], dtype='float32')
outset = inset * k
#outset = to_categorical(outset, num_classes =256)

# define the model
model = Sequential()
model.add(MyBasicLayer(input_shape=(1,))) #input_shape=(4,)
#model.add(Activation(activations.softmax))

# compile the model
model.compile()

# fit the model
model.fit(inset, outset)
model.summary()
</code>```

Maybe relevant for all I know:

I wanted to have a model.summary() before the compilation but I got

This model has not yet been built. Build the model first by calling build() or calling fit() with some data, or specify an input_shape argument in the first layer(s) for automatic build.

even after adding el famoso input_shape argument in the first layer.

Thank you

答:
Specifying the Solution here (Answer Section) even though it is present in the Comments Sections, for the benefit of the Community.

The error, ValueError: No gradients provided for any variable: ['Variable:0']. in the above case is because No Loss Function was provided when the Model is Compiled.

So, replacing

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

with

```<code>model.compile(loss='categorical_crossentropy')
</code>```

will fix the error.

For the sake of completeness, the Simple working example code which uses Custom Layer is shown below:

```<code>from tensorflow.python.keras import layers
import tensorflow as tf
from tensorflow.python.ops import math_ops
from tensorflow.python.framework import tensor_shape
import h5py
import numpy as np

class MyBasicLayer(layers.Layer):
    def __init__(self, **kwargs):
        super().__init__(self)
        self._set_dtype_policy('float32')
        self.w = self.add_weight(shape=(1,), initializer='zeros', trainable=True)

    def build(self, input_shape):
        input_shape = tensor_shape.TensorShape(input_shape)
        if tensor_shape.dimension_value(input_shape[-1]) is None:
            raise ValueError('The last dimension of the inputs to `MyBasicLayer` should be defined. Found `None`.')
        super().build(input_shape)

    def call(self, inputs):
        print(inputs)
        print(self.w)
        return tf.math.multiply(tf.dtypes.cast(inputs,dtype='float32'),self.w)

import numpy as np
import tensorflow as tf
import os
from tensorflow.keras import Sequential
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.utils import to_categorical
from tensorflow.python.keras.layers import Activation
from tensorflow.keras import activations

k = 2.

# load the dataset
inset = np.array([[i] for i in range(40)], dtype='float32')
outset = inset * k
#outset = to_categorical(outset, num_classes =256)

# define the model
model = Sequential()
model.add(MyBasicLayer(input_shape=(1,))) #input_shape=(4,)

# compile the model
model.compile(loss='categorical_crossentropy')

# fit the model
model.fit(inset, outset)
model.summary()
</code>```

Output of the above code is shown below:

```<code>Tensor("IteratorGetNext:0", shape=(None, 1), dtype=float32)
<tf.Variable 'Variable:0' shape=(1,) dtype=float32>
Tensor("IteratorGetNext:0", shape=(None, 1), dtype=float32)
<tf.Variable 'Variable:0' shape=(1,) dtype=float32>
2/2 [==============================] - 0s 2ms/step - loss: nan
Model: "sequential_3"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
my_basic_layer_3 (MyBasicLay multiple                  1
=================================================================
Total params: 1
Trainable params: 1
Non-trainable params: 0
</code>```

Hope this helps. Happy Learning!

Body:
This is the error message I get with the code down below:

ValueError: No gradients provided for any variable: ['Variable:0'].

right after it goes through the whole layer's build(), in model.fit().

It prints the input and the scalar after going through build() and before raising the error, but the tensors are both empty:

Tensor("IteratorGetNext:0", shape=(None, 1), dtype=float32)
<tf.Variable 'Variable:0' shape=(1,) dtype=float>

My goal was to write a (basic) custom layer and to insert it in a (basic) model.
My custom layer works properly on its own but I can't get the model to fit.
The layer take a tensor and multiply it by a scalar. I want my model to give me input*(scalar I chose early on).

Thus far I've gotten plenty of Error Warning about the dtype of various tensors (I had int32 instead of float32) so I wrote plenty of casts, and I had a model more complex but I stripped it to the bones to debug (it didn't help much…).

I tried with and without a "build()", with and without using "to_categorical" on the labels, with vector inputs and scalar inputs, and other probably insignificant stuff.

Here is the code of the layer:

from tensorflow.python.keras import layers
import tensorflow as tf
from tensorflow.python.ops import math_ops
from tensorflow.python.framework import tensor_shape
import h5py
import numpy as np

class MyBasicLayer(layers.Layer):
    def __init__(self, **kwargs):
        super().__init__(self)
        self._set_dtype_policy('float32')
        self.w = self.add_weight(shape=(1,), initializer='zeros', trainable=True)

    def build(self, input_shape):
        input_shape = tensor_shape.TensorShape(input_shape)
        if tensor_shape.dimension_value(input_shape[-1]) is None:
            raise ValueError('The last dimension of the inputs to `MyBasicLayer` should be defined. Found `None`.')
        super().build(input_shape)

    def call(self, inputs):
        print(inputs)
        print(self.w)
        return tf.math.multiply(tf.dtypes.cast(inputs,dtype='float32'),self.w)

And here is the code of the model:

import numpy as np
import tensorflow as tf
import os
from tensorflow.keras import Sequential
from my_basic_layer import MyBasicLayer
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.utils import to_categorical
from tensorflow.python.keras.layers import Activation
from tensorflow.keras import activations

k = 2.

# load the dataset
inset = np.array([[i] for i in range(40)], dtype='float32')
outset = inset * k
#outset = to_categorical(outset, num_classes =256)

# define the model
model = Sequential()
model.add(MyBasicLayer(input_shape=(1,))) #input_shape=(4,)
#model.add(Activation(activations.softmax))

# compile the model
model.compile()

# fit the model
model.fit(inset, outset)
model.summary()

Maybe relevant for all I know:

I wanted to have a model.summary() before the compilation but I got

This model has not yet been built. Build the model first by calling build() or calling fit() with some data, or specify an input_shape argument in the first layer(s) for automatic build.

even after adding el famoso input_shape argument in the first layer.

Thank you

Body:
Specifying the Solution here (Answer Section) even though it is present in the Comments Sections, for the benefit of the Community.

The error, ValueError: No gradients provided for any variable: ['Variable:0']. in the above case is because No Loss Function was provided when the Model is Compiled.

So, replacing

model.compile()

with

model.compile(loss='categorical_crossentropy')

will fix the error.

For the sake of completeness, the Simple working example code which uses Custom Layer is shown below:

from tensorflow.python.keras import layers
import tensorflow as tf
from tensorflow.python.ops import math_ops
from tensorflow.python.framework import tensor_shape
import h5py
import numpy as np

class MyBasicLayer(layers.Layer):
    def __init__(self, **kwargs):
        super().__init__(self)
        self._set_dtype_policy('float32')
        self.w = self.add_weight(shape=(1,), initializer='zeros', trainable=True)

    def build(self, input_shape):
        input_shape = tensor_shape.TensorShape(input_shape)
        if tensor_shape.dimension_value(input_shape[-1]) is None:
            raise ValueError('The last dimension of the inputs to `MyBasicLayer` should be defined. Found `None`.')
        super().build(input_shape)

    def call(self, inputs):
        print(inputs)
        print(self.w)
        return tf.math.multiply(tf.dtypes.cast(inputs,dtype='float32'),self.w)

import numpy as np
import tensorflow as tf
import os
from tensorflow.keras import Sequential
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.utils import to_categorical
from tensorflow.python.keras.layers import Activation
from tensorflow.keras import activations

k = 2.

# load the dataset
inset = np.array([[i] for i in range(40)], dtype='float32')
outset = inset * k
#outset = to_categorical(outset, num_classes =256)

# define the model
model = Sequential()
model.add(MyBasicLayer(input_shape=(1,))) #input_shape=(4,)

# compile the model
model.compile(loss='categorical_crossentropy')

# fit the model
model.fit(inset, outset)
model.summary()

Output of the above code is shown below:

Tensor("IteratorGetNext:0", shape=(None, 1), dtype=float32)
<tf.Variable 'Variable:0' shape=(1,) dtype=float32>
Tensor("IteratorGetNext:0", shape=(None, 1), dtype=float32)
<tf.Variable 'Variable:0' shape=(1,) dtype=float32>
2/2 [==============================] - 0s 2ms/step - loss: nan
Model: "sequential_3"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
my_basic_layer_3 (MyBasicLay multiple                  1
=================================================================
Total params: 1
Trainable params: 1
Non-trainable params: 0

Hope this helps. Happy Learning!


问:
How can I adjust DIV width to contents
I have a div element with style attached:

```<code>.mypost {
    border: 1px solid Peru;
    font-family: arial;
    margin: auto;
    min-width: 700px;
    width: 700px;
}
</code>```

I am diplaying WordPress post contents inside the DIV block but for simplicity let assume that there is only one  inside the DIV. I want my div to be minimum 700 px wide and adjust the width if image is wider than 700 px.

What are my options to achieve that? Please advice.

UPDATE

See my Fiddle
http://jsfiddle.net/cpt_comic/4qjXv/

答:
One way you can achieve this is setting display: inline-block; on the div. It is by default a block element, which will always fill the width it can fill (unless specifying width of course).

inline-block's only downside is that IE only supports it correctly from version 8. IE 6-7 only allows setting it on naturally inline elements, but there are hacks to solve this problem.

There are other options you have, you can either float it, or set position: absolute on it, but these also have other effects on layout, you need to decide which one fits your situation better.

inline-block jsFiddle Demo

Title: How can I adjust DIV width to contents

Body:
I have a div element with style attached:

.mypost {
    border: 1px solid Peru;
    font-family: arial;
    margin: auto;
    min-width: 700px;
    width: 700px;
}

I am diplaying WordPress post contents inside the DIV block but for simplicity let assume that there is only one  inside the DIV. I want my div to be minimum 700 px wide and adjust the width if image is wider than 700 px.

What are my options to achieve that? Please advice.

UPDATE

See my Fiddle
http://jsfiddle.net/cpt_comic/4qjXv/


问:
Excel power query, 1 row of multiple workbooks
hope you can help me.

I recently stumbled across excel power query, but I’m not getting too far with it.

I’m trying to pull data from around 40 workbooks in the same folder. Each workbook has 2 sheets , but the only sheet I’m concerned with is sheet 1. Row 1 of each sheet 1 has a summary of the data I need, so I only need row 1 x 40,

There are no tables on the workbooks, it’s just some basic data, however, row 1 contains a sum formula in each of the 20 columns.

Is this doable? I have to manually copy and paste each row 1 into a master every week.

Thanks very much if you can help.

答:
Assuming, column names in all files are the same and you wish to keep filenames:</p>

```<code>let
    Source = Folder.Files(YourFolder),
    transform = Table.TransformColumns(Source, {"Content", each Table.FirstN(Excel.Workbook(_){[Item="Sheet1"]}[Data],1)})[[Content],[Name]],
    expand = Table.ExpandTableColumn(transform, "Content", Table.ColumnNames(transform[Content]{0}))
in
    expand
</code>```

Body:
Assuming, column names in all files are the same and you wish to keep filenames:

let
    Source = Folder.Files(YourFolder),
    transform = Table.TransformColumns(Source, {"Content", each Table.FirstN(Excel.Workbook(_){[Item="Sheet1"]}[Data],1)})[[Content],[Name]],
    expand = Table.ExpandTableColumn(transform, "Content", Table.ColumnNames(transform[Content]{0}))
in
    expand


问:
How to change jQuery code to Vanilla JavaScript
I am trying to push my JS knowledge, hence I am trying to convert JQuery code to JavaScript. This is jQuery code

```<code>      $('a[href*="#"]')// Select all links with hashes
              // Remove links that don't actually link to anything
              .not('[href="#"]')
              .not('[href="#0"]')
              .click(function(event) {
                // On-page links
                if (
                  location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
                  &&
                  location.hostname == this.hostname
                ) {
                  // Figure out element to scroll to
                  var target = $(this.hash);
                  target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
                  // Does a scroll target exist?
                  if (target.length) {
                    // Only prevent default if animation is actually going to happen
                    event.preventDefault();
                    $('html, body').animate({
                      scrollTop: target.offset().top
                    }, 850, function() {
                      // Callback after animation
                      // Must change focus!
                      var $target = $(target);
                      $target.focus();
                      if ($target.is(":focus")) { // Checking if the target was focused
                        return false;
                      } else {
                        $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
                        $target.focus(); // Set focus again
                      };
                    });
                  }
                }
              });
</code>```

And this is something that I have changed, but I'm not sure how to continue, I'm a beginner so I am facing some struggles.I try my level best to convert that JQuery code to "vanilla" JS but did some mistakes. Can you please tell me where I went wrong??

```<code>  document.querySelectorAll('a[href*="#"]')// Select all links with hashes
  // Remove links that don't actually link to anything
  .not('[href="#"]')
  .not('[href="#0"]')
  .addEventListener(function(event) {
    // On-page links
    if (
      location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
      &&
      location.hostname == this.hostname
    ) {
      // Figure out element to scroll to
      var target =document.querySelector(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      // Does a scroll target exist?
      if (target.length) {
        // Only prevent default if animation is actually going to happen
        event.preventDefault();
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 850, function() {
          // Callback after animation
          // Must change focus!
          var $target = $(target);
          $target.focus();
          if ($target.is(":focus")) { // Checking if the target was focused
            return false;
          } else {
            $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
            $target.focus(); // Set focus again
          };
        });
      }
    }
  });
</code>```

答:
As your goal is to learn, I'll try to help with next steps rather than give a code solution.

jQuery uses fluent API. This is the syntax allowing you to chain operations, one after another. For example, see the way .not and .click are chained here:

```<code>$('a[href*="#"]').not('[href="#"]').not('[href="#0"]').click ...
</code>```

Although fluent interfaces can be created in Javascript, the language itself does not have a fluent API. The converted code would initially fail due to this foundational difference.

To convert the jQuery to Javascript, one approach is to look for functional parts of the code and then wrap those in functions. At this point it could still be jQuery in the functions. An example of this would be the code that selects the correct links on the page.

Next, you could call each function one by one, learning about and converting the parts which fail. You've correctly identified for example that one difference is the way selectors work.

A less frustrating approach might be to start from scratch though, after identifying the goal of the code overall. Snippets can still be taken from the jQuery version, but it could be easier to troubleshoot raising it from the ground yourself. This route might even mean ending up with simpler code for your intended purpose.

Body:
I am trying to push my JS knowledge, hence I am trying to convert JQuery code to JavaScript. This is jQuery code

      $('a[href*="#"]')// Select all links with hashes
              // Remove links that don't actually link to anything
              .not('[href="#"]')
              .not('[href="#0"]')
              .click(function(event) {
                // On-page links
                if (
                  location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
                  &&
                  location.hostname == this.hostname
                ) {
                  // Figure out element to scroll to
                  var target = $(this.hash);
                  target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
                  // Does a scroll target exist?
                  if (target.length) {
                    // Only prevent default if animation is actually going to happen
                    event.preventDefault();
                    $('html, body').animate({
                      scrollTop: target.offset().top
                    }, 850, function() {
                      // Callback after animation
                      // Must change focus!
                      var $target = $(target);
                      $target.focus();
                      if ($target.is(":focus")) { // Checking if the target was focused
                        return false;
                      } else {
                        $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
                        $target.focus(); // Set focus again
                      };
                    });
                  }
                }
              });

And this is something that I have changed, but I'm not sure how to continue, I'm a beginner so I am facing some struggles.I try my level best to convert that JQuery code to "vanilla" JS but did some mistakes. Can you please tell me where I went wrong??

  document.querySelectorAll('a[href*="#"]')// Select all links with hashes
  // Remove links that don't actually link to anything
  .not('[href="#"]')
  .not('[href="#0"]')
  .addEventListener(function(event) {
    // On-page links
    if (
      location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
      &&
      location.hostname == this.hostname
    ) {
      // Figure out element to scroll to
      var target =document.querySelector(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      // Does a scroll target exist?
      if (target.length) {
        // Only prevent default if animation is actually going to happen
        event.preventDefault();
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 850, function() {
          // Callback after animation
          // Must change focus!
          var $target = $(target);
          $target.focus();
          if ($target.is(":focus")) { // Checking if the target was focused
            return false;
          } else {
            $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
            $target.focus(); // Set focus again
          };
        });
      }
    }
  });

Body:
As your goal is to learn, I'll try to help with next steps rather than give a code solution.

jQuery uses fluent API. This is the syntax allowing you to chain operations, one after another. For example, see the way .not and .click are chained here:

$('a[href*="#"]').not('[href="#"]').not('[href="#0"]').click ...

Although fluent interfaces can be created in Javascript, the language itself does not have a fluent API. The converted code would initially fail due to this foundational difference.

To convert the jQuery to Javascript, one approach is to look for functional parts of the code and then wrap those in functions. At this point it could still be jQuery in the functions. An example of this would be the code that selects the correct links on the page.

Next, you could call each function one by one, learning about and converting the parts which fail. You've correctly identified for example that one difference is the way selectors work.

A less frustrating approach might be to start from scratch though, after identifying the goal of the code overall. Snippets can still be taken from the jQuery version, but it could be easier to troubleshoot raising it from the ground yourself. This route might even mean ending up with simpler code for your intended purpose.


问:
Guard duty and vpc flow log
We have enabled vpc flow logs which are stored in s3 bucket. We have also enabled guard duty and i see it analyze vpc logs.

Anybody have suggestions, do we still need Athena table to point to S3 bucket for analyzing logs Or guard duty is sufficient

答:
It depends on what you want to achieve.

Guardduty is a detection system, it will produce findings based on its heuristics. If you are fine just with that, that would be enough.

If you expect to have to dig deeper (i.e. not only "hey, this happened", but also "what is the pattern here"), then manual analysis might be in order. I would say both things are complimentary and since you don't pay for Athena if you're not using it, have some queries prepared and run them if you can't get full picture from Guardduty.

Title: Guard duty and vpc flow log


问:
Installing oracle database express edition error /u01/app/oracle/product/11.2.0/xe/bin/nls_lang.sh: No such file or directory
I am trying to install the oracle database express from here, but after adding the following lines to the ~/.bashrc:

```<code>export PYTHONPATH EDITOR
export ORACLE_HOME=/u01/app/oracle/product/11.2.0/xe
export ORACLE_SID=XE
export NLS_LANG=`$ORACLE_HOME/bin/nls_lang.sh`
export ORACLE_BASE=/u01/app/oracle
export LD_LIBRARY_PATH=$ORACLE_HOME/lib:$LD_LIBRARY_PATH
export PATH=$ORACLE_HOME/bin:$PATH
</code>```

and then running  ~/.profile I get this error:
bash: /u01/app/oracle/product/11.2.0/xe/bin/nls_lang.sh: No such file or directory

答:
Remove the back-ticks from your definition of NLS_LANG:

```<code>ed@ed-Gazelle-00:~$ export ORACLE_HOME=/u01/app/oracle/product/11.2.0/xe
ed@ed-Gazelle-00:~$ export NLS_LANG=`$ORACLE_HOME/bin/nls_lang.sh`
bash: /u01/app/oracle/product/11.2.0/xe/bin/nls_lang.sh: No such file or directory
ed@ed-Gazelle-00:~$ export NLS_LANG=$ORACLE_HOME/bin/nls_lang.sh
ed@ed-Gazelle-00:~$
</code>```

Why did you have them there in the first place?

Body:
I am trying to install the oracle database express from here, but after adding the following lines to the ~/.bashrc:

export PYTHONPATH EDITOR
export ORACLE_HOME=/u01/app/oracle/product/11.2.0/xe
export ORACLE_SID=XE
export NLS_LANG=`$ORACLE_HOME/bin/nls_lang.sh`
export ORACLE_BASE=/u01/app/oracle
export LD_LIBRARY_PATH=$ORACLE_HOME/lib:$LD_LIBRARY_PATH
export PATH=$ORACLE_HOME/bin:$PATH

and then running  ~/.profile I get this error:
bash: /u01/app/oracle/product/11.2.0/xe/bin/nls_lang.sh: No such file or directory

Body:
Remove the back-ticks from your definition of NLS_LANG:

ed@ed-Gazelle-00:~$ export ORACLE_HOME=/u01/app/oracle/product/11.2.0/xe
ed@ed-Gazelle-00:~$ export NLS_LANG=`$ORACLE_HOME/bin/nls_lang.sh`
bash: /u01/app/oracle/product/11.2.0/xe/bin/nls_lang.sh: No such file or directory
ed@ed-Gazelle-00:~$ export NLS_LANG=$ORACLE_HOME/bin/nls_lang.sh
ed@ed-Gazelle-00:~$

Why did you have them there in the first place?


问:
How dispaly an svg on the option of select with ReactJs?
I have a select flags which the options are the img (which src are svg)

My codeSandbox.

```<code>
Config.default = "fr";
Config.list = {
  de: {
    text: "Deutsch",
    icon: require("./images/de.svg")
  },
  en: {
    text: "English",
    icon: require("./images/eng.svg")
  },
  it: {
    text: "Italiano",
    icon: require("./images/italy.svg")
  }
};
class App extends Component {
  constructor() {
    super();

    this.state = {
      language: Config.default
    };
  }

  render() {
    return (
      <header className="d-flex align-items-end justify-content-end">
        <LanguageList Language={this.state.language} />
        <FormControl variant="outlined">
          <div className="wrap-select">
            <Select
              value={this.state.language}
              className="select-lang"
              onChange={e => this.setState({ language: e.target.value })}
              inputProps={{
                name: "locale"
              }}
            >
              <MenuItem value="en">
                <div className="wrap-content-lang">
                  <img width="20" src="./images/eng.svg" />
                </div>
              </MenuItem>
              <MenuItem value="it">
                <div className="wrap-content-lang">
                  <img width="20" src="./images/italy.svg" alt="it" />
                </div>
              </MenuItem>
              <MenuItem value="de">
                <div className="wrap-content-lang">
                  <img width="20" src="./images/de.svg" />
                </div>
              </MenuItem>
            </Select>
          </div>
        </FormControl>
      </header>
    );
  }
}
</code>```

When I run it, I get:

The pictures are not displayed, How can I display it ?

答:
The problem is that such src path not available in run time:

```<code><img width="20" src="./images/eng.svg" alt="en" />

// instead
<img src={require("./images/eng.svg")}/>
</code>```

In buildtime, webpack generates a hashed path, see Adding Images, Fonts, and Files and @gdh answer.

```<code>import { ReactComponent as GermanFlag } from "./images/de.svg";

class App extends Component {
  render() {
    return <GermanFlag />;
  }
}
</code>```

Body:
I have a select flags which the options are the img (which src are svg)

My codeSandbox.

Config.default = "fr";
Config.list = {
  de: {
    text: "Deutsch",
    icon: require("./images/de.svg")
  },
  en: {
    text: "English",
    icon: require("./images/eng.svg")
  },
  it: {
    text: "Italiano",
    icon: require("./images/italy.svg")
  }
};
class App extends Component {
  constructor() {
    super();

    this.state = {
      language: Config.default
    };
  }

  render() {
    return (

        <LanguageList Language={this.state.language} />
        <FormControl variant="outlined">

            <Select
              value={this.state.language}
              className="select-lang"
              onChange={e => this.setState({ language: e.target.value })}
              inputProps={{
                name: "locale"
              }}
            >
              <MenuItem value="en">

              </MenuItem>
              <MenuItem value="it">

              </MenuItem>
              <MenuItem value="de">

              </MenuItem>
            </Select>

        </FormControl>

    );
  }
}

When I run it, I get:

The pictures are not displayed, How can I display it ?

Body:
The problem is that such src path not available in run time:

<img width="20" src="./images/eng.svg" alt="en" />

// instead
<img src={require("./images/eng.svg")}/>

In buildtime, webpack generates a hashed path, see Adding Images, Fonts, and Files and @gdh answer.

import { ReactComponent as GermanFlag } from "./images/de.svg";

class App extends Component {
  render() {
    return <GermanFlag />;
  }
}


问:
Aqueduct: Bad state: No entity found for '_MyEntity'. Did you forget to create a 'ManagedContext'?
I'm getting started on a new project and want to use test driven development.This is my entity:

```<code>import 'package:aqueduct/aqueduct.dart';

class MyEntity extends ManagedObject<_MyEntity> implements _MyEntity {}class _MyEntity {
  @primaryKey
  int id;
  int myValue;
}
</code>```

I wanted to use MyEntity independently of the database while I extract some data from text files. But when I try to test it like this

```<code>void main() {
  test('DatabaseBuilder returns multiple entities', () {
    List<MyEntity> entities = [];
    entities.add(MyEntity());
    expect(entities.length, greaterThan(0));
  });
}
</code>```

I get the following error:

Bad state: No entity found for '_MyEntity. Did you forget to create a 'ManagedContext'?

Am I not allowed to use the Entities for non-database logic?

答:
For me it was enough to instantiate a ManagedContext:

void main() {
  final dataModel = ManagedDataModel.fromCurrentMirrorSystem();
  final _ = ManagedContext(dataModel, null);

  // my tests go here
}
```

I do a simple unit testing, no database required.

Body:
I'm getting started on a new project and want to use test driven development.This is my entity:

import 'package:aqueduct/aqueduct.dart';

class MyEntity extends ManagedObject<_MyEntity> implements _MyEntity {}class _MyEntity {
  @primaryKey
  int id;
  int myValue;
}

I wanted to use MyEntity independently of the database while I extract some data from text files. But when I try to test it like this

void main() {
  test('DatabaseBuilder returns multiple entities', () {
    List<MyEntity> entities = [];
    entities.add(MyEntity());
    expect(entities.length, greaterThan(0));
  });
}

I get the following error:

Bad state: No entity found for '_MyEntity. Did you forget to create a 'ManagedContext'?

Am I not allowed to use the Entities for non-database logic?

Body:
For me it was enough to instantiate a ManagedContext:

void main() {
  final dataModel = ManagedDataModel.fromCurrentMirrorSystem();
  final _ = ManagedContext(dataModel, null);

  // my tests go here
}

I do a simple unit testing, no database required.


问:
Close open Desktop Taskpane using office.js or Add-in manifest function
We have created add-in manifest xml file for our application and also embed office.js file.
We have use custom ribbon feature by assigning url to icon. When we click on icon, it open task pane on desktop. We want to open third party url in new window of browser using Add-in manifest and taskpane should be close.
We have gone through AppDomains and uses Office.addin.hide function. But both solutions are not working.
Please provide us solution if exist.</p>

答:
Office.js doesn't provide anything for opening a new tab in a web browser. Instead, you can display a popup message. In Excel, you can use the following code to hide the task pane:

```<code> Office.addin.hide();
</code>```

For example:

```<code>function onCurrentQuarterDeactivated() {
    Office.addin.hide();
}
</code>```

See Show or hide an Office Add-in in a shared runtime for more information.

Body:
Office.js doesn't provide anything for opening a new tab in a web browser. Instead, you can display a popup message. In Excel, you can use the following code to hide the task pane:

 Office.addin.hide();

For example:

function onCurrentQuarterDeactivated() {
    Office.addin.hide();
}

See Show or hide an Office Add-in in a shared runtime for more information.


问:
Filter array by dict values and keep only unique values
How can I filter this array by the key value "name"

```<code>arr = [
  {name: "A", val: 1},
  {name: "B", val: 4},
  {name: "C", val: 5},
  {name: "A", val: 2},
  {name: "C", val: 3},
]
</code>```

So that the output looks like this:

```<code>newArr = [
  {name: "A", val: 1},
  {name: "B", val: 4},
  {name: "C", val: 5},
]
</code>```

答:
const arr = [
    { name: 'A', val: 1 },
    { name: 'B', val: 4 },
    { name: 'C', val: 5 },
    { name: 'A', val: 2 },
    { name: 'C', val: 3 },
];

const newArr = arr.filter((value, index, self) => self.findIndex(i => i.name === value.name) === index);

console.log(newArr);```

Body:
How can I filter this array by the key value "name"

arr = [
  {name: "A", val: 1},
  {name: "B", val: 4},
  {name: "C", val: 5},
  {name: "A", val: 2},
  {name: "C", val: 3},
]

So that the output looks like this:

newArr = [
  {name: "A", val: 1},
  {name: "B", val: 4},
  {name: "C", val: 5},
]


问:
SQL Efficiency - Query using dateAdd Function twice; or SubQuery and DateAdd Function once; on Date BETWEEN
The expense is using the DateAdd function not only in the SELECT, but also in the WHERE;
Or using the Sub Query which initially returns more data than I need, but then can be filtered without using the DateAdd function again on the database.

Execution Plan seems to imply that they are identical as far as it is concerned.
I'm wondering which would be more efficient?

```<code>    DECLARE @DateFrom DateTime
    SET @DateFrom = '2011-05-27'
    DECLARE @DateTo DateTime
    SET @DateTo = '2011-06-27'

    SELECT id, name,
    dateAdd(hour, datediff(hour, getdate(), getutcdate()), --UTC offset
            dateadd(second, itsm_requiredbyx, '1/1/1970 12:00 AM')) as itsm_requiredbyx
    FROM tablename
    WHERE dateAdd(hour, datediff(hour, getdate(), getutcdate()), --UTC offset
            dateadd(second, itsm_requiredbyx, '1/1/1970 12:00 AM'))
            BETWEEN @DateFrom AND @DateTo

    ORDER BY itsm_requiredbyx desc

    ---------------------------------------------------------------------------------------------

    SELECT *
    FROM
        (
        select id, name,
        dateAdd(hour, datediff(hour, getdate(), getutcdate()), --UTC offset
                dateadd(second, itsm_requiredbyx, '1/1/1970 12:00 AM')) as itsm_requiredbyx
        from tablename
        ) RR
    WHERE itsm_requiredbyx BETWEEN @DateFrom AND @DateTo
    ORDER BY itsm_requiredbyx desc
</code>```

答:
I don't think it matters which of the two you use. And the Execution Plans agree.

But it seems you are doing calculations to column itsm_requiredbyx and then check if the result is between two external values, @DateFrom and @DateTo. This way, all datetimes from this field are processed by the functions before the WHERE conditions can be applied and no index can be used. The second link (Ten Common SQL Programming Mistakes) in @DOK's answer provide more detailed info on why and when this happens.

If you don't do any calculations to the column, but you do the (reversed) calculations to the external values instead and then check if itsm_requiredbyx is between these two calculated values, the query can use an index of itsm_requiredbyx (and the functions will only be called twice and not for every row in the table).

Body:
The expense is using the DateAdd function not only in the SELECT, but also in the WHERE;
Or using the Sub Query which initially returns more data than I need, but then can be filtered without using the DateAdd function again on the database.

Execution Plan seems to imply that they are identical as far as it is concerned.
I'm wondering which would be more efficient?

    DECLARE @DateFrom DateTime
    SET @DateFrom = '2011-05-27'
    DECLARE @DateTo DateTime
    SET @DateTo = '2011-06-27'

    SELECT id, name,
    dateAdd(hour, datediff(hour, getdate(), getutcdate()), --UTC offset
            dateadd(second, itsm_requiredbyx, '1/1/1970 12:00 AM')) as itsm_requiredbyx
    FROM tablename
    WHERE dateAdd(hour, datediff(hour, getdate(), getutcdate()), --UTC offset
            dateadd(second, itsm_requiredbyx, '1/1/1970 12:00 AM'))
            BETWEEN @DateFrom AND @DateTo

    ORDER BY itsm_requiredbyx desc

    ---------------------------------------------------------------------------------------------

    SELECT *
    FROM
        (
        select id, name,
        dateAdd(hour, datediff(hour, getdate(), getutcdate()), --UTC offset
                dateadd(second, itsm_requiredbyx, '1/1/1970 12:00 AM')) as itsm_requiredbyx
        from tablename
        ) RR
    WHERE itsm_requiredbyx BETWEEN @DateFrom AND @DateTo
    ORDER BY itsm_requiredbyx desc


问:
how to access the source code of built in methods of Dart?
I would like to understand how built in methods work in Dart, therefore i would like to access the source code, any idea how to access a source code of built in methods? below is an example of one method map()
enter image description here</p>

答:
Well, it can be a little complicated to find the concrete implementation of all methods. There are several reasons for that:

Some implementations are different for Dart running as JavaScript and Dart running on the Dart VM.

Some methods are heavily dependent on C++ code for the Dart VM implementation.

Lots of classes in Dart are just interfaces like the Iterable which means the Iterable.map method can have different implementations for e.g. lists and maps.

However, all of the source code can be found in the GitHub repository if you browse through the code. But it takes some experience to know where to look for things:

https://github.com/dart-lang/sdk/tree/stable

So if we e.g. want to look for the default map method in Iterable we need to see if there are a default implementation. We can find the class here in the repo.:

https://github.com/dart-lang/sdk/blob/9a618e5661665b8d687a28e6b1ec25e9177ec2d7/sdk/lib/core/iterable.dart#L197

```<code>Iterable<T> map<T>(T f(E e)) => MappedIterable<E, T>(this, f);
</code>```

By searching for class MappedIterable we can see this class is implemented in:

https://github.com/dart-lang/sdk/blob/stable/sdk/lib/internal/iterable.dart#L354

```<code>class MappedIterable<S, T> extends Iterable<T> {
  final Iterable<S> _iterable;
  final _Transformation<S, T> _f;

  factory MappedIterable(Iterable<S> iterable, T function(S value)) {
    if (iterable is EfficientLengthIterable) {
      return new EfficientLengthMappedIterable<S, T>(iterable, function);
    }
    return new MappedIterable<S, T>._(iterable, function);
  }

  MappedIterable._(this._iterable, this._f);

  Iterator<T> get iterator => new MappedIterator<S, T>(_iterable.iterator, _f);

  // Length related functions are independent of the mapping.
  int get length => _iterable.length;
  bool get isEmpty => _iterable.isEmpty;

  // Index based lookup can be done before transforming.
  T get first => _f(_iterable.first);
  T get last => _f(_iterable.last);
  T get single => _f(_iterable.single);
  T elementAt(int index) => _f(_iterable.elementAt(index));
}
</code>```

One details you will see is that a lot of the SDK are duplicated right now in a sdk and sdk_nnbd version. This is temporarily while the Dart team are implementing the non-nullable by default feature and is not used unless you are running with this feature turned on.

Body:
Well, it can be a little complicated to find the concrete implementation of all methods. There are several reasons for that:

Some implementations are different for Dart running as JavaScript and Dart running on the Dart VM.

Some methods are heavily dependent on C++ code for the Dart VM implementation.

Lots of classes in Dart are just interfaces like the Iterable which means the Iterable.map method can have different implementations for e.g. lists and maps.

However, all of the source code can be found in the GitHub repository if you browse through the code. But it takes some experience to know where to look for things:

https://github.com/dart-lang/sdk/tree/stable

So if we e.g. want to look for the default map method in Iterable we need to see if there are a default implementation. We can find the class here in the repo.:

https://github.com/dart-lang/sdk/blob/9a618e5661665b8d687a28e6b1ec25e9177ec2d7/sdk/lib/core/iterable.dart#L197

Iterable<T> map<T>(T f(E e)) => MappedIterable<E, T>(this, f);

By searching for class MappedIterable we can see this class is implemented in:

https://github.com/dart-lang/sdk/blob/stable/sdk/lib/internal/iterable.dart#L354

class MappedIterable<S, T> extends Iterable<T> {
  final Iterable<S> _iterable;
  final _Transformation<S, T> _f;

  factory MappedIterable(Iterable<S> iterable, T function(S value)) {
    if (iterable is EfficientLengthIterable) {
      return new EfficientLengthMappedIterable<S, T>(iterable, function);
    }
    return new MappedIterable<S, T>._(iterable, function);
  }

  MappedIterable._(this._iterable, this._f);

  Iterator<T> get iterator => new MappedIterator<S, T>(_iterable.iterator, _f);

  // Length related functions are independent of the mapping.
  int get length => _iterable.length;
  bool get isEmpty => _iterable.isEmpty;

  // Index based lookup can be done before transforming.
  T get first => _f(_iterable.first);
  T get last => _f(_iterable.last);
  T get single => _f(_iterable.single);
  T elementAt(int index) => _f(_iterable.elementAt(index));
}

One details you will see is that a lot of the SDK are duplicated right now in a sdk and sdk_nnbd version. This is temporarily while the Dart team are implementing the non-nullable by default feature and is not used unless you are running with this feature turned on.


问:
How to remove duplicate names from a list in python?
I've a list that contains thousands of Instagram usernames and some of them are repeated 2 or 3 times. I want to remove all the duplicates in one function but when I try to remove all the duplicates some of them remains in the list and are removed when I call that function again and again.

```<code>>>> def rem():
   for n in m:
       if m.count(n) > 1:
           m.remove(n)
   print(len(m))

>>> rem()
231
>>> rem()
200
>>> rem()
200
</code>```

Here is the sample List:

```<code>>>> a = list(range(100))
>>> b = list(range(150))
>>> c = list(range(40, 100))
>>> d = list(range(100, 200))
>>> m = a+b+c+d
</code>```

答:
Just convert it into a set, then back to a list:

```<code>def rem():
    m = list(set(m))
    print(len(m))
</code>```

Or even better, only ever store them in a set. Sets must have unique keys, meaning it won't ever store duplicates.

Body:
I've a list that contains thousands of Instagram usernames and some of them are repeated 2 or 3 times. I want to remove all the duplicates in one function but when I try to remove all the duplicates some of them remains in the list and are removed when I call that function again and again.

>>> def rem():
   for n in m:
       if m.count(n) > 1:
           m.remove(n)
   print(len(m))

>>> rem()
231
>>> rem()
200
>>> rem()
200

Here is the sample List:

>>> a = list(range(100))
>>> b = list(range(150))
>>> c = list(range(40, 100))
>>> d = list(range(100, 200))
>>> m = a+b+c+d

Body:
Just convert it into a set, then back to a list:

def rem():
    m = list(set(m))
    print(len(m))

Or even better, only ever store them in a set. Sets must have unique keys, meaning it won't ever store duplicates.


问:
Vuex: Add Dynamic Property to Object without triggering Watchers on existing Properties
I have a Vuex store with an object:

```<code> state: {
    contents: {},
 }
</code>```

where I dynamically store contents by key:

```<code>mutations: {
   updateContent: (state, { id, a, b }) => {
       Vue.set(state.contents, id, { a, b });
   },
}
</code>```

and get them using:

```<code>getters: {
    content: (state) => (id) => {
        if (id in state.contents) return state.contents[id];
        return [];
    }
},
</code>```

Let's say I have a component like this:

```<code>export default {
    props: ["id"],
    computed: {
       myContent() {
          return this.$store.getters.content(this.id)
       }
    },
    // ...
}
</code>```

How can I add dynamic properties using the mutation without triggering changes in components watching unchanged, already existant properties of state.contents?

Also see this fiddle.

答:
If you want to watch inner property of objects, you can use deep watchers.

In your situation, i am assuming you're setting properly yor getters, setter and update methods. You should add this to your watchers:

```<code>// ...
watch:{
  id: {
    deep: true,
    handler(newVal, oldVal){
      console.log("New value and old value: ", newVal, oldVal")
      // ... make your own logic here
    }
  }
}
</code>```

Let me explain little bit more above code, when we want to watch inner property of any object in Vue, we should use deep and handler function to manipulate in every change. (remember that, handler is not a random name, it's reserved keyword)

Body:
I have a Vuex store with an object:

 state: {
    contents: {},
 }

where I dynamically store contents by key:

mutations: {
   updateContent: (state, { id, a, b }) => {
       Vue.set(state.contents, id, { a, b });
   },
}

and get them using:

getters: {
    content: (state) => (id) => {
        if (id in state.contents) return state.contents[id];
        return [];
    }
},

Let's say I have a component like this:

export default {
    props: ["id"],
    computed: {
       myContent() {
          return this.$store.getters.content(this.id)
       }
    },
    // ...
}

How can I add dynamic properties using the mutation without triggering changes in components watching unchanged, already existant properties of state.contents?

Also see this fiddle.

Body:
If you want to watch inner property of objects, you can use deep watchers.

In your situation, i am assuming you're setting properly yor getters, setter and update methods. You should add this to your watchers:

// ...
watch:{
  id: {
    deep: true,
    handler(newVal, oldVal){
      console.log("New value and old value: ", newVal, oldVal")
      // ... make your own logic here
    }
  }
}

Let me explain little bit more above code, when we want to watch inner property of any object in Vue, we should use deep and handler function to manipulate in every change. (remember that, handler is not a random name, it's reserved keyword)


问:
Observable<string[]> in ngIf directive
I have a method that returns roles of a user like:

```<code>  getUserRoles() : Observable<string[]> {
    return this.getToken().pipe(
      map(token => {
        let payload = decode(token);
        return payload["roles"];
      })
    )
  }
</code>```

I'm trying to use this in an anchor to hide/show the item based on a role like:

```<code><a *ngIf="(authService.getUserRoles | async).includes('admin')" routerLink="/admin" clrDropdownItem>Admin</a>
</code>```

However, I get the compiler error:

```<code>ERROR in src/app/components/profile/profile.component.html:15:18 - error TS2769: No overload matches this call.
  The last overload gave the following error.
    Argument of type '() => Observable<string[]>' is not assignable to parameter of type 'Promise<unknown>'.
      Type '() => Observable<string[]>' is missing the following properties from type 'Promise<unknown>': then, catch, [Symbol.toStringTag], finally

15       <a *ngIf="(authService.getUserRoles | async).includes('admin')" routerLink="/admin" clrDropdownItem>Admin</a>
                    ~~~~~~~~~~~~~~~~~~~~~~~~~

  src/app/components/profile/profile.component.ts:7:16
    7   templateUrl: './profile.component.html',
                     ~~~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component ProfileComponent.
</code>```

Can't quite figure out what I'm doing wrong. I'm using Angular 9.

答:
Ah, I think I get it!

I had a somewhat similar problem once, also with a function call in the template. Long story short, change detection triggered change detection, which is more or less while (true);.

Try changing this

```<code><a *ngIf="(authService.getUserRoles() | async).includes('admin')" ...
</code>```

into something like

```<code><a *ngIf="userIsAdmin" ...
</code>```

and in the TS part of the component

```<code>userIsAdmin = false;
onDestroy = new Subject();

ngOnInit() {
    this.authService.getUserRoles().pipe(takeUntil(this.onDestroy)).subscribe(/* assign value to this.userIsAdmin here
}

ngOnDestroy() {
    /* To prevent a memory leak */
    this.onDestroy.next();
    this.onDestroy.complete();
}
</code>```

Title: Observable<string[]> in ngIf directive

Body:
I have a method that returns roles of a user like:

  getUserRoles() : Observable<string[]> {
    return this.getToken().pipe(
      map(token => {
        let payload = decode(token);
        return payload["roles"];
      })
    )
  }

I'm trying to use this in an anchor to hide/show the item based on a role like:

Admin

However, I get the compiler error:

ERROR in src/app/components/profile/profile.component.html:15:18 - error TS2769: No overload matches this call.
  The last overload gave the following error.
    Argument of type '() => Observable<string[]>' is not assignable to parameter of type 'Promise<unknown>'.
      Type '() => Observable<string[]>' is missing the following properties from type 'Promise<unknown>': then, catch, [Symbol.toStringTag], finally

15       Admin
                    ~~~~~~~~~~~~~~~~~~~~~~~~~

  src/app/components/profile/profile.component.ts:7:16
    7   templateUrl: './profile.component.html',
                     ~~~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component ProfileComponent.

Can't quite figure out what I'm doing wrong. I'm using Angular 9.

Body:
Ah, I think I get it!

I had a somewhat similar problem once, also with a function call in the template. Long story short, change detection triggered change detection, which is more or less while (true);.

Try changing this

<a *ngIf="(authService.getUserRoles() | async).includes('admin')" ...

into something like

<a *ngIf="userIsAdmin" ...

and in the TS part of the component

userIsAdmin = false;
onDestroy = new Subject();

ngOnInit() {
    this.authService.getUserRoles().pipe(takeUntil(this.onDestroy)).subscribe(/* assign value to this.userIsAdmin here
}

ngOnDestroy() {
    /* To prevent a memory leak */
    this.onDestroy.next();
    this.onDestroy.complete();
}


问:
Where is __USE_BSD flag defined?
My project is building to Debian 8 without any problems.

But when building on debian 10, it leaves for this block:

```<code>#if (defined __USE_BSD)
....
#else
#error "this condition is met"
#endif
</code>```

Where should __USE_BSD flag be defined?

Why is building to 8, but not 10?

答:
__USE_BSD is deprecated. It has changed to __USE_MISC and it is defined in features.h from glibc. You can see it in issues on github and on LWN. From Debian 8 to Debian 10 the glic package has changed to adapt to this situation, so you have to verify for the definition of __USE_MISC
.
Code below:

```<code>#include <features.h>

#if (defined __USE_MISC)
...
#else
 #error "this condition is met"
#endif
</code>```

Title: Where is __USE_BSD flag defined?

Body:
My project is building to Debian 8 without any problems.

But when building on debian 10, it leaves for this block:

#if (defined __USE_BSD)
....
#else
#error "this condition is met"
#endif

Where should __USE_BSD flag be defined?

Why is building to 8, but not 10?

Body:
__USE_BSD is deprecated. It has changed to __USE_MISC and it is defined in features.h from glibc. You can see it in issues on github and on LWN. From Debian 8 to Debian 10 the glic package has changed to adapt to this situation, so you have to verify for the definition of __USE_MISC
.
Code below:

#include <features.h>

#if (defined __USE_MISC)
...
#else
 #error "this condition is met"
#endif


问:
How would I find the top 10 values of a row every 100 values?
So I have a 1 x 7000 matrix  and I am wanting to to find the top 10 values of for every 100th 'sample' group of values, and replace all other values with a zero.

I have a code that works for finding the top 10 values of the whole row:

```<code>[sortvals, sortidx] = sort(A,2,'descend');
B = zeros(size(A),classA));
for K = 1 : size(A,1)
    B(K,sortidx(K,1:10)) = sortvals(K,1:10);
end
</code>```

But I can't think of how to implement this for every 100 values except maybe a brute method of splitting, finding the values, then appending but that seems needlessly messy.

答:
Reshape A into a matrix with 100 rows (and adjust the columns accordingly) and then apply maxk to find the indices of top 10 elements of each column. Convert these to linear indices of A and extract the elements at those indices.

```<code>%Extract top 10 values in every 100 values
top = 10;   every = 100;
%Reshape into a 100*x matrix
tmp =  reshape(A, every, []);
%Find row subscripts of required max values
[~, ind] = maxk(tmp,top);
%Convert row subscripts to linear indices
LinIdx = (0:every:(size(tmp,2)-1)*every) + ind;
%Initialize a matrix with all zeros of the same size and class as that of A
B = zeros(size(A), classA);
%Insert the top values
B(LinIdx) = A(LinIdx);
</code>```

Body:
So I have a 1 x 7000 matrix  and I am wanting to to find the top 10 values of for every 100th 'sample' group of values, and replace all other values with a zero.

I have a code that works for finding the top 10 values of the whole row:

[sortvals, sortidx] = sort(A,2,'descend');
B = zeros(size(A),classA));
for K = 1 : size(A,1)
    B(K,sortidx(K,1:10)) = sortvals(K,1:10);
end

But I can't think of how to implement this for every 100 values except maybe a brute method of splitting, finding the values, then appending but that seems needlessly messy.

Body:
Reshape A into a matrix with 100 rows (and adjust the columns accordingly) and then apply maxk to find the indices of top 10 elements of each column. Convert these to linear indices of A and extract the elements at those indices.

%Extract top 10 values in every 100 values
top = 10;   every = 100;
%Reshape into a 100*x matrix
tmp =  reshape(A, every, []);
%Find row subscripts of required max values
[~, ind] = maxk(tmp,top);
%Convert row subscripts to linear indices
LinIdx = (0:every:(size(tmp,2)-1)*every) + ind;
%Initialize a matrix with all zeros of the same size and class as that of A
B = zeros(size(A), classA);
%Insert the top values
B(LinIdx) = A(LinIdx);


问:
How to convert an integer into an array of digits
I want to convert an integer, say 12345, to an array like [1,2,3,4,5].

I have tried the below code, but is there a better way to do this?

```<code>var n = 12345;
var arr = n.toString().split('');
for (i = 0; i < arr.length; i++) arr[i] = +arr[i] | 0;
</code>```

答:
Another way is by using literals and then spread:

const n = 12345;
const arr = [...`${n}`].map(Number);
console.log(arr);```

Body:
I want to convert an integer, say 12345, to an array like [1,2,3,4,5].

I have tried the below code, but is there a better way to do this?

var n = 12345;
var arr = n.toString().split('');
for (i = 0; i < arr.length; i++) arr[i] = +arr[i] | 0;


问:
Sympy: Is there a way to collect and factorise the constant terms
If I have this expression:

x2a2 - x2b2 + 2xa1 - 2xb1 + 12a0 - 12b0

How do I get sympy to give me this?

x2(a2 - b2) + 2x(a1 - b1) + 12(a0 - b0)

This is my code:

```<code>from sympy import sympify, factor_terms, collect
x = symbols('x', real=True)
a2, a1, a0  = symbols('a2 a1 a0', real = True, constant = True)
b2, b1, b0  = symbols('b2 b1 b0', real = True, constant = True)
c2, c1, c0  = symbols('c2 c1 c0', real = True, constant = True)

expr = sympify(x**2*a2 - x**2*b2 + 2*a1*x - 2*b1*x + 12*a0 - 12*b0)
f_expr = factor_terms(collect(expr, x))
display(f_expr)
</code>```

Returns:

x2(a2 - b2) + 2x(a1 - b1) + 12a0 - 12b0

What I'm looking for is something that collects the constant terms (coefficients of x0 and is able to factorize them. Namely

x2(a2 - b2) + 2x(a1 - b1) + 12(a0 - b0)

Mainly so that I can replace the differences with another variable.

```<code>f_expr.replace(a2 - b2, c2).replace(a1 - b1, c1).replace(a0 - b0, c0)
</code>```

答:
You would have to do some expression wrangling to get this to happen. But doing an algebraic substitution is easier. Instead of replacing a - b -> A do a -> b + A:

```<code>>>> from sympy import var
>>> var('x:6')
(x0, x1, x2, x3, x4, x5)
>>> eq = 2*x0-2*x1+3*x2-3*x3+4*x4-4*x5
>>> eq
2*x0 - 2*x1 + 3*x2 - 3*x3 + 4*x4 - 4*x5
>>> eq.subs(dict(x0=x1+x,x2=x3+y,x4=x5+z))
2*x + 3*y + 4*z
</code>```

Body:
If I have this expression:

x2a2 - x2b2 + 2xa1 - 2xb1 + 12a0 - 12b0

How do I get sympy to give me this?

x2(a2 - b2) + 2x(a1 - b1) + 12(a0 - b0)

This is my code:

from sympy import sympify, factor_terms, collect
x = symbols('x', real=True)
a2, a1, a0  = symbols('a2 a1 a0', real = True, constant = True)
b2, b1, b0  = symbols('b2 b1 b0', real = True, constant = True)
c2, c1, c0  = symbols('c2 c1 c0', real = True, constant = True)

expr = sympify(x**2*a2 - x**2*b2 + 2*a1*x - 2*b1*x + 12*a0 - 12*b0)
f_expr = factor_terms(collect(expr, x))
display(f_expr)

Returns:

x2(a2 - b2) + 2x(a1 - b1) + 12a0 - 12b0

What I'm looking for is something that collects the constant terms (coefficients of x0 and is able to factorize them. Namely

x2(a2 - b2) + 2x(a1 - b1) + 12(a0 - b0)

Mainly so that I can replace the differences with another variable.

f_expr.replace(a2 - b2, c2).replace(a1 - b1, c1).replace(a0 - b0, c0)

Body:
You would have to do some expression wrangling to get this to happen. But doing an algebraic substitution is easier. Instead of replacing a - b -> A do a -> b + A:

>>> from sympy import var
>>> var('x:6')
(x0, x1, x2, x3, x4, x5)
>>> eq = 2*x0-2*x1+3*x2-3*x3+4*x4-4*x5
>>> eq
2*x0 - 2*x1 + 3*x2 - 3*x3 + 4*x4 - 4*x5
>>> eq.subs(dict(x0=x1+x,x2=x3+y,x4=x5+z))
2*x + 3*y + 4*z


问:
Correct usage of __str__ method for a dictionary (kwargs)
I have a task to print correctly kwargs arguments of a class.

Here is my code:

```<code> class Contact:
        def __init__(self, name, surname, number, selected=None, **kwargs):
            self.name=name
            self.surname=surname
            self.number=number
            self.selected=selected
            self.additional=kwargs
        def __str__(self):
            if self.selected==None:
                selected='No'
            else:
                selected='Yes'
            return 'Name: ' + self.name+'\n' + \
                   'Surname: ' + self.surname+ '\n' + \
                   'Phone: ' + self.number + '\n' + \
                   'In selected: ' + selected + '\n' + \
                   'Additional information: ' + '\n' + \
                   str(self.additional.keys()) + '\n' + \
                   str(self.additional.values())

    if __name__=='__main__':
        jhon = Contact('Jhon', 'Smith', '+71234567809', telegram='@jhony', email='jhony@smith.com')
        print (jhon)
</code>```

I need to have in the end:

```<code>Additional information:
     telegram : @jhony
     email : jhony@smith.com
</code>```

But all I've got is :

I've really tried to iterate over it, create lists, and I've got nothing, because the ___str___ method could only use str objects. How can I go through the kwargs arguments and take it in format of key : value?

答:
You need to iterate over the dict referenced by self.additional.

```<code>def __str__(self):
    return ('Name: ' + self.name + '\n'
            + 'Surname: ' + self.surname+ '\n' +
            + 'Phone: ' + self.number + '\n' +
            + 'In selected: ' + selected + '\n' +
            + 'Additional information: ' + '\n' +
            + '\n'.join([f'     {k}: {v}' for k, v in self.additional.items()]))
</code>```

Body:
I have a task to print correctly kwargs arguments of a class.

Here is my code:

 class Contact:
        def __init__(self, name, surname, number, selected=None, **kwargs):
            self.name=name
            self.surname=surname
            self.number=number
            self.selected=selected
            self.additional=kwargs
        def __str__(self):
            if self.selected==None:
                selected='No'
            else:
                selected='Yes'
            return 'Name: ' + self.name+'\n' + \
                   'Surname: ' + self.surname+ '\n' + \
                   'Phone: ' + self.number + '\n' + \
                   'In selected: ' + selected + '\n' + \
                   'Additional information: ' + '\n' + \
                   str(self.additional.keys()) + '\n' + \
                   str(self.additional.values())

    if __name__=='__main__':
        jhon = Contact('Jhon', 'Smith', '+71234567809', telegram='@jhony', email='jhony@smith.com')
        print (jhon)

I need to have in the end:

Additional information:
     telegram : @jhony
     email : jhony@smith.com

But all I've got is :

I've really tried to iterate over it, create lists, and I've got nothing, because the ___str___ method could only use str objects. How can I go through the kwargs arguments and take it in format of key : value?

Body:
You need to iterate over the dict referenced by self.additional.

def __str__(self):
    return ('Name: ' + self.name + '\n'
            + 'Surname: ' + self.surname+ '\n' +
            + 'Phone: ' + self.number + '\n' +
            + 'In selected: ' + selected + '\n' +
            + 'Additional information: ' + '\n' +
            + '\n'.join([f'     {k}: {v}' for k, v in self.additional.items()]))


问:
React Table usePagination not applying pagination
Codesandbox example: https://codesandbox.io/s/react-table-pagination-not-working-xt4yw

I am using the react-table package (version 7.1.0).

I have a table which shows some invoices.

I retrieve all the data on initial load. Then I want to apply client-side pagination to this data so that only some of the results show at any one time.

My data has 139 items in it.

The user will initially see 10 results and be able to 'Show More'. Currently this is implemented in a select field, which updates the pageSize

(In my example I am using fake data not coming from any endpoint.)

I am using the usePagination hook in the same way as in this official example: https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/pagination?file=/src/App.js

```<code>useTable(
    {
      columns,
      data,
      initialState: { pageIndex: 0, pageSize: 10 }
    },
    useSortBy,
    usePagination
  );
</code>```

However there must be something I am missing, because the pagination doesn't get applied, despite pageIndex and pageSize clearly being set.

```<code>  "pageIndex": 0,
  "pageSize": 10,
</code>```

All the results show at once, instead of only 10.

What is the cause of the pagination not being applied here?

Codesandbox example: https://codesandbox.io/s/react-table-pagination-not-working-xt4yw

答:
Maybe u can try this out :</p>

```<code>function Table({
  columns,
  data,
  updateMyData,

}) {
  const defaultColumn = React.useMemo(
    () => ({
      // Let's set up our default Filter UI
      Filter: false,
    }),
    []
  )
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    page,
    flatColumns,
    prepareRow,
    setColumnOrder,
    state,

    canPreviousPage,
    canNextPage,
    pageOptions,
    pageCount,
    gotoPage,
    nextPage,
    previousPage,
    setPageSize,

    state: { pageIndex, pageSize },

  } = useTable(
    {
      columns,
      data,
      defaultColumn,
      updateMyData,
      initialState: { pageIndex: 0, pageSize: 10 },
    },
    useColumnOrder,
    usePagination
  )
  const spring = React.useMemo(
    () => ({
      type: 'spring',
      damping: 50,
      stiffness: 100,
    }),
    []
  )
  return (
    <>

      <br></br>
      <div>Showing the {page.length} </div>
      <br></br>
      <div className="pagination" >
        <button onClick={() => gotoPage(0)} disabled={!canPreviousPage}>
          {'<<'}
        </button>{' '}
        <button onClick={() => previousPage()} disabled={!canPreviousPage}>
          {'<'}
        </button>{' '}
        <button onClick={() => nextPage()} disabled={!canNextPage}>
          {'>'}
        </button>{' '}
        <button onClick={() => gotoPage(pageCount - 1)} disabled={!canNextPage}>
          {'>>'}
        </button>{' '}
        <span >
          Page{' '}
          {/* <strong> */}
          {pageIndex + 1} of {pageOptions.length}
          {/* </strong>{' '} */}
        </span>
        <span>
                Go to page:{' '}
          <input
            type="number"
            defaultValue={pageIndex + 1}
            onChange={e => {
              const page = e.target.value ? Number(e.target.value) - 1 : 1
              gotoPage(page)
            }}
            style={{ width: '100px' }}
          />
        </span>{' '}
        <select
          value={pageSize}
          onChange={e => {
            setPageSize(Number(e.target.value))
          }}
        >
          {[5, 10, 20, 30, 40, 50].map(pageSize => (
            <option key={pageSize} value={pageSize}>
              Show {pageSize}
            </option>
          ))}
        </select>
      </div>
    </>
  )
}
</code>```

Body:
Codesandbox example: https://codesandbox.io/s/react-table-pagination-not-working-xt4yw

I am using the react-table package (version 7.1.0).

I have a table which shows some invoices.

I retrieve all the data on initial load. Then I want to apply client-side pagination to this data so that only some of the results show at any one time.

My data has 139 items in it.

The user will initially see 10 results and be able to 'Show More'. Currently this is implemented in a select field, which updates the pageSize

(In my example I am using fake data not coming from any endpoint.)

I am using the usePagination hook in the same way as in this official example: https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/pagination?file=/src/App.js

useTable(
    {
      columns,
      data,
      initialState: { pageIndex: 0, pageSize: 10 }
    },
    useSortBy,
    usePagination
  );

However there must be something I am missing, because the pagination doesn't get applied, despite pageIndex and pageSize clearly being set.

  "pageIndex": 0,
  "pageSize": 10,

All the results show at once, instead of only 10.

What is the cause of the pagination not being applied here?

Codesandbox example: https://codesandbox.io/s/react-table-pagination-not-working-xt4yw

Body:
Maybe u can try this out :

function Table({
  columns,
  data,
  updateMyData,

}) {
  const defaultColumn = React.useMemo(
    () => ({
      // Let's set up our default Filter UI
      Filter: false,
    }),
    []
  )
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    page,
    flatColumns,
    prepareRow,
    setColumnOrder,
    state,

    canPreviousPage,
    canNextPage,
    pageOptions,
    pageCount,
    gotoPage,
    nextPage,
    previousPage,
    setPageSize,

    state: { pageIndex, pageSize },

  } = useTable(
    {
      columns,
      data,
      defaultColumn,
      updateMyData,
      initialState: { pageIndex: 0, pageSize: 10 },
    },
    useColumnOrder,
    usePagination
  )
  const spring = React.useMemo(
    () => ({
      type: 'spring',
      damping: 50,
      stiffness: 100,
    }),
    []
  )
  return (
    <>

      <br></br>
      <div>Showing the {page.length} </div>
      <br></br>
      <div className="pagination" >
        <button onClick={() => gotoPage(0)} disabled={!canPreviousPage}>
          {'<<'}
        </button>{' '}&nbsp;
        <button onClick={() => previousPage()} disabled={!canPreviousPage}>
          {'<'}
        </button>{' '}&nbsp;
        <button onClick={() => nextPage()} disabled={!canNextPage}>
          {'>'}
        </button>{' '}&nbsp;
        <button onClick={() => gotoPage(pageCount - 1)} disabled={!canNextPage}>
          {'>>'}
        </button>{' '}&nbsp;
        <span >
          Page{' '}
          {/* <strong> */}
          {pageIndex + 1} of {pageOptions.length}
          {/* </strong>{' '} */}
        </span>
        <span>
          &nbsp;&nbsp;&nbsp;&nbsp;  Go to page:{' '}
          <input
            type="number"
            defaultValue={pageIndex + 1}
            onChange={e => {
              const page = e.target.value ? Number(e.target.value) - 1 : 1
              gotoPage(page)
            }}
            style={{ width: '100px' }}
          />
        </span>{' '}
        <select
          value={pageSize}
          onChange={e => {
            setPageSize(Number(e.target.value))
          }}
        >
          {[5, 10, 20, 30, 40, 50].map(pageSize => (
            <option key={pageSize} value={pageSize}>
              Show {pageSize}
            </option>
          ))}
        </select>
      </div>
    </>
  )
}


问:
Better way to use Laravel login into a "legacy system"?
I need to make a migration of a legacy system to Laravel.
I'm using PHP 5.6 and we have a login system using session and cookies to personalize some user stuffs.
Well, I want to migrate some parts of my system and the first one I believe that will be Login, I think that I need to share login between Laravel and the old PHP, but what is the better way to do it? The users password wasn't into bcrypt encryption and I will need to share the "login" into old system pages, and the new pages migrated to Laravel..

Thanks

答:
Create a new ServiceProvider such as LegacyHashProvider

```<code>namespace App\Providers;

use App\Services\LegacyHasher;
use Illuminate\Support\ServiceProvider;

class LegacyHashProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->singleton('hash', function ($app) {
            return new LegacyHasher($app);
        });
    }

    public function provides()
    {
        return ['hash'];
    }
}
</code>```

Create a class LegacyHasher which implements Illuminate\Contracts\Hashing\Hasher interface. Write down your methods(override) such as;

```<code>public function make($value, array $options = [])
{
    return hash('sha512', $value); // this will be your legacy hashing system
}
</code>```

Navigate to config/app.php and replace Illuminate\Hashing\HashServiceProvider::class with App\Providers\LegacyHashProvider and it should be ready to use your legacy login system.

Body:
Create a new ServiceProvider such as LegacyHashProvider

namespace App\Providers;

use App\Services\LegacyHasher;
use Illuminate\Support\ServiceProvider;

class LegacyHashProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->singleton('hash', function ($app) {
            return new LegacyHasher($app);
        });
    }

    public function provides()
    {
        return ['hash'];
    }
}

Create a class LegacyHasher which implements Illuminate\Contracts\Hashing\Hasher interface. Write down your methods(override) such as;

public function make($value, array $options = [])
{
    return hash('sha512', $value); // this will be your legacy hashing system
}

Navigate to config/app.php and replace Illuminate\Hashing\HashServiceProvider::class with App\Providers\LegacyHashProvider and it should be ready to use your legacy login system.


问:
Get the last run_at for a DelayedJob in Rails
I am using Rails Delayed Job to enqueue jobs to run at a specific time. Is it possible to know the timestamp for when a particular Delayed Job is last run?</p>

答:
If there is no timestamp in the database already, you can use a callback for the job: https://guides.rubyonrails.org/active_job_basics.html#callbacks
You could create a new model called JobLogs for example and save the data there.

As you can see from the documentation you can use the callback after_perform :save_time in your job and then define the method somewhat like this:

```<code>def save_time
  JobLog.create(last_run: Time.now.utc)
end
</code>```

Body:
If there is no timestamp in the database already, you can use a callback for the job: https://guides.rubyonrails.org/active_job_basics.html#callbacks
You could create a new model called JobLogs for example and save the data there.

As you can see from the documentation you can use the callback after_perform :save_time in your job and then define the method somewhat like this:

def save_time
  JobLog.create(last_run: Time.now.utc)
end


问:
Displaying Unlimited Structure of Categories --> Subcategories --> etc?
I imagine this is a fairly common requirement for people when it comes to building any kind of application that relies on sorting and displaying data in categories - any CMS/Forums/Carts etc and I've been tearing my hair out trying to think of a way to show all categories and their children to no avail - the best I've managed is while loop within while loop (however many levels I think I may require) but this defeats the point of programming in my opinion, it needs to be effortlessly extensible.

So, given:

```<code>Category 1
-Sub cat
-Sub cat
--Sub sub cat
--- Sub sub cat
-- Sub sub cat
-Sub cat
Category 2
-Sub cat
-Sub cat
--Sub sub cat
---sub sub sub cat
----sub sub sub sub cat
-sub cat
Category 3
-Sub cat
</code>```

Database fields: ID Name ParentIDS

How would you go about echoing each of the categories in their hierarchy from a database?

I'd post my code, but obviously its massive, given the long-hand way of nesting loops.

I've thought about writing bits of code that find the 'depth' of the category tree but that still isn't cutting it.. ideas?

答:
There is a pretty good tutorial on mysql website.

http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/
Goto the The Nested Set Model if you want to read the interesting part

Frankly I do not think there are any other /better way to store hierearchical data.

Body:
I imagine this is a fairly common requirement for people when it comes to building any kind of application that relies on sorting and displaying data in categories - any CMS/Forums/Carts etc and I've been tearing my hair out trying to think of a way to show all categories and their children to no avail - the best I've managed is while loop within while loop (however many levels I think I may require) but this defeats the point of programming in my opinion, it needs to be effortlessly extensible.

So, given:

Category 1
-Sub cat
-Sub cat
--Sub sub cat
--- Sub sub cat
-- Sub sub cat
-Sub cat
Category 2
-Sub cat
-Sub cat
--Sub sub cat
---sub sub sub cat
----sub sub sub sub cat
-sub cat
Category 3
-Sub cat

Database fields: ID Name ParentIDS

How would you go about echoing each of the categories in their hierarchy from a database?

I'd post my code, but obviously its massive, given the long-hand way of nesting loops.

I've thought about writing bits of code that find the 'depth' of the category tree but that still isn't cutting it.. ideas?


问:
How to intertwine Async functions and sync functions in flutter
I am a beginner to flutter and I don't quite understand how to use Async functions in flutter.
For example,

```<code>Future <String> readData() async {
  final file = await localFile;
  String body = await file.readAsString();
  return body;
}
</code>```

So in this code, I retrieve some data from a local file. But I want to run this function at the start of the app and want to display the result.

Unfortunately, my build function in main.dart is a synchronous one and when I do:

```<code>child : Text(readData());
</code>```

It does not work due to the fact that it returns a Future . I can't use the await keyword either because it Build is not async.
How do I go about waiting to get this string and display it?

答:
You can try using FutureBuilder

```<code>  child: FutureBuilder<String>(
      builder: (context, data) {
        return Text(data.hasData ? data.data : '');
      },
      future: readData(),
  ),
</code>```

Body:
I am a beginner to flutter and I don't quite understand how to use Async functions in flutter.
For example,

Future <String> readData() async {
  final file = await localFile;
  String body = await file.readAsString();
  return body;
}

So in this code, I retrieve some data from a local file. But I want to run this function at the start of the app and want to display the result.

Unfortunately, my build function in main.dart is a synchronous one and when I do:

child : Text(readData());

It does not work due to the fact that it returns a Future . I can't use the await keyword either because it Build is not async.
How do I go about waiting to get this string and display it?

Body:
You can try using FutureBuilder

  child: FutureBuilder<String>(
      builder: (context, data) {
        return Text(data.hasData ? data.data : '');
      },
      future: readData(),
  ),


问:
SwiftUI - Save results of a Form to JSON
I'm new to SwiftUI, haven't coded in 15 years, but taking this on as a hobby. I am trying to take the results of a form and convert it to JSON so that I can save the output to a database. Can anyone provide some guidance?

```<code>var body: some View {
   Form {
      Section(header: Text("Section 1")) {
          Toggle(isOn: $answer1) {
             Text("How would you like to answer this question?")
          }
          ...
      }
      ...
   }
   NavigationLink(destination: FormResult()) {
      Text("Submit")
   }
}
</code>```

How do I make that form into a JSON? Does it need to be codable?

答:
If you want to save your data locally, the best option (for most simple cases) would be to use CoreData. It uses entities which are classes, so you don't have to convert your data to JSON.

```<code>class Item: NSManagedObject {
    @NSManaged public var id: String
    @NSManaged public var name: String
}
</code>```

```<code>let item = Item(context: context)
item.id = form.id
item.name = form.name
try? context.save()
</code>```

Where context is your global managedObjectContext (and preferably its child).

Body:
I'm new to SwiftUI, haven't coded in 15 years, but taking this on as a hobby. I am trying to take the results of a form and convert it to JSON so that I can save the output to a database. Can anyone provide some guidance?

var body: some View {
   Form {
      Section(header: Text("Section 1")) {
          Toggle(isOn: $answer1) {
             Text("How would you like to answer this question?")
          }
          ...
      }
      ...
   }
   NavigationLink(destination: FormResult()) {
      Text("Submit")
   }
}

How do I make that form into a JSON? Does it need to be codable?

Body:
If you want to save your data locally, the best option (for most simple cases) would be to use CoreData. It uses entities which are classes, so you don't have to convert your data to JSON.

class Item: NSManagedObject {
    @NSManaged public var id: String
    @NSManaged public var name: String
}

let item = Item(context: context)
item.id = form.id
item.name = form.name
try? context.save()

Where context is your global managedObjectContext (and preferably its child).


问:
Azure resource monitoring issue
Questions that I have is:

How SQL Virtual machine is getting created in my azure subscription as I am not creating it through the Azure portal or neither through an ARM template?

I am installing SQL server express edition in my VM through Microsoft's site does this triggers a SQL VM resource creation in Azure as well?

How to figure out the resource creation/deployments in Azure, where to find these logs?

How to recreate this issue?

答:
In the resource group the vm is in click Deployments:

This will give the list of deployments and hopefully give you an idea where the deployment came from.

Title: Azure resource monitoring issue