问:
Understanding accumulated gradients in PyTorch
I am trying to comprehend inner workings of the gradient accumulation in PyTorch. My question is somewhat related to these two:

Why do we need to call zero_grad() in PyTorch?

Why do we need to explicitly call zero_grad()?

Comments to the accepted answer to the second question suggest that accumulated gradients can be used if a minibatch is too large to perform a gradient update in a single forward pass, and thus has to be split into multiple sub-batches.

Consider the following toy example:

```<code>import numpy as np
import torch

class ExampleLinear(torch.nn.Module):

    def __init__(self):
        super().__init__()
        # Initialize the weight at 1
        self.weight = torch.nn.Parameter(torch.Tensor([1]).float(),
                                         requires_grad=True)

    def forward(self, x):
        return self.weight * x

if __name__ == "__main__":
    # Example 1
    model = ExampleLinear()

    # Generate some data
    x = torch.from_numpy(np.array([4, 2])).float()
    y = 2 * x

    optimizer = torch.optim.SGD(model.parameters(), lr=0.01)

    y_hat = model(x)          # forward pass

    loss = (y - y_hat) ** 2
    loss = loss.mean()        # MSE loss

    loss.backward()           # backward pass

    optimizer.step()          # weight update

    print(model.weight.grad)  # tensor([-20.])
    print(model.weight)       # tensor([1.2000]
</code>```

Which is exactly the result one would expect. Now assume that we want to process the dataset sample-by-sample utilizing gradient accumulation:

```<code>    # Example 2: MSE sample-by-sample
    model2 = ExampleLinear()
    optimizer = torch.optim.SGD(model2.parameters(), lr=0.01)

    # Compute loss sample-by-sample, then average it over all samples
    loss = []
    for k in range(len(y)):
        y_hat = model2(x[k])
        loss.append((y[k] - y_hat) ** 2)
    loss = sum(loss) / len(y)

    loss.backward()     # backward pass
    optimizer.step()    # weight update

    print(model2.weight.grad)  # tensor([-20.])
    print(model2.weight)       # tensor([1.2000]
</code>```

Again as expected, the gradient is calculated when the .backward() method is called.

Finally to my question: what exactly happens 'under the hood'?

My understanding is that the computational graph is dynamically updated going from <PowBackward> to <AddBackward> <DivBackward> operations for the loss variable, and that no information about the data used for each forward pass is retained anywhere except for the loss tensor which can be updated until the backward pass.

Are there any caveats to the reasoning in the above paragraph? Lastly, are there any best practices to follow when using gradient accumulation (i.e. can the approach I use in Example 2 backfire somehow)?

答:
You are not actually accumulating gradients. Just leaving off optimizer.zero_grad() has no effect if you have a single .backward() call, as the gradients are already zero to begin with (technically None but they will be
automatically initialised to zero).

The only difference between your two versions, is how you calculate the final loss. The for loop of the second example does the same calculations as PyTorch does in the first example, but you do them individually, and PyTorch cannot optimise (parallelise and vectorise) your for loop, which makes an especially staggering difference on GPUs, granted that the tensors aren't tiny.

Before getting to gradient accumulation, let's start with your question:

Finally to my question: what exactly happens 'under the hood'?

Every operation on tensors is tracked in a computational graph if and only if one of the operands is already part of a computational graph. When you set requires_grad=True of a tensor, it creates a computational graph with a single vertex, the tensor itself, which will remain a leaf in the graph. Any operation with that tensor will create a new vertex, which is the result of the operation, hence there is an edge from the operands to it, tracking the operation that was performed.

a = torch.tensor(2.0, requires_grad=True)
b = torch.tensor(4.0)
c = a + b # => tensor(6., grad_fn=<AddBackward0>)

a.requires_grad # => True
a.is_leaf # => True

b.requires_grad # => False
b.is_leaf # => True

c.requires_grad # => True
c.is_leaf # => False
```
<p><img src="https://i.stack.imgur.com/Zgaxn.png" alt="Graph c = a + b" /></p>
<p>Every intermediate tensor automatically requires gradients and has a <code>grad_fn</code>, which is the function to calculate the partial derivatives with respect to its inputs. Thanks to the chain rule, we can traverse the whole graph in reverse order to calculate the derivatives with respect to every single leaf, which are the parameters we want to optimise. That's the idea of backpropagation, also known as <em>reverse mode differentiation</em>. For more details I recommend reading Calculus on Computational Graphs: Backpropagation.</p>
<p>PyTorch uses that exact idea, when you call <code>loss.backward()</code> it traverses the graph in reverse order, starting from <code>loss</code>, and calculates the derivatives for each vertex. Whenever a leaf is reached, the calculated derivative for that tensor is stored in its <code>.grad</code> attribute.</p>
<p>In your first example, that would lead to:</p>
```MeanBackward -> PowBackward -> SubBackward -> MulBackward`
```
<p>The second example is almost identical, except that you calculate the mean manually, and instead of having a single path for the loss, you have multiple paths for each element of the loss calculation. To clarify, the single path also calculates the derivatives of each element, but internally, which again opens up the possibilities for some optimisations.</p>
<pre class="lang-py prettyprint-override"><code># Example 1
loss = (y - y_hat) ** 2
# => tensor([16.,  4.], grad_fn=<PowBackward0>)

# Example 2
loss = []
for k in range(len(y)):
    y_hat = model2(x[k])
    loss.append((y[k] - y_hat) ** 2)
loss
# => [tensor([16.], grad_fn=<PowBackward0>), tensor([4.], grad_fn=<PowBackward0>)]
</code>```

In either case a single graph is created that is backpropagated exactly once, that's the reason it's not considered gradient accumulation.

Gradient Accumulation

Gradient accumulation refers to the situation, where multiple backwards passes are performed before updating the parameters. The goal is to have the same model parameters for multiple inputs (batches) and then update the model's parameters based on all these batches, instead of performing an update after every single batch.

Let's revisit your example. x has size [2], that's the size of our entire dataset. For some reason, we need to calculate the gradients based on the whole dataset. That is naturally the case when using a batch size of 2, since we would have the whole dataset at once. But what happens if we can only have batches of size 1? We could run them individually and update the model after each batch as usual, but then we don't calculate the gradients over the whole dataset.

What we need to do, is run each sample individually with the same model parameters and calculate the gradients without updating the model. Now you might be thinking, isn't that what you did in the second version? Almost, but not quite, and there is a crucial problem in your version, namely that you are using the same amount of memory as in the first version, because you have the same calculations and therefore the same number of values in the computational graph.

How do we free memory? We need to get rid of the tensors of the previous batch and also the computational graph, because that uses a lot of memory to keep track of everything that's necessary for the backpropagation. The computational graph is automatically destroyed when .backward() is called (unless retain_graph=True is specified).

def calculate_loss(x: torch.Tensor) -> torch.Tensor:
    y = 2 * x
    y_hat = model(x)
    loss = (y - y_hat) ** 2
    return loss.mean()

# With mulitple batches of size 1
batches = [torch.tensor([4.0]), torch.tensor([2.0])]

optimizer.zero_grad()
for i, batch in enumerate(batches):
    # The loss needs to be scaled, because the mean should be taken across the whole
    # dataset, which requires the loss to be divided by the number of batches.
    loss = calculate_loss(batch) / len(batches)
    loss.backward()
    print(f"Batch size 1 (batch {i}) - grad: {model.weight.grad}")
    print(f"Batch size 1 (batch {i}) - weight: {model.weight}")

# Updating the model only after all batches
optimizer.step()
print(f"Batch size 1 (final) - grad: {model.weight.grad}")
print(f"Batch size 1 (final) - weight: {model.weight}")
```
<p>Output (I removed the <em>Parameter containing</em> messages for readability):</p>
```Batch size 1 (batch 0) - grad: tensor([-16.])
Batch size 1 (batch 0) - weight: tensor([1.], requires_grad=True)
Batch size 1 (batch 1) - grad: tensor([-20.])
Batch size 1 (batch 1) - weight: tensor([1.], requires_grad=True)
Batch size 1 (final) - grad: tensor([-20.])
Batch size 1 (final) - weight: tensor([1.2000], requires_grad=True)
```
<p>As you can see, the model kept the same parameter for all batches, while the gradients were accumulate, and there is a single update at the end. Note that the loss needs to be scaled per batch, in order to have the same significance over the whole dataset as if you used a single batch.</p>
<p>While in this example, the whole dataset is used before performing the update, you can easily change that to update the parameters after a certain number of batches, but you have to remember to zero out the gradients after an optimiser step was taken. The general recipe would be:</p>
<pre class="lang-py prettyprint-override"><code>accumulation_steps = 10
for i, batch in enumerate(batches):
    # Scale the loss to the mean of the accumulated batch size
    loss = calculate_loss(batch) / accumulation_steps
    loss.backward()
    if (i + 1) % accumulation_steps == 0:
        optimizer.step()
        # Reset gradients, for the next accumulated batches
        optimizer.zero_grad()
</code>```

You can find that recipe and more techniques for working with large batch sizes in HuggingFace - Training Neural Nets on Larger Batches: Practical Tips for 1-GPU, Multi-GPU & Distributed setups.

Body:
I am trying to comprehend inner workings of the gradient accumulation in PyTorch. My question is somewhat related to these two:

Why do we need to call zero_grad() in PyTorch?

Why do we need to explicitly call zero_grad()?

Comments to the accepted answer to the second question suggest that accumulated gradients can be used if a minibatch is too large to perform a gradient update in a single forward pass, and thus has to be split into multiple sub-batches.

Consider the following toy example:

import numpy as np
import torch

class ExampleLinear(torch.nn.Module):

    def __init__(self):
        super().__init__()
        # Initialize the weight at 1
        self.weight = torch.nn.Parameter(torch.Tensor([1]).float(),
                                         requires_grad=True)

    def forward(self, x):
        return self.weight * x

if __name__ == "__main__":
    # Example 1
    model = ExampleLinear()

    # Generate some data
    x = torch.from_numpy(np.array([4, 2])).float()
    y = 2 * x

    optimizer = torch.optim.SGD(model.parameters(), lr=0.01)

    y_hat = model(x)          # forward pass

    loss = (y - y_hat) ** 2
    loss = loss.mean()        # MSE loss

    loss.backward()           # backward pass

    optimizer.step()          # weight update

    print(model.weight.grad)  # tensor([-20.])
    print(model.weight)       # tensor([1.2000]

Which is exactly the result one would expect. Now assume that we want to process the dataset sample-by-sample utilizing gradient accumulation:

    # Example 2: MSE sample-by-sample
    model2 = ExampleLinear()
    optimizer = torch.optim.SGD(model2.parameters(), lr=0.01)

    # Compute loss sample-by-sample, then average it over all samples
    loss = []
    for k in range(len(y)):
        y_hat = model2(x[k])
        loss.append((y[k] - y_hat) ** 2)
    loss = sum(loss) / len(y)

    loss.backward()     # backward pass
    optimizer.step()    # weight update

    print(model2.weight.grad)  # tensor([-20.])
    print(model2.weight)       # tensor([1.2000]

Again as expected, the gradient is calculated when the .backward() method is called.

Finally to my question: what exactly happens 'under the hood'?

My understanding is that the computational graph is dynamically updated going from <PowBackward> to <AddBackward> <DivBackward> operations for the loss variable, and that no information about the data used for each forward pass is retained anywhere except for the loss tensor which can be updated until the backward pass.

Are there any caveats to the reasoning in the above paragraph? Lastly, are there any best practices to follow when using gradient accumulation (i.e. can the approach I use in Example 2 backfire somehow)?

Body:
You are not actually accumulating gradients. Just leaving off optimizer.zero_grad() has no effect if you have a single .backward() call, as the gradients are already zero to begin with (technically None but they will be
automatically initialised to zero).

The only difference between your two versions, is how you calculate the final loss. The for loop of the second example does the same calculations as PyTorch does in the first example, but you do them individually, and PyTorch cannot optimise (parallelise and vectorise) your for loop, which makes an especially staggering difference on GPUs, granted that the tensors aren't tiny.

Before getting to gradient accumulation, let's start with your question:

Finally to my question: what exactly happens 'under the hood'?

Every operation on tensors is tracked in a computational graph if and only if one of the operands is already part of a computational graph. When you set requires_grad=True of a tensor, it creates a computational graph with a single vertex, the tensor itself, which will remain a leaf in the graph. Any operation with that tensor will create a new vertex, which is the result of the operation, hence there is an edge from the operands to it, tracking the operation that was performed.

a = torch.tensor(2.0, requires_grad=True)
b = torch.tensor(4.0)
c = a + b # => tensor(6., grad_fn=<AddBackward0>)

a.requires_grad # => True
a.is_leaf # => True

b.requires_grad # => False
b.is_leaf # => True

c.requires_grad # => True
c.is_leaf # => False

Every intermediate tensor automatically requires gradients and has a grad_fn, which is the function to calculate the partial derivatives with respect to its inputs. Thanks to the chain rule, we can traverse the whole graph in reverse order to calculate the derivatives with respect to every single leaf, which are the parameters we want to optimise. That's the idea of backpropagation, also known as reverse mode differentiation. For more details I recommend reading Calculus on Computational Graphs: Backpropagation.

PyTorch uses that exact idea, when you call loss.backward() it traverses the graph in reverse order, starting from loss, and calculates the derivatives for each vertex. Whenever a leaf is reached, the calculated derivative for that tensor is stored in its .grad attribute.

In your first example, that would lead to:

MeanBackward -> PowBackward -> SubBackward -> MulBackward`

The second example is almost identical, except that you calculate the mean manually, and instead of having a single path for the loss, you have multiple paths for each element of the loss calculation. To clarify, the single path also calculates the derivatives of each element, but internally, which again opens up the possibilities for some optimisations.

# Example 1
loss = (y - y_hat) ** 2
# => tensor([16.,  4.], grad_fn=<PowBackward0>)

# Example 2
loss = []
for k in range(len(y)):
    y_hat = model2(x[k])
    loss.append((y[k] - y_hat) ** 2)
loss
# => [tensor([16.], grad_fn=<PowBackward0>), tensor([4.], grad_fn=<PowBackward0>)]

In either case a single graph is created that is backpropagated exactly once, that's the reason it's not considered gradient accumulation.

Gradient Accumulation

Gradient accumulation refers to the situation, where multiple backwards passes are performed before updating the parameters. The goal is to have the same model parameters for multiple inputs (batches) and then update the model's parameters based on all these batches, instead of performing an update after every single batch.

Let's revisit your example. x has size [2], that's the size of our entire dataset. For some reason, we need to calculate the gradients based on the whole dataset. That is naturally the case when using a batch size of 2, since we would have the whole dataset at once. But what happens if we can only have batches of size 1? We could run them individually and update the model after each batch as usual, but then we don't calculate the gradients over the whole dataset.

What we need to do, is run each sample individually with the same model parameters and calculate the gradients without updating the model. Now you might be thinking, isn't that what you did in the second version? Almost, but not quite, and there is a crucial problem in your version, namely that you are using the same amount of memory as in the first version, because you have the same calculations and therefore the same number of values in the computational graph.

How do we free memory? We need to get rid of the tensors of the previous batch and also the computational graph, because that uses a lot of memory to keep track of everything that's necessary for the backpropagation. The computational graph is automatically destroyed when .backward() is called (unless retain_graph=True is specified).

def calculate_loss(x: torch.Tensor) -> torch.Tensor:
    y = 2 * x
    y_hat = model(x)
    loss = (y - y_hat) ** 2
    return loss.mean()

# With mulitple batches of size 1
batches = [torch.tensor([4.0]), torch.tensor([2.0])]

optimizer.zero_grad()
for i, batch in enumerate(batches):
    # The loss needs to be scaled, because the mean should be taken across the whole
    # dataset, which requires the loss to be divided by the number of batches.
    loss = calculate_loss(batch) / len(batches)
    loss.backward()
    print(f"Batch size 1 (batch {i}) - grad: {model.weight.grad}")
    print(f"Batch size 1 (batch {i}) - weight: {model.weight}")

# Updating the model only after all batches
optimizer.step()
print(f"Batch size 1 (final) - grad: {model.weight.grad}")
print(f"Batch size 1 (final) - weight: {model.weight}")

Output (I removed the Parameter containing messages for readability):

Batch size 1 (batch 0) - grad: tensor([-16.])
Batch size 1 (batch 0) - weight: tensor([1.], requires_grad=True)
Batch size 1 (batch 1) - grad: tensor([-20.])
Batch size 1 (batch 1) - weight: tensor([1.], requires_grad=True)
Batch size 1 (final) - grad: tensor([-20.])
Batch size 1 (final) - weight: tensor([1.2000], requires_grad=True)

As you can see, the model kept the same parameter for all batches, while the gradients were accumulate, and there is a single update at the end. Note that the loss needs to be scaled per batch, in order to have the same significance over the whole dataset as if you used a single batch.

While in this example, the whole dataset is used before performing the update, you can easily change that to update the parameters after a certain number of batches, but you have to remember to zero out the gradients after an optimiser step was taken. The general recipe would be:

accumulation_steps = 10
for i, batch in enumerate(batches):
    # Scale the loss to the mean of the accumulated batch size
    loss = calculate_loss(batch) / accumulation_steps
    loss.backward()
    if (i + 1) % accumulation_steps == 0:
        optimizer.step()
        # Reset gradients, for the next accumulated batches
        optimizer.zero_grad()

You can find that recipe and more techniques for working with large batch sizes in HuggingFace - Training Neural Nets on Larger Batches: Practical Tips for 1-GPU, Multi-GPU & Distributed setups.


来源: stackexchange

问:
Multithreaded socked server (chilkat, c)
I want to setup socket server which receive incoming connections, and for each connections makes few operations (reveive bytes, check something, send response bytes). But every connection should work independly and if something goes wrong - dont block entire server.

I want to do it using chilkat socket and task libraries.

Where in source code could i put the receiving/processing/answering/code?
Just below CkTask_Run()?
I cant get the idea how forking is done, what is "old" process/thread doing, and where is new process going.
Is there any example to get an idea how it works, or could i get some low-level explanation?

答: In my opinion, the easiest solution is to write a multi-threaded application.  You have one thread for accepting new connections.  A new thread is started to run each accepted connection.  No async or tasks are necessary.  Each thread can operate with synchronous calls for reading/writing/accepting.   </p>

ContentLicense: CC BY-SA 4.0


答:
It appears that you wish to "fix" some data that is already in your PostgreSQL database.

You could include the data using this technique:

WITH foo AS (VALUES (12, 'qwert'), (13, 'asd'), (390, 'iop'))
SELECT table.id, foo.column2
FROM table
JOIN foo ON (foo.column1 = table.id)
```

You could do it as an UPDATE statement, but it gets tricky. It would probably be easier to craft a SELECT statement that has everything you want, then use CREATE TABLE new_table AS SELECT...

See: CREATE TABLE AS - Amazon Redshift

Title: Create column based on values on another column in redshift

Body:
Suppose I have the following  table:

|---------------------|
|          id         |
|---------------------|
|          12         |
|---------------------|
|         390         |
|---------------------|
|          13         |
|---------------------|

And I want to create another column based on a map of the id column, for example:

12 -> qwert
13 -> asd
390 -> iop

So I basically want a query to create a column based on that map, my final table would be:

|---------------------|---------------------|
|          id         |          col        |
|---------------------|---------------------|
|          12         |          qwert      |
|---------------------|---------------------|
|         390         |          iop        |
|---------------------|---------------------|
|          13         |          asd        |
|---------------------|---------------------|

I have this map in a python dictionary.

Is this possible?

(It is basically pandas.map)

Body:
It appears that you wish to "fix" some data that is already in your PostgreSQL database.

You could include the data using this technique:

WITH foo AS (VALUES (12, 'qwert'), (13, 'asd'), (390, 'iop'))
SELECT table.id, foo.column2
FROM table
JOIN foo ON (foo.column1 = table.id)

You could do it as an UPDATE statement, but it gets tricky. It would probably be easier to craft a SELECT statement that has everything you want, then use CREATE TABLE new_table AS SELECT...

See: CREATE TABLE AS - Amazon Redshift


问:
Application insights without azure portal
We are building a enterprise application using UWP technology. We would like to monitor the application performance using Microsoft Application Insights. App insights telemetry data directly logged into the Azure portal. For security reason, we do not wanted to log the data to outside the boundary. Is there any way to implement the APM without using AZURE? What i meant is, we have to use app insights services, data should be logged in to on-prem server.That needs to visualized by using any tool

Thanks in advance.

Thanks
Sekar

答:
you could if you want to invent your own whole ingestion/storage system.  in the appinsights configuration you can affect the endpoint where the data created by the sdk is sent.

in the javascript sdk it is something like this

```<code>        let config: ApplicationInsights_Types.IConfiguration = {
            // endpoint by default is something like this:
            endpointUrl: "https://dc.services.visualstudio.com/v2/track",
            instrumentationKey: this._instrumentationKey
        };
</code>```

you'd have to find the corresponding thing in whatever SDK you are using.  then invent the whole backend and storage and query system to keep all that data.

the point of APM services like Application Insights and others it to not do all that work yourself.

Body:
you could if you want to invent your own whole ingestion/storage system.  in the appinsights configuration you can affect the endpoint where the data created by the sdk is sent.

in the javascript sdk it is something like this

        let config: ApplicationInsights_Types.IConfiguration = {
            // endpoint by default is something like this:
            endpointUrl: "https://dc.services.visualstudio.com/v2/track",
            instrumentationKey: this._instrumentationKey
        };

you'd have to find the corresponding thing in whatever SDK you are using.  then invent the whole backend and storage and query system to keep all that data.

the point of APM services like Application Insights and others it to not do all that work yourself.


问:
Memory efficient way for list comprehension of pandas dataframe using multiple columns
I want to run a function on rows of a pandas dataframe in list comprehension.
Dataframe can have varying number of columns.
How to make use these columns of dataframe?

import  pandas as pd

df = {'chrom': ['chr1', 'chr1','chr1'], 'start': [10000, 10100, 12000], 'end':[10150,10120,12250], 'S1':[1, 1, 1],'S2':[2, 2, 2],'S3':[3, 3, 3] }
df = pd.DataFrame(data=df)
print(df)

def func(row):
    print(row)

[func(row) for row in zip(df['chrom'],df['start'],df['S1'],df['S2'],df['S3'])]
```

How to do this in a memory efficient way? So that we do not get any memory error for big dataframes.

答:
Thanks for your answers.

Meantime, I found the following as a solution:

```<code>df_columns = list(df.columns.values)
[func_using_list_comp(
                row,
                var1,
                var2,
                var3,
                ...,
                df_columns) for row in df[df_columns].values]
</code>```

In this way, I did not need to use zip function and make it work for any number of columns.

I hope this is also memory efficient.
By the way, I'm accumulating in the var1, var2, var3 each time I process a row.

If I use generator instead of a list, how much will it affect my memory usage and will I get the all the accumulated data after processing all rows?

Since, I'm returning these var1, var2, var3 after all rows are processed.

Body:
I want to run a function on rows of a pandas dataframe in list comprehension.
Dataframe can have varying number of columns.
How to make use these columns of dataframe?

import  pandas as pd

df = {'chrom': ['chr1', 'chr1','chr1'], 'start': [10000, 10100, 12000], 'end':[10150,10120,12250], 'S1':[1, 1, 1],'S2':[2, 2, 2],'S3':[3, 3, 3] }
df = pd.DataFrame(data=df)
print(df)

def func(row):
    print(row)

[func(row) for row in zip(df['chrom'],df['start'],df['S1'],df['S2'],df['S3'])]

How to do this in a memory efficient way? So that we do not get any memory error for big dataframes.

Body:
Thanks for your answers.

Meantime, I found the following as a solution:

df_columns = list(df.columns.values)
[func_using_list_comp(
                row,
                var1,
                var2,
                var3,
                ...,
                df_columns) for row in df[df_columns].values]

In this way, I did not need to use zip function and make it work for any number of columns.

I hope this is also memory efficient.
By the way, I'm accumulating in the var1, var2, var3 each time I process a row.

If I use generator instead of a list, how much will it affect my memory usage and will I get the all the accumulated data after processing all rows?

Since, I'm returning these var1, var2, var3 after all rows are processed.


问:
React Native Push Notifications not appearing in settings
I am new to react native and I am trying to set up push notifications via iOS.

I have installed pushNotificationios and followed the instructions given. I have also signed up as an Apple Developer.

When I run my app the push notifications don't seem to work. When I go into my iPhone settings and click on the app it does not display notifications.

Here is my code

import PushNotificationIOS from '@react-native-community/push-notification-ios';
import PushNotification from "react-native-push-notification";

const configure = () => {
 PushNotification.configure({

   onRegister: (token) => {
    console.log('TOKEN:', token);
     //process token
   },

   onNotification: (notification) => {
     // process the notification
     console.log("NOTIFICATION:", notification);
     // required on iOS only
     notification.finish(PushNotificationIOS.FetchResult.NoData);
   },

   permissions: {
     alert: true,
     badge: true,
     sound: true
   },

   popInitialNotification: true,
   requestPermissions: true,

 });
};

 export {
    configure,
   };```

答:
Check your XCode Notification settings

Try to ask permission in your FirstPage as below. not index.

```<code>const MainPage = {} => {
  useEffect(() => {
    PushNotificationIOS.requestPermissions(['alert', 'badge', 'sound']);
  }, [])
}
</code>```

iOS: User cannot see the alarm option in preferences if user does not see the request Permission popup.

Android: Do not need asking permission.

Body:
Check your XCode Notification settings

Try to ask permission in your FirstPage as below. not index.

const MainPage = {} => {
  useEffect(() => {
    PushNotificationIOS.requestPermissions(['alert', 'badge', 'sound']);
  }, [])
}

iOS: User cannot see the alarm option in preferences if user does not see the request Permission popup.

Android: Do not need asking permission.


问:
Can I rewrite this macro_rules! macro in a way that works with rustfmt?
I would like to use a macro to generate identical impl blocks for multiple concrete types. My code currently looks something like this:

macro_rules! impl_methods {
    ($ty:ty, {  $($method:item);+} ) => {
        impl $ty { $($method)+ }
    };
    ($ty:ty, $($more:ty),+ {$($method:item);+}) => {
        impl_methods!($ty, {$($method);+});
        impl_methods!($($more),+, {$($method);+});
    };
}

struct Hi;
struct Hello;

impl_methods!(Hi, Hello {
    /// `true` if it works, good
    fn works_good(&self) -> bool {
        true
    };

    /// `true` if rustfmt is working
    fn gets_rustfmt(&self) -> bool {
        false
    }
});

assert!(Hi.works_good() && Hello.works_good());
assert!(!(Hi.gets_rustfmt() | Hello.gets_rustfmt()));

```

<p>This works well enough (the impls get generated) but it has one frustrating problem; the methods that are defined inside the macro don't get formatted by <code>rustfmt</code>.</p>

<p>This is a small problem, but it's annoying enough that I'm curious about a solution. I know that rustfmt will format the contents of a macro if those contents have some form (are an expression?) and so for instance the following macro's contents will get formatted:</p>

```macro_rules! fmt_me {
    ($inner:item) => {
        $inner
    };
}

fmt_me!(fn will_get_formatted() -> bool { true });
```

<p>And so I'm <em>hoping</em> that there is some way that I can write my macro like,</p>

<pre class="lang-rust prettyprint-override"><code>impl_methods!(Hi, Hello {
    fmt_me!(fn my_method(&self) -> bool { true });
    fmt_me!(fn my_other_method(&self) -> bool { false });
});
</code>```

And have each individual method get covered by rustfmt.

Is this possible? Is there some magic incantation that will give me the lovely formatting I desire?

Answer

Thanks to the answer below (from @seiichi-uchida), I can get this working with the following code:

macro_rules! impl_methods {
    ($ty:ty, {  $($method:item)+} ) => {
        impl $ty { $($method)+ }
    };
    ($ty:ty, $($more:ty),+, {$($method:item)+}) => {
        impl_methods!($ty, {$($method)+});
        impl_methods!($($more),+, {$($method)+});
    };
}

macro_rules! fmt_me {
    ($inner:item) => {
        $inner
    };
}

// called like:

impl_methods!(Hi, Hello, {
    fmt_me!(fn this_is_a_method(&self) -> bool { true });
    fmt_me!(fn this_is_another_method(&self) -> bool { true });
});
```

答:
Adding a comma between the last type and the impl block should do the trick:

impl_methods!(Hi, Hello, {
    fmt_me!(fn my_method(&self) -> bool { true });
    fmt_me!(fn my_other_method(&self) -> bool { false });
});
```

<p>This will be formatted to:</p>

``` impl_methods!(Hi, Hello, {
-    fmt_me!(fn my_method(&self) -> bool { true });
-    fmt_me!(fn my_other_method(&self) -> bool { false });
+    fmt_me!(
+        fn my_method(&self) -> bool {
+            true
+        }
+    );
+    fmt_me!(
+        fn my_other_method(&self) -> bool {
+            false
+        }
+    );
 });
```

In general, rustfmt can only format macro calls whose arguments can be parsed as valid Rust AST node (with some exceptions).

Body:
I would like to use a macro to generate identical impl blocks for multiple concrete types. My code currently looks something like this:

macro_rules! impl_methods {
    ($ty:ty, {  $($method:item);+} ) => {
        impl $ty { $($method)+ }
    };
    ($ty:ty, $($more:ty),+ {$($method:item);+}) => {
        impl_methods!($ty, {$($method);+});
        impl_methods!($($more),+, {$($method);+});
    };
}

struct Hi;
struct Hello;

impl_methods!(Hi, Hello {
    /// `true` if it works, good
    fn works_good(&self) -> bool {
        true
    };

    /// `true` if rustfmt is working
    fn gets_rustfmt(&self) -> bool {
        false
    }
});

assert!(Hi.works_good() && Hello.works_good());
assert!(!(Hi.gets_rustfmt() | Hello.gets_rustfmt()));

This works well enough (the impls get generated) but it has one frustrating problem; the methods that are defined inside the macro don't get formatted by rustfmt.

This is a small problem, but it's annoying enough that I'm curious about a solution. I know that rustfmt will format the contents of a macro if those contents have some form (are an expression?) and so for instance the following macro's contents will get formatted:

macro_rules! fmt_me {
    ($inner:item) => {
        $inner
    };
}

fmt_me!(fn will_get_formatted() -> bool { true });

And so I'm hoping that there is some way that I can write my macro like,

impl_methods!(Hi, Hello {
    fmt_me!(fn my_method(&self) -> bool { true });
    fmt_me!(fn my_other_method(&self) -> bool { false });
});

And have each individual method get covered by rustfmt.

Is this possible? Is there some magic incantation that will give me the lovely formatting I desire?

Answer

Thanks to the answer below (from @seiichi-uchida), I can get this working with the following code:

macro_rules! impl_methods {
    ($ty:ty, {  $($method:item)+} ) => {
        impl $ty { $($method)+ }
    };
    ($ty:ty, $($more:ty),+, {$($method:item)+}) => {
        impl_methods!($ty, {$($method)+});
        impl_methods!($($more),+, {$($method)+});
    };
}

macro_rules! fmt_me {
    ($inner:item) => {
        $inner
    };
}

// called like:

impl_methods!(Hi, Hello, {
    fmt_me!(fn this_is_a_method(&self) -> bool { true });
    fmt_me!(fn this_is_another_method(&self) -> bool { true });
});

Body:
Adding a comma between the last type and the impl block should do the trick:

impl_methods!(Hi, Hello, {
    fmt_me!(fn my_method(&self) -> bool { true });
    fmt_me!(fn my_other_method(&self) -> bool { false });
});

This will be formatted to:

 impl_methods!(Hi, Hello, {
-    fmt_me!(fn my_method(&self) -> bool { true });
-    fmt_me!(fn my_other_method(&self) -> bool { false });
+    fmt_me!(
+        fn my_method(&self) -> bool {
+            true
+        }
+    );
+    fmt_me!(
+        fn my_other_method(&self) -> bool {
+            false
+        }
+    );
 });

In general, rustfmt can only format macro calls whose arguments can be parsed as valid Rust AST node (with some exceptions).


问:
Javascript how to convert an anonym function to a named function
Under my Angular app :
i ve this template :

```<code><dxi-column dataField="ordre"
              caption="Ordre"
              [width]="70"
              dataType="number"
              [allowEditing]="true">
     <dxi-validation-rule type="async"
              [validationCallback]="myFunction"
              message="">
     </dxi-validation-rule>
</dxi-column>
</code>```

and myFuntion  looks like this :

```<code>  myFunction=(params) => {
    console.log(this.myClassVariable)
    return Of(!this.myClassVariable.includes(params.value)).toPromise()
  }
</code>```

My purpose is to change "myFunction" declaration to be something like this :

```<code>myFunction() {
  //SAME TREATMENT
}
</code>```

Maybe also change the invocation in the html , but basically keep the same beahviour ,
 i ve tried this :

```<code>myFunction() {
    console.log(this.myClassVariable)  // THROW UNDEFINED
    return Of(!this.myClassVariable.includes(params.value)).toPromise()
}
</code>```

but i got UNDEFINED for my class variable passing

Suggestions ??

答:
this.myFunction = this.myFunction.bind(this);

add this code in the constructor.

Body:
Under my Angular app :
i ve this template :

<dxi-column dataField="ordre"
              caption="Ordre"
              [width]="70"
              dataType="number"
              [allowEditing]="true">
     <dxi-validation-rule type="async"
              [validationCallback]="myFunction"
              message="">
     </dxi-validation-rule>
</dxi-column>

and myFuntion  looks like this :

  myFunction=(params) => {
    console.log(this.myClassVariable)
    return Of(!this.myClassVariable.includes(params.value)).toPromise()
  }

My purpose is to change "myFunction" declaration to be something like this :

myFunction() {
  //SAME TREATMENT
}

Maybe also change the invocation in the html , but basically keep the same beahviour ,
 i ve tried this :

myFunction() {
    console.log(this.myClassVariable)  // THROW UNDEFINED
    return Of(!this.myClassVariable.includes(params.value)).toPromise()
}

but i got UNDEFINED for my class variable passing

Suggestions ??


问:
Displaying the input from keypad on a LCD screen using Arduino
I want an Arduino code to give the output in following format on LCD display

If the user click 'A', 1, 2, 3 from the keypad, LCD should display Hi:1,2,3,

This is what I have tried but I cannot figure out a way to build the code as I am a beginner in arduino

```<code>#include <Keypad.h>
#include <LiquidCrystal.h>

const byte numRows= 4;
const byte numCols= 4;

char keymap[numRows][numCols]= {
    {'1', '2', '3', 'A'},
    {'4', '5', '6', 'B'},
    {'7', '8', '9', 'C'},
    {'*', '0', '#', 'D'}
};

byte rowPins[numRows] = {9,8,7,6};      // Pin Assign
byte colPins[numCols] = {5,4,3,2};      // Pin Assign

Keypad myKeypad= Keypad(makeKeymap(keymap), rowPins, colPins, numRows, numCols);

// LCD
//                RS E  D4 D5 D6 D7
LiquidCrystal lcd(A0,A1,A2,A3,A4,A5);   // Pin Assign

void setup()
{
    lcd.begin(16, 2);
    lcd.clear();
    lcd.print("PUSH ANY KEY! ");
    lcd.cursor();
    lcd.blink();
}

void loop(){
    char keypressed = myKeypad.getKey();
    if (keypressed != NO_KEY){
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print(keypressed);
        lcd.print(':');
        lcd.setCursor(3, 0);

    }

}
</code>```

答:
You may need to create a state machine, where the change in the state happens when you receive the 'A' char. So, while you do not receive the 'A' char, your state machine keeps in the busy-wait (while (keypressed != 'A') ).

Once the 'A' is received, you then are going to check the next 3 chars received, and verify if they match what you expect ('1', '2', '3').

If you receive it in any different order, then the loop breaks, and the verification fails at the statement if (i == 4). In other words, as soon as you receive a number that you do not expect, the loop breaks and the verification fails.

Here is what you could add in your loop() code:

void loop() {
  char expected[3] = { '1', '2', '3' };
  int i = 0;
  char keypressed = myKeypad.getKey();
  while (keypressed != 'A')
    ;

  while (i < 4) {
    for (i = 0; i < 4; i++) {
      if (keypressed != expected[i])
        break;
  }

  if (i == 4)
    lcd.print("Hi:1,2,3");
}
```

Body:
I want an Arduino code to give the output in following format on LCD display

If the user click 'A', 1, 2, 3 from the keypad, LCD should display Hi:1,2,3,

This is what I have tried but I cannot figure out a way to build the code as I am a beginner in arduino

#include <Keypad.h>
#include <LiquidCrystal.h>

const byte numRows= 4;
const byte numCols= 4;

char keymap[numRows][numCols]= {
    {'1', '2', '3', 'A'},
    {'4', '5', '6', 'B'},
    {'7', '8', '9', 'C'},
    {'*', '0', '#', 'D'}
};

byte rowPins[numRows] = {9,8,7,6};      // Pin Assign
byte colPins[numCols] = {5,4,3,2};      // Pin Assign

Keypad myKeypad= Keypad(makeKeymap(keymap), rowPins, colPins, numRows, numCols);

// LCD
//                RS E  D4 D5 D6 D7
LiquidCrystal lcd(A0,A1,A2,A3,A4,A5);   // Pin Assign

void setup()
{
    lcd.begin(16, 2);
    lcd.clear();
    lcd.print("PUSH ANY KEY! ");
    lcd.cursor();
    lcd.blink();
}

void loop(){
    char keypressed = myKeypad.getKey();
    if (keypressed != NO_KEY){
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print(keypressed);
        lcd.print(':');
        lcd.setCursor(3, 0);

    }

}


问:
npm install: Verfication failed while extracting
READ BEFORE ANSWER: I've already solved this issue. It was a caching issue on the npm servers. Everything works fine after switching to GitHub packages. I've already accepted my own answer.

I have a project, which I want to deploy to elastic beanstalk but sometimes the deploy fails on the npm install script with the following message:

npm ERR! code EINTEGRITY
npm ERR! Verification failed while extracting @my-package@^1.2.0:
npm ERR! Verification failed while extracting @my-package@^1.2.0:
npm ERR! sha512-lQ...HA== integrity checksum failed when using sha512: wanted sha512-lQ...HA== but got sha512-nH...ow==. (4835509 bytes)
```
<p>It fails even on packages which are severel weeks old.</p>
<p>I’ve tried:</p>
<ul>
<li><p><code>npm cache clean --force</code></p>
</li>
<li><p><code>npm cache verify</code></p>
</li>
<li><p><code>node_modules</code> is in <code>.npmignore</code></p>
</li>
<li><p><code>package-lock.json</code> is in <code>.npmignore</code></p>
</li>
<li><p>Writing a mail to support@npmjs.com, but they replying always with some helpless default replies without any solution or intention to help.</p>
</li>
</ul>
<p>It fails even on new elastic beanstalk instances.</p>
<p>I have no idea how to solve this problem.</p>
<p><strong>EDIT:</strong> I've also tried to delete the npm cache while preinstall script, but it doesn't work either.</p>
<p><strong>EDIT2:</strong> My repo has no <code>package-lock.json</code>.</p>
<p><strong>EDIT3:</strong> My <code>.npmrc</code> file has the following content</p>
```      //registry.npmjs.org/:_authToken=${NPM_TOKEN}
      unsafe-perm=true
      package-lock=false
      strict-ssl=false
```

EDIT4: I think it wasn't clear: It's a private package on the official npm registry. And it doesn't fail always. The current publish process includes several attempts to deploy on aws instance so long as it's succeed.

答:
Not exactly your case, but for those who run into the "integrity checksum failed" error the following might help. But first make sure you understand what's going on. npm tells you that the checksum from https://registry.npm.org doesn't match the one from package-lock.json. Either it changed in the registry, or...

Consider a line from the output:

```<code>npm ERR!
  sha512-lQ...HA==
integrity checksum failed when using sha512: wanted
  sha512-lQ...HA==
but got
  sha512-nH...ow==
. (4835509 bytes)
</code>```

Find the package in package-lock.json by the first two integrity checksums (sha512-lQ...HA==), and put the third one (sha512-nH...ow==) into its "integrity" field.

More on it here.

Body:
READ BEFORE ANSWER: I've already solved this issue. It was a caching issue on the npm servers. Everything works fine after switching to GitHub packages. I've already accepted my own answer.

I have a project, which I want to deploy to elastic beanstalk but sometimes the deploy fails on the npm install script with the following message:

npm ERR! code EINTEGRITY
npm ERR! Verification failed while extracting @my-package@^1.2.0:
npm ERR! Verification failed while extracting @my-package@^1.2.0:
npm ERR! sha512-lQ...HA== integrity checksum failed when using sha512: wanted sha512-lQ...HA== but got sha512-nH...ow==. (4835509 bytes)

It fails even on packages which are severel weeks old.

I’ve tried:

npm cache clean --force

npm cache verify

node_modules is in .npmignore

package-lock.json is in .npmignore

Writing a mail to support@npmjs.com, but they replying always with some helpless default replies without any solution or intention to help.

It fails even on new elastic beanstalk instances.

I have no idea how to solve this problem.

EDIT: I've also tried to delete the npm cache while preinstall script, but it doesn't work either.

EDIT2: My repo has no package-lock.json.

EDIT3: My .npmrc file has the following content

      //registry.npmjs.org/:_authToken=${NPM_TOKEN}
      unsafe-perm=true
      package-lock=false
      strict-ssl=false

EDIT4: I think it wasn't clear: It's a private package on the official npm registry. And it doesn't fail always. The current publish process includes several attempts to deploy on aws instance so long as it's succeed.

Body:
Not exactly your case, but for those who run into the "integrity checksum failed" error the following might help. But first make sure you understand what's going on. npm tells you that the checksum from https://registry.npm.org doesn't match the one from package-lock.json. Either it changed in the registry, or...

Consider a line from the output:

npm ERR!
  sha512-lQ...HA==
integrity checksum failed when using sha512: wanted
  sha512-lQ...HA==
but got
  sha512-nH...ow==
. (4835509 bytes)

Find the package in package-lock.json by the first two integrity checksums (sha512-lQ...HA==), and put the third one (sha512-nH...ow==) into its "integrity" field.

More on it here.


问:
After ItemClickListener call methot
I need to call the createRandomList() method at the end of gridView.setOnItemClickListener,
but when I make this gridView, the imageList doesn't update.

If I call it in textTT.setOnClickListener it works. But I need it to work after gridView.setOnItemClickListener.

I mean that after gridView.setOnItemClickListener, the method createRandomList() should automatically be called again.

```<code>public class FragmentTrainingTest extends Fragment {

    Context context;
    TextView textTT;
    ArrayList<kayitSinifi> kelimeList = new ArrayList<>();
    int rand,position;
    Random r = new Random();
    MediaPlayer noVoice,yesVoice;
    ArrayList<kayitSinifi> randomList = new ArrayList<>();
    ArrayList<Integer> imageList = new ArrayList<>();
    gridAdapter adapter;
    boolean ilkKez = true;

    @SuppressLint("ClickableViewAccessibility")
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_training_test, container, false);
        noVoice = MediaPlayer.create(context,R.raw.glitchinthematrix);
        yesVoice= MediaPlayer.create(context,R.raw.fillingyourinbox);
        final GridView gridView = inflate.findViewById(R.id.gridView);
        textTT= inflate.findViewById(R.id.txtTrainingTest);
        createRandomList();ilkKez = false;
        adapter = new gridAdapter(context,randomList,imageList);
        gridView.setAdapter(adapter);
        textTT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                createRandomList(); gridView.setAdapter(adapter);
            }
        });

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.i("tester","Item clicked");
                 if(position == rand){
                     yesVoice.start();
                     imageList.set(rand,R.drawable.ic_check_black_24dp);
                 } else {
                     noVoice.start();
                     imageList.set(position,R.drawable.ic_close_black_24dp);
                     imageList.set(rand,R.drawable.ic_check_black_24dp);
                 }
                gridView.setAdapter(adapter);
                //  createRandomList(); // please focus here
          }
        });

       return inflate;
    } //end of onCreateView

    private void createRandomList() {

        ArrayList<Integer> randomNumber = new ArrayList<>();
          // if (ilkKez) {} else try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
        for (int i=0; randomList.size()>0;i++) randomList.remove(0);
        for (int i=0; imageList.size()>0;i++) imageList.remove(0);
        for (int i = 0; i< 6; i++) {
            do {
                rand = r.nextInt(kelimeList.size());
            }
            while(randomNumber.contains(rand));
            randomNumber.add(rand);
            randomList.add(kelimeList.get(rand));
            imageList.add(R.drawable.ic_fingerprint_black_24dp);
        }
        rand = r.nextInt(5); // 6 sayi belirlendi bu ise esas oglan
        textTT.setText(randomList.get(rand).anaDil);
        textTT.setBackgroundColor(Color.parseColor("#4CAF50"));
    }

    @Override
    public void onAttach(Activity activity) {
        // TODO Auto-generated method stub
        super.onAttach(activity);
        context=activity;
        dbaseHelper db = new dbaseHelper(context);
        kelimeList=db.dbList2();
    }

}
</code>```

答:
Place createRandomList() in front of gridView.setAdapter(adapter);

```<code>gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Log.i("tester","Item clicked");
             if(position == rand){
                 yesVoice.start();
                 imageList.set(rand,R.drawable.ic_check_black_24dp);
             } else {
                 noVoice.start();
                 imageList.set(position,R.drawable.ic_close_black_24dp);
                 imageList.set(rand,R.drawable.ic_check_black_24dp);
             }
            createRandomList();
            gridView.setAdapter(adapter);
      }
    });
</code>```

Title: After ItemClickListener call methot

Body:
I need to call the createRandomList() method at the end of gridView.setOnItemClickListener,
but when I make this gridView, the imageList doesn't update.

If I call it in textTT.setOnClickListener it works. But I need it to work after gridView.setOnItemClickListener.

I mean that after gridView.setOnItemClickListener, the method createRandomList() should automatically be called again.

public class FragmentTrainingTest extends Fragment {

    Context context;
    TextView textTT;
    ArrayList<kayitSinifi> kelimeList = new ArrayList<>();
    int rand,position;
    Random r = new Random();
    MediaPlayer noVoice,yesVoice;
    ArrayList<kayitSinifi> randomList = new ArrayList<>();
    ArrayList<Integer> imageList = new ArrayList<>();
    gridAdapter adapter;
    boolean ilkKez = true;

    @SuppressLint("ClickableViewAccessibility")
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_training_test, container, false);
        noVoice = MediaPlayer.create(context,R.raw.glitchinthematrix);
        yesVoice= MediaPlayer.create(context,R.raw.fillingyourinbox);
        final GridView gridView = inflate.findViewById(R.id.gridView);
        textTT= inflate.findViewById(R.id.txtTrainingTest);
        createRandomList();ilkKez = false;
        adapter = new gridAdapter(context,randomList,imageList);
        gridView.setAdapter(adapter);
        textTT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                createRandomList(); gridView.setAdapter(adapter);
            }
        });

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.i("tester","Item clicked");
                 if(position == rand){
                     yesVoice.start();
                     imageList.set(rand,R.drawable.ic_check_black_24dp);
                 } else {
                     noVoice.start();
                     imageList.set(position,R.drawable.ic_close_black_24dp);
                     imageList.set(rand,R.drawable.ic_check_black_24dp);
                 }
                gridView.setAdapter(adapter);
                //  createRandomList(); // please focus here
          }
        });

       return inflate;
    } //end of onCreateView

    private void createRandomList() {

        ArrayList<Integer> randomNumber = new ArrayList<>();
          // if (ilkKez) {} else try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
        for (int i=0; randomList.size()>0;i++) randomList.remove(0);
        for (int i=0; imageList.size()>0;i++) imageList.remove(0);
        for (int i = 0; i< 6; i++) {
            do {
                rand = r.nextInt(kelimeList.size());
            }
            while(randomNumber.contains(rand));
            randomNumber.add(rand);
            randomList.add(kelimeList.get(rand));
            imageList.add(R.drawable.ic_fingerprint_black_24dp);
        }
        rand = r.nextInt(5); // 6 sayi belirlendi bu ise esas oglan
        textTT.setText(randomList.get(rand).anaDil);
        textTT.setBackgroundColor(Color.parseColor("#4CAF50"));
    }

    @Override
    public void onAttach(Activity activity) {
        // TODO Auto-generated method stub
        super.onAttach(activity);
        context=activity;
        dbaseHelper db = new dbaseHelper(context);
        kelimeList=db.dbList2();
    }

}

Body:
Place createRandomList() in front of gridView.setAdapter(adapter);

gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Log.i("tester","Item clicked");
             if(position == rand){
                 yesVoice.start();
                 imageList.set(rand,R.drawable.ic_check_black_24dp);
             } else {
                 noVoice.start();
                 imageList.set(position,R.drawable.ic_close_black_24dp);
                 imageList.set(rand,R.drawable.ic_check_black_24dp);
             }
            createRandomList();
            gridView.setAdapter(adapter);
      }
    });


问:
g++ warning when using optional 'struct' keyword
If I write this program:

```<code>#include <iostream>

namespace foo {
    struct bar {
        int x;
    };
}

int main (void) {
    struct foo::bar *a = new struct foo::bar;
    delete a;
    return 0;
}
</code>```

and compile it with:

```<code>g++ main.cxx -Wall -Wextra
</code>```

It gives me this warning:

```<code>main.cxx: In function ‘int main()’:
main.cxx:10:39: warning: declaration ‘struct foo::bar’ does not declare anything [enabled by default]
</code>```

However, if I take out the struct keyword after the new keyword:

```<code>#include <iostream>

namespace foo {
    struct bar {
        int x;
    };
}

int main (void) {
    struct foo::bar *a = new foo::bar;
    delete a;
    return 0;
}
</code>```

and compile it the same way, g++ outputs no warnings.  Why does g++ output that warning if I use the struct keyword?

答:
Note:

```<code>   struct foo::bar *a = new struct foo::bar;
// ^^^^^^ (1)
                        //  ^^^^^^ (2)
</code>```

Not needed in C++

Putting struct here is a hangover from C and is no longer needed in C++

As all the types are all in the same namespace.

While in C structs had there own namespace separate from other types.

It is allowed to retain backward compatibility with C.

struct here looks like it is forward declaring something.

In C++ the above is written as:

```<code>   foo::bar* a = new foo::bar;
</code>```

// or preferably

```<code>   foo::bar* a = new foo::bar(); // This makes a difference if you don't define
                                 // a default constructor.
</code>```

From David (Below)

Important enough I think it needs to be in the answer rather than the comments:

```<code>namespace foo
{
    struct bar {};
    void bar() {}
}

int main()
{
    struct foo::bar* p = new struct foo::bar;
    // Needed here because the compiler can't tell the difference between
    // a struct and a function otherwise
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If I write this program:

#include <iostream>

namespace foo {
    struct bar {
        int x;
    };
}

int main (void) {
    struct foo::bar *a = new struct foo::bar;
    delete a;
    return 0;
}

and compile it with:

g++ main.cxx -Wall -Wextra

It gives me this warning:

main.cxx: In function ‘int main()’:
main.cxx:10:39: warning: declaration ‘struct foo::bar’ does not declare anything [enabled by default]

However, if I take out the struct keyword after the new keyword:

#include <iostream>

namespace foo {
    struct bar {
        int x;
    };
}

int main (void) {
    struct foo::bar *a = new foo::bar;
    delete a;
    return 0;
}

and compile it the same way, g++ outputs no warnings.  Why does g++ output that warning if I use the struct keyword?

Body:
Note:

   struct foo::bar *a = new struct foo::bar;
// ^^^^^^ (1)
                        //  ^^^^^^ (2)

Not needed in C++

Putting struct here is a hangover from C and is no longer needed in C++

As all the types are all in the same namespace.

While in C structs had there own namespace separate from other types.

It is allowed to retain backward compatibility with C.

struct here looks like it is forward declaring something.

In C++ the above is written as:

   foo::bar* a = new foo::bar;

// or preferably

   foo::bar* a = new foo::bar(); // This makes a difference if you don't define
                                 // a default constructor.

From David (Below)

Important enough I think it needs to be in the answer rather than the comments:

namespace foo
{
    struct bar {};
    void bar() {}
}

int main()
{
    struct foo::bar* p = new struct foo::bar;
    // Needed here because the compiler can't tell the difference between
    // a struct and a function otherwise
}


问:
Persistent volume with Heroku Dynos
My Java application is built around an embedded database which stores db data directly to disk. I understand that Heroku by default is built on an ephemeral filesystem and anything stored in it will be removed when dynos restart or just don't stick.

What is the workaround to make such an application available and deployed in Heroku?

答:
I understand that Heroku by default is built on an ephemeral filesystem

This isn't "by default". It's fundamental to Heroku's architecture and cannot be changed. Heroku is designed to be trivially horizontally scalable, and part of that design is that state should exist apart from any one dyno. Dynos are disposable.

What is the workaround to make such an application available and deployed in Heroku?

As far as I know, none exists. Either change how you save your data or choose another host.

(You might be able to mount a shared persistent filesystem on your dynos, but that's awkward and undermines Heroku's architecture. I don't advise it. None of Heroku's offical addons provides a persistent filesystem, and a quick search finds a few blog posts outlining attempts but I don't see any successes.)

Title: Persistent volume with Heroku Dynos


问:
What's the best practice to update Redux state in components that needs the same values?
I have some components that can render together in a page or separately, but they need the same state (order info), which is an object with all the order info. Each component uses the data it needs from this state.

I'm using redux to manage the state, so when I update the state in one component, all other components can read this state change and update as well.

The problem is that this state comes from the API and its initial state is an undefined object:

```<code>const initialState = {
    orderInfo: undefined,
};
</code>```

This is because it will only have its state when the customer navigates to explore an order. So whenever the customer navigates to /dashboard/orders/:id/, the component needs to fetch the data from the API.

What I initially thought was to check if the state is undefined or if it's from a different order id. If so, dispatch the action to fetch from the API:

```<code>useEffect(() => {
    // check if orderState contains order info and it's the same order
    if (!orderState.orderInfo || orderState.orderInfo._id !== id) {
        dispatch(getOrderInfo(id));
    }
    //eslint-disable-next-line
}, []);
</code>```

This works, but I have to implement this check on every component, because they can render alone. The problem is that when there are more than 1 component in the page, all of them dispatch the action to fetch the data from the API in the same time.

What's the best way to make only one component to dispatch the action?

Thanks in advance!

答:
I think there are two ways that might be good for you:

1: Custom Hooks

You can have a hook that handles that useEffect, and dispatch logic, and which also consumes the selector of the data in the store. Something like:

```<code>function useOrder(foo, bar) {
  const dispatch = useDispatch()
  const order = useSelector(selectOrder)
  useEffect(() => {
    if (foo) {
      dispatch(bar)
    }
  }, [foo, bar])

 return order
}
</code>```

And then just consume it in your components by:

```<code>const order = useOrder(foo, bar)
</code>```

2.- Parent container.

If all components are present at the same time, there must probably be a global container that contains them all. You could just handle there your dispatch logic and pass down the property.
For passing down props you also got 2 options:

Explicit passing by prop (so just pass the prop to each nested component that needs it)

Using context

```<code>const ctx = createContext({...})

<Provider context={ctx}>
 // Your component hierarchy
</Provider>
</code>```

And then inside each of the components use the useContext hook.

*Edit:
In the first hook example, i passed the props directly to the hook, but for your example you might take that props from another selector as well.

Body:
I have some components that can render together in a page or separately, but they need the same state (order info), which is an object with all the order info. Each component uses the data it needs from this state.

I'm using redux to manage the state, so when I update the state in one component, all other components can read this state change and update as well.

The problem is that this state comes from the API and its initial state is an undefined object:

const initialState = {
    orderInfo: undefined,
};

This is because it will only have its state when the customer navigates to explore an order. So whenever the customer navigates to /dashboard/orders/:id/, the component needs to fetch the data from the API.

What I initially thought was to check if the state is undefined or if it's from a different order id. If so, dispatch the action to fetch from the API:

useEffect(() => {
    // check if orderState contains order info and it's the same order
    if (!orderState.orderInfo || orderState.orderInfo._id !== id) {
        dispatch(getOrderInfo(id));
    }
    //eslint-disable-next-line
}, []);

This works, but I have to implement this check on every component, because they can render alone. The problem is that when there are more than 1 component in the page, all of them dispatch the action to fetch the data from the API in the same time.

What's the best way to make only one component to dispatch the action?

Thanks in advance!

Body:
I think there are two ways that might be good for you:

1: Custom Hooks

You can have a hook that handles that useEffect, and dispatch logic, and which also consumes the selector of the data in the store. Something like:

function useOrder(foo, bar) {
  const dispatch = useDispatch()
  const order = useSelector(selectOrder)
  useEffect(() => {
    if (foo) {
      dispatch(bar)
    }
  }, [foo, bar])

 return order
}

And then just consume it in your components by:

const order = useOrder(foo, bar)

2.- Parent container.

If all components are present at the same time, there must probably be a global container that contains them all. You could just handle there your dispatch logic and pass down the property.
For passing down props you also got 2 options:

Explicit passing by prop (so just pass the prop to each nested component that needs it)

Using context

const ctx = createContext({...})

<Provider context={ctx}>
 // Your component hierarchy
</Provider>

And then inside each of the components use the useContext hook.

*Edit:
In the first hook example, i passed the props directly to the hook, but for your example you might take that props from another selector as well.


问:
find text and change format of text/range to bold or italic within table cells in powerpoint
Please help modify the code below to run within cells of a table in PowerPoint.

Column 1

Row 1 Sample

Row 2 The quick brown (bold) fox (/bold) jumps (bold) over (/bold) the lazy dog.

Row 2 (i) Next line: The quick brown fox jumps over the lazy dog. (/i)

Row 3 Result

Row 4 The quick brown fox jumps over the lazy dog.

Row 4 Next line: The quick brown fox jumps over the lazy dog.

Code:

```<code>Sub Htmlize()
    Dim oSld As Slide
    Dim oShp As Shape
    Dim oTxtRng As TextRange
    Dim openTag As TextRange
    Dim closeTag As TextRange
    Dim endRange As Long
    Dim startRange As Long

    For Each oSld In ActivePresentation.Slides
        For Each oShp In oSld.Shapes
            If oShp.HasTextFrame Then
                Set oTxtRng = oShp.TextFrame.TextRange
                Set openTag = oTxtRng.Find(FindWhat:="<i>", _
                    MatchCase:=False)
                Do While Not (openTag Is Nothing)
                    Set closeTag = oTxtRng.Find(FindWhat:="</i>", _
                        MatchCase:=False)
                    If closeTag Is Nothing Then
                        endRange = oTxtRng.Length
                    Else
                        endRange = closeTag.Start - 1
                        oTxtRng.Characters(closeTag.Start, _
                            closeTag.Length).Delete
                    End If
                    startRange = openTag.Start
                    oTxtRng.Characters(startRange, _
                        endRange - startRange + 1) _
                        .Font.Italic = True
                    oTxtRng.Characters(openTag.Start, _
                        openTag.Length).Delete
                    Set openTag = oTxtRng.Find(FindWhat:="<i>", _
                        MatchCase:=False)
                Loop
            End If
        Next oShp
    Next oSld

    For Each oSld In ActivePresentation.Slides
        For Each oShp In oSld.Shapes
            If oShp.HasTextFrame Then
                Set oTxtRng = oShp.TextFrame.TextRange
                Set openTag = oTxtRng.Find(FindWhat:="<bold>", _
                    MatchCase:=False)
                Do While Not (openTag Is Nothing)
                    Set closeTag = oTxtRng.Find(FindWhat:="</bold>", _
                        MatchCase:=False)
                    If closeTag Is Nothing Then
                        endRange = oTxtRng.Length
                    Else
                        endRange = closeTag.Start - 1
                        oTxtRng.Characters(closeTag.Start, _
                            closeTag.Length).Delete
                    End If
                    startRange = openTag.Start
                    oTxtRng.Characters(startRange, _
                        endRange - startRange + 1) _
                        .Font.Italic = True
                    oTxtRng.Characters(openTag.Start, _
                        openTag.Length).Delete
                    Set openTag = oTxtRng.Find(FindWhat:="<bold>", _
                        MatchCase:=False)
                Loop
            End If
        Next oShp
    Next oSld

End Sub
</code>```

答:
As I said in my comment, there are many topics in there -- This code should get you started. I put everything in the comments</p>

```<code>Sub Htmlize()
    Dim oSld As Slide
    Dim oShp As Shape
    Dim oTxtRng As TextRange
    Dim openTag As TextRange
    Dim closeTag As TextRange
    Dim endRange As Long
    Dim startRange As Long

    'You have to work with tables
    'You speak only of one Column, so I assume 1 Column
    Dim oTbl As Table
    Dim lRow As Long

    For Each oSld In ActivePresentation.Slides

        For Each oShp In oSld.Shapes

            'If oShp.HasTextFrame Then
            'You have to use Tables instead
            If oShp.HasTable Then
                Set oTbl = oShp.Table
                'with this you set the table

                'Now you have to iterate through the Rows (and of course through columns if that is necessary. I will assume here that it is only 1 column)
                For lRow = 1 To oTbl.Rows.Count

                    'Set oTxtRng = oShp.TextFrame.TextRange
                    'This has to be changed now to the content of the cell:
                    Set oTxtRng = oTbl.Cell(lRow, 1).Shape.TextFrame.TextRange

                    'Here is your original code
                    'I changed the < to ( so that it works
                    'This code will do the Italic work for you -- now you have to adapt it for bold

                    Set openTag = oTxtRng.Find(FindWhat:="(i)", _
                        MatchCase:=False)
                    Do While Not (openTag Is Nothing)
                        Set closeTag = oTxtRng.Find(FindWhat:="(/i)", _
                            MatchCase:=False)
                        If closeTag Is Nothing Then
                            endRange = oTxtRng.Length
                        Else
                            endRange = closeTag.Start - 1
                            oTxtRng.Characters(closeTag.Start, _
                                closeTag.Length).Delete
                        End If
                        startRange = openTag.Start
                        oTxtRng.Characters(startRange, _
                            endRange - startRange + 1) _
                            .Font.Italic = True
                        oTxtRng.Characters(openTag.Start, _
                            openTag.Length).Delete
                        Set openTag = oTxtRng.Find(FindWhat:="(i)", _
                            MatchCase:=False)
                    Loop

                    'Now you go through the rows
                Next 'lRow

            End If
        Next oShp

    Next oSld

    'I Don't know why you go through this twice -- makes the work just longer. You could do this in one sweep while you are going throught the tables already.
    'But I guess you know why you do it that way

    'You have to adapt the upper part for this one here too

    For Each oSld In ActivePresentation.Slides

        For Each oShp In oSld.Shapes
            If oShp.HasTextFrame Then
                Set oTxtRng = oShp.TextFrame.TextRange
                Set openTag = oTxtRng.Find(FindWhat:="(bold)", _
                    MatchCase:=False)
                Do While Not (openTag Is Nothing)
                    Set closeTag = oTxtRng.Find(FindWhat:="(/bold)", _
                        MatchCase:=False)
                    If closeTag Is Nothing Then
                        endRange = oTxtRng.Length
                    Else
                        endRange = closeTag.Start - 1
                        oTxtRng.Characters(closeTag.Start, _
                            closeTag.Length).Delete
                    End If
                    startRange = openTag.Start
                    oTxtRng.Characters(startRange, _
                        endRange - startRange + 1) _
                        .Font.Bold = True
                    oTxtRng.Characters(openTag.Start, _
                        openTag.Length).Delete
                    Set openTag = oTxtRng.Find(FindWhat:="(bold)", _
                        MatchCase:=False)
                Loop
            End If
        Next oShp

    Next oSld

End Sub
</code>```

Body:
Please help modify the code below to run within cells of a table in PowerPoint.

Column 1

Row 1 Sample

Row 2 The quick brown (bold) fox (/bold) jumps (bold) over (/bold) the lazy dog.

Row 2 (i) Next line: The quick brown fox jumps over the lazy dog. (/i)

Row 3 Result

Row 4 The quick brown fox jumps over the lazy dog.

Row 4 Next line: The quick brown fox jumps over the lazy dog.

Code:

Sub Htmlize()
    Dim oSld As Slide
    Dim oShp As Shape
    Dim oTxtRng As TextRange
    Dim openTag As TextRange
    Dim closeTag As TextRange
    Dim endRange As Long
    Dim startRange As Long

    For Each oSld In ActivePresentation.Slides
        For Each oShp In oSld.Shapes
            If oShp.HasTextFrame Then
                Set oTxtRng = oShp.TextFrame.TextRange
                Set openTag = oTxtRng.Find(FindWhat:="", _
                    MatchCase:=False)
                Do While Not (openTag Is Nothing)
                    Set closeTag = oTxtRng.Find(FindWhat:="", _
                        MatchCase:=False)
                    If closeTag Is Nothing Then
                        endRange = oTxtRng.Length
                    Else
                        endRange = closeTag.Start - 1
                        oTxtRng.Characters(closeTag.Start, _
                            closeTag.Length).Delete
                    End If
                    startRange = openTag.Start
                    oTxtRng.Characters(startRange, _
                        endRange - startRange + 1) _
                        .Font.Italic = True
                    oTxtRng.Characters(openTag.Start, _
                        openTag.Length).Delete
                    Set openTag = oTxtRng.Find(FindWhat:="", _
                        MatchCase:=False)
                Loop
            End If
        Next oShp
    Next oSld

    For Each oSld In ActivePresentation.Slides
        For Each oShp In oSld.Shapes
            If oShp.HasTextFrame Then
                Set oTxtRng = oShp.TextFrame.TextRange
                Set openTag = oTxtRng.Find(FindWhat:="<bold>", _
                    MatchCase:=False)
                Do While Not (openTag Is Nothing)
                    Set closeTag = oTxtRng.Find(FindWhat:="</bold>", _
                        MatchCase:=False)
                    If closeTag Is Nothing Then
                        endRange = oTxtRng.Length
                    Else
                        endRange = closeTag.Start - 1
                        oTxtRng.Characters(closeTag.Start, _
                            closeTag.Length).Delete
                    End If
                    startRange = openTag.Start
                    oTxtRng.Characters(startRange, _
                        endRange - startRange + 1) _
                        .Font.Italic = True
                    oTxtRng.Characters(openTag.Start, _
                        openTag.Length).Delete
                    Set openTag = oTxtRng.Find(FindWhat:="<bold>", _
                        MatchCase:=False)
                Loop
            End If
        Next oShp
    Next oSld

End Sub

Body:
As I said in my comment, there are many topics in there -- This code should get you started. I put everything in the comments

Sub Htmlize()
    Dim oSld As Slide
    Dim oShp As Shape
    Dim oTxtRng As TextRange
    Dim openTag As TextRange
    Dim closeTag As TextRange
    Dim endRange As Long
    Dim startRange As Long

    'You have to work with tables
    'You speak only of one Column, so I assume 1 Column
    Dim oTbl As Table
    Dim lRow As Long

    For Each oSld In ActivePresentation.Slides

        For Each oShp In oSld.Shapes

            'If oShp.HasTextFrame Then
            'You have to use Tables instead
            If oShp.HasTable Then
                Set oTbl = oShp.Table
                'with this you set the table

                'Now you have to iterate through the Rows (and of course through columns if that is necessary. I will assume here that it is only 1 column)
                For lRow = 1 To oTbl.Rows.Count

                    'Set oTxtRng = oShp.TextFrame.TextRange
                    'This has to be changed now to the content of the cell:
                    Set oTxtRng = oTbl.Cell(lRow, 1).Shape.TextFrame.TextRange

                    'Here is your original code
                    'I changed the < to ( so that it works
                    'This code will do the Italic work for you -- now you have to adapt it for bold

                    Set openTag = oTxtRng.Find(FindWhat:="(i)", _
                        MatchCase:=False)
                    Do While Not (openTag Is Nothing)
                        Set closeTag = oTxtRng.Find(FindWhat:="(/i)", _
                            MatchCase:=False)
                        If closeTag Is Nothing Then
                            endRange = oTxtRng.Length
                        Else
                            endRange = closeTag.Start - 1
                            oTxtRng.Characters(closeTag.Start, _
                                closeTag.Length).Delete
                        End If
                        startRange = openTag.Start
                        oTxtRng.Characters(startRange, _
                            endRange - startRange + 1) _
                            .Font.Italic = True
                        oTxtRng.Characters(openTag.Start, _
                            openTag.Length).Delete
                        Set openTag = oTxtRng.Find(FindWhat:="(i)", _
                            MatchCase:=False)
                    Loop

                    'Now you go through the rows
                Next 'lRow

            End If
        Next oShp

    Next oSld

    'I Don't know why you go through this twice -- makes the work just longer. You could do this in one sweep while you are going throught the tables already.
    'But I guess you know why you do it that way

    'You have to adapt the upper part for this one here too

    For Each oSld In ActivePresentation.Slides

        For Each oShp In oSld.Shapes
            If oShp.HasTextFrame Then
                Set oTxtRng = oShp.TextFrame.TextRange
                Set openTag = oTxtRng.Find(FindWhat:="(bold)", _
                    MatchCase:=False)
                Do While Not (openTag Is Nothing)
                    Set closeTag = oTxtRng.Find(FindWhat:="(/bold)", _
                        MatchCase:=False)
                    If closeTag Is Nothing Then
                        endRange = oTxtRng.Length
                    Else
                        endRange = closeTag.Start - 1
                        oTxtRng.Characters(closeTag.Start, _
                            closeTag.Length).Delete
                    End If
                    startRange = openTag.Start
                    oTxtRng.Characters(startRange, _
                        endRange - startRange + 1) _
                        .Font.Bold = True
                    oTxtRng.Characters(openTag.Start, _
                        openTag.Length).Delete
                    Set openTag = oTxtRng.Find(FindWhat:="(bold)", _
                        MatchCase:=False)
                Loop
            End If
        Next oShp

    Next oSld

End Sub


问:
readLine for a variable number of Ints
Is there a way to code something like this in kotlin for a variable number of ints? For example the input should be "1 3 5" or "3 2 2 7" (String with space-separated Ints). And I am not allowed to use java librarys.

```<code>val (x, y) = readLine()!!.split(' ').map(String::toInt)
println(x+y)
</code>```

Thanks in advance.

答:
Found a solution for my problem:</p>

```<code>var list: List<Int> = readLine()!!.split(' ').map(String::toInt)
for(m in  list){
    println(m)
}
</code>```

Title: readLine for a variable number of Ints

Body:
Is there a way to code something like this in kotlin for a variable number of ints? For example the input should be "1 3 5" or "3 2 2 7" (String with space-separated Ints). And I am not allowed to use java librarys.

val (x, y) = readLine()!!.split(' ').map(String::toInt)
println(x+y)

Thanks in advance.

Body:
Found a solution for my problem:

var list: List<Int> = readLine()!!.split(' ').map(String::toInt)
for(m in  list){
    println(m)
}


问:
How to get rid of extra-space (padding) between piechart and its border in JavaFX / TornadoFX?
I have a simple piechart without name, labels, legend. I need only a circle itself. But I can't get rid of that padding between borders and content. I've tried these all and received no result (TornadoFX CSS):

```<code>diagram {
  padding = box(0.px)
  labelPadding = box(0.px)

  borderImageInsets += box(0.px)
  borderInsets += box(0.px)
  backgroundInsets += box(0.px)

  maxWidth = 25.px
  maxHeight = 25.px
  labelLineLength = 0.px
  borderColor += box(Color.GREEN)
}
</code>```

I want to get rid of this extra-space between a circle and green borders. Does anybody know any Java / CSS / TornadoFX solutions/options here ?

答:
You can use a negative value for e. g. padding. Please have a look at this small example (JavaFX):

```<code>package sample;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.chart.PieChart;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage stage) {

        VBox vBox = new VBox();
        ObservableList<PieChart.Data> pieChartData =
                FXCollections.observableArrayList(
                        new PieChart.Data("", 75),
                        new PieChart.Data("", 25));
        final PieChart chart = new PieChart(pieChartData);
        chart.setLegendVisible(false);

        // Negative value for padding:
        chart.setStyle("-fx-padding: -35; -fx-border-color: green; -fx-border-width: 3;");

        vBox.getChildren().addAll(chart);
        stage.setScene(new Scene(vBox));
        stage.show();

        //chart.setMaxWidth(400d); // careful
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

You can also quickly set a maximum width for the chart to make the green box a square but be careful please, it could mess with the overall layout:

Body:
I have a simple piechart without name, labels, legend. I need only a circle itself. But I can't get rid of that padding between borders and content. I've tried these all and received no result (TornadoFX CSS):

diagram {
  padding = box(0.px)
  labelPadding = box(0.px)

  borderImageInsets += box(0.px)
  borderInsets += box(0.px)
  backgroundInsets += box(0.px)

  maxWidth = 25.px
  maxHeight = 25.px
  labelLineLength = 0.px
  borderColor += box(Color.GREEN)
}

I want to get rid of this extra-space between a circle and green borders. Does anybody know any Java / CSS / TornadoFX solutions/options here ?

Body:
You can use a negative value for e. g. padding. Please have a look at this small example (JavaFX):

package sample;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.chart.PieChart;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage stage) {

        VBox vBox = new VBox();
        ObservableList<PieChart.Data> pieChartData =
                FXCollections.observableArrayList(
                        new PieChart.Data("", 75),
                        new PieChart.Data("", 25));
        final PieChart chart = new PieChart(pieChartData);
        chart.setLegendVisible(false);

        // Negative value for padding:
        chart.setStyle("-fx-padding: -35; -fx-border-color: green; -fx-border-width: 3;");

        vBox.getChildren().addAll(chart);
        stage.setScene(new Scene(vBox));
        stage.show();

        //chart.setMaxWidth(400d); // careful
    }

    public static void main(String[] args) {
        launch(args);
    }
}

You can also quickly set a maximum width for the chart to make the green box a square but be careful please, it could mess with the overall layout:


问:
different mock objects to compare objects in unit tests
I have Equals method that I am trying to tests. this method return true if object passed to is is same as this object.

I test true condition as following.

```<code>        var mocks = new MockRepository();
        var mockActionAlert = mocks.StrictMock<ActionAlert>();
        var mockActionAlert2 = mocks.StrictMock<ActionAlert>();
        bool comparer = mockActionAlert.Equals(mockActionAlert2);
        Assert.Equal(true, comparer);
</code>```

However, how can I get a different mock object to test that equal method returns false.

Thank You,

答:
What you have shown doesn't appear to make any sense at all.

You only have mocks in your test code - no real implementations at all.

Not only are you not testing anything real, but since you are using mocks, your can even decide whether your pretend tests should fail or not.

To do what (I think) you want, simply create an ActionAlert (one from you real code, not a mock of one) and then create a second ActionAlert with properties that should make it equal using your Equals method. Pass the second ActionAlert in and assert that the result is true (Probably best to use Assert.True() since that is more expressive of intent).

Then when testing that the Equals method returns false, write tests with ActionAlerts with properties that make them not equals. No need for mocks at all.

The place where you need mocks is where you have depenendencies in your classes under test that you want to either assert some behaviour on (has a dependence method been called in a certain way) or you want some predifined behaviour from (make a method return a certain value when called).

Body:
I have Equals method that I am trying to tests. this method return true if object passed to is is same as this object.

I test true condition as following.

        var mocks = new MockRepository();
        var mockActionAlert = mocks.StrictMock<ActionAlert>();
        var mockActionAlert2 = mocks.StrictMock<ActionAlert>();
        bool comparer = mockActionAlert.Equals(mockActionAlert2);
        Assert.Equal(true, comparer);

However, how can I get a different mock object to test that equal method returns false.

Thank You,


问:
Problem with Scala Function and Call-by-Name
I am trying to loop a the second parameter (exp) in this function that uses call by name parameters. The first 3 parameters are the index, boolean to stop loop, and increment function. I am getting an output with 10 '()'s when I am trying to loop "hello world" 10 times as seen in the test code. May I get some help with what is wrong here? Thanks</p>

```<code>def forLoop(ival: => Int, f: (Int) => Boolean, g: (Int)=>Int)(exp: => Unit): Unit = {
  if(f(ival)==false)
    return
  else {
    println(exp)
    forLoop(g(ival),f,g)(exp)
  }
}

def f(x: Int): Boolean = { x<10 }
def g(y: Int): Int = { y+1 }
val exp: Unit = "Hello World"
forLoop(0,f,g)("Hello World")
</code>```

答:
I think this meets your requirements.</p>

```<code>def forLoop(ival: => Int, f: =>Int => Boolean, g: =>Int=>Int
           )(exp: => Unit): Unit =
  if (f(ival)) {
    exp
    forLoop(g(ival),f,g)(exp)
  }

def f(x: Int): Boolean = x<10
def g(y: Int): Int = y+1
def exp: Unit = println("Hello World")
forLoop(0,f,g)(exp)
</code>```

Body:
I am trying to loop a the second parameter (exp) in this function that uses call by name parameters. The first 3 parameters are the index, boolean to stop loop, and increment function. I am getting an output with 10 '()'s when I am trying to loop "hello world" 10 times as seen in the test code. May I get some help with what is wrong here? Thanks

def forLoop(ival: => Int, f: (Int) => Boolean, g: (Int)=>Int)(exp: => Unit): Unit = {
  if(f(ival)==false)
    return
  else {
    println(exp)
    forLoop(g(ival),f,g)(exp)
  }
}

def f(x: Int): Boolean = { x<10 }
def g(y: Int): Int = { y+1 }
val exp: Unit = "Hello World"
forLoop(0,f,g)("Hello World")

Body:
I think this meets your requirements.

def forLoop(ival: => Int, f: =>Int => Boolean, g: =>Int=>Int
           )(exp: => Unit): Unit =
  if (f(ival)) {
    exp
    forLoop(g(ival),f,g)(exp)
  }

def f(x: Int): Boolean = x<10
def g(y: Int): Int = y+1
def exp: Unit = println("Hello World")
forLoop(0,f,g)(exp)


问:
Azure Application Insights query to display time frequency
want to Display the time along with milliseconds with the time duration like 1200 ms, 1500 ms on the Dashboard , Is there a way to define these time duration to display on chart?

enter image description here

答:
You'd need to change the units in whatever chart that is however you got it on the dashboard.

If you did that query in workbooks, you'd go into chart settings in that step of the workbook and tell it the y-axis is milliseconds, and it would add the appropriate units for you in the labels.  If you are using metrics, the metrics should already know the units and show the right labels.

You'll need to clarify your question about exactly how / where you created that chart for anyone to help you any further.


问:
How to avoid function calling again and again
I created a function called remove_role which used to remove permission based on the role.  I can able to achieve by calling function again and again. Is there any other way  to avoid calling function repeatedly ?</p>

```<code>    remove_role('author', 'edit_others_pages');
    remove_role('author', 'upload_files');
    remove_role('author', 'manage_categories');```

</code>```

答:
Maybe you can put all the roles in an array like this and call them in a loop. I am not sure what exactly you want to achieve but i think using array will be the easiest.

```<code>$roles = ['role1', 'role2', 'role3'];

foreach ($roles in $role) {
   remove_role('author', $role);
}
</code>```

In fact you could also use a hash like $roles = ['author' => 'role1', 'somethng else' => 'role2'] and loop that through as well.

Body:
I created a function called remove_role which used to remove permission based on the role.  I can able to achieve by calling function again and again. Is there any other way  to avoid calling function repeatedly ?

    remove_role('author', 'edit_others_pages');
    remove_role('author', 'upload_files');
    remove_role('author', 'manage_categories');```

Body:
Maybe you can put all the roles in an array like this and call them in a loop. I am not sure what exactly you want to achieve but i think using array will be the easiest.

$roles = ['role1', 'role2', 'role3'];

foreach ($roles in $role) {
   remove_role('author', $role);
}

In fact you could also use a hash like $roles = ['author' => 'role1', 'somethng else' => 'role2'] and loop that through as well.


问:
onActivityCreated is deprecated, how to properly use LifecycleObserver?
Google deprecate fragment’s onActivityCreated() on Android and recommend to use LifeCycleObserver:

```<code> To get a callback specifically when a Fragment activity's
     * {@link Activity#onCreate(Bundle)} is called, register a
     * {@link androidx.lifecycle.LifecycleObserver} on the Activity's
     * {@link Lifecycle} in {@link #onAttach(Context)}, removing it when it receives the
     * {@link Lifecycle.State#CREATED} callback.
</code>```

So I try to make it in recommended way, but only state I can observe in Logcat is just State: INITIALIZED.

```<code> private lateinit var lifecycleObserver: LifecycleObserver

 override fun onAttach(context: Context) {
    super.onAttach(context)

    hostActivity = context as HostActivity

    lifecycleObserver = object : LifecycleObserver {

        @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
        fun onCreate() {
            Logger.tag("SOME-TAG")d("State: ${lifecycle.currentState}")

            if(lifecycle.currentState.isAtLeast(Lifecycle.State.CREATED)) {
                Logger.tag("SOME-TAG").d("CREATED")
                hostActivity.lifecycle.removeObserver(lifecycleObserver)
            }
        }
    }

    hostActivity.lifecycle.addObserver(lifecycleObserver)
}
</code>```

What is wrong in code above?

UPDATE 1: Looks like I forgot to use hostActivity.lifecycle.currentState and checked fragment's lifecycle instead of Activities lifecycle.

UPDATE 2: Suggested by Google approach not worked for
1 Host activity and 2 fragments when you click back button from one to another, cause onAttach never called, but onActivityCreated called.

答:
As per the changelog here

The onActivityCreated() method is now deprecated. Code touching the
fragment's view should be done in onViewCreated() (which is called
immediately before onActivityCreated()) and other initialization code
should be in onCreate(). To receive a callback specifically when the
activity's onCreate() is complete, a LifeCycleObserver should be
registered on the activity's Lifecycle in onAttach(), and removed once
the onCreate() callback is received.

You can do something like this in your fragment class:

```<code>class MyFragment : Fragment(), LifecycleObserver {
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun onCreated() {
        // ... Your Logic goes here ...
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        activity?.lifecycle?.addObserver(this)
    }

    override fun onDetach() {
        activity?.lifecycle?.removeObserver(this)
        super.onDetach()
    }
}
</code>```

Body:
Google deprecate fragment’s onActivityCreated() on Android and recommend to use LifeCycleObserver:

 To get a callback specifically when a Fragment activity's
     * {@link Activity#onCreate(Bundle)} is called, register a
     * {@link androidx.lifecycle.LifecycleObserver} on the Activity's
     * {@link Lifecycle} in {@link #onAttach(Context)}, removing it when it receives the
     * {@link Lifecycle.State#CREATED} callback.

So I try to make it in recommended way, but only state I can observe in Logcat is just State: INITIALIZED.

 private lateinit var lifecycleObserver: LifecycleObserver

 override fun onAttach(context: Context) {
    super.onAttach(context)

    hostActivity = context as HostActivity

    lifecycleObserver = object : LifecycleObserver {

        @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
        fun onCreate() {
            Logger.tag("SOME-TAG")d("State: ${lifecycle.currentState}")

            if(lifecycle.currentState.isAtLeast(Lifecycle.State.CREATED)) {
                Logger.tag("SOME-TAG").d("CREATED")
                hostActivity.lifecycle.removeObserver(lifecycleObserver)
            }
        }
    }

    hostActivity.lifecycle.addObserver(lifecycleObserver)
}

What is wrong in code above?

UPDATE 1: Looks like I forgot to use hostActivity.lifecycle.currentState and checked fragment's lifecycle instead of Activities lifecycle.

UPDATE 2: Suggested by Google approach not worked for
1 Host activity and 2 fragments when you click back button from one to another, cause onAttach never called, but onActivityCreated called.

Body:
As per the changelog here

The onActivityCreated() method is now deprecated. Code touching the
fragment's view should be done in onViewCreated() (which is called
immediately before onActivityCreated()) and other initialization code
should be in onCreate(). To receive a callback specifically when the
activity's onCreate() is complete, a LifeCycleObserver should be
registered on the activity's Lifecycle in onAttach(), and removed once
the onCreate() callback is received.

You can do something like this in your fragment class:

class MyFragment : Fragment(), LifecycleObserver {
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun onCreated() {
        // ... Your Logic goes here ...
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        activity?.lifecycle?.addObserver(this)
    }

    override fun onDetach() {
        activity?.lifecycle?.removeObserver(this)
        super.onDetach()
    }
}