问:
How to avoid transition between column-organized data processing and row-organized data processing
I'm working on DB2 Blu on with column organized tables.

My dataset is the following :

```<code>Day month year value
------- -------
20200101 202001 2020 100
20200102 202001 2020 110
...
20200215 202002 2020 120
</code>```

I want to aggregate by week, month and year for this result :

```<code>Id value
2020 12000
202001 4000 'january
202002 4000 'february
2020001 700 'first week of 2020
</code>```

In order to do this, I also have the table d_tps

```<code>Type Id week month year
J 20200101 2020001 202001 2020
J 20200102 2020001 202001 2020
...

J 20200215 2020007 202002 2020
M 202001 null 202001 2020
M 202002 null 202002 2020
Y 2020 null null 2020

</code>```

My approach is the following

```<code>select d.id, sum(value) from tab1
Inner join d_tps d
On d.id = tab1.year
Or d.id = tab1.month
Or d.id = tab1.year
group by d.id
</code>```

It works and return the expected result. Unfortunately, in the query plan, the join with OR condition causes the CTQ operator to come early and most of the query (which is in reality more complex) is treated as rows instead of columns.

How can I optimize it ?

答:
It looks like one join condition is sufficient along with aggregation:

```<code>select d.week, sum(value)
from tab1 Inner join
     d_tps d
     On d.id = tab1.day
group by d.week
</code>```

If you want to aggregate by multiple time levels, then use grouping sets:

```<code>select d.week, d.month, d.year, sum(value)
from tab1 Inner join
     d_tps d
     On d.id = tab1.day
group by grouping sets ((d.week), (d.month), (d.year))
</code>```

Body:
I'm working on DB2 Blu on with column organized tables.

My dataset is the following :

Day month year value
------- -------
20200101 202001 2020 100
20200102 202001 2020 110
...
20200215 202002 2020 120

I want to aggregate by week, month and year for this result :

Id value
2020 12000
202001 4000 'january
202002 4000 'february
2020001 700 'first week of 2020

In order to do this, I also have the table d_tps

Type Id week month year
J 20200101 2020001 202001 2020
J 20200102 2020001 202001 2020
...

J 20200215 2020007 202002 2020
M 202001 null 202001 2020
M 202002 null 202002 2020
Y 2020 null null 2020

My approach is the following

select d.id, sum(value) from tab1
Inner join d_tps d
On d.id = tab1.year
Or d.id = tab1.month
Or d.id = tab1.year
group by d.id

It works and return the expected result. Unfortunately, in the query plan, the join with OR condition causes the CTQ operator to come early and most of the query (which is in reality more complex) is treated as rows instead of columns.

How can I optimize it ?

Body:
It looks like one join condition is sufficient along with aggregation:

select d.week, sum(value)
from tab1 Inner join
     d_tps d
     On d.id = tab1.day
group by d.week

If you want to aggregate by multiple time levels, then use grouping sets:

select d.week, d.month, d.year, sum(value)
from tab1 Inner join
     d_tps d
     On d.id = tab1.day
group by grouping sets ((d.week), (d.month), (d.year))


来源: stackexchange

问:
Github page not linking to CSS
I'm working on HTML/CSS page. Here is my repo. The page won't load the CSS file when referenced like this:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.1/css/all.min.css">
    <link rel="stylesheet" href="style.css">
    <title>Google Homepage</title>
```

Thanks in advance.

答: Use the correct path to the sheet file: href=".\style.css"</p>

ContentLicense: CC BY-SA 4.0

Title: Github page not linking to CSS

Body:
I'm working on HTML/CSS page. Here is my repo. The page won't load the CSS file when referenced like this:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.1/css/all.min.css">
    <link rel="stylesheet" href="style.css">
    <title>Google Homepage</title>

Thanks in advance.


问:
How can I solve "TypeError: max() received an invalid combination of arguments - got (Linear, int), but expected"?
How I solve this error, I am trying to train a ticket classification model

I'm trying to make a ticket sorter with the Pytorch library, but I have this error. I can't understand what I've done wrong
Can you help me?

```<code>
data_transforms = {
    'train' : transforms.Compose([
        transforms.RandomResizedCrop(224),
        transforms.RandomHorizontalFlip(),
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    ]),
    'val' : transforms.Compose([
        transforms.Resize(256),
        transforms.CenterCrop(224),
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    ])

}

data_dir = 'dataset_billete_argentino'
image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x),
                                          data_transforms[x])
                  for x in ['train', 'val']}
dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=4,
                                              shuffle=True, num_workers=4)
               for x in ['train', 'val']}
dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'val']}
class_name = image_datasets['train'].classes

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(3,6,5)
        self.pool = nn.MaxPool2d(2,2)
        self.conv2 = nn.Conv2d(6,16,5)
        self.fc1 = nn.Linear(16 * 53 * 53, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 2)

    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = x.view(x.size(0), 16* 53 * 53)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3
        return x

net = Net()

def train_model(model, criterion, optimizer, scheduler, num_epochs=25):
    since = time.time()

    best_model_wts = copy.deepcopy(model.state_dict())
    best_acc = 0.0

    for epoch in range(num_epochs):
        print('Epoch {}/{}'.format(epoch, num_epochs - 1))
        print('-' * 10)

        # Each epoch has a training and validation phase
        for phase in ['train', 'val']:
            if phase == 'train':
                model.train()  # Set model to training mode
            else:
                model.eval()   # Set model to evaluate mode

            running_loss = 0.0
            running_corrects = 0

            # Iterate over data.
            for inputs, labels in dataloaders[phase]:
                inputs = inputs.to(device)
                labels = labels.to(device)

                # zero the parameter gradients
                optimizer.zero_grad()

                # forward
                # track history if only in train
                with torch.set_grad_enabled(phase == 'train'):
                    outputs = model(inputs)
                    _, preds = torch.max(outputs, 1)
                    loss = criterion(outputs, labels)

                    # backward + optimize only if in training phase
                    if phase == 'train':
                        loss.backward()
                        optimizer.step()

                # statistics
                running_loss += loss.item() * inputs.size(0)
                running_corrects += torch.sum(preds == labels.data)
            if phase == 'train':
                scheduler.step()

            epoch_loss = running_loss / dataset_sizes[phase]
            epoch_acc = running_corrects.double() / dataset_sizes[phase]

            print('{} Loss: {:.4f} Acc: {:.4f}'.format(
                phase, epoch_loss, epoch_acc))

            # deep copy the model
            if phase == 'val' and epoch_acc > best_acc:
                best_acc = epoch_acc
                best_model_wts = copy.deepcopy(model.state_dict())

        print()

    time_elapsed = time.time() - since
    print('Training complete in {:.0f}m {:.0f}s'.format(
        time_elapsed // 60, time_elapsed % 60))
    print('Best val Acc: {:4f}'.format(best_acc))

    # load best model weights
    model.load_state_dict(best_model_wts)
    return model

from torch.optim import lr_scheduler

exp_lr_scheduler = lr_scheduler.StepLR(optimizer, step_size=7, gamma=0.1)

net = train_model(net, criterion, optimizer, exp_lr_scheduler,
                  num_epochs=25)
</code>```

And give this error
TypeError: max() received an invalid combination of arguments - got (Linear, int), but expected one of:
 * (Tensor input)
 * (Tensor input, name dim, bool keepdim, tuple of Tensors out)
 * (Tensor input, Tensor other, Tensor out)
 * (Tensor input, int dim, bool keepdim, tuple of Tensors out)

```<code>Epoch 0/24
----------
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-27-29dfe3459d8a> in <module>
      4
      5 net = train_model(net, criterion, optimizer, exp_lr_scheduler,
----> 6                   num_epochs=25)

<ipython-input-19-1a5d4f162548> in train_model(model, criterion, optimizer, scheduler, num_epochs)
     31                 with torch.set_grad_enabled(phase == 'train'):
     32                     outputs = model(inputs)
---> 33                     _, preds = torch.max(outputs, 1)
     34                     loss = criterion(outputs, labels)
     35

TypeError: max() received an invalid combination of arguments - got (Linear, int), but expected one of:
 * (Tensor input)
 * (Tensor input, name dim, bool keepdim, tuple of Tensors out)
 * (Tensor input, Tensor other, Tensor out)
 * (Tensor input, int dim, bool keepdim, tuple of Tensors out)
</code>```

答:
The problem is in this line:

```<code>_, preds = torch.max(outputs, 1)
</code>```

torch.max returns the maximum value of a tensor.

For example:

```<code>>>> a = torch.randn(1, 3)
>>> a
tensor([[ 0.6763,  0.7445, -2.2369]])
>>> torch.max(a)
tensor(0.7445)
</code>```

You are giving it 2 arguments, neither of which is a tensor.

Body:
How I solve this error, I am trying to train a ticket classification model

I'm trying to make a ticket sorter with the Pytorch library, but I have this error. I can't understand what I've done wrong
Can you help me?

data_transforms = {
    'train' : transforms.Compose([
        transforms.RandomResizedCrop(224),
        transforms.RandomHorizontalFlip(),
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    ]),
    'val' : transforms.Compose([
        transforms.Resize(256),
        transforms.CenterCrop(224),
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    ])

}

data_dir = 'dataset_billete_argentino'
image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x),
                                          data_transforms[x])
                  for x in ['train', 'val']}
dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=4,
                                              shuffle=True, num_workers=4)
               for x in ['train', 'val']}
dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'val']}
class_name = image_datasets['train'].classes

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(3,6,5)
        self.pool = nn.MaxPool2d(2,2)
        self.conv2 = nn.Conv2d(6,16,5)
        self.fc1 = nn.Linear(16 * 53 * 53, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 2)

    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = x.view(x.size(0), 16* 53 * 53)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3
        return x

net = Net()

def train_model(model, criterion, optimizer, scheduler, num_epochs=25):
    since = time.time()

    best_model_wts = copy.deepcopy(model.state_dict())
    best_acc = 0.0

    for epoch in range(num_epochs):
        print('Epoch {}/{}'.format(epoch, num_epochs - 1))
        print('-' * 10)

        # Each epoch has a training and validation phase
        for phase in ['train', 'val']:
            if phase == 'train':
                model.train()  # Set model to training mode
            else:
                model.eval()   # Set model to evaluate mode

            running_loss = 0.0
            running_corrects = 0

            # Iterate over data.
            for inputs, labels in dataloaders[phase]:
                inputs = inputs.to(device)
                labels = labels.to(device)

                # zero the parameter gradients
                optimizer.zero_grad()

                # forward
                # track history if only in train
                with torch.set_grad_enabled(phase == 'train'):
                    outputs = model(inputs)
                    _, preds = torch.max(outputs, 1)
                    loss = criterion(outputs, labels)

                    # backward + optimize only if in training phase
                    if phase == 'train':
                        loss.backward()
                        optimizer.step()

                # statistics
                running_loss += loss.item() * inputs.size(0)
                running_corrects += torch.sum(preds == labels.data)
            if phase == 'train':
                scheduler.step()

            epoch_loss = running_loss / dataset_sizes[phase]
            epoch_acc = running_corrects.double() / dataset_sizes[phase]

            print('{} Loss: {:.4f} Acc: {:.4f}'.format(
                phase, epoch_loss, epoch_acc))

            # deep copy the model
            if phase == 'val' and epoch_acc > best_acc:
                best_acc = epoch_acc
                best_model_wts = copy.deepcopy(model.state_dict())

        print()

    time_elapsed = time.time() - since
    print('Training complete in {:.0f}m {:.0f}s'.format(
        time_elapsed // 60, time_elapsed % 60))
    print('Best val Acc: {:4f}'.format(best_acc))

    # load best model weights
    model.load_state_dict(best_model_wts)
    return model

from torch.optim import lr_scheduler

exp_lr_scheduler = lr_scheduler.StepLR(optimizer, step_size=7, gamma=0.1)

net = train_model(net, criterion, optimizer, exp_lr_scheduler,
                  num_epochs=25)

And give this error
TypeError: max() received an invalid combination of arguments - got (Linear, int), but expected one of:
 * (Tensor input)
 * (Tensor input, name dim, bool keepdim, tuple of Tensors out)
 * (Tensor input, Tensor other, Tensor out)
 * (Tensor input, int dim, bool keepdim, tuple of Tensors out)

Epoch 0/24
----------
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-27-29dfe3459d8a> in <module>
      4
      5 net = train_model(net, criterion, optimizer, exp_lr_scheduler,
----> 6                   num_epochs=25)

<ipython-input-19-1a5d4f162548> in train_model(model, criterion, optimizer, scheduler, num_epochs)
     31                 with torch.set_grad_enabled(phase == 'train'):
     32                     outputs = model(inputs)
---> 33                     _, preds = torch.max(outputs, 1)
     34                     loss = criterion(outputs, labels)
     35

TypeError: max() received an invalid combination of arguments - got (Linear, int), but expected one of:
 * (Tensor input)
 * (Tensor input, name dim, bool keepdim, tuple of Tensors out)
 * (Tensor input, Tensor other, Tensor out)
 * (Tensor input, int dim, bool keepdim, tuple of Tensors out)

Body:
The problem is in this line:

_, preds = torch.max(outputs, 1)

torch.max returns the maximum value of a tensor.

For example:

>>> a = torch.randn(1, 3)
>>> a
tensor([[ 0.6763,  0.7445, -2.2369]])
>>> torch.max(a)
tensor(0.7445)

You are giving it 2 arguments, neither of which is a tensor.


问:
C++: How do I assign a value from a 2D dynamic array to another 2D dynamic array since 'temp[0][0] = array[0][0]' doesn't work?
I'm new to c++, and I'm trying to figure out how to get a 2D dynamic array called temp to get values from another 2D dynamic array called array. I couldn't figure out how to assign any values from array to temp because the statement 'temp[0][0] = array[0][0];' doesn't seem to assign the value of array[0][0] which is 1 to temp[0][0]. Instead, temp[0][0] seems to have the same random number in it after 'temp[0][0] = array[0][0]' before any value was assign to temp[0][0]. I tried to assign temp[0][0] to 2 and it works. I don't really know how to exactly assign values from one 2d dynamic array to another. Anyway thanks in advance for helping me out!</p>

```<code>    ...
    //initializing first 2D dynamic array
    int x=2;
    int y=2;
    int** array = new int*[x];
    for(int i=0; i<x; i++) array[i] = new int[y];

    //initializing second 2D dynamic array
    int new_x=3;
    int new_y=3;
    int** temp = new int*[new_x];
    for(int i=0; i<new_x; i++) temp[i] = new int[new_y];

    //assigning values
    array[0][0] = 1;
    cout << array[0][0] << endl; //output is 1

    //before assigning values to temp[0][0]
    cout << temp[0][0] << endl; //out is a huge random number

    temp[0][0] = array[0][0];
    cout << temp[0][0] << endl; //output is the same huge random number

    temp[0][0] = 2;
    cout << temp[0][0] << endl; //output is 2
    ...
</code>```

答:
The code snippet you posted works exaclty as it should:

First cout prints 1 witch is the value of array[0][0].

Second cout prints the uninitialized temp[0][0], I compiled it here, and in this case the value is 0, but it could be anything.

Third cout prints 1 due to the assingment temp[0][0] = array[0][0].

Fourth cout prints the value of 2 assigned to temp[0][0].

If there are problems in your code it's not in the posted bit, aside from the fact that you are trying to print an unitialized variable in the second cout

Body:
I'm new to c++, and I'm trying to figure out how to get a 2D dynamic array called temp to get values from another 2D dynamic array called array. I couldn't figure out how to assign any values from array to temp because the statement 'temp[0][0] = array[0][0];' doesn't seem to assign the value of array[0][0] which is 1 to temp[0][0]. Instead, temp[0][0] seems to have the same random number in it after 'temp[0][0] = array[0][0]' before any value was assign to temp[0][0]. I tried to assign temp[0][0] to 2 and it works. I don't really know how to exactly assign values from one 2d dynamic array to another. Anyway thanks in advance for helping me out!

    ...
    //initializing first 2D dynamic array
    int x=2;
    int y=2;
    int** array = new int*[x];
    for(int i=0; i<x; i++) array[i] = new int[y];

    //initializing second 2D dynamic array
    int new_x=3;
    int new_y=3;
    int** temp = new int*[new_x];
    for(int i=0; i<new_x; i++) temp[i] = new int[new_y];

    //assigning values
    array[0][0] = 1;
    cout << array[0][0] << endl; //output is 1

    //before assigning values to temp[0][0]
    cout << temp[0][0] << endl; //out is a huge random number

    temp[0][0] = array[0][0];
    cout << temp[0][0] << endl; //output is the same huge random number

    temp[0][0] = 2;
    cout << temp[0][0] << endl; //output is 2
    ...


问:
Divide every element in 2 dimensional array
I have the sums of x and y coordinates and I need to calculate the mean

```<code>float [][] sums = new float[n][2];
</code>```

e.g. my array consists of:

```<code>
{ [ 8,6 ],
  [ 4,2 ] }
</code>```

After the dividing to 2:

```<code>
{ [ 4,3 ],
  [ 2,1 ] }
</code>```

I can do this with loops but I wonder if It is possible to do it with 1 function.

答:
You can simply encapsulate your for loops into a function and call it:

```<code>import java.util.Arrays;

void setup(){

    float [][] sums = new float[][]{ { 8,6 },
                                     { 4,2 } };

    print("pre: ");
    System.out.println(Arrays.deepToString(sums));

    matMul(sums,0.5);

    print("post:");
    System.out.println(Arrays.deepToString(sums));
}

void matMul(float[][] data,float multiplier){
  for(int y = 0; y < data.length; y++){
    for(int x = 0; x < data[y].length; x++){
      data[x][y] *= multiplier;
    }
  }
}
</code>```

Here are a few pointers if you're just getting started with functions.

The simplest thing a function can do is encapsulate a bunch of instructions, but
no allow any data from outside the function to be read and not return any data out.

Here is a very simple/boring example:

```<code>void sayHello(){
  println("hello");
}
</code>```

The point of is it to get familiar with the syntax.
A function has:

a (return) type: if the function returns any result, what kind of result is it ? (a number, a string of text, an Object, etc.), if not it's simply void

a name (so we can call it)

arguments (0 or more) within parenthesis, each having a type and name (similar to a local variable)

a body delinieated by the { and } symbols: this everything defined within this block is only visible to this block (except what's returned, if anything). This is known as the scope of the function

You've probably already defined functions that don't return results: void setup(){}, void draw(){}

You've probavly already called functions before: used the name and arguments (if any) in paranthesis (e.g. println("hi");, point(50,50);, noCursor();, etc.)

Here's a simple example of a function that takes two inputs and returns one output: the sum of the inputs:

```<code>int sum(int a, int b){
  return a+b;
}
</code>```

Instead of void we return a result of int type and the arguments are a couple of integers named a and b. The only other extra thing is the return keyword used to (you guessed it) return the result (and exit the function block).

Here a basic example calling the function:

```<code>void setup(){
  println(add(2,2));
  println(add(4,4));
}

int add(int a, int b){
  return a + b;
}
</code>```

If you want to read more on it check out Kevin Workman's Creating Functions Processing Tutorial

Bare in mind the the void method transforms the array reference to pass as an argument to the function. There may be situations where you don't want to change the input data, yet return the result. In such as case you can either copy the array beforehand and pass a copy, or have a version of the function that makes a copy for you:

```<code>import java.util.Arrays;

void setup(){

    float [][] sums = new float[][]{ { 8,6 },
                                     { 4,2 } };

    print("sums:    ");
    System.out.println(Arrays.deepToString(sums));

    float[][] result = matMul(sums,0.5);

    print("result:  ");
    System.out.println(Arrays.deepToString(result));

    print("original:");
    System.out.println(Arrays.deepToString(sums));
}

float[][] matMul(float[][] data,float multiplier){
  // check input data
  if(data == null || data.length == 0){
    println("no data to multiply, returning null");
    return null;
  }
  // make another array of the same shape
  float[][] result = new float[data.length][data[0].length];
  // do the multiplcation, storing the result into the duplicate array
  for(int y = 0; y < data.length; y++){
    for(int x = 0; x < data[y].length; x++){
      result[x][y] = data[x][y] * multiplier;
    }
  }
  // return the result
  return result;
}
</code>```

Notice a few checks at the start of the function: in general it's a good idea to validata data coming in, just in case, and display a message that will make it easy to fix the issue (withouth spending to much figuring out what the error means).

Body:
I have the sums of x and y coordinates and I need to calculate the mean

float [][] sums = new float[n][2];

e.g. my array consists of:

{ [ 8,6 ],
  [ 4,2 ] }

After the dividing to 2:

{ [ 4,3 ],
  [ 2,1 ] }

I can do this with loops but I wonder if It is possible to do it with 1 function.

Body:
You can simply encapsulate your for loops into a function and call it:

import java.util.Arrays;

void setup(){

    float [][] sums = new float[][]{ { 8,6 },
                                     { 4,2 } };

    print("pre: ");
    System.out.println(Arrays.deepToString(sums));

    matMul(sums,0.5);

    print("post:");
    System.out.println(Arrays.deepToString(sums));
}

void matMul(float[][] data,float multiplier){
  for(int y = 0; y < data.length; y++){
    for(int x = 0; x < data[y].length; x++){
      data[x][y] *= multiplier;
    }
  }
}

Here are a few pointers if you're just getting started with functions.

The simplest thing a function can do is encapsulate a bunch of instructions, but
no allow any data from outside the function to be read and not return any data out.

Here is a very simple/boring example:

void sayHello(){
  println("hello");
}

The point of is it to get familiar with the syntax.
A function has:

a (return) type: if the function returns any result, what kind of result is it ? (a number, a string of text, an Object, etc.), if not it's simply void

a name (so we can call it)

arguments (0 or more) within parenthesis, each having a type and name (similar to a local variable)

a body delinieated by the { and } symbols: this everything defined within this block is only visible to this block (except what's returned, if anything). This is known as the scope of the function

You've probably already defined functions that don't return results: void setup(){}, void draw(){}

You've probavly already called functions before: used the name and arguments (if any) in paranthesis (e.g. println("hi");, point(50,50);, noCursor();, etc.)

Here's a simple example of a function that takes two inputs and returns one output: the sum of the inputs:

int sum(int a, int b){
  return a+b;
}

Instead of void we return a result of int type and the arguments are a couple of integers named a and b. The only other extra thing is the return keyword used to (you guessed it) return the result (and exit the function block).

Here a basic example calling the function:

void setup(){
  println(add(2,2));
  println(add(4,4));
}

int add(int a, int b){
  return a + b;
}

If you want to read more on it check out Kevin Workman's Creating Functions Processing Tutorial

Bare in mind the the void method transforms the array reference to pass as an argument to the function. There may be situations where you don't want to change the input data, yet return the result. In such as case you can either copy the array beforehand and pass a copy, or have a version of the function that makes a copy for you:

import java.util.Arrays;

void setup(){

    float [][] sums = new float[][]{ { 8,6 },
                                     { 4,2 } };

    print("sums:    ");
    System.out.println(Arrays.deepToString(sums));

    float[][] result = matMul(sums,0.5);

    print("result:  ");
    System.out.println(Arrays.deepToString(result));

    print("original:");
    System.out.println(Arrays.deepToString(sums));
}

float[][] matMul(float[][] data,float multiplier){
  // check input data
  if(data == null || data.length == 0){
    println("no data to multiply, returning null");
    return null;
  }
  // make another array of the same shape
  float[][] result = new float[data.length][data[0].length];
  // do the multiplcation, storing the result into the duplicate array
  for(int y = 0; y < data.length; y++){
    for(int x = 0; x < data[y].length; x++){
      result[x][y] = data[x][y] * multiplier;
    }
  }
  // return the result
  return result;
}

Notice a few checks at the start of the function: in general it's a good idea to validata data coming in, just in case, and display a message that will make it easy to fix the issue (withouth spending to much figuring out what the error means).


问:
Is there a way to intercept setters and getters in C#?
In both Ruby and PHP (and I guess other languages as well) there are some utility methods that are called whenever a property is set. ( *instance_variable_set* for Ruby, *__set* for PHP).

So, let's say I have a C# class like this:

```<code>public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
</code>```

Now, let's say that if any property setter from the Person class is called, I want to call another method first, and then continue with the default behaviour of the setter, and the same applies for the property setters.

Is this possible?

Edit:
I want to do this without defining a backing field.

答:
Not generally; a few options though;

inherit from ContextBoundObject - which does allow this, but at a performance cost

write an explicit property (i.e. with a backing field), and add a utility method call manually

look at compile-time weavers, such as PostSharp - generally by spotting an attribute or similar

look at runtime code generators, as offered by some DI/IoC tools (and some other "decorator" based tools) - which either decorate or subclass your object to add the extra code

ContentLicense: CC BY-SA 3.0

Body:
In both Ruby and PHP (and I guess other languages as well) there are some utility methods that are called whenever a property is set. ( *instance_variable_set* for Ruby, *__set* for PHP).

So, let's say I have a C# class like this:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Now, let's say that if any property setter from the Person class is called, I want to call another method first, and then continue with the default behaviour of the setter, and the same applies for the property setters.

Is this possible?

Edit:
I want to do this without defining a backing field.


问:
Not able to retrieve or create database objects inside django view function inside aws amazon linux v2
I am using amazon linux v2 with python 3.6 and django 2.2.0:
I have set up database using RDS MYSQL DB instance. I am able to retrieve and/or create objects in python shell but not able to retrieve and/or create when using inside view function.

```<code>pqs=ExpertQa.objects.filter(category="public")
return render(request,'ebdjango/expert-qa.html',{'pqs':pqs})
</code>```

the above code isn't fetching objects.
I have tried passing list, string everything works fine.Just not able to get database objects.

Please can anyone provide the solution? Is there any other syntax for linux?

答:
Indentation(spaces) matters:</p>

```<code>pqs = ExpertQa.objects.filter(category="public")
return render(request,'ebdjango/expert-qa.html',{'pqs':pqs})
</code>```

Body:
I am using amazon linux v2 with python 3.6 and django 2.2.0:
I have set up database using RDS MYSQL DB instance. I am able to retrieve and/or create objects in python shell but not able to retrieve and/or create when using inside view function.

pqs=ExpertQa.objects.filter(category="public")
return render(request,'ebdjango/expert-qa.html',{'pqs':pqs})

the above code isn't fetching objects.
I have tried passing list, string everything works fine.Just not able to get database objects.

Please can anyone provide the solution? Is there any other syntax for linux?

Body:
Indentation(spaces) matters:

pqs = ExpertQa.objects.filter(category="public")
return render(request,'ebdjango/expert-qa.html',{'pqs':pqs})


问:
Continuing in Python's unittest when an assertion fails
EDIT: switched to a better example, and clarified why this is a real problem.

I'd like to write unit tests in Python that continue executing when an assertion fails, so that I can see multiple failures in a single test. For example:

```<code>class Car(object):
  def __init__(self, make, model):
    self.make = make
    self.model = make  # Copy and paste error: should be model.
    self.has_seats = True
    self.wheel_count = 3  # Typo: should be 4.

class CarTest(unittest.TestCase):
  def test_init(self):
    make = "Ford"
    model = "Model T"
    car = Car(make=make, model=model)
    self.assertEqual(car.make, make)
    self.assertEqual(car.model, model)  # Failure!
    self.assertTrue(car.has_seats)
    self.assertEqual(car.wheel_count, 4)  # Failure!
</code>```

Here, the purpose of the test is to ensure that Car's __init__ sets its fields correctly. I could break it up into four methods (and that's often a great idea), but in this case I think it's more readable to keep it as a single method that tests a single concept ("the object is initialized correctly").

If we assume that it's best here to not break up the method, then I have a new problem: I can't see all of the errors at once. When I fix the model error and re-run the test, then the wheel_count error appears. It would save me time to see both errors when I first run the test.

For comparison, Google's C++ unit testing framework distinguishes between between non-fatal EXPECT_* assertions and fatal ASSERT_* assertions:

The assertions come in pairs that test the same thing but have different effects on the current function. ASSERT_* versions generate fatal failures when they fail, and abort the current function. EXPECT_* versions generate nonfatal failures, which don't abort the current function. Usually EXPECT_* are preferred, as they allow more than one failures to be reported in a test. However, you should use ASSERT_* if it doesn't make sense to continue when the assertion in question fails.

Is there a way to get EXPECT_*-like behavior in Python's unittest? If not in unittest, then is there another Python unit test framework that does support this behavior?

Incidentally, I was curious about how many real-life tests might benefit from non-fatal assertions, so I looked at some code examples (edited 2014-08-19 to use searchcode instead of Google Code Search, RIP). Out of 10 randomly selected results from the first page, all contained tests that made multiple independent assertions in the same test method. All would benefit from non-fatal assertions.

答:
Since Python 3.4 you can also use subtests:

```<code>def test_init(self):
    make = "Ford"
    model = "Model T"
    car = Car(make=make, model=model)
    with self.subTest(msg='Car.make check'):
        self.assertEqual(car.make, make)
    with self.subTest(msg='Car.model check'):
        self.assertEqual(car.model, model)
    with self.subTest(msg='Car.has_seats check'):
        self.assertTrue(car.has_seats)
    with self.subTest(msg='Car.wheel_count check'):
        self.assertEqual(car.wheel_count, 4)
</code>```

(msg parameter is used to more easily determine which test failed.)

Output:

```<code>======================================================================
FAIL: test_init (__main__.CarTest) [Car.model check]
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 23, in test_init
    self.assertEqual(car.model, model)
AssertionError: 'Ford' != 'Model T'
- Ford
+ Model T

======================================================================
FAIL: test_init (__main__.CarTest) [Car.wheel_count check]
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 27, in test_init
    self.assertEqual(car.wheel_count, 4)
AssertionError: 3 != 4

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (failures=2)
</code>```

Body:
EDIT: switched to a better example, and clarified why this is a real problem.

I'd like to write unit tests in Python that continue executing when an assertion fails, so that I can see multiple failures in a single test. For example:

class Car(object):
  def __init__(self, make, model):
    self.make = make
    self.model = make  # Copy and paste error: should be model.
    self.has_seats = True
    self.wheel_count = 3  # Typo: should be 4.

class CarTest(unittest.TestCase):
  def test_init(self):
    make = "Ford"
    model = "Model T"
    car = Car(make=make, model=model)
    self.assertEqual(car.make, make)
    self.assertEqual(car.model, model)  # Failure!
    self.assertTrue(car.has_seats)
    self.assertEqual(car.wheel_count, 4)  # Failure!

Here, the purpose of the test is to ensure that Car's __init__ sets its fields correctly. I could break it up into four methods (and that's often a great idea), but in this case I think it's more readable to keep it as a single method that tests a single concept ("the object is initialized correctly").

If we assume that it's best here to not break up the method, then I have a new problem: I can't see all of the errors at once. When I fix the model error and re-run the test, then the wheel_count error appears. It would save me time to see both errors when I first run the test.

For comparison, Google's C++ unit testing framework distinguishes between between non-fatal EXPECT_* assertions and fatal ASSERT_* assertions:

The assertions come in pairs that test the same thing but have different effects on the current function. ASSERT_* versions generate fatal failures when they fail, and abort the current function. EXPECT_* versions generate nonfatal failures, which don't abort the current function. Usually EXPECT_* are preferred, as they allow more than one failures to be reported in a test. However, you should use ASSERT_* if it doesn't make sense to continue when the assertion in question fails.

Is there a way to get EXPECT_*-like behavior in Python's unittest? If not in unittest, then is there another Python unit test framework that does support this behavior?

Incidentally, I was curious about how many real-life tests might benefit from non-fatal assertions, so I looked at some code examples (edited 2014-08-19 to use searchcode instead of Google Code Search, RIP). Out of 10 randomly selected results from the first page, all contained tests that made multiple independent assertions in the same test method. All would benefit from non-fatal assertions.

Body:
Since Python 3.4 you can also use subtests:

def test_init(self):
    make = "Ford"
    model = "Model T"
    car = Car(make=make, model=model)
    with self.subTest(msg='Car.make check'):
        self.assertEqual(car.make, make)
    with self.subTest(msg='Car.model check'):
        self.assertEqual(car.model, model)
    with self.subTest(msg='Car.has_seats check'):
        self.assertTrue(car.has_seats)
    with self.subTest(msg='Car.wheel_count check'):
        self.assertEqual(car.wheel_count, 4)

(msg parameter is used to more easily determine which test failed.)

Output:

======================================================================
FAIL: test_init (__main__.CarTest) [Car.model check]
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 23, in test_init
    self.assertEqual(car.model, model)
AssertionError: 'Ford' != 'Model T'
- Ford
+ Model T

======================================================================
FAIL: test_init (__main__.CarTest) [Car.wheel_count check]
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 27, in test_init
    self.assertEqual(car.wheel_count, 4)
AssertionError: 3 != 4

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (failures=2)


问:
Why is my unfinished javascript game crashing after the 3rd death?

// Commented because does not work in Sandbox
// window.localStorage; //Ignore this line

// Where all my variables have been assigned

var c = document.getElementById("GameScreen");
var ctx = c.getContext("2d");
var charY = 220;
const gravity = 10;
var score = 0;
var time = 0;
var speed = 5;
var cloneID = 0;
var clonePos = [600];
var clonePoints = [0];
var animationBounce = 0;
var jump = 10;
var charDead = 0;
var dataCharY = [];
var dataDisObst = [];
var disObst = 1000;
var lowestLoopDis;
var jumpFactor = 0;
var disDeath;
var AIgames = 1;
var bestScoreAI = 0;

ctx.translate(c.width / 2, c.height / 2);

// Was going to use this for background trees but haven't done it yet

new obj(50, 50, 30, 30);

// Runs most functions

function runAll() {
  if (charDead == 0) {
    clearAll(); //This function runs most of the code
    updateChar();
    createGround();
    updateObj();
    groundDetect();
    updateScore();
    hitDetect();
    addData();
    testBetterAI();
    getDisObst();
    jumpAI();
    removeUnusedObst();
  }
}

// Was going to use this for trees but haven't yet

function obj(x, y, width, height) {
  this.width = width;
  this.height = height;
  this.x = x;
  this.y = y;

  ctx.beginPath();

  ctx = c.getContext("2d");
  ctx.fillStyle = "brown";
  ctx.fillRect(this.x, this.y, this.width, this.height);
  ctx.fillStyle = "green";
  ctx.arc(-293, 150, 50, 0, 2 * Math.PI);
  ctx.fill();
  ctx.stroke();

  this.cloneID = cloneID;
}

new obj(-293, 212, 0, 2 * Math.PI);

// Creates the floor (IKR)

function createGround() {
  ctx.fillStyle = "green";
  ctx.fillRect(-635, 250, c.width, 50);
}

// Creates the character every milisecond (or 10, I can't remember)

function updateChar() {
  ctx.fillStyle = "blue";
  ctx.fillRect(-300, charY - animationBounce, 15, 30);
  ctx.fillStyle = "pink";
  ctx.beginPath();
  ctx.arc(-293, charY - animationBounce - 15, 15, 0, 2 * Math.PI);
  ctx.fill();
  ctx.stroke();
}

// Removes everything in order to be redrawn in new position

function clearAll() {
  ctx.clearRect(-700, -700, 2000, 2000);
}

// Redraws every square / object

function updateObj() {
  for (var i = 0; i != clonePos.length; i++) {
    ctx.fillStyle = "green";
    ctx.fillRect(clonePos[i], 220, 30, 30);
  }
}

// Creates new square (I also decided to rename them half way through with obstacle instead of object)

function createObst() {
  clonePos.push(600);
  cloneID++;
}

// Changes the squares / obstacles position relative to the movement

function moveObst() {
  for (var ii = 0; ii != clonePos.length; ii++) {
    clonePos[ii] -= speed;
  }
}

// Tests to see if the character is on the ground

function groundDetect() {
  if (charY > 220) {
    charY = 220;
  }
}

// Makes gravity actually work

function charGravity() {
  if (charY < 220) {
    charY += gravity;
  }
}

// Updates the score counter text

function updateScore() {
  document.getElementById("scoreText").innerHTML = score;
}

// Gives the character a little bounce when moving

function charBounce() {
  setTimeout(function() {
    animationBounce++;
  }, 100);
  setTimeout(function() {
    animationBounce++;
  }, 200);
  setTimeout(function() {
    animationBounce++;
  }, 300);
  setTimeout(function() {
    animationBounce--;
  }, 400);
  setTimeout(function() {
    animationBounce--;
  }, 500);
  setTimeout(function() {
    animationBounce--;
  }, 600);
}

// Makes the character jump

function charJump() {
  if (charY == 220) {
    jump = 4;

    setTimeout(function() {
      charY -= jump;
    }, 20);
    jump = 8;
    setTimeout(function() {
      charY -= jump;
    }, 40);
    jump = 12;
    setTimeout(function() {
      charY -= jump;
    }, 60);
    jump = 16;
    setTimeout(function() {
      charY -= jump;
    }, 80);
    setTimeout(function() {
      charY -= jump;
    }, 100);
    setTimeout(function() {
      charY -= jump;
    }, 120);
  }
}

// Detects when the character has a hit a square

function hitDetect() {
  for (var iB = 0; iB != clonePos.length; iB++) {
    if (clonePos[iB] > -320 && clonePos[iB] < -280 && charY > 200) {
      charDied();
    }
  }
}

// Runs when character dies

function charDied() {
  disDeath = disObst;
  charDead = 1;

  charRevive();

  testBetterAI();

  decideAdjustments();
}

// Adds score very interval

function addingScore() {
  if (charDead == 0) {
    score += 100;
  }
}

// Adds to an array that I will use later

function addData() {
  dataCharY.push(charY);
  dataDisObst.push(disObst);
}

// Test to see if one of my AI's (which hasn't been made yet) scores is better than the previous best

function testBetterAI() {
  // Commented because does not work in Sandbox
  // if (score > localStorage.getItem("bestScore")) {
  // }
}

// Calculates the distance to the nearest square / obstacle

function getDisObst() {
  lowestLoopDis = 1000;

  for (var iiA = 0; iiA != clonePos.length; iiA++) {
    if (clonePos[iiA] > -320) {
      if (clonePos[iiA] > 0) {
        if (Math.abs(clonePos[iiA]) < lowestLoopDis) {
          lowestLoopDis = Math.abs(clonePos[iiA]);
        }
      } else {
        if (Math.abs(clonePos[iiA]) < lowestLoopDis) {
          lowestLoopDis = Math.abs(clonePos[iiA]);
        }
      }
    }
  }

  if (lowestLoopDis < disObst) {
    disObst = lowestLoopDis;
  }
}

// Increments the speed of the obstacles / squares and the character

function addSpeed() {
  if (speed < 25) {
    speed++;
  }
}

// Restarts the game

function charRevive() {
  clonePos = [600];
  charDead = 0;
  score = 0;
  time = 0;
  speed = 5;
  AIgames++;
}

// I accidently did this twice, whoops

function testBetterAI() {
  if (score > bestScoreAI) {
    bestScoreAI = score;
  }
}

// Makes the unfinished AI jump when it wants to

function jumpAI() {
  if (disObst <= disDeath + jumpFactor) {
    charJump();
  }
}

// What changes need to be made in order to improve the AI

function decideAdjustments() {
  jumpFactor += Math.floor(Math.random() * 10) - 5;

  if (jumpFactor < 0) {
    jumpFactor = 0;
  }
}

// Removing blocks that are off the screen

function removeUnusedObst() {
  if (clonePos[0] < -650) {
    clonePos.shift();
  }
}

// Intervals here

setInterval(function() {
  time++;
}, 1000);
setInterval(function() {
  runAll();
}, 10);
setInterval(function() {
  moveObst();
}, 50);
setInterval(function() {
  charGravity();
}, 25);
setInterval(function() {
  createObst();
}, 3000);
setInterval(function() {
  charBounce();
}, 650);
setInterval(function() {
  addingScore();
}, 3500);
setInterval(function() {
  addSpeed();
}, 25000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#GameScreen {
  background-color: CornflowerBlue;
}

#scoreText {
  text-align: center;
  font-size: 35px;
}</code>```

<canvas id="GameScreen" width="1270px" height="550px"></canvas>```

答:
What happens

In your hitDetect function:

```<code>function hitDetect() {
  for (var iB = 0; iB != clonePos.length; iB++) {
    if (clonePos[iB] > -320 && clonePos[iB] < -280 && charY > 200) {
      charDied();
    }
  }
}
</code>```

You loop over the clonePos array, until iB is equal to the length of that array. If a condition is met (collision), you execute charDied, which, in turn, executes charRevive:

```<code>function charRevive() {
  clonePos = [600];
  // ...
}
</code>```

Meanwhile, the hitDetect loop continues. And at one point (seemingly when you start to increase the speed), it happens that iB is now above 1, which is the new length of clonePos. Now, what happens? Well, you are trapped in an infinite loop:

Lesson to be learned

If you're looping on an Array which can mutate during the loop (and change its length), never use this type of condition:

```<code>i != myArr.length
</code>```

Always prefer a stricter condition if you want your loop to end at some point:

```<code>i < myArr.length
</code>```

And, even better, if looping makes no sense after a condition is met, end this loop by returning. eg:

```<code>function hitDetect() {
  for (var iB = 0; iB < clonePos.length; iB++) {
    if (clonePos[iB] > -320 && clonePos[iB] < -280 && charY > 200) {
      return charDied();
      // Alternatively, if there is other stuff to do after the loop, you can use:
      // break;
    }
  }
}
</code>```

Fixed code

// Commented because does not work in Sandbox
// window.localStorage; //Ignore this line

// Where all my variables have been assigned

var c = document.getElementById("GameScreen");
var ctx = c.getContext("2d");
var charY = 220;
const gravity = 10;
var score = 0;
var time = 0;
var speed = 5;
var cloneID = 0;
var clonePos = [600];
var clonePoints = [0];
var animationBounce = 0;
var jump = 10;
var charDead = 0;
var dataCharY = [];
var dataDisObst = [];
var disObst = 1000;
var lowestLoopDis;
var jumpFactor = 0;
var disDeath;
var AIgames = 1;
var bestScoreAI = 0;

ctx.translate(c.width / 2, c.height / 2);

// Was going to use this for background trees but haven't done it yet

new obj(50, 50, 30, 30);

// Runs most functions

function runAll() {
  if (charDead == 0) {
    clearAll(); //This function runs most of the code
    updateChar();
    createGround();
    updateObj();
    groundDetect();
    updateScore();
    hitDetect();
    addData();
    testBetterAI();
    getDisObst();
    jumpAI();
    removeUnusedObst();
  }
}

// Was going to use this for trees but haven't yet

function obj(x, y, width, height) {
  this.width = width;
  this.height = height;
  this.x = x;
  this.y = y;

  ctx.beginPath();

  ctx = c.getContext("2d");
  ctx.fillStyle = "brown";
  ctx.fillRect(this.x, this.y, this.width, this.height);
  ctx.fillStyle = "green";
  ctx.arc(-293, 150, 50, 0, 2 * Math.PI);
  ctx.fill();
  ctx.stroke();

  this.cloneID = cloneID;
}

new obj(-293, 212, 0, 2 * Math.PI);

// Creates the floor (IKR)

function createGround() {
  ctx.fillStyle = "green";
  ctx.fillRect(-635, 250, c.width, 50);
}

// Creates the character every milisecond (or 10, I can't remember)

function updateChar() {
  ctx.fillStyle = "blue";
  ctx.fillRect(-300, charY - animationBounce, 15, 30);
  ctx.fillStyle = "pink";
  ctx.beginPath();
  ctx.arc(-293, charY - animationBounce - 15, 15, 0, 2 * Math.PI);
  ctx.fill();
  ctx.stroke();
}

// Removes everything in order to be redrawn in new position

function clearAll() {
  ctx.clearRect(-700, -700, 2000, 2000);
}

// Redraws every square / object

function updateObj() {
  for (var i = 0; i < clonePos.length; i++) {
    ctx.fillStyle = "green";
    ctx.fillRect(clonePos[i], 220, 30, 30);
  }
}

// Creates new square (I also decided to rename them half way through with obstacle instead of object)

function createObst() {
  clonePos.push(600);
  cloneID++;
}

// Changes the squares / obstacles position relative to the movement

function moveObst() {
  for (var ii = 0; ii < clonePos.length; ii++) {
    clonePos[ii] -= speed;
  }
}

// Tests to see if the character is on the ground

function groundDetect() {
  if (charY > 220) {
    charY = 220;
  }
}

// Makes gravity actually work

function charGravity() {
  if (charY < 220) {
    charY += gravity;
  }
}

// Updates the score counter text

function updateScore() {
  document.getElementById("scoreText").innerHTML = score;
}

// Gives the character a little bounce when moving

function charBounce() {
  setTimeout(function() {
    animationBounce++;
  }, 100);
  setTimeout(function() {
    animationBounce++;
  }, 200);
  setTimeout(function() {
    animationBounce++;
  }, 300);
  setTimeout(function() {
    animationBounce--;
  }, 400);
  setTimeout(function() {
    animationBounce--;
  }, 500);
  setTimeout(function() {
    animationBounce--;
  }, 600);
}

// Makes the character jump

function charJump() {
  if (charY == 220) {
    jump = 4;

    setTimeout(function() {
      charY -= jump;
    }, 20);
    jump = 8;
    setTimeout(function() {
      charY -= jump;
    }, 40);
    jump = 12;
    setTimeout(function() {
      charY -= jump;
    }, 60);
    jump = 16;
    setTimeout(function() {
      charY -= jump;
    }, 80);
    setTimeout(function() {
      charY -= jump;
    }, 100);
    setTimeout(function() {
      charY -= jump;
    }, 120);
  }
}

// Detects when the character has a hit a square

function hitDetect() {
  for (var iB = 0; iB < clonePos.length; iB++) {
    if (clonePos[iB] > -320 && clonePos[iB] < -280 && charY > 200) {
      return charDied();
    }
  }
}

// Runs when character dies

function charDied() {
  disDeath = disObst;
  charDead = 1;

  charRevive();

  testBetterAI();

  decideAdjustments();
}

// Adds score very interval

function addingScore() {
  if (charDead == 0) {
    score += 100;
  }
}

// Adds to an array that I will use later

function addData() {
  dataCharY.push(charY);
  dataDisObst.push(disObst);
}

// Test to see if one of my AI's (which hasn't been made yet) scores is better than the previous best

function testBetterAI() {
  // Commented because does not work in Sandbox
  // if (score > localStorage.getItem("bestScore")) {
  // }
}

// Calculates the distance to the nearest square / obstacle

function getDisObst() {
  lowestLoopDis = 1000;

  for (var iiA = 0; iiA < clonePos.length; iiA++) {
    if (clonePos[iiA] > -320) {
      if (clonePos[iiA] > 0) {
        if (Math.abs(clonePos[iiA]) < lowestLoopDis) {
          lowestLoopDis = Math.abs(clonePos[iiA]);
        }
      } else {
        if (Math.abs(clonePos[iiA]) < lowestLoopDis) {
          lowestLoopDis = Math.abs(clonePos[iiA]);
        }
      }
    }
  }

  if (lowestLoopDis < disObst) {
    disObst = lowestLoopDis;
  }
}

// Increments the speed of the obstacles / squares and the character

function addSpeed() {
  if (speed < 25) {
    speed++;
  }
}

// Restarts the game

function charRevive() {
  clonePos = [600];
  charDead = 0;
  score = 0;
  time = 0;
  speed = 5;
  AIgames++;
}

// I accidently did this twice, whoops

function testBetterAI() {
  if (score > bestScoreAI) {
    bestScoreAI = score;
  }
}

// Makes the unfinished AI jump when it wants to

function jumpAI() {
  if (disObst <= disDeath + jumpFactor) {
    charJump();
  }
}

// What changes need to be made in order to improve the AI

function decideAdjustments() {
  jumpFactor += Math.floor(Math.random() * 10) - 5;

  if (jumpFactor < 0) {
    jumpFactor = 0;
  }
}

// Removing blocks that are off the screen

function removeUnusedObst() {
  if (clonePos[0] < -650) {
    clonePos.shift();
  }
}

// Intervals here

setInterval(function() {
  time++;
}, 1000);
setInterval(function() {
  runAll();
}, 10);
setInterval(function() {
  moveObst();
}, 50);
setInterval(function() {
  charGravity();
}, 25);
setInterval(function() {
  createObst();
}, 3000);
setInterval(function() {
  charBounce();
}, 650);
setInterval(function() {
  addingScore();
}, 3500);
setInterval(function() {
  addSpeed();
}, 25000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body { text-align: center; }
#GameScreen {
  background-color: CornflowerBlue;
  width: 350px; height: 150px;
}</code>```

<canvas id="GameScreen" width="1270px" height="550px"></canvas>```

Body:
// Commented because does not work in Sandbox
// window.localStorage; //Ignore this line

// Where all my variables have been assigned

var c = document.getElementById("GameScreen");
var ctx = c.getContext("2d");
var charY = 220;
const gravity = 10;
var score = 0;
var time = 0;
var speed = 5;
var cloneID = 0;
var clonePos = [600];
var clonePoints = [0];
var animationBounce = 0;
var jump = 10;
var charDead = 0;
var dataCharY = [];
var dataDisObst = [];
var disObst = 1000;
var lowestLoopDis;
var jumpFactor = 0;
var disDeath;
var AIgames = 1;
var bestScoreAI = 0;

ctx.translate(c.width / 2, c.height / 2);

// Was going to use this for background trees but haven't done it yet

new obj(50, 50, 30, 30);

// Runs most functions

function runAll() {
  if (charDead == 0) {
    clearAll(); //This function runs most of the code
    updateChar();
    createGround();
    updateObj();
    groundDetect();
    updateScore();
    hitDetect();
    addData();
    testBetterAI();
    getDisObst();
    jumpAI();
    removeUnusedObst();
  }
}

// Was going to use this for trees but haven't yet

function obj(x, y, width, height) {
  this.width = width;
  this.height = height;
  this.x = x;
  this.y = y;

  ctx.beginPath();

  ctx = c.getContext("2d");
  ctx.fillStyle = "brown";
  ctx.fillRect(this.x, this.y, this.width, this.height);
  ctx.fillStyle = "green";
  ctx.arc(-293, 150, 50, 0, 2 * Math.PI);
  ctx.fill();
  ctx.stroke();

  this.cloneID = cloneID;
}

new obj(-293, 212, 0, 2 * Math.PI);

// Creates the floor (IKR)

function createGround() {
  ctx.fillStyle = "green";
  ctx.fillRect(-635, 250, c.width, 50);
}

// Creates the character every milisecond (or 10, I can't remember)

function updateChar() {
  ctx.fillStyle = "blue";
  ctx.fillRect(-300, charY - animationBounce, 15, 30);
  ctx.fillStyle = "pink";
  ctx.beginPath();
  ctx.arc(-293, charY - animationBounce - 15, 15, 0, 2 * Math.PI);
  ctx.fill();
  ctx.stroke();
}

// Removes everything in order to be redrawn in new position

function clearAll() {
  ctx.clearRect(-700, -700, 2000, 2000);
}

// Redraws every square / object

function updateObj() {
  for (var i = 0; i != clonePos.length; i++) {
    ctx.fillStyle = "green";
    ctx.fillRect(clonePos[i], 220, 30, 30);
  }
}

// Creates new square (I also decided to rename them half way through with obstacle instead of object)

function createObst() {
  clonePos.push(600);
  cloneID++;
}

// Changes the squares / obstacles position relative to the movement

function moveObst() {
  for (var ii = 0; ii != clonePos.length; ii++) {
    clonePos[ii] -= speed;
  }
}

// Tests to see if the character is on the ground

function groundDetect() {
  if (charY > 220) {
    charY = 220;
  }
}

// Makes gravity actually work

function charGravity() {
  if (charY < 220) {
    charY += gravity;
  }
}

// Updates the score counter text

function updateScore() {
  document.getElementById("scoreText").innerHTML = score;
}

// Gives the character a little bounce when moving

function charBounce() {
  setTimeout(function() {
    animationBounce++;
  }, 100);
  setTimeout(function() {
    animationBounce++;
  }, 200);
  setTimeout(function() {
    animationBounce++;
  }, 300);
  setTimeout(function() {
    animationBounce--;
  }, 400);
  setTimeout(function() {
    animationBounce--;
  }, 500);
  setTimeout(function() {
    animationBounce--;
  }, 600);
}

// Makes the character jump

function charJump() {
  if (charY == 220) {
    jump = 4;

    setTimeout(function() {
      charY -= jump;
    }, 20);
    jump = 8;
    setTimeout(function() {
      charY -= jump;
    }, 40);
    jump = 12;
    setTimeout(function() {
      charY -= jump;
    }, 60);
    jump = 16;
    setTimeout(function() {
      charY -= jump;
    }, 80);
    setTimeout(function() {
      charY -= jump;
    }, 100);
    setTimeout(function() {
      charY -= jump;
    }, 120);
  }
}

// Detects when the character has a hit a square

function hitDetect() {
  for (var iB = 0; iB != clonePos.length; iB++) {
    if (clonePos[iB] > -320 && clonePos[iB] < -280 && charY > 200) {
      charDied();
    }
  }
}

// Runs when character dies

function charDied() {
  disDeath = disObst;
  charDead = 1;

  charRevive();

  testBetterAI();

  decideAdjustments();
}

// Adds score very interval

function addingScore() {
  if (charDead == 0) {
    score += 100;
  }
}

// Adds to an array that I will use later

function addData() {
  dataCharY.push(charY);
  dataDisObst.push(disObst);
}

// Test to see if one of my AI's (which hasn't been made yet) scores is better than the previous best

function testBetterAI() {
  // Commented because does not work in Sandbox
  // if (score > localStorage.getItem("bestScore")) {
  // }
}

// Calculates the distance to the nearest square / obstacle

function getDisObst() {
  lowestLoopDis = 1000;

  for (var iiA = 0; iiA != clonePos.length; iiA++) {
    if (clonePos[iiA] > -320) {
      if (clonePos[iiA] > 0) {
        if (Math.abs(clonePos[iiA]) < lowestLoopDis) {
          lowestLoopDis = Math.abs(clonePos[iiA]);
        }
      } else {
        if (Math.abs(clonePos[iiA]) < lowestLoopDis) {
          lowestLoopDis = Math.abs(clonePos[iiA]);
        }
      }
    }
  }

  if (lowestLoopDis < disObst) {
    disObst = lowestLoopDis;
  }
}

// Increments the speed of the obstacles / squares and the character

function addSpeed() {
  if (speed < 25) {
    speed++;
  }
}

// Restarts the game

function charRevive() {
  clonePos = [600];
  charDead = 0;
  score = 0;
  time = 0;
  speed = 5;
  AIgames++;
}

// I accidently did this twice, whoops

function testBetterAI() {
  if (score > bestScoreAI) {
    bestScoreAI = score;
  }
}

// Makes the unfinished AI jump when it wants to

function jumpAI() {
  if (disObst <= disDeath + jumpFactor) {
    charJump();
  }
}

// What changes need to be made in order to improve the AI

function decideAdjustments() {
  jumpFactor += Math.floor(Math.random() * 10) - 5;

  if (jumpFactor < 0) {
    jumpFactor = 0;
  }
}

// Removing blocks that are off the screen

function removeUnusedObst() {
  if (clonePos[0] < -650) {
    clonePos.shift();
  }
}

// Intervals here

setInterval(function() {
  time++;
}, 1000);
setInterval(function() {
  runAll();
}, 10);
setInterval(function() {
  moveObst();
}, 50);
setInterval(function() {
  charGravity();
}, 25);
setInterval(function() {
  createObst();
}, 3000);
setInterval(function() {
  charBounce();
}, 650);
setInterval(function() {
  addingScore();
}, 3500);
setInterval(function() {
  addSpeed();
}, 25000);

#GameScreen {
  background-color: CornflowerBlue;
}

#scoreText {
  text-align: center;
  font-size: 35px;
}

<canvas id="GameScreen" width="1270px" height="550px"></canvas>

Body:
What happens

In your hitDetect function:

function hitDetect() {
  for (var iB = 0; iB != clonePos.length; iB++) {
    if (clonePos[iB] > -320 && clonePos[iB] < -280 && charY > 200) {
      charDied();
    }
  }
}

You loop over the clonePos array, until iB is equal to the length of that array. If a condition is met (collision), you execute charDied, which, in turn, executes charRevive:

function charRevive() {
  clonePos = [600];
  // ...
}

Meanwhile, the hitDetect loop continues. And at one point (seemingly when you start to increase the speed), it happens that iB is now above 1, which is the new length of clonePos. Now, what happens? Well, you are trapped in an infinite loop:

Lesson to be learned

If you're looping on an Array which can mutate during the loop (and change its length), never use this type of condition:

i != myArr.length

Always prefer a stricter condition if you want your loop to end at some point:

i < myArr.length

And, even better, if looping makes no sense after a condition is met, end this loop by returning. eg:

function hitDetect() {
  for (var iB = 0; iB < clonePos.length; iB++) {
    if (clonePos[iB] > -320 && clonePos[iB] < -280 && charY > 200) {
      return charDied();
      // Alternatively, if there is other stuff to do after the loop, you can use:
      // break;
    }
  }
}

Fixed code

// Commented because does not work in Sandbox
// window.localStorage; //Ignore this line

// Where all my variables have been assigned

var c = document.getElementById("GameScreen");
var ctx = c.getContext("2d");
var charY = 220;
const gravity = 10;
var score = 0;
var time = 0;
var speed = 5;
var cloneID = 0;
var clonePos = [600];
var clonePoints = [0];
var animationBounce = 0;
var jump = 10;
var charDead = 0;
var dataCharY = [];
var dataDisObst = [];
var disObst = 1000;
var lowestLoopDis;
var jumpFactor = 0;
var disDeath;
var AIgames = 1;
var bestScoreAI = 0;

ctx.translate(c.width / 2, c.height / 2);

// Was going to use this for background trees but haven't done it yet

new obj(50, 50, 30, 30);

// Runs most functions

function runAll() {
  if (charDead == 0) {
    clearAll(); //This function runs most of the code
    updateChar();
    createGround();
    updateObj();
    groundDetect();
    updateScore();
    hitDetect();
    addData();
    testBetterAI();
    getDisObst();
    jumpAI();
    removeUnusedObst();
  }
}

// Was going to use this for trees but haven't yet

function obj(x, y, width, height) {
  this.width = width;
  this.height = height;
  this.x = x;
  this.y = y;

  ctx.beginPath();

  ctx = c.getContext("2d");
  ctx.fillStyle = "brown";
  ctx.fillRect(this.x, this.y, this.width, this.height);
  ctx.fillStyle = "green";
  ctx.arc(-293, 150, 50, 0, 2 * Math.PI);
  ctx.fill();
  ctx.stroke();

  this.cloneID = cloneID;
}

new obj(-293, 212, 0, 2 * Math.PI);

// Creates the floor (IKR)

function createGround() {
  ctx.fillStyle = "green";
  ctx.fillRect(-635, 250, c.width, 50);
}

// Creates the character every milisecond (or 10, I can't remember)

function updateChar() {
  ctx.fillStyle = "blue";
  ctx.fillRect(-300, charY - animationBounce, 15, 30);
  ctx.fillStyle = "pink";
  ctx.beginPath();
  ctx.arc(-293, charY - animationBounce - 15, 15, 0, 2 * Math.PI);
  ctx.fill();
  ctx.stroke();
}

// Removes everything in order to be redrawn in new position

function clearAll() {
  ctx.clearRect(-700, -700, 2000, 2000);
}

// Redraws every square / object

function updateObj() {
  for (var i = 0; i < clonePos.length; i++) {
    ctx.fillStyle = "green";
    ctx.fillRect(clonePos[i], 220, 30, 30);
  }
}

// Creates new square (I also decided to rename them half way through with obstacle instead of object)

function createObst() {
  clonePos.push(600);
  cloneID++;
}

// Changes the squares / obstacles position relative to the movement

function moveObst() {
  for (var ii = 0; ii < clonePos.length; ii++) {
    clonePos[ii] -= speed;
  }
}

// Tests to see if the character is on the ground

function groundDetect() {
  if (charY > 220) {
    charY = 220;
  }
}

// Makes gravity actually work

function charGravity() {
  if (charY < 220) {
    charY += gravity;
  }
}

// Updates the score counter text

function updateScore() {
  document.getElementById("scoreText").innerHTML = score;
}

// Gives the character a little bounce when moving

function charBounce() {
  setTimeout(function() {
    animationBounce++;
  }, 100);
  setTimeout(function() {
    animationBounce++;
  }, 200);
  setTimeout(function() {
    animationBounce++;
  }, 300);
  setTimeout(function() {
    animationBounce--;
  }, 400);
  setTimeout(function() {
    animationBounce--;
  }, 500);
  setTimeout(function() {
    animationBounce--;
  }, 600);
}

// Makes the character jump

function charJump() {
  if (charY == 220) {
    jump = 4;

    setTimeout(function() {
      charY -= jump;
    }, 20);
    jump = 8;
    setTimeout(function() {
      charY -= jump;
    }, 40);
    jump = 12;
    setTimeout(function() {
      charY -= jump;
    }, 60);
    jump = 16;
    setTimeout(function() {
      charY -= jump;
    }, 80);
    setTimeout(function() {
      charY -= jump;
    }, 100);
    setTimeout(function() {
      charY -= jump;
    }, 120);
  }
}

// Detects when the character has a hit a square

function hitDetect() {
  for (var iB = 0; iB < clonePos.length; iB++) {
    if (clonePos[iB] > -320 && clonePos[iB] < -280 && charY > 200) {
      return charDied();
    }
  }
}

// Runs when character dies

function charDied() {
  disDeath = disObst;
  charDead = 1;

  charRevive();

  testBetterAI();

  decideAdjustments();
}

// Adds score very interval

function addingScore() {
  if (charDead == 0) {
    score += 100;
  }
}

// Adds to an array that I will use later

function addData() {
  dataCharY.push(charY);
  dataDisObst.push(disObst);
}

// Test to see if one of my AI's (which hasn't been made yet) scores is better than the previous best

function testBetterAI() {
  // Commented because does not work in Sandbox
  // if (score > localStorage.getItem("bestScore")) {
  // }
}

// Calculates the distance to the nearest square / obstacle

function getDisObst() {
  lowestLoopDis = 1000;

  for (var iiA = 0; iiA < clonePos.length; iiA++) {
    if (clonePos[iiA] > -320) {
      if (clonePos[iiA] > 0) {
        if (Math.abs(clonePos[iiA]) < lowestLoopDis) {
          lowestLoopDis = Math.abs(clonePos[iiA]);
        }
      } else {
        if (Math.abs(clonePos[iiA]) < lowestLoopDis) {
          lowestLoopDis = Math.abs(clonePos[iiA]);
        }
      }
    }
  }

  if (lowestLoopDis < disObst) {
    disObst = lowestLoopDis;
  }
}

// Increments the speed of the obstacles / squares and the character

function addSpeed() {
  if (speed < 25) {
    speed++;
  }
}

// Restarts the game

function charRevive() {
  clonePos = [600];
  charDead = 0;
  score = 0;
  time = 0;
  speed = 5;
  AIgames++;
}

// I accidently did this twice, whoops

function testBetterAI() {
  if (score > bestScoreAI) {
    bestScoreAI = score;
  }
}

// Makes the unfinished AI jump when it wants to

function jumpAI() {
  if (disObst <= disDeath + jumpFactor) {
    charJump();
  }
}

// What changes need to be made in order to improve the AI

function decideAdjustments() {
  jumpFactor += Math.floor(Math.random() * 10) - 5;

  if (jumpFactor < 0) {
    jumpFactor = 0;
  }
}

// Removing blocks that are off the screen

function removeUnusedObst() {
  if (clonePos[0] < -650) {
    clonePos.shift();
  }
}

// Intervals here

setInterval(function() {
  time++;
}, 1000);
setInterval(function() {
  runAll();
}, 10);
setInterval(function() {
  moveObst();
}, 50);
setInterval(function() {
  charGravity();
}, 25);
setInterval(function() {
  createObst();
}, 3000);
setInterval(function() {
  charBounce();
}, 650);
setInterval(function() {
  addingScore();
}, 3500);
setInterval(function() {
  addSpeed();
}, 25000);

body { text-align: center; }
#GameScreen {
  background-color: CornflowerBlue;
  width: 350px; height: 150px;
}

<div id="scoreText"></div>
<canvas id="GameScreen" width="1270px" height="550px"></canvas>


问:
How do I set focus to a text box in Blazor
How do I set focus to a textbox in Blazor? So far the only way we have found is with JavaScript.</p>

答:
There is no other way to do it... You can use JSInterop to do this, as follows:

```<code> <input type="text" @ref="myref"/>

 @code {

    private ElementReference myref;
    [Inject] IJSRuntime JSRuntime { get; set; }

     protected override async Task OnAfterRenderAsync(bool firstRender)
    {
         if (firstRender)
        {
            await
        JSRuntime.InvokeVoidAsync("exampleJsFunctions.focusElement", myref);
        }
   }
 }
</code>```

JavaScript

```<code><script>

    window.exampleJsFunctions =
    {
        focusElement: function (element) {
           element.focus();
        }
    };
</script>
</code>```

Hope this helps...

Body:
There is no other way to do it... You can use JSInterop to do this, as follows:

 <input type="text" @ref="myref"/>

 @code {

    private ElementReference myref;
    [Inject] IJSRuntime JSRuntime { get; set; }

     protected override async Task OnAfterRenderAsync(bool firstRender)
    {
         if (firstRender)
        {
            await
        JSRuntime.InvokeVoidAsync("exampleJsFunctions.focusElement", myref);
        }
   }
 }

JavaScript

<script>

    window.exampleJsFunctions =
    {
        focusElement: function (element) {
           element.focus();
        }
    };
</script>

Hope this helps...


问:
perl two consecutive back ticked shell command do not run
I am trying to write perl script for managing amazon ec2 instances. In part of my code, I have two shell commands, and when I invoke them, the first runs but not the second. I cannot seem to find a good explanation for this. Here is the code:

```<code>$run_instances = 'ec2-run-instances ami-8e1fece7 -k mykey -t t1.micro';
$outp = `$run_instances`;
$outp =~ /INSTANCE\s+(i-\w+)\s/;
$instance_id = $1;
$describe_instances = "ec2-describe-instances $instance_id";
$outp = `$describe_instances`;
$outp =~ /(ec2-(\d+-\d+-\d+-\d+).\S+)/;
</code>```

The problem is $outp here has the output of $run_instances. For some time I could not understand why I was getting the wrong output; then I realised that $describe_instances command does not run.

I looked at the value of $describe_instances, called that from the Linux shell, and it worked fine. I called it from another Perl script, and it worked fine.

Then I gave $outp the output that is captured when $run_instances runs ($outp = "INSTANCE ......"). It worked, so I got the idea that somehow when these two commands run consecutively the second does not run.

One more thing to note is that when I put above code in a loop every time $run_instances works but $describe_instances does not.

I would be really happy if you could provide some light on this :)

Thank you

答:
Your program has a few red flags. I discuss them below and at the end suggest a better way to write your code.

Red Flag 1

The code from your question attempts to execute external commands with backticks and assumes success. You should always check the status of any call to the operating system. A failed `$command`—also known as qx// or readpipe—makes itself known in one or more ways depending on whether the command executed and failed or whether attempted execution of the command failed:

The value of the special variable $? is non-zero.

In cases of failed execution

the special variable $! contains a description of the failure.

the operator returns the undefined value in scalar context or the empty list in list context.

With Perl, `$command` executes a subshell in order to execute $command, so the subshell may be the program that executes and fails, e.g., for bad command syntax.

Exactly one command in the example below succeeds on my machine.

```<code>#! /usr/bin/env perl

use strict;
use warnings;

my @commands = (
  "bad syntax (",
  "does-not-exist",
  "/etc/passwd",
  "perl --no-such-option",
  "perl -le 'print q(Hello world)'",
);

foreach my $c (@commands) {
  print "Capturing output of command $c...\n";
  my $output = `$c`;

  if ($? == 0) {
    print "  - command executed successfully!\n";
  }
  elsif ($? == -1) {
    print "  - command failed to execute: \$!=$!\n";
  }
  else {
    print "  - command exited with status " . ($? >> 8) . "\n";
  }

  print "  - value of \$output is ",
        (defined $output ? "" : "un"), "defined\n\n";
}
</code>```

Output:

```Capturing output of command bad syntax (...
sh: Syntax error: "(" unexpected
  - command exited with status 2
  - value of $output is defined

Capturing output of command does-not-exist...
Can't exec "does-not-exist": No such file or directory at ./runcmds line 16.
  - command failed to execute: $!=No such file or directory
  - value of $output is undefined

Capturing output of command /etc/passwd...
Can't exec "/etc/passwd": Permission denied at ./runcmds line 16.
  - command failed to execute: $!=Permission denied
  - value of $output is undefined

Capturing output of command perl --no-such-option...
Unrecognized switch: --no-such-option  (-h will show valid options).
  - command exited with status 29
  - value of $output is defined

Capturing output of command perl -le 'print q(Hello world)'...
  - command executed successfully!
  - value of $output is defined```

Red Flag 2

Note for example the line of output

```Can't exec "does-not-exist": No such file or directory at ./runcmds line 16.```

I didn't write the code that generated this warning. Instead, it happened automatically because I enabled the warnings pragma with the line use warnings. Had you enabled warnings, Perl would have already given you at least a hint about the cause of your problem, so I assume you didn't enable warnings.

This is another red flag. Warnings are there to help you. Always enable them for any non-trivial program.

Red Flag 3

Finally, you're using regex capture-variable $1 unconditionally, and this habit will lead to surprising bugs when the match fails and you get a captured value from different match. You should always wrap uses of $1, $2, and friends inside a conditional, e.g.,

```<code>if (/pa(tte)rn/) {
  do_something_with $1;
}
</code>```

Recommended Fixes

Near the top of your code just after the shebang line, you should immediately add the line

```<code>use warnings;
</code>```

I'd also recommend

```<code>use strict;
</code>```

but that will likely require more work to clean up your code. We're here to help you understand and overcome any issues you find in that worthwhile effort.

Use output_of below to capture a command's output or die with an appropriate diagnostic.

```<code>sub output_of {
  my($cmd) = @_;
  my $output = `$cmd`;
  return $output if $? == 0;

  if ($? == -1) {
    die "$0: $cmd failed to execute: $!\n";
  }
  elsif ($? & 127) {
    my $signal = $? & 127;
    my $core = ($? & 128) ? ", core dumped" : "";
    die "$0: $cmd died with signal $signal$core\n";
  }
  else {
    die "$0: $cmd exited with status " . ($? >> 8) . "\n";
  }
}
</code>```

The section of code from your question becomes

```<code>my $output;
$output = output_of 'ec2-run-instances ami-8e1fece7 -k mykey -t t1.micro';
if ($output =~ /INSTANCE\s+(i-\w+)\s/) {
  my $instance_id = $1;

  $output = output_of "ec2-describe-instances $instance_id";
  if ($output =~ /(ec2-(\d+-\d+-\d+-\d+).\S+)/) {
    print "$0: found instance $2\n";  # or whatever
  }
  else {
    die "$0: no ec2-IP in ec2-describe-instances output:\n$output";
  }
}
else {
  die "$0: no INSTANCE in ec2-run-instances output:\n$output";
}
</code>```

With these changes, your code will supply on the standard error diagnostics for all failure modes in processing output from ec2-run-instances and ec2-describe-instances instead of leaving you to wonder what went wrong.

Body:
I am trying to write perl script for managing amazon ec2 instances. In part of my code, I have two shell commands, and when I invoke them, the first runs but not the second. I cannot seem to find a good explanation for this. Here is the code:

$run_instances = 'ec2-run-instances ami-8e1fece7 -k mykey -t t1.micro';
$outp = `$run_instances`;
$outp =~ /INSTANCE\s+(i-\w+)\s/;
$instance_id = $1;
$describe_instances = "ec2-describe-instances $instance_id";
$outp = `$describe_instances`;
$outp =~ /(ec2-(\d+-\d+-\d+-\d+).\S+)/;

The problem is $outp here has the output of $run_instances. For some time I could not understand why I was getting the wrong output; then I realised that $describe_instances command does not run.

I looked at the value of $describe_instances, called that from the Linux shell, and it worked fine. I called it from another Perl script, and it worked fine.

Then I gave $outp the output that is captured when $run_instances runs ($outp = "INSTANCE ......"). It worked, so I got the idea that somehow when these two commands run consecutively the second does not run.

One more thing to note is that when I put above code in a loop every time $run_instances works but $describe_instances does not.

I would be really happy if you could provide some light on this :)

Thank you

Body:
Your program has a few red flags. I discuss them below and at the end suggest a better way to write your code.

Red Flag 1

The code from your question attempts to execute external commands with backticks and assumes success. You should always check the status of any call to the operating system. A failed `$command`—also known as qx// or readpipe—makes itself known in one or more ways depending on whether the command executed and failed or whether attempted execution of the command failed:

The value of the special variable $? is non-zero.

In cases of failed execution

the special variable $! contains a description of the failure.

the operator returns the undefined value in scalar context or the empty list in list context.

With Perl, `$command` executes a subshell in order to execute $command, so the subshell may be the program that executes and fails, e.g., for bad command syntax.

Exactly one command in the example below succeeds on my machine.

#! /usr/bin/env perl

use strict;
use warnings;

my @commands = (
  "bad syntax (",
  "does-not-exist",
  "/etc/passwd",
  "perl --no-such-option",
  "perl -le 'print q(Hello world)'",
);

foreach my $c (@commands) {
  print "Capturing output of command $c...\n";
  my $output = `$c`;

  if ($? == 0) {
    print "  - command executed successfully!\n";
  }
  elsif ($? == -1) {
    print "  - command failed to execute: \$!=$!\n";
  }
  else {
    print "  - command exited with status " . ($? >> 8) . "\n";
  }

  print "  - value of \$output is ",
        (defined $output ? "" : "un"), "defined\n\n";
}

Output:

Capturing output of command bad syntax (...
sh: Syntax error: "(" unexpected
  - command exited with status 2
  - value of $output is defined

Capturing output of command does-not-exist...
Can't exec "does-not-exist": No such file or directory at ./runcmds line 16.
  - command failed to execute: $!=No such file or directory
  - value of $output is undefined

Capturing output of command /etc/passwd...
Can't exec "/etc/passwd": Permission denied at ./runcmds line 16.
  - command failed to execute: $!=Permission denied
  - value of $output is undefined

Capturing output of command perl --no-such-option...
Unrecognized switch: --no-such-option  (-h will show valid options).
  - command exited with status 29
  - value of $output is defined

Capturing output of command perl -le 'print q(Hello world)'...
  - command executed successfully!
  - value of $output is defined

Red Flag 2

Note for example the line of output

Can't exec "does-not-exist": No such file or directory at ./runcmds line 16.

I didn't write the code that generated this warning. Instead, it happened automatically because I enabled the warnings pragma with the line use warnings. Had you enabled warnings, Perl would have already given you at least a hint about the cause of your problem, so I assume you didn't enable warnings.

This is another red flag. Warnings are there to help you. Always enable them for any non-trivial program.

Red Flag 3

Finally, you're using regex capture-variable $1 unconditionally, and this habit will lead to surprising bugs when the match fails and you get a captured value from different match. You should always wrap uses of $1, $2, and friends inside a conditional, e.g.,

if (/pa(tte)rn/) {
  do_something_with $1;
}

Recommended Fixes

Near the top of your code just after the shebang line, you should immediately add the line

use warnings;

I'd also recommend

use strict;

but that will likely require more work to clean up your code. We're here to help you understand and overcome any issues you find in that worthwhile effort.

Use output_of below to capture a command's output or die with an appropriate diagnostic.

sub output_of {
  my($cmd) = @_;
  my $output = `$cmd`;
  return $output if $? == 0;

  if ($? == -1) {
    die "$0: $cmd failed to execute: $!\n";
  }
  elsif ($? & 127) {
    my $signal = $? & 127;
    my $core = ($? & 128) ? ", core dumped" : "";
    die "$0: $cmd died with signal $signal$core\n";
  }
  else {
    die "$0: $cmd exited with status " . ($? >> 8) . "\n";
  }
}

The section of code from your question becomes

my $output;
$output = output_of 'ec2-run-instances ami-8e1fece7 -k mykey -t t1.micro';
if ($output =~ /INSTANCE\s+(i-\w+)\s/) {
  my $instance_id = $1;

  $output = output_of "ec2-describe-instances $instance_id";
  if ($output =~ /(ec2-(\d+-\d+-\d+-\d+).\S+)/) {
    print "$0: found instance $2\n";  # or whatever
  }
  else {
    die "$0: no ec2-IP in ec2-describe-instances output:\n$output";
  }
}
else {
  die "$0: no INSTANCE in ec2-run-instances output:\n$output";
}

With these changes, your code will supply on the standard error diagnostics for all failure modes in processing output from ec2-run-instances and ec2-describe-instances instead of leaving you to wonder what went wrong.


问:
Convert date/time format from Etc/GMT to ISO
I need to convert date/time values.

For example I want to convert this "2019-11-21 09:53:10 Etc/GMT" to a value with the same format as this "2020-02-13T15:24:47.977Z".

If you can provide the resulting equivalent value of the given example, I can make that as reference so I can already find the correct code for the conversion.

Or else if you can provide the exact javascript code for the conversion, that is better. I am using 'moment' and 'moment-timezone'.

答:
As commented by Nitesh in his answer, Etc/GMT is the same as GMT when the offset is zero or GMT+0. If I have realized this at the beginning, I may not have ask this question.

I've tried the following, and they results with "2019-11-21T09:53:10.000Z".

```<code>    let date1 = new Date('2019 11 21 09:53:10 GMT+0');
    console.log(date1.toISOString());

    let date2 = new Date('2019 11 21 09:53:10 GMT');
    console.log(date2.toISOString());

    let date3 = new Date('11/21/2019 09:53:10 GMT+0000');
    console.log(date3.toISOString());

    let date4 = new Date('11/21/2019 09:53:10 GMT');
    console.log(date4.toISOString());
</code>```

The conversion will not work if I use my original sample value which contains '-' and 'Etc/'.

The following will also results to "2019-11-21T09:53:10Z"

```<code>    let date5 = moment.tz("2019-11-21 09:53:10", "Etc/GMT+0");
    console.log(date5.format());

    let date6 = moment.tz("2019-11-21 09:53:10", "Etc/GMT+0");
    console.log(date6.utc().format());

    let date7 = moment.tz("2019-11-21 09:53:10", "Etc/GMT");
    console.log(date7.format());

    let date8 = moment.tz("2019-11-21 09:53:10", "Etc/GMT");
    console.log(date8.utc().format());
</code>```

I did not find any solution that does not alter the original value. So I will need to modify the original value first before creating the Date object.

```<code>    let a = "2019-11-21 09:53:10 Etc/GMT";  // sample value
    let b = a.replace(/-/g, " ").replace("Etc/", ""); // result: "2019 11 21 09:53:10 GMT"
    let c = new Date(b);
    console.log(c.toISOString()); // 2019-11-21T09:53:10.000Z
</code>```

Alternatively, without creating a new Date object is also acceptable to me.

```<code>    let d = "2019-11-21 09:53:10 Etc/GMT";  // sample value
    let b = d.replace(" Etc/GMT", "Z").replace(" ", "T"); // result: "2019-11-21T09:53:10Z"
    console.log(b);
</code>```

Body:
As commented by Nitesh in his answer, Etc/GMT is the same as GMT when the offset is zero or GMT+0. If I have realized this at the beginning, I may not have ask this question.

I've tried the following, and they results with "2019-11-21T09:53:10.000Z".

    let date1 = new Date('2019 11 21 09:53:10 GMT+0');
    console.log(date1.toISOString());

    let date2 = new Date('2019 11 21 09:53:10 GMT');
    console.log(date2.toISOString());

    let date3 = new Date('11/21/2019 09:53:10 GMT+0000');
    console.log(date3.toISOString());

    let date4 = new Date('11/21/2019 09:53:10 GMT');
    console.log(date4.toISOString());

The conversion will not work if I use my original sample value which contains '-' and 'Etc/'.

The following will also results to "2019-11-21T09:53:10Z"

    let date5 = moment.tz("2019-11-21 09:53:10", "Etc/GMT+0");
    console.log(date5.format());

    let date6 = moment.tz("2019-11-21 09:53:10", "Etc/GMT+0");
    console.log(date6.utc().format());

    let date7 = moment.tz("2019-11-21 09:53:10", "Etc/GMT");
    console.log(date7.format());

    let date8 = moment.tz("2019-11-21 09:53:10", "Etc/GMT");
    console.log(date8.utc().format());

I did not find any solution that does not alter the original value. So I will need to modify the original value first before creating the Date object.

    let a = "2019-11-21 09:53:10 Etc/GMT";  // sample value
    let b = a.replace(/-/g, " ").replace("Etc/", ""); // result: "2019 11 21 09:53:10 GMT"
    let c = new Date(b);
    console.log(c.toISOString()); // 2019-11-21T09:53:10.000Z

Alternatively, without creating a new Date object is also acceptable to me.

    let d = "2019-11-21 09:53:10 Etc/GMT";  // sample value
    let b = d.replace(" Etc/GMT", "Z").replace(" ", "T"); // result: "2019-11-21T09:53:10Z"
    console.log(b);


问:
Bootstrap 4: Add an input field in a popover
I would like to add an input field inside a popover using Bootstrap 4.

The following code doesn't work. The popover is empty and the input field is not rendered as it should.

HTML

<button
    type="button"
    class="btn btn-secondary"
    data-toggle="popover"
    data-html="true"
    data-container="body"
    data-content='
    <input type="text" value="my input value">
    '>
    Popover
</button>
```

<p><strong>JS</strong></p>

<pre class="lang-js prettyprint-override"><code>$(function () {
    $('[data-toggle="popover"]').popover({
        delay: {
            show: 100
        }
    })
})
</code>```

How can I make this work?

答:
seems to work if you move it out of the html and into the js.

```<code><button
    type="button"
    class="btn btn-secondary"
    data-toggle="popover"
    data-container="body">
    Popover
</button>

$(function () {
    $('[data-toggle="popover"]').popover({
        delay: {
            show: 100
        },
         html: true,
         sanitize: false,
         content: '<input type="text" value="my input value">'
    })
})
</code>```

https://jsfiddle.net/mkz2qhxu/

Body:
I would like to add an input field inside a popover using Bootstrap 4.

The following code doesn't work. The popover is empty and the input field is not rendered as it should.

HTML

<button
    type="button"
    class="btn btn-secondary"
    data-toggle="popover"
    data-html="true"
    data-container="body"
    data-content='
    <input type="text" value="my input value">
    '>
    Popover
</button>

JS

$(function () {
    $('[data-toggle="popover"]').popover({
        delay: {
            show: 100
        }
    })
})

How can I make this work?

Body:
seems to work if you move it out of the html and into the js.

<button
    type="button"
    class="btn btn-secondary"
    data-toggle="popover"
    data-container="body">
    Popover
</button>

$(function () {
    $('[data-toggle="popover"]').popover({
        delay: {
            show: 100
        },
         html: true,
         sanitize: false,
         content: '<input type="text" value="my input value">'
    })
})

https://jsfiddle.net/mkz2qhxu/


问:
How to manual trigger close ng-bootstrap popover
How to set the popover not to close automatically on blur?
I want to only manually close this popover

https://stackblitz.com/edit/angular-xt18mj

Any suggestions?

答:
You need to add this : [autoClose]="false"

Example :

```<code><button type="button" class="btn mr-2" placement="bottom" [autoClose]="false"
        ngbPopover="Vivamus sagittis lacus vel augue laoreet rutrum faucibus." popoverTitle="Popover on bottom">
  button 1
</button>
</code>```

For more information : Documentation

Body:
You need to add this : [autoClose]="false"

Example :

<button type="button" class="btn mr-2" placement="bottom" [autoClose]="false"
        ngbPopover="Vivamus sagittis lacus vel augue laoreet rutrum faucibus." popoverTitle="Popover on bottom">
  button 1
</button>

For more information : Documentation


问:
functionality of django blog
Can any one please explain me the functionality of this blog APP, https://github.com/nathanborror/django-basic-apps

What is category and why is that a Mamy to Many field with POSt what is the concept of this blog App

答:
You can categorize your blog posts

For example you can create categories: Life, Career, Hobby
And then you can associate the blog posts to the categories (many of them)

You can look at my blog, to understand what I mean (categories are on the right):

http://b-fil.com/blog/

Title: functionality of django blog


问:
SeriLog MongoDB databaseName is null
I am trying to write to a MongoDB hosted locally using Serilog.

I'm getting an error when trying to start the application

ArgumentNullException: Value cannot be null. (Parameter 'databaseName')
MongoDB.Driver.Core.Misc.Ensure.IsNotNull(T value, string paramName)

My Serilog code is

```<code>WriteTo.MongoDB(databaseUrl: "mongodb://##.##.#.#:#####/", collectionName: "TDSlog")
</code>```

答:
I figured it out :
the database name is what comes after the databaseURL (as opposed to just using a collection name)

I changed my writeTo code to

```<code>.WriteTo.MongoDB(databaseUrl: "mongodb://10.60.1.15:27017/TDS", collectionName: "TDSlog")
</code>```

and now everything is working fine.

Title: SeriLog MongoDB databaseName is null

Body:
I am trying to write to a MongoDB hosted locally using Serilog.

I'm getting an error when trying to start the application

ArgumentNullException: Value cannot be null. (Parameter 'databaseName')
MongoDB.Driver.Core.Misc.Ensure.IsNotNull(T value, string paramName)

My Serilog code is

WriteTo.MongoDB(databaseUrl: "mongodb://##.##.#.#:#####/", collectionName: "TDSlog")

Body:
I figured it out :
the database name is what comes after the databaseURL (as opposed to just using a collection name)

I changed my writeTo code to

.WriteTo.MongoDB(databaseUrl: "mongodb://10.60.1.15:27017/TDS", collectionName: "TDSlog")

and now everything is working fine.


问:
Mongoose not querying
I just recently migrated my DB to Atlas. After mongoose.connect I successfully get the promise returned and am connected to my DB.

However, if I do User.find({}).then(users=>{res.json(users)}) I do not get any users returned (empty array) (This all worked prior to migrating)

User Schema

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

// Create Schema
const UserSchema = new Schema({
  email: {
    type: String
  }
});

module.exports = User = mongoose.model(
  "User",
  UserSchema.plugin(require("mongoose-autopopulate"))
);
```

If I query using MongoShell directly

db.getCollection("users").find({})

I get the expected results. I am not really sure how I should isolate the issue on my local server side.

I double checked my connection string and that is correct.

答:
I contact Atlas and even though I was connected successfully to my DB the connection string was incorrect. </p>

<p>Atlas will display the connection string to use, but in fact, it was not the correct one to use. The support team helped me resolve what is actually should be. I migrated from mLab and I was still needing to use the name of my mLab DB name. </p>

Title: Mongoose not querying

Body:
I just recently migrated my DB to Atlas. After mongoose.connect I successfully get the promise returned and am connected to my DB.

However, if I do User.find({}).then(users=>{res.json(users)}) I do not get any users returned (empty array) (This all worked prior to migrating)

User Schema

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

// Create Schema
const UserSchema = new Schema({
  email: {
    type: String
  }
});

module.exports = User = mongoose.model(
  "User",
  UserSchema.plugin(require("mongoose-autopopulate"))
);

If I query using MongoShell directly

db.getCollection("users").find({})

I get the expected results. I am not really sure how I should isolate the issue on my local server side.

I double checked my connection string and that is correct.

Body:
I contact Atlas and even though I was connected successfully to my DB the connection string was incorrect.

Atlas will display the connection string to use, but in fact, it was not the correct one to use. The support team helped me resolve what is actually should be. I migrated from mLab and I was still needing to use the name of my mLab DB name.