问:
Mismatch in integer calculation results between C++ and Python (random number generator)
I needed a pseudo random number generation scheme (independent of standard libraries) for one of my projects and I tried a simple LCG based RNG. It seems to work fine except that it produces different values in C++ and Python. I am giving the relevant code for both below. I am not able to find the error. Any help will be greatly appreciated!

(c++)

```<code>// file: lgc.cc
// compile and run with: g++ lgc.cc -o lgc && ./lgc

#include <cstdio>
#include <cstdint>
#include <vector>

using namespace std;

uint64_t LGC(uint64_t x) {
  uint64_t A = 1103515245;
  uint64_t C = 12345;
  uint64_t M = (1 << 31);
  return (A * x + C) % M;
}

int main(int argc, char* argv[]) {

  for (auto x : {485288831, 485288832, 10, 16, 255, 756}) {
    uint64_t y = LGC(x);
    printf("%u %u\n", (uint32_t)x, (uint32_t) y);
  }

  return 0;
}
</code>```

(python)

```<code># file: lgc.py
# run with: python3 lgc.py

def LGC(x):
    A = 1103515245;
    C = 12345;
    M = int(2 ** 31);
    return (A * x + C) % M;

for x in [485288831, 485288832, 10, 16, 255, 756]:
    y = LGC(x)
    print(x, y)
</code>```

(Results: c++)

```<code>485288831 3822790476
485288832 631338425
10 2445230203
16 476387081
255 2223525580
756 1033882141
</code>```

(Results: python)

```<code>485288831 1675306828
485288832 631338425
10 297746555
16 476387081
255 76041932
756 1033882141
</code>```

答:
The problem is with the shift in: uint64_t M = (1 << 31); the (1<<31) is a negative number -2147483648 for 32 bit integers because this is signed integer math. To fix you can use uint64_t M = (1U << 31); to make the shift use unsigned 32 bit integers. You could also use uint64_t M = (1UL << 31); to have the calculation use 64 bit unsigned integers

The following link shows printing the output of: (1 << 31), (1U << 31) and (1UL << 31) on a system with 32 bit int:
https://ideone.com/vU0eyX

Body:
I needed a pseudo random number generation scheme (independent of standard libraries) for one of my projects and I tried a simple LCG based RNG. It seems to work fine except that it produces different values in C++ and Python. I am giving the relevant code for both below. I am not able to find the error. Any help will be greatly appreciated!

(c++)

// file: lgc.cc
// compile and run with: g++ lgc.cc -o lgc && ./lgc

#include <cstdio>
#include <cstdint>
#include <vector>

using namespace std;

uint64_t LGC(uint64_t x) {
  uint64_t A = 1103515245;
  uint64_t C = 12345;
  uint64_t M = (1 << 31);
  return (A * x + C) % M;
}

int main(int argc, char* argv[]) {

  for (auto x : {485288831, 485288832, 10, 16, 255, 756}) {
    uint64_t y = LGC(x);
    printf("%u %u\n", (uint32_t)x, (uint32_t) y);
  }

  return 0;
}

(python)

# file: lgc.py
# run with: python3 lgc.py

def LGC(x):
    A = 1103515245;
    C = 12345;
    M = int(2 ** 31);
    return (A * x + C) % M;

for x in [485288831, 485288832, 10, 16, 255, 756]:
    y = LGC(x)
    print(x, y)

(Results: c++)

485288831 3822790476
485288832 631338425
10 2445230203
16 476387081
255 2223525580
756 1033882141

(Results: python)

485288831 1675306828
485288832 631338425
10 297746555
16 476387081
255 76041932
756 1033882141


来源: stackexchange

问:
data frame to file.txt python
I have this dataframe

```<code>       X    Y  Z    Value
0      18   55  1      70
1      18   55  2      67
2      18   57  2      75
3      18   58  1      35
4      19   54  2      70
</code>```

I want to save it as a text file with this format

```<code>   X    Y  Z    Value
   18   55  1      70
   18   55  2      67
   18   57  2      75
   18   58  1      35
   19   54  2      70
</code>```

I tried this code but is not working:

```<code>np.savetxt('xgboost.txt', a.values, delimiter ='\t')

TypeError: Mismatch between array dtype ('object') and format specifier ('%.18e %.18e %.18e')
</code>```

答:
Just in case still getting error try this.</p>
```<code>np.savetxt("test_file.txt", dataframe.to_numpy(), fmt = "%d")
</code>```

ContentLicense: CC BY-SA 3.0

Title: data frame to file.txt python

Body:
I have this dataframe

       X    Y  Z    Value
0      18   55  1      70
1      18   55  2      67
2      18   57  2      75
3      18   58  1      35
4      19   54  2      70

I want to save it as a text file with this format

   X    Y  Z    Value
   18   55  1      70
   18   55  2      67
   18   57  2      75
   18   58  1      35
   19   54  2      70

I tried this code but is not working:

np.savetxt('xgboost.txt', a.values, delimiter ='\t')

TypeError: Mismatch between array dtype ('object') and format specifier ('%.18e %.18e %.18e')

Body:
Just in case still getting error try this.

np.savetxt("test_file.txt", dataframe.to_numpy(), fmt = "%d")

ContentLicense: CC BY-SA 4.0


问:
Is it possible in Hazelcast (client-server model) to indicate the service to build the cache?
I have 2 microservices in spring boot (let's say microservice A and B) and client-server Hazelcast. There is some cache-building logic in microservice A and I want to use the same cache in microservice B. I know we can get the Map and use it. But what if there is a cache miss? is there any way to indicate the microservice A to build the cache and then return it to microservice B? If it's not possible, can we do something after we ship the cache-building logic to cache server? I don't want to have the same cache-building logic in multiple services.</p>

答:
One option here might be a MapLoader

When a map is first accessed (and so empty) map loader logic can be attached to populate it.

You can choose to load all content at once, per key on a cache miss, or a combination of the two.


问:
compare two properties of type Any
I'm trying to compare the properties of two instances of a class. I used this before and it's working fine:

```<code>override public func isEqual(_ object: Any?) -> Bool {
    if let rhs = object as? BankDataModel, self.accountHolderName == rhs.accountHolderName, self.accountNumber == rhs.accountNumber,
        self.accountHolderThirdPartyAccountOwner == rhs.accountHolderThirdPartyAccountOwner, self.bankName == rhs.bankName, self.bankRoutingNumber == rhs.bankRoutingNumber, self.bic == rhs.bic, self.iban == rhs.iban, self.directDebitStatus == rhs.directDebitStatus, self.sepaCreditorID == rhs.sepaCreditorID, self.sepaMandateID == rhs.sepaMandateID{
        return true
    }else{
        return false
    }
}
</code>```

However I have to write this for all of my model classes again if I want to use this. I want to have a function which I can use for all my model classes, so I have used the Mirror struct and tried something like this:

```<code> override public func isEqual(_ object: Any?) -> Bool {
    if let rhs = object as? BankDataModel{
        return compareTwoObjects(objectToCompare: rhs, objectSelf: self)
    }else{
        return false
    }
}
</code>```

The overridden isEqual method in each model will call this method from a Helper class, so I can use this in every Model that I have:

```<code>func compareTwoObjects(objectToCompare: Any, objectSelf: Any) -> Bool{
    let objectSelf2 = Mirror(reflecting: objectSelf)
    let objectToCompare2 = Mirror(reflecting: objectToCompare)
    var index = objectToCompare2.children.startIndex
    for attr in objectSelf2.children{
        let type1 = Mirror(reflecting: attr.value).subjectType
        print(type1)
        let type2 = Mirror(reflecting: objectToCompare2.children[index].value).subjectType
        print(type2)
        if type1 == type2{
            print("Equal")
            if attr.value as! type1 != objectToCompare2.children[index].value as! type2{
                return false
            }
        }
        index = objectToCompare2.children.index(index, offsetBy: 1)
    }
    return true
}
</code>```

The most of the code is working fine, the print("Equal") is always executed when the types of the two variables are equal.
The problem is this line:

```<code>if attr.value as! type1 != objectToCompare.children[index].value as! type2{
      return false
 }
</code>```

I get this error message: "Use of undeclared type "type1"".
If I don't use the casting to type1 and type2, I get the error that I cannot use == with two properties of type "Any".
Is there a way to convert the type1 and type2 Strings to real datatypes? Or is there maybe a better way for what I'm trying to achieve?

This is my output from the prints:

Optional<String>
Optional<String>
Equal
Optional<String>
Optional<String>
Equal
Optional<Bool>
Optional<Bool>
Equal
String
String
Equal
Optional<String>
Optional<String>
Equal
String
String
Equal
String
String
Equal
Optional<DirectDebitStatus>
Optional<DirectDebitStatus>
Equal

I would appreciate any help!

答:
I had a similar problem. Needed to compare several (huge) model objects that I got from different sources. Starting with your code and expanding with recursion and special cases I ended up with the following code snippet.

(Please note that I use this in a Test class, so there's no need to be efficient.)

```<code>func compareProperties(of target1: Any, with target2: Any) -> Bool {

    let mirror1 = Mirror(reflecting: target1)
    let mirror2 = Mirror(reflecting: target2)
    var index = mirror1.children.startIndex

    for child in mirror1.children {
        let child2 = mirror2.children[index]

        //Make another mirror to see if it has children
        let innerMirror1 = Mirror(reflecting: child.value)

        if (innerMirror1.children.count > 0) {
            // Use recursive reflection on the value of each child.
            print("Recursion on \(innerMirror1.subjectType)")
            if (!compareProperties(of: child.value, with: child2.value)) {
                return false
            }
        } else {
            //Compare the values
            let type1 = innerMirror1.subjectType
            let innerMirror2 = Mirror(reflecting: child2.value)
            let type2 = innerMirror2.subjectType
            if type1 == type2 {

                let stringValue1 = "\(child.value)"
                let stringValue2 = "\(child2.value)"

                //print("\(type1): \(stringValue1) ==? \(type2): \(stringValue2)")

                if (stringValue1 != stringValue2) {
                    print("\(type1): \(stringValue1) != \(type2): \(stringValue2)")
                    //Special case with Dates
                    if ("\(mirror1.subjectType)" == "Date") {
                        //Skip comparison of Doubles in Dates
                        if ("\(target1 as? Date)" != "\(target2 as? Date)") {
                            return false
                        }
                    } else {
                        return false
                    }
                }

            } else {
                print("Different classes \(type1) and \(type2)")
                return false
            }
        }
        //Increase index for next value pair
        index = mirror1.children.index(index, offsetBy: 1)
    }
    //If we get here it was never false.
    return true
}
</code>```

Title: compare two properties of type Any

Body:
I'm trying to compare the properties of two instances of a class. I used this before and it's working fine:

override public func isEqual(_ object: Any?) -> Bool {
    if let rhs = object as? BankDataModel, self.accountHolderName == rhs.accountHolderName, self.accountNumber == rhs.accountNumber,
        self.accountHolderThirdPartyAccountOwner == rhs.accountHolderThirdPartyAccountOwner, self.bankName == rhs.bankName, self.bankRoutingNumber == rhs.bankRoutingNumber, self.bic == rhs.bic, self.iban == rhs.iban, self.directDebitStatus == rhs.directDebitStatus, self.sepaCreditorID == rhs.sepaCreditorID, self.sepaMandateID == rhs.sepaMandateID{
        return true
    }else{
        return false
    }
}

However I have to write this for all of my model classes again if I want to use this. I want to have a function which I can use for all my model classes, so I have used the Mirror struct and tried something like this:

 override public func isEqual(_ object: Any?) -> Bool {
    if let rhs = object as? BankDataModel{
        return compareTwoObjects(objectToCompare: rhs, objectSelf: self)
    }else{
        return false
    }
}

The overridden isEqual method in each model will call this method from a Helper class, so I can use this in every Model that I have:

func compareTwoObjects(objectToCompare: Any, objectSelf: Any) -> Bool{
    let objectSelf2 = Mirror(reflecting: objectSelf)
    let objectToCompare2 = Mirror(reflecting: objectToCompare)
    var index = objectToCompare2.children.startIndex
    for attr in objectSelf2.children{
        let type1 = Mirror(reflecting: attr.value).subjectType
        print(type1)
        let type2 = Mirror(reflecting: objectToCompare2.children[index].value).subjectType
        print(type2)
        if type1 == type2{
            print("Equal")
            if attr.value as! type1 != objectToCompare2.children[index].value as! type2{
                return false
            }
        }
        index = objectToCompare2.children.index(index, offsetBy: 1)
    }
    return true
}

The most of the code is working fine, the print("Equal") is always executed when the types of the two variables are equal.
The problem is this line:

if attr.value as! type1 != objectToCompare.children[index].value as! type2{
      return false
 }

I get this error message: "Use of undeclared type "type1"".
If I don't use the casting to type1 and type2, I get the error that I cannot use == with two properties of type "Any".
Is there a way to convert the type1 and type2 Strings to real datatypes? Or is there maybe a better way for what I'm trying to achieve?

This is my output from the prints:

Optional<String>
Optional<String>
Equal
Optional<String>
Optional<String>
Equal
Optional<Bool>
Optional<Bool>
Equal
String
String
Equal
Optional<String>
Optional<String>
Equal
String
String
Equal
String
String
Equal
Optional<DirectDebitStatus>
Optional<DirectDebitStatus>
Equal

I would appreciate any help!

Body:
I had a similar problem. Needed to compare several (huge) model objects that I got from different sources. Starting with your code and expanding with recursion and special cases I ended up with the following code snippet.

(Please note that I use this in a Test class, so there's no need to be efficient.)

func compareProperties(of target1: Any, with target2: Any) -> Bool {

    let mirror1 = Mirror(reflecting: target1)
    let mirror2 = Mirror(reflecting: target2)
    var index = mirror1.children.startIndex

    for child in mirror1.children {
        let child2 = mirror2.children[index]

        //Make another mirror to see if it has children
        let innerMirror1 = Mirror(reflecting: child.value)

        if (innerMirror1.children.count > 0) {
            // Use recursive reflection on the value of each child.
            print("Recursion on \(innerMirror1.subjectType)")
            if (!compareProperties(of: child.value, with: child2.value)) {
                return false
            }
        } else {
            //Compare the values
            let type1 = innerMirror1.subjectType
            let innerMirror2 = Mirror(reflecting: child2.value)
            let type2 = innerMirror2.subjectType
            if type1 == type2 {

                let stringValue1 = "\(child.value)"
                let stringValue2 = "\(child2.value)"

                //print("\(type1): \(stringValue1) ==? \(type2): \(stringValue2)")

                if (stringValue1 != stringValue2) {
                    print("\(type1): \(stringValue1) != \(type2): \(stringValue2)")
                    //Special case with Dates
                    if ("\(mirror1.subjectType)" == "Date") {
                        //Skip comparison of Doubles in Dates
                        if ("\(target1 as? Date)" != "\(target2 as? Date)") {
                            return false
                        }
                    } else {
                        return false
                    }
                }

            } else {
                print("Different classes \(type1) and \(type2)")
                return false
            }
        }
        //Increase index for next value pair
        index = mirror1.children.index(index, offsetBy: 1)
    }
    //If we get here it was never false.
    return true
}


问:
How to automatically delete old records from sql server database?
I'm making a web application in aspnet, and I created a table in the database to insert notifications. I would like to know if there is any way to automatically delete data from this table that is older than 30 days. Is there any way this can be done?</p>

答:
I would like to know if there is any way to automatically

SQL Server build-in tool for schedule tasks (also called jobs) is the SQL Server Agent.

https://learn.microsoft.com/en-us/sql/ssms/agent/sql-server-agent

You can create a JOB which run a DELETE query

Note! I HIGHLY recommend NOT to delete data from the database in most cases! Disk are cheap and you will never know when the history information will be needed, but more important is simply that you should not have a reason for this in most cases. In big system you are using partitions and you can store the old data in separate file as well and there is no need to backup that file every time. In small system you can simply buy another cheap HDD disk if needed. Instead of DELETE rows you should design the system to mark the rows as logically deleted (for example add another column) if needed

Update: and what if we are using SQL Server Express?!?

SQL Server express does not support the use of the SQL Server Agent, which means that we need a different solution to schedule task, and the common solutions you can use are:

Solution 1: Using external scheduler

Disadvantage: This solution is in the Operating System level

If you are using SQL Server on windows, then you can Windows Task Scheduler: start menu -> search for "Task Scheduler" -> Right click "Task Scheduler" and select "Create Basic Task" -> fill the task information -> choose "Start a Program" as the action type and execute a ".bat" file which include sqlcmd command which execute your query

If you are using Linux then you can use Cron daemon - a system-managed executable that runs in memory in the background with which users may schedule tasks.

Solution 2: schedule tasks using SQL Server SERVICE (service broker); CONVERSATION TIMER; MESSAGE; CONTRACT; QUEUE

Note! This is my preferred option and I use it even when Agent is supported for many reasons! Service broker is super reliable, it's part of the SQL Engine, there is almost no overhead, it allows asynchronous and timed (repeated) execution at any time interval. With that said, it does not have access to the operating system like the SQL Agent does.

You can get a full sample including all the code to implement this solution in this post: https://www.sqlteam.com/articles/scheduling-jobs-in-sql-server-express-2


问:
Why does my Bootstrap stretched link extend out several levels?
I am trying to stretched link for my nested div but it is including even parent. I need only listItem to be clickable but this makes entire card div clickable.

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">

Page Title

Title

Views

Category

              ....

```

答:
Per the Bootstrap docs (and the fundamental rules of absolute positioning), stretched links apply to the nearest element with non-static positioning. You can put the position-relative class on the parent to make that so.

I've also replaced your inline font size styles with the lead class on the parent paragraph. Just don't use inline styles, especially when your style library provides typography classes for that.

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">

Page Title

Title

Views

Category

              ....

```

Body:
Per the Bootstrap docs (and the fundamental rules of absolute positioning), stretched links apply to the nearest element with non-static positioning. You can put the position-relative class on the parent to make that so.

I've also replaced your inline font size styles with the lead class on the parent paragraph. Just don't use inline styles, especially when your style library provides typography classes for that.

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">

<div class="container-fluid">
  <div class="row">
    <div class="col-xs-8">
      <div class="col-xl-12 col-md-12 mb-3 mt-2">
        <div class="card custom-bg-2 h-100">
          <div class="card-header bg-secondary">
            <h3 class="fw-bold text-white text-center">Page Title</h3>
          </div>

          <div class="card-body">
            <div class="listItem position-relative">
              <img src="https://via.placeholder.com/100" class="rounded" alt="Title">
              <p class="lead"><span class="badge bg-secondary text-light">Title</span></p>
              <p><span class="badge bg-secondary ms-2">Views</span></p>
              <a href="#" class="stretched-link"></a>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="col-xs-4">
      <div class="row">
        <div class="col-xl-12 col-md-8 mb-3 mt-2">
          <div class="card custom-bg-2 h-100">
            <div class="card-header bg-secondary">
              <h3 class="fw-bold text-white">Category</h3>
            </div>
            <div class="card-body">
              ....
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>


问:
Is Function really an Object
I am a self taught web developer and am  still trying to come to grips with some JavaScript fundamentals. Below are some quotes extracted from Douglas Crockford's Good Parts.

"Functions in JavaScript are Objects"

"In JavaScript, arrays are objects, functions are objects, regular expressions are objects, and, of course, objects are objects"

"Every object is linked to a prototype object from which it can inherit properties" (namely constructor, toString, ...)

If Function is an Object then why

```<code> console.log(typeof Function);  // function
</code>```

is its type a function and not object

```<code> console.log(Object.constructor);  // Function()
</code>```

is it the constructor of its 'parent'

```<code> console.log(Function.constructor);  // Function()
</code>```

puzzled so the constructor is in-fact a function?

```<code> console.log(typeof Function.prototype); // Function
</code>```

is the type of its prototype a function and not an object? i thought it inherited from Object

Answers to these questions will greatly assist my understanding on JavaScript.

答:
reference Is every JavaScript Object a function?

```<code>javascript:alert([ window.navigator.userAgent, Object, Function ].join("\n\n") )
</code>```

displays

```<code>Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.3) Gecko/20100423
      Ubuntu/10.04 (lucid) Firefox/3.6.3

function Object() {
    [native code]
}

function Function() {
    [native code]
}
</code>```

also

```<code>javascript:alert([ new Object, new Function ].join("\n\n") )
</code>```

displays

```<code>[object Object]

function anonymous() {  }
</code>```

and

```<code>javascript:alert([ new new Function ].join("\n\n") )
</code>```

displays

```<code>[object Object]
</code>```

ContentLicense: CC BY-SA 2.5

Title: Is Function really an Object

Body:
I am a self taught web developer and am  still trying to come to grips with some JavaScript fundamentals. Below are some quotes extracted from Douglas Crockford's Good Parts.

"Functions in JavaScript are Objects"

"In JavaScript, arrays are objects, functions are objects, regular expressions are objects, and, of course, objects are objects"

"Every object is linked to a prototype object from which it can inherit properties" (namely constructor, toString, ...)

If Function is an Object then why

 console.log(typeof Function);  // function

is its type a function and not object

 console.log(Object.constructor);  // Function()

is it the constructor of its 'parent'

 console.log(Function.constructor);  // Function()

puzzled so the constructor is in-fact a function?

 console.log(typeof Function.prototype); // Function

is the type of its prototype a function and not an object? i thought it inherited from Object

Answers to these questions will greatly assist my understanding on JavaScript.

Body:
reference Is every JavaScript Object a function?

javascript:alert([ window.navigator.userAgent, Object, Function ].join("\n\n") )

displays

Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.3) Gecko/20100423
      Ubuntu/10.04 (lucid) Firefox/3.6.3

function Object() {
    [native code]
}

function Function() {
    [native code]
}

also

javascript:alert([ new Object, new Function ].join("\n\n") )

displays

[object Object]

function anonymous() {  }

and

javascript:alert([ new new Function ].join("\n\n") )

displays

[object Object]


问:
Why does my array print more than I want?
I'm trying to write an array in c++, which consist of 10 integers that are all 1, unless changed through keyboard input. For some reason my code prints out way more than 10 integers and I'm not sure why.

```<code>int main()
{
    int index, value;
    int count = 0;
    int myData [10];
    for (int i = 0; i < sizeof(myData); i++)
    {
        myData[i] = 1;
    }

    do
    {
        for (int i = 0; i < sizeof(myData); i++)
        {
            std::cout << myData[i] << " ";
        }

        std::cout << "Input index: ";
        std::cin >> index;
        std::cout << "Input value: ";
        std::cin >> value;

        myData[index] = value;

    } while ((0 <= index) && (index <= sizeof(myData)));

    std::cout << "Index out of range. Exit." << std::endl;

    return 0;
}
</code>```

EDIT
I got it to work thank you :D but for some reason now I'm getting a buffer overflow. Anyway to fix this?

答:
Replacing sizeof(myData) with std::size(myData) or with sizeof(myData) / sizeof(int) is fine, but IMO it would be better if you just use range-based for loop or/and use constant to define size of that array:

int main()
{
    static const DataSize = 10;
    int index, value;
    int count = 0;
    int myData [DataSize];
    for (auto &x : myData)
    {
        x = 1;
    }

    do
    {
        for (auto x : myData)
        {
            std::cout << x << " ";
        }

        std::cout << "Input index: ";
        std::cin >> index;
        std::cout << "Input value: ";
        std::cin >> value;

        myData[index] = value;

    } while (0 <= index && index < DataSize);

    std::cout << "Index out of range. Exit." << std::endl;

    return 0;
}
```

Disclaimer: your code is still invalid, but this is another issue.

Body:
I'm trying to write an array in c++, which consist of 10 integers that are all 1, unless changed through keyboard input. For some reason my code prints out way more than 10 integers and I'm not sure why.

int main()
{
    int index, value;
    int count = 0;
    int myData [10];
    for (int i = 0; i < sizeof(myData); i++)
    {
        myData[i] = 1;
    }

    do
    {
        for (int i = 0; i < sizeof(myData); i++)
        {
            std::cout << myData[i] << " ";
        }

        std::cout << "Input index: ";
        std::cin >> index;
        std::cout << "Input value: ";
        std::cin >> value;

        myData[index] = value;

    } while ((0 <= index) && (index <= sizeof(myData)));

    std::cout << "Index out of range. Exit." << std::endl;

    return 0;
}

EDIT
I got it to work thank you :D but for some reason now I'm getting a buffer overflow. Anyway to fix this?

Body:
Replacing sizeof(myData) with std::size(myData) or with sizeof(myData) / sizeof(int) is fine, but IMO it would be better if you just use range-based for loop or/and use constant to define size of that array:

int main()
{
    static const DataSize = 10;
    int index, value;
    int count = 0;
    int myData [DataSize];
    for (auto &x : myData)
    {
        x = 1;
    }

    do
    {
        for (auto x : myData)
        {
            std::cout << x << " ";
        }

        std::cout << "Input index: ";
        std::cin >> index;
        std::cout << "Input value: ";
        std::cin >> value;

        myData[index] = value;

    } while (0 <= index && index < DataSize);

    std::cout << "Index out of range. Exit." << std::endl;

    return 0;
}

Disclaimer: your code is still invalid, but this is another issue.


问:
SuperController of Getx Package in Flutter causing a problem
I am facing a problem when I extends a class with SuperController of Getx PAckage in Flutter. Please go through my code and let me know the solution.

main.dart

```<code>import 'package:flutter/material.dart';
import 'package:flutter_app/user_status_controller.dart';
import 'package:get/get.dart';

void main() {
  Get.put(UserStatusController());
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
          child: Text(
        'Hello',
        style: TextStyle(fontSize: 50),
      )),
    );
  }
}
</code>```

user_status_controller.dart

```<code>import 'package:get/get.dart';

class UserStatusController extends SuperController {
  @override
  void onDetached() {}

  @override
  void onInactive() {}

  @override
  void onPaused() {}

  @override
  void onResumed() {}
}
</code>```

The error thrown is:

```<code>E/flutter ( 3620): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Null check operator used on a null value
E/flutter ( 3620): #0      FullLifeCycleMixin.onInit (package:get/get_state_manager/src/simple/get_controllers.dart:90:28)
E/flutter ( 3620): #1      GetLifeCycleBase._onStart (package:get/get_instance/src/lifecycle.dart:66:5)
E/flutter ( 3620): #2      InternalFinalCallback.call (package:get/get_instance/src/lifecycle.dart:12:26)
E/flutter ( 3620): #3      GetInstance._startController (package:get/get_instance/src/get_instance.dart:253:16)
E/flutter ( 3620): #4      GetInstance._initDependencies (package:get/get_instance/src/get_instance.dart:204:11)
E/flutter ( 3620): #5      GetInstance.find (package:get/get_instance/src/get_instance.dart:301:17)
E/flutter ( 3620): #6      GetInstance.put (package:get/get_instance/src/get_instance.dart:86:12)
E/flutter ( 3620): #7      Inst.put (package:get/get_instance/src/extension_instance.dart:89:21)
E/flutter ( 3620): #8      main (package:flutter_app/main.dart:6:7)
E/flutter ( 3620): #9      _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:129:25)
E/flutter ( 3620): #10     _rootRun (dart:async/zone.dart:1428:13)
E/flutter ( 3620): #11     _CustomZone.run (dart:async/zone.dart:1328:19)
[GETX] Instance "UserStatusController" has been created
E/flutter ( 3620): #12     _runZoned (dart:async/zone.dart:1863:10)
E/flutter ( 3620): #13     runZonedGuarded (dart:async/zone.dart:1851:12)
E/flutter ( 3620): #14     _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:125:5)
E/flutter ( 3620): #15     _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:297:19)
E/flutter ( 3620): #16     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
</code>```

Could anybody tell me what is throwing the error. Please help me. This is a simple code I'm unable to understand what is causing this.

答:
hmm try this if its working if not mention me

xample your main.dart

```<code>void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      home: HomePage(),
      getPages: RouteList.routeLists,
      initialRoute: "/home"
    );
  }
}
</code>```

create a binding dart named it binding_home.dart depends on you

```<code>class YourBinding extends Bindings {
  @override
  void dependencies() {
    // TODO: implement dependencies
    Get.lazyPut(() => UserStatusController (), fenix: true);
  }
}
</code>```

then on your route to bind it

```<code>class RouteList {
  static final routeLists = [
    GetPage(
        transition: Transition.cupertinoDialog,
        transitionDuration: 350.milliseconds,
        name: "/home",
        binding: YourBinding(),
        page: () => const HomePage()),
  ];
}
</code>```

next is your controller

```<code>class UserStatusController extends SuperController {
  @override
  void onDetached() {}

  @override
  void onInactive() {}

  @override
  void onPaused() {}

  @override
  void onResumed() {}
}
</code>```

then lastly on homepage try use Getview

```<code>class HomePage extends GetView<UserStatusController > {
  const HomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
          child: Text(
        'Hello',
        style: TextStyle(fontSize: 50),
      )),
    );
  }
}
</code>```

i do sometime it depends use Getview so that i wont put on the stateless like Get.put() or find(). as per default calling on the controller just type controller.yourValue

Body:
I am facing a problem when I extends a class with SuperController of Getx PAckage in Flutter. Please go through my code and let me know the solution.

main.dart

import 'package:flutter/material.dart';
import 'package:flutter_app/user_status_controller.dart';
import 'package:get/get.dart';

void main() {
  Get.put(UserStatusController());
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
          child: Text(
        'Hello',
        style: TextStyle(fontSize: 50),
      )),
    );
  }
}

user_status_controller.dart

import 'package:get/get.dart';

class UserStatusController extends SuperController {
  @override
  void onDetached() {}

  @override
  void onInactive() {}

  @override
  void onPaused() {}

  @override
  void onResumed() {}
}

The error thrown is:

E/flutter ( 3620): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Null check operator used on a null value
E/flutter ( 3620): #0      FullLifeCycleMixin.onInit (package:get/get_state_manager/src/simple/get_controllers.dart:90:28)
E/flutter ( 3620): #1      GetLifeCycleBase._onStart (package:get/get_instance/src/lifecycle.dart:66:5)
E/flutter ( 3620): #2      InternalFinalCallback.call (package:get/get_instance/src/lifecycle.dart:12:26)
E/flutter ( 3620): #3      GetInstance._startController (package:get/get_instance/src/get_instance.dart:253:16)
E/flutter ( 3620): #4      GetInstance._initDependencies (package:get/get_instance/src/get_instance.dart:204:11)
E/flutter ( 3620): #5      GetInstance.find (package:get/get_instance/src/get_instance.dart:301:17)
E/flutter ( 3620): #6      GetInstance.put (package:get/get_instance/src/get_instance.dart:86:12)
E/flutter ( 3620): #7      Inst.put (package:get/get_instance/src/extension_instance.dart:89:21)
E/flutter ( 3620): #8      main (package:flutter_app/main.dart:6:7)
E/flutter ( 3620): #9      _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:129:25)
E/flutter ( 3620): #10     _rootRun (dart:async/zone.dart:1428:13)
E/flutter ( 3620): #11     _CustomZone.run (dart:async/zone.dart:1328:19)
[GETX] Instance "UserStatusController" has been created
E/flutter ( 3620): #12     _runZoned (dart:async/zone.dart:1863:10)
E/flutter ( 3620): #13     runZonedGuarded (dart:async/zone.dart:1851:12)
E/flutter ( 3620): #14     _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:125:5)
E/flutter ( 3620): #15     _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:297:19)
E/flutter ( 3620): #16     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)

Could anybody tell me what is throwing the error. Please help me. This is a simple code I'm unable to understand what is causing this.

Body:
hmm try this if its working if not mention me

xample your main.dart

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      home: HomePage(),
      getPages: RouteList.routeLists,
      initialRoute: "/home"
    );
  }
}

create a binding dart named it binding_home.dart depends on you

class YourBinding extends Bindings {
  @override
  void dependencies() {
    // TODO: implement dependencies
    Get.lazyPut(() => UserStatusController (), fenix: true);
  }
}

then on your route to bind it

class RouteList {
  static final routeLists = [
    GetPage(
        transition: Transition.cupertinoDialog,
        transitionDuration: 350.milliseconds,
        name: "/home",
        binding: YourBinding(),
        page: () => const HomePage()),
  ];
}

next is your controller

class UserStatusController extends SuperController {
  @override
  void onDetached() {}

  @override
  void onInactive() {}

  @override
  void onPaused() {}

  @override
  void onResumed() {}
}

then lastly on homepage try use Getview

class HomePage extends GetView<UserStatusController > {
  const HomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
          child: Text(
        'Hello',
        style: TextStyle(fontSize: 50),
      )),
    );
  }
}

i do sometime it depends use Getview so that i wont put on the stateless like Get.put() or find(). as per default calling on the controller just type controller.yourValue


问:
Dynamic child pipelines and stop action not working
after adding dynamic child pipelines to our CI pipeline on stop action(eg. deleting branch), stopped working.
In stop job we are deleting created k8s resources, so its important to be executed.
What i noticed is that defining environment in child pipeline is probable cause(without environment section, on stop action is working).

Any ideas?

gitlab-ci.yaml looks like this

```<code>stages:
  ....
  - deploy
  - tests_prepare
  - maintenance_tests
  ....

deploy_branch_to_k8s:
  stage: deploy
  only:
    - branches
  except:
    - master
  dependencies:
    - build_api
  environment:
    name: branches/$CI_COMMIT_REF_NAME
    on_stop: stop_deployed_branch_in_k8s
  script:
    - deploy to k8s

stop_deployed_branch_in_k8s:
  stage: deploy
  only:
    - branches
  except:
    - master
  when: manual
  dependencies: []
  variables:
    GIT_STRATEGY: none
  environment:
    name: branches/$CI_COMMIT_REF_NAME
    action: stop
  script:
    - delete k8s resources

generate_config_tests:
  stage: tests_prepare
  only:
    - branches
  except:
    - master
  dependencies:
    - build_api
    ....
  script:
    - python3 ./utils/generate-jobs-config.py > generated-config.yml
  artifacts:
    paths:
      - generated-config.yml

create_maintenance_tests_pipeline:
  stage: maintenance_tests
  only:
    - branches
  except:
    - master
  trigger:
    strategy: depend
    include:
      - artifact: generated-config.yml
        job: generate_config_tests
  variables:
    PARENT_PIPELINE_ID: $CI_PIPELINE_ID
</code>```

generated-config.yml looks something like this

```<code>stages:
  - tests

run_maintenance_test_job___TEST_NAME__:
  stage: tests
  retry: 2
  environment:
    name: branches/$CI_COMMIT_REF_NAME
  needs:
    - pipeline: $PARENT_PIPELINE_ID
      job: generate_config_maintenance_tests
  script:
    - deploy a run tests in k8s
</code>```

答: If I'm not wrong, you should skip the needs part altogether in the child pipeline, since it is only used for jobs in the same pipeline. Its upstream will be the parent pipeline anyway.

Body:
after adding dynamic child pipelines to our CI pipeline on stop action(eg. deleting branch), stopped working.
In stop job we are deleting created k8s resources, so its important to be executed.
What i noticed is that defining environment in child pipeline is probable cause(without environment section, on stop action is working).

Any ideas?

gitlab-ci.yaml looks like this

stages:
  ....
  - deploy
  - tests_prepare
  - maintenance_tests
  ....

deploy_branch_to_k8s:
  stage: deploy
  only:
    - branches
  except:
    - master
  dependencies:
    - build_api
  environment:
    name: branches/$CI_COMMIT_REF_NAME
    on_stop: stop_deployed_branch_in_k8s
  script:
    - deploy to k8s

stop_deployed_branch_in_k8s:
  stage: deploy
  only:
    - branches
  except:
    - master
  when: manual
  dependencies: []
  variables:
    GIT_STRATEGY: none
  environment:
    name: branches/$CI_COMMIT_REF_NAME
    action: stop
  script:
    - delete k8s resources

generate_config_tests:
  stage: tests_prepare
  only:
    - branches
  except:
    - master
  dependencies:
    - build_api
    ....
  script:
    - python3 ./utils/generate-jobs-config.py > generated-config.yml
  artifacts:
    paths:
      - generated-config.yml

create_maintenance_tests_pipeline:
  stage: maintenance_tests
  only:
    - branches
  except:
    - master
  trigger:
    strategy: depend
    include:
      - artifact: generated-config.yml
        job: generate_config_tests
  variables:
    PARENT_PIPELINE_ID: $CI_PIPELINE_ID

generated-config.yml looks something like this

stages:
  - tests

run_maintenance_test_job___TEST_NAME__:
  stage: tests
  retry: 2
  environment:
    name: branches/$CI_COMMIT_REF_NAME
  needs:
    - pipeline: $PARENT_PIPELINE_ID
      job: generate_config_maintenance_tests
  script:
    - deploy a run tests in k8s


问:
Export messages from the ActiveMQ Artemis dead letter queue and reimport them on another cluster
I would like to export failed messages from an ActiveMQ Artemis dead letter queue and re-import them on another cluster to debug the processing. The functionality of the Artemis CLI does not seem to support anything like that? Has somebody an idea how to accomplish that?</p>

答:
You can use the message transfer command to consume messages from a JMS queue on one broker and send them to a JMS queue on another broker, e.g.:

```<code>$ ./artemis message transfer --source-url tcp://broker1:61616 --source-queue DLQ --target-url tcp://broker2:61616 --target-queue myQueue
</code>```

Body:
You can use the message transfer command to consume messages from a JMS queue on one broker and send them to a JMS queue on another broker, e.g.:

$ ./artemis message transfer --source-url tcp://broker1:61616 --source-queue DLQ --target-url tcp://broker2:61616 --target-queue myQueue


问:
How to skin all ASP.Net validators?
I want all of the validators in an ASP.Net 3.5 website to have a CssClass value of "error".  My initial thought was to do this in a theme skin like so:

```<code><asp:CompareValidator runat="server"
    CssClass="error" />
<asp:CustomValidator runat="server"
    CssClass="error" />
<asp:RequiredFieldValidator runat="server"
    CssClass="error" />
<belCommon:ZipCodeValidator runat="server"
    CssClass="error" />
<belCommon:PhoneNumberValidator runat="server"
    CssClass="error" />
</code>```

This is only a partial listing of validators that I use. Ideally, I would like to do something like this:

```<code><asp:BaseValidator runat="server"
    CssClass="error" />
</code>```

And because all validators inherit from BaseValidator, I would expect that this would work, but it doesn't.  Is there a way to accomplish this without adding every single validator control to the skin explicitly?

Update:

I found a different approach using javascript:

```<code>Sys.Application.add_init(function(sender, args)
{
    if (Page_Validators != null)
    {
        for (i = 0; i < Page_Validators.length; i++)
        {
            Page_Validators[i].className = "error";
        }
    }
});
</code>```

ASP.Net generates a javascript variable called Page_Validators, which is an array of the validation spans.  This script checks to see if it exists and then loops through and sets the class name.  I added this to the master page and its working so far.

答:
Not that I am aware of, when defining a skin you are specifically working with individual controls and you don't have a way of specifying it any other way, as it matches based on the tags used.

From the looks of it though, you are creating your own custom validators as well, you might modify your controls to have a default cssclass of error to save a bit of time.

OwnerDisplayName: jrummell

Title: How to skin all ASP.Net validators?

Body:
I want all of the validators in an ASP.Net 3.5 website to have a CssClass value of "error".  My initial thought was to do this in a theme skin like so:

<asp:CompareValidator runat="server"
    CssClass="error" />
<asp:CustomValidator runat="server"
    CssClass="error" />
<asp:RequiredFieldValidator runat="server"
    CssClass="error" />
<belCommon:ZipCodeValidator runat="server"
    CssClass="error" />
<belCommon:PhoneNumberValidator runat="server"
    CssClass="error" />

This is only a partial listing of validators that I use. Ideally, I would like to do something like this:

<asp:BaseValidator runat="server"
    CssClass="error" />

And because all validators inherit from BaseValidator, I would expect that this would work, but it doesn't.  Is there a way to accomplish this without adding every single validator control to the skin explicitly?

Update:

I found a different approach using javascript:

Sys.Application.add_init(function(sender, args)
{
    if (Page_Validators != null)
    {
        for (i = 0; i < Page_Validators.length; i++)
        {
            Page_Validators[i].className = "error";
        }
    }
});

ASP.Net generates a javascript variable called Page_Validators, which is an array of the validation spans.  This script checks to see if it exists and then loops through and sets the class name.  I added this to the master page and its working so far.

LastEditorDisplayName: jrummell

OwnerDisplayName: Mitchel Sellers


问:
Removing the MainPage.xaml
I have been looking into this for awhile and have had no real luck.

My project consists of a Login page that happens to be the MainPage.xaml.

The users who will be using this App should not be able to go back to the page with the Windows mobile 7 back button.

My Second Page is Called afterLoginMenu.xaml, i want it so that when the user presses the back button from the second page it will close the application never showing the login page again.

Is this Possible? and if so How?

Thank you In advance!

答:
after create your Login popup control, do something like this:</p>

```<code>        public MainPage()
    {
        InitializeComponent();
        if (someVariable == 0)
        {
            myPopup = new Popup() { IsOpen = true, Child = new Login() };

            someVariable = 1; //this will be a global value, so the popup wouldn't open again when back key is pressed
        }

    }
</code>```

Title: Removing the MainPage.xaml

Body:
after create your Login popup control, do something like this:

        public MainPage()
    {
        InitializeComponent();
        if (someVariable == 0)
        {
            myPopup = new Popup() { IsOpen = true, Child = new Login() };

            someVariable = 1; //this will be a global value, so the popup wouldn't open again when back key is pressed
        }

    }


问:
Why can't I reassign variables in this function?
Here is the question:

You will be given an array of numbers. You have to sort the odd numbers in ascending order while leaving the even numbers at their original positions.

Here is my code:

```<code>def sort_array(source_array):
    odd_ints = []

    for i in source_array:
        if i % 2 == 1:
            odd_ints.append(i)
            odd_ints.sort()
        else:
            pass
    counter = 0
    for x in source_array:
        if x % 2 == 1:
            x = odd_ints[counter]
            counter += 1
            print(source_array)
        else:
            pass

    return source_array
</code>```

When I test it, it does this:

```<code>>>> sort_array([5, 3, 2, 8, 1, 4])
[5, 3, 2, 8, 1, 4]
[5, 3, 2, 8, 1, 4]
[5, 3, 2, 8, 1, 4]

[5, 3, 2, 8, 1, 4]
</code>```

For some reason, I can't re-assign the variable x in the function to odd_ints in ascending order. Would anyone know the problem in my code?

答:
You just need to save the positions of the odd integers as well to replace them:

```<code>def sort_array(source_array):
    odd_ints = []
    positions = []
    counter = 0 #need counter to get positions
    for i in source_array:
        if i % 2 == 1:
            odd_ints.append(i) #keep the values
            positions.append(counter) #keep the position
        counter += 1
    odd_ints.sort() #sort for replacement
    counter2 = 0 #need second counter to place sorted list
    for pos in positions:
        source_array[pos] = odd_ints[counter2] #place the sorted values
        counter2 += 1
    return source_array

print(sort_array([5, 3, 2, 8, 1, 4]))
</code>```

Output:

```<code>[1, 3, 2, 8, 5, 4]
</code>```

Body:
Here is the question:

You will be given an array of numbers. You have to sort the odd numbers in ascending order while leaving the even numbers at their original positions.

Here is my code:

def sort_array(source_array):
    odd_ints = []

    for i in source_array:
        if i % 2 == 1:
            odd_ints.append(i)
            odd_ints.sort()
        else:
            pass
    counter = 0
    for x in source_array:
        if x % 2 == 1:
            x = odd_ints[counter]
            counter += 1
            print(source_array)
        else:
            pass

    return source_array

When I test it, it does this:

>>> sort_array([5, 3, 2, 8, 1, 4])
[5, 3, 2, 8, 1, 4]
[5, 3, 2, 8, 1, 4]
[5, 3, 2, 8, 1, 4]

[5, 3, 2, 8, 1, 4]

For some reason, I can't re-assign the variable x in the function to odd_ints in ascending order. Would anyone know the problem in my code?

Body:
You just need to save the positions of the odd integers as well to replace them:

def sort_array(source_array):
    odd_ints = []
    positions = []
    counter = 0 #need counter to get positions
    for i in source_array:
        if i % 2 == 1:
            odd_ints.append(i) #keep the values
            positions.append(counter) #keep the position
        counter += 1
    odd_ints.sort() #sort for replacement
    counter2 = 0 #need second counter to place sorted list
    for pos in positions:
        source_array[pos] = odd_ints[counter2] #place the sorted values
        counter2 += 1
    return source_array

print(sort_array([5, 3, 2, 8, 1, 4]))

Output:

[1, 3, 2, 8, 5, 4]


问:
SystemError: PY_SSIZE_T_CLEAN macro must be defined for '#' formats
I cannot find anything on this. I'm getting error:

Traceback (most recent call last):
  File "/path/to/pwdb.py", line 265, in <module>
    password_db()
  File "/path/to/pwdb.py", line 73, in __init__
    self.cipher = AES.new(key,AES.MODE_ECB)
  File "/home/STACKOVERFLOW/.local/lib/python3.10/site-packages/Crypto/Cipher/AES.py", line 95, in new
    return AESCipher(key, *args, **kwargs)
  File "/home/STACKOVERFLOW/.local/lib/python3.10/site-packages/Crypto/Cipher/AES.py", line 59, in __init__
    blockalgo.BlockAlgo.__init__(self, _AES, key, *args, **kwargs)
  File "/home/STACKOVERFLOW/.local/lib/python3.10/site-packages/Crypto/Cipher/blockalgo.py", line 141, in __init__
    self._cipher = factory.new(key, *args, **kwargs)
SystemError: PY_SSIZE_T_CLEAN macro must be defined for '#' formats
```
<p>I'm pretty sure the line it's getting the error from is:</p>
<pre class="lang-py prettyprint-override"><code>self.cipher = AES.new(key,AES.MODE_ECB)
</code>```

The script was working not too long ago. Did PyCrypto update its formatting or something ? And does anyone have any idea on how to fix this ? I can provide more of the code if need be.

答:
It sounds like the extension was not updated for python 3.10.

On 3.10 any module(s) that use the # variant when parsing arguments need to have a #define PY_SSIZE_T_CLEAN before including Python.h.

From the docs:

For all # variants of formats (s#, y#, etc.), the macro
PY_SSIZE_T_CLEAN must be defined before including Python.h. On Python
3.9 and older, the type of the length argument is Py_ssize_t if the PY_SSIZE_T_CLEAN macro is defined, or int otherwise.

See https://docs.python.org/3/c-api/arg.html#strings-and-buffers

Body:
I cannot find anything on this. I'm getting error:

Traceback (most recent call last):
  File "/path/to/pwdb.py", line 265, in <module>
    password_db()
  File "/path/to/pwdb.py", line 73, in __init__
    self.cipher = AES.new(key,AES.MODE_ECB)
  File "/home/STACKOVERFLOW/.local/lib/python3.10/site-packages/Crypto/Cipher/AES.py", line 95, in new
    return AESCipher(key, *args, **kwargs)
  File "/home/STACKOVERFLOW/.local/lib/python3.10/site-packages/Crypto/Cipher/AES.py", line 59, in __init__
    blockalgo.BlockAlgo.__init__(self, _AES, key, *args, **kwargs)
  File "/home/STACKOVERFLOW/.local/lib/python3.10/site-packages/Crypto/Cipher/blockalgo.py", line 141, in __init__
    self._cipher = factory.new(key, *args, **kwargs)
SystemError: PY_SSIZE_T_CLEAN macro must be defined for '#' formats

I'm pretty sure the line it's getting the error from is:

self.cipher = AES.new(key,AES.MODE_ECB)

The script was working not too long ago. Did PyCrypto update its formatting or something ? And does anyone have any idea on how to fix this ? I can provide more of the code if need be.


问:
jQuery .fadeOut problems in FireFox 6.0
So far, I have the fadeIn working, but the fadeOut has not been quite right.  Right now, as soon as the mouse leaves the hover area, it doesn't look like any fadeOut is happening at all.  I would like to have a smooth fade out that completes before the next animation (the next fadeIn) begins and doesn't queue up.  Basically this is over some links that are within  tags.  I'm in the home stretch now!

P.S. I know I'm not using .hover.  I'd rather stick with mouseover and mouseleave for now, or even mouseout.  Please accomodate this small request.

```<code><script>
    $("a").mouseover(function () {
        $("div").fadeIn(0, function () {
            $("span").fadeIn(3000,0.0);
        });
        return false;
    });

    $dequeue;

    $("a").mouseleave(function () {
        $("span").fadeOut(3000,0.0);
    });
</script>

<!DOCTYPE html>

<html>
<head>
<script type="text/javascript" src="jQuery.js"></script>
</head>
<body>

<a href="#">MouseOver!</a>

<div>

<h3><span>Sample Text</span></h3>

</div>
</body>
</html>
</code>```

Edit: 08/18/2011

I realized that there may be script conflicting with the one above.  I have an additional jquery script running on the same page.  By itself it works fine, but when I add the script for the text box (above) the .fadeOut on both images and text becomes ignored or at the very least, inconsistent.

2nd jQuery script:

```<code><script>
$(document).ready(function(){

$(".latest_img").fadeTo("slow", 0.0);
$(".latest_img").hover(function(){
$(this).fadeTo(1000, 1.0).dequeue();

},function(){
$(this).fadeTo(1000, 0.0).dequeue();
});
});
</script>
</code>```

Here is an example of one of the four "targets" that should prompt the text and image to display (there are four text boxes accompanying four images - each get shown by a mouseover on the target).

HTML:

```<code><div class="gallerycontainer">
<div width="100%" height="30%">

<a class="thumbnail" href="#thumb"><h2 class="ftb" id="tg1">Target A</h2>

<span class="txspan">
<img src="img/ima.jpg" class="latest_img" id="images" />
<h3 class="text"><br>Textbox content for Target A</h3></span></a>

</div>
</div>
</code>```

答:
Place everyting inside the document ready event

Remove the $dequeue.

Add stop(true, true) before the fadeIn's and fadeOut's

```<code>$(document).ready(function() {
  $("a").mouseover(function () {
      $("div").stop(true, true).fadeIn(0, function () {
          $("span").fadeIn(3000,0.0);
      });
      return false;
  });

  //$dequeue;

  $("a").mouseleave(function () {
      $("span").stop(true, true).fadeOut(3000,0.0);
  });
});
</code>```

Title: jQuery .fadeOut problems in FireFox 6.0

Body:
So far, I have the fadeIn working, but the fadeOut has not been quite right.  Right now, as soon as the mouse leaves the hover area, it doesn't look like any fadeOut is happening at all.  I would like to have a smooth fade out that completes before the next animation (the next fadeIn) begins and doesn't queue up.  Basically this is over some links that are within  tags.  I'm in the home stretch now!

P.S. I know I'm not using .hover.  I'd rather stick with mouseover and mouseleave for now, or even mouseout.  Please accomodate this small request.

<!DOCTYPE html>

MouseOver!

Sample Text

Edit: 08/18/2011

I realized that there may be script conflicting with the one above.  I have an additional jquery script running on the same page.  By itself it works fine, but when I add the script for the text box (above) the .fadeOut on both images and text becomes ignored or at the very least, inconsistent.

2nd jQuery script:

Here is an example of one of the four "targets" that should prompt the text and image to display (there are four text boxes accompanying four images - each get shown by a mouseover on the target).

HTML:

Target A

Textbox content for Target A

Body:
Place everyting inside the document ready event

Remove the $dequeue.

Add stop(true, true) before the fadeIn's and fadeOut's

$(document).ready(function() {
  $("a").mouseover(function () {
      $("div").stop(true, true).fadeIn(0, function () {
          $("span").fadeIn(3000,0.0);
      });
      return false;
  });

  //$dequeue;

  $("a").mouseleave(function () {
      $("span").stop(true, true).fadeOut(3000,0.0);
  });
});


问:
How to return something from a Concern and update a record?
I want to move some class methods for some of my models that are the same to a concern.
One method takes an input and returns something which then should be used to update a record like this:

```<code>def create_sort_title
    self.sort_title = self.title.gsub(/^the |^a |^an /i, '').gsub(/'|"|!|\?|-/, '').gsub(/(?<!\w) /,'')
end
</code>```

While it's clear that I need to refactor it to take an input:

```<code>def create_sort_title(title)
    self.sort_title = title.gsub...
...
</code>```

I don't understand how I can RETURN a value to update a record - i. e. how to replace the self.sort_title above with something that then is used to update the sort_title of the corresponding record?

The method is called by a before_safe hook:

```<code>before_save :create_sort_title
</code>```

(and I understand once I take an argument, I need to use a lambda like this:

```<code>before_save -> { create_sort_title(title) }
</code>```

答: You don't really need to pass any arguments if you're using a concern that is included on the model. When you do include ConcernName you're adding class and/or instance methods on the model class/instance itself. So your create_sort_title method that is called from before_save callback will have access to all instance methods, including title and will work as-is just fine

Body:
I want to move some class methods for some of my models that are the same to a concern.
One method takes an input and returns something which then should be used to update a record like this:

def create_sort_title
    self.sort_title = self.title.gsub(/^the |^a |^an /i, '').gsub(/'|"|!|\?|-/, '').gsub(/(?<!\w) /,'')
end

While it's clear that I need to refactor it to take an input:

def create_sort_title(title)
    self.sort_title = title.gsub...
...

I don't understand how I can RETURN a value to update a record - i. e. how to replace the self.sort_title above with something that then is used to update the sort_title of the corresponding record?

The method is called by a before_safe hook:

before_save :create_sort_title

(and I understand once I take an argument, I need to use a lambda like this:

before_save -> { create_sort_title(title) }


问:
Adding labels to a dual axis that are non-related to datapoints in ggplot
I am attempting to create a barplot that has has labels on a dual axis but for whom these new labels are not related or a transformation of the labels/values on the main axis. I.e., I can't use sec.axis.

I am looking to add the numbers from data$unknown for each year period (see plot below).

I am not sure if this is possible at all - using the data directly? Alternatively one could add text with annotate() - but this also doesn't seem to work for me.

Anybody in here who has a solution?

```<code>library('tidyverse')
library('scales')

data <- tibble(model = rep(c("model 0", "model I", "model II", "model III", "model IV"),3),
                year = c(rep('2005-2009', 5), rep('2010-2014',5), rep('2015-2017',5)),
                value = c(0.0, 10.4, 30.7, 26.7, 32.2, 0.0, 9.9, 31.0, 26.5, 32.6, 0.0, 19.1, 29.6, 25.6, 25.7),
                unknown = c(rep(30,5), rep(40,5), rep(27,5)))

p1 <- ggplot(data, aes(fill=model, y=value, x=year)) +
  geom_bar(stat='identity', position = position_fill(reverse = TRUE)) +
  scale_fill_grey(start=0.8, end=0.2) +
  theme_bw() +
  ggtitle('Model') +
  xlab('') + ylab('') +
  theme(legend.position="bottom",
        plot.title = element_text(hjust = 0.5),
        legend.title=element_blank(),
        text = element_text(family = "serif")
  ) +
  scale_y_continuous(labels = percent_format(scale = 100)) +
  scale_x_discrete(limits = rev(levels(data$year))) +
  coord_flip()
p1

</code>```

In the plot below I have manually (outside of R) added the labels in order to clarify the question.

答:
The issue is that discrete positional scales do not allow for a secondary or duplicated axis, i.e. the have no sec.axis argument.

However, one option would be to make use of a continuous scale by converting your year variable to a numeric and making use of dup_axis.

Note 1: To create the labels for the secondary scale I create a named vector to make sure that the right values of your unknown gets assigned to each level of year.

Note 2: I dropped coord_flip and switched the role of x and y. Also, as we now have numerics on both axes I forced the horizontal bars via orientation="y".

library('tidyverse')
library('scales')

# Numeric year
data$year_num <- as.numeric(factor(data$year))
# Labels for primary scale
labels <- levels(factor(data$year))
# Labels for secondary scale
dup_labels <- distinct(data, year, unknown) %>% tibble::deframe()

p1 <- ggplot(data, aes(fill=model, x=value, y = year_num)) +
  geom_bar(stat='identity', position = position_fill(reverse = TRUE), orientation = "y") +
  scale_fill_grey(start=0.8, end=0.2) +
  theme_bw() +
  ggtitle('Model') +
  xlab('') + ylab('') +
  theme(legend.position="bottom",
        plot.title = element_text(hjust = 0.5),
        legend.title=element_blank(),
        text = element_text(family = "serif")
  ) +
  scale_x_continuous(labels = percent_format(scale = 100)) +
  scale_y_continuous(breaks = seq_along(labels), labels = labels, sec.axis = dup_axis(labels = dup_labels))
p1
```

Body:
I am attempting to create a barplot that has has labels on a dual axis but for whom these new labels are not related or a transformation of the labels/values on the main axis. I.e., I can't use sec.axis.

I am looking to add the numbers from data$unknown for each year period (see plot below).

I am not sure if this is possible at all - using the data directly? Alternatively one could add text with annotate() - but this also doesn't seem to work for me.

Anybody in here who has a solution?

library('tidyverse')
library('scales')

data <- tibble(model = rep(c("model 0", "model I", "model II", "model III", "model IV"),3),
                year = c(rep('2005-2009', 5), rep('2010-2014',5), rep('2015-2017',5)),
                value = c(0.0, 10.4, 30.7, 26.7, 32.2, 0.0, 9.9, 31.0, 26.5, 32.6, 0.0, 19.1, 29.6, 25.6, 25.7),
                unknown = c(rep(30,5), rep(40,5), rep(27,5)))

p1 <- ggplot(data, aes(fill=model, y=value, x=year)) +
  geom_bar(stat='identity', position = position_fill(reverse = TRUE)) +
  scale_fill_grey(start=0.8, end=0.2) +
  theme_bw() +
  ggtitle('Model') +
  xlab('') + ylab('') +
  theme(legend.position="bottom",
        plot.title = element_text(hjust = 0.5),
        legend.title=element_blank(),
        text = element_text(family = "serif")
  ) +
  scale_y_continuous(labels = percent_format(scale = 100)) +
  scale_x_discrete(limits = rev(levels(data$year))) +
  coord_flip()
p1

In the plot below I have manually (outside of R) added the labels in order to clarify the question.


问:
Parsing tagless text regex / BB codes - PHP
I'm working on a BB codes project using preg_replaces/matches aka regex, now i'm faced with a problem dont really now where to go from here: i want to encapsulate all empty text fields using paragraph elements,

Example structure

```<code>[article]
 Lorem ipsum dolor sit amet consectetur adipisicing elit. Distinctio nihil excepturi quo impedit, beatae neque repudiandae temporibus sit rerum ullam.</p>
[table=lorem, lorem, lorem]
[table-item]loremA, loremB, loremC[/table-item]
[table-item]loremD, loremE, loremF[/table-item]
[/table]
Lorem ipsum dolor sit amet consectetur adipisicing elit. Distinctio nihil excepturi quo impedit, beatae neque repudiandae temporibus sit rerum ullam.
[/article]
</code>```

so it would become something  like:

```<code>[article]
 <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Distinctio nihil excepturi quo impedit, beatae neque repudiandae temporibus sit rerum ullam.</p>
[table=lorem, lorem, lorem]
[table-item]loremA, loremB, loremC[/table-item]
[table-item]loremD, loremE, loremF[/table-item]
[/table]
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Distinctio nihil excepturi quo impedit, beatae neque repudiandae temporibus sit rerum ullam.</p>
[/article]
</code>```

答: ^([^\[].*?[^]])$ - Match all lines that does not start with [ and does not end with ]: Example

Body:
I'm working on a BB codes project using preg_replaces/matches aka regex, now i'm faced with a problem dont really now where to go from here: i want to encapsulate all empty text fields using paragraph elements,

Example structure

[article]
 Lorem ipsum dolor sit amet consectetur adipisicing elit. Distinctio nihil excepturi quo impedit, beatae neque repudiandae temporibus sit rerum ullam.

[table=lorem, lorem, lorem]
[table-item]loremA, loremB, loremC[/table-item]
[table-item]loremD, loremE, loremF[/table-item]
[/table]
Lorem ipsum dolor sit amet consectetur adipisicing elit. Distinctio nihil excepturi quo impedit, beatae neque repudiandae temporibus sit rerum ullam.
[/article]

so it would become something  like:

[article]

Lorem ipsum dolor sit amet consectetur adipisicing elit. Distinctio nihil excepturi quo impedit, beatae neque repudiandae temporibus sit rerum ullam.

[table=lorem, lorem, lorem]
[table-item]loremA, loremB, loremC[/table-item]
[table-item]loremD, loremE, loremF[/table-item]
[/table]

Lorem ipsum dolor sit amet consectetur adipisicing elit. Distinctio nihil excepturi quo impedit, beatae neque repudiandae temporibus sit rerum ullam.

[/article]


问:
Universal typescript npm module
I am modifying an existing library so it can be imported in typescript. I've boiled it down to a Minimal working example

The requirements

To remain backwards compatible, the library needs to be importable with a simple
<script>
    var a = new Lib({message:"message here"});
</script>
```
<p>It works. So far so good.</p>
<h3>In another typescript project</h3>
<p>Next, I created a simple typescript project that utilizes my library.</p>
<p>File structure:</p>
```│   gulpfile.js
│   package.json
│   tsconfig.json
│   yarn.lock
│
├───dist
│       index.html
│
└───Scripts
        Index.ts
```
<p>In <code>package.json</code> I include my library as a dependency, along with jQuery to hopefully rule out improper configuration of this project:</p>
<pre class="lang-json prettyprint-override"><code>{
    "private": true,
    "version": "1.0.0",
    "scripts": {
        "preinstall": "npx use-yarn",
        "gulp": "node_modules/.bin/gulp"
    },
    "name": "ts-import",
    "devDependencies": {
        "@types/jquery": "^3.5.13",
        "gulp": "^4.0.2",
        "gulp-browserify": "^0.5.1",
        "gulp-clean": "^0.4.0",
        "gulp-concat": "^2.6.1",
        "gulp-sourcemaps": "^3.0.0",
        "gulp-typescript": "^6.0.0-alpha.1",
        "gulp-uglify": "^3.0.2",
        "typescript": "^4.5.5",
        "vinyl-source-stream": "^2.0.0"
    },
    "dependencies": {
        "jquery": "*",
        "library": "file:../../library"
    }
}
</code>```

tsconfig.json:

{
    "compilerOptions": {
        "noEmitOnError": true,
        "noImplicitAny": true,
        "sourceMap": true,
        "target": "es5",
        "moduleResolution": "node",
        "outDir":"./js"
    },
    "compileOnSave": true,
    "exclude": [
        "**/node_modules/**"
    ],
    "include":[
        "./Scripts"
    ]
}
```
<p>I'm using gulp to compile ts and resolve imports - <code>gulpfile.js</code>:</p>
<pre class="lang-js prettyprint-override"><code>const gulp = require('gulp');
const {series} = require('gulp');
const clean = require('gulp-clean');
const ts = require('gulp-typescript');
const sourcemaps = require('gulp-sourcemaps');
const browserify = require('gulp-browserify');
const concat = require('gulp-concat');
const uglify = require('gulp-uglify');

function cleanAll(cb) {
  return gulp.src([
      "./tmp/",
      "./dist/js"
    ], { read: false, allowEmpty: true })
    .pipe(clean());
}

function transpileTS() {
  const tsproject = ts.createProject('./tsconfig.json');
  return tsproject
      .src()
      .pipe(sourcemaps.init())
      .pipe(tsproject()).js
      .pipe(sourcemaps.write('./sourcemaps'))
      .pipe(gulp.dest('./tmp/js'));
}

function minJS() {
  return gulp
      .src('./tmp/js/Index.js')
      .pipe(sourcemaps.init({ loadMaps: true }))
      .pipe(browserify())
    //   .pipe(uglify())
      .pipe(concat('index.min.js'))
      .pipe(sourcemaps.write('./sourcemaps'))
      .pipe(gulp.dest('./dist/js'))
}

exports.default = series( cleanAll, transpileTS, minJS );
</code>```

I'm importing and using my library like this - Scripts/Index.ts:

```<code>import * as $ from "jquery";
import Lib from "library";

$(()=>{
    console.log("creating lib instance.");
    new Lib({message:"example message here"});
});
</code>```

But when I launch this in a browser - dist/index.html:

```<code>
</code>```

I get an error:

```<code>Uncaught TypeError: library_1.default is not a constructor
</code>```

Indeed, library_1.default doesn't exist, library_1 does though:

> library_1
< class Lib {
        constructor(options) {
            console.log("It works!");
            console.log(options.message);
        }
    }
```

How do I fix this? I suspect the error is somewhere in the library, but I have no idea where.

答:
I've figured it out.
In my lib.ts I had to change the way I export my class:

import Options from "./options";

class Lib{
    constructor(options:Options){
        console.log("It works!");
        console.log(options.message);
    }
}

export default Lib;
```
<p>Next, I changed <code>rollup.config.js</code> (added <code>exports:'default'</code>) to keep the exported class global:</p>
<pre class="lang-js prettyprint-override"><code>...
{
      file: 'dist/lib.umd.js',
      format: 'umd',
      name: 'Lib',
      exports:'default'
},
...
</code>```

I also had to change the library's package.json - I pointed main to my es module as it looks like browserify just ignores the module directive.

I also ended up removing the exports section as some of our other projects (not using browserify) kept using the require file, not the import one:

{
  "name": "library",
  "version": "1.0.16",
  "description": "example library",
  "main": "dist/lib.esm.js",
  "module":"dist/lib.esm.js",
  "types":"dist/types/lib.d.ts",
  "license": "MIT",
  "private": true,
  "devDependencies": {
    "@rollup/plugin-typescript": "^8.3.0",
    "rollup": "^2.67.0",
    "tslib": "^2.3.1",
    "typescript": "^4.5.5"
  },
  "exports": {
    "import": "./dist/lib.esm.js",
    "require": "./dist/lib.umd.js"
  },
  "scripts": {
    "build": "rollup -c rollup.config.js"
  }
}
```

Finally, I had to use babelify in my consumer project to avoid ParseError: 'import' and 'export' may appear only with 'sourceType: module' while running browserify.

The full source is available here

Title: Universal typescript npm module

Body:
I am modifying an existing library so it can be imported in typescript. I've boiled it down to a Minimal working example

The requirements

To remain backwards compatible, the library needs to be importable with a simple

It works. So far so good.

In another typescript project

Next, I created a simple typescript project that utilizes my library.

File structure:

│   gulpfile.js
│   package.json
│   tsconfig.json
│   yarn.lock
│
├───dist
│       index.html
│
└───Scripts
        Index.ts

In package.json I include my library as a dependency, along with jQuery to hopefully rule out improper configuration of this project:

{
    "private": true,
    "version": "1.0.0",
    "scripts": {
        "preinstall": "npx use-yarn",
        "gulp": "node_modules/.bin/gulp"
    },
    "name": "ts-import",
    "devDependencies": {
        "@types/jquery": "^3.5.13",
        "gulp": "^4.0.2",
        "gulp-browserify": "^0.5.1",
        "gulp-clean": "^0.4.0",
        "gulp-concat": "^2.6.1",
        "gulp-sourcemaps": "^3.0.0",
        "gulp-typescript": "^6.0.0-alpha.1",
        "gulp-uglify": "^3.0.2",
        "typescript": "^4.5.5",
        "vinyl-source-stream": "^2.0.0"
    },
    "dependencies": {
        "jquery": "*",
        "library": "file:../../library"
    }
}

tsconfig.json:

{
    "compilerOptions": {
        "noEmitOnError": true,
        "noImplicitAny": true,
        "sourceMap": true,
        "target": "es5",
        "moduleResolution": "node",
        "outDir":"./js"
    },
    "compileOnSave": true,
    "exclude": [
        "**/node_modules/**"
    ],
    "include":[
        "./Scripts"
    ]
}

I'm using gulp to compile ts and resolve imports - gulpfile.js:

const gulp = require('gulp');
const {series} = require('gulp');
const clean = require('gulp-clean');
const ts = require('gulp-typescript');
const sourcemaps = require('gulp-sourcemaps');
const browserify = require('gulp-browserify');
const concat = require('gulp-concat');
const uglify = require('gulp-uglify');

function cleanAll(cb) {
  return gulp.src([
      "./tmp/",
      "./dist/js"
    ], { read: false, allowEmpty: true })
    .pipe(clean());
}

function transpileTS() {
  const tsproject = ts.createProject('./tsconfig.json');
  return tsproject
      .src()
      .pipe(sourcemaps.init())
      .pipe(tsproject()).js
      .pipe(sourcemaps.write('./sourcemaps'))
      .pipe(gulp.dest('./tmp/js'));
}

function minJS() {
  return gulp
      .src('./tmp/js/Index.js')
      .pipe(sourcemaps.init({ loadMaps: true }))
      .pipe(browserify())
    //   .pipe(uglify())
      .pipe(concat('index.min.js'))
      .pipe(sourcemaps.write('./sourcemaps'))
      .pipe(gulp.dest('./dist/js'))
}

exports.default = series( cleanAll, transpileTS, minJS );

I'm importing and using my library like this - Scripts/Index.ts:

import * as $ from "jquery";
import Lib from "library";

$(()=>{
    console.log("creating lib instance.");
    new Lib({message:"example message here"});
});

But when I launch this in a browser - dist/index.html:

I get an error:

Uncaught TypeError: library_1.default is not a constructor

Indeed, library_1.default doesn't exist, library_1 does though:

> library_1
< class Lib {
        constructor(options) {
            console.log("It works!");
            console.log(options.message);
        }
    }

How do I fix this? I suspect the error is somewhere in the library, but I have no idea where.

Body:
I've figured it out.
In my lib.ts I had to change the way I export my class:

import Options from "./options";

class Lib{
    constructor(options:Options){
        console.log("It works!");
        console.log(options.message);
    }
}

export default Lib;

Next, I changed rollup.config.js (added exports:'default') to keep the exported class global:

...
{
      file: 'dist/lib.umd.js',
      format: 'umd',
      name: 'Lib',
      exports:'default'
},
...

I also had to change the library's package.json - I pointed main to my es module as it looks like browserify just ignores the module directive.

I also ended up removing the exports section as some of our other projects (not using browserify) kept using the require file, not the import one:

{
  "name": "library",
  "version": "1.0.16",
  "description": "example library",
  "main": "dist/lib.esm.js",
  "module":"dist/lib.esm.js",
  "types":"dist/types/lib.d.ts",
  "license": "MIT",
  "private": true,
  "devDependencies": {
    "@rollup/plugin-typescript": "^8.3.0",
    "rollup": "^2.67.0",
    "tslib": "^2.3.1",
    "typescript": "^4.5.5"
  },
  "exports": {
    "import": "./dist/lib.esm.js",
    "require": "./dist/lib.umd.js"
  },
  "scripts": {
    "build": "rollup -c rollup.config.js"
  }
}

Finally, I had to use babelify in my consumer project to avoid ParseError: 'import' and 'export' may appear only with 'sourceType: module' while running browserify.

The full source is available here


问:
nextjs: TypeError: Cannot read properties of null (reading 'push')
I use sweetalert2 to show popups:

```<code>export default function Home() {
    const MySwal = withReactContent(Swal)

    useEffect(() => {
        MySwal.fire({
            showConfirmButton: false,
            customClass: {
                container: "swalPopup"
            },
            html:<Link href={"/profile/dashboard"}><a>TEST</a></Link>,
        })
    }, []);

    return ('<div>Home</div>')
}
</code>```

After a popup is shown, I click on TEST and I get the following error:

```<code>Unhandled Runtime Error
TypeError: Cannot read properties of null (reading 'push')

Call Stack
linkClicked
node_modules/next/dist/client/link.js (50:11)
onClick
node_modules/next/dist/client/link.js (200:16)
</code>```

Without sweetalert2, <Link> it works fine otherwise I get the error.

答:
Please try one of these:

```<code><Button type="button" onClick={(e) => router.push('/profile/dashboard')}>
    Test
</Button>
</code>```

or

```<code><Link href="/">
    <a onClick={(e) => handleClick(e, "//profile/dashboard")}>Test</a>
</Link>```

```

Body:
I use sweetalert2 to show popups:

export default function Home() {
    const MySwal = withReactContent(Swal)

    useEffect(() => {
        MySwal.fire({
            showConfirmButton: false,
            customClass: {
                container: "swalPopup"
            },
            html:<Link href={"/profile/dashboard"}>TEST</Link>,
        })
    }, []);

    return ('
Home
')
}

After a popup is shown, I click on TEST and I get the following error:

Unhandled Runtime Error
TypeError: Cannot read properties of null (reading 'push')

Call Stack
linkClicked
node_modules/next/dist/client/link.js (50:11)
onClick
node_modules/next/dist/client/link.js (200:16)

Without sweetalert2, <Link> it works fine otherwise I get the error.

Body:
Please try one of these:

<Button type="button" onClick={(e) => router.push('/profile/dashboard')}>
    Test
</Button>

or

<Link href="/">
    <a onClick={(e) => handleClick(e, "//profile/dashboard")}>Test</a>
</Link>```


问:
Cannot push strings set by variable to Javascript array
I want to loop id's of select/option elements and store the selected options text into an array which doesn't work this way:

```<code>function jsGetSelectedOptionText(optionID) {

    var otext = [];
    var oid;

    optionID.forEach(function(id,i) {

        oid = d3.select('#' + id).node();
        var t = oid.options[oid.selectedIndex].text;
        console.log(typeof(t), t);
        otext.push(t);
    });

    console.log(otext);

    return(otext);
}
</code>```

I can see the type (string) and the text print out by console.log, but otext remains empty.
What's wrong here?

答:
You can select the option directly with a selector and read the textContent of the element.

const id = 's1';
console.log(d3.select('#' + id + ' option:checked').node().textContent);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.3.0/d3.min.js" integrity="sha512-NMhzM2RHzbCRO0s5VPaRC+2bW6nmNXimzC9p5sp2x19M+zzuSJ2T50dEQ7hpHkNjnX1mt8nQg1NNthwRZgsoIg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<select class="foo" id="s1">
<option>Hello 1-1 </option>
<option selected>Hello 1-2</option>
</select></code>```

If all of your selects have a common class you can just use one selector

const allSelectedText = Array.from(d3.selectAll('select.foo  option:checked')).map(opt => opt.textContent);

console.log(allSelectedText);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.3.0/d3.min.js" integrity="sha512-NMhzM2RHzbCRO0s5VPaRC+2bW6nmNXimzC9p5sp2x19M+zzuSJ2T50dEQ7hpHkNjnX1mt8nQg1NNthwRZgsoIg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<select class="foo">
<option>Hello 1-1 </option>
<option selected>Hello 1-2</option>
</select>

<select class="foo">
<option>Hello 2-1</option>
<option>Hello 2-2</option>
</select>

<select class="foo">
<option>Hello 3-1</option>
<option>Hello 3-1</option>
</select></code>```

Body:
I want to loop id's of select/option elements and store the selected options text into an array which doesn't work this way:

function jsGetSelectedOptionText(optionID) {

    var otext = [];
    var oid;

    optionID.forEach(function(id,i) {

        oid = d3.select('#' + id).node();
        var t = oid.options[oid.selectedIndex].text;
        console.log(typeof(t), t);
        otext.push(t);
    });

    console.log(otext);

    return(otext);
}

I can see the type (string) and the text print out by console.log, but otext remains empty.
What's wrong here?

Body:
You can select the option directly with a selector and read the textContent of the element.

const id = 's1';
console.log(d3.select('#' + id + ' option:checked').node().textContent);

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.3.0/d3.min.js" integrity="sha512-NMhzM2RHzbCRO0s5VPaRC+2bW6nmNXimzC9p5sp2x19M+zzuSJ2T50dEQ7hpHkNjnX1mt8nQg1NNthwRZgsoIg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<select class="foo" id="s1">
<option>Hello 1-1 </option>
<option selected>Hello 1-2</option>
</select>

If all of your selects have a common class you can just use one selector

const allSelectedText = Array.from(d3.selectAll('select.foo  option:checked')).map(opt => opt.textContent);

console.log(allSelectedText);

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.3.0/d3.min.js" integrity="sha512-NMhzM2RHzbCRO0s5VPaRC+2bW6nmNXimzC9p5sp2x19M+zzuSJ2T50dEQ7hpHkNjnX1mt8nQg1NNthwRZgsoIg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<select class="foo">
<option>Hello 1-1 </option>
<option selected>Hello 1-2</option>
</select>

<select class="foo">
<option>Hello 2-1</option>
<option>Hello 2-2</option>
</select>

<select class="foo">
<option>Hello 3-1</option>
<option>Hello 3-1</option>
</select>


问:
Elasticsearch ILM rollover - Start the index from 00001 for every new date
I have a ILM policy which rollover lets say after "max_docs": 15000. Meaning rollover the index once the docs.count reaches to 15000.

{
    "policy": {
        "phases": {
            "hot": {
                "actions": {
                    "rollover": {
                        "max_docs": 15000
                    }
                }
            },
            "delete": {
                "min_age": "1d",
                "actions": {
                    "delete": {}
                }
            }
        }
    }
}
```
<p>Rollover is also happening when I bootstrap the initial index <code>index-2022-07-02-00001</code> and appending the new date for next date to the index like :</p>
```index-2022-07-02-00002
index-2022-08-02-00003
index-2022-08-02-00004
```
<p>and so.</p>
<p>Now I want to create the new index for each day but the index pattern should also start from <code>00001</code> meaning :</p>
```index-2022-07-02-00001
index-2022-07-02-00002
index-2022-08-02-00001 - For next day the pattern (00001) should be applied instead of (00003)
```

Please suggest a way to apply this kind of pattern.

答:
I'm sorry but I think this can't be done.

The ILM pattern we have is:
ilm_pattern => "{now/d}-00001"

This number is always increased by one, no matter what comes before.

Body:
I have a ILM policy which rollover lets say after "max_docs": 15000. Meaning rollover the index once the docs.count reaches to 15000.

{
    "policy": {
        "phases": {
            "hot": {
                "actions": {
                    "rollover": {
                        "max_docs": 15000
                    }
                }
            },
            "delete": {
                "min_age": "1d",
                "actions": {
                    "delete": {}
                }
            }
        }
    }
}

Rollover is also happening when I bootstrap the initial index index-2022-07-02-00001 and appending the new date for next date to the index like :

index-2022-07-02-00002
index-2022-08-02-00003
index-2022-08-02-00004

and so.

Now I want to create the new index for each day but the index pattern should also start from 00001 meaning :

index-2022-07-02-00001
index-2022-07-02-00002
index-2022-08-02-00001 - For next day the pattern (00001) should be applied instead of (00003)

Please suggest a way to apply this kind of pattern.


问:
git clone: Authentication failed for <URL>
Trying to access private corporate tfs.
They gave me access by giving appropriate rights to windows user (domain\login).

I'm fine with accessing web interface of tfs, browse repository and stuff.

But when I try to run

```<code> git clone https://tfs.somehostname.com/tfs/somefolder/_git/therepository
</code>```

It fails with

```<code>Cloning into 'therepository'...

fatal: Authentication failed for 'https://tfs.somehostname.com/tfs/somefolder/_git/therepository/'
</code>```

Tried with home pc without corporate network stuff - same error.

Tried in PowerShell, Git Bash, Clone via VisualStudio - same error.

SSH is closed (gave request timeout).

Web & Git both ask for credentials once (tried deleting in Credentials Manager - asks again, after submitting web is fine, git fails)

Corporate helper tried to help, but all he gave is tfs logs.
He says, my username doesn't come with requests (tracked by syncing my attempts timestamps with logs).

```<code>2018-07-19 07:04:00 SOMEIP GET /tfs/SOMEFOLDER/_git/REPOSITORY/info/refs service=git-upload-pack 443 - ANOTHERIP git/2.12.2+(Microsoft+Windows+NT+6.3.9600.0;+Win32NT+x64)+CLR/4.0.30319+VS15/15.0.0 - 401 2 5 62
2018-07-19 07:23:00 SOMEIP GET /tfs/SOMEFOLDER/_git/REPOSITORY/info/refs service=git-upload-pack 443 - ANOTHERIP git/2.18.0.windows.1 - 401 2 5 62
2018-07-19 07:23:00 SOMEIP GET /tfs/SOMEFOLDER/_git/REPOSITORY/info/refs service=git-upload-pack 443 - ANOTHERIP git/2.18.0.windows.1 - 401 1 3221225581 187
</code>```

while others include it

```<code>2018-07-19 05:44:27 SOMEIP GET /tfs/SOMEFOLDER/_git/REPOSITORY/info/refs service=git-upload-pack 443 DOMAIN\LOGIN ANOTHERIP git/2.12.2+(Microsoft+Windows+NT+6.1.7601+Service+Pack+1;+Win32NT+x64)+CLR/4.0.30319+VS15/15.0.0 - 200 0 0 265
</code>```

答:
For the new comers,

Upvoted answers are not the answers anymore since,

remote: Support for password authentication was removed on August 13,
2021. Please use a personal access token instead.
remote: Please see https://github.blog/2020-12-15-token-authentication-requirements-for-git-operations/
for more information.

And no need to repeat the access token replies, go and follow them.

Body:
Trying to access private corporate tfs.
They gave me access by giving appropriate rights to windows user (domain\login).

I'm fine with accessing web interface of tfs, browse repository and stuff.

But when I try to run

 git clone https://tfs.somehostname.com/tfs/somefolder/_git/therepository

It fails with

Cloning into 'therepository'...

fatal: Authentication failed for 'https://tfs.somehostname.com/tfs/somefolder/_git/therepository/'

Tried with home pc without corporate network stuff - same error.

Tried in PowerShell, Git Bash, Clone via VisualStudio - same error.

SSH is closed (gave request timeout).

Web & Git both ask for credentials once (tried deleting in Credentials Manager - asks again, after submitting web is fine, git fails)

Corporate helper tried to help, but all he gave is tfs logs.
He says, my username doesn't come with requests (tracked by syncing my attempts timestamps with logs).

2018-07-19 07:04:00 SOMEIP GET /tfs/SOMEFOLDER/_git/REPOSITORY/info/refs service=git-upload-pack 443 - ANOTHERIP git/2.12.2+(Microsoft+Windows+NT+6.3.9600.0;+Win32NT+x64)+CLR/4.0.30319+VS15/15.0.0 - 401 2 5 62
2018-07-19 07:23:00 SOMEIP GET /tfs/SOMEFOLDER/_git/REPOSITORY/info/refs service=git-upload-pack 443 - ANOTHERIP git/2.18.0.windows.1 - 401 2 5 62
2018-07-19 07:23:00 SOMEIP GET /tfs/SOMEFOLDER/_git/REPOSITORY/info/refs service=git-upload-pack 443 - ANOTHERIP git/2.18.0.windows.1 - 401 1 3221225581 187

while others include it

2018-07-19 05:44:27 SOMEIP GET /tfs/SOMEFOLDER/_git/REPOSITORY/info/refs service=git-upload-pack 443 DOMAIN\LOGIN ANOTHERIP git/2.12.2+(Microsoft+Windows+NT+6.1.7601+Service+Pack+1;+Win32NT+x64)+CLR/4.0.30319+VS15/15.0.0 - 200 0 0 265


问:
How do I use SQL count with group by causing an error
Here is my code

```<code>SELECT
(SELECT count(*) WHERE status_id = @TO) as 'TO' ,
(SELECT count(*) WHERE status_id = @RO)as 'RO' ,
(SELECT count(*) WHERE status_id = @AO)as 'AO',
(SELECT count(*) WHERE status_id = @IO)as 'IP',
(SELECT count(*) WHERE status_id = @SO)as 'SO',
          created_user
      FROM
          table1
      GROUP BY
          created_user
</code>```

Now i'm getting the following error

Column 'status_id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

I don't want to group by status_id, how to fix this issue?

答:
I guess you can try to use conditional aggregation</p>
```<code> SELECT created_user,
  SUM
  (
     CASE
        WHEN status_id = @TO THEN 1 ELSE 0 END
  )AS 'TO',
 SUM
  (
    CASE
      WHEN status_id = @RO THEN 1 ELSE 0 END
 )AS 'RO'
FROM table1
  GROUP BY created_user
</code>```

Body:
Here is my code

SELECT
(SELECT count(*) WHERE status_id = @TO) as 'TO' ,
(SELECT count(*) WHERE status_id = @RO)as 'RO' ,
(SELECT count(*) WHERE status_id = @AO)as 'AO',
(SELECT count(*) WHERE status_id = @IO)as 'IP',
(SELECT count(*) WHERE status_id = @SO)as 'SO',
          created_user
      FROM
          table1
      GROUP BY
          created_user

Now i'm getting the following error

Column 'status_id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

I don't want to group by status_id, how to fix this issue?

Body:
I guess you can try to use conditional aggregation

 SELECT created_user,
  SUM
  (
     CASE
        WHEN status_id = @TO THEN 1 ELSE 0 END
  )AS 'TO',
 SUM
  (
    CASE
      WHEN status_id = @RO THEN 1 ELSE 0 END
 )AS 'RO'
FROM table1
  GROUP BY created_user


问:
Make image just fit to a text
I'm using PHP GD and trying to draw a text and make the image size
just fit to the text.

I found this question and tried Martin Geisler's code.

Resize image size according to size of text

It looked work fine, but when I tried other texts, some got out of the image.

Of course, I could add extra padding, but required padding depends on the text.
That's too ad-hock.

Does anyone know proper way to do this?

Thanks in advance.

```<code>// Martin Geisler's version using MS Gothic
header("Content-type: image/png");

$q     = 'Image example';
$font  = './msgothic.ttc';  // MS Gothic
$size  = 30;
$bbox   = imageftbbox($size, 0, $font, $q);

$width  = $bbox[2] - $bbox[6];
$height = $bbox[3] - $bbox[7];

$im    = imagecreatetruecolor($width, $height);
$green = imagecolorallocate($im, 60, 240, 60);

imagefttext($im, $size, 0, -$bbox[6], -$bbox[7], $green, $font, $q);
imagepng($im);
imagedestroy($im);
</code>```

http://www.betatechnology.jp/~ao/imageexample.png

答:
This is an issue related to the width of the text you are writing.
3 i's are smaller than 3 o's unless you are using fixed font.

Instead of trying to create an image that has the exact right proportions I would rather make it big enough and then crop out the unused space around it.

Since you create the image, you can make the border a solid color and then crop it.
See this here for an instruction on how to do the cropping:

Crop whitespace from image in PHP

Title: Make image just fit to a text

Body:
I'm using PHP GD and trying to draw a text and make the image size
just fit to the text.

I found this question and tried Martin Geisler's code.

Resize image size according to size of text

It looked work fine, but when I tried other texts, some got out of the image.

Of course, I could add extra padding, but required padding depends on the text.
That's too ad-hock.

Does anyone know proper way to do this?

Thanks in advance.

// Martin Geisler's version using MS Gothic
header("Content-type: image/png");

$q     = 'Image example';
$font  = './msgothic.ttc';  // MS Gothic
$size  = 30;
$bbox   = imageftbbox($size, 0, $font, $q);

$width  = $bbox[2] - $bbox[6];
$height = $bbox[3] - $bbox[7];

$im    = imagecreatetruecolor($width, $height);
$green = imagecolorallocate($im, 60, 240, 60);

imagefttext($im, $size, 0, -$bbox[6], -$bbox[7], $green, $font, $q);
imagepng($im);
imagedestroy($im);

http://www.betatechnology.jp/~ao/imageexample.png


问:
Kivy ScrollView is not able to scroll
This is the .py file:

```<code>from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.scrollview import ScrollView
from kivy.uix.stacklayout import StackLayout

class Stack(StackLayout):
    def __init__(self,**kwargs):
        super().__init__(**kwargs)
        for i in range(0,100):
            b1 = Button(text=str(i+1),size_hint=(.1,.1))
            self.add_widget(b1)

class ScrollView(ScrollView):
    pass

class GameApp(App):
    def build(self):
        return Stack()

GameApp().run()
</code>```

And this is the .kV file:

```<code><ScrollView>:
        Stack:
                size_hint:1,None
                height:4000
</code>```

In the output I am getting the buttons but I am unable to scroll.

答:
Hello if you are new please check this link for beginners guide.

The ScrollView only works if you put 1 widget on it with specific adjustments to size ofcourse.

Instead of this line

```<code>return stack()
</code>```

You must return the scrollview widget and add the stack() layout on top. Even better you can modify your code like so

For .py

```<code>from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.scrollview import ScrollView
from kivy.uix.stacklayout import StackLayout
from kivy.uix.screenmanager import Screen

class MainScreen(Screen):
    pass

class Stack(StackLayout):
    def __init__(self,**kwargs):
        super().__init__(**kwargs)
        for i in range(0,100):
            b1 = Button(text=str(i+1),size_hint=(.1,.1))
            self.add_widget(b1)

class GameApp(App):
    def build(self):
        return MainScreen()

GameApp().run()
</code>```

.kv

```<code><MainScreen>:
    ScrollView:
        do_scroll_y: True
        do_scroll_y: False
        Stack:
                size_hint:1,None
                height:4000
</code>```

I did not test the code but thats the logic of how the code can be. The rest you can check here

Title: Kivy ScrollView is not able to scroll

Body:
This is the .py file:

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.scrollview import ScrollView
from kivy.uix.stacklayout import StackLayout

class Stack(StackLayout):
    def __init__(self,**kwargs):
        super().__init__(**kwargs)
        for i in range(0,100):
            b1 = Button(text=str(i+1),size_hint=(.1,.1))
            self.add_widget(b1)

class ScrollView(ScrollView):
    pass

class GameApp(App):
    def build(self):
        return Stack()

GameApp().run()

And this is the .kV file:

<ScrollView>:
        Stack:
                size_hint:1,None
                height:4000

In the output I am getting the buttons but I am unable to scroll.

Body:
Hello if you are new please check this link for beginners guide.

The ScrollView only works if you put 1 widget on it with specific adjustments to size ofcourse.

Instead of this line

return stack()

You must return the scrollview widget and add the stack() layout on top. Even better you can modify your code like so

For .py

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.scrollview import ScrollView
from kivy.uix.stacklayout import StackLayout
from kivy.uix.screenmanager import Screen

class MainScreen(Screen):
    pass

class Stack(StackLayout):
    def __init__(self,**kwargs):
        super().__init__(**kwargs)
        for i in range(0,100):
            b1 = Button(text=str(i+1),size_hint=(.1,.1))
            self.add_widget(b1)

class GameApp(App):
    def build(self):
        return MainScreen()

GameApp().run()

.kv

<MainScreen>:
    ScrollView:
        do_scroll_y: True
        do_scroll_y: False
        Stack:
                size_hint:1,None
                height:4000

I did not test the code but thats the logic of how the code can be. The rest you can check here