问:
DateTime is described with 11 bytes in MySQL - Document says 5 bytes - How to interpret first bytes and last bytes
I have a DATETIME cell in MySQL 8.0. It has the value 2022-12-08 20:43:45.787.

When I read the cell in MySQL C++ Connector 8.0, then I get these bytes.

My first conclusion is that byte 2 must be month, byte 3 must be date, byte 4 must be hour in UTC, byte 5 must be minute and byte 6 must be seconds.

Question:

How can I create the year 2022 from byte 0 and byte 1?
I think it has to be that the year is 12-bit, because 15 is 0xf = 4 bits. If I want to send 12-bits as 2 bytes. I need to first shift 4 bits of 12-bits.

```<code>12bits >> 4 = 8bits
</code>```

So if I reconstruct the 12-bit year, then it would be...well I tried...

```<code>15 << 8 | 230 = 4070
</code>```

How can I create the milliseconds 787 from byte 7 to byte 10?

The code for reading the MySQL Database. Notice that this is the latest MySQL Connector for C++. Not the legacy C++ connector.

```<code>std::vector<std::vector<std::string>> getDatabaseValues(const char tableName[]) {
    std::vector<std::string> values;
    std::vector<std::vector<std::string>> table;
    if (isConnectedToDatabase()) {
        // Select only the first row
        std::string query = "SELECT * FROM " + std::string(tableName);
        mysqlx::SqlResult result = connection->sql(query).execute();
        int columnCount = result.getColumnCount();
        if (result.hasData()) {
            mysqlx::Row row;
            while (row = result.fetchOne()) {
                for (int i = 0; i < columnCount; i++) {
                    switch (row[i].getType()) {
                    case mysqlx::common::Value::UINT64:
                        values.push_back(std::to_string(row[i].get<uint64_t>()));
                        break;
                    case mysqlx::common::Value::INT64:
                        values.push_back(std::to_string(row[i].get<int64_t>()));
                        break;
                    case mysqlx::common::Value::FLOAT:
                        values.push_back(std::to_string(row[i].get<float>()));
                        break;
                    case mysqlx::common::Value::STRING:
                        values.push_back(row[i].get<std::string>());
                        break;
                    case mysqlx::common::Value::RAW:
                        mysqlx::bytes data = row[i].getRawBytes();
                        const mysqlx::byte* first = data.begin();
                        std::vector<int> a;
                        for (int i = 0; i < data.length(); i++)
                            a.push_back(first[i]);
                        a;
                        int month = first[2];
                        int date = first[3];
                        int hour = first[4];
                        int minute = first[5];
                        int second = first[6];

                        values.push_back("YYYY-MM-DDTHH:MM:SS:sss");
                        break;
                    }
                }
                table.push_back(values);
                values.clear();
            }
        }
    }
    return table;
}
</code>```

According to the documentation,

https://dev.mysql.com/doc/refman/8.0/en/storage-requirements.html

Body:
I have a DATETIME cell in MySQL 8.0. It has the value 2022-12-08 20:43:45.787.

When I read the cell in MySQL C++ Connector 8.0, then I get these bytes.

My first conclusion is that byte 2 must be month, byte 3 must be date, byte 4 must be hour in UTC, byte 5 must be minute and byte 6 must be seconds.

Question:

How can I create the year 2022 from byte 0 and byte 1?
I think it has to be that the year is 12-bit, because 15 is 0xf = 4 bits. If I want to send 12-bits as 2 bytes. I need to first shift 4 bits of 12-bits.

12bits >> 4 = 8bits

So if I reconstruct the 12-bit year, then it would be...well I tried...

15 << 8 | 230 = 4070

How can I create the milliseconds 787 from byte 7 to byte 10?

The code for reading the MySQL Database. Notice that this is the latest MySQL Connector for C++. Not the legacy C++ connector.

std::vector<std::vector<std::string>> getDatabaseValues(const char tableName[]) {
    std::vector<std::string> values;
    std::vector<std::vector<std::string>> table;
    if (isConnectedToDatabase()) {
        // Select only the first row
        std::string query = "SELECT * FROM " + std::string(tableName);
        mysqlx::SqlResult result = connection->sql(query).execute();
        int columnCount = result.getColumnCount();
        if (result.hasData()) {
            mysqlx::Row row;
            while (row = result.fetchOne()) {
                for (int i = 0; i < columnCount; i++) {
                    switch (row[i].getType()) {
                    case mysqlx::common::Value::UINT64:
                        values.push_back(std::to_string(row[i].get<uint64_t>()));
                        break;
                    case mysqlx::common::Value::INT64:
                        values.push_back(std::to_string(row[i].get<int64_t>()));
                        break;
                    case mysqlx::common::Value::FLOAT:
                        values.push_back(std::to_string(row[i].get<float>()));
                        break;
                    case mysqlx::common::Value::STRING:
                        values.push_back(row[i].get<std::string>());
                        break;
                    case mysqlx::common::Value::RAW:
                        mysqlx::bytes data = row[i].getRawBytes();
                        const mysqlx::byte* first = data.begin();
                        std::vector<int> a;
                        for (int i = 0; i < data.length(); i++)
                            a.push_back(first[i]);
                        a;
                        int month = first[2];
                        int date = first[3];
                        int hour = first[4];
                        int minute = first[5];
                        int second = first[6];

                        values.push_back("YYYY-MM-DDTHH:MM:SS:sss");
                        break;
                    }
                }
                table.push_back(values);
                values.clear();
            }
        }
    }
    return table;
}

According to the documentation,

https://dev.mysql.com/doc/refman/8.0/en/storage-requirements.html


来源: stackexchange

问:
In gitlab ci , how can we add the test report for npm test
My jest.config.js looks like :

```<code>module.exports = {
  moduleFileExtensions: ['mock.js', 'ts', 'tsx', 'js', 'jsx', 'json', 'node'],
  moduleNameMapper: {
    '\\.(gif|ttf|eot|png|jpg)$': '<rootDir>/test/__mocks__/mockExportString.js',
  },
  "testResultsProcessor": "<rootDir>/node_modules/jest-html-reporter"
};
</code>```

gitlabci:

artifacts:
expire_in: 1 hour
paths:
- test-build.tar.gz
reports:
junit:
- $CI_PROJECT_DIR/plugins/creative-dispa/test-*.html
when: always

I can see the test report generated but gitlab ci isn't able to follow the HTML report format.

ContentLicense: CC BY-SA 4.0

Body:
My jest.config.js looks like :

module.exports = {
  moduleFileExtensions: ['mock.js', 'ts', 'tsx', 'js', 'jsx', 'json', 'node'],
  moduleNameMapper: {
    '\\.(gif|ttf|eot|png|jpg)$': '<rootDir>/test/__mocks__/mockExportString.js',
  },
  "testResultsProcessor": "<rootDir>/node_modules/jest-html-reporter"
};

gitlabci:

artifacts:
expire_in: 1 hour
paths:
- test-build.tar.gz
reports:
junit:
- $CI_PROJECT_DIR/plugins/creative-dispa/test-*.html
when: always

I can see the test report generated but gitlab ci isn't able to follow the HTML report format.


问:
How to filter @OneToMany child collection in JPA
I wonder if it is possible to filter the child list in a @OneToMany mapping in Spring JPA.

For example, let's say I have a "Manager" entity.

```<code>@Entity
@Table(name = "manager")
data class Manager(

 @Id
 @Type(type = "pg-uuid")
 @Column
 var id: UUID = UUID.randomUUID(),

 @JsonManagedReference
 @OneToMany(mappedBy = "manager", cascade = [CascadeType.ALL], orphanRemoval = true)
 var employees: List<Employee> = listOf()

)
</code>```

and an "Employee" entity

```<code>@Entity
@Table(name = "employee")
data class Employee(

var firstName: String,

var lastName: String,

var startDate: OffsetDateTime

@JsonBackReference
@ManyToOne
@JoinColumn(name = "manager_id")
var manager: Manager,

)
</code>```

Is it possible to retrieve a list of "Managers" who have a list of "Employees" attached to them that begin before or after a certain startDate?

I don't want to retrieve the list of "Managers" and all their "Employees" and then apply the filter.

I expect a list of managers to have a filtered list of employees attached to them after querying the database.

Body:
I wonder if it is possible to filter the child list in a @OneToMany mapping in Spring JPA.

For example, let's say I have a "Manager" entity.

@Entity
@Table(name = "manager")
data class Manager(

 @Id
 @Type(type = "pg-uuid")
 @Column
 var id: UUID = UUID.randomUUID(),

 @JsonManagedReference
 @OneToMany(mappedBy = "manager", cascade = [CascadeType.ALL], orphanRemoval = true)
 var employees: List<Employee> = listOf()

)

and an "Employee" entity

@Entity
@Table(name = "employee")
data class Employee(

var firstName: String,

var lastName: String,

var startDate: OffsetDateTime

@JsonBackReference
@ManyToOne
@JoinColumn(name = "manager_id")
var manager: Manager,

)

Is it possible to retrieve a list of "Managers" who have a list of "Employees" attached to them that begin before or after a certain startDate?

I don't want to retrieve the list of "Managers" and all their "Employees" and then apply the filter.

I expect a list of managers to have a filtered list of employees attached to them after querying the database.


问:
Dynamic imported class variables in python
I have a setup similar to the following simplified code.

A config module containing variables:

```<code>## _cfg.py

cfg_var1 = 'old_value'
</code>```

A module which has a class with variables:

```<code>## _io.py

import _cfg as cfg

class class1:

    class1_vars = {'var1':cfg.cfg_var1}
</code>```

A script which the user actually interacts with:

```<code>## user.py

import _cfg as cfg
import _io as io

def main():
    cfg.cfg_var1 = 'new_value'

    print(io.class1_vars['var1'])

if __name__ == "__main__":
    main()
</code>```

The trouble is that the io.class1_vars['var1'] in user.py does not reflect the modifications to the cfg.cfg_var1 variable. I understand why this is the case, but can't see a simple way to set this all up to achieve the desired outcome. The _cfg variables have to be modified (they get modified to reflect user input, etc.), and the _io class variables need to depend on the _cfg variables.

I thought of somehow re-declaring the class but I don't want to be in a position of having to know everywhere the _cfg variables are used when I modify them.

Can anyone think of a way to have the class variables look to the current _cfg variables when that class variable is actually used?

Body:
I have a setup similar to the following simplified code.

A config module containing variables:

## _cfg.py

cfg_var1 = 'old_value'

A module which has a class with variables:

## _io.py

import _cfg as cfg

class class1:

    class1_vars = {'var1':cfg.cfg_var1}

A script which the user actually interacts with:

## user.py

import _cfg as cfg
import _io as io

def main():
    cfg.cfg_var1 = 'new_value'

    print(io.class1_vars['var1'])

if __name__ == "__main__":
    main()

The trouble is that the io.class1_vars['var1'] in user.py does not reflect the modifications to the cfg.cfg_var1 variable. I understand why this is the case, but can't see a simple way to set this all up to achieve the desired outcome. The _cfg variables have to be modified (they get modified to reflect user input, etc.), and the _io class variables need to depend on the _cfg variables.

I thought of somehow re-declaring the class but I don't want to be in a position of having to know everywhere the _cfg variables are used when I modify them.

Can anyone think of a way to have the class variables look to the current _cfg variables when that class variable is actually used?


问:
What happens when you apply a label using the Microsoft Information Protection (MIP) SDK?
According to the File Parsing section on the MIP SDK FAQs and known issues page, applying a sensitivity label results in a protected copy of the original being made:

Any labeled files will result in a copy of the input file with the label actions applied.

This raises a few questions:

Does the labeled copy ever touch the filesystem in an unprotected state? For example, does the SDK only begin applying label actions after making a full, unprotected copy of the original?

Does the MIP SDK allocate the disk space required to store an encrypted copy ahead of time (e.g. using fallocate(2) on Linux)?

Is there any risk of leaving behind partially encrypted or corrupted copies if the protecting process is suddenly terminated?

The version release history page also makes mention of a Timeout category of NetworkError:

Category=Timeout: Failed to establish HTTP connection after timeout (retry will probably succeed)

What is the HTTP connection timeout, and is it configurable?


问:
How can I determine if a word is a part of an english word or is a portmanteau (a word created by combining parts of valid English words)?
I am trying to create a validator that takes in words and tries to determine if the word is one of the following:

It is a valid English word

It is a part of an English word

It is an abbreviation

It is a portmanteau -- a word created by concatenating parts of valid English words

Are there Java or Python libraries/frameworks that can perform this task?

Samples of words:  meds, ppg, reauthorization, appmetadata, reconsent, rawlog

I've tried Python NLTK (cursory investigation so far) and a Python library called enchant (this fails to identify many valid words/parts of words and portmanteaus).


问:
Hello. I want to create a Role-Based Access Control in my Login. When I put the following code in the another form it is working but here it's not
this is my code...

roles.id=txtid.getText();

```<code> if((roles.id.equals("admin"))||(roles.id.equals("assistant"))){

       main mn= new main();
       mn.setVisible(true);
    }
     else if(roles.id.equals("user")){
  //      mn.setVisible(false);

        EmpSearch es= new EmpSearch();
        es.setVisible(true);

}

</code>```

I am expecting if the user role is "Admin" or "Assistant" to go the Main Form, but when it is "user" to go the EmpSearch form but the Login form goes and nothing comes.

Body:
this is my code...

roles.id=txtid.getText();

 if((roles.id.equals("admin"))||(roles.id.equals("assistant"))){

       main mn= new main();
       mn.setVisible(true);
    }
     else if(roles.id.equals("user")){
  //      mn.setVisible(false);

        EmpSearch es= new EmpSearch();
        es.setVisible(true);

}

I am expecting if the user role is "Admin" or "Assistant" to go the Main Form, but when it is "user" to go the EmpSearch form but the Login form goes and nothing comes.


问:
.Net MAUI keep app alive in the background without a service - Android
.NET Maui (Android)
I need to keep an app playing music in the background even if it's not focused.

I searched and found most research redirects to use a service.

I do many calculations and I call APIs on regular bases to update the stream so I'm not sure if using a service is the best choice as I need to stay connected with the stream from the app.

I tired to override OnPause as following

```<code>  protected override void OnPause()
    {
        base.OnPause();
    }
</code>```

But not sure if that will do the trick

Body:
.NET Maui (Android)
I need to keep an app playing music in the background even if it's not focused.

I searched and found most research redirects to use a service.

I do many calculations and I call APIs on regular bases to update the stream so I'm not sure if using a service is the best choice as I need to stay connected with the stream from the app.

I tired to override OnPause as following

  protected override void OnPause()
    {
        base.OnPause();
    }

But not sure if that will do the trick


问:
How do I properly "mothball" my company's software?
I work for a small startup that is currently is the process of winding down and shutting it's doors. We're down to a skeleton crew of two developers, myself and one other person. Our COO has asked us what we should do to "mothball" our source code for minimal cost, in case at some point in the future they are able to sell the technology or possibly even give the company another go.

Currently our code is sitting in a bunch of separate private projects in our GitHub repository. My assumption is it could continue to sit there indefinitely, although I'm not sure what costs that would involve.  We could also pull it down and preserve it on a series of hard drives/CDs/whatever. Curious if anyone else has ever gone through this experience and what they did.


问:
How to avoid using System GC in Eclipse
I have bolded what I thought should have resolved the issue. Basically, the bufferreader is not releasing the thread and its causing errors in the rest of my project.
`

```<code>public double fileGame(ArrayList<String> d) {
    System.out.println("file 1");
    String line;
    System.out.println(d.size());

    try {
        Month  Month = LocalDate.now().getMonth();
         String m = Month.toString().substring(0,3);
         System.out.println(m);
         int yr = LocalDate.now().getYear();
         String fin = m+" "+yr;
            Path gamepath = Paths.get(game);
            String dabe = "C:\\Users\OneDrive\\Documents\\financials\\tempread.csv";
            Path read = Paths.get(dabe);
            Files.copy(gamepath, read);
             Path New = Paths.get(dabe);
             Files.deleteIfExists(New);
            Files.copy(gamepath,New);
            BufferedReader br = new BufferedReader(new FileReader(dabe));
            boolean cont = false; //checks if Game id is in paid list
            int i = 0;
            double paidAmount=0;
            while ((line = br.readLine() ) != null) {
                System.out.println(line+"li");
                String[] values = line.split(",");
                System.out.println(values.length+" size") ;
                String id = values[0];
                String date = values[1];
                String loc = values[2];
                Double amount = Double.parseDouble(values[3]);
                String by = values[4];
                String paid = values[5];
                Game g = new Game(id,date,loc,amount,by,paid);
                records.add(g);
                }
            while (i<records.size()&&d.size()>0) {
                System.out.println("Game Paid: "+records.get(i).getEverything());
                if(records.get(i).getId().equals(d.get(0))) {
                    records.get(i).setPaid();
                    paidAmount += records.get(i).getAmount();
                    records.get(i).setPaid();
                    records.get(i).setPaidMonth(fin);
                    System.out.println("Game Paid: "+records.get(i).getEverything());
                    d.remove(0);
                    if(records.size()==0) {
                        break;
                    }
                }
                i++;
            }
            **br.close();**
            Files.delete(read);
            System.out.println("br close");
        //  Files.deleteIfExists(gamepath);
            System.gc();
            fileGame2(records);
            return paidAmount;
    }
            catch (IOException e1) {
                JOptionPane.showMessageDialog(null,e1.getMessage());
                e1.printStackTrace();
            }
</code>```

`

Deleting GC causes a "File is used by another process" at the next instance of me trying to replace the file.

Title: How to avoid using System GC in Eclipse

Body:
I have bolded what I thought should have resolved the issue. Basically, the bufferreader is not releasing the thread and its causing errors in the rest of my project.
`

public double fileGame(ArrayList<String> d) {
    System.out.println("file 1");
    String line;
    System.out.println(d.size());

    try {
        Month  Month = LocalDate.now().getMonth();
         String m = Month.toString().substring(0,3);
         System.out.println(m);
         int yr = LocalDate.now().getYear();
         String fin = m+" "+yr;
            Path gamepath = Paths.get(game);
            String dabe = "C:\\Users\OneDrive\\Documents\\financials\\tempread.csv";
            Path read = Paths.get(dabe);
            Files.copy(gamepath, read);
             Path New = Paths.get(dabe);
             Files.deleteIfExists(New);
            Files.copy(gamepath,New);
            BufferedReader br = new BufferedReader(new FileReader(dabe));
            boolean cont = false; //checks if Game id is in paid list
            int i = 0;
            double paidAmount=0;
            while ((line = br.readLine() ) != null) {
                System.out.println(line+"li");
                String[] values = line.split(",");
                System.out.println(values.length+" size") ;
                String id = values[0];
                String date = values[1];
                String loc = values[2];
                Double amount = Double.parseDouble(values[3]);
                String by = values[4];
                String paid = values[5];
                Game g = new Game(id,date,loc,amount,by,paid);
                records.add(g);
                }
            while (i<records.size()&&d.size()>0) {
                System.out.println("Game Paid: "+records.get(i).getEverything());
                if(records.get(i).getId().equals(d.get(0))) {
                    records.get(i).setPaid();
                    paidAmount += records.get(i).getAmount();
                    records.get(i).setPaid();
                    records.get(i).setPaidMonth(fin);
                    System.out.println("Game Paid: "+records.get(i).getEverything());
                    d.remove(0);
                    if(records.size()==0) {
                        break;
                    }
                }
                i++;
            }
            **br.close();**
            Files.delete(read);
            System.out.println("br close");
        //  Files.deleteIfExists(gamepath);
            System.gc();
            fileGame2(records);
            return paidAmount;
    }
            catch (IOException e1) {
                JOptionPane.showMessageDialog(null,e1.getMessage());
                e1.printStackTrace();
            }

`

Deleting GC causes a "File is used by another process" at the next instance of me trying to replace the file.


问:
How do I pass cookies from HEAD to POST-Request
I need to pass csrf cookies _gorila_csrf and csrf_token from my HEAD-Request to my POST-Request. What is the best practice for that?
For now I get the Cookie Value with res.Cookies() for the two cookies, built the Cookie-Header Value and pass to the next function. Is there any method to pass the real cookie to the next request?

```<code>var c = resp.Cookies()[0].Name+"="+resp.Cookies()[0].Value+";"+resp.Cookies()[1].Name+"="+resp.Cookies()[1].Value
var t = resp.Cookies()[1].Value
</code>```

Is it possible to address the cookie by name in case more cookies are added in the future and the order changes?

Edit - Example (not working because the api url does not response with the right cookies):

```<code>package main

import (
    "fmt"
    "net/http"
    "time"
)

const url = "https://google.com"

func main() {
    client := &http.Client{
        Timeout: time.Second * 5,
    }
    r, _ := http.NewRequest("HEAD", url, nil)
    resp, _ := client.Do(r)

    var c = resp.Cookies()[0].Name + "=" + resp.Cookies()[0].Value + ";" + resp.Cookies()[1].Name + "=" + resp.Cookies()[1].Value
    var t = resp.Cookies()[1].Value

    fmt.Println(c)
    fmt.Println(t)
    }
</code>```

Body:
I need to pass csrf cookies _gorila_csrf and csrf_token from my HEAD-Request to my POST-Request. What is the best practice for that?
For now I get the Cookie Value with res.Cookies() for the two cookies, built the Cookie-Header Value and pass to the next function. Is there any method to pass the real cookie to the next request?

var c = resp.Cookies()[0].Name+"="+resp.Cookies()[0].Value+";"+resp.Cookies()[1].Name+"="+resp.Cookies()[1].Value
var t = resp.Cookies()[1].Value

Is it possible to address the cookie by name in case more cookies are added in the future and the order changes?

Edit - Example (not working because the api url does not response with the right cookies):

package main

import (
    "fmt"
    "net/http"
    "time"
)

const url = "https://google.com"

func main() {
    client := &http.Client{
        Timeout: time.Second * 5,
    }
    r, _ := http.NewRequest("HEAD", url, nil)
    resp, _ := client.Do(r)

    var c = resp.Cookies()[0].Name + "=" + resp.Cookies()[0].Value + ";" + resp.Cookies()[1].Name + "=" + resp.Cookies()[1].Value
    var t = resp.Cookies()[1].Value

    fmt.Println(c)
    fmt.Println(t)
    }


问:
Run Long Function in Background While Updating Log (QTextEdit) for intermittent status updates
I have this GUI that takes in file inputs and processes them. Naturally, this takes a fair amount of time and it would be nice for the user to see what is happening in the background as they wait for the file processing to finish. For example: "Creating dataframe...", "Exporting dataframe to csv...", "Done!". I have these types of statements placed in the middle of the function.

The problem: The statements get updated to the Log, but only when the entire function is done running.

```<code>class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    # Initialize GUI
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)

        # Set the font in the logger
        font = QFont()
        font.setPointSize(9)
        self.Log_textEdit.setFont(font)

        # Allow selecting multiple files in QWidgetLists
        self.KeysightCurveTracer_List.setSelectionMode(QAbstractItemView.ExtendedSelection)

        # Drag-Drop Functionality
        self.setAcceptDrops(True)

        # setup user click handlers
        self.main_tab.tabBarClicked.connect(lambda: GUIMethods.setCurrentTab())
        self.KeysightCurveTracer_AddFile_Button.clicked.connect(lambda: GUIMethods.addFile())
        self.KeysightCurveTracer_AddFolder_Button.clicked.connect(lambda: GUIMethods.addFolder())
        self.KeysightCurveTracer_Remove_Button.clicked.connect(lambda: GUIMethods.removeFile())
        self.KeysightCurveTracer_Characterization_button.clicked.connect(lambda: GUIMethods.keysightCurveTracer_Characterization())
        self.KeysightCurveTracer_ModuleEOL_Button.clicked.connect(lambda: GUIMethods.keysightCurveTracer_ModuleEOL())
        self.KeysightCurveTracer_RemoveAll_Button.clicked.connect(lambda: GUIMethods.removeAllFiles())

# Start of program
if __name__ == "__main__":
    # "Starts" program in command prompt
    QCoreApplication.setLibraryPaths([os.getcwd() + "\\virtualenv\\Lib\\site-packages\\PyQt5\\Qt5\\plugins"])

    app = QtWidgets.QApplication(sys.argv)
    app.setStyleSheet("QLabel{font-size: 10pt;}")
    app.setWindowIcon(QtGui.QIcon(os.path.join(os.path.dirname(__file__), 'Icon.ico')))

    # Initialize and show GUI
    window = MainWindow()
    window.show()

    # Passes the window to other python files
    GUIMethods.window = window
    FileProcessing.window = window
    KeysightCurveTracer.window = window

    GUIMethods.log("Initialized Post-Processing App")

    app.exec_()
</code>```

Here's an example of my integration of logging:

```<code>GUIMethods.log("Finding index.txt")
        for fullPath in fullPathList:
            if "index.txt" in fullPath:
                GUIMethods.log("index.txt found")
                indexFile = fullPath
                break
</code>```

And here is the actual logging function:

```<code>def log(string):
    if "ERROR" in type(string).__name__.upper():
        logString = type(string).__name__ + ": " + str(string)

    else:
        logString = string

    window.Log_textEdit.append(logString)
</code>```

I have tried looking around, but I could not find anything that would help my certain case or perhaps I am not using my brain enough to figure out how to warp the answers for my case. I have tried some tutorials like this and this. I have also tried a couple answers from stackoverflow like here or here or here or here. This answer is the closest to my case though.

What I find hard with these answers is that they're initializing the QWidget from within the MainWindow init() where my QWidgets are being made in a separate script (because I'm using Qt Designer and use a batch file to update the file). And I'm not sure how to weave in my methods into the multithreading. Any help is appreciated!

Body:
I have this GUI that takes in file inputs and processes them. Naturally, this takes a fair amount of time and it would be nice for the user to see what is happening in the background as they wait for the file processing to finish. For example: "Creating dataframe...", "Exporting dataframe to csv...", "Done!". I have these types of statements placed in the middle of the function.

The problem: The statements get updated to the Log, but only when the entire function is done running.

class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    # Initialize GUI
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)

        # Set the font in the logger
        font = QFont()
        font.setPointSize(9)
        self.Log_textEdit.setFont(font)

        # Allow selecting multiple files in QWidgetLists
        self.KeysightCurveTracer_List.setSelectionMode(QAbstractItemView.ExtendedSelection)

        # Drag-Drop Functionality
        self.setAcceptDrops(True)

        # setup user click handlers
        self.main_tab.tabBarClicked.connect(lambda: GUIMethods.setCurrentTab())
        self.KeysightCurveTracer_AddFile_Button.clicked.connect(lambda: GUIMethods.addFile())
        self.KeysightCurveTracer_AddFolder_Button.clicked.connect(lambda: GUIMethods.addFolder())
        self.KeysightCurveTracer_Remove_Button.clicked.connect(lambda: GUIMethods.removeFile())
        self.KeysightCurveTracer_Characterization_button.clicked.connect(lambda: GUIMethods.keysightCurveTracer_Characterization())
        self.KeysightCurveTracer_ModuleEOL_Button.clicked.connect(lambda: GUIMethods.keysightCurveTracer_ModuleEOL())
        self.KeysightCurveTracer_RemoveAll_Button.clicked.connect(lambda: GUIMethods.removeAllFiles())

# Start of program
if __name__ == "__main__":
    # "Starts" program in command prompt
    QCoreApplication.setLibraryPaths([os.getcwd() + "\\virtualenv\\Lib\\site-packages\\PyQt5\\Qt5\\plugins"])

    app = QtWidgets.QApplication(sys.argv)
    app.setStyleSheet("QLabel{font-size: 10pt;}")
    app.setWindowIcon(QtGui.QIcon(os.path.join(os.path.dirname(__file__), 'Icon.ico')))

    # Initialize and show GUI
    window = MainWindow()
    window.show()

    # Passes the window to other python files
    GUIMethods.window = window
    FileProcessing.window = window
    KeysightCurveTracer.window = window

    GUIMethods.log("Initialized Post-Processing App")

    app.exec_()

Here's an example of my integration of logging:

GUIMethods.log("Finding index.txt")
        for fullPath in fullPathList:
            if "index.txt" in fullPath:
                GUIMethods.log("index.txt found")
                indexFile = fullPath
                break

And here is the actual logging function:

def log(string):
    if "ERROR" in type(string).__name__.upper():
        logString = type(string).__name__ + ": " + str(string)

    else:
        logString = string

    window.Log_textEdit.append(logString)

I have tried looking around, but I could not find anything that would help my certain case or perhaps I am not using my brain enough to figure out how to warp the answers for my case. I have tried some tutorials like this and this. I have also tried a couple answers from stackoverflow like here or here or here or here. This answer is the closest to my case though.

What I find hard with these answers is that they're initializing the QWidget from within the MainWindow init() where my QWidgets are being made in a separate script (because I'm using Qt Designer and use a batch file to update the file). And I'm not sure how to weave in my methods into the multithreading. Any help is appreciated!


问:
Newman Junit output on failures
I'm running a newman command and outputting to a junit file for testmo to pick up. When newman fails to run the collection it does not log anything to the junit file. Is it possible to make newman log failed runs to junit?</p>

Title: Newman Junit output on failures


问:
Dropzone not displaying correctly drag and drop on nested dropzones inside one form
I'm trying to add the dropzone library to my form using the ASP.NET Core MVC project as the following code:

```<code>@model Project.Models.FileList

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.3/basic.css" rel="stylesheet" />

<div class="form-check form-check-inline">
    <input class="form-check-input" type="checkbox" id="10" value="10">
    <label class="form-check-label" for="10">10sec</label>
</div>
<div class="form-check form-check-inline">
    <input class="form-check-input" type="checkbox" id="15" value="15">
    <label class="form-check-label" for="15">15sec</label>
</div>
<div class="form-check form-check-inline">
    <input class="form-check-input" type="checkbox" id="30" value="30">
    <label class="form-check-label" for="30">30sec</label>
</div>
<div class="form-check form-check-inline">
    <input class="form-check-input" type="checkbox" id="45" value="45">
    <label class="form-check-label" for="45">45sec</label>
</div>

<form enctype="multipart/form-data" asp-action="CreateFile" method="post">
    <div class="row" id="10secs" style="display: none">
      <div class="col-lg-12">
        <div class="card">
         <div class="card-header">
             <h4 class="card-title">10sec</h4>
          </div>
          <div class="card-body">
            <div>
              <div class="clsbox-1">
                  <input type="file" multiple asp-for="@Model.Files10" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="row" id="15secs" style="display: none">
      <div class="col-lg-12">
        <div class="card">
         <div class="card-header">
             <h4 class="card-title">15sec</h4>
          </div>
          <div class="card-body">
            <div>
              <div class="clsbox-1">
                  <input type="file" multiple asp-for="@Model.Files15" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="row" id="30secs" style="display: none">
      <div class="col-lg-12">
        <div class="card">
         <div class="card-header">
             <h4 class="card-title">30sec</h4>
          </div>
          <div class="card-body">
            <div>
              <div class="clsbox-1">
                  <input type="file" multiple asp-for="@Model.Files30" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="row" id="45secs" style="display: none">
      <div class="col-lg-12">
        <div class="card">
         <div class="card-header">
             <h4 class="card-title">45sec</h4>
          </div>
          <div class="card-body">
            <div>
              <div class="clsbox-1">
                  <input type="file" multiple asp-for="@Model.Files45" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div id="submit" style="display: none">
        <input type="submit" value="Submit" />
    </div>
</form>

<script>
    var id;
    $("input[type=checkbox]").on("change", function () {
        id = $(this).attr("id");
        var text = document.getElementById(id+"secs");
        if ($(this).is(":checked")) {
            text.style.display = "block";
            document.getElementById("submit").style.display = "block";
        }
        else
        {
            text.style.display = "none";
            var IsChecked = $("input[type=checkbox]");
            var show = "none";
            for (var i = 0; i < IsChecked.length; i++) {
                if (IsChecked[i].checked) {
                    show = "block";
                }
                break;
            }
            document.getElementById("submit").style.display = show;
        }
    })
</script>
</code>```

Now I want to change the inputs for dropzones to achieve something like this on each file upload:

But after my change of the dropzone, it is showing as:

Several things need to be fixed.

The dropzone area is only on the input button

The input button should not be shown

It only admits one file per dropzone, and it should be multiple

Example of code I changed for the dropzone.

```<code><div class="row" id="45secs" style="display: none">
      <div class="col-lg-12">
        <div class="card">
          <div class="card-header">
            <h4 class="card-title">30sec</h4>
          </div>
            <div class="card-body">
                <div class="dropzone">
                    <div class="fallback">
                        <input name="file" type="file" multiple="multiple">
                    </div>
                    <div class="dz-message needsclick">
                        <div class="mb-3">
                            <i class="display-4 text-muted bx bx-cloud-upload"></i>
                        </div>

                        <h5>Drop files here or click to upload.</h5>
                    </div>
                </div>
          </div>
        </div>
      </div>
    </div>
</code>```

What am I doing wrong?

UPDATE

For some reason, if I comment the all the <form> and everything inside it with nested dropzones and place a new form as:

```<code><form asp-action="create" class="dropzone">
    <div class="fallback">
        <input name="file" type="file" multiple="multiple">
    </div>
    <div class="dz-message needsclick">
        <div class="mb-3">
            <i class="display-4 text-muted bx bx-cloud-upload"></i>
        </div>

        <h5>Drop files here or click to upload.</h5>
    </div>
</form>
</code>```

It works as expected!!, why is it not working correctly on the nested dropzone form? Is it a workaround for that?

UPDATE 2

In this question someone asks the same and the answer implements native drag-and-drop functionality and it works! but it does not show the nice dropzone interface, with remove links and file thumbnail, is there a way to apply them?

JQuery:

```<code> const dropzone = $('#10secs')
        // click input file field
        dropzone.on('click', function () {
          $("#file10").trigger("click");
        })

        // prevent default browser behavior
        dropzone.on('drag dragstart dragend dragover dragenter dragleave drop', function(e) {
            e.preventDefault();
            e.stopPropagation();
          })

        // add visual drag information
        dropzone.on('dragover dragenter', function() {
            $('#10secs').addClass('active');
          })
        dropzone.on('dragleave dragend', function() {
          $('#10secs').removeClass('active');
          })

        // catch file drop and add it to input
        dropzone.on("drop", e => {
          e.preventDefault();
          let files = e.originalEvent.dataTransfer.files

          if (files.length) {
            $("#file10").prop("files", files);
          }
        });

        // trigger file submission behavior
        $("#file10").on('change', function (e) {
          if (e.target.files.length) {
            // trigger any behavior here
          }
        })
</code>```

Current interface

Body:
I'm trying to add the dropzone library to my form using the ASP.NET Core MVC project as the following code:

@model Project.Models.FileList

<link href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.3/basic.css" rel="stylesheet" />

    <input class="form-check-input" type="checkbox" id="10" value="10">
    10sec

    <input class="form-check-input" type="checkbox" id="15" value="15">
    15sec

    <input class="form-check-input" type="checkbox" id="30" value="30">
    30sec

    <input class="form-check-input" type="checkbox" id="45" value="45">
    45sec

<form enctype="multipart/form-data" asp-action="CreateFile" method="post">

10sec

                  <input type="file" multiple asp-for="@Model.Files10" />

15sec

                  <input type="file" multiple asp-for="@Model.Files15" />

30sec

                  <input type="file" multiple asp-for="@Model.Files30" />

45sec

                  <input type="file" multiple asp-for="@Model.Files45" />

        <input type="submit" value="Submit" />

</form>

Now I want to change the inputs for dropzones to achieve something like this on each file upload:

But after my change of the dropzone, it is showing as:

Several things need to be fixed.

The dropzone area is only on the input button

The input button should not be shown

It only admits one file per dropzone, and it should be multiple

Example of code I changed for the dropzone.

30sec

                        <input name="file" type="file" multiple="multiple">

Drop files here or click to upload.

What am I doing wrong?

UPDATE

For some reason, if I comment the all the <form> and everything inside it with nested dropzones and place a new form as:

<form asp-action="create" class="dropzone">

        <input name="file" type="file" multiple="multiple">

Drop files here or click to upload.

</form>

It works as expected!!, why is it not working correctly on the nested dropzone form? Is it a workaround for that?

UPDATE 2

In this question someone asks the same and the answer implements native drag-and-drop functionality and it works! but it does not show the nice dropzone interface, with remove links and file thumbnail, is there a way to apply them?

JQuery:

 const dropzone = $('#10secs')
        // click input file field
        dropzone.on('click', function () {
          $("#file10").trigger("click");
        })

        // prevent default browser behavior
        dropzone.on('drag dragstart dragend dragover dragenter dragleave drop', function(e) {
            e.preventDefault();
            e.stopPropagation();
          })

        // add visual drag information
        dropzone.on('dragover dragenter', function() {
            $('#10secs').addClass('active');
          })
        dropzone.on('dragleave dragend', function() {
          $('#10secs').removeClass('active');
          })

        // catch file drop and add it to input
        dropzone.on("drop", e => {
          e.preventDefault();
          let files = e.originalEvent.dataTransfer.files

          if (files.length) {
            $("#file10").prop("files", files);
          }
        });

        // trigger file submission behavior
        $("#file10").on('change', function (e) {
          if (e.target.files.length) {
            // trigger any behavior here
          }
        })

Current interface


问:
Modifying Archive Widget in Wordpress so that it shows only posts from current category
I was not able to find the exact solution here, so I'm posting a question.

So, I need a code that will turn Archive widget on every page to show only the pages/posts that are inside of the category on which you pressed it. for example if category is named "Acts" (url https://website.com/category/acts/) when you on the right sidebar press Archive and select month fromthe dropdown it will go to the url
https://website.com/2022/08/?category_name=acts instead of the usual https://website.com/2022/08/.

I would like to ask for a code I could put into my functions.php of the child theme so that it'd work. Also if possible to put the code so that it registers the modified archive widget as a new widget.

Thanks.

I tried several solutions here, but none of the worked. like:
Display posts from current category in archives
https://wordpress.stackexchange.com/questions/176573/display-only-posts-from-referred-category-on-date-archive-page

I was able to identify that I actually just need the widget to work so that it forwards to the new URL mentioned above (the two posts above were helpful, but I wasn't able to get a complete answer)


问:
ggplot() geom_boxplot() how to change point styles for different treatments
I am looping to make boxplots with ggplot. I want to customize the look of the box plots with color and using different point styles. I have color formatting working but I cannot get the point style to change. I am using the following to make the graphs:

```<code>variables <- met_df %>%
  select(28, 30:34, 38:62, 93:101, 103:106, 112:114, 140:168, 172:184, 190:202, 208:216, 219:224, 226:236, 238:245, 267:275,278 ,334 , 341, 344:347, 358:365, 474:516) %>%
  names()

for(i in variables) {
  g <- ggplot(met_df, aes(x = Rx, y = get(i), color= Rx)) +
    geom_boxplot(outlier.shape=NA)+
    ylab(i)
  print(g + theme_classic()+ geom_jitter(position=position_jitter(0.2))+ color_4)
}
</code>```

For the color I used:

```<code>color_4 <- list(scale_color_manual(
  values = c("gray60", "midnightblue", "steelblue2", "dodgerblue3"),
  name = "Treatment",
  labels = c("Control", "Metformin", "Met Early", "Met Late")
))
</code>```

I have tried the following for the points:

```<code>point_4_v2 <- list(scale_shape_manual(
  values = c(23, 22, 21, 24),
  name = "Treatment",
  labels = c("Control", "Metformin", "Met Early", "Met Late")
))
</code>```

However, that did not work.

Body:
I am looping to make boxplots with ggplot. I want to customize the look of the box plots with color and using different point styles. I have color formatting working but I cannot get the point style to change. I am using the following to make the graphs:

variables <- met_df %>%
  select(28, 30:34, 38:62, 93:101, 103:106, 112:114, 140:168, 172:184, 190:202, 208:216, 219:224, 226:236, 238:245, 267:275,278 ,334 , 341, 344:347, 358:365, 474:516) %>%
  names()

for(i in variables) {
  g <- ggplot(met_df, aes(x = Rx, y = get(i), color= Rx)) +
    geom_boxplot(outlier.shape=NA)+
    ylab(i)
  print(g + theme_classic()+ geom_jitter(position=position_jitter(0.2))+ color_4)
}

For the color I used:

color_4 <- list(scale_color_manual(
  values = c("gray60", "midnightblue", "steelblue2", "dodgerblue3"),
  name = "Treatment",
  labels = c("Control", "Metformin", "Met Early", "Met Late")
))

I have tried the following for the points:

point_4_v2 <- list(scale_shape_manual(
  values = c(23, 22, 21, 24),
  name = "Treatment",
  labels = c("Control", "Metformin", "Met Early", "Met Late")
))

However, that did not work.


问:
PM4Py DFG - get additional edge metrics besides performance and frequency
In PM4Py DFG, performance and frequency edge metrics are already available out of the box. Can we define other metrics besides these two? Like the cost it took to go from one node to the other?</p>


问:
Duplicate sqs events in aws
I have a service that calls an aws sqs queue which in turn executes a lambda function, and it rarely happens that this function is executed twice for the same queue message, and it shouldn't.

```<code>import aws from 'aws-sdk';
import { v4 as uuidv4 } from 'uuid';

import * as awsConfig from '../config/aws';

const accessKeyId = awsConfig.accessKeyId;
const secretAccessKey = awsConfig.secretAccessKey;
const region = awsConfig.generalRegion;

class SqsMessenger {
  sqs: aws.SQS;
  constructor() {
    this.sqs = new aws.SQS();
  }

  send(body: any, queueUrl: string, groupId?: string) {
    const params: aws.SQS.Types.SendMessageRequest = {
      MessageBody: JSON.stringify(body),
      MessageGroupId: groupId || uuidv4(),
      MessageDeduplicationId: uuidv4(),
      QueueUrl: queueUrl,
    };

    return new Promise((resolve, reject) => {
      this.sqs.sendMessage(params, (error: aws.AWSError, data: aws.SQS.SendMessageResult) => {
        if (error) {
          return reject(error);
        }
        resolve(data);
      });
    });
  }
}

export const sqs = new SqsMessenger();
</code>```

Lambda function logs

On the first call the MessageDeduplicationId field is displayed

And in the second call the MessageDeduplicationId field is no longer displayed, I emphasize that it does not happen all the time, but it should not be executed twice again.

Title: Duplicate sqs events in aws

Body:
I have a service that calls an aws sqs queue which in turn executes a lambda function, and it rarely happens that this function is executed twice for the same queue message, and it shouldn't.

import aws from 'aws-sdk';
import { v4 as uuidv4 } from 'uuid';

import * as awsConfig from '../config/aws';

const accessKeyId = awsConfig.accessKeyId;
const secretAccessKey = awsConfig.secretAccessKey;
const region = awsConfig.generalRegion;

class SqsMessenger {
  sqs: aws.SQS;
  constructor() {
    this.sqs = new aws.SQS();
  }

  send(body: any, queueUrl: string, groupId?: string) {
    const params: aws.SQS.Types.SendMessageRequest = {
      MessageBody: JSON.stringify(body),
      MessageGroupId: groupId || uuidv4(),
      MessageDeduplicationId: uuidv4(),
      QueueUrl: queueUrl,
    };

    return new Promise((resolve, reject) => {
      this.sqs.sendMessage(params, (error: aws.AWSError, data: aws.SQS.SendMessageResult) => {
        if (error) {
          return reject(error);
        }
        resolve(data);
      });
    });
  }
}

export const sqs = new SqsMessenger();

Lambda function logs

On the first call the MessageDeduplicationId field is displayed

And in the second call the MessageDeduplicationId field is no longer displayed, I emphasize that it does not happen all the time, but it should not be executed twice again.


问:
How to withSum on relationship records that have been filtered?
My $user has relationship called 'earnings', which are basically transactions he earned from. Earnings need to be filtered according to some properties, but when I add withSum, it sums ALL of the relationship records. That's why I had to repeat the filtering subquery when getting 'earnings' and when getting 'earnings_sum_amount'.

Here is the code:

```<code>$users->with([
            'earnings' => function($query) use ($dateSpanArray, $brandModel) {

                /* Subquery is executing when one of 2 parameters are true */
                $query->when(($dateSpanArray || $brandModel) , function($query) use ($dateSpanArray, $brandModel) {

                    if($brandModel)
                    {
                        $query->whereIn('sender_id', $brandModel->wallets->pluck('id')->toArray());
                    }
                    if($dateSpanArray)
                    {
                        $query->whereBetween('created_at', [$dateSpanArray['from'],$dateSpanArray['to']]);
                    }
                })
                ->latest();
            }]
        )

->withSum([
            'earnings' => function($query) use ($dateSpanArray, $brandModel) {

                $query->when(($dateSpanArray || $brandModel) , function($query) use ($dateSpanArray, $brandModel) {

                    if($brandModel)
                    {
                        $query->whereIn('sender_id', $brandModel->wallets->pluck('id')->toArray());
                    }
                    if($dateSpanArray)
                    {
                        $query->whereBetween('created_at', [$dateSpanArray['from'],$dateSpanArray['to']]);
                    }
                })->select(DB::raw('COALESCE(SUM(amount), 0)'));
            }
        ], 'amount')
->get();

</code>```

I was just wondering if there is a better way to write this, to avoid the code repetition?

Body:
My $user has relationship called 'earnings', which are basically transactions he earned from. Earnings need to be filtered according to some properties, but when I add withSum, it sums ALL of the relationship records. That's why I had to repeat the filtering subquery when getting 'earnings' and when getting 'earnings_sum_amount'.

Here is the code:

$users->with([
            'earnings' => function($query) use ($dateSpanArray, $brandModel) {

                /* Subquery is executing when one of 2 parameters are true */
                $query->when(($dateSpanArray || $brandModel) , function($query) use ($dateSpanArray, $brandModel) {

                    if($brandModel)
                    {
                        $query->whereIn('sender_id', $brandModel->wallets->pluck('id')->toArray());
                    }
                    if($dateSpanArray)
                    {
                        $query->whereBetween('created_at', [$dateSpanArray['from'],$dateSpanArray['to']]);
                    }
                })
                ->latest();
            }]
        )

->withSum([
            'earnings' => function($query) use ($dateSpanArray, $brandModel) {

                $query->when(($dateSpanArray || $brandModel) , function($query) use ($dateSpanArray, $brandModel) {

                    if($brandModel)
                    {
                        $query->whereIn('sender_id', $brandModel->wallets->pluck('id')->toArray());
                    }
                    if($dateSpanArray)
                    {
                        $query->whereBetween('created_at', [$dateSpanArray['from'],$dateSpanArray['to']]);
                    }
                })->select(DB::raw('COALESCE(SUM(amount), 0)'));
            }
        ], 'amount')
->get();

I was just wondering if there is a better way to write this, to avoid the code repetition?


问:
docker compose different image size on x86 vs ARM
On running docker compose on Intel Mac or AMD Windows, the image size is 482MB and this image works as intended.

However, on M1 PRO (ARM) Mac, the image size is 704MB and doesn't work.

Has anyone encountered this or has any idea why this is?

Thanks!


问:
Im looking to add cyclic lines in pinescript, but I could not seem to find any api inside of pinescript to do so
So basically my goal, is to have multiple cyclic lines starting at a start date I chose in the code along with the width of the lines. I was wondering if there was a way to do it.

I tried to add vertical lines but that would not work if I am adding multiple cyclic lines.


问:
So I need some help as to why this code fails SubStringAfter/ toIntOrNull() produces a null Why?
I know this is going to end up with me smacking my head but I don't understand why this does not worked as expected. Basically I am calling a google Sheet Append method getting the result and saving the last row value.
I have tried these and still the toIntOrNull ends up null but if I use a numeric value (s ="117" it works as expected ! So at this point I'm totally stumped. Using the Android Studio scratch utility</p>
```<code>    /*This should produce the output of an Integer !
    response from Google Sheets Append
    "updatedRange":"tData!A117:I117","updatedRows":1}}
    get the "target"
    var s: String = result.updates.updatedRange.substringAfter("I")
    this returns "117" as expected

    testing !  */
    var s = "tData!A117:I117"
    s = s.substringAfter("I")
    // again result is 117 with a length of 3
    //  .trimStart("I"
    var lr = s.toIntOrNull()
    println ("$s  $lr") // 117 null Why ?
</code>```
```<code></code>```

Body:
I know this is going to end up with me smacking my head but I don't understand why this does not worked as expected. Basically I am calling a google Sheet Append method getting the result and saving the last row value.
I have tried these and still the toIntOrNull ends up null but if I use a numeric value (s ="117" it works as expected ! So at this point I'm totally stumped. Using the Android Studio scratch utility

    /*This should produce the output of an Integer !
    response from Google Sheets Append
    "updatedRange":"tData!A117:I117","updatedRows":1}}
    get the "target"
    var s: String = result.updates.updatedRange.substringAfter("I")
    this returns "117" as expected

    testing !  */
    var s = "tData!A117:I117"
    s = s.substringAfter("I")
    // again result is 117 with a length of 3
    //  .trimStart("I"
    var lr = s.toIntOrNull()
    println ("$s  $lr") // 117 null Why ?


问:
Problems with scripts in a SPA
This is the script I am using to create a spa.

```<code>const route = (event) => {
  event = event || window.event;
  event.preventDefault();
  window.history.pushState({}, "", event.target.href);
  handleLocation();
};

const routes = {
  404: "./pages/404.html",
  "/": "./pages/index.html",
  "/vehicles": "./pages/vehicles.html",
  "/services": "./pages/services.html",
  "/contact": "./pages/contact.html",
  "/financing": "./pages/financing.html",
  "/locations": "./pages/locations.html",
};

const handleLocation = async () => {
  const path = window.location.pathname;
  const route = routes[path] || routes[404];
  const html = await fetch(route).then((data) => data.text());
  document.getElementById("main-page").innerHTML = html;
};

window.onpopstate = handleLocation;
window.route = route;

handleLocation();
<a href="/financing" onclick="route()" class="mainServices-section">
  <div class="main-title">
    <h2>Financing</h2>
  </div>
  <img src="../image/financing-image-colored.svg" alt="">
</a>
</code>```

It worked correctly for me. But in a section of the web, I need a contact form, which through javascript open the Email app and pre complete the corresponding fields.

```<code>        <section class="contact inset-wrapper">
            <form class="form content" id="form" action="">
                <h2 class="title"><strong>let's talk</strong></h2>
                <h4 class="subtitle">Do not hesitate to contact us for more information about the vehicle you are interested in.</h4>
                <label for="name">
                    <h4>Name</h4>
                </label>
                    <input required name="name" id="name" type="text" placeholder="Juan Lucas López">
                <label for="email">
                    <h4>Email</h4>
                </label>
                    <input required name="email" id="email" type="email" placeholder="Email">
                <label for="message">
                    <h4>Message</h4>
                </label>
                    <textarea required name="message" placeholder="Message" id="message" cols="30" rows="10"></textarea>
                <button class="form-button" type="submit">Send Message</button>
                <a id="sendMail" href="mailto:mauriciolaratro@gmail.com" ></a>
            </form>
        </section>

        <script>
            const $form = document.querySelector('#form')
            const $buttonMailto = document.querySelector('#sendMail')

            $form.addEventListener('submit', handleSubmit)

            function handleSubmit(event) {
                event.preventDefault()
                const form = new FormData(this)
                $buttonMailto.setAttribute('href', `mailto:mauriciolaratro@gmail.com?subjet=${form.get('name')} ${form.get('email')}&body=${form.get('message')}`)
                $buttonMailto.click()
            }
        </script>
</code>```

This is the code I use to make the form, which works perfectly, when I use it in another project, however, the previous script interferes with this somehow and I do not know how to fix it (Again I clarify that I am new to js).
What happens is that instead of redirecting to the Email app, it tries to redirect the web to a non-existent link.
I would appreciate any contribution, to be able to solve this in the simplest way, I am trying to make this project, without consuming external API, I know that there are simpler and more efficient ways to make the form functional, but the idea is to do everything with vanilla code and without API

Title: Problems with scripts in a SPA

Body:
This is the script I am using to create a spa.

const route = (event) => {
  event = event || window.event;
  event.preventDefault();
  window.history.pushState({}, "", event.target.href);
  handleLocation();
};

const routes = {
  404: "./pages/404.html",
  "/": "./pages/index.html",
  "/vehicles": "./pages/vehicles.html",
  "/services": "./pages/services.html",
  "/contact": "./pages/contact.html",
  "/financing": "./pages/financing.html",
  "/locations": "./pages/locations.html",
};

const handleLocation = async () => {
  const path = window.location.pathname;
  const route = routes[path] || routes[404];
  const html = await fetch(route).then((data) => data.text());
  document.getElementById("main-page").innerHTML = html;
};

window.onpopstate = handleLocation;
window.route = route;

handleLocation();

Financing

It worked correctly for me. But in a section of the web, I need a contact form, which through javascript open the Email app and pre complete the corresponding fields.

            <form class="form content" id="form" action="">

let's talk

Do not hesitate to contact us for more information about the vehicle you are interested in.

Name

                    <input required name="name" id="name" type="text" placeholder="Juan Lucas López">

Email

                    <input required name="email" id="email" type="email" placeholder="Email">

Message

                    <textarea required name="message" placeholder="Message" id="message" cols="30" rows="10"></textarea>
                <button class="form-button" type="submit">Send Message</button>

            </form>

This is the code I use to make the form, which works perfectly, when I use it in another project, however, the previous script interferes with this somehow and I do not know how to fix it (Again I clarify that I am new to js).
What happens is that instead of redirecting to the Email app, it tries to redirect the web to a non-existent link.
I would appreciate any contribution, to be able to solve this in the simplest way, I am trying to make this project, without consuming external API, I know that there are simpler and more efficient ways to make the form functional, but the idea is to do everything with vanilla code and without API


问:
JWT authentication 401 Unauthorized .net
```<code></code>```

Hello Dear Friends,
I have jwt token problem on my project. I want to do Authorization however, http 401 error was occured in my app. I want to enter the website by connecting NVS and the controller I wrote with WEBAPI.
How can I solve this error guys, Thank yoU.
I shared my codes below.
Here is my WebAPI Login Code

```<code>[HttpPost("Login")]
        public async Task<IActionResult> Login([FromBody] UserForLoginDto userForLoginDto)
        {
            LoginCommand loginCommand = new() { UserForLoginDto = userForLoginDto, IpAddress = GetIpAddress() };
            LoginDto result = await Mediator.Send(loginCommand);

            if (result.RefreshToken is not null) setRefreshTokenToCookie(result.RefreshToken);

            return Ok(result.CreateResponseDto());
        }

</code>```

and this is my MVC controller code

```<code>[HttpPost]

        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Login(LoginViewModel loginViewModel)
        {
            var response = await _client.PostAsJsonAsync("Auth/Login",loginViewModel);
            if (response.IsSuccessStatusCode)
            {
                //var body =await response.Content.ReadFromJsonAsync<LoginResponse>();
                var body=await response.Content.ReadAsStringAsync();
                LoginResponse loginResponse=JsonConvert.DeserializeObject<LoginResponse>(body);

                return RedirectToAction("Index", "Dashboard");

            }
            return View("Index",loginViewModel);
</code>```

and my startup cs MVC code

```<code>builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
    options.RequireHttpsMetadata = false;
    options.SaveToken = true;
    options.TokenValidationParameters = new TokenValidationParameters()
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidAudience = builder.Configuration["Jwt:Audience"],
        ValidIssuer = builder.Configuration["Jwt:Issuer"],
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
    };
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAuthentication();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();
</code>```

startup cs WEBAPI  code

```<code>builder.Services.AddControllers();
builder.Services.AddApplicationServices();
builder.Services.AddSecurityServices();
builder.Services.AddPersistenceServices(builder.Configuration);
//builder.Services.AddInfrastructureServices();
builder.Services.AddHttpContextAccessor();
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(x =>
{
    x.LoginPath = "/Login";
});
TokenOptions? tokenOptions = builder.Configuration.GetSection("TokenOptions").Get<TokenOptions>();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidIssuer = tokenOptions.Issuer,
        ValidAudience = tokenOptions.Audience,
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = SecurityKeyHelper.CreateSecurityKey(tokenOptions.SecurityKey)
    };
});

builder.Services.AddSwaggerGen(opt =>
{
    opt.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        Name = "Authorization",
        Type = SecuritySchemeType.ApiKey,
        Scheme = "Bearer",
        BearerFormat = "JWT",
        In = ParameterLocation.Header,
        Description =
            "JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] and then your token in the text input below.\r\n\r\nExample: \"Bearer 12345.54321\""
    });
    opt.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
                { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } },
            new string[] { }
        }
    });
});

</code>```

ı tried change  [Authorize] from my dasboard
and am ı need change someting about this. Thanks For Helping

Body:
Hello Dear Friends,
I have jwt token problem on my project. I want to do Authorization however, http 401 error was occured in my app. I want to enter the website by connecting NVS and the controller I wrote with WEBAPI.
How can I solve this error guys, Thank yoU.
I shared my codes below.
Here is my WebAPI Login Code

[HttpPost("Login")]
        public async Task<IActionResult> Login([FromBody] UserForLoginDto userForLoginDto)
        {
            LoginCommand loginCommand = new() { UserForLoginDto = userForLoginDto, IpAddress = GetIpAddress() };
            LoginDto result = await Mediator.Send(loginCommand);

            if (result.RefreshToken is not null) setRefreshTokenToCookie(result.RefreshToken);

            return Ok(result.CreateResponseDto());
        }

and this is my MVC controller code

[HttpPost]

        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Login(LoginViewModel loginViewModel)
        {
            var response = await _client.PostAsJsonAsync("Auth/Login",loginViewModel);
            if (response.IsSuccessStatusCode)
            {
                //var body =await response.Content.ReadFromJsonAsync<LoginResponse>();
                var body=await response.Content.ReadAsStringAsync();
                LoginResponse loginResponse=JsonConvert.DeserializeObject<LoginResponse>(body);

                return RedirectToAction("Index", "Dashboard");

            }
            return View("Index",loginViewModel);

and my startup cs MVC code

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
    options.RequireHttpsMetadata = false;
    options.SaveToken = true;
    options.TokenValidationParameters = new TokenValidationParameters()
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidAudience = builder.Configuration["Jwt:Audience"],
        ValidIssuer = builder.Configuration["Jwt:Issuer"],
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
    };
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAuthentication();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

startup cs WEBAPI  code

builder.Services.AddControllers();
builder.Services.AddApplicationServices();
builder.Services.AddSecurityServices();
builder.Services.AddPersistenceServices(builder.Configuration);
//builder.Services.AddInfrastructureServices();
builder.Services.AddHttpContextAccessor();
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(x =>
{
    x.LoginPath = "/Login";
});
TokenOptions? tokenOptions = builder.Configuration.GetSection("TokenOptions").Get<TokenOptions>();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidIssuer = tokenOptions.Issuer,
        ValidAudience = tokenOptions.Audience,
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = SecurityKeyHelper.CreateSecurityKey(tokenOptions.SecurityKey)
    };
});

builder.Services.AddSwaggerGen(opt =>
{
    opt.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        Name = "Authorization",
        Type = SecuritySchemeType.ApiKey,
        Scheme = "Bearer",
        BearerFormat = "JWT",
        In = ParameterLocation.Header,
        Description =
            "JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] and then your token in the text input below.\r\n\r\nExample: \"Bearer 12345.54321\""
    });
    opt.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
                { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } },
            new string[] { }
        }
    });
});

ı tried change  [Authorize] from my dasboard
and am ı need change someting about this. Thanks For Helping


问:
React-router-dom: Error 404 on Vite config and gh-pages
After I deployed my react app on GitHub (using gh-pages), I ran into a navigation problem. The site takes the following URL as a home page:
https://1kiritos1.github.io/,

Whereas, the homepage should be:
https://1kiritos1.github.io/youtube-clone/

I need the site navigation to depend on the above-mentioned URL, for example:
https://1kiritos1.github.io/youtube-clone/video/***

Or

https://1kiritos1.github.io/youtube-clone/channel/***

App

```<code>import React from 'react';
import { Box } from '@mui/material';
import { HashRouter as Router, Routes, Route } from 'react-router-dom';
import { Navbar, Feed, VideoDetail, ChannelDetail, SearchFeed } from './components';

function App() {
    return (
        <Router>
            <Box>
                <Navbar />
                <Routes>
                    <Route exact path="/" element={<Feed />} />
                    <Route path="/video/:id" element={<VideoDetail />} />
                    <Route path="/channel/:id" element={<ChannelDetail />} />
                    <Route path="/search/:searchTerm" element={<SearchFeed />} />
                </Routes>
            </Box>
        </Router>
    )
}
export default App;
</code>```

Index

```<code>import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './style.css';

ReactDOM.createRoot(document.getElementById('root')).render(
    <App />
)
</code>```

Package.json:

```<code>"name": "youtube_clone",
  "homepage": "/youtube-clone/#",
  "private": true,
  "version": "0.0.0",
  "type": "module",
</code>```

Vite.config.js:

```<code>import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

export default defineConfig({
  base: '/youtube-clone/', // Base url of the website
  plugins: [react()]
});
</code>```

I've tried to use basename="youtube-clone/", and also make changes following these solutions, but none of that didn't help me. The site works correctly on local server. Maybe issue in vite config, I don't know.
( If you need any additional information, please tell me, thank you )

Body:
After I deployed my react app on GitHub (using gh-pages), I ran into a navigation problem. The site takes the following URL as a home page:
https://1kiritos1.github.io/,

Whereas, the homepage should be:
https://1kiritos1.github.io/youtube-clone/

I need the site navigation to depend on the above-mentioned URL, for example:
https://1kiritos1.github.io/youtube-clone/video/***

Or

https://1kiritos1.github.io/youtube-clone/channel/***

App

import React from 'react';
import { Box } from '@mui/material';
import { HashRouter as Router, Routes, Route } from 'react-router-dom';
import { Navbar, Feed, VideoDetail, ChannelDetail, SearchFeed } from './components';

function App() {
    return (
        <Router>
            <Box>
                <Navbar />
                <Routes>
                    <Route exact path="/" element={<Feed />} />
                    <Route path="/video/:id" element={<VideoDetail />} />
                    <Route path="/channel/:id" element={<ChannelDetail />} />
                    <Route path="/search/:searchTerm" element={<SearchFeed />} />
                </Routes>
            </Box>
        </Router>
    )
}
export default App;

Index

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './style.css';

ReactDOM.createRoot(document.getElementById('root')).render(
    <App />
)

Package.json:

"name": "youtube_clone",
  "homepage": "/youtube-clone/#",
  "private": true,
  "version": "0.0.0",
  "type": "module",

Vite.config.js:

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

export default defineConfig({
  base: '/youtube-clone/', // Base url of the website
  plugins: [react()]
});

I've tried to use basename="youtube-clone/", and also make changes following these solutions, but none of that didn't help me. The site works correctly on local server. Maybe issue in vite config, I don't know.
( If you need any additional information, please tell me, thank you )


问:
How to manipulate image bands as arrays of numbers
I'm new to Python, and I'm trying to deconstruct image bands as arrays of numbers by applying the Singular Value Decomposition (SVD) to them and then putting them back together with matplotlib.image and the Image module from PIL. An SVD may also be written as a sum of dyads s1u1v1T + ... + sKuKvKT, and the point in decomposing it in this way is that a near-perfect approximation of the image can be made from just a few of those dyads, so less data is required.

There must be something wrong with the calculation, though because result_r, result_g, and result_b look like this when converted to Images, and new_image looks like this.

For an example of what this should look like, here are the first dyads of the layers of this image. The image that I'm using (April23.jpg) is this.

```<code>import matplotlib.image as image
import numpy.linalg as la
import numpy as np
from PIL import Image

def getcolumn(j, m):
    col = []
    for i in range(len(m)):
        col.append(m[i][j])
    return col

def extractCols(U):
    Ucols = []
    for j in range(len(U[0])):
        Ucols.append(getcolumn(j, U))
    return np.asarray(Ucols)

def vectorMultiply(u, v):
    matrix = []
    for i in range(len(u)):
        newVec = []
        for j in range(len(v)):
            newVec.append(u[i] * v[j])
        matrix.append(newVec)
    return np.asarray(matrix)

im = Image.open('C:/Users/<user>/Desktop/img/April23.jpg')
im.load()

sim = Image.Image.split(im)

rsim = sim[0].save("rsim.jpg") # image bands as images
gsim = sim[1].save("gsim.jpg")
bsim = sim[2].save("bsim.jpg")

# image bands as arrays of numbers
arsim = image.imread('C:/Users/<user>/Desktop/img/rsim.jpg')
agsim = image.imread('C:/Users/<user>/Desktop/img/gsim.jpg')
absim = image.imread('C:/Users/<user>/Desktop/img/bsim.jpg')

ur, sr, vhr = la.svd(arsim, False) # SVD on each band
ug, sg, vhg = la.svd(agsim, False)
ub, sb, vhb = la.svd(absim, False)

urcols = extractCols(ur)
ugcols = extractCols(ug)
ubcols = extractCols(ub)

# calculating the first dyads
result_r = np.multiply(sr[0], vectorMultiply(urcols[0], vhr[0]))
result_g = np.multiply(sg[0], vectorMultiply(ugcols[0], vhg[0]))
result_b = np.multiply(sb[0], vectorMultiply(ubcols[0], vhb[0]))

r = Image.fromarray(result_r, "L")
g = Image.fromarray(result_g, "L")
b = Image.fromarray(result_b, "L")

new_image = Image.merge("RGB", (r, g, b))
</code>```

What am I missing, here? It seems to be something with the calculations. I figured for a matrix one would have to extract the columns, say the column [1, 2, 3] from a matrix [[1,...], [2,...], [3,...]], since each element of the matrix is a row. So, I wrote extractCols() for that. numpy's matrix add and multiply seem to be fine. I wrote vectorMultiply because np.dot(), np.multiply(), and np.matmul() didn't seem to realize that u was a column and kept saying the dimensions didn't match up. I tested it and it seemed to do what I wanted it to. I was also thinking that maybe the "rows" of U are actually the columns already and don't need to be extracted, but that didn't work either. I've also tried not using np.asarray() without any luck.

Any advice is appreciated.

Body:
I'm new to Python, and I'm trying to deconstruct image bands as arrays of numbers by applying the Singular Value Decomposition (SVD) to them and then putting them back together with matplotlib.image and the Image module from PIL. An SVD may also be written as a sum of dyads s1u1v1T + ... + sKuKvKT, and the point in decomposing it in this way is that a near-perfect approximation of the image can be made from just a few of those dyads, so less data is required.

There must be something wrong with the calculation, though because result_r, result_g, and result_b look like this when converted to Images, and new_image looks like this.

For an example of what this should look like, here are the first dyads of the layers of this image. The image that I'm using (April23.jpg) is this.

import matplotlib.image as image
import numpy.linalg as la
import numpy as np
from PIL import Image

def getcolumn(j, m):
    col = []
    for i in range(len(m)):
        col.append(m[i][j])
    return col

def extractCols(U):
    Ucols = []
    for j in range(len(U[0])):
        Ucols.append(getcolumn(j, U))
    return np.asarray(Ucols)

def vectorMultiply(u, v):
    matrix = []
    for i in range(len(u)):
        newVec = []
        for j in range(len(v)):
            newVec.append(u[i] * v[j])
        matrix.append(newVec)
    return np.asarray(matrix)

im = Image.open('C:/Users/<user>/Desktop/img/April23.jpg')
im.load()

sim = Image.Image.split(im)

rsim = sim[0].save("rsim.jpg") # image bands as images
gsim = sim[1].save("gsim.jpg")
bsim = sim[2].save("bsim.jpg")

# image bands as arrays of numbers
arsim = image.imread('C:/Users/<user>/Desktop/img/rsim.jpg')
agsim = image.imread('C:/Users/<user>/Desktop/img/gsim.jpg')
absim = image.imread('C:/Users/<user>/Desktop/img/bsim.jpg')

ur, sr, vhr = la.svd(arsim, False) # SVD on each band
ug, sg, vhg = la.svd(agsim, False)
ub, sb, vhb = la.svd(absim, False)

urcols = extractCols(ur)
ugcols = extractCols(ug)
ubcols = extractCols(ub)

# calculating the first dyads
result_r = np.multiply(sr[0], vectorMultiply(urcols[0], vhr[0]))
result_g = np.multiply(sg[0], vectorMultiply(ugcols[0], vhg[0]))
result_b = np.multiply(sb[0], vectorMultiply(ubcols[0], vhb[0]))

r = Image.fromarray(result_r, "L")
g = Image.fromarray(result_g, "L")
b = Image.fromarray(result_b, "L")

new_image = Image.merge("RGB", (r, g, b))

What am I missing, here? It seems to be something with the calculations. I figured for a matrix one would have to extract the columns, say the column [1, 2, 3] from a matrix [[1,...], [2,...], [3,...]], since each element of the matrix is a row. So, I wrote extractCols() for that. numpy's matrix add and multiply seem to be fine. I wrote vectorMultiply because np.dot(), np.multiply(), and np.matmul() didn't seem to realize that u was a column and kept saying the dimensions didn't match up. I tested it and it seemed to do what I wanted it to. I was also thinking that maybe the "rows" of U are actually the columns already and don't need to be extracted, but that didn't work either. I've also tried not using np.asarray() without any luck.

Any advice is appreciated.


问:
How to make XCode bundle C++ project as an .app?
A few months ago, I inherited a C++ command-line XCode project that I've since turned into an app with a GUI, but XCode won't build it as an .app bundle:

Instead, XCode builds a Debug folder, which, interestingly enough, works as an app if I copy it and rename it to "[Bundle Display Name].app".

There are two problems with this though:

(1) I have to manually do this for each build

(2) It doesn't link to my Assets.xcassets file containing my app icons or my Info.plist file or any of the other resources I need.

I've scoured Apple's XCode documentation and come up with nothing. Are there any XCode veterans who know the solution?

EDIT: It seems like the only solution is to add a script to the Build Rules to manually change the Debug directory to an .app and structure it properly. The problem I'm now having is that my app doesn't see my .icns file unless the absolute path is hardcoded into the Info.plist file. For example:

```<code><key>CFBundleIconFile</key>
    <string>AppIcon.icns</string>
</code>```

^This doesn't work

```<code><key>CFBundleIconFile</key>
    <string>/Users/.../build/Control Cam.app/Contents/Resources/AppIcon.icns</string>
</code>```

^This works. But of course it can't find the icon anymore if I move the app to a different folder. Any ideas how to get it to use relative path names?

Body:
A few months ago, I inherited a C++ command-line XCode project that I've since turned into an app with a GUI, but XCode won't build it as an .app bundle:

Instead, XCode builds a Debug folder, which, interestingly enough, works as an app if I copy it and rename it to "[Bundle Display Name].app".

There are two problems with this though:

(1) I have to manually do this for each build

(2) It doesn't link to my Assets.xcassets file containing my app icons or my Info.plist file or any of the other resources I need.

I've scoured Apple's XCode documentation and come up with nothing. Are there any XCode veterans who know the solution?

EDIT: It seems like the only solution is to add a script to the Build Rules to manually change the Debug directory to an .app and structure it properly. The problem I'm now having is that my app doesn't see my .icns file unless the absolute path is hardcoded into the Info.plist file. For example:

<key>CFBundleIconFile</key>
    <string>AppIcon.icns</string>

^This doesn't work

<key>CFBundleIconFile</key>
    <string>/Users/.../build/Control Cam.app/Contents/Resources/AppIcon.icns</string>

^This works. But of course it can't find the icon anymore if I move the app to a different folder. Any ideas how to get it to use relative path names?


问:
Why does rpmbuild rewrite elf headers and how do I stop it?
I have a stripped down spec file that looks like:

```<code>Name: some-binary
Version: 6.1.0
Release: 1
License: proprietary
Summary: a binary

%description
Whatever

%install
install -d %{buildroot}/fromrpm
cp %{_sourcedir}/thebinary %{buildroot}//fromrpm/thebinary

%files
/fromrpm/thebinary
</code>```

Then I run:

```<code>$ cd ~/rpmbuild/

$ rpmbuild -bb SPECS/some-binary.spec 2>/dev/null
Executing(%install): /bin/sh -e /var/tmp/rpm-tmp.gxRpSj
Processing files: some-binary-6.1.0-1.x86_64
Provides: some-binary = 6.1.0-1 some-binary(x86-64) = 6.1.0-1
Requires(rpmlib): rpmlib(CompressedFileNames) <= 3.0.4-1 rpmlib(FileDigests) <= 4.6.0-1 rpmlib(PayloadFilesHavePrefix) <= 4.0-1
Checking for unpackaged file(s): /usr/lib/rpm/check-files /home/dspeyer/rpmbuild/BUILDROOT/some-binary-6.1.0-1.x86_64
Wrote: /home/dspeyer/rpmbuild/RPMS/x86_64/some-binary-6.1.0-1.x86_64.rpm
Executing(%clean): /bin/sh -e /var/tmp/rpm-tmp.WR3Utx

$ rpm2cpio RPMS/x86_64/some-binary-6.1.0-1.x86_64.rpm | cpio -idmv
./fromrpm/thebinary
41456 blocks

$ readelf -a SOURCES/thebinary | grep rela\\.
  [ 5] .rela.plt         RELA             0000000000400338  00000338
   00     .note.gnu.property .note.gnu.build-id .note.ABI-tag .note.go.buildid .rela.plt
Relocation section '.rela.plt' at offset 0x338 contains 29 entries:

$ readelf -a fromrpm/thebinary | grep rela\\.
  [ 6] .rela.got.plt     RELA             0000000000000000  0143d048
Relocation section '.rela.got.plt' at offset 0x143d048 contains 29 entries:
</code>```

I'm not actually sure what the rela tags do, but I strongly suspect they're the reason the post-rpm binary when run on rhel 7.9 immediately crashes trying to crash with "Unexpected reloc type in static binary".  Yes, the binary is statically linked.  (And, yes, I did say "crashes trying to crash": sigsegv inside __libc_fatal)

Any ideas what rpmbuild is trying to do, or how to stop it?

Body:
I have a stripped down spec file that looks like:

Name: some-binary
Version: 6.1.0
Release: 1
License: proprietary
Summary: a binary

%description
Whatever

%install
install -d %{buildroot}/fromrpm
cp %{_sourcedir}/thebinary %{buildroot}//fromrpm/thebinary

%files
/fromrpm/thebinary

Then I run:

$ cd ~/rpmbuild/

$ rpmbuild -bb SPECS/some-binary.spec 2>/dev/null
Executing(%install): /bin/sh -e /var/tmp/rpm-tmp.gxRpSj
Processing files: some-binary-6.1.0-1.x86_64
Provides: some-binary = 6.1.0-1 some-binary(x86-64) = 6.1.0-1
Requires(rpmlib): rpmlib(CompressedFileNames) <= 3.0.4-1 rpmlib(FileDigests) <= 4.6.0-1 rpmlib(PayloadFilesHavePrefix) <= 4.0-1
Checking for unpackaged file(s): /usr/lib/rpm/check-files /home/dspeyer/rpmbuild/BUILDROOT/some-binary-6.1.0-1.x86_64
Wrote: /home/dspeyer/rpmbuild/RPMS/x86_64/some-binary-6.1.0-1.x86_64.rpm
Executing(%clean): /bin/sh -e /var/tmp/rpm-tmp.WR3Utx

$ rpm2cpio RPMS/x86_64/some-binary-6.1.0-1.x86_64.rpm | cpio -idmv
./fromrpm/thebinary
41456 blocks

$ readelf -a SOURCES/thebinary | grep rela\\.
  [ 5] .rela.plt         RELA             0000000000400338  00000338
   00     .note.gnu.property .note.gnu.build-id .note.ABI-tag .note.go.buildid .rela.plt
Relocation section '.rela.plt' at offset 0x338 contains 29 entries:

$ readelf -a fromrpm/thebinary | grep rela\\.
  [ 6] .rela.got.plt     RELA             0000000000000000  0143d048
Relocation section '.rela.got.plt' at offset 0x143d048 contains 29 entries:

I'm not actually sure what the rela tags do, but I strongly suspect they're the reason the post-rpm binary when run on rhel 7.9 immediately crashes trying to crash with "Unexpected reloc type in static binary".  Yes, the binary is statically linked.  (And, yes, I did say "crashes trying to crash": sigsegv inside __libc_fatal)

Any ideas what rpmbuild is trying to do, or how to stop it?


问:
Can I use tracemalloc to line-by-line profile a subprocess?
I am attempting to write a generic,python script that memory profiles a target script, but I can't figure out how to get line-by-line memory stats from the script being run by subprocess.

```<code># mem_profiler.py

import subprocess
import tracemalloc

    def profile(script_name, script_args):
        tracemalloc.start() snap1 = tracemalloc.take_snapshot()

        sp = subprocess.Popen["python", script_name] + script_args)
        sp.wait()
        snap2 = tracemalloc.take_snapshot()

        stats = snapshot2.compare_to(snapshot1, 'lineno')

        print("===[ Top 5 stats ]===")
        for stat in stats[:5]:
          print(stat)
</code>```

Running command python mem_profiler.py --target some_script.py --arg1 --arg2 gives this output:

```<code>===[ Top 5 stats ]===
/src/lib/python3.10/subprocess.py:1234: size=1320 B (+1320 B), count=3 (+3), average=440 B
/src/lib/python3.10/os.py:637: size=1248 B (+1248 B), count=3 (+3), average=416 B
/src/lib/python3.10/subprocess.py:971: size=928 B (+928 B), count=1 (+1), average=928 B
/src/mem_profiler.py:43: size=920 B (+920 B), count=2 (+2), average=460 B
/src/mem_profiler.py:27: size=912 B (+912 B), count=1 (+1), average=912 B
</code>```

Obviously, tracemalloc is tracing mem_profiler.py rather than the target script; I want the above output, but for whatever script subprocess.py is running! Is this possible with tracemalloc and subroutines? If not, are there another PyPi packages I can use?

Body:
I am attempting to write a generic,python script that memory profiles a target script, but I can't figure out how to get line-by-line memory stats from the script being run by subprocess.

# mem_profiler.py

import subprocess
import tracemalloc

    def profile(script_name, script_args):
        tracemalloc.start() snap1 = tracemalloc.take_snapshot()

        sp = subprocess.Popen["python", script_name] + script_args)
        sp.wait()
        snap2 = tracemalloc.take_snapshot()

        stats = snapshot2.compare_to(snapshot1, 'lineno')

        print("===[ Top 5 stats ]===")
        for stat in stats[:5]:
          print(stat)

Running command python mem_profiler.py --target some_script.py --arg1 --arg2 gives this output:

===[ Top 5 stats ]===
/src/lib/python3.10/subprocess.py:1234: size=1320 B (+1320 B), count=3 (+3), average=440 B
/src/lib/python3.10/os.py:637: size=1248 B (+1248 B), count=3 (+3), average=416 B
/src/lib/python3.10/subprocess.py:971: size=928 B (+928 B), count=1 (+1), average=928 B
/src/mem_profiler.py:43: size=920 B (+920 B), count=2 (+2), average=460 B
/src/mem_profiler.py:27: size=912 B (+912 B), count=1 (+1), average=912 B

Obviously, tracemalloc is tracing mem_profiler.py rather than the target script; I want the above output, but for whatever script subprocess.py is running! Is this possible with tracemalloc and subroutines? If not, are there another PyPi packages I can use?


问:
bioruby how to find regex match coordinates
I am using BioRuby working with a gene sequence (retrieved by API EMBL) and trying to find the coordinates of subsequence found there by Regex/Match. I need the start and end positions of the query subseq in the EMBL Seq. Any suggestion would be very welcome.
Thanks

I found the sub sequence by Regex/Match. And I am wondering if Bio::Fasta::Report::Hit::Query could work just from the documentation but I do not see examples of use.


问:
Chart.js How to limit data shown based only on x-axis labels?
I have a set graph that ranges from 300 - 850 on the y-axis, and the user can update the chart and select a 3, 6, or 12 month range on the x-axis, where the far right value should be the most recent month in the data set.  But Chart.js appends the data that is out of my label range: ] where

labels: ["Apr'17", "May'17", "Jun'17"]

data: [{"x": "Jan'17", "y": 565},{"x": "Mar'17","y": 765},{"x": "Jun'17","y": 665}]

I only want the Jun'17 data point shown here, but Jan'17 and Mar'17 data points are appended.  I can add a max, min limit on the x-scale, but is that the only way to accomplish this?  There seems like there should be a cleaner solution.

It works with the 6 month range as I would expect with the same data, but the previous three months added to the labels array:


问:
Selenium DevTools addListener not working on multiple tabs
I am try to use devTools in selenium 4. When i add listener, with one tab it works great.
But the listener is not responding to the new tab.

My code is

```<code> public static void main(String[] args) throws IOException, InterruptedException
    {
        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.addArguments("--no-sandbox");
        chromeOptions.addArguments("--disable-gpu");

        ChromeDriverService chromeDriverService = new ChromeDriverService.Builder()
                .usingAnyFreePort()
                .usingDriverExecutable(
                        new File(
                               "C:\\dev\\chromedriver.exe"))
                .build();

        ChromeDriver driver = new ChromeDriver(chromeDriverService, chromeOptions);
        DevTools devTools = ((HasDevTools) driver).getDevTools();
        devTools.createSession();
        devTools.send(Log.enable());
        devTools.addListener(Log.entryAdded(), logEntry -> {

            System.out.println("Log Text : " + logEntry.getText());

            System.out.println("Log Level : " + logEntry.getLevel());

            System.out.println("Log Source : " + logEntry.getSource());

            System.out.println("URL : " + logEntry.getUrl().toString());

        });

        driver.get("https://www.google.com//");
        driver.switchTo().newWindow(WindowType.TAB).get("https://www.google.com/");
    }
</code>```

But I only see the log of the first tab, how can I listen the same for the other tabs?

Body:
I am try to use devTools in selenium 4. When i add listener, with one tab it works great.
But the listener is not responding to the new tab.

My code is

 public static void main(String[] args) throws IOException, InterruptedException
    {
        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.addArguments("--no-sandbox");
        chromeOptions.addArguments("--disable-gpu");

        ChromeDriverService chromeDriverService = new ChromeDriverService.Builder()
                .usingAnyFreePort()
                .usingDriverExecutable(
                        new File(
                               "C:\\dev\\chromedriver.exe"))
                .build();

        ChromeDriver driver = new ChromeDriver(chromeDriverService, chromeOptions);
        DevTools devTools = ((HasDevTools) driver).getDevTools();
        devTools.createSession();
        devTools.send(Log.enable());
        devTools.addListener(Log.entryAdded(), logEntry -> {

            System.out.println("Log Text : " + logEntry.getText());

            System.out.println("Log Level : " + logEntry.getLevel());

            System.out.println("Log Source : " + logEntry.getSource());

            System.out.println("URL : " + logEntry.getUrl().toString());

        });

        driver.get("https://www.google.com//");
        driver.switchTo().newWindow(WindowType.TAB).get("https://www.google.com/");
    }

But I only see the log of the first tab, how can I listen the same for the other tabs?