问:
How to make a list of Months along with Year (for eg. January 2022, February 2022) from a given Date until current month in Flutter/Dart?
I am trying to prepare a list of Months with Years, such as below:

```<code>monthYearList = ["December 2021", "January 2022", "February 2022"]
</code>```

I have a date given, say:  date = "2021-10-25" .
Date Format is yyyy-MM-dd.

Now how to prepare the data for all the Months along with Years from this given date until the current month in a List.

Expected Output: monthYearList =  ["October 2021", "November 2021", "December 2021", "January 2022", "February 2022"]

Such that it's in non-decreasing order as per month progression.

"November 2021", "December 2021" comes before "January 2022" only until the current month.

I am new to Flutter, and don't have much idea how to work with Dates in dart.

答:
Check this out:

```<code>
List<String> getMonthsFromDayTillNow(String day) {
  // 2021-10-
  List<String> dateSplit = day.split("-");
  DateTime loopDateTime =
      DateTime(int.parse(dateSplit[0]), int.parse(dateSplit[1]), 28);
  DateTime currentDateTime = DateTime.now();
  List<String> months = [];
  while (loopDateTime.isBefore(currentDateTime)) {
    months.add("${getMonth(loopDateTime.month)} ${loopDateTime.year}");
    loopDateTime = loopDateTime.add(Duration(days: 5));
    loopDateTime = DateTime(loopDateTime.year, loopDateTime.month, 28);
  }
  months.add("${getMonth(currentDateTime.month)} ${currentDateTime.year}");
  return months;
}

String getMonth(int monthNumber) {
  late String month;
  switch (monthNumber) {
    case 1:
      month = "January";
      break;
    case 2:
      month = "February";
      break;
    case 3:
      month = "March";
      break;
    case 4:
      month = "April";
      break;
    case 5:
      month = "May";
      break;
    case 6:
      month = "June";
      break;
    case 7:
      month = "July";
      break;
    case 8:
      month = "August";
      break;
    case 9:
      month = "September";
      break;
    case 10:
      month = "October";
      break;
    case 11:
      month = "November";
      break;
    case 12:
      month = "December";
      break;
  }
  return month;
}
</code>```

Output:

```<code>void main() {
  print(getMonthsFromDayTillNow("2021-10-5")); //[October 2021, November 2021, December 2021, January 2022, February 2022]

}
</code>```

Body:
I am trying to prepare a list of Months with Years, such as below:

monthYearList = ["December 2021", "January 2022", "February 2022"]

I have a date given, say:  date = "2021-10-25" .
Date Format is yyyy-MM-dd.

Now how to prepare the data for all the Months along with Years from this given date until the current month in a List.

Expected Output: monthYearList =  ["October 2021", "November 2021", "December 2021", "January 2022", "February 2022"]

Such that it's in non-decreasing order as per month progression.

"November 2021", "December 2021" comes before "January 2022" only until the current month.

I am new to Flutter, and don't have much idea how to work with Dates in dart.

Body:
Check this out:

List<String> getMonthsFromDayTillNow(String day) {
  // 2021-10-
  List<String> dateSplit = day.split("-");
  DateTime loopDateTime =
      DateTime(int.parse(dateSplit[0]), int.parse(dateSplit[1]), 28);
  DateTime currentDateTime = DateTime.now();
  List<String> months = [];
  while (loopDateTime.isBefore(currentDateTime)) {
    months.add("${getMonth(loopDateTime.month)} ${loopDateTime.year}");
    loopDateTime = loopDateTime.add(Duration(days: 5));
    loopDateTime = DateTime(loopDateTime.year, loopDateTime.month, 28);
  }
  months.add("${getMonth(currentDateTime.month)} ${currentDateTime.year}");
  return months;
}

String getMonth(int monthNumber) {
  late String month;
  switch (monthNumber) {
    case 1:
      month = "January";
      break;
    case 2:
      month = "February";
      break;
    case 3:
      month = "March";
      break;
    case 4:
      month = "April";
      break;
    case 5:
      month = "May";
      break;
    case 6:
      month = "June";
      break;
    case 7:
      month = "July";
      break;
    case 8:
      month = "August";
      break;
    case 9:
      month = "September";
      break;
    case 10:
      month = "October";
      break;
    case 11:
      month = "November";
      break;
    case 12:
      month = "December";
      break;
  }
  return month;
}

Output:

void main() {
  print(getMonthsFromDayTillNow("2021-10-5")); //[October 2021, November 2021, December 2021, January 2022, February 2022]

}


来源: stackexchange

问:
Class error 'str' object has no attribute
I am getting the following error for my code:

```<code>Enter your first 3x3 matrix:
    matrices.matrix_one("")
  File "C:\Users\ablev\eclipse-workspace\SDEV300Lab4\matrix.py", line 61, in matrix_one
    self.MATRIX1=[]
AttributeError: 'str' object has no attribute 'MATRIX1'
</code>```

Program is supposed to ask the user to enter two matrices, then compute the addition of the two matrices. I am new to python and probably structuring the class wrong. Any help is appreciated. Thanks.

```<code>class matrices:

    def __init__(self,MATRIX1,MATRIX2):
        self.MATRIX1 = ''
        self.MATRIX2 = ''

    def matrix_one(self):
        """first matrix"""
        print("Enter your first 3x3 matrix: ")
        self.MATRIX1=[]
        for i in range(3):
            while True:
                row=input().split()
                row=list(map(int,row))
                if len(row) != 3:
                    print("Please enter 3 rows of 3 columns of\
    numbers separated by a space: ")
                else:
                    break
            self.MATRIX1.append(row)
        print("Your first 3x3 matrix is: ")
        for i in range(3):
            for j in range(3):
                print(self.MATRIX1[i][j],end=" ")
            print()

    def matrix_two(self):
        """asking user for input of second matrix"""
        print("Enter your second 3x3 matrix: ")
        self.MATRIX2=[]
        for i in range(3):
            while True:
                row=input().split()
                row=list(map(int,row))
                if len(row) != 3:
                    print("Please enter 3 rows of 3 columns of\
    numbers separated by a space: ")
                else:
                    break
            self.MATRIX2.append(row)
        print("Your second 3x3 matrix is: ")
        for i in range(3):
            for j in range(3):
                print(self.MATRIX2[i][j],end=" ")
            print()

    def add(self):
        '''function to subtract results of matrix'''
        results = np.add(self.MATRIX1,self.MATRIX2)
        return results

matrices.matrix_one("")
matrices.matrix_two("")

matrices.add("")
</code>```

答:
By calling matrices.matrix_one("") you are passing an empty string as self to matrix_one.

You probably want to create an instance of your class instead, so that self refers to the class instance when you call the methods:

```<code>m = matrices()
m.matrix_one()
m.matrix_two()
m.add()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am getting the following error for my code:

Enter your first 3x3 matrix:
    matrices.matrix_one("")
  File "C:\Users\ablev\eclipse-workspace\SDEV300Lab4\matrix.py", line 61, in matrix_one
    self.MATRIX1=[]
AttributeError: 'str' object has no attribute 'MATRIX1'

Program is supposed to ask the user to enter two matrices, then compute the addition of the two matrices. I am new to python and probably structuring the class wrong. Any help is appreciated. Thanks.

class matrices:

    def __init__(self,MATRIX1,MATRIX2):
        self.MATRIX1 = ''
        self.MATRIX2 = ''

    def matrix_one(self):
        """first matrix"""
        print("Enter your first 3x3 matrix: ")
        self.MATRIX1=[]
        for i in range(3):
            while True:
                row=input().split()
                row=list(map(int,row))
                if len(row) != 3:
                    print("Please enter 3 rows of 3 columns of\
    numbers separated by a space: ")
                else:
                    break
            self.MATRIX1.append(row)
        print("Your first 3x3 matrix is: ")
        for i in range(3):
            for j in range(3):
                print(self.MATRIX1[i][j],end=" ")
            print()

    def matrix_two(self):
        """asking user for input of second matrix"""
        print("Enter your second 3x3 matrix: ")
        self.MATRIX2=[]
        for i in range(3):
            while True:
                row=input().split()
                row=list(map(int,row))
                if len(row) != 3:
                    print("Please enter 3 rows of 3 columns of\
    numbers separated by a space: ")
                else:
                    break
            self.MATRIX2.append(row)
        print("Your second 3x3 matrix is: ")
        for i in range(3):
            for j in range(3):
                print(self.MATRIX2[i][j],end=" ")
            print()

    def add(self):
        '''function to subtract results of matrix'''
        results = np.add(self.MATRIX1,self.MATRIX2)
        return results

matrices.matrix_one("")
matrices.matrix_two("")

matrices.add("")

Body:
By calling matrices.matrix_one("") you are passing an empty string as self to matrix_one.

You probably want to create an instance of your class instead, so that self refers to the class instance when you call the methods:

m = matrices()
m.matrix_one()
m.matrix_two()
m.add()


问:
Drupal 7 I need to change the sku directly in the commerce_product table and want to know if this is possible to do without creating a drush script
I need to change the sku directly in the commerce_product table and want to know if this is possible to do without creating a drush script.</p>

答:
This can be done by changing the same sku in both commerce_product & commerce_product_revision then truncating all of the cache tables.</p>
```<code>UPDATE `commerce_product` SET `sku` = 456 WHERE `sku` = 123;

UPDATE `commerce_product_revision` SET `sku` = 456 WHERE `sku` = 123;
</code>```

Body:
This can be done by changing the same sku in both commerce_product & commerce_product_revision then truncating all of the cache tables.

UPDATE `commerce_product` SET `sku` = 456 WHERE `sku` = 123;

UPDATE `commerce_product_revision` SET `sku` = 456 WHERE `sku` = 123;


问:
How to use while with loc as condition?

import pandas as pd

```<code>x = pd.read_excel("C:\\Users\\Igor\\Desktop\\Visão Geral - Carteira FII - IGOR.xlsx",sheet_name = "dividendos")
y = pd.DataFrame(x)
y
</code>```

out:

```<code>Stock   DIVIDEND    Payment Month
0   BRCR11  4.50    2022-01-14  2022-01-01
1   BLMG11  15.30   2022-01-15  2022-01-01
2   BRCO11  10.71   2022-01-07  2022-01-01
3   BTAL11  9.13    2022-01-26  2022-01-01
4   BTRA11  10.68   2022-01-31  2022-01-01
5   BTLG11  10.80   2022-01-25  2022-01-01
</code>```

```<code>t = 0
while y.loc[t] != "":
    print(t)
t = t + 1
</code>```

out:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

答:
I assume you are new to Python and Pandas. look what is type(df.loc[0]). It is  pandas.core.series.Series=, and cannot be compare to a string.
Using of while is not common in Python and even less with Pandas.
are you looking for an empty "cell">
Probably you are looking to something like print(df[df['Stock'].isna()])
I am not sure which columns you assume to be empty.

Title: How to use while with loc as condition?

Body:
import pandas as pd

x = pd.read_excel("C:\\Users\\Igor\\Desktop\\Visão Geral - Carteira FII - IGOR.xlsx",sheet_name = "dividendos")
y = pd.DataFrame(x)
y

out:

Stock   DIVIDEND    Payment Month
0   BRCR11  4.50    2022-01-14  2022-01-01
1   BLMG11  15.30   2022-01-15  2022-01-01
2   BRCO11  10.71   2022-01-07  2022-01-01
3   BTAL11  9.13    2022-01-26  2022-01-01
4   BTRA11  10.68   2022-01-31  2022-01-01
5   BTLG11  10.80   2022-01-25  2022-01-01

t = 0
while y.loc[t] != "":
    print(t)
t = t + 1

out:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().


问:
Go timeout for Read
I'd like to do something like unix's tail -f, but on the output produced by a process run through Go's Cmd facility.

My google-fu is not up to par, evidently, but I did find this article which lead me to write the following code, which almost works, with a bizarre twist I'm hoping I can get help with.

If it matters, I'm running this on a Mac.

First, here's the minimal program that's compiled to be the slowroll executable:

package main

import (
    "fmt"
    "time"
)

func main() {
    line := 1
    for {
        fmt.Println("This is line", line)
        line += 1
        time.Sleep(2 * time.Second)
    }
}
```
<p>When run, it produces the following output, one line every 2 seconds:</p>
```    > ./slowroll
    This is line 1
    This is line 2
    This is line 3
    This is line 4
```
<p>And so on.</p>
<p>Here's the package code that attempts to read this, but allowing timeouts so other things can be done:</p>
<pre class="lang-golang prettyprint-override"><code>package timeout_io

import (
    "bufio"
    "bytes"
    "context"
    "errors"
    "time"
)

const BufferSize = 4096

var ErrTimeout = errors.New("timeout")

type TimeoutReader struct {
    b *bufio.Reader
    t time.Duration
}

func NewTimeoutReader(stdOut *bytes.Buffer) *TimeoutReader {
    return &TimeoutReader{b: bufio.NewReaderSize(stdOut, BufferSize), t: 0}
}

func (r *TimeoutReader) SetTimeout(t time.Duration) time.Duration {
    prev := r.t
    r.t = t
    return prev
}

type CallResponse struct {
    Resp string
    Err  error
}

func helper(r *bufio.Reader) <-chan *CallResponse {
    respChan := make(chan *CallResponse, 1)

    go func() {
        resp, err := r.ReadString('\n')

        if err != nil {
            respChan <- &CallResponse{resp, err}
        } else {
            respChan <- &CallResponse{resp, nil}
        }

        return
    }()

    return respChan
}

func (r *TimeoutReader) ReadLineCtx(ctx context.Context) (string, error) {
    select {
    case <-ctx.Done():
        return "", ErrTimeout
    case respChan := <-helper(r.b):
        return respChan.Resp, respChan.Err
    }
}

func (r *TimeoutReader) ReadLine() (string, error) {
    ctx, cancel := context.WithTimeout(context.Background(), r.t)
    defer cancel()

    s, err := r.ReadLineCtx(ctx)
    if err != nil {
        return "", err
    }

    return s, nil
}
</code>```

Finally, here's the main code that calls ReadLine with timeout:

package main

import (
    "bytes"
    "fmt"
    "io"
    "os"
    "os/exec"
    "sync"
    "time"

    "watcher/timeout_io"
)

func main() {
    var stdOut bytes.Buffer
    var stdErr bytes.Buffer
    runCommand := &exec.Cmd{
        Path:   "./slowroll",
        Stdout: &stdOut,
        Stderr: &stdErr,
    }

    var wg sync.WaitGroup

    go func(wg *sync.WaitGroup) {
        defer wg.Done()

        err := runCommand.Run()
        if err != nil {
            fmt.Println("failed due to error:", err)
            os.Exit(1)
        }
    }(&wg)

    wg.Add(1)

    stdOutReader := timeout_io.NewTimeoutReader(&stdOut)
    stdOutReader.SetTimeout(10 * time.Millisecond)
    index := 1
    for {
        s, err := stdOutReader.ReadLine()
        if err != nil {
            if err != timeout_io.ErrTimeout && err != io.EOF {
                fmt.Println("ReadLine got error", err)
                break
            }
        } else if len(s) > 0 {
            fmt.Println("index: ", index, " s: ", s)
            index += 1
            s = ""
        }
    }

    wg.Wait()
    fmt.Println("Done!")
}
```
<p>When run, it produces the following output:</p>
```    > go run watcher.go
    index:  1  s:  This is line 1

    index:  2  s:  This is line 2

    index:  3  s:  This is line 2

    index:  4  s:  This is line 3

    index:  5  s:  This is line 2

    index:  6  s:  This is line 3

    index:  7  s:  This is line 4

    index:  8  s:  This is line 2

    index:  9  s:  This is line 3

    index:  10  s:  This is line 4

    index:  11  s:  This is line 5
```

And so on.

Occasionally, some slowroll output lines don't show up at all; which lines get repeated is random.

So that's my mystery... I don't see where the (apparent) loop is happening that causes the lines to be produced multiple times.

Thanks very much in advance for any help!

答:
if err != timeout_io.ErrTimeout && err != io.EOF { ...; break; }

With such a condition, an ErrTimeout will be silently ignored and will not interrupt your reading loop.

Also note that reaching io.EOF would send your program in an endless loop (try using echo "Hello" instead of ./slowroll as a command).

You probably want to place the break instruction after the if block :

```<code>if err != timeout_io.ErrTimeout && err != io.EOF {
    fmt.Println("ReadLine got error", err)
}
break
</code>```

Title: Go timeout for Read

Body:
I'd like to do something like unix's tail -f, but on the output produced by a process run through Go's Cmd facility.

My google-fu is not up to par, evidently, but I did find this article which lead me to write the following code, which almost works, with a bizarre twist I'm hoping I can get help with.

If it matters, I'm running this on a Mac.

First, here's the minimal program that's compiled to be the slowroll executable:

package main

import (
    "fmt"
    "time"
)

func main() {
    line := 1
    for {
        fmt.Println("This is line", line)
        line += 1
        time.Sleep(2 * time.Second)
    }
}

When run, it produces the following output, one line every 2 seconds:

    > ./slowroll
    This is line 1
    This is line 2
    This is line 3
    This is line 4

And so on.

Here's the package code that attempts to read this, but allowing timeouts so other things can be done:

package timeout_io

import (
    "bufio"
    "bytes"
    "context"
    "errors"
    "time"
)

const BufferSize = 4096

var ErrTimeout = errors.New("timeout")

type TimeoutReader struct {
    b *bufio.Reader
    t time.Duration
}

func NewTimeoutReader(stdOut *bytes.Buffer) *TimeoutReader {
    return &TimeoutReader{b: bufio.NewReaderSize(stdOut, BufferSize), t: 0}
}

func (r *TimeoutReader) SetTimeout(t time.Duration) time.Duration {
    prev := r.t
    r.t = t
    return prev
}

type CallResponse struct {
    Resp string
    Err  error
}

func helper(r *bufio.Reader) <-chan *CallResponse {
    respChan := make(chan *CallResponse, 1)

    go func() {
        resp, err := r.ReadString('\n')

        if err != nil {
            respChan <- &CallResponse{resp, err}
        } else {
            respChan <- &CallResponse{resp, nil}
        }

        return
    }()

    return respChan
}

func (r *TimeoutReader) ReadLineCtx(ctx context.Context) (string, error) {
    select {
    case <-ctx.Done():
        return "", ErrTimeout
    case respChan := <-helper(r.b):
        return respChan.Resp, respChan.Err
    }
}

func (r *TimeoutReader) ReadLine() (string, error) {
    ctx, cancel := context.WithTimeout(context.Background(), r.t)
    defer cancel()

    s, err := r.ReadLineCtx(ctx)
    if err != nil {
        return "", err
    }

    return s, nil
}

Finally, here's the main code that calls ReadLine with timeout:

package main

import (
    "bytes"
    "fmt"
    "io"
    "os"
    "os/exec"
    "sync"
    "time"

    "watcher/timeout_io"
)

func main() {
    var stdOut bytes.Buffer
    var stdErr bytes.Buffer
    runCommand := &exec.Cmd{
        Path:   "./slowroll",
        Stdout: &stdOut,
        Stderr: &stdErr,
    }

    var wg sync.WaitGroup

    go func(wg *sync.WaitGroup) {
        defer wg.Done()

        err := runCommand.Run()
        if err != nil {
            fmt.Println("failed due to error:", err)
            os.Exit(1)
        }
    }(&wg)

    wg.Add(1)

    stdOutReader := timeout_io.NewTimeoutReader(&stdOut)
    stdOutReader.SetTimeout(10 * time.Millisecond)
    index := 1
    for {
        s, err := stdOutReader.ReadLine()
        if err != nil {
            if err != timeout_io.ErrTimeout && err != io.EOF {
                fmt.Println("ReadLine got error", err)
                break
            }
        } else if len(s) > 0 {
            fmt.Println("index: ", index, " s: ", s)
            index += 1
            s = ""
        }
    }

    wg.Wait()
    fmt.Println("Done!")
}

When run, it produces the following output:

    > go run watcher.go
    index:  1  s:  This is line 1

    index:  2  s:  This is line 2

    index:  3  s:  This is line 2

    index:  4  s:  This is line 3

    index:  5  s:  This is line 2

    index:  6  s:  This is line 3

    index:  7  s:  This is line 4

    index:  8  s:  This is line 2

    index:  9  s:  This is line 3

    index:  10  s:  This is line 4

    index:  11  s:  This is line 5

And so on.

Occasionally, some slowroll output lines don't show up at all; which lines get repeated is random.

So that's my mystery... I don't see where the (apparent) loop is happening that causes the lines to be produced multiple times.

Thanks very much in advance for any help!

Body:
if err != timeout_io.ErrTimeout && err != io.EOF { ...; break; }

With such a condition, an ErrTimeout will be silently ignored and will not interrupt your reading loop.

Also note that reaching io.EOF would send your program in an endless loop (try using echo "Hello" instead of ./slowroll as a command).

You probably want to place the break instruction after the if block :

if err != timeout_io.ErrTimeout && err != io.EOF {
    fmt.Println("ReadLine got error", err)
}
break


问:
Can I set specific env variable to only one of the Pods within a deployment with multiple replicas?
I have a deployment of my backend app which has 6 replicas. In the code of the app, I have a node.js cronjob running every minute. But the problem is that because I have 6 replicas, it runs 6 times in parallel. I want to send env variable to exactly only one Pod in the deployment to ensure that only 1 Pod performs the cronjob. Then in the app code I will check this using the process.env.SHOULD_PROCESS_CRONJOBS == 1.

If this is not the right way to achieve what I need, can you inform me on how to handle cronjobs using nodejs in distributed environment like K8S?

答:
Let Kubernetes schedule a CronJob in addition to the application

```<code>apiVersion: batch/v1
kind: CronJob
metadata:
  name: app-cron
spec:
  schedule: "* * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: my-app-cron
            image: same-as-app
            imagePullPolicy: IfNotPresent
            command:
            - /bin/sh
            - -c
            - date; echo Hello from scheduled job
          restartPolicy: OnFailure
</code>```

If you don't want kubernetes supervising the cron scheduling, then another option is to split out the application that schedules the cron into two Deployments. Only use 1 replica for the container that has environment variable:

```<code>      env:
      - name: SHOULD_PROCESS_CRONJOBS
        value: "1"
</code>```

Body:
Let Kubernetes schedule a CronJob in addition to the application

apiVersion: batch/v1
kind: CronJob
metadata:
  name: app-cron
spec:
  schedule: "* * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: my-app-cron
            image: same-as-app
            imagePullPolicy: IfNotPresent
            command:
            - /bin/sh
            - -c
            - date; echo Hello from scheduled job
          restartPolicy: OnFailure

If you don't want kubernetes supervising the cron scheduling, then another option is to split out the application that schedules the cron into two Deployments. Only use 1 replica for the container that has environment variable:

      env:
      - name: SHOULD_PROCESS_CRONJOBS
        value: "1"


问:
how to use '\n' within text property of mx:TextArea in flex 4?
As per my observation this does not work in flex4:

```<code><mx:TextArea id="taMytext" text="\n hi\n san"/> //use of \n does not work here
<s:Button label="Click it" click="Myfun()" />
</code>```

Using script it's possible:

```<code>public function Myfun():void
            {
                taMytext.text="hi\n";
                taMytext.text+="san";
            }
</code>```

答:
You have to use the following syntax:

```<code><mx:TextArea id="taMytext" text="\n hi{'\n'} san"/>
</code>```

More detailled explaination can be found on adobe cookbooks

ContentLicense: CC BY-SA 3.0

Body:
As per my observation this does not work in flex4:

<mx:TextArea id="taMytext" text="\n hi\n san"/> //use of \n does not work here
<s:Button label="Click it" click="Myfun()" />

Using script it's possible:

public function Myfun():void
            {
                taMytext.text="hi\n";
                taMytext.text+="san";
            }

Body:
You have to use the following syntax:

<mx:TextArea id="taMytext" text="\n hi{'\n'} san"/>

More detailled explaination can be found on adobe cookbooks


问:
Using "x:" in an XML element name
I'm trying to create an XML file that needs to be sent to a server, with this format:

```<code><x:Envelope xmlns:x="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:sen2="http://www.some_url.com">
<x:Header>
</code>```

I'm working with Python 3 and the lxml library, but when trying to create the element I get an error.

Test code:

```<code>def authSendDataExtraccion():
    envelope = etree.Element("x:Envelope")
    debug_XML(envelope)
</code>```

Result:

```<code>ValueError: Invalid tag name 'x:Envelope'
</code>```

How can I use the ":" character in the element and attribute names?

答:
Use an nsmap to create an element in a namespace:

```<code>envelope = etree.Element("Envelope", nsmap={'x': 'http://schemas.xmlsoap.org/soap/envelope/'})
</code>```

Title: Using "x:" in an XML element name

Body:
I'm trying to create an XML file that needs to be sent to a server, with this format:

<x:Envelope xmlns:x="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:sen2="http://www.some_url.com">
<x:Header>

I'm working with Python 3 and the lxml library, but when trying to create the element I get an error.

Test code:

def authSendDataExtraccion():
    envelope = etree.Element("x:Envelope")
    debug_XML(envelope)

Result:

ValueError: Invalid tag name 'x:Envelope'

How can I use the ":" character in the element and attribute names?

Body:
Use an nsmap to create an element in a namespace:

envelope = etree.Element("Envelope", nsmap={'x': 'http://schemas.xmlsoap.org/soap/envelope/'})


问:
Windows 10 electron forge icon isn't working
I'm trying to publish my electron app, And I'm using the following code in the package.json:

```<code>  "packagerConfig": {
    "icon": "./src/icon.ico"
  },
</code>```

But when I use electron forge and look into out/win32-x64 directory, the single executable is the default electron icon, when I run it the icon appears both in the app top right corner, as well as the shortcut icon.

I've scoured the internet and couldn't find a fix for this.

Heres the github with the code: https://github.com/Paxxous/Extremely-minamilistic-text-editor

答: Okay so it was just a weird bug that I found, You just have to move the exe out of the directory and then it would show. (Though also make sure to remove the out folder just in case)</p>

Body:
I'm trying to publish my electron app, And I'm using the following code in the package.json:

  "packagerConfig": {
    "icon": "./src/icon.ico"
  },

But when I use electron forge and look into out/win32-x64 directory, the single executable is the default electron icon, when I run it the icon appears both in the app top right corner, as well as the shortcut icon.

I've scoured the internet and couldn't find a fix for this.

Heres the github with the code: https://github.com/Paxxous/Extremely-minamilistic-text-editor


问:
Eventbridge - Use FIFO SQS for deduplication
I need some events to be delivered exactly once, but I have no control of the message processor (so I can‘t make the recipient idempotent).

Is it possible to route events from Eventbridge to a FIFO SQS for deduplication and from the FIFO sqs to the recipient (lambda on other account? Would this achieve exact-once delivery?

答:
It EventBridge (EB) has at-least-once deliver which means you can get more then one event of the same type. But if this is not an issue, and your only concern is SQS, then yes, EB supports SQS FIFO targets:

EventBridge lets you set a variety of targets—such as Amazon SQS standard and FIFO queues—which receive events in JSON format.


问:
Is my Java solution O(n) or am I missing something?
My solution for a certain problem is apparently slower than 95% of solutions and I wanted to make sure that I was correct on the time complexity.

It looks to me like this code is O(n). I use a couple of loops that are at most O(n) and they aren't nested so I don't believe the solution is n^2.

I use a HashMap as storage and use HashMap methods which are O(1) inside my while and for-loop for insertion and look ups respectively.

Am I correct in that this solution is O(n) or am I missing something?

```<code> public int pairSum(ListNode head) {

    HashMap<Integer, Integer> nodeVals = new HashMap<Integer, Integer>();

    int count = 0;

    ListNode current = head;
    nodeVals.put(count, current.val);
    count++;

    while (current.next != null) {
        current = current.next;
        nodeVals.put(count, current.val);
        count++;
    }

    int maxTwinSum = 0;
    for (int i = 0; i < nodeVals.size() / 2; i++) {
        int currTwinSum;
        currTwinSum = nodeVals.get(i) + nodeVals.get(nodeVals.size() - 1 - i);
        if (currTwinSum > maxTwinSum) maxTwinSum = currTwinSum;
    }

    return maxTwinSum;
}
</code>```

答:
Is my Java solution O(N) or am I missing something?

Yes to both!

Your solution is O(N), AND you are missing something.

The something that you are missing is that complexity and performance are NOT the same thing.  Complexity is about how some measure (e.g. time taken, space used, etc) changes depending on certain problem size variables; e.g. the size of the list N.

Put it another way ... not all O(N) solutions to a problem will have the same performance.  Some are faster, some are slower.

In your case, HashMap is a relatively expensive data structure.  While it it (amortized) O(1) for operations like get and put, the constants of proportionality are large compared with (say) using an ArrayList or an array to hold the same information.

So ... I expect that the solutions that are faster than yours won't be using HashMap.

The flipside is that an O(N^2) solution can be faster than an O(N) solution if you only consider values of N less than some threshold.  This follows from the mathematical definition of Big O.

For instance, if you are sorting arrays of integers and the array size is small enough, a naive bubblesort will be faster than quicksort.

In short: complexity is not performance.

Body:
My solution for a certain problem is apparently slower than 95% of solutions and I wanted to make sure that I was correct on the time complexity.

It looks to me like this code is O(n). I use a couple of loops that are at most O(n) and they aren't nested so I don't believe the solution is n^2.

I use a HashMap as storage and use HashMap methods which are O(1) inside my while and for-loop for insertion and look ups respectively.

Am I correct in that this solution is O(n) or am I missing something?

 public int pairSum(ListNode head) {

    HashMap<Integer, Integer> nodeVals = new HashMap<Integer, Integer>();

    int count = 0;

    ListNode current = head;
    nodeVals.put(count, current.val);
    count++;

    while (current.next != null) {
        current = current.next;
        nodeVals.put(count, current.val);
        count++;
    }

    int maxTwinSum = 0;
    for (int i = 0; i < nodeVals.size() / 2; i++) {
        int currTwinSum;
        currTwinSum = nodeVals.get(i) + nodeVals.get(nodeVals.size() - 1 - i);
        if (currTwinSum > maxTwinSum) maxTwinSum = currTwinSum;
    }

    return maxTwinSum;
}


问:
How to make property type depends on it's brother
I have configuration that build dynamic components.

Any class implement the property data with some unique type.

I need the config property in ConfType to have the type of the data within the giving Class in the exec configuration dynamically.

```<code>type TestData = { /** ...some data object */ }
class TestClass<T extends TestData = TestData>{
  data: T
}
export type ConfType<T extends { data: any }> = {
  type: Type<T>;
  config: T['data'];
}

const dynamicComponentConfig: ConfType = {
  type: TestClass,
  config: will force me to have type of TestClass['data'] // TestData
  // jsut becuse the type in the brother property is TestClass
  // need to be change dynamically by the Class i Put on the type property
}
</code>```

the type of the config need to be dynamic and depends on the giving class on the property type

One way to get it by use function.

I want to get some result without function only types or interfaces

```<code>// data to be implements
type Data = { fullScreen: boolean }
// class implements data of type data
class Class<T extends Data = Data>{
  data: T
}
// data to be implements
type Data2 = { text: string }
// class implements data of type data
class Class2<T extends Data2 = Data2>{
  data: T
}

// the type of some configuration object
export type ConfType<T extends { data: object } = any, Data extends T['data'] = T['data']> = {
  type: T;
  config: { data: Data };
}
// function that at write the code will play with the giving types // this type will cause that the config type will be depends on the giving class type implements of the data property
const buildConf = function <T extends { data: object }>({ type, config }: Omit<ConfType, 'config'> & { type: Type<T>, config: ConfType<T, T['data']>['config'] }): { type: T, config: T['data'] } {
  return {
    type,
    config // this['type']['data']
  }
}

// build some configuration object
const conf = buildConf({
  type: Class,
  config: { data: { fullScreen: true } } // Class['dta'] === Data
})

// build some wrong configuration object
const conf1 = buildConf({
  type: Class2,
  config: { data: { fullScreen: true } } //  will cause error because Class2['dta'] === Data2
})

// build some configuration object
const conf3 = buildConf({
  type: Class2,
  config: { data: { text: 'my custom text' } } // Class2['dta'] === Data2
})
</code>```

答:
Your code is close, but you must actually use the generic parameter in ConfType in order to enforce the constraint:

TS Playground

type Data = { fullScreen: boolean };

class TestClass<T extends Data = Data> {
  data: T;
  constructor (data: T) {
    this.data = data;
  }
}

export type ConfType<T extends { data: any }> = {
  type: new (...params: any[]) => T;
  config: T['data'];
}

const config1: ConfType<TestClass> = {
  type: TestClass,
  config: {}, /*
  ^^^^^^
  Property 'fullScreen' is missing in type '{}' but required in type 'Data'.(2741) */
};

// OK:
const config2: ConfType<TestClass> = {
  type: TestClass,
  config: {fullScreen: true},
};
```

Body:
I have configuration that build dynamic components.

Any class implement the property data with some unique type.

I need the config property in ConfType to have the type of the data within the giving Class in the exec configuration dynamically.

type TestData = { /** ...some data object */ }
class TestClass<T extends TestData = TestData>{
  data: T
}
export type ConfType<T extends { data: any }> = {
  type: Type<T>;
  config: T['data'];
}

const dynamicComponentConfig: ConfType = {
  type: TestClass,
  config: will force me to have type of TestClass['data'] // TestData
  // jsut becuse the type in the brother property is TestClass
  // need to be change dynamically by the Class i Put on the type property
}

the type of the config need to be dynamic and depends on the giving class on the property type

One way to get it by use function.

I want to get some result without function only types or interfaces

// data to be implements
type Data = { fullScreen: boolean }
// class implements data of type data
class Class<T extends Data = Data>{
  data: T
}
// data to be implements
type Data2 = { text: string }
// class implements data of type data
class Class2<T extends Data2 = Data2>{
  data: T
}

// the type of some configuration object
export type ConfType<T extends { data: object } = any, Data extends T['data'] = T['data']> = {
  type: T;
  config: { data: Data };
}
// function that at write the code will play with the giving types // this type will cause that the config type will be depends on the giving class type implements of the data property
const buildConf = function <T extends { data: object }>({ type, config }: Omit<ConfType, 'config'> & { type: Type<T>, config: ConfType<T, T['data']>['config'] }): { type: T, config: T['data'] } {
  return {
    type,
    config // this['type']['data']
  }
}

// build some configuration object
const conf = buildConf({
  type: Class,
  config: { data: { fullScreen: true } } // Class['dta'] === Data
})

// build some wrong configuration object
const conf1 = buildConf({
  type: Class2,
  config: { data: { fullScreen: true } } //  will cause error because Class2['dta'] === Data2
})

// build some configuration object
const conf3 = buildConf({
  type: Class2,
  config: { data: { text: 'my custom text' } } // Class2['dta'] === Data2
})

Body:
Your code is close, but you must actually use the generic parameter in ConfType in order to enforce the constraint:

<a href="https://www.typescriptlang.org/play?noUncheckedIndexedAccess=true&target=99&useUnknownInCatchVariables=true&exactOptionalPropertyTypes=true#code/C4TwDgpgBAIghsOUC8UDeUBmBXANrgZQGMAnCCAOwC4oAjAe3twjgqgF8BuAKG6NzgBnQVAAqEQcADCA4QB5RUCAA9glACYj4iFLARwAfOm5Qo6-TVE9TRehUklsRYPRJQAFOcSWAlMdOmwAAWAJaCAHReSKhR1hzc7LwqYK7AUKCQUFJ2mKLgEApKqhoiGFE0rCAcRqhoJun5NBQQAO4e4R1gcCRwALaCFRQgANoAun7IRlb1thSYIQDmlsMA5FErozyJfHaSULPzCwCMNNlzeZAKEtKygjX+DZCW1zJCggA0MzmLNGjs71AAPQAKnqAD0IZD6gAFEj0SAkUBQFY4fDEMiUFZQMJQXphQQhCgLbFsDLQFZ-LG0bBpMgAR2wITI6hJj3J2jgK3C7gATAB2AAsRz8wMBCR4O3saQOix5pxyFwK4kkr2E9zqgUaYhet0+Nm+S3QqMIpHI1HSjgg-3FQA" rel="nofollow noreferrer">TS Playground

type Data = { fullScreen: boolean };

class TestClass<T extends Data = Data> {
  data: T;
  constructor (data: T) {
    this.data = data;
  }
}

export type ConfType<T extends { data: any }> = {
  type: new (...params: any[]) => T;
  config: T['data'];
}

const config1: ConfType<TestClass> = {
  type: TestClass,
  config: {}, /*
  ^^^^^^
  Property 'fullScreen' is missing in type '{}' but required in type 'Data'.(2741) */
};

// OK:
const config2: ConfType<TestClass> = {
  type: TestClass,
  config: {fullScreen: true},
};


问:
c++builder linker problem with Abbrevia GetIt package : ilink32 error unresolved external
I am trying to use the abbrevia package ( https://github.com/TurboPack/Abbrevia ) with c++Builder in a console application.
First i tried to manually install the package. But then i found it on GetIt. Issue persists no matter how it setup the package. I think the path settings i did manually are the same as the package installer did.
It results always in unresolved externel for Abdfbase::TAbDeflateHelper::
This is the original error message:

[ilink32 Fehler] Error: Nicht auflösbares externes 'Abdfbase::TAbDeflateHelper::' referenziert von c:\pathtotheobjectfile\main.obj

Just setting up the path and compiling the projects for the c++builder ( therefore getting the objects ) is all the setup aks for. And with GetIt i dont even have to do that.

This is my most simple start which i cant even get to link.

```<code>#pragma hdrstop
#pragma argsused

#ifdef _WIN32
#include <tchar.h>
#else
  typedef char _TCHAR;
  #define _tmain main
#endif

#include <stdio.h>
#include <AbDfBase.hpp>
using namespace Abdfbase;

int _tmain(int argc, _TCHAR* argv[])
{
    TAbDeflateHelper* helper = new TAbDeflateHelper();
    return 0;
}
</code>```

This is my first try using c++builder. What system setting or special code am I missing?

For reference the start of the .hpp imported which show the class i try to instantiate.

```<code>/ CodeGear C++Builder
// Copyright (c) 1995, 2021 by Embarcadero Technologies, Inc.
// All rights reserved

// (DO NOT EDIT: machine generated header) 'AbDfBase.pas' rev: 35.00 (Windows)

#ifndef AbdfbaseHPP
#define AbdfbaseHPP

#pragma delphiheader begin
#pragma option push
#pragma option -w-      // All warnings off
#pragma option -Vx      // Zero-length empty class member
#pragma pack(push,8)
#include <System.hpp>
#include <SysInit.hpp>
#include <System.SysUtils.hpp>
#include <System.Classes.hpp>

//-- user supplied -----------------------------------------------------------

namespace Abdfbase
{
//-- forward type declarations -----------------------------------------------
class DELPHICLASS TAbDeflateHelper;
class DELPHICLASS TAbLogger;
class DELPHICLASS TAbNodeManager;
class DELPHICLASS EAbAbortProgress;
class DELPHICLASS EAbPartSizedInflate;
class DELPHICLASS EAbInflatePasswordError;
class DELPHICLASS EAbInternalInflateError;
class DELPHICLASS EAbInflateError;
class DELPHICLASS EAbInternalDeflateError;
class DELPHICLASS EAbDeflateError;
//-- type declarations -------------------------------------------------------
typedef System::StaticArray<int, 536870911> TAbDfIntegerList;

typedef TAbDfIntegerList *PAbDfIntegerList;

typedef void __fastcall (__closure *TAbProgressStep)(int aPercentDone);

class PASCALIMPLEMENTATION TAbDeflateHelper : public System::TObject
{
    typedef System::TObject inherited;

private:
    int FAmpleLength;
    int FChainLength;
    System::UnicodeString FLogFile;
    int FMaxLazy;
    TAbProgressStep FOnProgressStep;
    int FOptions;
    __int64 FPartSize;
    __int64 FSizeCompressed;
    __int64 FSizeNormal;
    __int64 FStreamSize;
    int FWindowSize;
    System::WideChar FZipOption;

protected:
    void __fastcall dhSetAmpleLength(int aValue);
    void __fastcall dhSetChainLength(int aValue);
    void __fastcall dhSetLogFile(const System::UnicodeString aValue);
    void __fastcall dhSetMaxLazy(int aValue);
    void __fastcall dhSetOnProgressStep(TAbProgressStep aValue);
    void __fastcall dhSetOptions(int aValue);
    void __fastcall dhSetWindowSize(int aValue);
    void __fastcall dhSetZipOption(System::WideChar aValue);

public:
    __fastcall TAbDeflateHelper();
    void __fastcall Assign(TAbDeflateHelper* aHelper);
    __property int AmpleLength = {read=FAmpleLength, write=dhSetAmpleLength, nodefault};
    __property int ChainLength = {read=FChainLength, write=dhSetChainLength, nodefault};
    __property System::UnicodeString LogFile = {read=FLogFile, write=dhSetLogFile};
    __property int MaxLazyLength = {read=FMaxLazy, write=dhSetMaxLazy, nodefault};
    __property int Options = {read=FOptions, write=dhSetOptions, nodefault};
    __property __int64 PartialSize = {read=FPartSize, write=FPartSize};
    __property System::WideChar PKZipOption = {read=FZipOption, write=dhSetZipOption, nodefault};
    __property __int64 StreamSize = {read=FStreamSize, write=FStreamSize};
    __property int WindowSize = {read=FWindowSize, write=dhSetWindowSize, nodefault};
    __property __int64 CompressedSize = {read=FSizeCompressed, write=FSizeCompressed};
    __property __int64 NormalSize = {read=FSizeNormal, write=FSizeNormal};
    __property TAbProgressStep OnProgressStep = {read=FOnProgressStep, write=dhSetOnProgressStep};
public:
    /* TObject.Destroy */ inline __fastcall virtual ~TAbDeflateHelper() { }

};
</code>```

答:
Setting up search paths doesn't tell the compiler/linker which specific libraries you are actually using.  Your project is not linking to the Abbrevia package library, hence the error.

Had you created a GUI app instead and visually dropped the Abbrevia component(s) onto a TForm, TFrame, or TDataModule at design-time, the necessary package library reference(s) would have been added for you.

But, in a console app, without at least a TDataModule, you will have to manually add reference(s) to Abbrevia's .bpi package library(s) to the project.

Body:
I am trying to use the abbrevia package ( https://github.com/TurboPack/Abbrevia ) with c++Builder in a console application.
First i tried to manually install the package. But then i found it on GetIt. Issue persists no matter how it setup the package. I think the path settings i did manually are the same as the package installer did.
It results always in unresolved externel for Abdfbase::TAbDeflateHelper::
This is the original error message:

[ilink32 Fehler] Error: Nicht auflösbares externes 'Abdfbase::TAbDeflateHelper::' referenziert von c:\pathtotheobjectfile\main.obj

Just setting up the path and compiling the projects for the c++builder ( therefore getting the objects ) is all the setup aks for. And with GetIt i dont even have to do that.

This is my most simple start which i cant even get to link.

#pragma hdrstop
#pragma argsused

#ifdef _WIN32
#include <tchar.h>
#else
  typedef char _TCHAR;
  #define _tmain main
#endif

#include <stdio.h>
#include <AbDfBase.hpp>
using namespace Abdfbase;

int _tmain(int argc, _TCHAR* argv[])
{
    TAbDeflateHelper* helper = new TAbDeflateHelper();
    return 0;
}

This is my first try using c++builder. What system setting or special code am I missing?

For reference the start of the .hpp imported which show the class i try to instantiate.

/ CodeGear C++Builder
// Copyright (c) 1995, 2021 by Embarcadero Technologies, Inc.
// All rights reserved

// (DO NOT EDIT: machine generated header) 'AbDfBase.pas' rev: 35.00 (Windows)

#ifndef AbdfbaseHPP
#define AbdfbaseHPP

#pragma delphiheader begin
#pragma option push
#pragma option -w-      // All warnings off
#pragma option -Vx      // Zero-length empty class member
#pragma pack(push,8)
#include <System.hpp>
#include <SysInit.hpp>
#include <System.SysUtils.hpp>
#include <System.Classes.hpp>

//-- user supplied -----------------------------------------------------------

namespace Abdfbase
{
//-- forward type declarations -----------------------------------------------
class DELPHICLASS TAbDeflateHelper;
class DELPHICLASS TAbLogger;
class DELPHICLASS TAbNodeManager;
class DELPHICLASS EAbAbortProgress;
class DELPHICLASS EAbPartSizedInflate;
class DELPHICLASS EAbInflatePasswordError;
class DELPHICLASS EAbInternalInflateError;
class DELPHICLASS EAbInflateError;
class DELPHICLASS EAbInternalDeflateError;
class DELPHICLASS EAbDeflateError;
//-- type declarations -------------------------------------------------------
typedef System::StaticArray<int, 536870911> TAbDfIntegerList;

typedef TAbDfIntegerList *PAbDfIntegerList;

typedef void __fastcall (__closure *TAbProgressStep)(int aPercentDone);

class PASCALIMPLEMENTATION TAbDeflateHelper : public System::TObject
{
    typedef System::TObject inherited;

private:
    int FAmpleLength;
    int FChainLength;
    System::UnicodeString FLogFile;
    int FMaxLazy;
    TAbProgressStep FOnProgressStep;
    int FOptions;
    __int64 FPartSize;
    __int64 FSizeCompressed;
    __int64 FSizeNormal;
    __int64 FStreamSize;
    int FWindowSize;
    System::WideChar FZipOption;

protected:
    void __fastcall dhSetAmpleLength(int aValue);
    void __fastcall dhSetChainLength(int aValue);
    void __fastcall dhSetLogFile(const System::UnicodeString aValue);
    void __fastcall dhSetMaxLazy(int aValue);
    void __fastcall dhSetOnProgressStep(TAbProgressStep aValue);
    void __fastcall dhSetOptions(int aValue);
    void __fastcall dhSetWindowSize(int aValue);
    void __fastcall dhSetZipOption(System::WideChar aValue);

public:
    __fastcall TAbDeflateHelper();
    void __fastcall Assign(TAbDeflateHelper* aHelper);
    __property int AmpleLength = {read=FAmpleLength, write=dhSetAmpleLength, nodefault};
    __property int ChainLength = {read=FChainLength, write=dhSetChainLength, nodefault};
    __property System::UnicodeString LogFile = {read=FLogFile, write=dhSetLogFile};
    __property int MaxLazyLength = {read=FMaxLazy, write=dhSetMaxLazy, nodefault};
    __property int Options = {read=FOptions, write=dhSetOptions, nodefault};
    __property __int64 PartialSize = {read=FPartSize, write=FPartSize};
    __property System::WideChar PKZipOption = {read=FZipOption, write=dhSetZipOption, nodefault};
    __property __int64 StreamSize = {read=FStreamSize, write=FStreamSize};
    __property int WindowSize = {read=FWindowSize, write=dhSetWindowSize, nodefault};
    __property __int64 CompressedSize = {read=FSizeCompressed, write=FSizeCompressed};
    __property __int64 NormalSize = {read=FSizeNormal, write=FSizeNormal};
    __property TAbProgressStep OnProgressStep = {read=FOnProgressStep, write=dhSetOnProgressStep};
public:
    /* TObject.Destroy */ inline __fastcall virtual ~TAbDeflateHelper() { }

};


问:
Failed to download metadata for repo 'rhel-8-for-x86_64-baseos-rpms' on RedHat
While creating a local repository and after using yum repolist on RedHat 8.1 I got this result

```<code>Updating Subscription Management repositories.
AppStream                                        57 MB/s | 5.6 MB     00:00
BaseOS                                           98 MB/s | 2.2 MB     00:00
Red Hat Enterprise Linux 8 for x86_64 - BaseOS  0.0  B/s |   0  B     00:00
Failed to download metadata for repo 'rhel-8-for-x86_64-baseos-rpms'
Error: Failed to download metadata for repo 'rhel-8-for-x86_64-baseos-rpms'
</code>```

I'm on VmWare and the machine is on host-only for the purpose of my assignement
I also got the same error while running the dnf install dhcp-server -y
I tried to restart the virtual machine but nothing changes

I have no clues on the not sure what to do

答: I had the same issue yesterday. But i solved it by unsubscribing and then subscribing the RHEL in subscription app.</p>

Body:
While creating a local repository and after using yum repolist on RedHat 8.1 I got this result

Updating Subscription Management repositories.
AppStream                                        57 MB/s | 5.6 MB     00:00
BaseOS                                           98 MB/s | 2.2 MB     00:00
Red Hat Enterprise Linux 8 for x86_64 - BaseOS  0.0  B/s |   0  B     00:00
Failed to download metadata for repo 'rhel-8-for-x86_64-baseos-rpms'
Error: Failed to download metadata for repo 'rhel-8-for-x86_64-baseos-rpms'

I'm on VmWare and the machine is on host-only for the purpose of my assignement
I also got the same error while running the dnf install dhcp-server -y
I tried to restart the virtual machine but nothing changes

I have no clues on the not sure what to do


问:
How to compare pandas data frames and then "fill in" any missing rows with the other data frame
I have the following two arrays: Data and Baseline

```<code>Data
   Phase  ENSO  EJO
0      1    -1    2
1      1     0    2
2      1     1    2
3      2    -1    7
4      2     1    1

Baseline
   Phase  ENSO  EJO
0      1    -1    0.0
1      1     0    0.0
2      1     1    0.0
3      2    -1    0.0
4      2     0    0.0
5      2     1    0.0
</code>```

I want to alter the 'Data' data frame such that the "missing row" gets filled in by the Baseline data. Final result would look like this

```<code>Data
   Phase  ENSO  EJO
0      1    -1    2
1      1     0    2
2      1     1    2
3      2    -1    7
4      2     0    0
5      2     1    1
</code>```

Body:
I have the following two arrays: Data and Baseline

Data
   Phase  ENSO  EJO
0      1    -1    2
1      1     0    2
2      1     1    2
3      2    -1    7
4      2     1    1

Baseline
   Phase  ENSO  EJO
0      1    -1    0.0
1      1     0    0.0
2      1     1    0.0
3      2    -1    0.0
4      2     0    0.0
5      2     1    0.0

I want to alter the 'Data' data frame such that the "missing row" gets filled in by the Baseline data. Final result would look like this

Data
   Phase  ENSO  EJO
0      1    -1    2
1      1     0    2
2      1     1    2
3      2    -1    7
4      2     0    0
5      2     1    1

Body:
Here's an ultra-short solution:

>>> tmp = baseline.copy()
>>> tmp.update(data)
>>> tmp
   Phase  ENSO  EJO
0    1.0  -1.0  2.0
1    1.0   0.0  2.0
2    1.0   1.0  2.0
3    2.0  -1.0  7.0
4    2.0   1.0  1.0
5    2.0   1.0  0.0

Or (Python 3.8+)

>>> (tmp := baseline.copy()).update(data)
>>> tmp
   Phase  ENSO  EJO
0    1.0  -1.0  2.0
1    1.0   0.0  2.0
2    1.0   1.0  2.0
3    2.0  -1.0  7.0
4    2.0   1.0  1.0
5    2.0   1.0  0.0

Simplest:

>>> baseline.update(data)
>>> baseline
   Phase  ENSO  EJO
0    1.0  -1.0  2.0
1    1.0   0.0  2.0
2    1.0   1.0  2.0
3    2.0  -1.0  7.0
4    2.0   1.0  1.0
5    2.0   1.0  0.0


问:
Parse HTML with jquery
suppose in a variable html is saved like

```<code>var vhtm="<div><div id='test'>zebra</div><div id='foo'>here is my many other html content</div></div>";
</code>```

i want to parse the above html stored in variable with the help of jquery.
i need to extract a particular div by id and including its content. the return result would like

```<code><div id='foo'>here is my many other html content</div>
</code>```

so i need to find div by id like id='foo'

please help me how to parse the above like jquery.

答:
Try this</p>

```<code>var divHtml = $(vhtm).find("#foo").html();
</code>```

Title: Parse HTML with jquery

Body:
suppose in a variable html is saved like

var vhtm="

zebra

here is my many other html content

";

i want to parse the above html stored in variable with the help of jquery.
i need to extract a particular div by id and including its content. the return result would like

here is my many other html content

so i need to find div by id like id='foo'

please help me how to parse the above like jquery.

Body:
Try this

var divHtml = $(vhtm).find("#foo").html();


问:
understanding the error response to an http request to rest api
This is a simple request to a REST API using AXIOS:

```<code>  await axios.request({
    url: 'https://gorest.co.in/public/v2/users',
    method: 'POST',
    data: {
      "id":2925,
      "name":"Himani Rana",
      "email":"rana_himani@boehm-okeefe.biz",
      "gender":"female",
      "status":"inactive"})
   .catch(error => {
      console.log(error);
    });
  }
</code>```

This EMAIL is ALREADY taken. So this raises an exception because all users must have unique emails.

This code logs the following error:

```<code>{
"message": "Network Error",
"name": "Error",
"fileName": "https://c.staticblitz.com/d/webcontainer.a330fe2aef0d6950e5edf5ad2e9521381ac64c16.js line 15 > eval",
"lineNumber": 3,
"columnNumber": 8750,
"stack": "e.exports@https://typescript-9ggya9.stackblitz.io/turbo_modules/axios@0.25.0/dist/axios.min.js:3:8750\ne.exports/</g.onerror@https://typescript-9ggya9.stackblitz.io/turbo_modules/axios@0.25.0/dist/axios.min.js:3:7558\n",
"config": {
"transitional": {
"silentJSONParsing": true,
"forcedJSONParsing": true,
"clarifyTimeoutError": false
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1,
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json",
"Authorization": "Token 1a459dd3d2e13a989f01565f5f1ba32350f8216897bb7fee5493feb210a06"
},
"url": "https://gorest.co.in/public/v2/users",
"method": "post",
"data": "{\"id\":2925,\"name\":\"Himani Rana\",\"email\":\"rana_himani@boehm-okeefe.biz\",\"gender\":\"female\",\"status\":\"inactive\"}"
},
"status": null
}
</code>```

This is difficult to read and when I went through it carefully, I did not see something that helps me identify the error apart from a message that says "Network Error".

NOW, doing this http request with POSTMAN or THUNDER CLIENT simply shows:

```<code>[
  {
    "field": "email",
    "message": "has already been taken"
  }
]
</code>```

How do these REST clients identify the error properly but AXIOS doesn't?

答:
From what I can understand, the problem is in axios library.

Try to reinstall axios or use the Fetch API instead (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch).

P.S: Nowadays, Fetch API is more preferred, than axios.

Body:
This is a simple request to a REST API using AXIOS:

  await axios.request({
    url: 'https://gorest.co.in/public/v2/users',
    method: 'POST',
    data: {
      "id":2925,
      "name":"Himani Rana",
      "email":"rana_himani@boehm-okeefe.biz",
      "gender":"female",
      "status":"inactive"})
   .catch(error => {
      console.log(error);
    });
  }

This EMAIL is ALREADY taken. So this raises an exception because all users must have unique emails.

This code logs the following error:

{
"message": "Network Error",
"name": "Error",
"fileName": "https://c.staticblitz.com/d/webcontainer.a330fe2aef0d6950e5edf5ad2e9521381ac64c16.js line 15 > eval",
"lineNumber": 3,
"columnNumber": 8750,
"stack": "e.exports@https://typescript-9ggya9.stackblitz.io/turbo_modules/axios@0.25.0/dist/axios.min.js:3:8750\ne.exports/</g.onerror@https://typescript-9ggya9.stackblitz.io/turbo_modules/axios@0.25.0/dist/axios.min.js:3:7558\n",
"config": {
"transitional": {
"silentJSONParsing": true,
"forcedJSONParsing": true,
"clarifyTimeoutError": false
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1,
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json",
"Authorization": "Token 1a459dd3d2e13a989f01565f5f1ba32350f8216897bb7fee5493feb210a06"
},
"url": "https://gorest.co.in/public/v2/users",
"method": "post",
"data": "{\"id\":2925,\"name\":\"Himani Rana\",\"email\":\"rana_himani@boehm-okeefe.biz\",\"gender\":\"female\",\"status\":\"inactive\"}"
},
"status": null
}

This is difficult to read and when I went through it carefully, I did not see something that helps me identify the error apart from a message that says "Network Error".

NOW, doing this http request with POSTMAN or THUNDER CLIENT simply shows:

[
  {
    "field": "email",
    "message": "has already been taken"
  }
]

How do these REST clients identify the error properly but AXIOS doesn't?


问:
How do you write nested routes after dynamic path in React Router v5.2?
I'm trying to write a route that uses a dynamic path and then add an additional parameter after that. The problem is it's being ignored and not rendering my component. As an example the following code works.

```<code><Route path={`${SPA_PREFIX}/cases/:caseToken`} component={CaseView} />}
<Route path={`${SPA_PREFIX}/notifications`}><NotificationsView /></Route>
</code>```

However, the following doesn't work. This will render the CaseView component in the previous example. This should render the <Sars /> component, but it gets ignored.

Update:

```<code>                    {caseManagement
                      && <Route path={`${SPA_PREFIX}/cases/:caseToken`} exact component={CaseView} />}
                    {caseManagement
                      && <Route path={`${SPA_PREFIX}/cases`}><CasesView /></Route>}
                    <Route path={`${SPA_PREFIX}/notifications`}><NotificationsView /></Route>
                    <Route path={`${SPA_PREFIX}/audit`}><AuditView /></Route>
                    <Route path={`${SPA_PREFIX}/cases/:caseToken/sars`} component={Sars} />
                    <Route path={`${SPA_PREFIX}/settings`}><SettingsView /></Route>
</code>```

What am I doing wrong?

答:
Try adding the exact prop to the Route and wrapping the routes in a switch tag

```<code><Switch>
{caseManagement
                      && <Route path={`${SPA_PREFIX}/cases/:caseToken`} exact component={CaseView} />}
                    {caseManagement
                      && <Route path={`${SPA_PREFIX}/cases`}><CasesView /></Route>}
                    <Route path={`${SPA_PREFIX}/notifications`}><NotificationsView /></Route>
                    <Route path={`${SPA_PREFIX}/audit`}><AuditView /></Route>
                    <Route path={`${SPA_PREFIX}/cases/:caseToken/sars`} component={Sars} />
                    <Route path={`${SPA_PREFIX}/settings`}><SettingsView /></Route>
</Switch>
</code>```

Body:
I'm trying to write a route that uses a dynamic path and then add an additional parameter after that. The problem is it's being ignored and not rendering my component. As an example the following code works.

<Route path={`${SPA_PREFIX}/cases/:caseToken`} component={CaseView} />}
<Route path={`${SPA_PREFIX}/notifications`}><NotificationsView /></Route>

However, the following doesn't work. This will render the CaseView component in the previous example. This should render the <Sars /> component, but it gets ignored.

Update:

                    {caseManagement
                      && <Route path={`${SPA_PREFIX}/cases/:caseToken`} exact component={CaseView} />}
                    {caseManagement
                      && <Route path={`${SPA_PREFIX}/cases`}><CasesView /></Route>}
                    <Route path={`${SPA_PREFIX}/notifications`}><NotificationsView /></Route>
                    <Route path={`${SPA_PREFIX}/audit`}><AuditView /></Route>
                    <Route path={`${SPA_PREFIX}/cases/:caseToken/sars`} component={Sars} />
                    <Route path={`${SPA_PREFIX}/settings`}><SettingsView /></Route>

What am I doing wrong?

Body:
Try adding the exact prop to the Route and wrapping the routes in a switch tag

<Switch>
{caseManagement
                      && <Route path={`${SPA_PREFIX}/cases/:caseToken`} exact component={CaseView} />}
                    {caseManagement
                      && <Route path={`${SPA_PREFIX}/cases`}><CasesView /></Route>}
                    <Route path={`${SPA_PREFIX}/notifications`}><NotificationsView /></Route>
                    <Route path={`${SPA_PREFIX}/audit`}><AuditView /></Route>
                    <Route path={`${SPA_PREFIX}/cases/:caseToken/sars`} component={Sars} />
                    <Route path={`${SPA_PREFIX}/settings`}><SettingsView /></Route>
</Switch>


答:
Try adding the exact prop to the Route

```<code><Route exact path={`${SPA_PREFIX}/cases/:caseToken`} component={CaseView} />}
<Route exact path={`${SPA_PREFIX}/notifications`}><NotificationsView /></Route>
</code>```

Title: How do you write nested routes after dynamic path in React Router v5.2?

Body:
Try adding the exact prop to the Route

<Route exact path={`${SPA_PREFIX}/cases/:caseToken`} component={CaseView} />}
<Route exact path={`${SPA_PREFIX}/notifications`}><NotificationsView /></Route>


问:
On Xamarin in Visual Studio 2022 I keep getting "There were deployment errors continue?" I'm on windows 11 and I'm using an android emulator
The model emulator I'm using is a pixel 5 or android 11.0, I've tried downloading the intelx86 Emulator Accelerator (HAXM installer) and resetting visual studio, but nothing has worked, I even tried to create a new project but that didn't work either.

enter image description here

答:
The problem is that the path to your project is too long or on that path you have accented chars like ã, ç or º or ª and maybe others.
Try creating your project in your Visual Studio 2022 standard/default directory like C:\Users\YourName\source\repos Best Regards!</p>


问:
Adding all string constants from a class to a List of string constants in C#
I have a class,

```<code>        public static class Permissions
        {
            public const string AccessRightFormAdmin = "TEST1";
            public const string AccessRightExperimental = "TEST2";
        }
</code>```

I want to have List<string> myConsts = new List<string>; such that, myConsts contains all the string constants from the Permissions class. How can I achieve this in C#?

答:
If you want to avoid having to manually maintain your myConsts collection, you will have to use reflection.

```<code>public readonly List<string> myConsts =
    typeof(Permissions)
        .GetFields()
        .Select(x => x.GetValue(null).ToString())
        .ToList();
</code>```

This looks at the Permissions type, selects all public fields, then pulls the values from those FieldInfo into a new collection.

Body:
I have a class,

        public static class Permissions
        {
            public const string AccessRightFormAdmin = "TEST1";
            public const string AccessRightExperimental = "TEST2";
        }

I want to have List<string> myConsts = new List<string>; such that, myConsts contains all the string constants from the Permissions class. How can I achieve this in C#?

Body:
If you want to avoid having to manually maintain your myConsts collection, you will have to use reflection.

public readonly List<string> myConsts =
    typeof(Permissions)
        .GetFields()
        .Select(x => x.GetValue(null).ToString())
        .ToList();

This looks at the Permissions type, selects all public fields, then pulls the values from those FieldInfo into a new collection.


问:
Replace a column value for a select set of rows
I have a pandas DataFrame for which I'd like to replace one column value for a small subset of rows. E.g. given:

```<code>in_dict = [{ 'what': 'abc', 'num': 42}, {'what': 'abc', 'num': 43}, {'what': 'def', 'num': 99}]

df = pd.DataFrame.from_records(in_dict)
</code>```

which looks like:

```<code>  what  num
0  abc   42
1  abc   43
2  def   99
</code>```

Using

```<code>lookup = {'abc': 'xyz'}
</code>```

I want to end up with:

```<code>  what  num
0  xyz   42
1  xyz   43
2  def   99
</code>```

I can use map, but then I get NaN's for entries not in the lookup table:

```<code>>>> df['what'] = df['what'].map(lookup)
>>> df
  what  num
0  xyz   42
1  xyz   43
2  NaN   99
</code>```

My actual DataFrame is about 100k items, of which <100 need the update.

What is the most efficient (and ideally pandas-idiomatic) approach here?

答:
You could use fillna on the mapped Series to fill it with the original:

```<code>df['what'] = df['what'].map(lookup).fillna(df['what'])
</code>```

But a better option is to use replace:

```<code>df['what'] = df['what'].replace(lookup)
</code>```

Output:

```<code>  what  num
0  xyz   42
1  xyz   43
2  def   99
</code>```

Body:
I have a pandas DataFrame for which I'd like to replace one column value for a small subset of rows. E.g. given:

in_dict = [{ 'what': 'abc', 'num': 42}, {'what': 'abc', 'num': 43}, {'what': 'def', 'num': 99}]

df = pd.DataFrame.from_records(in_dict)

which looks like:

  what  num
0  abc   42
1  abc   43
2  def   99

Using

lookup = {'abc': 'xyz'}

I want to end up with:

  what  num
0  xyz   42
1  xyz   43
2  def   99

I can use map, but then I get NaN's for entries not in the lookup table:

>>> df['what'] = df['what'].map(lookup)
>>> df
  what  num
0  xyz   42
1  xyz   43
2  NaN   99

My actual DataFrame is about 100k items, of which <100 need the update.

What is the most efficient (and ideally pandas-idiomatic) approach here?

Body:
You could use fillna on the mapped Series to fill it with the original:

df['what'] = df['what'].map(lookup).fillna(df['what'])

But a better option is to use replace:

df['what'] = df['what'].replace(lookup)

Output:

  what  num
0  xyz   42
1  xyz   43
2  def   99


问:
How to define an array of structs return type in ethers.js ABI
Currently I got this abi:

const stakingAbi = [
    'function getStakes(address user) external view returns (Stake[] memory)',
    'function stake7Days(uint128 _amount) external whenNotPaused',
    'function stake14Days(uint128 _amount) external whenNotPaused',
    'function stake30Days(uint128 _amount) external whenNotPaused',
    'function stake90Days(uint128 _amount) external whenNotPaused'
]
```
<p>The <code>Stake</code> struct looks like this:</p>
```struct Stake {
    uint16 bonusPercentage;
    uint40 unlockTimestamp;
    uint128 amount;
    bool withdrawn;
}
```

Currently the getStakes function doesn't work because Ethers doesn't know what Stake[] is, how do I define this in the ABI?

答:
Specifying structs in the human-readable ABI format is still not supported in ethers.js. See https://github.com/ethers-io/ethers.js/issues/315

You would need to use the JSON ABI format: https://docs.ethers.io/v5/api/utils/abi/formats/#abi-formats--solidity

Alternatively, you work around it by returning an array of tuples:

```<code>function getStakes(address user) external view returns (tuple(uint16 bonusPercentage, uint40 unlockTimestamp, uint128 amount, bool withdrawn)[] memory)
</code>```

Or tuple of arrays:

```<code>function getStakes(address user) external view returns (uint16[] memory, uint40[] memory, uint128[] memory, bool[] memory)
</code>```

Body:
Currently I got this abi:

const stakingAbi = [
    'function getStakes(address user) external view returns (Stake[] memory)',
    'function stake7Days(uint128 _amount) external whenNotPaused',
    'function stake14Days(uint128 _amount) external whenNotPaused',
    'function stake30Days(uint128 _amount) external whenNotPaused',
    'function stake90Days(uint128 _amount) external whenNotPaused'
]

The Stake struct looks like this:

struct Stake {
    uint16 bonusPercentage;
    uint40 unlockTimestamp;
    uint128 amount;
    bool withdrawn;
}

Currently the getStakes function doesn't work because Ethers doesn't know what Stake[] is, how do I define this in the ABI?

Body:
Specifying structs in the human-readable ABI format is still not supported in ethers.js. See https://github.com/ethers-io/ethers.js/issues/315

You would need to use the JSON ABI format: https://docs.ethers.io/v5/api/utils/abi/formats/#abi-formats--solidity

Alternatively, you work around it by returning an array of tuples:

function getStakes(address user) external view returns (tuple(uint16 bonusPercentage, uint40 unlockTimestamp, uint128 amount, bool withdrawn)[] memory)

Or tuple of arrays:

function getStakes(address user) external view returns (uint16[] memory, uint40[] memory, uint128[] memory, bool[] memory)


问:
CUDA Convex Hull program crashes on large input
I am trying to implement quickHull algorithm (for convex hull) parallely in CUDA. It works correctly for input_size <= 1 million. When I try 10 million points, the program crashes. My graphic card size is 1982 MB and all my data structures in the algorithm collectively require not more than 600 MB for this input size, which is less than 50 % of the  available space.

By commenting out lines of my kernels, I found out that the crash occurs when I try to access array element and the index of the element I am trying to access is not out of bounds (double checked). The following is the kernel code where it crashes.

```<code>for(unsigned int i = old_setIndex; i < old_setIndex + old_setS[tid]; i++)
{

    int pI = old_set[i];
    if(pI <= -1 || pI > pts.size())
    {
        printf("Thread %d: i = %d, pI = %d\n", tid, i, pI);
        continue;
    }
    p = pts[pI];

    double d = distance(A,B,p);

    if(d > dist) {
        dist = d;
        furthestPoint = i;
        fpi = pI;
    }
}
//fpi = old_set[furthestPoint];
//printf("Thread %d: Furthestpoint = %d\n", tid, furthestPoint);
</code>```

My code crashes when I uncomment the statements (array access and printf) after the for loop. I am unable to explain the error as furthestPoint is always within bounds of old_set array size. Old_setS stores the size of smaller arrays that each thread can operate on. It crashes even if just try to print the value of furthestPoint (last line) without the array access statement above it.

There's no problem with the above code for input size <= 1 million. Am I overflowing some buffer in the device in case of 10 million?

Please help me in finding the source of the crash.

答:
There is no out of bounds memory access in your code (or at least not one which is causing the symptoms you are seeing).

What is happening is that your kernel is being killed by the display driver because it is taking too much time to execute on your display GPU. All CUDA platform display drivers include a time limit for any operation on the GPU. This exists to prevent the display from freezing for a sufficiently long time that either the OS kernel panics or the user panics and thinks the machine has crashed. On the windows platform you are using, the time limit is about 2 seconds.

What has partly mislead you into thinking the source of the problem is array adressing is the commenting out of code makes the problem disappear. But what really happens there is an artifact of compiler optimization. When you comment out a global memory write, the compiler recognizes that the calculations which lead to the value being stored are unused, and it removes all that code from the assembler code it emits (google "nvcc dead code removal" for more information). That has the effect of making the code run much faster and puts it under the display driver time limit.

For workarounds see this recent stackoverflow question and answer

Body:
I am trying to implement quickHull algorithm (for convex hull) parallely in CUDA. It works correctly for input_size <= 1 million. When I try 10 million points, the program crashes. My graphic card size is 1982 MB and all my data structures in the algorithm collectively require not more than 600 MB for this input size, which is less than 50 % of the  available space.

By commenting out lines of my kernels, I found out that the crash occurs when I try to access array element and the index of the element I am trying to access is not out of bounds (double checked). The following is the kernel code where it crashes.

for(unsigned int i = old_setIndex; i < old_setIndex + old_setS[tid]; i++)
{

    int pI = old_set[i];
    if(pI <= -1 || pI > pts.size())
    {
        printf("Thread %d: i = %d, pI = %d\n", tid, i, pI);
        continue;
    }
    p = pts[pI];

    double d = distance(A,B,p);

    if(d > dist) {
        dist = d;
        furthestPoint = i;
        fpi = pI;
    }
}
//fpi = old_set[furthestPoint];
//printf("Thread %d: Furthestpoint = %d\n", tid, furthestPoint);

My code crashes when I uncomment the statements (array access and printf) after the for loop. I am unable to explain the error as furthestPoint is always within bounds of old_set array size. Old_setS stores the size of smaller arrays that each thread can operate on. It crashes even if just try to print the value of furthestPoint (last line) without the array access statement above it.

There's no problem with the above code for input size <= 1 million. Am I overflowing some buffer in the device in case of 10 million?

Please help me in finding the source of the crash.


问:
Function to compare a column with a series Pandas
I'm trying to use a functiom to compare values from a column of a dataframe to a series.

I want to check if a value of that column is inside that series.

```<code>
import pandas as pd
import numpy as np

df = pd.read_excel ('FS.xlsx',sep=";",na_values="Ninguno",encoding='latin1')

a=pd.Series(['7401','7403','7394','4404'],
              name="vals")

a=a.to_frame()

df['Centro']=df['Centro'].apply(str)

def seccion (row):
    if row['Centro'].isin(a['vals'])==True  and row['Almacén']=='EW01':
        return 'Ventas'

df['Sector']=df.apply(seccion,axis=1)

</code>```

I'm receiving as a result 'str' object has no attribute 'isin'

Also I'va tried to use the following:

```<code>    if row.apply(lambda x: (row['Centro'] in a['vals']))==True  and row['Almacén']=='EW01':
        return 'Ventas'
</code>```

And I'm receiving as a result The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

```<code>
df.head().to_dict() :

{'Referencia': {0: '9000126531',
  1: '9000126540',
  2: '9000126784',
  3: '9000126853',
  4: '9000126304'},
 'Material': {0: 3140401570900.0,
  1: 3140401570900.0,
  2: 3140401570900.0,
  3: 3140401570900.0,
  4: 3140401570900.0},
 'Lote': {0: 'F', 1: 'F', 2: 'F', 3: 'F', 4: 'F'},
 'Texto breve de material': {0: 'TECLADO HP USB SMART CARD BLACK',
  1: 'TECLADO HP USB SMART CARD BLACK',
  2: 'TECLADO HP USB SMART CARD BLACK',
  3: 'TECLADO HP USB SMART CARD BLACK',
  4: 'TECLADO HP USB SMART CARD BLACK'},
 'Centro': {0: '7404', 1: '7404', 2: '7404', 3: '7404', 4: '7404'},
 'Almacén': {0: '0001', 1: '0001', 2: '0001', 3: '0001', 4: '0001'},
 'Clase de movimiento': {0: 641, 1: 641, 2: 641, 3: 641, 4: 641},
 'Texto de clase de movimiento': {0: 'TR A stock tránsito',
  1: 'TR A stock tránsito',
  2: 'TR A stock tránsito',
  3: 'TR A stock tránsito',
  4: 'TR A stock tránsito'},
 'Elemento PEP': {0: nan, 1: nan, 2: nan, 3: nan, 4: nan},
 'Documento material': {0: 4903632156,
  1: 4903632157,
  2: 4903632934,
  3: 4903632953,
  4: 4903631823},
 'Posición doc.mat.': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1},
 'Fe.contabilización': {0: Timestamp('2022-01-26 00:00:00'),
  1: Timestamp('2022-01-26 00:00:00'),
  2: Timestamp('2022-01-26 00:00:00'),
  3: Timestamp('2022-01-26 00:00:00'),
  4: Timestamp('2022-01-26 00:00:00')},
 'Ctd.en UM entrada': {0: -1, 1: -1, 2: -1, 3: -1, 4: -1},
 'Un.medida de entrada': {0: 'UN', 1: 'UN', 2: 'UN', 3: 'UN', 4: 'UN'},
 'Doc.Mat. FI': {0: nan, 1: nan, 2: nan, 3: nan, 4: nan},
 'Pedido': {0: 8000094647.0,
  1: 8000094652.0,
  2: 8000094881.0,
  3: 8000094927.0,
  4: 8000094420.0},
 'Posición': {0: 10, 1: 10, 2: 10, 3: 10, 4: 10},
 'Nombre del usuario': {0: '933514',
  1: '933514',
  2: '933514',
  3: '933514',
  4: '933514'},
 'UM precio pedido': {0: nan, 1: nan, 2: nan, 3: nan, 4: nan},
 'Importe ML': {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0},
 'Sector': {0: 'FS', 1: 'FS', 2: 'FS', 3: 'FS', 4: 'FS'}}

</code>```

Thank you!

答:
```<code>import pandas as pd

df = pd.read_excel ('FS.xlsx',sep=";",na_values="Ninguno",encoding='latin1')

a=pd.Series(['7401','7403','7394','4404'], name="vals")

df['Sector'] = (df['Centro'].astype(str).isin(a) & (df['Almacén']=='EW01')).map({True: 'Ventas'})
</code>```

The last line performs the two checks and assign a value between True / False to each row depending on the result of the checks. We can then use map to replace True with 'Ventas' and the rest with np.nan.

Body:
I'm trying to use a functiom to compare values from a column of a dataframe to a series.

I want to check if a value of that column is inside that series.

import pandas as pd
import numpy as np

df = pd.read_excel ('FS.xlsx',sep=";",na_values="Ninguno",encoding='latin1')

a=pd.Series(['7401','7403','7394','4404'],
              name="vals")

a=a.to_frame()

df['Centro']=df['Centro'].apply(str)

def seccion (row):
    if row['Centro'].isin(a['vals'])==True  and row['Almacén']=='EW01':
        return 'Ventas'

df['Sector']=df.apply(seccion,axis=1)

I'm receiving as a result 'str' object has no attribute 'isin'

Also I'va tried to use the following:

    if row.apply(lambda x: (row['Centro'] in a['vals']))==True  and row['Almacén']=='EW01':
        return 'Ventas'

And I'm receiving as a result The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

df.head().to_dict() :

{'Referencia': {0: '9000126531',
  1: '9000126540',
  2: '9000126784',
  3: '9000126853',
  4: '9000126304'},
 'Material': {0: 3140401570900.0,
  1: 3140401570900.0,
  2: 3140401570900.0,
  3: 3140401570900.0,
  4: 3140401570900.0},
 'Lote': {0: 'F', 1: 'F', 2: 'F', 3: 'F', 4: 'F'},
 'Texto breve de material': {0: 'TECLADO HP USB SMART CARD BLACK',
  1: 'TECLADO HP USB SMART CARD BLACK',
  2: 'TECLADO HP USB SMART CARD BLACK',
  3: 'TECLADO HP USB SMART CARD BLACK',
  4: 'TECLADO HP USB SMART CARD BLACK'},
 'Centro': {0: '7404', 1: '7404', 2: '7404', 3: '7404', 4: '7404'},
 'Almacén': {0: '0001', 1: '0001', 2: '0001', 3: '0001', 4: '0001'},
 'Clase de movimiento': {0: 641, 1: 641, 2: 641, 3: 641, 4: 641},
 'Texto de clase de movimiento': {0: 'TR A stock tránsito',
  1: 'TR A stock tránsito',
  2: 'TR A stock tránsito',
  3: 'TR A stock tránsito',
  4: 'TR A stock tránsito'},
 'Elemento PEP': {0: nan, 1: nan, 2: nan, 3: nan, 4: nan},
 'Documento material': {0: 4903632156,
  1: 4903632157,
  2: 4903632934,
  3: 4903632953,
  4: 4903631823},
 'Posición doc.mat.': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1},
 'Fe.contabilización': {0: Timestamp('2022-01-26 00:00:00'),
  1: Timestamp('2022-01-26 00:00:00'),
  2: Timestamp('2022-01-26 00:00:00'),
  3: Timestamp('2022-01-26 00:00:00'),
  4: Timestamp('2022-01-26 00:00:00')},
 'Ctd.en UM entrada': {0: -1, 1: -1, 2: -1, 3: -1, 4: -1},
 'Un.medida de entrada': {0: 'UN', 1: 'UN', 2: 'UN', 3: 'UN', 4: 'UN'},
 'Doc.Mat. FI': {0: nan, 1: nan, 2: nan, 3: nan, 4: nan},
 'Pedido': {0: 8000094647.0,
  1: 8000094652.0,
  2: 8000094881.0,
  3: 8000094927.0,
  4: 8000094420.0},
 'Posición': {0: 10, 1: 10, 2: 10, 3: 10, 4: 10},
 'Nombre del usuario': {0: '933514',
  1: '933514',
  2: '933514',
  3: '933514',
  4: '933514'},
 'UM precio pedido': {0: nan, 1: nan, 2: nan, 3: nan, 4: nan},
 'Importe ML': {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0},
 'Sector': {0: 'FS', 1: 'FS', 2: 'FS', 3: 'FS', 4: 'FS'}}

Thank you!

Body:
import pandas as pd

df = pd.read_excel ('FS.xlsx',sep=";",na_values="Ninguno",encoding='latin1')

a=pd.Series(['7401','7403','7394','4404'], name="vals")

df['Sector'] = (df['Centro'].astype(str).isin(a) & (df['Almacén']=='EW01')).map({True: 'Ventas'})

The last line performs the two checks and assign a value between True / False to each row depending on the result of the checks. We can then use map to replace True with 'Ventas' and the rest with np.nan.


问:
Are there ways to perform membership tests in pact? (performing membership test for pact tables)
Hello to the kadena pact developer community

I was looking at some basic code examples and as I wanted to play around with the functionality to develop a better grasp for it, I got curios about the following:

We see that some capabilities as defined in example code test for values within a row inside a table.
Is there a way one could simply test for a key and fail the predicate if the key is not present in the table?

Thank you for your insight.

答:
While this may not be the most efficient way, I have found a solution to the question.

The pact syntax for testing membership is with the function call to 'contains'

Now we want to know whether a key exists within our table. In order to do this we can use the built-in function 'keys'

This will return a list of strings (i.e. our keys) and will let us query via the use of 'contains' whether the key in question exists as a key in our table, or: is X a member in our table.

Since this requires us to get a complete list of keys just to see whether the particular key is within our table, this is where my concern regarding performance comes in.
I wanted to share this with everyone, regardless, but in certain circumstances it may be better to just let the transaction fail instead of enforcing membership explicitly like this.

Edit: I used some code previously to show how to achieve this, but it was faulty code.
If you need a membership test, you can do it within the context of an if statement, but not with (enforce  ) as enforce will only allow "pure" expressions (i.e. expressions that can be evaluated on the spot and do not involve database lookups like the 'keys' function).

Enforcing a test outcome that requires database transaction will return an error like

Error from (api.testnet.chainweb.com): : Failure: Database exception:
: Failure: Illegal database access attempt (keys)


问:
Class 'Pusher' not found
When I install Pusher package, I got an error "Class 'Pusher' not found".</p>

答:
Use this command and install pusher. It worked for me in Laravel and PHP 8.0.8 perfectly without any additions of code changes.</p>
```<code>composer require pusher/pusher-php-server
</code>```

Title: Class 'Pusher' not found

Body:
Use this command and install pusher. It worked for me in Laravel and PHP 8.0.8 perfectly without any additions of code changes.

composer require pusher/pusher-php-server


问:
"Module has no entry points defined", except it does (migrating the gwt-maven-plugin)
[INFO]    [ERROR] Module has no entry points defined

I am migrating from org.codehaus.mojo:gwt-maven-plugin to net.ltgt.gwt.maven:gwt-maven-plugin, and I can't seem to convince the compiler that my module DOES have an entry point defined.

The old plugin could only work with older Java, which I don't have anymore... So I moved on to the newer incarnation of the GWT Maven plugin... Unfortunately this plugin uses parameters that GWT 2.0.2 compiler does not recognize (like -deploy or -sourceLevel)... Which forced me to change ${gwt.version} to 2.8.2. That's rather massive jump, but I don't see how that could invalidate something as simple as implementing the EntryPoint interface.

TheApp/Web/src/main/module.xml:

```<code>    <entry-point class='net.theapp.client.TheEntryPoint' />
...
    <source path='net/theapp/client'/>
    <source path='net/theapp/data'/>
</code>```

Location of the entry-point class:

```<code>TheApp/Web/src/main/java/net/theapp/client/
  - TheEntryPoint.java
</code>```

The class:

```<code>...
public class TheEntryPoint
    implements EntryPoint
{
...
</code>```

答: You have named your module file module.mxl.  The correct name is module.gwt.xml

Body:
[INFO]    [ERROR] Module has no entry points defined

I am migrating from org.codehaus.mojo:gwt-maven-plugin to net.ltgt.gwt.maven:gwt-maven-plugin, and I can't seem to convince the compiler that my module DOES have an entry point defined.

The old plugin could only work with older Java, which I don't have anymore... So I moved on to the newer incarnation of the GWT Maven plugin... Unfortunately this plugin uses parameters that GWT 2.0.2 compiler does not recognize (like -deploy or -sourceLevel)... Which forced me to change ${gwt.version} to 2.8.2. That's rather massive jump, but I don't see how that could invalidate something as simple as implementing the EntryPoint interface.

TheApp/Web/src/main/module.xml:

    <entry-point class='net.theapp.client.TheEntryPoint' />
...
    <source path='net/theapp/client'/>
    <source path='net/theapp/data'/>

Location of the entry-point class:

TheApp/Web/src/main/java/net/theapp/client/
  - TheEntryPoint.java

The class:

...
public class TheEntryPoint
    implements EntryPoint
{
...


问:
Groupby year and month for a column without having indexes in the output
I have a dataset with dates and avarage tempratures
I want to groupby year and month on AVG_TEMP column.

data:

```<code>           DATE      AVG_TEMP
912     1957-07-01     22.2
913     1957-07-02     26.1
914     1957-07-03     25.6
            .
            .
            .

23249   2020-12-30     16.7
23250   2020-12-31     15.6
</code>```

When I do

```<code>pd.DataFrame(data.groupby([data['DATE'].dt.year, data['DATE'].dt.month])['AVG_TEMP'])
</code>```

The output contain the index among with the AVG_TEMP.

```<code>           0                          1

0      (1957, 7)         912 22.2 913 26.1 914 25.6 915 26....
1      (1957, 8)         943 28.3 944 28.9 945 28.9 946 27....
                    .
                    .
                    .
698   (2020, 11)         23190 17.2 23191 16.7 23192 17.8 2319...
699   (2020, 12)         23220 12.2 23221 13.3 23222 13.9 2322...
</code>```

As you can see exept from the AVG_TEMP it returns the index of the row as well.(below I cold the indexes to make it clear).

912 22.2 913 26.1 914 25.6 915 26....

943 28.3 944 28.9 945 28.9 946 27....

23190 17.2 23191 16.7 23192 17.8 2319...

I used as_index=False but the output is worse.

```<code>pd.DataFrame(new_data.groupby([new_data.DATE.dt.year, new_data.DATE.dt.month], as_index=False))
</code>```

The outeput:

```<code>           0                              1

0      (1957, 7)        DATE TAVG 912 22.2 913 26.1 914 25.6 915 26....
1      (1957, 8)        DATE TAVG 943 1957-08-01 28.3 944 ...
                   .
                   .
                   .
</code>```

I try to explain it as much as I can because I can't make my code more reproducible.
What can I do to solve this problem?

答:
You can simply pass list when calling aggregate() on the DataFrameGroupBy object.

Here is an toy example:

```<code>import pandas as pd

import numpy as np  # just to create some random values

df = pd.DataFrame(
    {
        "A": ["one", "one", "two", "three", "two", "two", "one", "three"],
        "B": np.random.randn(8),
    }
)

df.groupby("A").agg(list)

#                                                       B
# A
# one    [-0.38149367708676907, -0.5909611421048793, 2....
# three            [2.596225710326822, 0.4576674264970426]
# two    [-0.2581723789437292, 0.8189484792083834, -0.6...

</code>```

In your case this would probably then look like this:

```<code>data.groupby([data['DATE'].dt.year, data['DATE'].dt.month]).agg(list)['AVG_TEMP']
</code>```

Body:
I have a dataset with dates and avarage tempratures
I want to groupby year and month on AVG_TEMP column.

data:

           DATE      AVG_TEMP
912     1957-07-01     22.2
913     1957-07-02     26.1
914     1957-07-03     25.6
            .
            .
            .

23249   2020-12-30     16.7
23250   2020-12-31     15.6

When I do

pd.DataFrame(data.groupby([data['DATE'].dt.year, data['DATE'].dt.month])['AVG_TEMP'])

The output contain the index among with the AVG_TEMP.

           0                          1

0      (1957, 7)         912 22.2 913 26.1 914 25.6 915 26....
1      (1957, 8)         943 28.3 944 28.9 945 28.9 946 27....
                    .
                    .
                    .
698   (2020, 11)         23190 17.2 23191 16.7 23192 17.8 2319...
699   (2020, 12)         23220 12.2 23221 13.3 23222 13.9 2322...

As you can see exept from the AVG_TEMP it returns the index of the row as well.(below I cold the indexes to make it clear).

912 22.2 913 26.1 914 25.6 915 26....

943 28.3 944 28.9 945 28.9 946 27....

23190 17.2 23191 16.7 23192 17.8 2319...

I used as_index=False but the output is worse.

pd.DataFrame(new_data.groupby([new_data.DATE.dt.year, new_data.DATE.dt.month], as_index=False))

The outeput:

           0                              1

0      (1957, 7)        DATE TAVG 912 22.2 913 26.1 914 25.6 915 26....
1      (1957, 8)        DATE TAVG 943 1957-08-01 28.3 944 ...
                   .
                   .
                   .

I try to explain it as much as I can because I can't make my code more reproducible.
What can I do to solve this problem?

Body:
You can simply pass list when calling aggregate() on the DataFrameGroupBy object.

Here is an toy example:

import pandas as pd

import numpy as np  # just to create some random values

df = pd.DataFrame(
    {
        "A": ["one", "one", "two", "three", "two", "two", "one", "three"],
        "B": np.random.randn(8),
    }
)

df.groupby("A").agg(list)

#                                                       B
# A
# one    [-0.38149367708676907, -0.5909611421048793, 2....
# three            [2.596225710326822, 0.4576674264970426]
# two    [-0.2581723789437292, 0.8189484792083834, -0.6...

In your case this would probably then look like this:

data.groupby([data['DATE'].dt.year, data['DATE'].dt.month]).agg(list)['AVG_TEMP']


问:
Query to sum calls
I have table contain call durations of a telecom company.

ex:
Table 1

```<code>| callerid | receiverid  | call duration
| 1        | 2           | 5
| 1        | 2           | 2
| 2        | 3           | 4
| 1        | 5           | 2
</code>```

i need to query above table so the result table after query:

Table 2

```<code>| callerid | receiverid  | call duration
| 1        | 2           | 7
| 2        | 3           | 4
| 1        | 5           | 2
</code>```

答:
use below

```<code>select callerid, receiverid, sum(call_duration) call_duration
from your_table
group by callerid, receiverid
</code>```

if applied to sample data in your question - output is

Title: Query to sum calls

Body:
I have table contain call durations of a telecom company.

ex:
Table 1

| callerid | receiverid  | call duration
| 1        | 2           | 5
| 1        | 2           | 2
| 2        | 3           | 4
| 1        | 5           | 2

i need to query above table so the result table after query:

Table 2

| callerid | receiverid  | call duration
| 1        | 2           | 7
| 2        | 3           | 4
| 1        | 5           | 2

Body:
use below

select callerid, receiverid, sum(call_duration) call_duration
from your_table
group by callerid, receiverid

if applied to sample data in your question - output is


问:
Improve performance on updating stock for 4000 variants in SHOPIFY
I've made an app for shopify REST-API coded in python to update stock for 4000 variants from 750 different products that I get from a local machine mySQL database.

I have an intermidiate table where I get all the product information then I sync their variants, stock and price. As far as I've read, you can only update shopify variant's stock (inventory available) one by one. Info here

@Abhishek told me to use Threading. Could anyone give me some guides how to use this?

This is my previous explanation of my problem:

Everything runs smothly except when it runs the "for each" cicle to POST the available stock from "myList" (previously appended).
requests.post(send_url, myList[index])
It lasts about 65minutes.
Is there any way to bulk it, in one operation or optimize it to a faster way?

Thanks.

答:
Shopify has Bulk Inventory Updates. Just as quick pointer. You can update 100 SKUs with one API call. So 4000 variants is only 40 calls. That is not going to be a problem. I update 40,000 SKUs without writing any exotic code.

If you do a bulk update, it is even easier. You upload a single JSON file with your updates, and Shopify does all the work.

You have plenty of options and none of them involve Multi-threading API Requests.


问:
Kotlin Polymorphism Confusion
I was following a tutorial for learning kotlin and ran into this example.

```<code>open class AquariumPlant(val color: String, private val size: Int)

class GreenLeafyPlant(size: Int) : AquariumPlant("green", size)

fun AquariumPlant.print() = println("AquariumPlant")
fun GreenLeafyPlant.print() = println("GreenLeafyPlant")

val plant = GreenLeafyPlant(size = 10)
plant.print()
println("\n")
val aquariumPlant: AquariumPlant = plant
aquariumPlant.print()  // what will it print?
</code>```

Well this apparently prints "Aquarium Plant" instead of "GreenLeafyPlant". I was a bit confused by this so I tested this out with this little snippet of code.

```<code>open class Aquarium {
    open fun printSize() {
        println("hello")
    }
}

class TowerTank: Aquarium() {
    override fun printSize() {
        println("rawr")
    }
}

fun main() {
    towerTank = TowerTank()
    (towerTank as Aquarium).printSize()
}
</code>```

So this prints "rawr" and not "hello". My question is why doesn't it print "hello"? Aren't these two examples contradicting themselves? How does the function extensions create this difference in behaviour? Sorry if this may seem like a dumb question, I'm new to Kotlin as you can probably tell.

答:
To understand this we need to understand how extensions work. Extensions don't magically add new members to existing classes. This is technically impossible both in Java and Kotlin. Instead, they work as good old static utility functions in Java. Accessing them as members is just a syntactic sugar.

First example is really similar to these functions:

fun print(plant: AquariumPlant) = println("AquariumPlant")
fun print(plant: GreenLeafyPlant) = println("GreenLeafyPlant")
```
<p>To make it even more clear, we can rename these functions:</p>
<pre class="lang-kotlin prettyprint-override"><code>fun printAquariumPlant(plant: AquariumPlant) = println("AquariumPlant")
fun printGreenLeafyPlant(plant: GreenLeafyPlant) = println("GreenLeafyPlant")
</code>```

Now, it is pretty clear that if we have object like this:

val aquariumPlant: AquariumPlant = GreenLeafyPlant(size = 10)
```

Then we can only invoke printAquariumPlant() function with it and it will print AquariumPlant, not GreenLeafyPlant. Despite the fact aquariumPlant is actually a GreenLeafyPlant object.

If we move one step back and rename them again to just print, nothing will really change. aquariumPlant variable is of type AquariumPlant (even if it contains GreenLeafyPlant object), so the compiler chooses print(AquariumPlant) function.

This is why we say extensions are resolved statically. Compiler decides which function to call at compile time. Virtual functions are resolved at runtime, taking into consideration the real type of the object.

Title: Kotlin Polymorphism Confusion

Body:
I was following a tutorial for learning kotlin and ran into this example.

open class AquariumPlant(val color: String, private val size: Int)

class GreenLeafyPlant(size: Int) : AquariumPlant("green", size)

fun AquariumPlant.print() = println("AquariumPlant")
fun GreenLeafyPlant.print() = println("GreenLeafyPlant")

val plant = GreenLeafyPlant(size = 10)
plant.print()
println("\n")
val aquariumPlant: AquariumPlant = plant
aquariumPlant.print()  // what will it print?

Well this apparently prints "Aquarium Plant" instead of "GreenLeafyPlant". I was a bit confused by this so I tested this out with this little snippet of code.

open class Aquarium {
    open fun printSize() {
        println("hello")
    }
}

class TowerTank: Aquarium() {
    override fun printSize() {
        println("rawr")
    }
}

fun main() {
    towerTank = TowerTank()
    (towerTank as Aquarium).printSize()
}

So this prints "rawr" and not "hello". My question is why doesn't it print "hello"? Aren't these two examples contradicting themselves? How does the function extensions create this difference in behaviour? Sorry if this may seem like a dumb question, I'm new to Kotlin as you can probably tell.

Body:
To understand this we need to understand how extensions work. Extensions don't magically add new members to existing classes. This is technically impossible both in Java and Kotlin. Instead, they work as good old static utility functions in Java. Accessing them as members is just a syntactic sugar.

First example is really similar to these functions:

fun print(plant: AquariumPlant) = println("AquariumPlant")
fun print(plant: GreenLeafyPlant) = println("GreenLeafyPlant")

To make it even more clear, we can rename these functions:

fun printAquariumPlant(plant: AquariumPlant) = println("AquariumPlant")
fun printGreenLeafyPlant(plant: GreenLeafyPlant) = println("GreenLeafyPlant")

Now, it is pretty clear that if we have object like this:

val aquariumPlant: AquariumPlant = GreenLeafyPlant(size = 10)

Then we can only invoke printAquariumPlant() function with it and it will print AquariumPlant, not GreenLeafyPlant. Despite the fact aquariumPlant is actually a GreenLeafyPlant object.

If we move one step back and rename them again to just print, nothing will really change. aquariumPlant variable is of type AquariumPlant (even if it contains GreenLeafyPlant object), so the compiler chooses print(AquariumPlant) function.

This is why we say extensions are resolved statically. Compiler decides which function to call at compile time. Virtual functions are resolved at runtime, taking into consideration the real type of the object.