问:
Why the elements cannot be add in this stack?
I have this stack, and the elements of type NAMES(char), I'm trying to print all of the names of the array below (names) but I can't. Idk if the problem is in the STACK() function.

```<code>#define TAMMAX 30

typedef char NAMES[TAMMAX];

struct stack{
    int nItems;
    int capacity;
    NAMES *names;
};
typedef struct stack Stack;

bool stack(Stack *st, NAMES *name){

    if (st->capacity== st->nItems){
        return false;
    }

    strcpy(st->names[st->nItems], *name);

    st->nItems++;

    return true;

}

int main(){

Stack *st;

 NAMES *names[] = {
        {"James"},
        {"Kimberly"},
        {"John"},
    };

    int nNames= sizeof(names) / sizeof(Stack);

    for (int i = 0; i < nNames; i++){
        stack(st, names[i]);
    }

    printStack(st);

  return 0;
}
</code>```

I have these warnings, I don't know how to fix them. The output of the code just print the first name of the array names: James.

```<code>stack.c:97:9: warning: braces around scalar initializer
   97 |      {"James"},
      |         ^
stack.c:97:9: note: (near initialization for 'postagens[0]')
stack.c:97:10: warning: initialization of 'char (*)[50]' from incompatible pointer type 'char *' [-Wincompatible-pointer-types]
   97 |         {"Kimberly"},
      |          ^~~~~~~~~~~
stack.c:97:10: note: (near initialization for 'postagens[0]')
stack.c:98:9: warning: braces around scalar initializer
   98 |         {"John"},
      |         ^
</code>```

Body:
I have this stack, and the elements of type NAMES(char), I'm trying to print all of the names of the array below (names) but I can't. Idk if the problem is in the STACK() function.

#define TAMMAX 30

typedef char NAMES[TAMMAX];

struct stack{
    int nItems;
    int capacity;
    NAMES *names;
};
typedef struct stack Stack;

bool stack(Stack *st, NAMES *name){

    if (st->capacity== st->nItems){
        return false;
    }

    strcpy(st->names[st->nItems], *name);

    st->nItems++;

    return true;

}

int main(){

Stack *st;

 NAMES *names[] = {
        {"James"},
        {"Kimberly"},
        {"John"},
    };

    int nNames= sizeof(names) / sizeof(Stack);

    for (int i = 0; i < nNames; i++){
        stack(st, names[i]);
    }

    printStack(st);

  return 0;
}

I have these warnings, I don't know how to fix them. The output of the code just print the first name of the array names: James.

stack.c:97:9: warning: braces around scalar initializer
   97 |      {"James"},
      |         ^
stack.c:97:9: note: (near initialization for 'postagens[0]')
stack.c:97:10: warning: initialization of 'char (*)[50]' from incompatible pointer type 'char *' [-Wincompatible-pointer-types]
   97 |         {"Kimberly"},
      |          ^~~~~~~~~~~
stack.c:97:10: note: (near initialization for 'postagens[0]')
stack.c:98:9: warning: braces around scalar initializer
   98 |         {"John"},
      |         ^


来源: stackexchange

问:
Will JWT token from "sign in with apple" always contain email field if email scope is specified?
I am wondering whether I can rely on email field in Apple's JWT identityToken being present all the time if I specify email scope?

I need something to be able to identify person. Email would be great but I am not sure if this field will always be present in that token.

Thank you

ContentLicense: CC BY-SA 4.0


问:
use of include between two one-to-one related entities
when performing a query of table B including the data from table A, the entity within the other is obtained several times

```<code>[HttpGet("{id}")]
public ActionResult GetById(int id)
{
  using(var db=new ExampleContext())
  {
    var data = db.TableBs.Include(x => x.TableA).FirstOrDefault(x => x.Id == id);
    return Ok(data);
  }
}
</code>```

Image behavior

when returning you get the error: System.Text.Json.JsonException: A possible object cycle was detected. This can either be due to a cycle or if the object depth is larger than the maximum allowed...

Models

```<code>public partial class TableA
{
    public int Id { get; set; }
    public string? Item { get; set; }
    public virtual TableB? TableB { get; set; }
}
public partial class TableB
{
    public int Id { get; set; }
    public string? Title { get; set; }
    public virtual TableA TableA { get; set; } = null!;
}
</code>```

Tables DB

```<code>create table TableA(
Id int primary key identity(1,1),
Item varchar(10)
);
create table TableB(
Id int primary key,
Title varchar(10)
constraint FK_TableA_TableB foreign key (Id) references TableA(Id)
);
</code>```

Body:
when performing a query of table B including the data from table A, the entity within the other is obtained several times

[HttpGet("{id}")]
public ActionResult GetById(int id)
{
  using(var db=new ExampleContext())
  {
    var data = db.TableBs.Include(x => x.TableA).FirstOrDefault(x => x.Id == id);
    return Ok(data);
  }
}

Image behavior

when returning you get the error: System.Text.Json.JsonException: A possible object cycle was detected. This can either be due to a cycle or if the object depth is larger than the maximum allowed...

Models

public partial class TableA
{
    public int Id { get; set; }
    public string? Item { get; set; }
    public virtual TableB? TableB { get; set; }
}
public partial class TableB
{
    public int Id { get; set; }
    public string? Title { get; set; }
    public virtual TableA TableA { get; set; } = null!;
}

Tables DB

create table TableA(
Id int primary key identity(1,1),
Item varchar(10)
);
create table TableB(
Id int primary key,
Title varchar(10)
constraint FK_TableA_TableB foreign key (Id) references TableA(Id)
);


问:
O365 MS Teams MessageCard img alignment issue in markdown text
I'm using a legacy MessageCard type to send to a Microsoft Teams channel connector. This card is used to accept user-supplied markdown as the text:

{
    "@type": "MessageCard",
    "@context": "https://schema.org/extensions",
    "title": "title",
    "summary": "summary",
    "markdown": true,
    "text": user_markdown,
}
```
<p>A common source for the markdown is to be provided something like a changelog, using list items, images, and text:</p>
```# Release Notes

What's new:

*  Issue 1
*  Issue 2
```
<p>This works great and the markdown is rendered perfectly on desktop and web Teams clients.</p>
<p><img src="https://i.stack.imgur.com/8Ckk6t.png" alt="good layout in desktop and web" /></p>
<p>But I have found that on the Teams mobile app there is some kind of different layout being applied to the markdown when displaying the same card that looks fine in other clients.</p>
<p><img src="https://i.stack.imgur.com/ztcKrt.png" alt="bad layout in mobile" /></p>
<p>Per this example you can see that it ignores the fixed image size and seems to enlarge it to the equivalent of "1.5em", and aligns it before the list item. I've been trying to fix this with various style settings to the img tag (float, display, ...), or wrapping the content in each list item to control the layout as a whole. But it seems the mobile client is applying some extra style to the img to make it display as "block" or similar.</p>
<p>Is it possible to correct the way images are aligned in this case?</p>
<p>Update:</p>
<p>Here is a complete repro for testing purposes:</p>
<p><strong>teams_card.json</strong></p>
<pre class="lang-json prettyprint-override"><code>{
    "@type": "MessageCard",
    "@context": "https://schema.org/extensions",
    "title": "title",
    "summary": "summary",
    "markdown": true,
    "text": "# Release Notes\n\nWhat's new:\n\n* <img style=\"width:16px; height:16px; vertical-align:middle;\" src=\"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmlld2JveD0iMCAwIDE2IDE2Ij48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxwYXRoIGQ9Ik0wIDEuNzc3QzAgLjc5Ni43OTYgMCAxLjc3NyAwaDEyLjQ0NkMxNS4yMDQgMCAxNiAuNzk2IDE2IDEuNzc3djEyLjQ0NmMwIC45ODEtLjc5NiAxLjc3Ny0xLjc3NyAxLjc3N0gxLjc3N0ExLjc3OCAxLjc3OCAwIDAgMSAwIDE0LjIyM1YxLjc3N3oiIGZpbGw9IiNGRjU2MzAiLz48Y2lyY2xlIGZpbGw9IiNGRkYiIGN4PSI4IiBjeT0iOCIgcj0iNCIvPjwvZz48L3N2Zz4=\" /> Issue 1\n"
}
</code>```

Sending to an existing MS Teams channel connector:

```<code>curl -H 'Content-Type: application/json' -d "@teams_card.json" https://<company>.webhook.office.com/webhookb2/<id path>
</code>```

Body:
I'm using a legacy MessageCard type to send to a Microsoft Teams channel connector. This card is used to accept user-supplied markdown as the text:

{
    "@type": "MessageCard",
    "@context": "https://schema.org/extensions",
    "title": "title",
    "summary": "summary",
    "markdown": true,
    "text": user_markdown,
}

A common source for the markdown is to be provided something like a changelog, using list items, images, and text:

# Release Notes

What's new:

*  Issue 1
*  Issue 2

This works great and the markdown is rendered perfectly on desktop and web Teams clients.

But I have found that on the Teams mobile app there is some kind of different layout being applied to the markdown when displaying the same card that looks fine in other clients.

Per this example you can see that it ignores the fixed image size and seems to enlarge it to the equivalent of "1.5em", and aligns it before the list item. I've been trying to fix this with various style settings to the img tag (float, display, ...), or wrapping the content in each list item to control the layout as a whole. But it seems the mobile client is applying some extra style to the img to make it display as "block" or similar.

Is it possible to correct the way images are aligned in this case?

Update:

Here is a complete repro for testing purposes:

teams_card.json

{
    "@type": "MessageCard",
    "@context": "https://schema.org/extensions",
    "title": "title",
    "summary": "summary",
    "markdown": true,
    "text": "# Release Notes\n\nWhat's new:\n\n* <img style=\"width:16px; height:16px; vertical-align:middle;\" src=\"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmlld2JveD0iMCAwIDE2IDE2Ij48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxwYXRoIGQ9Ik0wIDEuNzc3QzAgLjc5Ni43OTYgMCAxLjc3NyAwaDEyLjQ0NkMxNS4yMDQgMCAxNiAuNzk2IDE2IDEuNzc3djEyLjQ0NmMwIC45ODEtLjc5NiAxLjc3Ny0xLjc3NyAxLjc3N0gxLjc3N0ExLjc3OCAxLjc3OCAwIDAgMSAwIDE0LjIyM1YxLjc3N3oiIGZpbGw9IiNGRjU2MzAiLz48Y2lyY2xlIGZpbGw9IiNGRkYiIGN4PSI4IiBjeT0iOCIgcj0iNCIvPjwvZz48L3N2Zz4=\" /> Issue 1\n"
}

Sending to an existing MS Teams channel connector:

curl -H 'Content-Type: application/json' -d "@teams_card.json" https://<company>.webhook.office.com/webhookb2/<id path>


问:
Setting up Azure ADB2C with Custom Policies integrated with Dynamics Power Portal
I have ADB2C set up with the local account custom policy starter pack.  I am able to run the custom policies and create users when testing the flows. (https://learn.microsoft.com/en-us/azure/active-directory-b2c/tutorial-create-user-flows?pivots=b2c-custom-policy)

I have followed the steps here (https://learn.microsoft.com/en-us/power-apps/maker/portals/configure/configure-azure-ad-b2c-provider-manual) on integrating these flows with Dynamics Power Apps Portal - however, when I go to click "Sign-"in I get this message with very little to go on as to what is wrong.

Trying to figure out how to troubleshoot what is wrong with my implementation as I've been going through all the steps.

Thanks - Greg.


问:
Import XML in Google Sheets
I am trying to import the amount of followers from a Spotify artist. The only problem is it's inside a react modular. I used to be able to get the full xpath from dev tools, however, I believe the react modular is causing any error.

Any ideas on how I could get around this to use import xml to get the amount of spotify followers?
Example link: https://open.spotify.com/artist/1Xyo4u8uXC1ZmMpatF05PJ?si=VGW1om-XTNew5VD-KQ-7xA

Thanks!

Title: Import XML in Google Sheets


问:
TypeError: new(): invalid data type 'str' from ( Training a Deep learning model using import torch )
The actual code

```<code>import torch
from torch import nn
import re

# Define the vocabulary of the input and output sequences
vocab = ["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog", ".",
         "old", "man", "and", "sea", "A", "story", "as", "time", "cat", "in", "hat",
         "To", "be", "or", "not", "to", "be"]

# Define the input and output sizes
input_size = len(vocab)
output_size = len(vocab)

# Define the other parameters of the  model
hidden_size = 256
n_layers = 2
dropout = 0.2
batch_size = 64
learning_rate = 0.01

class MyLSTMModel(nn.Module):
    def __init__(self, input_size, hidden_size, num_layers, dropout, batch_size):
        super().__init__()
        self.input_size = input_size
        self.hidden_size = hidden_size
        self.num_layers = num_layers
        self.dropout = dropout
        self.batch_size = batch_size

        # Define the LSTM cell to use in the  layer
        self.lstm_cell = nn.LSTM(input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, dropout=dropout)

        # Define the architecture of the  using the LSTM cell
        self.model = nn.LSTM(input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, dropout=dropout)

    def forward(self, input_seq, hidden):
        # Preprocess the input string to lowercase and remove punctuation marks
        input_seq = str(input_seq).lower()
        input_seq = re.sub(r'[^\w\s]', '', input_seq)

        # Convert the input string to a list of integers, where each integer represents the index of a word in the vocab list
        input_seq = [vocab.index(word) for word in input_seq.split() if word in vocab]

        # Convert the list of integers to a tensor
        input_seq = torch.tensor(input_seq).unsqueeze(0)

        # Reshape the input tensor to have three dimensions
        input_seq = input_seq.unsqueeze(1)

        # Apply the LSTM cell to the input sequence
        hidden = self.init_hidden()
        output, hidden = self.lstm_cell(input_seq, hidden)
        return output, hidden

    def loss(self, output, target_seq):
        # Convert the target string to a list of integers, where each integer represents the index of a word in the vocab list
        target_seq = [vocab.index(word) for word in target_seq.split() if word in vocab]

        # Convert the list of integers to a tensor
        target_seq = torch.tensor(target_seq)

       # Calculate the cross-entropy loss between the output and the target sequence, using a sequence loss function
        output = output.view(-1, output_size)
        target_seq = target_seq.view(-1)
        loss = nn.CrossEntropyLoss()(output, target_seq)
        return loss

    def init_hidden(self):
        # Initialize the hidden state with zeros
        return torch.zeros(self.num_layers, self.batch_size, self.hidden_size).unsqueeze(0)

    def train(self, train_data):
        # Loop through each training example
        for input_seq, target_seq in train_data:
            # Convert input and target sequences to tensors
            input_seq = [vocab.index(word) for word in input_seq.split()]
            input_seq = torch.tensor(input_seq)

            target_seq = torch.Tensor(target_seq)

            # Set initial hidden state to all zeros
            hidden = torch.zeros(1, self.hidden_size)

            # Forward pass to get the output sequence
            output, hidden = self.forward(input_seq, hidden)

            # Calculate the loss between the output sequence and the target sequence
            loss = self.loss(output, target_seq)

            # Backward pass to compute the gradients of the loss with respect to the model's parameters
            loss.backward()

            # Update the model's parameters using the optimizer object
            optimizer = torch.optim.SGD(self.parameters(), lr=learning_rate)
            optimizer.step()

# Create an instance of the MyLSTMModel class
model = MyLSTMModel(input_size, hidden_size, n_layers, dropout, batch_size)

# Define some example training data
train_data = [("The quick brown fox jumps over the lazy dog", "A story as old as time"),
              ("To be or not to be", "That is the question")]

# Train the model on the training data
model.train(train_data)
</code>```

i run the code as a normal python script

my code goal

The code defines a MyLSTMModel class which extends the nn.Module class from PyTorch.
This class contains methods for defining the model architecture, initializing the hidden state of the model,
calculating the loss, training the model, and generating text using the trained model.
The MyLSTMModel class uses an LSTM (Long Short-Term Memory) layer to process the input sequence
and generate an output sequence. LSTM is a type of recurrent neural network that is particularly
well-suited for processing sequences of data. It can remember important information from earlier in
the sequence and use that information to make predictions about the future. In this case, the LSTM layer
is used to generate text based on the input sequence.

*but I get this error when I run the code:*

Traceback (most recent call last):
File "D:\path", line 121, in
model.train(train_data)
File "D:\path"", line 95, in train

target_seq = torch.Tensor(target_seq)
TypeError: new(): invalid data type 'str'

Body:
The actual code

import torch
from torch import nn
import re

# Define the vocabulary of the input and output sequences
vocab = ["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog", ".",
         "old", "man", "and", "sea", "A", "story", "as", "time", "cat", "in", "hat",
         "To", "be", "or", "not", "to", "be"]

# Define the input and output sizes
input_size = len(vocab)
output_size = len(vocab)

# Define the other parameters of the  model
hidden_size = 256
n_layers = 2
dropout = 0.2
batch_size = 64
learning_rate = 0.01

class MyLSTMModel(nn.Module):
    def __init__(self, input_size, hidden_size, num_layers, dropout, batch_size):
        super().__init__()
        self.input_size = input_size
        self.hidden_size = hidden_size
        self.num_layers = num_layers
        self.dropout = dropout
        self.batch_size = batch_size

        # Define the LSTM cell to use in the  layer
        self.lstm_cell = nn.LSTM(input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, dropout=dropout)

        # Define the architecture of the  using the LSTM cell
        self.model = nn.LSTM(input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, dropout=dropout)

    def forward(self, input_seq, hidden):
        # Preprocess the input string to lowercase and remove punctuation marks
        input_seq = str(input_seq).lower()
        input_seq = re.sub(r'[^\w\s]', '', input_seq)

        # Convert the input string to a list of integers, where each integer represents the index of a word in the vocab list
        input_seq = [vocab.index(word) for word in input_seq.split() if word in vocab]

        # Convert the list of integers to a tensor
        input_seq = torch.tensor(input_seq).unsqueeze(0)

        # Reshape the input tensor to have three dimensions
        input_seq = input_seq.unsqueeze(1)

        # Apply the LSTM cell to the input sequence
        hidden = self.init_hidden()
        output, hidden = self.lstm_cell(input_seq, hidden)
        return output, hidden

    def loss(self, output, target_seq):
        # Convert the target string to a list of integers, where each integer represents the index of a word in the vocab list
        target_seq = [vocab.index(word) for word in target_seq.split() if word in vocab]

        # Convert the list of integers to a tensor
        target_seq = torch.tensor(target_seq)

       # Calculate the cross-entropy loss between the output and the target sequence, using a sequence loss function
        output = output.view(-1, output_size)
        target_seq = target_seq.view(-1)
        loss = nn.CrossEntropyLoss()(output, target_seq)
        return loss

    def init_hidden(self):
        # Initialize the hidden state with zeros
        return torch.zeros(self.num_layers, self.batch_size, self.hidden_size).unsqueeze(0)

    def train(self, train_data):
        # Loop through each training example
        for input_seq, target_seq in train_data:
            # Convert input and target sequences to tensors
            input_seq = [vocab.index(word) for word in input_seq.split()]
            input_seq = torch.tensor(input_seq)

            target_seq = torch.Tensor(target_seq)

            # Set initial hidden state to all zeros
            hidden = torch.zeros(1, self.hidden_size)

            # Forward pass to get the output sequence
            output, hidden = self.forward(input_seq, hidden)

            # Calculate the loss between the output sequence and the target sequence
            loss = self.loss(output, target_seq)

            # Backward pass to compute the gradients of the loss with respect to the model's parameters
            loss.backward()

            # Update the model's parameters using the optimizer object
            optimizer = torch.optim.SGD(self.parameters(), lr=learning_rate)
            optimizer.step()

# Create an instance of the MyLSTMModel class
model = MyLSTMModel(input_size, hidden_size, n_layers, dropout, batch_size)

# Define some example training data
train_data = [("The quick brown fox jumps over the lazy dog", "A story as old as time"),
              ("To be or not to be", "That is the question")]

# Train the model on the training data
model.train(train_data)

i run the code as a normal python script

my code goal

The code defines a MyLSTMModel class which extends the nn.Module class from PyTorch.
This class contains methods for defining the model architecture, initializing the hidden state of the model,
calculating the loss, training the model, and generating text using the trained model.
The MyLSTMModel class uses an LSTM (Long Short-Term Memory) layer to process the input sequence
and generate an output sequence. LSTM is a type of recurrent neural network that is particularly
well-suited for processing sequences of data. It can remember important information from earlier in
the sequence and use that information to make predictions about the future. In this case, the LSTM layer
is used to generate text based on the input sequence.

*but I get this error when I run the code:*

Traceback (most recent call last):
File "D:\path", line 121, in
model.train(train_data)
File "D:\path"", line 95, in train

target_seq = torch.Tensor(target_seq)
TypeError: new(): invalid data type 'str'


问:
It there a Python equivalent module of node-pty
We have a site which exposes a remote shell terminal from an on-prem Node.js agent using node-pty. We also have a Python based agent, and would like to provive the experience.

The node.js code looks a bit like this:

pty = require('node-pty');
ptyProcess = pty.spawn('bash', [], {
    name: 'xterm-color',
    cols: 100,
    rows: 100,
    cwd: process.env.HOME,
    env: process.env
});

// Receiving terminal output
ptyProcess.on('data', function (data) {
    // send terminal data to web application
});

// Sending commands to terminal
_ptyProcess.write("ls -la");
```

I have looked a bit on Python pty but can't figure out the "on_data" event.

Thank you

Body:
We have a site which exposes a remote shell terminal from an on-prem Node.js agent using node-pty. We also have a Python based agent, and would like to provive the experience.

The node.js code looks a bit like this:

pty = require('node-pty');
ptyProcess = pty.spawn('bash', [], {
    name: 'xterm-color',
    cols: 100,
    rows: 100,
    cwd: process.env.HOME,
    env: process.env
});

// Receiving terminal output
ptyProcess.on('data', function (data) {
    // send terminal data to web application
});

// Sending commands to terminal
_ptyProcess.write("ls -la");

I have looked a bit on Python pty but can't figure out the "on_data" event.

Thank you


问:
503 and 502 errors with Node app when using Apache Proxy
I'm trying to host a Node app on an Ubuntu server using Apache Proxy which was working when using localhost. Its a basic ToDo tasklist app.

The app sends the HTML homepage to the client. The webpage uses external JS to modify the page and to send requests to the Node app, while the node app connects to MongoDB.

The whole project is located at /var/www/nodeapp/

My two main issues are:

Whenever I try to send the HTML page by using res.sendFile("./public/index.html") an 502 error occurs. The Apache error log:

```<code>[DATE] [proxy_http:error] [pid 91169:tid 140041225496320] (20014)Internal error (specific information not available): [My Device IP] AH01102: error reading status line from remote server 127.0.0.1:3000
[DATE] [proxy:error] [pid 91169:tid 140041225496320] [My Device IP] AH00898: Error reading from remote server returned by /
[DATE] [proxy:error] [pid 91169:tid 140041217103616] (111)Connection refused: AH00957: HTTP: attempt to connect to 127.0.0.1:3000 (127.0.0.1) failed
[DATE] [proxy_http:error] [pid 91169:tid 140041217103616] [My Device IP] AH01114: HTTP: failed to make connection to backend: 127.0.0.1, referer: http://[SERVER IP]:8080/
</code>```

When I try to use mongoose via const mongoose = require('mongoose') the 503 error occurs.

Apache encounters the same errors of

```<code>[DATE] [proxy:error] [pid 91487:tid 140387876316928] (111)Connection refused: AH00957: HTTP: attempt to connect to 127.0.0.1:3000 (127.0.0.1) failed
[DATE] [proxy_http:error] [pid 91487:tid 140387876316928] [client My Device IP] AH01114: HTTP: failed to make connection to backend: 127.0.0.1
</code>```

Node app

```<code>const express = require('express')
const http = require('http');
const cors = require('cors')
const app = express()
const port = 3000
const hostname = '127.0.0.0.1'

// cors - allows connection from different domains and ports.
app.use(cors())

// convert json string to json alias (on demand).
app.use(express.json())

//So that the CSS is rendered
app.use(express.static("public"));

/*
// use mongoose
//const mongoose = require('mongoose')

// the connection string
//const mongoDB = 'mongodb+srv://blahblah'

// connect to mongodb
mongoose.connect(mongoDB, {useNewUrlParser: true, useUnifiedTopology: true})
const db = mongoose.connection

// check connection - ok or error
db.on('error', console.error.bind(console, 'connection error:'))
db.once('open', function() {
  console.log("Database test connected")
})

// schema
const todoSchema = new mongoose.Schema({
    text: { type: String, required: true }
})

// template
const Todo = mongoose.model('Todo', todoSchema, 'todos')
*/

const server = http.createServer((req, res) => {
  res.statusCode = 200
  res.setHeader('Content-Type', 'text/plain')
  res.write('Hello World!')
  res.end()
})

app.post('/todos', async (request, response) => { {
    const { text } = request.body
    const todo = new Todo({
      text: text
    })
    const savedTodo = await todo.save()
    response.json(savedTodo)
})

app.put('/todos/:id', async (request, response) => { {
    const id = request.params.id
    const document = request.body
    const updatedTodo = await Todo.findOneAndUpdate({_id: id}, document, (err, result) => { //use the findOneAndUpdate function.
        if (err) {
            console.log(err) //if there is an error then show in console.
            response.status(404).end() //and respond with 404 status.
        }
    }).clone();
    console.log("Document value after change:", updatedTodo.text) //show the new value of the document.
    response.json(updatedTodo) //send the object to the client
})

app.get('/todos', async (request, response) => { {
    const todos = await Todo.find({})
    response.json(todos)
})

app.get('/todos/:id', async (request, response) => {
    const todo = await Todo.findById(request.params.id) //retrieve by ID.
    if (todo) response.json(todo) //if exists then respond with object.
    else response.status(404).end() //change 404 status
})

app.delete('/todos/:id', async (request, response) => { {
    console.log(request.params.id)
    const deletedTodo = await Todo.findByIdAndRemove(request.params.id) //retrieve and delete by ID.
    if (deletedTodo) response.json(deletedTodo) //respond with the object that was deleted.
    else response.status(404).end()
})

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`)
})
</code>```

I tried setting an absolute path to the node app in the .conf file

```<code><VirtualHost *:8080>
 ServerName nodeapp.com
 ServerAlias www.nodeapp.com
 ProxyRequests Off
 ProxyPreserveHost on
 ProxyVia Full
 <Proxy *>
        Require all granted
 </Proxy>
 ProxyPass /var/www/nodeapp http://127.0.0.1:3000/
 ProxyPassReverse /var/www/nodeapp http://127.0.0.1:3000/
</VirtualHost>

</code>```

but no effect.

I tried
res.sendFile(__dirname+/public/index.html)) also but no effect.

res.write('Hello world') works just fine and the page loads without any major issues but the moment I try to use mongoose or send the HTML file it stops working.

The index.html file is located in the public folder.

I am not quite sure where to go from here.

Body:
I'm trying to host a Node app on an Ubuntu server using Apache Proxy which was working when using localhost. Its a basic ToDo tasklist app.

The app sends the HTML homepage to the client. The webpage uses external JS to modify the page and to send requests to the Node app, while the node app connects to MongoDB.

The whole project is located at /var/www/nodeapp/

My two main issues are:

Whenever I try to send the HTML page by using res.sendFile("./public/index.html") an 502 error occurs. The Apache error log:

[DATE] [proxy_http:error] [pid 91169:tid 140041225496320] (20014)Internal error (specific information not available): [My Device IP] AH01102: error reading status line from remote server 127.0.0.1:3000
[DATE] [proxy:error] [pid 91169:tid 140041225496320] [My Device IP] AH00898: Error reading from remote server returned by /
[DATE] [proxy:error] [pid 91169:tid 140041217103616] (111)Connection refused: AH00957: HTTP: attempt to connect to 127.0.0.1:3000 (127.0.0.1) failed
[DATE] [proxy_http:error] [pid 91169:tid 140041217103616] [My Device IP] AH01114: HTTP: failed to make connection to backend: 127.0.0.1, referer: http://[SERVER IP]:8080/

When I try to use mongoose via const mongoose = require('mongoose') the 503 error occurs.

Apache encounters the same errors of

[DATE] [proxy:error] [pid 91487:tid 140387876316928] (111)Connection refused: AH00957: HTTP: attempt to connect to 127.0.0.1:3000 (127.0.0.1) failed
[DATE] [proxy_http:error] [pid 91487:tid 140387876316928] [client My Device IP] AH01114: HTTP: failed to make connection to backend: 127.0.0.1

Node app

const express = require('express')
const http = require('http');
const cors = require('cors')
const app = express()
const port = 3000
const hostname = '127.0.0.0.1'

// cors - allows connection from different domains and ports.
app.use(cors())

// convert json string to json alias (on demand).
app.use(express.json())

//So that the CSS is rendered
app.use(express.static("public"));

/*
// use mongoose
//const mongoose = require('mongoose')

// the connection string
//const mongoDB = 'mongodb+srv://blahblah'

// connect to mongodb
mongoose.connect(mongoDB, {useNewUrlParser: true, useUnifiedTopology: true})
const db = mongoose.connection

// check connection - ok or error
db.on('error', console.error.bind(console, 'connection error:'))
db.once('open', function() {
  console.log("Database test connected")
})

// schema
const todoSchema = new mongoose.Schema({
    text: { type: String, required: true }
})

// template
const Todo = mongoose.model('Todo', todoSchema, 'todos')
*/

const server = http.createServer((req, res) => {
  res.statusCode = 200
  res.setHeader('Content-Type', 'text/plain')
  res.write('Hello World!')
  res.end()
})

app.post('/todos', async (request, response) => { {
    const { text } = request.body
    const todo = new Todo({
      text: text
    })
    const savedTodo = await todo.save()
    response.json(savedTodo)
})

app.put('/todos/:id', async (request, response) => { {
    const id = request.params.id
    const document = request.body
    const updatedTodo = await Todo.findOneAndUpdate({_id: id}, document, (err, result) => { //use the findOneAndUpdate function.
        if (err) {
            console.log(err) //if there is an error then show in console.
            response.status(404).end() //and respond with 404 status.
        }
    }).clone();
    console.log("Document value after change:", updatedTodo.text) //show the new value of the document.
    response.json(updatedTodo) //send the object to the client
})

app.get('/todos', async (request, response) => { {
    const todos = await Todo.find({})
    response.json(todos)
})

app.get('/todos/:id', async (request, response) => {
    const todo = await Todo.findById(request.params.id) //retrieve by ID.
    if (todo) response.json(todo) //if exists then respond with object.
    else response.status(404).end() //change 404 status
})

app.delete('/todos/:id', async (request, response) => { {
    console.log(request.params.id)
    const deletedTodo = await Todo.findByIdAndRemove(request.params.id) //retrieve and delete by ID.
    if (deletedTodo) response.json(deletedTodo) //respond with the object that was deleted.
    else response.status(404).end()
})

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`)
})

I tried setting an absolute path to the node app in the .conf file

<VirtualHost *:8080>
 ServerName nodeapp.com
 ServerAlias www.nodeapp.com
 ProxyRequests Off
 ProxyPreserveHost on
 ProxyVia Full
 <Proxy *>
        Require all granted
 </Proxy>
 ProxyPass /var/www/nodeapp http://127.0.0.1:3000/
 ProxyPassReverse /var/www/nodeapp http://127.0.0.1:3000/
</VirtualHost>

but no effect.

I tried
res.sendFile(__dirname+/public/index.html)) also but no effect.

res.write('Hello world') works just fine and the page loads without any major issues but the moment I try to use mongoose or send the HTML file it stops working.

The index.html file is located in the public folder.

I am not quite sure where to go from here.


问:
Is there a class containing statics for algorithm names/modes/paddings?
If I needed to reference an encoding, like UTF-8, I'd typically reference the StandardCharset.UTF-8 static, not use a String literal "UTF-8".

When working with cipher transformations, I see everywhere that transformations are given as String literals, like Cipher.getInstance("AES") or Cipher.getInstance("AES/CBC/PKCS5Padding"), and occasionally, there's a typo.

Which class can I use for statics of cipher algorithm names, modes and paddings? Does one exist?

For reference, list of permitted names/modes/paddings in the docs.


问:
scrollIntoView Not maintaining position after scrolling is finished
the problem is as follows:
I have a function that runs on <body onload="init();",
next, I have the init function:

```<code>function init() {

            id = window.location.href.split('#!')[1];
            console.log(id)
            document.getElementById(id).scrollIntoView({
                behavior: "auto",
                block: "center",
                inline: "center"
            });

        }
</code>```

The id is correct and working. The wanted behavior is for the page to scroll to the element with the id
What actually happens is the document scroll as expected to the element id, but then it jumps back to the original position the page was in before I refreshed it.

Can you help me remove this jump to the original position?

Thanks

Body:
the problem is as follows:
I have a function that runs on <body onload="init();",
next, I have the init function:

function init() {

            id = window.location.href.split('#!')[1];
            console.log(id)
            document.getElementById(id).scrollIntoView({
                behavior: "auto",
                block: "center",
                inline: "center"
            });

        }

The id is correct and working. The wanted behavior is for the page to scroll to the element with the id
What actually happens is the document scroll as expected to the element id, but then it jumps back to the original position the page was in before I refreshed it.

Can you help me remove this jump to the original position?

Thanks


问:
ASP.NET WebForms Login ReturnURL missing on first time access
I have a web application written with ASP.NET WebForms. Yes I know its an old technology but this is a legacy project and they won't let me start from scratch.

If the user directly accesses a page without first logging in, the user is redirected to the login screen as is supposed to happen. But, if the application is being accessed for the first time since the browser has been open, the ReturnURL parameter is never added to the login request URL. Consequently, the user is not redirected back to the page he originally tried to access when he logs in. This happens regardless of the browser used.

The web.config file has the following authentication and authorization tags in it.

```<code>    <authentication mode="Forms">
        <forms name=".ASPXAUTH" defaultUrl="Default.aspx" loginUrl="Default.aspx" timeout="180" protection="All" path="/"/>
    </authentication>
    <authorization>
        <deny users="?"/>
    </authorization>
</code>```

Body:
I have a web application written with ASP.NET WebForms. Yes I know its an old technology but this is a legacy project and they won't let me start from scratch.

If the user directly accesses a page without first logging in, the user is redirected to the login screen as is supposed to happen. But, if the application is being accessed for the first time since the browser has been open, the ReturnURL parameter is never added to the login request URL. Consequently, the user is not redirected back to the page he originally tried to access when he logs in. This happens regardless of the browser used.

The web.config file has the following authentication and authorization tags in it.

    <authentication mode="Forms">
        <forms name=".ASPXAUTH" defaultUrl="Default.aspx" loginUrl="Default.aspx" timeout="180" protection="All" path="/"/>
    </authentication>
    <authorization>
        <deny users="?"/>
    </authorization>


问:
Vue3 - VeeValidate Dynamic FieldArray Change Event
How can I delete the field values if the option type is changed.

If option type is text or date, can add option button be hidden? How can i delete field values when option type is changed

Version Vue.js 3.x and vee-validate 4.x

https://stackblitz.com/edit/vue3-vite-starter-bpdpwc?file=src/App.vue


问:
Can i somehow download pictures from my wordpress database?
I have done a lot of research and I don't know what to do anymore. I have a database from an old wordpress site that I no longer have access to. I need to download all pictures from database or at leats find where they are stored. When I open the "field_data_field_image" table, it shows the name, id, height and width in pixels of all the images, but the image itself is not stored there.

Does anyone have idea where the pictures could be stored?

Structure of my database

Thanks for you help guys ;).


问:
.detoxrc for Windows
I'm configuring Detox for AwesomeProject on a Windows computer. I made modifications to the commands to get it working for running on PowerShell on Windows 10. Running detox build --configuration android.emu.debug doesn't work, but I can copy and paste from the error message to get BUILD SUCCESSFUL in 8s. The error message starts: 'Set-Location' is not recognized as an internal or external command,. The part of the error message I copy follows: Set-Location android ; .\gradlew assembleDebug assembleAndroidTest -DtestBuildType=debug ; Set-Location ... If I use cd then the error becomes: The system cannot find the path specified.

Is there an example .detoxrc.json file for Windows users available or is there some advise to help me modify the build string correctly in .detoxrc.json?

```<code>/** @type {Detox.DetoxConfig} */
module.exports = {
  testRunner: {
    args: {
      '$0': 'jest',
      config: 'e2e/jest.config.js'
    },
    jest: {
      setupTimeout: 120000
    }
  },
  apps: {
    'ios.debug': {
      type: 'ios.app',
      binaryPath: 'ios/build/Build/Products/Debug-iphonesimulator/AwesomeApp.app',
      build: 'xcodebuild -workspace ios/YOUR_APP.xcworkspace -scheme YOUR_APP -configuration Debug -sdk iphonesimulator -derivedDataPath ios/build'
    },
    'ios.release': {
      type: 'ios.app',
      binaryPath: 'ios/build/Build/Products/Release-iphonesimulator/YOUR_APP.app',
      build: 'xcodebuild -workspace ios/YOUR_APP.xcworkspace -scheme YOUR_APP -configuration Release -sdk iphonesimulator -derivedDataPath ios/build'
    },
    'android.debug': {
      type: 'android.apk',
      binaryPath: 'android\\app\\build\\outputs\\apk\\debug\\app-debug.apk',
      build: 'Set-Location android ; .\\gradlew assembleDebug assembleAndroidTest -DtestBuildType=debug ; Set-Location ..',
      reversePorts: [
        8081
      ]
    },
    'android.release': {
      type: 'android.apk',
      binaryPath: 'android\\app\\build\\outputs\\apk\\release\\app-release.apk',
      build: 'Set-Location android ; .\\gradlew assembleRelease assembleAndroidTest -DtestBuildType=release ; Set-Location ..'
    }
  },
  devices: {
    simulator: {
      type: 'ios.simulator',
      device: {
        type: 'iPhone 12'
      }
    },
    attached: {
      type: 'android.attached',
      device: {
        adbName: '.*'
      }
    },
    emulator: {
      type: 'android.emulator',
      device: {
        avdName: '4_WVGA_Nexus_S_API_28'
      }
    }
  },
  configurations: {
    'ios.sim.debug': {
      device: 'simulator',
      app: 'ios.debug'
    },
    'ios.sim.release': {
      device: 'simulator',
      app: 'ios.release'
    },
    'android.att.debug': {
      device: 'attached',
      app: 'android.debug'
    },
    'android.att.release': {
      device: 'attached',
      app: 'android.release'
    },
    'android.emu.debug': {
      device: 'emulator',
      app: 'android.debug'
    },
    'android.emu.release': {
      device: 'emulator',
      app: 'android.release'
    }
  }
};
</code>```

Title: .detoxrc for Windows

Body:
I'm configuring Detox for AwesomeProject on a Windows computer. I made modifications to the commands to get it working for running on PowerShell on Windows 10. Running detox build --configuration android.emu.debug doesn't work, but I can copy and paste from the error message to get BUILD SUCCESSFUL in 8s. The error message starts: 'Set-Location' is not recognized as an internal or external command,. The part of the error message I copy follows: Set-Location android ; .\gradlew assembleDebug assembleAndroidTest -DtestBuildType=debug ; Set-Location ... If I use cd then the error becomes: The system cannot find the path specified.

Is there an example .detoxrc.json file for Windows users available or is there some advise to help me modify the build string correctly in .detoxrc.json?

/** @type {Detox.DetoxConfig} */
module.exports = {
  testRunner: {
    args: {
      '$0': 'jest',
      config: 'e2e/jest.config.js'
    },
    jest: {
      setupTimeout: 120000
    }
  },
  apps: {
    'ios.debug': {
      type: 'ios.app',
      binaryPath: 'ios/build/Build/Products/Debug-iphonesimulator/AwesomeApp.app',
      build: 'xcodebuild -workspace ios/YOUR_APP.xcworkspace -scheme YOUR_APP -configuration Debug -sdk iphonesimulator -derivedDataPath ios/build'
    },
    'ios.release': {
      type: 'ios.app',
      binaryPath: 'ios/build/Build/Products/Release-iphonesimulator/YOUR_APP.app',
      build: 'xcodebuild -workspace ios/YOUR_APP.xcworkspace -scheme YOUR_APP -configuration Release -sdk iphonesimulator -derivedDataPath ios/build'
    },
    'android.debug': {
      type: 'android.apk',
      binaryPath: 'android\\app\\build\\outputs\\apk\\debug\\app-debug.apk',
      build: 'Set-Location android ; .\\gradlew assembleDebug assembleAndroidTest -DtestBuildType=debug ; Set-Location ..',
      reversePorts: [
        8081
      ]
    },
    'android.release': {
      type: 'android.apk',
      binaryPath: 'android\\app\\build\\outputs\\apk\\release\\app-release.apk',
      build: 'Set-Location android ; .\\gradlew assembleRelease assembleAndroidTest -DtestBuildType=release ; Set-Location ..'
    }
  },
  devices: {
    simulator: {
      type: 'ios.simulator',
      device: {
        type: 'iPhone 12'
      }
    },
    attached: {
      type: 'android.attached',
      device: {
        adbName: '.*'
      }
    },
    emulator: {
      type: 'android.emulator',
      device: {
        avdName: '4_WVGA_Nexus_S_API_28'
      }
    }
  },
  configurations: {
    'ios.sim.debug': {
      device: 'simulator',
      app: 'ios.debug'
    },
    'ios.sim.release': {
      device: 'simulator',
      app: 'ios.release'
    },
    'android.att.debug': {
      device: 'attached',
      app: 'android.debug'
    },
    'android.att.release': {
      device: 'attached',
      app: 'android.release'
    },
    'android.emu.debug': {
      device: 'emulator',
      app: 'android.debug'
    },
    'android.emu.release': {
      device: 'emulator',
      app: 'android.release'
    }
  }
};


问:
Adding the duration of the service
There are such entities (models): Client, Services, Master and a table with records for services. The records table has fields: start date and time, client name, master name and list of services. Each service has its own execution time, and when enrolling in the queue, the client can select several services and the date / time of entry. The task is to calculate the duration of one record (taking into account the number of services) from the date / time of the record. And ideally, the end date / time is set automatically (depending on the number of services and their duration).

I assume that it is necessary to do some manipulations in the service records model, namely to add a duration or complete_date. I can't figure out how to insert the required time calculation, especially if more than one service is selected.

Thanks in advance for your help

Title: Adding the duration of the service


问:
ServiceActivator invoked twice when only one message is published
I have the following JUnit test that is basically an example of a production test.

```<code>@Autowired
private MessageChannel messageChannel;

@SpyBean
@Autowired
private Handler handler;

@Test
public void testPublishing() {
    SomeEvent event = new SomeEvent(); // implements Message
    messageChannel.send(event);

    Thread.sleep(2000); // sleep 2 seconds

    Mockito.verify(handler, times(1))
        .someMethod(Mockito.any());
}
</code>```

The service activator is the someMethod method inside the Handler class. For some reason this test fails stating that someMethod was invoked twice even though only a single message was published to the channel. I even added code to someMethod to print the memory address of the message consumed and both invocations are the exact same address. Any idea what could cause this?

NOTE: I built this basic code example as a test case and it verifies as single invocation as I'd expect, but what could possibly (in my production system test) cause the send operation to result in 2 separate invocations of the service activator?

NOTE2: I added a print statement inside my real service activator. When I have the @SpyBean annotation on the handler and use the Mockito.verify(... I get two print outs of the input. However, if I remove the annotation and the verify call then I only get one print out. However, this does not happen in the simple demo I shared here.

NOTE3: Seems to be some sort of weird SpyBean behavior as I am only seeing the single event downstream. No idea why Mockito is giving me trouble on this.

Body:
I have the following JUnit test that is basically an example of a production test.

@Autowired
private MessageChannel messageChannel;

@SpyBean
@Autowired
private Handler handler;

@Test
public void testPublishing() {
    SomeEvent event = new SomeEvent(); // implements Message
    messageChannel.send(event);

    Thread.sleep(2000); // sleep 2 seconds

    Mockito.verify(handler, times(1))
        .someMethod(Mockito.any());
}

The service activator is the someMethod method inside the Handler class. For some reason this test fails stating that someMethod was invoked twice even though only a single message was published to the channel. I even added code to someMethod to print the memory address of the message consumed and both invocations are the exact same address. Any idea what could cause this?

NOTE: I built this basic code example as a test case and it verifies as single invocation as I'd expect, but what could possibly (in my production system test) cause the send operation to result in 2 separate invocations of the service activator?

NOTE2: I added a print statement inside my real service activator. When I have the @SpyBean annotation on the handler and use the Mockito.verify(... I get two print outs of the input. However, if I remove the annotation and the verify call then I only get one print out. However, this does not happen in the simple demo I shared here.

NOTE3: Seems to be some sort of weird SpyBean behavior as I am only seeing the single event downstream. No idea why Mockito is giving me trouble on this.


问:
SwiftUI View Composition with VStack Text Not Working
I am building a complex View with a number of different TextFields. I've shown a simplified version below- the first code block builds and runs. When I add an identical VStack block to it- the second code block, it fails to run- I get "the compiler is unable to type-check" error. Is the a child limit issue? I wish XCode provided decent error messaging!

Working.....

```<code>var body: some View {

    ScrollView() {

        VStack{   //  parts

            ForEach(Array(stride(from: 0, to: 461, by: 33)), id: \.self) { index_v in

                HStack {
                    VStack {
                        Group{
                            Text("resultsLine1")
                            Text(PartDisplay[index_v][0])
                            Text(db.sPart[index_v][1])

                            if (db.sSelectedMode == "detailMode") {
                                Text("resultsLine4D")
                                Text("\(db.sPart[index_v][16]) \(db.sPart[index_v][19]) \(db.sPart[index_v][18])")
                                Text("results")
                                Text("\(db.sPart[index_v][22])")
                            } else {
                                Text("resultsLine4B")
                                Text("\(db.sPart[index_v][16])      \(db.sPart[index_v][18])")
                            }
                        }
                    }
                    .padding(.bottom, 6)

                    VStack {
                        Group{
                            Text("resultsLine4")
                            Text(PartDisplay[index_v][2])
                            Text(db.sPart[index_v][3])
                            Text(db.sPart[index_v][4])

                            if (db.sSelectedMode == "detailMode") {
                                Text("resultsLine4D")
                                Text("\(db.sPart[index_v][1]) \(db.sPart[index_v][3]) \(db.sPart[index_v][8])")
                                Text("results4")
                                Text("\(db.sPart[index_v][22])")
                            } else {
                                Text("resultsLine4B")
                                Text("\(db.sPart[index_v][16])      \(db.sPart[index_v][18])")
                            }
                        }
                    }
                    .padding(.bottom, 6)

                }
            }
        }

    }

}
</code>```

Not working..

```<code>var body: some View {

    ScrollView() {

        VStack{   //  parts

            ForEach(Array(stride(from: 0, to: 461, by: 33)), id: \.self) { index_v in

                HStack {
                    VStack {
                        Group{
                            Text("resultsLine1")
                            Text(PartDisplay[index_v][0])
                            Text(db.sPart[index_v][1])

                            if (db.sSelectedMode == "detailMode") {
                                Text("resultsLine4D")
                                Text("\(db.sPart[index_v][16]) \(db.sPart[index_v][19]) \(db.sPart[index_v][18])")
                                Text("results")
                                Text("\(db.sPart[index_v][22])")
                            } else {
                                Text("resultsLine4B")
                                Text("\(db.sPart[index_v][16])      \(db.sPart[index_v][18])")
                            }
                        }
                    }
                    .padding(.bottom, 6)

                    VStack {
                        Group{
                            Text("resultsLine4")
                            Text(PartDisplay[index_v][2])
                            Text(db.sPart[index_v][3])
                            Text(db.sPart[index_v][4])

                            if (db.sSelectedMode == "detailMode") {
                                Text("resultsLine4D")
                                Text("\(db.sPart[index_v][1]) \(db.sPart[index_v][3]) \(db.sPart[index_v][8])")
                                Text("results4")
                                Text("\(db.sPart[index_v][22])")
                            } else {
                                Text("resultsLine4B")
                                Text("\(db.sPart[index_v][16])      \(db.sPart[index_v][18])")
                            }
                        }
                    }
                    .padding(.bottom, 6)

                    VStack {
                        Group{
                            Text("resultsLine1")
                            Text(PartDisplay[index_v][0])
                            Text(db.sPart[index_v][1])

                            if (db.sSelectedMode == "detailMode") {
                                Text("resultsLine14D")
                                Text("\(db.sPart[index_v][6]) \(db.sPart[index_v][9]) \(db.sPart[index_v][8])")
                                Text("results")
                                Text("\(db.sPart[index_v][2])")
                            } else {
                                Text("resultsLine4B")
                                Text("\(db.sPart[index_v][6])      \(db.sPart[index_v][18])")
                            }
                        }
                    }
                    .padding(.bottom, 6)

                }
            }
        }

    }

}
</code>```

Body:
I am building a complex View with a number of different TextFields. I've shown a simplified version below- the first code block builds and runs. When I add an identical VStack block to it- the second code block, it fails to run- I get "the compiler is unable to type-check" error. Is the a child limit issue? I wish XCode provided decent error messaging!

Working.....

var body: some View {

    ScrollView() {

        VStack{   //  parts

            ForEach(Array(stride(from: 0, to: 461, by: 33)), id: \.self) { index_v in

                HStack {
                    VStack {
                        Group{
                            Text("resultsLine1")
                            Text(PartDisplay[index_v][0])
                            Text(db.sPart[index_v][1])

                            if (db.sSelectedMode == "detailMode") {
                                Text("resultsLine4D")
                                Text("\(db.sPart[index_v][16]) \(db.sPart[index_v][19]) \(db.sPart[index_v][18])")
                                Text("results")
                                Text("\(db.sPart[index_v][22])")
                            } else {
                                Text("resultsLine4B")
                                Text("\(db.sPart[index_v][16])      \(db.sPart[index_v][18])")
                            }
                        }
                    }
                    .padding(.bottom, 6)

                    VStack {
                        Group{
                            Text("resultsLine4")
                            Text(PartDisplay[index_v][2])
                            Text(db.sPart[index_v][3])
                            Text(db.sPart[index_v][4])

                            if (db.sSelectedMode == "detailMode") {
                                Text("resultsLine4D")
                                Text("\(db.sPart[index_v][1]) \(db.sPart[index_v][3]) \(db.sPart[index_v][8])")
                                Text("results4")
                                Text("\(db.sPart[index_v][22])")
                            } else {
                                Text("resultsLine4B")
                                Text("\(db.sPart[index_v][16])      \(db.sPart[index_v][18])")
                            }
                        }
                    }
                    .padding(.bottom, 6)

                }
            }
        }

    }

}

Not working..

var body: some View {

    ScrollView() {

        VStack{   //  parts

            ForEach(Array(stride(from: 0, to: 461, by: 33)), id: \.self) { index_v in

                HStack {
                    VStack {
                        Group{
                            Text("resultsLine1")
                            Text(PartDisplay[index_v][0])
                            Text(db.sPart[index_v][1])

                            if (db.sSelectedMode == "detailMode") {
                                Text("resultsLine4D")
                                Text("\(db.sPart[index_v][16]) \(db.sPart[index_v][19]) \(db.sPart[index_v][18])")
                                Text("results")
                                Text("\(db.sPart[index_v][22])")
                            } else {
                                Text("resultsLine4B")
                                Text("\(db.sPart[index_v][16])      \(db.sPart[index_v][18])")
                            }
                        }
                    }
                    .padding(.bottom, 6)

                    VStack {
                        Group{
                            Text("resultsLine4")
                            Text(PartDisplay[index_v][2])
                            Text(db.sPart[index_v][3])
                            Text(db.sPart[index_v][4])

                            if (db.sSelectedMode == "detailMode") {
                                Text("resultsLine4D")
                                Text("\(db.sPart[index_v][1]) \(db.sPart[index_v][3]) \(db.sPart[index_v][8])")
                                Text("results4")
                                Text("\(db.sPart[index_v][22])")
                            } else {
                                Text("resultsLine4B")
                                Text("\(db.sPart[index_v][16])      \(db.sPart[index_v][18])")
                            }
                        }
                    }
                    .padding(.bottom, 6)

                    VStack {
                        Group{
                            Text("resultsLine1")
                            Text(PartDisplay[index_v][0])
                            Text(db.sPart[index_v][1])

                            if (db.sSelectedMode == "detailMode") {
                                Text("resultsLine14D")
                                Text("\(db.sPart[index_v][6]) \(db.sPart[index_v][9]) \(db.sPart[index_v][8])")
                                Text("results")
                                Text("\(db.sPart[index_v][2])")
                            } else {
                                Text("resultsLine4B")
                                Text("\(db.sPart[index_v][6])      \(db.sPart[index_v][18])")
                            }
                        }
                    }
                    .padding(.bottom, 6)

                }
            }
        }

    }

}


问:
How to find all occurrences of a word in a string and move them to the beginning of the string?
Good evening formites

The task is: "Text file L4_16T.txt contains text. Delimiters are known. Move each longest word beginning with an uppercase letter to the beginning of the line with delimiters behind. Write the modified text to a separate Results.txt file. Prepare an Analysis file. txt in table format (2 columns): line number, word starting with a capital (upper) letter."

It is not possible to properly implement word wrapping in a line if there are two or more identical longest words in the line that begin with an uppercase letter.

That's because I'm looking for the maximum words in a string using IndexOf, which returns the first occurrence of the element. And since I have the same word several times in the line, the program each time transfers the same word to the beginning. And I need to transfer all the words.

I'll give you an example. There is this line:

" ,,,,,,,,,,,,,,,,,,,,,,,,Sdfsdf;;;;;;;;;;;;;;;sdfh Sdfsdf,,,,,,, ,,,,,,,,,,,,. Sdfsdf aaaaaaaaaaaaaaaaaaaaaaaaa

I should get the following output:

"Mdfsdf,,,,,,,,,Sdfsdf Sdfsdf,,,,,,,,,,,,,,,,,,,,.Sdfsdf;;;;;;;;;;;;;;; ,,,,,,,,,,,,,,,,,,,,,,,,sdfh aaaaaaaaaaaaaaaaaaaaaaaaa"

But for now I only get this line:

"Mdfsdf,,,,,,,,Sdfsdf;;;;;;;;;;;;;;;sdfh kj ,,,,,,,,,,,,,,,Sdfsdf ,,,,, ,,,,,,,,,,,,,,,.sdfsdf aaaaaaaaaaaaaaaaaaaaaaaaa

Tell me how can I solve this?

Program code:

```<code>using System;
using System.IO;
using System.Text;

namespace LAB_4_2
{
    internal class Program
    {
        const string strFile = "TextFile.txt";
        const string resFile = "Result.txt";
        const string aFile = "Analiz.txt";

        static void Main(string[] args)
        {
            char[] delimiters = { ' ', '.', ',', ';', ':', '[', ']', '(', ')', '!', '?', '\t', '\n' };
            Process(strFile, aFile, resFile, delimiters);
        }

        static void Process(string strFile, string aFile, string resFile, char[] delimiters)
        {
            using (StreamReader readStr = new StreamReader(strFile, Encoding.GetEncoding(1257)))
            {
                using (StreamWriter writeA = new StreamWriter(aFile))
                {
                    using (StreamWriter writeRes = new StreamWriter(resFile))
                    {
                        string top = "----------------------------\n" +
                                 "| Line № | Longest word    |\n" +
                                 "----------------------------";
                        writeA.WriteLine(top);
                        string line;
                        int countline = 1;

                        while ((line = readStr.ReadLine()) != null) {
                            if (line.Length >= 0) {
                                string AllMaxWords = "";
                                string[] longestWords = FindMaxWords(line, delimiters, ref AllMaxWords);

                                if (AllMaxWords.Length == 0)
                                    writeA.WriteLine("|   {0, -4} | {1, -15} |", countline, "No words found");
                                else
                                    for (int i = 0; i < longestWords.Length; i++)
                                    {
                                        if (longestWords[i] == "")
                                            continue;
                                        writeA.WriteLine("|   {0, -4} | {1, -15} |", countline, longestWords[i]);
                                        MoveToStart(ref line, longestWords[i], line.IndexOf(longestWords[i]));
                                    }
                                countline++;

                                writeRes.WriteLine(line);
                            }
                        }
                        writeA.WriteLine("----------------------------");
                    }
                }
            }
        }

        static void MoveToStart(ref string myLine, string word, int start)
        {
            string tempLine = string.Empty;
            int index = myLine.IndexOf(word) + word.Length;

            while (index < myLine.Length)
            {
                if (myLine[index] == ' ')
                {
                    tempLine += " ";
                    break;
                }
                else
                {
                    tempLine += myLine[index];
                    index++;
                }
            }

            string myLine1 = myLine.Remove(start, word.Length);
            myLine1 = myLine1.Remove(myLine1.IndexOf(tempLine), tempLine.Length);

            myLine = myLine1.Insert(0, word+tempLine);
        }

        static int MaxWordLength(string line, char[] delimiters)
        {
            int maxlength = 1;
            string[] words = line.Split(delimiters,
                StringSplitOptions.RemoveEmptyEntries);

            for (int i = 0; i < words.Length; i++)
            {
                if (Char.IsUpper(words[i][0]) &&
                    maxlength < words[i].Length)
                {
                    maxlength = words[i].Length;
                }
            }

            return maxlength;
        }

        static string[] FindMaxWords(string line, char[] delimiters, ref string AllMaxWords)
        {
            string[] temp = line.Split(delimiters,
                                   StringSplitOptions.RemoveEmptyEntries);
            int maxlength = MaxWordLength(line, delimiters);

            for (int i = 0, k = 0; i < temp.Length; i++, k++)
            {
                if (Char.IsUpper(temp[i][0]) &&
                    maxlength == temp[i].Length)
                {
                    AllMaxWords += temp[k] + " ";
                }
            }
            return AllMaxWords.Split();
        }
    }
}
</code>```

Body:
Good evening formites

The task is: "Text file L4_16T.txt contains text. Delimiters are known. Move each longest word beginning with an uppercase letter to the beginning of the line with delimiters behind. Write the modified text to a separate Results.txt file. Prepare an Analysis file. txt in table format (2 columns): line number, word starting with a capital (upper) letter."

It is not possible to properly implement word wrapping in a line if there are two or more identical longest words in the line that begin with an uppercase letter.

That's because I'm looking for the maximum words in a string using IndexOf, which returns the first occurrence of the element. And since I have the same word several times in the line, the program each time transfers the same word to the beginning. And I need to transfer all the words.

I'll give you an example. There is this line:

" ,,,,,,,,,,,,,,,,,,,,,,,,Sdfsdf;;;;;;;;;;;;;;;sdfh Sdfsdf,,,,,,, ,,,,,,,,,,,,. Sdfsdf aaaaaaaaaaaaaaaaaaaaaaaaa

I should get the following output:

"Mdfsdf,,,,,,,,,Sdfsdf Sdfsdf,,,,,,,,,,,,,,,,,,,,.Sdfsdf;;;;;;;;;;;;;;; ,,,,,,,,,,,,,,,,,,,,,,,,sdfh aaaaaaaaaaaaaaaaaaaaaaaaa"

But for now I only get this line:

"Mdfsdf,,,,,,,,Sdfsdf;;;;;;;;;;;;;;;sdfh kj ,,,,,,,,,,,,,,,Sdfsdf ,,,,, ,,,,,,,,,,,,,,,.sdfsdf aaaaaaaaaaaaaaaaaaaaaaaaa

Tell me how can I solve this?

Program code:

using System;
using System.IO;
using System.Text;

namespace LAB_4_2
{
    internal class Program
    {
        const string strFile = "TextFile.txt";
        const string resFile = "Result.txt";
        const string aFile = "Analiz.txt";

        static void Main(string[] args)
        {
            char[] delimiters = { ' ', '.', ',', ';', ':', '[', ']', '(', ')', '!', '?', '\t', '\n' };
            Process(strFile, aFile, resFile, delimiters);
        }

        static void Process(string strFile, string aFile, string resFile, char[] delimiters)
        {
            using (StreamReader readStr = new StreamReader(strFile, Encoding.GetEncoding(1257)))
            {
                using (StreamWriter writeA = new StreamWriter(aFile))
                {
                    using (StreamWriter writeRes = new StreamWriter(resFile))
                    {
                        string top = "----------------------------\n" +
                                 "| Line № | Longest word    |\n" +
                                 "----------------------------";
                        writeA.WriteLine(top);
                        string line;
                        int countline = 1;

                        while ((line = readStr.ReadLine()) != null) {
                            if (line.Length >= 0) {
                                string AllMaxWords = "";
                                string[] longestWords = FindMaxWords(line, delimiters, ref AllMaxWords);

                                if (AllMaxWords.Length == 0)
                                    writeA.WriteLine("|   {0, -4} | {1, -15} |", countline, "No words found");
                                else
                                    for (int i = 0; i < longestWords.Length; i++)
                                    {
                                        if (longestWords[i] == "")
                                            continue;
                                        writeA.WriteLine("|   {0, -4} | {1, -15} |", countline, longestWords[i]);
                                        MoveToStart(ref line, longestWords[i], line.IndexOf(longestWords[i]));
                                    }
                                countline++;

                                writeRes.WriteLine(line);
                            }
                        }
                        writeA.WriteLine("----------------------------");
                    }
                }
            }
        }

        static void MoveToStart(ref string myLine, string word, int start)
        {
            string tempLine = string.Empty;
            int index = myLine.IndexOf(word) + word.Length;

            while (index < myLine.Length)
            {
                if (myLine[index] == ' ')
                {
                    tempLine += " ";
                    break;
                }
                else
                {
                    tempLine += myLine[index];
                    index++;
                }
            }

            string myLine1 = myLine.Remove(start, word.Length);
            myLine1 = myLine1.Remove(myLine1.IndexOf(tempLine), tempLine.Length);

            myLine = myLine1.Insert(0, word+tempLine);
        }

        static int MaxWordLength(string line, char[] delimiters)
        {
            int maxlength = 1;
            string[] words = line.Split(delimiters,
                StringSplitOptions.RemoveEmptyEntries);

            for (int i = 0; i < words.Length; i++)
            {
                if (Char.IsUpper(words[i][0]) &&
                    maxlength < words[i].Length)
                {
                    maxlength = words[i].Length;
                }
            }

            return maxlength;
        }

        static string[] FindMaxWords(string line, char[] delimiters, ref string AllMaxWords)
        {
            string[] temp = line.Split(delimiters,
                                   StringSplitOptions.RemoveEmptyEntries);
            int maxlength = MaxWordLength(line, delimiters);

            for (int i = 0, k = 0; i < temp.Length; i++, k++)
            {
                if (Char.IsUpper(temp[i][0]) &&
                    maxlength == temp[i].Length)
                {
                    AllMaxWords += temp[k] + " ";
                }
            }
            return AllMaxWords.Split();
        }
    }
}


问:
How to add raw (frequentist) estimates to forest plot
Let's say I want to add raw point estimates with 95% confidence intervals to forest plot. What's the best way to achieve that? Here's a simple example of creating a forest plot (without frequentist/raw estimates):</p>
```<code>import bambi as bmb
import pandas as pd
import arviz as az

df_simple = pd.DataFrame({
    'x': ['A', 'B', 'C'],
    'y': [10, 20, 30],
    'n': [100, 100, 100]
})

m = bmb.Model('p(y, n) ~ 0 + x', data=df_simple, family='binomial')
idata = m.fit(cores=4)

m.predict(idata)

az.plot_forest(idata, var_names='p(y, n)_mean', combined=True)
</code>```

Body:
Let's say I want to add raw point estimates with 95% confidence intervals to forest plot. What's the best way to achieve that? Here's a simple example of creating a forest plot (without frequentist/raw estimates):

import bambi as bmb
import pandas as pd
import arviz as az

df_simple = pd.DataFrame({
    'x': ['A', 'B', 'C'],
    'y': [10, 20, 30],
    'n': [100, 100, 100]
})

m = bmb.Model('p(y, n) ~ 0 + x', data=df_simple, family='binomial')
idata = m.fit(cores=4)

m.predict(idata)

az.plot_forest(idata, var_names='p(y, n)_mean', combined=True)


问:
dragulaModel is not sorting properly after upgrading to Angular 11
I have upgraded to Angular 11 and accordingly upgraded the version of ng-dragula from 1.3.0 to 2.1.1. Now I have a functionality of drag and drop. Below is the code snippet.
order-packages.html

```<code><div class="row mt-5">
    <div class="col-md-8"><h3>Order Packages</h3></div>
    <div class="col-md-4">
        <div class="row">
          <div class="col-md-6">
            <button *ngIf="!disablePublish" href="#" class="btn btn-primary" (click)="publishOrder()">Publish Order</button>
            <button *ngIf="disablePublish" [disabled]="disablePublish" class="btn btn-disabled">Publish Order</button>
          </div>
        </div>
    </div>
</div>
<div class="row mt-5">
    <div class="col-md-8 mt-5">
        <tux-alert *ngIf="publishSuccess" [type]="'success'" [heading]="'Success'" [dismissible]="false">Succesfully published the package order.</tux-alert>
        <app-loading-indicator *ngIf="showLoading"></app-loading-indicator>
        <!--tux-sortable [(items)]="packages" (onChange)="newOrder($event)" [bind_label]="'name'"></tux-sortable-->
        <ul dragula="PACKAGES" [(dragulaModel)]="packages" class="draganddrop">
          <p>test</p>
            <li *ngFor="let package of packages" class="draggable">
                <i class="iconWhite fa fa-book small"></i><span> </span>{{ package.name }}<span> </span>({{package.resourceKey}})
            </li>
        </ul>
    </div>
    <div class="col-md-4 mt-5">
        <p>Waiting for reordering the packages...</p>
        <ol>
            <li *ngFor="let item of movements">Moved <b>{{item.currentItem}}</b> between <b>{{item.prevItem}}</b> and <b>{{item.nextItem}}</b></li>
        </ol>
    </div>
</div>
</code>```

order-packages.ts

```<code>import {Component, OnInit, Input} from '@angular/core';

import { HttpClient, HttpParams, HttpErrorResponse } from '@angular/common/http';

import {DataService} from '../../../shared/services/data.service';
import { DragulaService } from 'ng2-dragula';
import {NotificationsService} from '../../../shared/services/notification.service';
import {AutoUnsubscribe} from '../../../shared/Decorators/autounsubscribe';

@Component({
    selector: 'app-order-packages',
    templateUrl: './order-packages.component.html'
})
@AutoUnsubscribe
export class OrderPackagesComponent  implements OnInit {
    subscriptions: any[] = new Array();
    packages: any;
    orderPackages: any = 'PACKAGES';
    newPackageOrder: any;
    showLoading = false;
    publishSuccess = false;
    disablePublish = true;
    originalOrder: any;
    movements: any = [];
    constructor(private _dataService: DataService, private dragulaService: DragulaService, private _notificationsService: NotificationsService) {
        dragulaService.createGroup('PACKAGES', {});
        this.subscriptions.push(dragulaService.drop('PACKAGES').subscribe((value) => {
            this.onDropModel(value);
          }));
    }
    ngOnInit() {
        this.showLoading = true;
      this.subscriptions.push(this._dataService.getPackageOrder(sessionStorage.getItem('selectedLOB'))
        .subscribe(
            data => {
              console.log('In getPackageOrder');
                this.packages = JSON.parse(data['packages']);
                this.showLoading = false;
                this.originalOrder = JSON.parse(data['packages']);
              },
              (err: HttpErrorResponse) => {
                console.log (err.message);
                this.showLoading = false;
              }
        ));
    }
    ngOnDestroy() {
        this.dragulaService.destroy('PACKAGES');
    }
    publishOrder() {
        this.showLoading = true;
        this.newPackageOrder = this.packages.map((item, index) => {
            const newObj = {};
            newObj['id'] = item.id;
            newObj['order'] = index + 1;
            return newObj;
        });
        let param = new HttpParams();
        param = param.set('packageOrderJson', JSON.stringify(this.newPackageOrder));
      this.subscriptions.push(this._dataService.savePackageOrder(param)
            .subscribe(
                data => {
                    console.log('Succesfully published the order.');
                    this.showLoading = false;
                    this.publishSuccess = true;
                  this._notificationsService.emit('refresh report-nav');
                },
                (err: HttpErrorResponse) => {
                  console.log (err.message);
                  this.showLoading = false;
                }
            ));
    }

    private getElementIndex(el: any) {
        return [].slice.call(el.parentElement.children).indexOf(el);
    }
    onDropModel(args) {
        const [bag, target, source, other] = args;
        const index = this.getElementIndex(target);
        const temp = {};
        temp['currentItem'] = this.packages[index].name;
        temp['prevItem'] = index > 0 ? this.packages[index - 1].name : '';
        temp['nextItem'] = this.packages[index + 1] ? this.packages[index + 1].name : '';
        this.movements.push(temp);
        this.validateOrderChanges();
    }

    validateOrderChanges() {
      console.log(this.disablePublish);
      if (JSON.stringify(this.originalOrder) === JSON.stringify(this.packages)) {
        this.disablePublish = true;
      } else { this.disablePublish = false; }
      console.log(this.disablePublish);
    }
}
</code>```

In the above code in html packages is not saving the updated order after drag and drop. Any help is appreciated

Body:
I have upgraded to Angular 11 and accordingly upgraded the version of ng-dragula from 1.3.0 to 2.1.1. Now I have a functionality of drag and drop. Below is the code snippet.
order-packages.html

Order Packages

            <button *ngIf="!disablePublish" href="#" class="btn btn-primary" (click)="publishOrder()">Publish Order</button>
            <button *ngIf="disablePublish" [disabled]="disablePublish" class="btn btn-disabled">Publish Order</button>

        <tux-alert *ngIf="publishSuccess" [type]="'success'" [heading]="'Success'" [dismissible]="false">Succesfully published the package order.</tux-alert>
        <app-loading-indicator *ngIf="showLoading"></app-loading-indicator>

test

                 {{ package.name }} ({{package.resourceKey}})

Waiting for reordering the packages...

Moved {{item.currentItem}} between {{item.prevItem}} and {{item.nextItem}}

order-packages.ts

import {Component, OnInit, Input} from '@angular/core';

import { HttpClient, HttpParams, HttpErrorResponse } from '@angular/common/http';

import {DataService} from '../../../shared/services/data.service';
import { DragulaService } from 'ng2-dragula';
import {NotificationsService} from '../../../shared/services/notification.service';
import {AutoUnsubscribe} from '../../../shared/Decorators/autounsubscribe';

@Component({
    selector: 'app-order-packages',
    templateUrl: './order-packages.component.html'
})
@AutoUnsubscribe
export class OrderPackagesComponent  implements OnInit {
    subscriptions: any[] = new Array();
    packages: any;
    orderPackages: any = 'PACKAGES';
    newPackageOrder: any;
    showLoading = false;
    publishSuccess = false;
    disablePublish = true;
    originalOrder: any;
    movements: any = [];
    constructor(private _dataService: DataService, private dragulaService: DragulaService, private _notificationsService: NotificationsService) {
        dragulaService.createGroup('PACKAGES', {});
        this.subscriptions.push(dragulaService.drop('PACKAGES').subscribe((value) => {
            this.onDropModel(value);
          }));
    }
    ngOnInit() {
        this.showLoading = true;
      this.subscriptions.push(this._dataService.getPackageOrder(sessionStorage.getItem('selectedLOB'))
        .subscribe(
            data => {
              console.log('In getPackageOrder');
                this.packages = JSON.parse(data['packages']);
                this.showLoading = false;
                this.originalOrder = JSON.parse(data['packages']);
              },
              (err: HttpErrorResponse) => {
                console.log (err.message);
                this.showLoading = false;
              }
        ));
    }
    ngOnDestroy() {
        this.dragulaService.destroy('PACKAGES');
    }
    publishOrder() {
        this.showLoading = true;
        this.newPackageOrder = this.packages.map((item, index) => {
            const newObj = {};
            newObj['id'] = item.id;
            newObj['order'] = index + 1;
            return newObj;
        });
        let param = new HttpParams();
        param = param.set('packageOrderJson', JSON.stringify(this.newPackageOrder));
      this.subscriptions.push(this._dataService.savePackageOrder(param)
            .subscribe(
                data => {
                    console.log('Succesfully published the order.');
                    this.showLoading = false;
                    this.publishSuccess = true;
                  this._notificationsService.emit('refresh report-nav');
                },
                (err: HttpErrorResponse) => {
                  console.log (err.message);
                  this.showLoading = false;
                }
            ));
    }

    private getElementIndex(el: any) {
        return [].slice.call(el.parentElement.children).indexOf(el);
    }
    onDropModel(args) {
        const [bag, target, source, other] = args;
        const index = this.getElementIndex(target);
        const temp = {};
        temp['currentItem'] = this.packages[index].name;
        temp['prevItem'] = index > 0 ? this.packages[index - 1].name : '';
        temp['nextItem'] = this.packages[index + 1] ? this.packages[index + 1].name : '';
        this.movements.push(temp);
        this.validateOrderChanges();
    }

    validateOrderChanges() {
      console.log(this.disablePublish);
      if (JSON.stringify(this.originalOrder) === JSON.stringify(this.packages)) {
        this.disablePublish = true;
      } else { this.disablePublish = false; }
      console.log(this.disablePublish);
    }
}

In the above code in html packages is not saving the updated order after drag and drop. Any help is appreciated


问:
Issues with text moving below image
So I am trying to make different texts next to specific symbols (in the elevator-pitch div) but somehow the
 element skip rows and text end up below the images. Ideally I want each text to be nicely aligned next to the images (hence making the float).

Here is the code: https://codepen.io/andreassoteriou/pen/PoaLBjv

```<code><!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>AndreasSoteriouCV</title>
    <link rel="stylesheet" href="css/styles.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="https://fonts.googleapis.com/css2?family=Dancing+Script&family=Merriweather&family=Montserrat&family=Pacifico&family=Playball&family=Playfair+Display&display=swap" rel="stylesheet">
  </head>
  <body>
    <div class="top-container">
      <img src="andreassoteriou-modified.png" alt="andreas">
      <h1>Andreas Soteriou</h1>
      <h2>aspiring web developer</h2>
    </div>
      <h1>My Story</h1>
      <div class="elevator-pitch">
        <img class="creativity-img" src="https://cdn-icons-png.flaticon.com/512/1126/1126453.png" alt="creativity">
        <h2>Creativity</h2>
        <p>Why I am creativfdfdfdfdfdfdfdwerv4vrtyvrtyvrtyvyrytve</p>
      </div>
      <hr>
      <div class="elevator-pitch">
        <img class="logical-img" src="https://cdn-icons-png.flaticon.com/128/1935/1935467.png" alt="logical">
        <h2>Logical</h2>
        <p>Why I am creativggggfgotjgirtgfdffdffdfdfdfdfdfd</p>
      </div>
    <div class="story-container">
    </div>
  </body>
</html>
</code>```
```<code>body {
  margin: 0;
  font-family: 'Merriweather', serif;
  text-align: center;
}

.top-container {
  background-color: #F8EDE3;
  margin: 0;
  height: 450px;
  padding-top: 60px;

}

.top-container > h1 {
  margin-top:40px;
  font-size: 40px;
}

.top-container > h2 {
  font-family: 'Dancing script', serif;
  font-size: 30px;

}

.middle-container {

}

.elevator-pitch {
  width: 25%;
  text-align: left;
  line-height: 1.5;
  margin: 50px auto 50px auto;
  overflow:auto;

}

.creativity-img {
  float: left;
  margin-right: 20px;
  width: 30%;
}

.logical-img {
  float: right;
  width: 30%;
  margin-left: 20px;
</code>```

any idea on how I should tackle this? Most importantly, very curious as to why this happens!

Best regards,
Andreas

I was expecting the text to be nicely aligned next to the image as in the udemy course I am doing now:

Title: Issues with text moving below image

Body:
So I am trying to make different texts next to specific symbols (in the elevator-pitch div) but somehow the
 element skip rows and text end up below the images. Ideally I want each text to be nicely aligned next to the images (hence making the float).

Here is the code: https://codepen.io/andreassoteriou/pen/PoaLBjv

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>AndreasSoteriouCV</title>
    <link rel="stylesheet" href="css/styles.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="https://fonts.googleapis.com/css2?family=Dancing+Script&family=Merriweather&family=Montserrat&family=Pacifico&family=Playball&family=Playfair+Display&display=swap" rel="stylesheet">

Andreas Soteriou

aspiring web developer

My Story

Creativity

Why I am creativfdfdfdfdfdfdfdwerv4vrtyvrtyvrtyvyrytve

Logical

Why I am creativggggfgotjgirtgfdffdffdfdfdfdfdfd

body {
  margin: 0;
  font-family: 'Merriweather', serif;
  text-align: center;
}

.top-container {
  background-color: #F8EDE3;
  margin: 0;
  height: 450px;
  padding-top: 60px;

}

.top-container > h1 {
  margin-top:40px;
  font-size: 40px;
}

.top-container > h2 {
  font-family: 'Dancing script', serif;
  font-size: 30px;

}

.middle-container {

}

.elevator-pitch {
  width: 25%;
  text-align: left;
  line-height: 1.5;
  margin: 50px auto 50px auto;
  overflow:auto;

}

.creativity-img {
  float: left;
  margin-right: 20px;
  width: 30%;
}

.logical-img {
  float: right;
  width: 30%;
  margin-left: 20px;

any idea on how I should tackle this? Most importantly, very curious as to why this happens!

Best regards,
Andreas

I was expecting the text to be nicely aligned next to the image as in the udemy course I am doing now:


问:
Create an executable jar project java using command prompt and with multiple package
I would like to create an executable file of my project. I've looked at several tutorials to do this but all the ones I'm looking at do it on the same package. The problem is that my project has many packages and I can't create the executable.
I tried to do in shell in the root folder of my project : javac *.java but it does not work
So I tried to do the same command but in one of the package where some of my classes are. This time I have this error : App.java:3: error: package javafx.application (its an import for my project) does not exist
However, I have the impression to make the right command.

if you want to see what I have

My project :
to the root project has one of the packages with 2 classes
this 2 classes

so in shell I do :

my commande from the package
my error

my commande from the root project and my error

thank you in advance if you can help me a little and thank you for taking the time.


问:
How to implement different pallets but maintain the same component overrides with MUI themes?
I'm working on a react app that uses MUI. We've been developing things within the "light" mode pallet, but would like to add the ability to switch things to a "dark" mode pallet. This change should affect only the colors defined within the pallet and not any of the other css/styling overrides.

I've done by best to understand the documentation and have looked at several different examples that I've found online, but none seem to show how to do this when your theme has more than just pallet. And including another pallet object gives a warning in the console, but I'm convinced there's a way to do this without reverting to just copying and pasting the components and typography parts of the theme to the dark version of the theme. Here's our current theme:

import { createTheme } from "@mui/material/styles";

export const appTheme = createTheme({

  palette: {
    mode: "light",

    neutral: {
      main: "#72ccda",
      one: "#ffffff",
      two: "#f5f5f5",
    },

    primary: {
      main: "#72ccda",
      one: "#9edce5",
      two: "#72ccda",
    },

    info: {
      main: "#72ccda",
      one: "#9edce5",
      two: "#72ccda",
    },

  },

  typography: {
    fontFamily:
      '"Ubuntu", "Segoe UI", "Roboto", "Droid Sans", "Helvetica",  "Arial", sans-serif',
  },

  components: {
    MuiCssBaseline: {
      // "normal" scss styling goes here and will override any MUI stuff
      styleOverrides: `
        .hidden {
          display: none;
          visibility: hidden;
        },

        .json {
          width: 34vw;
          min-wdith: 400px;
          max-width: 800px;
          height: 40vh;
          min-height: 100px;
          max-height: 450px;
          overflow: scroll;
        }
    `,
    },
  },
});

export const darkTheme = createTheme({
  palette: {
    mode: "dark",

    neutral: {
      main: "#72ccda",
      one: "#ffffff",
      two: "#f5f5f5",
    },

    primary: {
      main: "#72ccda",
      one: "#9edce5",
      two: "#72ccda",
    },

    info: {
      main: "#34afc2",
      one: "#9edce5",
      two: "#72ccda",
    },
  },
  typography: {
    fontFamily:
      '"Ubuntu", "Segoe UI", "Roboto", "Droid Sans", "Helvetica",  "Arial", sans-serif',
  },

 components: {
    MuiCssBaseline: {
      // "normal" scss styling goes here and will override any MUI stuff
      styleOverrides: `
        .hidden {
          display: none;
          visibility: hidden;
        },

        .json {
          width: 34vw;
          min-wdith: 400px;
          max-width: 800px;
          height: 40vh;
          min-height: 100px;
          max-height: 450px;
          overflow: scroll;
        }
    `,
    },
});
```


问:
SQLAlchemy: Query against a secondary relationship
I have a User class that looks like this

```<code> class User(db.Model, CommonFields):
    __tablename__ = "user"
    __table_args__ = {"schema": "metadata"}

    emails = db.Column(db.String)
    name = db.Column(db.String)
    client_id = db.Column(db.BigInteger, db.ForeignKey("metadata.client.id"))
    roles = db.relationship("ClientRoles", secondary=user_client_roles)

user_client_roles = db.Table(
    "user_client_roles",
    db.Model.metadata,
    db.Column("users", db.Integer, db.ForeignKey("metadata.user.id")),
    db.Column("client_role_id", db.Integer, db.ForeignKey("metadata.client_role.id"))
</code>```

I am trying to make a query that filters the users against client_id and client_role_id.

For example, if I wanted to get all of the users that had a client_id of 11 but also had a client_role_id of 30. Thus just return me user with id = 1.

This is what I have so far but will return an error because of an incorrect join.

```<code>@classmethod
     def get_users_by_client_role_and_client_id(cls, client_role_id:int, client_id: int):
         return (
             db.session.query(cls)
             .join(user_client_roles)
             .filter_by(client_role_id=client_role_id, client_id=client_id)
             .all()
         )
</code>```

Error:

sqlalchemy.exc.InvalidRequestError: Entity
'metadata.user_client_roles' has no property 'client_id'

Body:
I have a User class that looks like this

 class User(db.Model, CommonFields):
    __tablename__ = "user"
    __table_args__ = {"schema": "metadata"}

    emails = db.Column(db.String)
    name = db.Column(db.String)
    client_id = db.Column(db.BigInteger, db.ForeignKey("metadata.client.id"))
    roles = db.relationship("ClientRoles", secondary=user_client_roles)

user_client_roles = db.Table(
    "user_client_roles",
    db.Model.metadata,
    db.Column("users", db.Integer, db.ForeignKey("metadata.user.id")),
    db.Column("client_role_id", db.Integer, db.ForeignKey("metadata.client_role.id"))

I am trying to make a query that filters the users against client_id and client_role_id.

For example, if I wanted to get all of the users that had a client_id of 11 but also had a client_role_id of 30. Thus just return me user with id = 1.

This is what I have so far but will return an error because of an incorrect join.

@classmethod
     def get_users_by_client_role_and_client_id(cls, client_role_id:int, client_id: int):
         return (
             db.session.query(cls)
             .join(user_client_roles)
             .filter_by(client_role_id=client_role_id, client_id=client_id)
             .all()
         )

Error:

sqlalchemy.exc.InvalidRequestError: Entity
'metadata.user_client_roles' has no property 'client_id'


问:
MOBX: Each page has store for orders, is it correct?
I just got acquainted with MOBX and I'm trying to understand the principles of creating applications with the help of MOBX, using the example of a finished application. I had a question, because I noticed that each page of the app has its own store for orders (the difference is one field). It's definitely the same data. Is it right approach?

Previously, in React applications, I used one store, and any component could use data from it. In this one each page use its own store for specific data and it doesn't matter if we have already created a store with this data for another page.

I have never created duplicate data. But I'm not sure how it should look like with MOBX.

Thanks for help.

I want to understand how create store with MOBX correctly. Can we share one store between different pages/components?


问:
C# DataTable, copy number to excel in string format because first digit is 0?
I need to be able to copy a DataTable in C# to excel, and I have one small problem. When I import a number, lets say, '0203', it comes into Excel as '203'. Our software is very particular and it needs the zero. I am aware adding an apostrophe(') before the number will allow the proper format, but if I manually add it into C#, it doesn't work when copying over. You have to click in and out of each cell, then the single quote method works. But clicking each cell defeats the entire purpose.

Is there a way to copy over a number like '0203' into excel with the formatting?

It needs this way in excel because we have a program that allows data entry through excel. it gives an error when importing into our software.

I added an apostrophe in C#. It doesn't format the cell until you click in. Example: '0203 instead of 0203 showing in excel, giving an error for my import.


问:
CONCAT not working in mysql56, need help running below sql
So I am using MySQL56, with nodejs. When trying to create the table below, I get an error for the uniqueId line. the error i get is:

CONCAT is not valid at this position.

```<code>CREATE TABLE IF NOT EXISTS `tickets` (
`id` INTEGER NOT NULL auto_increment ,
`title` VARCHAR(255),
`uniqueId` VARCHAR(255) DEFAULT concat(Test_string, `id`) UNIQUE,
`imageUrl` VARCHAR(255) NOT NULL,
`description` VARCHAR(255) NOT NULL,
`createdAt` DATETIME NOT NULL,
`updatedAt` DATETIME NOT NULL,
PRIMARY KEY (`id`)) ENGINE=InnoDB;
</code>```

Body:
So I am using MySQL56, with nodejs. When trying to create the table below, I get an error for the uniqueId line. the error i get is:

CONCAT is not valid at this position.

CREATE TABLE IF NOT EXISTS `tickets` (
`id` INTEGER NOT NULL auto_increment ,
`title` VARCHAR(255),
`uniqueId` VARCHAR(255) DEFAULT concat(Test_string, `id`) UNIQUE,
`imageUrl` VARCHAR(255) NOT NULL,
`description` VARCHAR(255) NOT NULL,
`createdAt` DATETIME NOT NULL,
`updatedAt` DATETIME NOT NULL,
PRIMARY KEY (`id`)) ENGINE=InnoDB;


问:
Deleting with TypeORM when a join is needed
I am trying to delete Author when their book is over a year old.

Author

```<code>@Entity()

export class Author {
@PrimaryGeneratedColumn()
id: number;

@Column()
@OneToMany(() => Book)
book: Book[];
</code>```

Book

```<code>@Entity()

export class Book {
@PrimaryGeneratedColumn()
id: number;

@Column()
timestamp: Date;

@Column()
ManyToOne(() => Author)
author: Author
</code>```

In typeorm, I have tried to multiple variations of this delete query:

```<code>const AuthorRepo = DataSource.manager.getRepository(Author);

AuthorRepo
    .createQueryBuilder('author')
    .delete()
    .leftJoin('author.book', 'book')
    .where('book.timestamp < new Date(new Date().getTime() - 365 * 24 * 60 * 60 * 1000)
    .execute();
</code>```

The issue is TypeORM not allowing joins in a delete, I would be open to a pure SQL query worst case.

Body:
I am trying to delete Author when their book is over a year old.

Author

@Entity()

export class Author {
@PrimaryGeneratedColumn()
id: number;

@Column()
@OneToMany(() => Book)
book: Book[];

Book

@Entity()

export class Book {
@PrimaryGeneratedColumn()
id: number;

@Column()
timestamp: Date;

@Column()
ManyToOne(() => Author)
author: Author

In typeorm, I have tried to multiple variations of this delete query:

const AuthorRepo = DataSource.manager.getRepository(Author);

AuthorRepo
    .createQueryBuilder('author')
    .delete()
    .leftJoin('author.book', 'book')
    .where('book.timestamp < new Date(new Date().getTime() - 365 * 24 * 60 * 60 * 1000)
    .execute();

The issue is TypeORM not allowing joins in a delete, I would be open to a pure SQL query worst case.


问:
Ag-Grid AutoColumnSizing not working for longer content
I'm using ag-grid ng2 v28.1, and some columns are autosizing, and some are not (using selective column autoresize based on ColId). On both Chrome and Edge. I dug into the autosize code, and something is preventing the dummy container from actually growing its contents based on the dummy row/cells cloned into it. I see the cells with their content but the measuring span doesn't seem to be expanding based on its contents. I have stripped out all my own styles and div layers from my cellRender, and it still doesn't work. I can't find any CSS reason why that span won't expand to consider it's contents.

Anyone ever hit up against this wall?