问:
using nn.Cross entropy between outputs and target label
I use this code

function to train the model

```<code>def train():

  model.train()

  total_loss, total_accuracy = 0, 0

  # empty list to save model predictions
  total_preds=[]

  # iterate over batches
  for step,batch in enumerate(train_dataloader):

    # progress update after every 50 batches.
    if step % 50 == 0 and not step == 0:
      print('  Batch {:>5,}  of  {:>5,}.'.format(step, len(train_dataloader)))

    # push the batch to gpu
    #batch = [r for r in batch]

    sent_id, mask, labels = batch['input_ids'],batch['attention_mask'],batch['labels']
    print(6)
    print(sent_id)
    print(mask)
    print(labels)
    print(batch['input_ids'].shape)
    print(batch['attention_mask'].shape)
    print(batch['labels'].shape)

    # clear previously calculated gradients
    model.zero_grad()
    print(7)

    # get model predictions for the current batch
    preds = model(sent_id, mask)
    print(8)
    print(len(preds))
    print(len(labels))
    print(preds.size())

    preds =torch.argmax(preds, dim=1)
    preds =torch.argmax(preds, dim=1)
    print(preds)
    print(labels)

    # compute the loss between actual and predicted values
    loss = loss_fn(preds, labels)
    print(9)

    # add on to the total loss
    total_loss = total_loss + loss.item()
    print(10)

    # backward pass to calculate the gradients
    loss.backward()

    # clip the the gradients to 1.0. It helps in preventing the exploding gradient problem
  # clip the the gradients to 1.0. It helps in preventing the exploding gradient problem
    torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)

    # update parameters
    optimizer.step()

    # model predictions are stored on GPU. So, push it to CPU
    preds=preds.numpy()

    # append the model predictions
    total_preds.append(preds)

  # compute the training loss of the epoch
  avg_loss = total_loss / len(train_dataloader)

  # predictions are in the form of (no. of batches, size of batch, no. of classes).
  # reshape the predictions in form of (number of samples, no. of classes)
  total_preds  = np.concatenate(total_preds, axis=0)

  #returns the loss and predictions
  return avg_loss, total_preds
</code>```
```<code>import torch.nn as nn

loss_fn=nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.00001)
</code>```

i got error in calculation of loss
preds
tensor([5, 1, 1, 1, 0, 2, 1, 4, 2, 3, 0, 2, 0, 1, 0, 3, 5, 3, 1, 2, 0, 2, 2, 1,
0, 1, 4, 0, 5, 5, 4, 5, 0, 2, 0, 1, 4, 0, 0, 3, 5, 1, 1, 1, 4, 4, 4, 1,
2, 1, 3, 3, 2, 1, 0, 2, 0, 4, 4, 4, 3, 2, 0, 5])

labels
tensor([0, 0, 1, 2, 3, 0, 0, 0, 0, 1, 1, 0, 0, 0, 4, 0, 0, 2, 1, 0, 0, 0, 0, 0,
1, 0, 0, 1, 1, 2, 1, 3, 2, 0, 3, 4, 0, 1, 0, 0, 0, 0, 0, 0, 5, 0, 0, 3,
0, 0, 1, 0, 0, 0, 2, 0, 0, 2, 0, 0, 2, 0, 0, 0])
i used them in
loss=loss_fn(preds,labels)
error:

```<code>in cross_entropy(input, target, weight, size_average, ignore_index, reduce, reduction, label_smoothing)
   2844     if size_average is not None or reduce is not None:
   2845         reduction = _Reduction.legacy_get_string(size_average, reduce)
-> 2846     return torch._C._nn.cross_entropy_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index, label_smoothing)
   2847
   2848

RuntimeError: Expected floating point type for target with class probabilities, got Long
</code>```

答:
The problem is that you passing the wrong value of preds (tensor) to the loss_fn function. Look well and you will notice that you are passing the output of preds = torch.argmax(preds, dim=1) while you should pass the output of preds = model(sent_id, mask). Doing so you are passing two tensors of dtype int64 to the loss function. However, the loss function (CrossEntropyLoss) expects a tensor of dtype float32 as its first parameter (i.e. the input parameter) -- see in 'Examples' at https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html. Then you get a error: "Expected floating point type..."

To solve the problem you can compute the loss before changing the value of preds (i.e. before preds = torch.argmax(preds, dim=1)), as I do bellow. Or you could give another name to the output of model(), for instance outp, and pass it to your loss function, like: loss_fn(outp, labels).

# get model predictions for the current batch

```<code>preds = model(sent_id, mask)
</code>```

# compute the loss between actual and predicted values

```<code>loss = loss_fn(preds, labels)
preds =torch.argmax(preds, dim=1)
</code>```

Body:
I use this code

function to train the model

def train():

  model.train()

  total_loss, total_accuracy = 0, 0

  # empty list to save model predictions
  total_preds=[]

  # iterate over batches
  for step,batch in enumerate(train_dataloader):

    # progress update after every 50 batches.
    if step % 50 == 0 and not step == 0:
      print('  Batch {:>5,}  of  {:>5,}.'.format(step, len(train_dataloader)))

    # push the batch to gpu
    #batch = [r for r in batch]

    sent_id, mask, labels = batch['input_ids'],batch['attention_mask'],batch['labels']
    print(6)
    print(sent_id)
    print(mask)
    print(labels)
    print(batch['input_ids'].shape)
    print(batch['attention_mask'].shape)
    print(batch['labels'].shape)

    # clear previously calculated gradients
    model.zero_grad()
    print(7)

    # get model predictions for the current batch
    preds = model(sent_id, mask)
    print(8)
    print(len(preds))
    print(len(labels))
    print(preds.size())

    preds =torch.argmax(preds, dim=1)
    preds =torch.argmax(preds, dim=1)
    print(preds)
    print(labels)

    # compute the loss between actual and predicted values
    loss = loss_fn(preds, labels)
    print(9)

    # add on to the total loss
    total_loss = total_loss + loss.item()
    print(10)

    # backward pass to calculate the gradients
    loss.backward()

    # clip the the gradients to 1.0. It helps in preventing the exploding gradient problem
  # clip the the gradients to 1.0. It helps in preventing the exploding gradient problem
    torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)

    # update parameters
    optimizer.step()

    # model predictions are stored on GPU. So, push it to CPU
    preds=preds.numpy()

    # append the model predictions
    total_preds.append(preds)

  # compute the training loss of the epoch
  avg_loss = total_loss / len(train_dataloader)

  # predictions are in the form of (no. of batches, size of batch, no. of classes).
  # reshape the predictions in form of (number of samples, no. of classes)
  total_preds  = np.concatenate(total_preds, axis=0)

  #returns the loss and predictions
  return avg_loss, total_preds

import torch.nn as nn

loss_fn=nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.00001)

i got error in calculation of loss
preds
tensor([5, 1, 1, 1, 0, 2, 1, 4, 2, 3, 0, 2, 0, 1, 0, 3, 5, 3, 1, 2, 0, 2, 2, 1,
0, 1, 4, 0, 5, 5, 4, 5, 0, 2, 0, 1, 4, 0, 0, 3, 5, 1, 1, 1, 4, 4, 4, 1,
2, 1, 3, 3, 2, 1, 0, 2, 0, 4, 4, 4, 3, 2, 0, 5])

labels
tensor([0, 0, 1, 2, 3, 0, 0, 0, 0, 1, 1, 0, 0, 0, 4, 0, 0, 2, 1, 0, 0, 0, 0, 0,
1, 0, 0, 1, 1, 2, 1, 3, 2, 0, 3, 4, 0, 1, 0, 0, 0, 0, 0, 0, 5, 0, 0, 3,
0, 0, 1, 0, 0, 0, 2, 0, 0, 2, 0, 0, 2, 0, 0, 0])
i used them in
loss=loss_fn(preds,labels)
error:

in cross_entropy(input, target, weight, size_average, ignore_index, reduce, reduction, label_smoothing)
   2844     if size_average is not None or reduce is not None:
   2845         reduction = _Reduction.legacy_get_string(size_average, reduce)
-> 2846     return torch._C._nn.cross_entropy_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index, label_smoothing)
   2847
   2848

RuntimeError: Expected floating point type for target with class probabilities, got Long

Body:
The problem is that you passing the wrong value of preds (tensor) to the loss_fn function. Look well and you will notice that you are passing the output of preds = torch.argmax(preds, dim=1) while you should pass the output of preds = model(sent_id, mask). Doing so you are passing two tensors of dtype int64 to the loss function. However, the loss function (CrossEntropyLoss) expects a tensor of dtype float32 as its first parameter (i.e. the input parameter) -- see in 'Examples' at https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html. Then you get a error: "Expected floating point type..."

To solve the problem you can compute the loss before changing the value of preds (i.e. before preds = torch.argmax(preds, dim=1)), as I do bellow. Or you could give another name to the output of model(), for instance outp, and pass it to your loss function, like: loss_fn(outp, labels).

# get model predictions for the current batch

preds = model(sent_id, mask)

# compute the loss between actual and predicted values

loss = loss_fn(preds, labels)
preds =torch.argmax(preds, dim=1)


来源: stackexchange

问:
C# program that can connect to different SQL databases
Is it possible to make a C# program that can connect to different SQL databases? I've watched multiple videos about it and they all connect to only one database. Is it possible to add something like a search box to a program where you type in the server name and connect to it?Something like this Thanks in advance.</p>

答:
Yes.
Any C# program or module uses some database framework or module to connect to the database server, using the information like server name/ip, db name, user name or credentials, etc.,
Read about the various ways in which you can connect to databases and retrieve data using C# - there is ADO.NET, Entity Framework, Dapper and so on.

PS: As per SO guidelines, this question needs to be more focussed, than a 'is it possible' type of question. See How to Ask questions in SO.

ContentLicense: CC BY-SA 4.0


问:
What does if [ $? -eq 0 ] mean for shell scripts?
There is this line in a shell script i have seen:</p>

```<code>grep -e ERROR ${LOG_DIR_PATH}/${LOG_NAME}  > /dev/null
if [ $? -eq 0 ]
</code>```

答:
It's checking the return value ($?) of grep. In this case it's comparing it to 0 (success).

Usually when you see something like this (checking the return value of grep) it's checking to see whether the particular string was detected. Although the redirect to /dev/null isn't necessary, the same thing can be accomplished using -q.

ContentLicense: CC BY-SA 3.0

Body:
There is this line in a shell script i have seen:

grep -e ERROR ${LOG_DIR_PATH}/${LOG_NAME}  > /dev/null
if [ $? -eq 0 ]


问:
Uncommon homebrew error: "Unknown command: switch"
I am in the process of trying to restart some legacy project that demands the use of an older version of openssl.

I have found good input on the issue here, which worked on one of my machines but not the other, which gives me the following error:

```<code>$  brew switch openssl 1.0.2t
Error: Unknown command: switch
</code>```

The error does not seem to be very common, nothing helpful is showing up on a google/stackoverflow search.

What I have tried so far:

resolved all warnings shown by brew doctor

run brew update && brew upgrade

updated Xcode Command Line Tools

reinstalled openssl

What can I do to fix this?

答:
I just used sudo:

```<code>sudo brew switch dart 2.16.0
</code>```

and close the vs code and start again.
That's it and run without any errors.

Body:
I am in the process of trying to restart some legacy project that demands the use of an older version of openssl.

I have found good input on the issue here, which worked on one of my machines but not the other, which gives me the following error:

$  brew switch openssl 1.0.2t
Error: Unknown command: switch

The error does not seem to be very common, nothing helpful is showing up on a google/stackoverflow search.

What I have tried so far:

resolved all warnings shown by brew doctor

run brew update && brew upgrade

updated Xcode Command Line Tools

reinstalled openssl

What can I do to fix this?

Body:
I just used sudo:

sudo brew switch dart 2.16.0

and close the vs code and start again.
That's it and run without any errors.


问:
How can i call a modal component from another page
I am having a modal component shown below, which is opening by default because the open state is set to true.

```<code> import { Fragment, useRef, useState } from 'react'
    import { Dialog, Transition } from '@headlessui/react'
    import { FcApproval,  } from "react-icons/fc";

    export default function Modal() {
      const [open, setOpen] = useState(true)

      const cancelButtonRef = useRef(null)

      return (
        <Transition.Root show={open} as={Fragment}>
          <Dialog as="div" className="fixed z-10 inset-0 overflow-y-auto" initialFocus={cancelButtonRef}  static onClose={() => null}>
            <div className="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
              <Transition.Child
                as={Fragment}
                enter="ease-out duration-300"
                enterFrom="opacity-0"
                enterTo="opacity-100"
                leave="ease-in duration-200"
                leaveFrom="opacity-100"
                leaveTo="opacity-0"
              >
                <Dialog.Overlay className="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" />
              </Transition.Child>

              <span className="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">

              </span>
              <Transition.Child
                as={Fragment}
                enter="ease-out duration-300"
                enterFrom="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
                enterTo="opacity-100 translate-y-0 sm:scale-100"
                leave="ease-in duration-200"
                leaveFrom="opacity-100 translate-y-0 sm:scale-100"
                leaveTo="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
              >
                <div className="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
                  <div className="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                    <div className="sm:flex sm:items-start">
                      <div className="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-red-100 sm:mx-0 sm:h-10 sm:w-10">
                     <FcApproval size={100} />
                      </div>
                      <div className="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
                        <Dialog.Title as="h3" className="text-lg leading-6 font-medium text-gray-900">
                          <b>Registered Successfully</b>
                        </Dialog.Title>
                        <div className="mt-2 inline-block">
                          <p className="text-sm text-gray-500">
                            Yayy,Start your shopping
                          </p>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div className="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                    <button
                      type="button"
                      className="w-full inline-flex justify-center rounded-md border border-
                      transparent shadow-sm px-4 py-2 bg-green-600 text-base font-medium text-white
                      hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2
                      focus:ring-green-500 sm:ml-3 sm:w-auto sm:text-sm"
                      onClick={() => setOpen(false)}
                    >
                      Continue
                  </div>
                </div>
              </Transition.Child>
            </div>
          </Dialog>
        </Transition.Root>
      )
    }
</code>```

But when I call a function to trigger the modal component it does not open up the modal.

But when I call a function to trigger the modal component it does not open up the modal.

Example

```<code>OpenModal.js

export default function openModal() {
  const popModal = () => {
     return <Modal />
   }
  return (
    <div className='App'>
    <button onClick={popModal}>Open Modal</button>
   </div>
  );
}
</code>```

What am i doing wrong?

答:
I'm sorry, I cannot exactly point out why your approach is wrong, but it just not how it works. Instead I would do something similar to this:

```<code>// Some component using your Modal

const [modalVisible, setModalVisible] = useState(false);

return (
  <>
   <button onClick={() => setModalVisible(true)}>Open Modal</button>
   {/* Modal accepts visible and onClose props */}
   <Modal visible={modalVisible} onClose={() => setModalVisible(false)}
  </>
)
</code>```

This way you can easily control the state of the modal, in every single component that you're using.

Body:
I am having a modal component shown below, which is opening by default because the open state is set to true.

 import { Fragment, useRef, useState } from 'react'
    import { Dialog, Transition } from '@headlessui/react'
    import { FcApproval,  } from "react-icons/fc";

    export default function Modal() {
      const [open, setOpen] = useState(true)

      const cancelButtonRef = useRef(null)

      return (
        <Transition.Root show={open} as={Fragment}>
          <Dialog as="div" className="fixed z-10 inset-0 overflow-y-auto" initialFocus={cancelButtonRef}  static onClose={() => null}>

              <Transition.Child
                as={Fragment}
                enter="ease-out duration-300"
                enterFrom="opacity-0"
                enterTo="opacity-100"
                leave="ease-in duration-200"
                leaveFrom="opacity-100"
                leaveTo="opacity-0"
              >
                <Dialog.Overlay className="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" />
              </Transition.Child>

              <Transition.Child
                as={Fragment}
                enter="ease-out duration-300"
                enterFrom="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
                enterTo="opacity-100 translate-y-0 sm:scale-100"
                leave="ease-in duration-200"
                leaveFrom="opacity-100 translate-y-0 sm:scale-100"
                leaveTo="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
              >

                     <FcApproval size={100} />

                        <Dialog.Title as="h3" className="text-lg leading-6 font-medium text-gray-900">
                          Registered Successfully
                        </Dialog.Title>

                            Yayy,Start your shopping

                    <button
                      type="button"
                      className="w-full inline-flex justify-center rounded-md border border-
                      transparent shadow-sm px-4 py-2 bg-green-600 text-base font-medium text-white
                      hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2
                      focus:ring-green-500 sm:ml-3 sm:w-auto sm:text-sm"
                      onClick={() => setOpen(false)}
                    >
                      Continue

              </Transition.Child>

          </Dialog>
        </Transition.Root>
      )
    }

But when I call a function to trigger the modal component it does not open up the modal.

But when I call a function to trigger the modal component it does not open up the modal.

Example

OpenModal.js

export default function openModal() {
  const popModal = () => {
     return <Modal />
   }
  return (

    <button onClick={popModal}>Open Modal</button>

  );
}

What am i doing wrong?

Body:
I'm sorry, I cannot exactly point out why your approach is wrong, but it just not how it works. Instead I would do something similar to this:

// Some component using your Modal

const [modalVisible, setModalVisible] = useState(false);

return (
  <>
   <button onClick={() => setModalVisible(true)}>Open Modal</button>
   {/* Modal accepts visible and onClose props */}
   <Modal visible={modalVisible} onClose={() => setModalVisible(false)}
  </>
)

This way you can easily control the state of the modal, in every single component that you're using.


问:
Closest subsequent index for a specified value
Consider a vector:

int = c(1, 1, 0, 5, 2, 0, 0, 2)
```
<p>I'd like to get the closest subsequent index (not the difference) for a specified value. The first parameter of the function should be the vector, while the second should be the value one wants to see the closest subsequent elements.</p>
<p>For instance,</p>
<pre class="lang-r prettyprint-override"><code>f(int, 0)
# [1] 2 1 0 2 1 0 0 NA
</code>```

Here, the first element of the vector (1) is two positions away from the first subsequent 0, (3 - 1 = 2), so it should return 2. Then the second element is 1 position away from a 0 (2 - 1 = 1). When there is no subsequent values that match the specified value, return NA (here it's the case for the last element, because no subsequent value is 0).

Other examples:

f(int, 1)
# [1] 0 0 NA NA NA NA NA NA

f(int, 2)
# [1] 4 3 2 1 0 2 1 0

f(int, 3)
# [1] NA NA NA NA NA NA NA NA
```
<p>This should also work for character vectors:</p>
<pre class="lang-r prettyprint-override"><code>char = c("A", "B", "C", "A", "A")

f(char, "A")
# [1] 0 2 1 0 0
</code>```

答:
A base R option using ave + cumsum

```<code>f <- function(init, k) {
  ave(
    seq_along(init),
    c(0, head(cumsum(init == k), -1)),
    FUN = function(x) if (any(x == k)) rev(seq_along(x) - 1) else NA
  )
}
</code>```

and you will see

```<code>> f(init, 0)
[1]  2  1  0  2  1  0  0 NA

> f(init, 1)
[1]  0  0 NA NA NA NA NA NA

> f(init, 2)
[1] 4 3 2 1 0 2 1 0

> f(init, 3)
[1] NA NA NA NA NA NA NA NA
</code>```

Body:
Consider a vector:

int = c(1, 1, 0, 5, 2, 0, 0, 2)

I'd like to get the closest subsequent index (not the difference) for a specified value. The first parameter of the function should be the vector, while the second should be the value one wants to see the closest subsequent elements.

For instance,

f(int, 0)
# [1] 2 1 0 2 1 0 0 NA

Here, the first element of the vector (1) is two positions away from the first subsequent 0, (3 - 1 = 2), so it should return 2. Then the second element is 1 position away from a 0 (2 - 1 = 1). When there is no subsequent values that match the specified value, return NA (here it's the case for the last element, because no subsequent value is 0).

Other examples:

f(int, 1)
# [1] 0 0 NA NA NA NA NA NA

f(int, 2)
# [1] 4 3 2 1 0 2 1 0

f(int, 3)
# [1] NA NA NA NA NA NA NA NA

This should also work for character vectors:

char = c("A", "B", "C", "A", "A")

f(char, "A")
# [1] 0 2 1 0 0

Body:
A base R option using ave + cumsum

f <- function(init, k) {
  ave(
    seq_along(init),
    c(0, head(cumsum(init == k), -1)),
    FUN = function(x) if (any(x == k)) rev(seq_along(x) - 1) else NA
  )
}

and you will see

> f(init, 0)
[1]  2  1  0  2  1  0  0 NA

> f(init, 1)
[1]  0  0 NA NA NA NA NA NA

> f(init, 2)
[1] 4 3 2 1 0 2 1 0

> f(init, 3)
[1] NA NA NA NA NA NA NA NA


问:
'cdk destroy' is not working as intended or I am not understanding it correctly?
Here is my demo stack,

```<code>export class HelloCdkStack extends cdk.Stack {
  constructor(parent: cdk.App, id: string, props?: cdk.StackProps) {
    super(parent, id, props);
    new s3.Bucket(this, 'MyFirstBucket', {
      versioned: true,
      encryption: s3.BucketEncryption.KmsManaged,
    });
  }
}
</code>```

'cdk deploy' creates a new bucket, but when I execute 'cdk destroy' it does not delete the bucket. Am I doing anything wrong?

答:
In my case the problem was, cdk was trying to fetch different accounts Credentials. Add the --verbose or -v flag to see if any exception is thrown internally.

It's a shame that the exception was not getting logged to stdout or stderr (as it should for any tool)

Body:
Here is my demo stack,

export class HelloCdkStack extends cdk.Stack {
  constructor(parent: cdk.App, id: string, props?: cdk.StackProps) {
    super(parent, id, props);
    new s3.Bucket(this, 'MyFirstBucket', {
      versioned: true,
      encryption: s3.BucketEncryption.KmsManaged,
    });
  }
}

'cdk deploy' creates a new bucket, but when I execute 'cdk destroy' it does not delete the bucket. Am I doing anything wrong?


问:
How to multiply test data sets in JUnit 5 Parameterized test?
Here is an example of Parameterized test in JUnit 5.

```<code>@ParameterizedTest
@MethodSource("generalDataset")
fun shouldCreateItem(color: String, size: String) {
    val item = Item(color, size)

    assertThat(item.color).isEqualTo(color)
}

@JvmStatic
fun generalDataset() =
    Stream.of(
        arguments("blue", "S"),
        arguments("red", "S"),
        arguments("green", "S"),
        arguments("blue", "L"),
        arguments("red", "L"),
        arguments("green", "L")
    )
</code>```

See that generalDataset is a multiplcation of two sets {"blue", "red", "green"} x {"S", "L"}.

To avoid duplication it would be great to describe it explicitly like this pseudocode

```<code>@ParameterizedTest
@MethodSource("colorDataset"  %MULTIPLY%  "sizeDataset")
fun shouldCreateItem(color: String, size: String) {
    val item = Item(color, size)

    assertThat(item.color).isEqualTo(color)
}

@JvmStatic
fun colorDataset() =
    Stream.of(
        arguments("blue"),
        arguments("red"),
        arguments("green")
    )

@JvmStatic
fun sizeDataset() =
    Stream.of(
        arguments("S"),
        arguments("L")
    )
</code>```

Is it possible to implement something similar (Parameterized test with multiplied sources) in JUnit 5?

答:
You can specify a method as the source. In that method you can provide the cartesian product.

Simple example:

```<code>@ParameterizedTest
@MethodSource("provideStringsForIsBlank")
...

private static Stream<Arguments> provideStringsForIsBlank() {
    return Stream.of(
      Arguments.of(null, true),
      Arguments.of("", true),
      Arguments.of("  ", true),
      Arguments.of("not blank", false)
    );
}
</code>```

Reference: https://www.baeldung.com/parameterized-tests-junit-5

Body:
Here is an example of Parameterized test in JUnit 5.

@ParameterizedTest
@MethodSource("generalDataset")
fun shouldCreateItem(color: String, size: String) {
    val item = Item(color, size)

    assertThat(item.color).isEqualTo(color)
}

@JvmStatic
fun generalDataset() =
    Stream.of(
        arguments("blue", "S"),
        arguments("red", "S"),
        arguments("green", "S"),
        arguments("blue", "L"),
        arguments("red", "L"),
        arguments("green", "L")
    )

See that generalDataset is a multiplcation of two sets {"blue", "red", "green"} x {"S", "L"}.

To avoid duplication it would be great to describe it explicitly like this pseudocode

@ParameterizedTest
@MethodSource("colorDataset"  %MULTIPLY%  "sizeDataset")
fun shouldCreateItem(color: String, size: String) {
    val item = Item(color, size)

    assertThat(item.color).isEqualTo(color)
}

@JvmStatic
fun colorDataset() =
    Stream.of(
        arguments("blue"),
        arguments("red"),
        arguments("green")
    )

@JvmStatic
fun sizeDataset() =
    Stream.of(
        arguments("S"),
        arguments("L")
    )

Is it possible to implement something similar (Parameterized test with multiplied sources) in JUnit 5?

Body:
You can specify a method as the source. In that method you can provide the cartesian product.

Simple example:

@ParameterizedTest
@MethodSource("provideStringsForIsBlank")
...

private static Stream<Arguments> provideStringsForIsBlank() {
    return Stream.of(
      Arguments.of(null, true),
      Arguments.of("", true),
      Arguments.of("  ", true),
      Arguments.of("not blank", false)
    );
}

Reference: https://www.baeldung.com/parameterized-tests-junit-5


问:
Android PDF Rendering
I would like to render/open PDF file (stored in SDCard) in Android without using in-build application or viewer.

1) We have tried MuPDF open source library but rendering using this library is very slow.

2) Can we use iText library for rendering PDF files in Android (i.e. iText as a PDF Viewer).

Is there any other PDF library(open source) that can be used in Android Or suggest basic guideline for developing PDF viewer for Android.

答:
Take a look at my PDF reader for Android here at anddev.
As I remember it uses modified PDFBox (without things related to editing), and features my own font converter (to feed fonts to Android and render them faster).

I don't develop PDF reader anymore and I can make all my changes opensource (though it will require some work, and time). You can try it out to find out how well it performs for you. Note: reader doesn't support encryption and copy-protection.

Title: Android PDF Rendering


问:
Create column conditioning the behavior of rows in the dataset
I would like to do something very specific. I have a vast set of data, which, in summary, looks more or less like this, with values 0, 1 and 2:

I need to create a situation variable so that it contains the value 0, 1 and 2.

The value 0 for cases that contain only 0's and 1's in the entire line.

The value 1 for the case where the value 2 appears, but at some point 1 appears before it.

The value 2 for the case where the value 2 appears, but at some point 0 appears before it.

So it's something close to:

```<code>structure(list(X1 = c(1, 1, 1, 1, 1, 1, 1, 1, 0, 1), X2 = c(1,
1, 1, 1, 0, 0, 0, 0, 0, 2), X3 = c(0, 1, 1, 1, 1, 0, 0, 1, 0,
0), X4 = c(0, 1, 1, 0, 1, 1, 0, 0, 0, 0), X5 = c(2, 1, 1, 0,
2, 1, 1, 0, 0, 0), X6 = c(2, 1, 1, 0, 2, 1, 1, 0, 0, 0), X7 = c(2,
1, 1, 1, 2, 1, 1, 2, 0, 0), X8 = c(0, 1, 1, 1, 2, 1, 2, 2, 2,
0)), class = "data.frame", row.names = c(NA, 10L))
</code>```

答:
Here's a tidyverse approach.

I'll first concatenate all columns together, then use grepl() to look for 12 or 02.

```<code>library(tidyverse)

df %>% rowwise() %>%
  mutate(concat = paste(c_across(everything()), collapse = "")) %>%
  ungroup() %>%
  mutate(situation = case_when(
    !grepl(2, concat) ~ 0,
    grepl("12", concat) ~ 1,
    grepl("02", concat) ~ 2
  )) %>%
  select(-concat)
</code>```

Output

```<code># A tibble: 10 x 9
      X1    X2    X3    X4    X5    X6    X7    X8 situation
   <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>     <dbl>
 1     1     1     0     0     2     2     2     0         2
 2     1     1     1     1     1     1     1     1         0
 3     1     1     1     1     1     1     1     1         0
 4     1     1     1     0     0     0     1     1         0
 5     1     0     1     1     2     2     2     2         1
 6     1     0     0     1     1     1     1     1         0
 7     1     0     0     0     1     1     1     2         1
 8     1     0     1     0     0     0     2     2         2
 9     0     0     0     0     0     0     0     2         2
10     1     2     0     0     0     0     0     0         1
</code>```

Note that this solution assumes that:

2 will not appear in the first column

1 or 2 in the situation is defined by the number immediately before 2 in your dataset

There will not be a case of 12 and 02 happening in the same row

Body:
I would like to do something very specific. I have a vast set of data, which, in summary, looks more or less like this, with values 0, 1 and 2:

I need to create a situation variable so that it contains the value 0, 1 and 2.

The value 0 for cases that contain only 0's and 1's in the entire line.

The value 1 for the case where the value 2 appears, but at some point 1 appears before it.

The value 2 for the case where the value 2 appears, but at some point 0 appears before it.

So it's something close to:

structure(list(X1 = c(1, 1, 1, 1, 1, 1, 1, 1, 0, 1), X2 = c(1,
1, 1, 1, 0, 0, 0, 0, 0, 2), X3 = c(0, 1, 1, 1, 1, 0, 0, 1, 0,
0), X4 = c(0, 1, 1, 0, 1, 1, 0, 0, 0, 0), X5 = c(2, 1, 1, 0,
2, 1, 1, 0, 0, 0), X6 = c(2, 1, 1, 0, 2, 1, 1, 0, 0, 0), X7 = c(2,
1, 1, 1, 2, 1, 1, 2, 0, 0), X8 = c(0, 1, 1, 1, 2, 1, 2, 2, 2,
0)), class = "data.frame", row.names = c(NA, 10L))

Body:
Here's a tidyverse approach.

I'll first concatenate all columns together, then use grepl() to look for 12 or 02.

library(tidyverse)

df %>% rowwise() %>%
  mutate(concat = paste(c_across(everything()), collapse = "")) %>%
  ungroup() %>%
  mutate(situation = case_when(
    !grepl(2, concat) ~ 0,
    grepl("12", concat) ~ 1,
    grepl("02", concat) ~ 2
  )) %>%
  select(-concat)

Output

# A tibble: 10 x 9
      X1    X2    X3    X4    X5    X6    X7    X8 situation
   <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>     <dbl>
 1     1     1     0     0     2     2     2     0         2
 2     1     1     1     1     1     1     1     1         0
 3     1     1     1     1     1     1     1     1         0
 4     1     1     1     0     0     0     1     1         0
 5     1     0     1     1     2     2     2     2         1
 6     1     0     0     1     1     1     1     1         0
 7     1     0     0     0     1     1     1     2         1
 8     1     0     1     0     0     0     2     2         2
 9     0     0     0     0     0     0     0     2         2
10     1     2     0     0     0     0     0     0         1

Note that this solution assumes that:

2 will not appear in the first column

1 or 2 in the situation is defined by the number immediately before 2 in your dataset

There will not be a case of 12 and 02 happening in the same row


问:
pandas - How to unstack dict column values to 2 new columns with the same name to all?
I currently have the dataframe bellow, with a dict inside the column value.

```<code>     variable    value
0       b44     {55: 20}
1       a11     {56: 19}
5       a34     {33: 19}
</code>```

How to transform the above df to a df that looks like this:

```<code>      variable    id   value
0       b44       55     20
1       a11       56     19
5       a34       33     19
</code>```

答:
You can use the apply function :

```<code>df['id'] = df.values.apply(lambda x: list(x.keys())[0])
df['value'] = df.values.apply(lambda x: list(x.values())[0])
</code>```

Body:
I currently have the dataframe bellow, with a dict inside the column value.

     variable    value
0       b44     {55: 20}
1       a11     {56: 19}
5       a34     {33: 19}

How to transform the above df to a df that looks like this:

      variable    id   value
0       b44       55     20
1       a11       56     19
5       a34       33     19

Body:
You can use the apply function :

df['id'] = df.values.apply(lambda x: list(x.keys())[0])
df['value'] = df.values.apply(lambda x: list(x.values())[0])


答:
```<code>import pandas as pd
df = pd.DataFrame({'variable': ['b44', 'a11', 'a34'],'value': [{55: 20}, {56: 19}, {33: 19}]})
df = df.assign(**{'key': df.value.apply(lambda x: list(x.keys())[0]), 'value': df.value.apply(lambda x: list(x.values())[0])})
</code>```

Title: pandas - How to unstack dict column values to 2 new columns with the same name to all?


问:
add/overwrite field of type array in Firestore
I want to add a field of type array inside a collection.

if the field doesn't exist create it. if it exists overwrite it with the new array value.

the field should be called macAddress and it's of type array of String

I have tried the following:

```<code>val macInput = setting_mac_text.text.toString()
            val macArray = macInput.split(",")
            val macList = Arrays.asList(macArray)
            val data =
                hashMapOf(Pair(FirebaseConstants.USER_MAC_ADDRESS, macArray))
            //save it in firebase
            db.collection(FirebaseConstants.ORGANIZATION)
                .document(orgID + ".${FirebaseConstants.USER_MAC_ADDRESS}")
                .set(FieldValue.arrayUnion(macList))
                .addOnCompleteListener { task ->
                    if (task.isSuccessful) {
                        Log.d(TAG, "successfully inserted")
                    } else {
                        Log.d(TAG, " failed ${task.exception}")
                    }
                }
</code>```

also tried to insert the list itself and hash map like this

```<code>val data = hashMapOf(Pair(FirebaseConstants.USER_MAC_ADDRESS, macArray))
db.collection(FirebaseConstants.ORGANIZATION)
                .document(orgID)
                .set(data))
</code>```

but it keeps giving me java.lang.IllegalArgumentException: Invalid data. Nested arrays are not supported

what am I doing wrong here?

答:
To overwrite an array, you would simply call the set method and have the merge option set to true:

try {
  const query = await DatabaseService.queryBuilder({
    collection: CollectionName,
  });

  return await query
    .doc(insuranceId)
    .set(
      { DOCUMENT_PROPERTY_HERE: ARRAY_HERE },
      { merge: true }
    );
} catch (exception) {
  return Promise.reject(exception);
}
```

Body:
I want to add a field of type array inside a collection.

if the field doesn't exist create it. if it exists overwrite it with the new array value.

the field should be called macAddress and it's of type array of String

I have tried the following:

val macInput = setting_mac_text.text.toString()
            val macArray = macInput.split(",")
            val macList = Arrays.asList(macArray)
            val data =
                hashMapOf(Pair(FirebaseConstants.USER_MAC_ADDRESS, macArray))
            //save it in firebase
            db.collection(FirebaseConstants.ORGANIZATION)
                .document(orgID + ".${FirebaseConstants.USER_MAC_ADDRESS}")
                .set(FieldValue.arrayUnion(macList))
                .addOnCompleteListener { task ->
                    if (task.isSuccessful) {
                        Log.d(TAG, "successfully inserted")
                    } else {
                        Log.d(TAG, " failed ${task.exception}")
                    }
                }

also tried to insert the list itself and hash map like this

val data = hashMapOf(Pair(FirebaseConstants.USER_MAC_ADDRESS, macArray))
db.collection(FirebaseConstants.ORGANIZATION)
                .document(orgID)
                .set(data))

but it keeps giving me java.lang.IllegalArgumentException: Invalid data. Nested arrays are not supported

what am I doing wrong here?


问:
Turning a subset based on multiple parameters into a looping function
I have a dataframe with 3000+ items (each row is a new item with the item_id in the first column) with 2500+ attributes in each subsequent column.

```<code>item_id    attribute_1    attribute_2 ... category_1 ... category_2
x3902      1              5               1              0
x1402      2              0               1              1
</code>```

I am able to successfully grab a random list of 10 items that fulfil a given attribute and category:

```<code>subset_of_items = sample(subset(df$item_id, (df$attribute1 == 3 & df$category_2 == 1 )),10)
</code>```

I need to repeat this for 30+ combinations of attribute + category. So I was hoping to create a function that loops and saves the output into a table where each table column is a list of 10 items that fulfils a set of conditions.

This is as far as I could get, but can't get it to successfully run:

```<code>df <- read.csv ("data.csv",sep=",")

attribute <- c("attribute_1", "attribute_2", "attribute_3")
value <- c(1, 2, 5)
category <- c("category_1", "category_1", "category_2")

function1 <- function(x, attribute_x, value_x, category_x)
{
  dftemp = subset(x[["item_id"]], (x[[attribute_x]] == value_x & x[[category_x]] == 1 ))
  output <- cbind(output, dftemp)
}

function1(df, attribute, value, category)
</code>```

The cherry on the cake would be to name each of the columns as attribute_x .

答:
You can do the following (this uses a data.table approach)

Set your df to data.table

```<code>library(data.table)
df <- read.csv("data.csv",sep=",")
setDT(df)
</code>```

Make a revised function, called get_subset() that returns a vector of item_ids that meet the attribute and category requirements, using get(). It
also checks if you have size items return, and pads with as.character(NA)  to ensure that the returned vector has length = size

```<code>get_subset <- function(x, attribute_x, value_x, category_x, size=10)
{
  subset = x[get(attribute_x)==value_x & get(category_x) == 1, .(item_id)] %>%
    .[sample(1:.N, size=min(size, .N)), item_id]
  if(length(subset)<size) subset=c(subset,rep(as.character(NA),size-length(subset)))
  return(subset)
}
</code>```

Put your combinations of interest into a small data.table

```<code>combinations = data.table(
  attribute = c("attribute_1", "attribute_2"),
  value = c(1, 5),
  category = c("category_1", "category_2")
)
</code>```

use lapply, to loop over the rows of your combinations, each time feeding the attribute, value, and category value of the combination to the get_subset function

```<code>result = lapply(seq(1,nrow(combinations)), function(i) {
    items = data.table(get_subset(
      x=df,
      attribute_x = combinations[i,attribute],
      value_x = combinations[i,value],
      category_x = combinations[i, category],
      size=10))
    setNames(items, combinations[i,attribute])
})
</code>```

That returns a list of data.tables with a single column, that is named after the attribute for that contribution

Use do.call with cbind to bind them into a single data.table

```<code>result = do.call(cbind, result)
</code>```

If this is your original df

```<code>df = data.table(
  item_id = paste0("x", stringr::str_pad(sample(1:1000,100),width = 4,side = "left",pad = "0")),
  attribute_1=sample(1:10, 100, replace=T),
  attribute_2=sample(1:10, 100, replace=T),
  category_1=sample(c(0,1),100, replace=T),
  category_2=sample(c(0,1),100, replace=T)
)
</code>```

then the above combinations, will return something like the following in result (Note, that my df example uses sample without seed, so your results will differ)

```<code>    attribute_1 attribute_2
 1:       x7511       x7302
 2:       x0325       x0956
 3:       x6748       x1893
 4:       x4462       x6958
 5:       x4146        <NA>
 6:       x5407        <NA>
 7:        <NA>        <NA>
 8:        <NA>        <NA>
 9:        <NA>        <NA>
10:        <NA>        <NA>
</code>```

Body:
I have a dataframe with 3000+ items (each row is a new item with the item_id in the first column) with 2500+ attributes in each subsequent column.

item_id    attribute_1    attribute_2 ... category_1 ... category_2
x3902      1              5               1              0
x1402      2              0               1              1

I am able to successfully grab a random list of 10 items that fulfil a given attribute and category:

subset_of_items = sample(subset(df$item_id, (df$attribute1 == 3 & df$category_2 == 1 )),10)

I need to repeat this for 30+ combinations of attribute + category. So I was hoping to create a function that loops and saves the output into a table where each table column is a list of 10 items that fulfils a set of conditions.

This is as far as I could get, but can't get it to successfully run:

df <- read.csv ("data.csv",sep=",")

attribute <- c("attribute_1", "attribute_2", "attribute_3")
value <- c(1, 2, 5)
category <- c("category_1", "category_1", "category_2")

function1 <- function(x, attribute_x, value_x, category_x)
{
  dftemp = subset(x[["item_id"]], (x[[attribute_x]] == value_x & x[[category_x]] == 1 ))
  output <- cbind(output, dftemp)
}

function1(df, attribute, value, category)

The cherry on the cake would be to name each of the columns as attribute_x .

Body:
You can do the following (this uses a data.table approach)

Set your df to data.table

library(data.table)
df <- read.csv("data.csv",sep=",")
setDT(df)

Make a revised function, called get_subset() that returns a vector of item_ids that meet the attribute and category requirements, using get(). It
also checks if you have size items return, and pads with as.character(NA)  to ensure that the returned vector has length = size

get_subset <- function(x, attribute_x, value_x, category_x, size=10)
{
  subset = x[get(attribute_x)==value_x & get(category_x) == 1, .(item_id)] %>%
    .[sample(1:.N, size=min(size, .N)), item_id]
  if(length(subset)<size) subset=c(subset,rep(as.character(NA),size-length(subset)))
  return(subset)
}

Put your combinations of interest into a small data.table

combinations = data.table(
  attribute = c("attribute_1", "attribute_2"),
  value = c(1, 5),
  category = c("category_1", "category_2")
)

use lapply, to loop over the rows of your combinations, each time feeding the attribute, value, and category value of the combination to the get_subset function

result = lapply(seq(1,nrow(combinations)), function(i) {
    items = data.table(get_subset(
      x=df,
      attribute_x = combinations[i,attribute],
      value_x = combinations[i,value],
      category_x = combinations[i, category],
      size=10))
    setNames(items, combinations[i,attribute])
})

That returns a list of data.tables with a single column, that is named after the attribute for that contribution

Use do.call with cbind to bind them into a single data.table

result = do.call(cbind, result)

If this is your original df

df = data.table(
  item_id = paste0("x", stringr::str_pad(sample(1:1000,100),width = 4,side = "left",pad = "0")),
  attribute_1=sample(1:10, 100, replace=T),
  attribute_2=sample(1:10, 100, replace=T),
  category_1=sample(c(0,1),100, replace=T),
  category_2=sample(c(0,1),100, replace=T)
)

then the above combinations, will return something like the following in result (Note, that my df example uses sample without seed, so your results will differ)

    attribute_1 attribute_2
 1:       x7511       x7302
 2:       x0325       x0956
 3:       x6748       x1893
 4:       x4462       x6958
 5:       x4146        <NA>
 6:       x5407        <NA>
 7:        <NA>        <NA>
 8:        <NA>        <NA>
 9:        <NA>        <NA>
10:        <NA>        <NA>


问:
Macro: Edit Recorded MobaXterm Macro
How can recorded MobaXterm Macro can be edited so that it can take input from the user and append it to a query and then executing rest of the macro after?

答:
There is a macro tab in the left toolbar where you can edit your macros, see:
https://superuser.com/a/1588231/319387

It's a bit weird that this is the only way to access them for editing, deleting etc.

Title: Macro: Edit Recorded MobaXterm Macro


问:
Element wise multiplication of 2 pandas series containing matrices as elements
Suppose I have 2 pandas series, a and b, where the elements are matrices as follows

```<code>a = pd.Series([np.array([[1,2], [3,4]]), np.array([[1,2], [3,4]])])

b = pd.Series([np.array([[1,2], [3,4]]), np.array([[1,2], [3,4]])])

</code>```

I would like to multiply the series elements of a with b such that the output looks like:

output of series multiplication

I have the following solution which works:

```<code>
c = []

for i in range(a.shape[0]):

    c.append(np.matmul(a[i], b[i]))

</code>```

however, this requires a for loop and outputs a list rather than a .Series. Any ideas how this could be done in a more compact form? Thanks.

答:
Just convert the list to pandas Series and print.
Add the following code at the end:</p>
```<code>print(pd.Series(c))
</code>```

Body:
Suppose I have 2 pandas series, a and b, where the elements are matrices as follows

a = pd.Series([np.array([[1,2], [3,4]]), np.array([[1,2], [3,4]])])

b = pd.Series([np.array([[1,2], [3,4]]), np.array([[1,2], [3,4]])])

I would like to multiply the series elements of a with b such that the output looks like:

output of series multiplication

I have the following solution which works:

c = []

for i in range(a.shape[0]):

    c.append(np.matmul(a[i], b[i]))

however, this requires a for loop and outputs a list rather than a .Series. Any ideas how this could be done in a more compact form? Thanks.

Body:
Just convert the list to pandas Series and print.
Add the following code at the end:

print(pd.Series(c))


问:
How to install jdk 8 on ubuntu server 18.04?
I am trying to install JDK 8 ON Ubuntu server 18.04 LTS, with the following commands:

```<code>sudo apt install openjdk-8-jre
sudo apt install openjdk-8-jdk
</code>```

/usr/lib/jvm folder has:

I also set the path into /etc/environment for JAVA_HOME
But I still get an error while java -version as:

```<code>Command 'java' not found, but can be installed with:

sudo apt install default-jre
sudo apt install openjdk-11-jre-headless
sudo apt install openjdk-8-jre-headless

</code>```

Can anyone please suggest to solve an error?
Thank you in advance.

答:
I got an answer, I mistakenly deleted default files i.e. java 11,

So I run following commands:

```<code>sudo apt purge -y openjdk-11-jre-headless
sudo apt purge -y openjdk-8-jre-headless
sudo apt purge -y default-jdk

</code>```

then I run command to set java 8 as default:

```<code>sudo update-alternatives --config java
</code>```

and the version is correctly reflect..

Body:
I am trying to install JDK 8 ON Ubuntu server 18.04 LTS, with the following commands:

sudo apt install openjdk-8-jre
sudo apt install openjdk-8-jdk

/usr/lib/jvm folder has:

I also set the path into /etc/environment for JAVA_HOME
But I still get an error while java -version as:

Command 'java' not found, but can be installed with:

sudo apt install default-jre
sudo apt install openjdk-11-jre-headless
sudo apt install openjdk-8-jre-headless

Can anyone please suggest to solve an error?
Thank you in advance.

Body:
I got an answer, I mistakenly deleted default files i.e. java 11,

So I run following commands:

sudo apt purge -y openjdk-11-jre-headless
sudo apt purge -y openjdk-8-jre-headless
sudo apt purge -y default-jdk

then I run command to set java 8 as default:

sudo update-alternatives --config java

and the version is correctly reflect..


问:
How to implement debounce in vue3
I have a filter input field and want to filter a list of items. The list is large so I want to use debounce to delay the filter being applied until the user has stopped typing for improved user experience. This is my input field and it's bound to filterText that is used to filter the list.</p>
```<code><input type="text" v-model="state.filterText" />
</code>```

答:
<input @input="updateValue"/>

const updateValue = (event) => {
  const timeoutId = window.setTimeout(() => {}, 0);
  for (let id = timeoutId; id >= 0; id -= 1) {
    window.clearTimeout(id);
  }

  setTimeout(() => {
    console.log(event.target.value)
  }, 500);
};```

You can try this one

Title: How to implement debounce in vue3

Body:
I have a filter input field and want to filter a list of items. The list is large so I want to use debounce to delay the filter being applied until the user has stopped typing for improved user experience. This is my input field and it's bound to filterText that is used to filter the list.

<input type="text" v-model="state.filterText" />

Body:
<input @input="updateValue"/>

const updateValue = (event) => {
  const timeoutId = window.setTimeout(() => {}, 0);
  for (let id = timeoutId; id >= 0; id -= 1) {
    window.clearTimeout(id);
  }

  setTimeout(() => {
    console.log(event.target.value)
  }, 500);
};

You can try this one


问:
Google App Engine non-latin names for files&folders?
I need to have cyrillic file and folder names. Example /запись/Index.html But i'm getting error when accessing these files. It says that GAE couldn't find them. I really think it is because encoding. But doesn't GAE support UTF8?

答:
Different operating systems store filenames in different ways. In Linux, filenames are uninterpreted byte strings, while in Windows they are unicode strings. This means that cross-platform compatibility with unicode filenames are tough.

The easiest way around this is to stick to names that are representable in both - eg, the lower 128 codepoints. You don't need cyrillic filenames, because the filenames are an internal detail of your app. You can serve any file you want under any URL path you want, independent of where it's stored, or if it's dynamic or static.


问:
How to get helm module codebase?
I'm new to helm charts, want to do the customisation to existing public chart, anyway to do it?
We are okay to host it at our end, just wanted to check how to dump the existing helm chart.</p>

答:
You can do below if you want to pull the helm chart at your local to customise it -

```<code>helm pull [chart URL | repo/chartname] [...] [flags]
</code>```

Example -

```<code>helm repo add <name> <url>
helm pull repo-name/chart-name
</code>```

Then you can customise it as per your need.

Any further explanation needed then let me know

Title: How to get helm module codebase?

Body:
You can do below if you want to pull the helm chart at your local to customise it -

helm pull [chart URL | repo/chartname] [...] [flags]

Example -

helm repo add <name> <url>
helm pull repo-name/chart-name

Then you can customise it as per your need.

Any further explanation needed then let me know


问:
Is there any way to create new python API endpoints on the fly?
I am just trying to figure out is there any way that one python script will create new endpoints or new python services on the fly, Like spawning new API endpoints from the script.

Some basic design will work! I just need some insights on how to do this design?

For a greater overview, let's say I have an application that creates an userId and the user provides some path for an endpoint that python app should generate a new API endpoint based on the path provided in the host, What should be the ideal way to do it?

Any help will be appreciated

答:
so fastapi uses decorators to produce endpoints, and decorators are just syntax sugar where the decorator is function that takes in another function as input. with that you should just be able to apply the fastapi get/post/etc dynamically same way you would just apply a function dynamically

below is example how to apply decorator in way describe above

```<code># Python code to illustrate
# Decorators with parameters in Python  (Multi-level Decorators)

def decodecorator(dataType, message1, message2):
    def decorator(fun):
        print(message1)
        def wrapper(*args, **kwargs):
            print(message2)
            if all([type(arg) == dataType for arg in args]):
                return fun(*args, **kwargs)
            return "Invalid Input"
        return wrapper
    return decorator

def summation(*args):
    summ = 0
    for arg in args:
        summ += arg
    return summ

@decodecorator(int, "Decorator for 'summation'\n", "summation started ...")
def summation_with_decorator(*args):
    summ = 0
    for arg in args:
        summ += arg
    return summ

l = [19, 2, 8, 533, 67, 981, 119]
print(summation(*l))
print()
print(summation_with_decorator(*l))
print()
# applying decorator
summation = decodecorator(int, "Decorator for 'summation'\n", "summation started ...")(summation)
print(summation(*l))
</code>```

Body:
so fastapi uses decorators to produce endpoints, and decorators are just syntax sugar where the decorator is function that takes in another function as input. with that you should just be able to apply the fastapi get/post/etc dynamically same way you would just apply a function dynamically

below is example how to apply decorator in way describe above

# Python code to illustrate
# Decorators with parameters in Python  (Multi-level Decorators)

def decodecorator(dataType, message1, message2):
    def decorator(fun):
        print(message1)
        def wrapper(*args, **kwargs):
            print(message2)
            if all([type(arg) == dataType for arg in args]):
                return fun(*args, **kwargs)
            return "Invalid Input"
        return wrapper
    return decorator

def summation(*args):
    summ = 0
    for arg in args:
        summ += arg
    return summ

@decodecorator(int, "Decorator for 'summation'\n", "summation started ...")
def summation_with_decorator(*args):
    summ = 0
    for arg in args:
        summ += arg
    return summ

l = [19, 2, 8, 533, 67, 981, 119]
print(summation(*l))
print()
print(summation_with_decorator(*l))
print()
# applying decorator
summation = decodecorator(int, "Decorator for 'summation'\n", "summation started ...")(summation)
print(summation(*l))


问:
JavaScript Add key to each value in array
I have this array below that consists of a simple array. What i'm trying to accomplish is to put a key id in front of every array value to achieve something like this ["id:a", "id:b","id:c","id:d"] is there a easy way to accomplish this? any help would be greatly appreciated thank you.

var test = ['a','b','c','d']```

答:
Unable to edit @ObsidianAge answer, so minor change:

If you need in the form that the OP asked (Array of objects)

var test = ['a', 'b', 'c', 'd'];

function setID(item, index) {
  var fullname = {"id: ": item};
  return fullname;
}

var output = test.map(setID);
console.log(output);```


问:
Delete duplicate rows in mySQL in same table
I have this script running to check for duplicates in my table:

select s.id, t.*
from [stuff] s
join (
   select name, city, count(*) as qty
   from [stuff]
   group by name, city
   having count(*) > 1
) t on s.name = t.name and s.city = t.city
```
<p>This works fine and returns the ID's of the duplicate rows:</p>
<pre class="lang-py prettyprint-override"><code>myresult = cur.fetchall()
print(myresult)
</code>```

Example output:

```<code>[(84,), (85,), (339,), (340,), (351,), (352,), (416,), (417,), (511,), (512,), (532,), (533,),
(815,), (816,), (978,), (979,), (1075,), (1076,), (1385,), (1386,), (1512,)]
</code>```

Now I want to delete records 84, 339, 351, 416, etc.
What would be the most convenient way to do so?

答:
you can remove duplicate rows in MySQL in this way</p>
```<code>      WHERE customer_id NOT IN
      (
          SELECT
          customer_id
          FROM
          (
              SELECT MIN(customer_id) as customer_id
              FROM CUSTOMERS
              GROUP BY CONCAT(first_name, last_name, phone)
          ) AS duplicate_customer_ids
      );`

</code>```

Body:
I have this script running to check for duplicates in my table:

select s.id, t.*
from [stuff] s
join (
   select name, city, count(*) as qty
   from [stuff]
   group by name, city
   having count(*) > 1
) t on s.name = t.name and s.city = t.city

This works fine and returns the ID's of the duplicate rows:

myresult = cur.fetchall()
print(myresult)

Example output:

[(84,), (85,), (339,), (340,), (351,), (352,), (416,), (417,), (511,), (512,), (532,), (533,),
(815,), (816,), (978,), (979,), (1075,), (1076,), (1385,), (1386,), (1512,)]

Now I want to delete records 84, 339, 351, 416, etc.
What would be the most convenient way to do so?

Body:
you can remove duplicate rows in MySQL in this way

      WHERE customer_id NOT IN
      (
          SELECT
          customer_id
          FROM
          (
              SELECT MIN(customer_id) as customer_id
              FROM CUSTOMERS
              GROUP BY CONCAT(first_name, last_name, phone)
          ) AS duplicate_customer_ids
      );`


问:
how to load Svg components in remix run application
I have some Svg files which i want to load as react components in remix run app.
for example in create-react-app your could do something like this

```<code>
import { ReactComponent as Logo } from './logo.svg';
function App() {
  return (
    <div>
      {/* Logo is an actual React component */}
      <Logo />
    </div>
  );
}
</code>```

is there any similar way in remix-run do achieve the same ?

答:
Unfortunately there is no way currently to import an SVG file in your component file directly like in create react app.

And maintainers do not allow currently manipulating the esbuild config to add features like that via plugins (cf. the discussion in this merge request).

If you don't need to style your SVG, you could simply put it in the public/ folder and include it with an img element in your component.

Smaller JS bundles, faster page hydration, and immutable .svg's over the network that are only ever downloaded once. (cf. this message)

```<code>function App() {
  return (
    <div>
      <img src="/logo.svg" alt="My logo" />
    </div>
  );
}
</code>```

You could also create yourself a JSX component and put your SVG code inside it (with some manual conversion for prop names), or even put your SVG file in a folder, and use an external automatic conversion tool like SVGR to generate optimized JSX component from it with a simple CLI command.

In that case you have a component that you can import like any other component:

```<code>import Logo from './Logo.svg';
function App() {
  return (
    <div>
      <Logo />
    </div>
  );
}
</code>```

Body:
I have some Svg files which i want to load as react components in remix run app.
for example in create-react-app your could do something like this

import { ReactComponent as Logo } from './logo.svg';
function App() {
  return (

      {/* Logo is an actual React component */}
      <Logo />

  );
}

is there any similar way in remix-run do achieve the same ?

Body:
Unfortunately there is no way currently to import an SVG file in your component file directly like in create react app.

And maintainers do not allow currently manipulating the esbuild config to add features like that via plugins (cf. the discussion in this merge request).

If you don't need to style your SVG, you could simply put it in the public/ folder and include it with an img element in your component.

Smaller JS bundles, faster page hydration, and immutable .svg's over the network that are only ever downloaded once. (cf. this message)

function App() {
  return (
    <div>
      <img src="/logo.svg" alt="My logo" />
    </div>
  );
}

You could also create yourself a JSX component and put your SVG code inside it (with some manual conversion for prop names), or even put your SVG file in a folder, and use an external automatic conversion tool like SVGR to generate optimized JSX component from it with a simple CLI command.

In that case you have a component that you can import like any other component:

import Logo from './Logo.svg';
function App() {
  return (
    <div>
      <Logo />
    </div>
  );
}


问:
rxjs map cannot hint type to project function with overload, causing type errors if not explicitly defiend
I am have a hard time figuring how to make typescript happy with this case:

```<code>const t1 = new BehaviorSubject("test");
const t2 = new BehaviorSubject(["test2"]);

function transformString(subject:string):string
function transformString(subject:string[]):string[]
function transformString(subject:string|string[]):string|string[]{
  if(Array.isArray(subject)){
    return subject.map(t=>t.toUpperCase());
  }
  return subject.toUpperCase();
}

t1.pipe(map(transformString)); // Type error
t2.pipe(map(transformString));

t1.next(transformString(t1.value));
t2.next(transformString(t2.value));
</code>```

The type error I am receiving is this:

Argument of type 'OperatorFunction<string[], string[]>' is not
assignable to parameter of type 'OperatorFunction<string, string[]>'.
Type 'string[]' is not assignable to type 'string'.ts(2345)

I have added the last two lines just to test if the override was working correctly and it does. For now, the only solution I find is to hunt the types at the map level:

```<code>t1.pipe(map<string,string>(transformString));
</code>```

But this is getting redundant since we do know t1's type already. Also, the plan was at first to include the map into a variable, but I left it outside for now.

Edit:

As @Zerotwelve pointed out, the code above can work without using the overloads. I did not catch the real issue from my code in the minimal code above.

The problem comes when this is used in another function:

```<code>function t1F(): Observable<string> {
  const t1 = new BehaviorSubject("test");
  return t1.pipe(map(transformString));
}
</code>```

Here typescript complains that

```<code>Type 'Observable<string | string[]>' is not assignable to type 'Observable<string>'.   Type 'string | string[]' is not assignable to type 'string'.
    Type 'string[]' is not assignable to type 'string'.
</code>```

答:
you can do it just like this:

const t1 = new BehaviorSubject("test");
const t2 = new BehaviorSubject(["test2"]);

function transformString(subject:string|string[]):string|string[]{
  if(Array.isArray(subject)){
    return subject.map(t=>t.toUpperCase());
  }
  return subject.toUpperCase();
}

t1.pipe(map(transformString));
t2.pipe(map(transformString));
```

Body:
I am have a hard time figuring how to make typescript happy with this case:

const t1 = new BehaviorSubject("test");
const t2 = new BehaviorSubject(["test2"]);

function transformString(subject:string):string
function transformString(subject:string[]):string[]
function transformString(subject:string|string[]):string|string[]{
  if(Array.isArray(subject)){
    return subject.map(t=>t.toUpperCase());
  }
  return subject.toUpperCase();
}

t1.pipe(map(transformString)); // Type error
t2.pipe(map(transformString));

t1.next(transformString(t1.value));
t2.next(transformString(t2.value));

The type error I am receiving is this:

Argument of type 'OperatorFunction<string[], string[]>' is not
assignable to parameter of type 'OperatorFunction<string, string[]>'.
Type 'string[]' is not assignable to type 'string'.ts(2345)

I have added the last two lines just to test if the override was working correctly and it does. For now, the only solution I find is to hunt the types at the map level:

t1.pipe(map<string,string>(transformString));

But this is getting redundant since we do know t1's type already. Also, the plan was at first to include the map into a variable, but I left it outside for now.

Edit:

As @Zerotwelve pointed out, the code above can work without using the overloads. I did not catch the real issue from my code in the minimal code above.

The problem comes when this is used in another function:

function t1F(): Observable<string> {
  const t1 = new BehaviorSubject("test");
  return t1.pipe(map(transformString));
}

Here typescript complains that

Type 'Observable<string | string[]>' is not assignable to type 'Observable<string>'.   Type 'string | string[]' is not assignable to type 'string'.
    Type 'string[]' is not assignable to type 'string'.


问:
What does if [ $? -eq 0 ] mean for shell scripts?
There is this line in a shell script i have seen:</p>

```<code>grep -e ERROR ${LOG_DIR_PATH}/${LOG_NAME}  > /dev/null
if [ $? -eq 0 ]
</code>```

答:
$? is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure.  That line is testing whether the grep command succeeded.

The grep manpage states:

The exit status is 0 if selected lines are found, and 1 if  not  found.  If an error occurred the exit status is 2.  (Note: POSIX error handling code should check for '2' or greater.)

So in this case it's checking whether any ERROR lines were found.

Body:
There is this line in a shell script i have seen:

grep -e ERROR ${LOG_DIR_PATH}/${LOG_NAME}  > /dev/null
if [ $? -eq 0 ]


问:
React/Typescript : how to type a value in a setter with onChange
i'm new with react/typescript and i have a problem to "type" a value with an Onchange.
here's the code :

```<code>    interface Props {
  race : CharacterRace | '',
  classe : CharacterClass | '',
  sexe : CharacterGender | '',
  setRace : (race : CharacterRace | '')=>void,
  setClasse : (classe : CharacterClass | '')=>void,
  setSexe : (sexe: CharacterGender | '')=>void
}
...
          <select name="race" id="race" value={props.race} onChange={({ target: { value } })=>props.setRace(value)}>
        <option value=""> </option>
        <option value="humains">Humain</option>
        <option value="elfes">Elfe</option>
        <option value="orcs">Orc</option>
        <option value="mort-vivants">Mort-Vivant</option>
        <option value="nains">Nain</option>
      </select>
</code>```

He told me that "value" is a string and can't be assigned to CharacterRace | ''

if I make this :

```<code> setClasse : (classe : CharacterClass | string)=>void,
</code>```

That "solve" the problem, but it's just a hack, it's not clean

I try to type the "value" but it didn't work

Do you have an idea how I can fix that ?

The type :

```<code>    export type CharacterRace = 'humains' | 'elfes' | 'orcs' | 'mort-vivants' | 'nains';

    export type CharacterClass = 'guerrier' | 'barbare' | 'paladin' | 'rodeur' | 'voleur' | 'mage' | 'pretre' | 'guerrier-mage';

    export type CharacterGender = 'masculin' | 'feminin';
</code>```

答: You should use "HTMLInputElement"</p>

Body:
i'm new with react/typescript and i have a problem to "type" a value with an Onchange.
here's the code :

    interface Props {
  race : CharacterRace | '',
  classe : CharacterClass | '',
  sexe : CharacterGender | '',
  setRace : (race : CharacterRace | '')=>void,
  setClasse : (classe : CharacterClass | '')=>void,
  setSexe : (sexe: CharacterGender | '')=>void
}
...
          <select name="race" id="race" value={props.race} onChange={({ target: { value } })=>props.setRace(value)}>
        <option value=""> </option>
        <option value="humains">Humain</option>
        <option value="elfes">Elfe</option>
        <option value="orcs">Orc</option>
        <option value="mort-vivants">Mort-Vivant</option>
        <option value="nains">Nain</option>
      </select>

He told me that "value" is a string and can't be assigned to CharacterRace | ''

if I make this :

 setClasse : (classe : CharacterClass | string)=>void,

That "solve" the problem, but it's just a hack, it's not clean

I try to type the "value" but it didn't work

Do you have an idea how I can fix that ?

The type :

    export type CharacterRace = 'humains' | 'elfes' | 'orcs' | 'mort-vivants' | 'nains';

    export type CharacterClass = 'guerrier' | 'barbare' | 'paladin' | 'rodeur' | 'voleur' | 'mage' | 'pretre' | 'guerrier-mage';

    export type CharacterGender = 'masculin' | 'feminin';

Body: You should use "HTMLInputElement"


问:
Mocking call to static method call inside spy method
Pretty new to mockito. Stuck with a basic thing:

```<code>@Override
    public void updateMeeting(Meeting meeting, Meeting oldMeeting, List<MeetingOccurrence> oldMeetingOccurrences, List<MeetingOccurrence> newMeetingOccurrences) {
        Predicate<Meeting> update = (e) -> MeetingUtil.needReminderChange(oldMeeting, meeting, oldMeetingOccurrences, newMeetingOccurrences);
        // DO STUFF
            if(ConfUtil.isRecurrenceMeeting(meeting.getType()) && meeting.getType() == oldMeeting.getType()){
                update = update.or((e) -> recurringMeetingDurationChange(oldMeetingOccurrences, newMeetingOccurrences));
            }

        }
        if (update.test(meeting)) {
            sendEvent(meeting, MeetingConstants.MTG_CHANGE_EVEN_TYPE_UPDATE, getNotifiers(meeting, oldMeeting));
        }
    }
</code>```

//---
TEST CLASS

```<code>public void testUpdateMeeting(){
        MeetingNotifyService meetingNotifyService = Mockito.spy(MeetingNotifyServiceImpl.class);
        Meeting meeting = Mockito.spy(Meeting.class);
        Meeting oldMeeting = Mockito.spy(Meeting.class);
        meeting.setType(Constants.MTG_TYPE_RECURRENCE);
        meetingNotifyService.updateMeeting(meeting,oldMeeting,null,null);
    }
</code>```

//--

Problem is that when the code hits this line: ConfUtil.isRecurrenceMeeting it fails. It happens because of static block code inside ConfUtil. How can I tell mockito to not actually call ConfUtil.isRecurrenceMeeting and just return true. I cannot use powermockito

答: You can use PowerMockito to mock the static method. But the best way I would suggest you to avoid PowerMockito and have your code designed as testable code. So you don't have to mock a static method, consider to have it as a singleton service and you just have to mock a service normally.</p>

Body:
Pretty new to mockito. Stuck with a basic thing:

@Override
    public void updateMeeting(Meeting meeting, Meeting oldMeeting, List<MeetingOccurrence> oldMeetingOccurrences, List<MeetingOccurrence> newMeetingOccurrences) {
        Predicate<Meeting> update = (e) -> MeetingUtil.needReminderChange(oldMeeting, meeting, oldMeetingOccurrences, newMeetingOccurrences);
        // DO STUFF
            if(ConfUtil.isRecurrenceMeeting(meeting.getType()) && meeting.getType() == oldMeeting.getType()){
                update = update.or((e) -> recurringMeetingDurationChange(oldMeetingOccurrences, newMeetingOccurrences));
            }

        }
        if (update.test(meeting)) {
            sendEvent(meeting, MeetingConstants.MTG_CHANGE_EVEN_TYPE_UPDATE, getNotifiers(meeting, oldMeeting));
        }
    }

//---
TEST CLASS

public void testUpdateMeeting(){
        MeetingNotifyService meetingNotifyService = Mockito.spy(MeetingNotifyServiceImpl.class);
        Meeting meeting = Mockito.spy(Meeting.class);
        Meeting oldMeeting = Mockito.spy(Meeting.class);
        meeting.setType(Constants.MTG_TYPE_RECURRENCE);
        meetingNotifyService.updateMeeting(meeting,oldMeeting,null,null);
    }

//--

Problem is that when the code hits this line: ConfUtil.isRecurrenceMeeting it fails. It happens because of static block code inside ConfUtil. How can I tell mockito to not actually call ConfUtil.isRecurrenceMeeting and just return true. I cannot use powermockito


问:
Calculate column date value from variable and other column date offset
I have a project management table with 1000 tasks/records, each with a dynamic starting_date and ending_date column. The values of those dates are calculated by taking a static project "going-live" date (e.g. 2022-10-01) and then deducting the task_offset_days value of each record (e.g. -211), resulting in the starting_date value. The end date is calculated via a days_to_complete column with e.g. 60 days value, which if added to the starting_date gives me the final ending_date.

Example: Live date = 2022-10-01, offset by -211 days results in starting_date = '2022-03-04', which plus days_offset of 60 results in ending_date = 2022-05-03.

Here the issue:

I want to copy the 1000 records to another table and during the process want to update the starting_date, ending_date value based on another going-live date. How can I do this in the most efficient way considering I am copying and editing 1000 records?

Current copy query:

```<code>@live_date = '2022-10-01';   // going-live date

INSERT INTO `new_task_table` (
    `property_id`,  // unique identifier, not present in original table
    `status`,
    `task_desc`,
    `phase`,
    `workstream`,
    `task_level`,
    `task_owner_group`,
    `start_date`,   // = live date - offset
    `end_date`,     // = start date + days to complete
    `offset_days`,  // eg. -211 (note: can be below / above zero: -211 or 120)
    `days_to_complete`, // eg. 60
    `created_at`
)
SELECT
    '31',
    `status`,
    `task_desc`,
    `phase`,
    `workstream`,
    `task_level`,
    `task_owner_group`,
    `start_date`,
    `end_date`,
    `offset_days`,
    `days_to_complete`,
    '2022-01-01 00:00:00'   // date of query execution
FROM `old_task_table`;
</code>```

答:
It's probably simpler than you think. You just pass the values into the SELECT

```<code>@live_date = '2022-10-01';   // going-live date

INSERT INTO `new_task_table` (
    `property_id`,  // unique identifier, not present in original table
    `status`,
    `task_desc`,
    `phase`,
    `workstream`,
    `task_level`,
    `task_owner_group`,
    `start_date`,   // = live date - offset
    `end_date`,     // = start date + days to complete
    `offset_days`,  // eg. -211 (note: can be below / above zero: -211 or 120)
    `days_to_complete`, // eg. 60
    `created_at`
)
SELECT
    '31',
    `status`,
    `task_desc`,
    `phase`,
    `workstream`,
    `task_level`,
    `task_owner_group`,
    DATE_ADD(@live_date, INTERVAL offset_days DAY) AS start_date,
    DATE_ADD(@live_date,INTERVAL offset_days + days_to_complete DAY) AS end_date,
    `offset_days`,
    `days_to_complete`,
    '2022-01-01 00:00:00'   // date of query execution
FROM `old_task_table`;
</code>```

Body:
I have a project management table with 1000 tasks/records, each with a dynamic starting_date and ending_date column. The values of those dates are calculated by taking a static project "going-live" date (e.g. 2022-10-01) and then deducting the task_offset_days value of each record (e.g. -211), resulting in the starting_date value. The end date is calculated via a days_to_complete column with e.g. 60 days value, which if added to the starting_date gives me the final ending_date.

Example: Live date = 2022-10-01, offset by -211 days results in starting_date = '2022-03-04', which plus days_offset of 60 results in ending_date = 2022-05-03.

Here the issue:

I want to copy the 1000 records to another table and during the process want to update the starting_date, ending_date value based on another going-live date. How can I do this in the most efficient way considering I am copying and editing 1000 records?

Current copy query:

@live_date = '2022-10-01';   // going-live date

INSERT INTO `new_task_table` (
    `property_id`,  // unique identifier, not present in original table
    `status`,
    `task_desc`,
    `phase`,
    `workstream`,
    `task_level`,
    `task_owner_group`,
    `start_date`,   // = live date - offset
    `end_date`,     // = start date + days to complete
    `offset_days`,  // eg. -211 (note: can be below / above zero: -211 or 120)
    `days_to_complete`, // eg. 60
    `created_at`
)
SELECT
    '31',
    `status`,
    `task_desc`,
    `phase`,
    `workstream`,
    `task_level`,
    `task_owner_group`,
    `start_date`,
    `end_date`,
    `offset_days`,
    `days_to_complete`,
    '2022-01-01 00:00:00'   // date of query execution
FROM `old_task_table`;

Body:
It's probably simpler than you think. You just pass the values into the SELECT

@live_date = '2022-10-01';   // going-live date

INSERT INTO `new_task_table` (
    `property_id`,  // unique identifier, not present in original table
    `status`,
    `task_desc`,
    `phase`,
    `workstream`,
    `task_level`,
    `task_owner_group`,
    `start_date`,   // = live date - offset
    `end_date`,     // = start date + days to complete
    `offset_days`,  // eg. -211 (note: can be below / above zero: -211 or 120)
    `days_to_complete`, // eg. 60
    `created_at`
)
SELECT
    '31',
    `status`,
    `task_desc`,
    `phase`,
    `workstream`,
    `task_level`,
    `task_owner_group`,
    DATE_ADD(@live_date, INTERVAL offset_days DAY) AS start_date,
    DATE_ADD(@live_date,INTERVAL offset_days + days_to_complete DAY) AS end_date,
    `offset_days`,
    `days_to_complete`,
    '2022-01-01 00:00:00'   // date of query execution
FROM `old_task_table`;


问:
Binary Gap Program in Java
My problem statement:

A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N. For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps. The number 32 has binary representation 100000 and has no binary gaps.

My code:

```<code>public class Abc {

    static void decToBinary(int n) {

        int[] binaryNum = new int[1000];

        // counter for binary array
        int i = 0;
        while (n > 0) {
            // storing remainder in binary array
            binaryNum[i] = n % 2;
            n = n / 2;
            i++;
        }
        int ctr = 0, k = 0;
        ArrayList<Integer> al = new ArrayList<Integer>();

        // printing binary array in reverse order
        for (int j = i - 1; j >= 0; j--) {
            System.out.print(binaryNum[j]);
            if (binaryNum[j] == 0) {
                k = j;
                do {
                    ctr++;
                    k++;
                } while (binaryNum[k] == 0);
                al.add(ctr);
                ctr = 0;
            }
        }

        for (int ii = 0; ii < al.size(); ii++) {
            System.out.println(al.get(ii));
        }
    }

    // driver program
    public static void main(String[] args) {
        int n = 1041;
        decToBinary(n);
    }
}
</code>```

I am trying to show the output of binary gap that is stored in my ArrayList.  But the output is quite different for a given input of 1041. I  don't know why it is storing 1,2,3,4; according to my logic it should store only the gap values 5 and 3 in case of input:1041, even though 5 and 3 are also stored in the ArrayList but at some other index.

I think there is a problem in the do-while loop especially in al.add(ctr) but I haven't figured it out yet.

答:
another solution that I did and it works totally fine</p>
```<code>public int solution(int N) {
        String value = Integer.toBinaryString(N);
        String[] a = value.split("1");
        if (value.endsWith("0")) {
            a = Arrays.copyOf(a, a.length-1);
        }
        OptionalInt finalResult = Arrays.stream(a).filter(h -> h.length() > 0).mapToInt(String::length).max();

        return finalResult.isPresent() ? finalResult.getAsInt() :  0;
    }
</code>```

Title: Binary Gap Program in Java

Body:
My problem statement:

A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N. For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps. The number 32 has binary representation 100000 and has no binary gaps.

My code:

public class Abc {

    static void decToBinary(int n) {

        int[] binaryNum = new int[1000];

        // counter for binary array
        int i = 0;
        while (n > 0) {
            // storing remainder in binary array
            binaryNum[i] = n % 2;
            n = n / 2;
            i++;
        }
        int ctr = 0, k = 0;
        ArrayList<Integer> al = new ArrayList<Integer>();

        // printing binary array in reverse order
        for (int j = i - 1; j >= 0; j--) {
            System.out.print(binaryNum[j]);
            if (binaryNum[j] == 0) {
                k = j;
                do {
                    ctr++;
                    k++;
                } while (binaryNum[k] == 0);
                al.add(ctr);
                ctr = 0;
            }
        }

        for (int ii = 0; ii < al.size(); ii++) {
            System.out.println(al.get(ii));
        }
    }

    // driver program
    public static void main(String[] args) {
        int n = 1041;
        decToBinary(n);
    }
}

I am trying to show the output of binary gap that is stored in my ArrayList.  But the output is quite different for a given input of 1041. I  don't know why it is storing 1,2,3,4; according to my logic it should store only the gap values 5 and 3 in case of input:1041, even though 5 and 3 are also stored in the ArrayList but at some other index.

I think there is a problem in the do-while loop especially in al.add(ctr) but I haven't figured it out yet.

Body:
another solution that I did and it works totally fine

public int solution(int N) {
        String value = Integer.toBinaryString(N);
        String[] a = value.split("1");
        if (value.endsWith("0")) {
            a = Arrays.copyOf(a, a.length-1);
        }
        OptionalInt finalResult = Arrays.stream(a).filter(h -> h.length() > 0).mapToInt(String::length).max();

        return finalResult.isPresent() ? finalResult.getAsInt() :  0;
    }


问:
We made it reliable. What's next? Usability?
I'm working in a small development group. We are building and improving our product.

Half a year ago we couldn't think about higher characteristics, such as usability, because we had so many problems with our product. Many bugs, high technical debt, low performance and other problems kept us from being able to focus on usability.

With time we've improved our process substantially. What we've done:

Real Agile iterations

Continuous integration

Testing(unit-tests, functional Smoke tests, performance)

Code quality is 'good'

Painless deployment process

So we are now producing stable, reliable releases. The following quote (paraphrased) describes our current situation:

first - make it work; after that, make it reliable; after that, make it usable

We are geeks, so we can't 'make' a great UI by ourselves.
So what should we do? What direction can you recommend?
Maybe we should hire Usability experts part-time or full-time?
How can we explain the importance of Usability to our stakeholders?
How do we convince them that this is useful?

答:
When analyzing the next step it really all comes down to business requirements & goals.

What is upper management like? Are they tech-savy?  Are they open to new ideas? Do they think that the current product needs adjustment, improvement, etc?  Is the product still in high demand?  Is the marketplace changing such that the product/service will soon be obsolete? etc. etc. etc.

IF there are real business reasons for spending the $/time/resources then you can begin to explore product improvements.  At that point consider the opinions of previous posters regarding user opinion.

OwnerDisplayName: Fedyashev Nikita

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Gortok

LastEditorDisplayName: Chadwick


问:
Python convert.txt to .csv without having a specific file name
I am currently working on an application that will convert a messy text file full of data into an organized CSV. It currently works well but when I convert the text file to csv I want to be able to select a text file with any name. The way my code is currently written, I have to name the file "file.txt". How do I go about this?

Here is my code. I can send the whole script if necessary. Just to note this is a function that is linked to a tkinter button. Thanks in advance.

```<code>def convert():
df = pd.read_csv("file.txt",delimiter=';')
df.to_csv('Cognex_Data.csv')
</code>```

答:
Try defining your function as follow:

def convert(input_filename, output_filename='Cognex_Data.csv'):
    df = pd.read_csv(input_filename, delimiter=';')
    df.to_csv(output_filename)
```
<p>And for instance use it as follow:</p>
<pre class="lang-py prettyprint-override"><code>filename = input("Enter filename: ")
convert(filename, "Cognex_Data.csv")
</code>```

You can also put "Cognex_Data.csv" as a default value for the output_filename argument in the convert function definition (as done above).

And finally you can use any way you like to get the filename (for instance tkinter.filedialog as suggested by matszwecja).

Body:
I am currently working on an application that will convert a messy text file full of data into an organized CSV. It currently works well but when I convert the text file to csv I want to be able to select a text file with any name. The way my code is currently written, I have to name the file "file.txt". How do I go about this?

Here is my code. I can send the whole script if necessary. Just to note this is a function that is linked to a tkinter button. Thanks in advance.

def convert():
df = pd.read_csv("file.txt",delimiter=';')
df.to_csv('Cognex_Data.csv')

Body:
Try defining your function as follow:

def convert(input_filename, output_filename='Cognex_Data.csv'):
    df = pd.read_csv(input_filename, delimiter=';')
    df.to_csv(output_filename)

And for instance use it as follow:

filename = input("Enter filename: ")
convert(filename, "Cognex_Data.csv")

You can also put "Cognex_Data.csv" as a default value for the output_filename argument in the convert function definition (as done above).

And finally you can use any way you like to get the filename (for instance tkinter.filedialog as suggested by matszwecja).


问:
Trouble With Lists of Lists in Python
I'm brand new to python, but I have a lot of experience with C++, Java, and .NET. I'm hoping that someone can explain why this sample program works the way it does and how I can change it to work the way I would like it to work.

Essentially, I'm trying to create a list of objects, and each object in the list contains a list of objects. In the end, the sub lists are all the same list, instead of being unique to the instance of their parent class.

```<code>class Obj1(object):
    list_of_obj2 = []
    name = ''

class Obj2(object):
    name = ''

list_of_obj1 = []

for i in range(2):
    new_obj1 = Obj1()
    new_obj1.name = "obj1_%s" % i
    print "Creating Object1 named %s" % new_obj1.name

    for j in range(2):
        new_obj2 = Obj2()
        new_obj2.name = "...obj2_%s_%s" % (i, j)

        new_obj1.list_of_obj2.append(new_obj2)
        print "...Added Object2 named %s to %s list" % (new_obj2.name, new_obj1.name)

    list_of_obj1.append(new_obj1)
    print "Added Object1 named %s to master list" % (new_obj1.name)

print ""

for obj in list_of_obj1:
    print "%s has %s items in list" % (obj.name, len(obj.list_of_obj2))
    for obj2 in obj.list_of_obj2:
        print "...%s" % obj2.name
</code>```

The output of the program:

```<code>Creating Object1 named obj1_0
...Added Object2 named ...obj2_0_0 to obj1_0 list
...Added Object2 named ...obj2_0_1 to obj1_0 list
Added Object1 named obj1_0 to master list
Creating Object1 named obj1_1
...Added Object2 named ...obj2_1_0 to obj1_1 list
...Added Object2 named ...obj2_1_1 to obj1_1 list
Added Object1 named obj1_1 to master list

obj1_0 has 4 items in list
......obj2_0_0
......obj2_0_1
......obj2_1_0
......obj2_1_1
obj1_1 has 4 items in list
......obj2_0_0
......obj2_0_1
......obj2_1_0
......obj2_1_1
</code>```

Why don't the two Obj1 lists each have 2 items? Is there a better way to implement this?

答:
list_of_obj2 is a class attribute of Obj1, if you want instance attribute:</p>

```<code>class Obj1(object):
    def __init__(self):
        self.list_of_obj2 = []
</code>```

Title: Trouble With Lists of Lists in Python

Body:
I'm brand new to python, but I have a lot of experience with C++, Java, and .NET. I'm hoping that someone can explain why this sample program works the way it does and how I can change it to work the way I would like it to work.

Essentially, I'm trying to create a list of objects, and each object in the list contains a list of objects. In the end, the sub lists are all the same list, instead of being unique to the instance of their parent class.

class Obj1(object):
    list_of_obj2 = []
    name = ''

class Obj2(object):
    name = ''

list_of_obj1 = []

for i in range(2):
    new_obj1 = Obj1()
    new_obj1.name = "obj1_%s" % i
    print "Creating Object1 named %s" % new_obj1.name

    for j in range(2):
        new_obj2 = Obj2()
        new_obj2.name = "...obj2_%s_%s" % (i, j)

        new_obj1.list_of_obj2.append(new_obj2)
        print "...Added Object2 named %s to %s list" % (new_obj2.name, new_obj1.name)

    list_of_obj1.append(new_obj1)
    print "Added Object1 named %s to master list" % (new_obj1.name)

print ""

for obj in list_of_obj1:
    print "%s has %s items in list" % (obj.name, len(obj.list_of_obj2))
    for obj2 in obj.list_of_obj2:
        print "...%s" % obj2.name

The output of the program:

Creating Object1 named obj1_0
...Added Object2 named ...obj2_0_0 to obj1_0 list
...Added Object2 named ...obj2_0_1 to obj1_0 list
Added Object1 named obj1_0 to master list
Creating Object1 named obj1_1
...Added Object2 named ...obj2_1_0 to obj1_1 list
...Added Object2 named ...obj2_1_1 to obj1_1 list
Added Object1 named obj1_1 to master list

obj1_0 has 4 items in list
......obj2_0_0
......obj2_0_1
......obj2_1_0
......obj2_1_1
obj1_1 has 4 items in list
......obj2_0_0
......obj2_0_1
......obj2_1_0
......obj2_1_1

Why don't the two Obj1 lists each have 2 items? Is there a better way to implement this?

Body:
list_of_obj2 is a class attribute of Obj1, if you want instance attribute:

class Obj1(object):
    def __init__(self):
        self.list_of_obj2 = []


问:
How to combine 2 arrays with the condition that 2 and 5 values will be from the second array?
There are two arrays:

```<code>$arrOne = [1, 3, 4];
$arrTwo = [2, 5,];
$newArr = [];
</code>```

How to merge to get like this;

$newArr = [1, 2, 3, 4, 5];

Now displays through one, this option is not suitable.

```<code>foreach ($arrOne as $k => $v) {
 $newArr[] = $v;
 $newArr[] = $arrTwo[$k];
}
</code>```

Here is another example. Tthe values can be different in the array.

```<code>$arrOne = [154, 32, 15];
$arrTwo = [682, 124,];
</code>```

Again for this example it is necessary that the values from the second array always be at 2 and 5 positions in the new array:

```<code>$newArr = [154, 682, 32, 15, 124];
</code>```

答:
You can use array_splice to merge the arrays in the intended way to the specific indices:

```<code>array_splice( $arrOne, 1, 0, $arrTwo[0]);
array_splice( $arrOne, 4, 0, $arrTwo[1]);

var_dump($arrOne);
</code>```

Demo 1:

Using original data:

```<code>$arrOne = [1, 3, 4];
$arrTwo = [2, 5,];
</code>```

https://3v4l.org/dAMav

Demo 2:

Using second set of data:

```<code>$arrOne = [154, 32, 15];
$arrTwo = [682, 124,];
</code>```

https://3v4l.org/Xhl3K

Body:
There are two arrays:

$arrOne = [1, 3, 4];
$arrTwo = [2, 5,];
$newArr = [];

How to merge to get like this;

$newArr = [1, 2, 3, 4, 5];

Now displays through one, this option is not suitable.

foreach ($arrOne as $k => $v) {
 $newArr[] = $v;
 $newArr[] = $arrTwo[$k];
}

Here is another example. Tthe values can be different in the array.

$arrOne = [154, 32, 15];
$arrTwo = [682, 124,];

Again for this example it is necessary that the values from the second array always be at 2 and 5 positions in the new array:

$newArr = [154, 682, 32, 15, 124];

Body:
You can use array_splice to merge the arrays in the intended way to the specific indices:

array_splice( $arrOne, 1, 0, $arrTwo[0]);
array_splice( $arrOne, 4, 0, $arrTwo[1]);

var_dump($arrOne);

Demo 1:

Using original data:

$arrOne = [1, 3, 4];
$arrTwo = [2, 5,];

https://3v4l.org/dAMav

Demo 2:

Using second set of data:

$arrOne = [154, 32, 15];
$arrTwo = [682, 124,];

https://3v4l.org/Xhl3K


答:
I haven't worked with tkinter, but PySimplyGUI, which to my knowledge is built on tkinter so you should have the possibility to extract the variables that correspond to the name of the file selected by the user. That's what I'm doing using PySimpleGUIon a similar problem.

Then, extract the file name selected by the user through the prompt and pass it as an argument to your function:

```<code>def convert(file):
    df = pd.read_csv("{}.txt".format(file), delimiter=';')
    df.to_csv('Cognex_Data.csv')
</code>```

Title: Python convert.txt to .csv without having a specific file name

Body:
I haven't worked with tkinter, but PySimplyGUI, which to my knowledge is built on tkinter so you should have the possibility to extract the variables that correspond to the name of the file selected by the user. That's what I'm doing using PySimpleGUIon a similar problem.

Then, extract the file name selected by the user through the prompt and pass it as an argument to your function:

def convert(file):
    df = pd.read_csv("{}.txt".format(file), delimiter=';')
    df.to_csv('Cognex_Data.csv')


问:
How show one element of the JSON on interpolation with Angular
How show one element of the JSON on interpolation with Angular

```<code>  public responseData:any;

  renderTokenCard(){
    this.mundipaggS.checkToken().subscribe((response:any)=> {
    console.log("success: ", JSON.stringify(response));
    this.cartS.tokenCard = response;
    this.responseData = response;
  }, );
</code>```

         {{responseData}}
        </div

```
<p>The JSON</p>
<pre class="lang-json prettyprint-override"><code>[{"id":1,"pessoa_id":75505,"created_at":"2022-02-01T17:42:46.000000Z","holder":"test ","validade":"2026-06-01","bandeira":"Mastercard"}]
</code>```

How can I show the JSON holder property for example?

答:
sould be pretty simple if I understand you correctly:

this.responseData = response?[0];
```
<pre class="lang-html prettyprint-override"><code><!-- the whole responseData -->
<b>{{responseData | json}}</b>

<!-- only the holder property -->
<b *ngIf="responseData">{{responseData.holder}}</b>
</code>```

Body:
How show one element of the JSON on interpolation with Angular

  public responseData:any;

  renderTokenCard(){
    this.mundipaggS.checkToken().subscribe((response:any)=> {
    console.log("success: ", JSON.stringify(response));
    this.cartS.tokenCard = response;
    this.responseData = response;
  }, );

         {{responseData}}
        </div

The JSON

[{"id":1,"pessoa_id":75505,"created_at":"2022-02-01T17:42:46.000000Z","holder":"test ","validade":"2026-06-01","bandeira":"Mastercard"}]

How can I show the JSON holder property for example?

Body:
sould be pretty simple if I understand you correctly:

this.responseData = response?[0];

<!-- the whole responseData -->
<b>{{responseData | json}}</b>

<!-- only the holder property -->
<b *ngIf="responseData">{{responseData.holder}}</b>


问:
pandas - How to unstack dict column values to 2 new columns with the same name to all?
I currently have the dataframe bellow, with a dict inside the column value.

```<code>     variable    value
0       b44     {55: 20}
1       a11     {56: 19}
5       a34     {33: 19}
</code>```

How to transform the above df to a df that looks like this:

```<code>      variable    id   value
0       b44       55     20
1       a11       56     19
5       a34       33     19
</code>```

答:
Try with stack after create the new df

```<code>s = pd.DataFrame(df.pop('value').tolist(),index=df.index).stack().reset_index(level=1)
s.columns = ['id','value']
df = df.join(s)
df
Out[82]:
  variable  id  value
0      b44  55   20.0
1      a11  56   19.0
5      a34  33   19.0
</code>```

Body:
I currently have the dataframe bellow, with a dict inside the column value.

     variable    value
0       b44     {55: 20}
1       a11     {56: 19}
5       a34     {33: 19}

How to transform the above df to a df that looks like this:

      variable    id   value
0       b44       55     20
1       a11       56     19
5       a34       33     19

Body:
Try with stack after create the new df

s = pd.DataFrame(df.pop('value').tolist(),index=df.index).stack().reset_index(level=1)
s.columns = ['id','value']
df = df.join(s)
df
Out[82]:
  variable  id  value
0      b44  55   20.0
1      a11  56   19.0
5      a34  33   19.0