问:
Sending a HTTP POST with a file >2GB from VBA
I try to upload a file (POST request) to a web service through their API in VBA. I get an "out of memory error" if the file is too large.

Unfortunately the web service does not support chunked transfer (which seems to be deprecated since http/2 anyway). Is there a way to "stream" the file without loading it into memory at once before sending?

I would like to avoid calling curl.exe, because it's cleaner.

```<code>    Dim url As String
    Dim dataStream As Object

    Const adTypeBinary = 1
    url = "https://api-endpoint.domain.com"

    Dim oWinHttpReq As Object
    Set oWinHttpReq = CreateObject("WinHttp.WinHttpRequest.5.1")

    With oWinHttpReq
        .Open "POST", url, False
        .setRequestHeader "Content-Type", "application/octet-stream"
        .setRequestHeader "Authorization", "Bearer " & AUTH_TOKEN

        Set dataStream = CreateObject("ADODB.Stream")

        dataStream.Type = adTypeBinary
        dataStream.Open
        dataStream.LoadFromFile filePath

        .send dataStream.Read
    End With
</code>```

I tried Win32 file API as well but cannot transfer the output to the HTTP post.

/edit: I think I came closer. The solution seems to be chunked transfer - by setting the Header "Transfer-Encoding" to "chunked". Looks like you have to handle the chunk structure yourself because WinHTTP 5.1 does only support chunked download, not chunked upload. How do I use the winhttp api with "transfer-encoding: chunked"

But when I set the "Transfer-Encoding" Header, the .send method does not seem to be present anymore

/edit: I developed this function with the help of ChatGPT, but the HttpSendRequest fails...

```<code>
Public Sub UploadFileChunkedLarge(filePath As String, url As String)
    Dim CHUNK_SIZE As Long
    CHUNK_SIZE = CLng(1024) * CLng(1024)   ' 1 MB

    Dim hSession As Long
    Dim hRequest As Long
    Dim hConnection As Long
    Dim lngRetVal As Long
    Dim strBoundary As String
    Dim strPost As String
    Dim strHeader As String
    Dim varData() As Byte
    Dim lngIndex As Long
    Dim lngSize As Long
    Dim lngBytesRead As Long

    Dim result As Boolean

    ' Set the boundary for the POST data
    strBoundary = "---------------------------7d93b2a700d04"

    ' Open the file for binary access
    Open filePath For Binary Access Read As #1

    ' Get the file size
    lngSize = LOF(1)

    ' Create the session
    hSession = InternetOpen("Upload", INTERNET_OPEN_TYPE_PRECONFIG, vbNullString, vbNullString, 0)

    ' Create the request
    hConnection = InternetConnect(hSession, url, INTERNET_DEFAULT_HTTP_PORT, vbNullString, vbNullString, INTERNET_SERVICE_HTTP, 0, 0)
   ' HttpOpenRequest hRequest, "POST", "", "HTTP/1.1", "", "", INTERNET_FLAG_NO_CACHE_WRITE Or INTERNET_FLAG_NO_AUTH, 0
    hRequest = HttpOpenRequest(hConnection, "POST", "", "HTTP/1.1", "", "", INTERNET_FLAG_NO_CACHE_WRITE, 0)

    ' Add the headers
    strHeader = "Content-Type: multipart/form-data; boundary=" & strBoundary & vbCrLf
    strHeader = strHeader & "Authorization: Bearer " & KDRIVE_TOKEN & vbCrLf
    strHeader = strHeader & "Content-Length: " & lngSize & vbCrLf & vbCrLf
    result = HttpAddRequestHeaders(hRequest, strHeader, Len(strHeader), HTTP_ADDREQ_FLAG_ADD)
    Debug.Print WININET_GetLastError
    ' Send the request
    result = HttpSendRequest(hRequest, vbNullString, 0, vbNullString, 0)
    Debug.Print WININET_GetLastError

    ' Send the file data in chunks
    Do While Not EOF(1)
        ' Read the next chunk of data
        ReDim varData(CHUNK_SIZE)
        lngBytesRead = LOF(1) - Loc(1)
        If lngBytesRead > CHUNK_SIZE Then
            lngBytesRead = CHUNK_SIZE
        End If
        Get #1, , varData

        ' Send the chunk
        result = InternetWriteFile(hRequest, varData(0), lngBytesRead, lngIndex)
    Loop

    ' Close the file
    Close #1

    ' Close the request
    InternetCloseHandle hRequest

    ' Close the session
    InternetCloseHandle hSession
End Sub
</code>```

Body:
I try to upload a file (POST request) to a web service through their API in VBA. I get an "out of memory error" if the file is too large.

Unfortunately the web service does not support chunked transfer (which seems to be deprecated since http/2 anyway). Is there a way to "stream" the file without loading it into memory at once before sending?

I would like to avoid calling curl.exe, because it's cleaner.

    Dim url As String
    Dim dataStream As Object

    Const adTypeBinary = 1
    url = "https://api-endpoint.domain.com"

    Dim oWinHttpReq As Object
    Set oWinHttpReq = CreateObject("WinHttp.WinHttpRequest.5.1")

    With oWinHttpReq
        .Open "POST", url, False
        .setRequestHeader "Content-Type", "application/octet-stream"
        .setRequestHeader "Authorization", "Bearer " & AUTH_TOKEN

        Set dataStream = CreateObject("ADODB.Stream")

        dataStream.Type = adTypeBinary
        dataStream.Open
        dataStream.LoadFromFile filePath

        .send dataStream.Read
    End With

I tried Win32 file API as well but cannot transfer the output to the HTTP post.

/edit: I think I came closer. The solution seems to be chunked transfer - by setting the Header "Transfer-Encoding" to "chunked". Looks like you have to handle the chunk structure yourself because WinHTTP 5.1 does only support chunked download, not chunked upload. How do I use the winhttp api with "transfer-encoding: chunked"

But when I set the "Transfer-Encoding" Header, the .send method does not seem to be present anymore

/edit: I developed this function with the help of ChatGPT, but the HttpSendRequest fails...

Public Sub UploadFileChunkedLarge(filePath As String, url As String)
    Dim CHUNK_SIZE As Long
    CHUNK_SIZE = CLng(1024) * CLng(1024)   ' 1 MB

    Dim hSession As Long
    Dim hRequest As Long
    Dim hConnection As Long
    Dim lngRetVal As Long
    Dim strBoundary As String
    Dim strPost As String
    Dim strHeader As String
    Dim varData() As Byte
    Dim lngIndex As Long
    Dim lngSize As Long
    Dim lngBytesRead As Long

    Dim result As Boolean

    ' Set the boundary for the POST data
    strBoundary = "---------------------------7d93b2a700d04"

    ' Open the file for binary access
    Open filePath For Binary Access Read As #1

    ' Get the file size
    lngSize = LOF(1)

    ' Create the session
    hSession = InternetOpen("Upload", INTERNET_OPEN_TYPE_PRECONFIG, vbNullString, vbNullString, 0)

    ' Create the request
    hConnection = InternetConnect(hSession, url, INTERNET_DEFAULT_HTTP_PORT, vbNullString, vbNullString, INTERNET_SERVICE_HTTP, 0, 0)
   ' HttpOpenRequest hRequest, "POST", "", "HTTP/1.1", "", "", INTERNET_FLAG_NO_CACHE_WRITE Or INTERNET_FLAG_NO_AUTH, 0
    hRequest = HttpOpenRequest(hConnection, "POST", "", "HTTP/1.1", "", "", INTERNET_FLAG_NO_CACHE_WRITE, 0)

    ' Add the headers
    strHeader = "Content-Type: multipart/form-data; boundary=" & strBoundary & vbCrLf
    strHeader = strHeader & "Authorization: Bearer " & KDRIVE_TOKEN & vbCrLf
    strHeader = strHeader & "Content-Length: " & lngSize & vbCrLf & vbCrLf
    result = HttpAddRequestHeaders(hRequest, strHeader, Len(strHeader), HTTP_ADDREQ_FLAG_ADD)
    Debug.Print WININET_GetLastError
    ' Send the request
    result = HttpSendRequest(hRequest, vbNullString, 0, vbNullString, 0)
    Debug.Print WININET_GetLastError

    ' Send the file data in chunks
    Do While Not EOF(1)
        ' Read the next chunk of data
        ReDim varData(CHUNK_SIZE)
        lngBytesRead = LOF(1) - Loc(1)
        If lngBytesRead > CHUNK_SIZE Then
            lngBytesRead = CHUNK_SIZE
        End If
        Get #1, , varData

        ' Send the chunk
        result = InternetWriteFile(hRequest, varData(0), lngBytesRead, lngIndex)
    Loop

    ' Close the file
    Close #1

    ' Close the request
    InternetCloseHandle hRequest

    ' Close the session
    InternetCloseHandle hSession
End Sub


来源: stackexchange

问:
React-calendar Prop `aria-label` did not match. Server: "December 26, 2022" Client: "26 December 2022"
I am using react-calendar. The problem comes when the browser console throw an error:
Prop aria-label did not match. Server: "December 26, 2022" Client: "26 December 2022"

I created the Calendar component inside main tag.

```<code> <main>
        <DashboardHeaderInfo userInfo={props.newSession.user}>
            {/* Wrapper section */}
            <section>
              <Calendar
                value={date}
                onChange={handleOnchangeDate}
                onClickDay={value => handleSelectDay(value)}
                />
            </section>

            <CalendarCreateDayModal show={show} setShow={setShow}/>
        </DashboardHeaderInfo>
      </main>
    </Fragment>
</code>```

I dont know what to look for. I cannot find this error anywhere:

ContentLicense: CC BY-SA 4.0

Body:
I am using react-calendar. The problem comes when the browser console throw an error:
Prop aria-label did not match. Server: "December 26, 2022" Client: "26 December 2022"

I created the Calendar component inside main tag.

        <DashboardHeaderInfo userInfo={props.newSession.user}>
            {/* Wrapper section */}

              <Calendar
                value={date}
                onChange={handleOnchangeDate}
                onClickDay={value => handleSelectDay(value)}
                />

            <CalendarCreateDayModal show={show} setShow={setShow}/>
        </DashboardHeaderInfo>

    </Fragment>

I dont know what to look for. I cannot find this error anywhere:


问:
Flutter Android: Making spotbugs-SAST work
I am new to flutter multiplatform (web and mobile).

I have the default spotbugs-SAST setup in gitlab CI for a flutter multiplatform project, and it fails because it does not like the Flutter-specific Android configurations.  So, it wants me to include local.properties which has the default references (absolute paths) to the flutter sdk (flutter.sdk) and android sdk (sdk.dir).

What is the best practice for running spotbugs-SAST for a multiplatform flutter project?


问:
How to set a custom extension in Visual Studio Code
I enjoy writing code in Visual Studio Code. But the .tpl extension in Opencart is actually a file with PHP and HTML, but Visual Studio Code does not recognize this extension. Is it possible to teach Visual Studio Code to open .tpl as html? I mostly do the code in PS pad. Thank you, Ondra

I tried searching on google and didn't find much. Maybe I can't ask the question.


问:
_channel.invokeMethod not working in multi entry-points flutter ios
I have 2 entry-points in my flutter application.
_channel.invokeMethod works well in the first entry point. But it doesn't work in second entry point on iOS (It works OK for android)

Anyone has the same problem ?


问:
Javascript Nesting Doll Problem - How Dangerous Is It?
I ran into an issue in my current project where I needed to access the array that held an object, as the event listener that an object inside that object needed to access all of the elements of the array. So, I did a little test and discovered for myself that you can, in fact, store the container array that contains an object inside that object and it will actually reference the original array, not a copy.

There are some fairly obvious problems with this in terms of being maintainable code, but I'm curious as to what the potential harm of doing this is. Is there anything I should know regarding this recursive property scenario before I put this in my project? Is there a better way to do what I'm looking to do?

For clarity: the way I'm planning on setting it up is as follows:

The array (linesArray) contains a series of objects of class GraphLine. Each Graphline object (lineObject) contains a Raphael canvas element object (line) for the purposes of formatting that element post drawing. It would also contain a reference property to linesArray (container)

I am planning on having the lineObject.line.mousedown() [which fires on clicking the line] event run a for loop through lineObject.container, aka linesArray, to transform each of the lineObject.line's within it based off of which lineObject.line fired the lineObject.line.mousedown() event.

It would look something like this:

class GraphLine {
    id;
    line;
    lineStr;
    container;

    constructor(container, /* Bunch of Inputs */) {
        this.container = container;
        //...
    }

    Draw() {
        this.line = canvas.path(this.lineStr);

        this.line.mousedown( function() {
            for(let i = 0; i < this.container.length;i i++) {
                if(this.container[i].id != this.id) {
                    //Do A Thing
                }
                else {
                    //Do A Different Thing
                }
            }
        });
    }
}

var canvas;

$(document).ready(function() {
    function Run() {
        var container = [];

        canvas = new Raphael($('#canvas'), 100, 100);

        container.push(new GraphLine(container, /* Bunch of Inputs */));
        //...
        container[0].Draw();
    }

    Run();
});
```


问:
Can I disable Screenshot/screen capture in react web app?
I would like to know whether we can disable screenshot or screen capture in firebase react progressive web app ? Please reply on priority

I am looking for the reply as soon as possible


问:
How do I paginate an update in Node Cassandra?
I cannot find a standard way to paginate my update in Cassandra using the Node connector. I cannot find any resource that would explain how to do it or whether it is possible at all.

My function looks like this:

```<code>
async function whitelistCustomers(account, customerIds) {
    let data = [account._id.toString(), customerIds]
    let options = { prepare: true, fetchSize: 200 }
    let query = "UPDATE customers SET reason_blacklist=null WHERE id_account = ? AND id IN ?"

    await new Promise((resolve, reject) => {
        function rowCallback(n, rows) {}

        function callback(err, result) {
            if (err) reject(err)
            else resolve()
        }

        client.eachRow(query, data, options, rowCallback, callback)
    })
}
</code>```

But it does not seem to work. When there are lots of customerIds, the query fails with PayloadTooLargeError: too many parameters.

I could solve this by making a custom JS pagination. I would iterate over customerIds and make multiple queries to Cassandra with small portions of customerIds each, but if I could find a more standard way to do this it would be best.

```<code>
    do {
        let paginatedCustomerIds = customerIds.splice(0, 200)
        // make a request with paginatedCustomerIds
    } while (customerIds.length > 0)
</code>```

Is it possible to paginate the update request? If yes how do I do it?

Body:
I cannot find a standard way to paginate my update in Cassandra using the Node connector. I cannot find any resource that would explain how to do it or whether it is possible at all.

My function looks like this:

async function whitelistCustomers(account, customerIds) {
    let data = [account._id.toString(), customerIds]
    let options = { prepare: true, fetchSize: 200 }
    let query = "UPDATE customers SET reason_blacklist=null WHERE id_account = ? AND id IN ?"

    await new Promise((resolve, reject) => {
        function rowCallback(n, rows) {}

        function callback(err, result) {
            if (err) reject(err)
            else resolve()
        }

        client.eachRow(query, data, options, rowCallback, callback)
    })
}

But it does not seem to work. When there are lots of customerIds, the query fails with PayloadTooLargeError: too many parameters.

I could solve this by making a custom JS pagination. I would iterate over customerIds and make multiple queries to Cassandra with small portions of customerIds each, but if I could find a more standard way to do this it would be best.

    do {
        let paginatedCustomerIds = customerIds.splice(0, 200)
        // make a request with paginatedCustomerIds
    } while (customerIds.length > 0)

Is it possible to paginate the update request? If yes how do I do it?


问:
Plot decision region does not correspond to my accuracy
I've made some SVM model and I have a problem with some parameters.

Here is my code :

```<code>fig, ax = plt.subplots(3,3, figsize=(15,10))
index = 1

for a,i in zip(ax,C):
    for b,j in zip(a,G):
        poly = SVC(kernel='poly', C = i, gamma = j, degree = 3, cache_size = 1000)
        poly_model = poly.fit(x_train, y_train)
        poly_pred = poly_model.predict(x_test)
        POLY = poly_model
        POLY.fit(x_train2, y_train)
        ax = plt.subplot(3,3,index)
        plot_decision_regions(x_train2, y_train, clf = POLY, zoom_factor = 1, legend = 0)
        plt.title(f'C = {i} Gamma = {j} Accuracy: {accuracy_score(y_test, poly_pred):.3f}')
        #plt.scatter(x_test_pca[:, 0], x_test_pca[:, 1], c='red', edgecolors='black', s=10, label='test')
        #plt.scatter(linear_model.support_vectors_[:, 0], linear_model.support_vectors_[:, 1], s=20, color='red')
        index += 1

plt.suptitle("Polynomial kernel")
plt.show()
</code>```

And here is my result:

On the first left-up plot, I see only 2 decision regions but my accuracy is equal to 0.978! What's the problem?

NB: I am working on the Iris dataset

When zoom_factor = 0.2, it is the same problem, I try to modify the clf parameters from POLY to poly but it doesn't matter.

Body:
I've made some SVM model and I have a problem with some parameters.

Here is my code :

fig, ax = plt.subplots(3,3, figsize=(15,10))
index = 1

for a,i in zip(ax,C):
    for b,j in zip(a,G):
        poly = SVC(kernel='poly', C = i, gamma = j, degree = 3, cache_size = 1000)
        poly_model = poly.fit(x_train, y_train)
        poly_pred = poly_model.predict(x_test)
        POLY = poly_model
        POLY.fit(x_train2, y_train)
        ax = plt.subplot(3,3,index)
        plot_decision_regions(x_train2, y_train, clf = POLY, zoom_factor = 1, legend = 0)
        plt.title(f'C = {i} Gamma = {j} Accuracy: {accuracy_score(y_test, poly_pred):.3f}')
        #plt.scatter(x_test_pca[:, 0], x_test_pca[:, 1], c='red', edgecolors='black', s=10, label='test')
        #plt.scatter(linear_model.support_vectors_[:, 0], linear_model.support_vectors_[:, 1], s=20, color='red')
        index += 1

plt.suptitle("Polynomial kernel")
plt.show()

And here is my result:

On the first left-up plot, I see only 2 decision regions but my accuracy is equal to 0.978! What's the problem?

NB: I am working on the Iris dataset

When zoom_factor = 0.2, it is the same problem, I try to modify the clf parameters from POLY to poly but it doesn't matter.


问:
Can't get value from asyncstorage in react native to be intial state
I am looking for a way to write my code so that I can set my Redux toolkit state to be coming from the asyncstorage. Here is my code:

```<code>const initialState={
token: null,
session: AsyncStorage.getItem('sessionId') || null,
loading: false,
error: false
}

const userSlice = createSlice({
name: 'user',
initialState,

  reducers:{
   ......
   }
})
export default  userSlice.reducer;
</code>```

Definitely, AsyncStorage returns a Promise so it is not getting resolved before I assigned the value to initial state. How Do I achieve this? In web, this can be done. How do I access the AsyncStorage as the first place to check if the user has a sessionId?

Body:
I am looking for a way to write my code so that I can set my Redux toolkit state to be coming from the asyncstorage. Here is my code:

const initialState={
token: null,
session: AsyncStorage.getItem('sessionId') || null,
loading: false,
error: false
}

const userSlice = createSlice({
name: 'user',
initialState,

  reducers:{
   ......
   }
})
export default  userSlice.reducer;

Definitely, AsyncStorage returns a Promise so it is not getting resolved before I assigned the value to initial state. How Do I achieve this? In web, this can be done. How do I access the AsyncStorage as the first place to check if the user has a sessionId?


问:
Creating login page through Microsoft Azure or OneDrive (WPF, Onedrive, Azure)
I was wondering if there is a way for someone to login to a WPF app (kind of like logging into your outlook account), authenticate whether the user is on the OneDrive/Microsoft server, and displaying separate UI's depending on the user's permissions (like sales vs. engineering).

I haven't found much information on this and was wondering if anyone has had any experience deploying an application like this.


问:
GitLab K8s Runner fails for get_sources
we are trying to move gitlab-runners from standard CentOS VMs to kebernetes.
But after setup and registration, pipeline fails with unknown error:

```<code>Running with gitlab-runner 15.7.0 (259d2fd4)
  on Kubernetes-local JXRw3mH1
Preparing the "kubernetes" executor
00:00
Using Kubernetes namespace: gitlab-runner
Using Kubernetes executor with image gitlab-test.domain:5005/image:latest ...
Using attach strategy to execute scripts...
Preparing environment
00:04
Waiting for pod gitlab-runner/runner-jxrw3mh1-project-290-concurrent-0dpd88 to be running, status is Pending
Running on runner-jxrw3mh1-project-290-concurrent-0dpd88 via gitlab-runner-d7df6c548-hsgxg...
Getting source from Git repository
00:00
error: could not lock config file /root/.gitconfig: Read-only file system
Cleaning up project directory and file based variables
00:01
ERROR: Job failed: command terminated with exit code 1
</code>```

Inside the log of the job pod we found:

```<code> helper Running on runner-jxrw3mh1-project-290-concurrent-0dpd88 via gitlab-runner-d7df6c548-hsgxg...
 helper
 helper {"command_exit_code": 0, "script": "/scripts-290-207166/prepare_script"}
 helper error: could not lock config file /root/.gitconfig: Read-only file system
 helper
 helper {"command_exit_code": 1, "script": "/scripts-290-207166/get_sources"}
 helper
 helper {"command_exit_code": 0, "script": "/scripts-290-207166/cleanup_file_variables"}
</code>```

Inside the log of the gitlab-runner pod we found:

```<code> Starting in container "helper" the command ["gitlab-runner-build" "<<<" "/scripts-290-207167/get_sources" "2>&1 | tee -a /logs-290-207167/output.log"] with script: #!/usr/bin/env bash
 if set -o | grep pipefail > /dev/null; then set -o pipefail; fi; set -o errexit
 set +o noclobber
 : | eval $'export FF_CMD_DISABLE_DELAYED_ERROR_LEVEL_EXPANSION=$\'false\'\nexport FF_NETWORK_PER_BUILD=$\'false\'\nexport FF_USE_LEGACY_KUBERNETES_EXECUTION_STRATEGY=$\'false\'\nexport FF_USE_DIRECT_DOWNLOAD
 exit 0
   job=207167 project=290 runner=JXRw3mH1
 Remote process exited with the status: CommandExitCode: 1, Script: /scripts-290-207167/get_sources  job=207167 project=290 runner=JXRw3mH1
 Container "helper" exited with error: command terminated with exit code 1  job=207167 project=290 runner=JXRw3mH1
</code>```

notes:

the error "error: could not lock config file /root/.gitconfig: Read-only file system" is due to the current user inside container is different by root

the file /logs-290-207167/output.log contains the log of the job pod

Inside job pod shell we also tested some git commands and perform successfully fetch and clone using our personal credentials (the same user that perform the run of the pipeline from gitlab gui).

We think the problem can be related on gitlab-ci-token, but we have finished our investigation... :frowning:

Title: GitLab K8s Runner fails for get_sources

Body:
we are trying to move gitlab-runners from standard CentOS VMs to kebernetes.
But after setup and registration, pipeline fails with unknown error:

Running with gitlab-runner 15.7.0 (259d2fd4)
  on Kubernetes-local JXRw3mH1
Preparing the "kubernetes" executor
00:00
Using Kubernetes namespace: gitlab-runner
Using Kubernetes executor with image gitlab-test.domain:5005/image:latest ...
Using attach strategy to execute scripts...
Preparing environment
00:04
Waiting for pod gitlab-runner/runner-jxrw3mh1-project-290-concurrent-0dpd88 to be running, status is Pending
Running on runner-jxrw3mh1-project-290-concurrent-0dpd88 via gitlab-runner-d7df6c548-hsgxg...
Getting source from Git repository
00:00
error: could not lock config file /root/.gitconfig: Read-only file system
Cleaning up project directory and file based variables
00:01
ERROR: Job failed: command terminated with exit code 1

Inside the log of the job pod we found:

 helper Running on runner-jxrw3mh1-project-290-concurrent-0dpd88 via gitlab-runner-d7df6c548-hsgxg...
 helper
 helper {"command_exit_code": 0, "script": "/scripts-290-207166/prepare_script"}
 helper error: could not lock config file /root/.gitconfig: Read-only file system
 helper
 helper {"command_exit_code": 1, "script": "/scripts-290-207166/get_sources"}
 helper
 helper {"command_exit_code": 0, "script": "/scripts-290-207166/cleanup_file_variables"}

Inside the log of the gitlab-runner pod we found:

 Starting in container "helper" the command ["gitlab-runner-build" "<<<" "/scripts-290-207167/get_sources" "2>&1 | tee -a /logs-290-207167/output.log"] with script: #!/usr/bin/env bash
 if set -o | grep pipefail > /dev/null; then set -o pipefail; fi; set -o errexit
 set +o noclobber
 : | eval $'export FF_CMD_DISABLE_DELAYED_ERROR_LEVEL_EXPANSION=$\'false\'\nexport FF_NETWORK_PER_BUILD=$\'false\'\nexport FF_USE_LEGACY_KUBERNETES_EXECUTION_STRATEGY=$\'false\'\nexport FF_USE_DIRECT_DOWNLOAD
 exit 0
   job=207167 project=290 runner=JXRw3mH1
 Remote process exited with the status: CommandExitCode: 1, Script: /scripts-290-207167/get_sources  job=207167 project=290 runner=JXRw3mH1
 Container "helper" exited with error: command terminated with exit code 1  job=207167 project=290 runner=JXRw3mH1

notes:

the error "error: could not lock config file /root/.gitconfig: Read-only file system" is due to the current user inside container is different by root

the file /logs-290-207167/output.log contains the log of the job pod

Inside job pod shell we also tested some git commands and perform successfully fetch and clone using our personal credentials (the same user that perform the run of the pipeline from gitlab gui).

We think the problem can be related on gitlab-ci-token, but we have finished our investigation... :frowning:


问:
How can I import HTMLButtonElement into ReactNative
I'd like use HTMLButtonElement instead React Button element in my code.
I get error when I run this code:

```<code>import React from 'react';
import {SafeAreaView} from 'react-native';

const App = () => {
  return (
    <SafeAreaView>
      <button title="test" data-code="test" />
    </SafeAreaView>
  );
};

export default App;
</code>```

Error message is:

ReactNativeJS: Invariant Violation: View config getter callback for
component button must be a function (received undefined). Make
sure to start component names with a capital letter.

Body:
I'd like use HTMLButtonElement instead React Button element in my code.
I get error when I run this code:

import React from 'react';
import {SafeAreaView} from 'react-native';

const App = () => {
  return (
    <SafeAreaView>
      <button title="test" data-code="test" />
    </SafeAreaView>
  );
};

export default App;

Error message is:

ReactNativeJS: Invariant Violation: View config getter callback for
component button must be a function (received undefined). Make
sure to start component names with a capital letter.


问:
Typing issue when mapping a useState object
I am creating a simple modal form where you create a team, and you can assign existing users to said team. This is the relevant part of the modal;

```<code>export default function CreateTeamModal() {
const [memberData, setMemberData] = useState([{}]);
const users = useUsers();

return (
      <Modal>
              <Box
                  component="form"
                  sx={style}
                  noValidate
                  onSubmit={onSave}
                  autoComplete="off"
              >
                      <FormControl>
                          <InputLabel id="demo-multiple-chip-label">Members</InputLabel>
                          <Select
                              labelId="demo-multiple-chip-label"
                              id="demo-multiple-chip"
                              multiple
                              value={memberData.name}
                              onChange={handleMemberChange}
                              input={<OutlinedInput id="select-multiple-chip" label="Members" />}
                              renderValue={(selected) => (
                                  <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
                                      {selected.map((value) => (
                                          <Chip key={value} label={value} />
                                      ))}
                                  </Box>
                              )}
                          >
                              {users.map((user) => {
                                return(
                                  <MenuItem
                                      key={user.id as number}
                                      value={user}
                                  >
                                      {user.name}
                                  </MenuItem>
                                )
                              })}
                          </Select>
                      </FormControl>
                  </div>
              </Box>
          </Modal>
          </>
  );
}
</code>```

useUsers is a custom hook defined like so;

```<code>export const useUsers = () => {
  const [users, setUsers] = useState<User[]>([]);

  useEffect(() => {
    let subscribed = true;
    let apiClient = new APIClient();
    apiClient.getUser().then((response) => {
        if (subscribed) {
        setUsers(response);
        }
    });

    return () => {
        subscribed = false
    };
  }, []);

  return users;
};
</code>```

Obviously this implementation doesn't work here, but the users.map is working elsewhere. Now, if I do something like this;

```<code>function returnThis(a) {
    return a;
}

var returnedUsers = returnThis(users);

{returnedUsers.map((user) => {
  return(
   <MenuItem
     key={user.id as number}
     value={user}
    >
   {user.name}
   </MenuItem>
  )
})}
</code>```

Then I get no issues with the map. Which area(s) am I going wrong with, and how should I fix them?

Body:
I am creating a simple modal form where you create a team, and you can assign existing users to said team. This is the relevant part of the modal;

export default function CreateTeamModal() {
const [memberData, setMemberData] = useState([{}]);
const users = useUsers();

return (
      <Modal>
              <Box
                  component="form"
                  sx={style}
                  noValidate
                  onSubmit={onSave}
                  autoComplete="off"
              >
                      <FormControl>
                          <InputLabel id="demo-multiple-chip-label">Members</InputLabel>
                          <Select
                              labelId="demo-multiple-chip-label"
                              id="demo-multiple-chip"
                              multiple
                              value={memberData.name}
                              onChange={handleMemberChange}
                              input={<OutlinedInput id="select-multiple-chip" label="Members" />}
                              renderValue={(selected) => (
                                  <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
                                      {selected.map((value) => (
                                          <Chip key={value} label={value} />
                                      ))}
                                  </Box>
                              )}
                          >
                              {users.map((user) => {
                                return(
                                  <MenuItem
                                      key={user.id as number}
                                      value={user}
                                  >
                                      {user.name}
                                  </MenuItem>
                                )
                              })}
                          </Select>
                      </FormControl>

              </Box>
          </Modal>
          </>
  );
}

useUsers is a custom hook defined like so;

export const useUsers = () => {
  const [users, setUsers] = useState<User[]>([]);

  useEffect(() => {
    let subscribed = true;
    let apiClient = new APIClient();
    apiClient.getUser().then((response) => {
        if (subscribed) {
        setUsers(response);
        }
    });

    return () => {
        subscribed = false
    };
  }, []);

  return users;
};

Obviously this implementation doesn't work here, but the users.map is working elsewhere. Now, if I do something like this;

function returnThis(a) {
    return a;
}

var returnedUsers = returnThis(users);

{returnedUsers.map((user) => {
  return(
   <MenuItem
     key={user.id as number}
     value={user}
    >
   {user.name}
   </MenuItem>
  )
})}

Then I get no issues with the map. Which area(s) am I going wrong with, and how should I fix them?


问:
Creating an Inventory of gcloud instances using googleapiclient
I am attempting to use googleapiclient.discovery.build('compute', 'v1').instances() to generate a list of devices. The below works fine but I want to know if there is a way I can pass format "json(disks,networkInterfaces,machineType,scheduling)" through cmdCompute.instances().list or even csv format. The current output is really messy.

I have gone through the docs but cannot seem so see a way. I know I can do it with gcloud but I am not able to use gcloud in a gcloud function which is where this script is going to be executed. The file will be used by other cloud functions so I would like a cleaner output.

`
from datetime import datetime, timedelta
from google.cloud import storage

```<code>from googleapiclient.discovery import build
from oauth2client.client import GoogleCredentials

def fncListVMs(self):
    strHostProjectID='project'
    strZone='zone'
    strBucketName = 'bucketname'

    credentials = GoogleCredentials.get_application_default()
    cmdCompute=build('compute', 'v1',credentials=credentials, static_discovery=False)

    strOutput = cmdCompute.instances().list(project=strHostProjectID, zone=strZone,filter=    ('status=RUNNING')).execute()
    strFile = strHostProjectID+"_Instance.json"

    stoClient = storage.Client()
    strBucket=stoClient.get_bucket(strBucketName)
    strBlob = strBucket.blob('scripts/output/'+strFile)
    with strBlob.open(mode='w') as strTarget:
        strTarget.write(str(strOutput))

    return "Done"
</code>```

`

Body:
I am attempting to use googleapiclient.discovery.build('compute', 'v1').instances() to generate a list of devices. The below works fine but I want to know if there is a way I can pass format "json(disks,networkInterfaces,machineType,scheduling)" through cmdCompute.instances().list or even csv format. The current output is really messy.

I have gone through the docs but cannot seem so see a way. I know I can do it with gcloud but I am not able to use gcloud in a gcloud function which is where this script is going to be executed. The file will be used by other cloud functions so I would like a cleaner output.

`
from datetime import datetime, timedelta
from google.cloud import storage

from googleapiclient.discovery import build
from oauth2client.client import GoogleCredentials

def fncListVMs(self):
    strHostProjectID='project'
    strZone='zone'
    strBucketName = 'bucketname'

    credentials = GoogleCredentials.get_application_default()
    cmdCompute=build('compute', 'v1',credentials=credentials, static_discovery=False)

    strOutput = cmdCompute.instances().list(project=strHostProjectID, zone=strZone,filter=    ('status=RUNNING')).execute()
    strFile = strHostProjectID+"_Instance.json"

    stoClient = storage.Client()
    strBucket=stoClient.get_bucket(strBucketName)
    strBlob = strBucket.blob('scripts/output/'+strFile)
    with strBlob.open(mode='w') as strTarget:
        strTarget.write(str(strOutput))

    return "Done"

`


问:
How to add event listener for console logs in selenium Python?
I have the following code which works in getting the console log messages when the function is called, the problem is the console log list driver.get_log('browser') is not self updating. The console log messages are only gathered in driver.get_log('browser') when printConsoleLog function is called. How do i add an event listener to the console to automatically display console log messages in Python selenium 4?

```<code>from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.common.log import Log
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium import webdriver
import trio
import time

service = Service(executable_path=f"C:/Users/Dell/Desktop/PyCharm/bl/chromedriver.exe")

def wait_seconds(t):
   time.sleep(t)

def printConsoleLogs():
   options = Options()
   options.add_experimental_option('excludeSwitches', ['enable-logging'])

   dc = DesiredCapabilities.CHROME
   dc["goog:loggingPrefs"] = {"browser":"INFO"}

   driver = webdriver.Chrome(service=service, options=options, desired_capabilities=dc)
   driver.get("http://localhost:9091")

   time.sleep(5)

   for entry in driver.get_log('browser'):
        print(entry)

   time.sleep(5)

   for repeat in driver.get_log('browser'):
        print(repeat)

printConsoleLogs()
</code>```

Body:
I have the following code which works in getting the console log messages when the function is called, the problem is the console log list driver.get_log('browser') is not self updating. The console log messages are only gathered in driver.get_log('browser') when printConsoleLog function is called. How do i add an event listener to the console to automatically display console log messages in Python selenium 4?

from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.common.log import Log
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium import webdriver
import trio
import time

service = Service(executable_path=f"C:/Users/Dell/Desktop/PyCharm/bl/chromedriver.exe")

def wait_seconds(t):
   time.sleep(t)

def printConsoleLogs():
   options = Options()
   options.add_experimental_option('excludeSwitches', ['enable-logging'])

   dc = DesiredCapabilities.CHROME
   dc["goog:loggingPrefs"] = {"browser":"INFO"}

   driver = webdriver.Chrome(service=service, options=options, desired_capabilities=dc)
   driver.get("http://localhost:9091")

   time.sleep(5)

   for entry in driver.get_log('browser'):
        print(entry)

   time.sleep(5)

   for repeat in driver.get_log('browser'):
        print(repeat)

printConsoleLogs()


问:
Use bash script to source through multiple .env files at once
I currently have a bash script that loops through all .env files, these files are nested in subdirectories, and I want to source each env file (making them seen under printenv command), how do I go about it?

Currently, I have this script

```<code>#!/bin/bash

for i in $(find . -type f -iname '.env'); do
    echo $i
done
</code>```

Which outputs:

```<code>./packages/database/.env
./packages/api/.env
./packages/email/.env
./apps/starter/.env
</code>```

This does not work:

```<code>for i in $(find . -type f -iname '.env'); do
    source $i
done
</code>```

Body:
I currently have a bash script that loops through all .env files, these files are nested in subdirectories, and I want to source each env file (making them seen under printenv command), how do I go about it?

Currently, I have this script

#!/bin/bash

for i in $(find . -type f -iname '.env'); do
    echo $i
done

Which outputs:

./packages/database/.env
./packages/api/.env
./packages/email/.env
./apps/starter/.env

This does not work:

for i in $(find . -type f -iname '.env'); do
    source $i
done


问:
Programmatically converting SLDPRT to STL file without external tools, APIs, etc
I am working on attempting to convert SLDPRT (as well as STEP) files to STL files programmatically without the use of external tools or APIs.

Here's an example of an API that does this: https://anyconv.com/sldprt-to-stl-converter/

I understand that STL files are binary files that can simply be converted to ASCII. I am trying to figure out what text encoding is used on SLDPRT files and how I can extract this into readable text that can be parsed and formatted as an STL file. I currently have a web page created with JavaScript and PHP in which I would like to upload SLDPRT files, convert them to STL files on the server, and view them in THREE.js.

Using Python Code

```<code>filename = "LABL_Double.SLDPRT"

with open(filename, "rb") as file:
    hex_list = [ord(c) for c in f'{file.read()}']
    print(hex_list)`
</code>```

I used the following code to attempt to look inside the SolidWorks file and received a long list of integers such as:

```<code>[123, 23, 34, 5, 23, 0, ... 57, 97, 112, 91, 39]
</code>```

If I change the code to the following:

```<code>filename = "LABL_Double.SLDPRT"

with open(filename, "rb") as file:
    print(file.read())
</code>```

I then receive a binary string output with hex values as such:

```<code>b'\x87>\xd1#\x00\x00\x00\x04k...\xd2\x1d\xafxa8\xbe\xc4\x8c\x9ap['
</code>```

What can I do with these two different outputs from reading the SLDPRT file. Can either of them be converted to human-readable text that can be parsed and converted into an STL file? I know this is possible to do stand alone within a program because tools like SolidWorks and the provided API above are capable of this. Any help regarding knowledge behind what is going inside SolidWorks files would be greatly appreciated.

Body:
I am working on attempting to convert SLDPRT (as well as STEP) files to STL files programmatically without the use of external tools or APIs.

Here's an example of an API that does this: https://anyconv.com/sldprt-to-stl-converter/

I understand that STL files are binary files that can simply be converted to ASCII. I am trying to figure out what text encoding is used on SLDPRT files and how I can extract this into readable text that can be parsed and formatted as an STL file. I currently have a web page created with JavaScript and PHP in which I would like to upload SLDPRT files, convert them to STL files on the server, and view them in THREE.js.

Using Python Code

filename = "LABL_Double.SLDPRT"

with open(filename, "rb") as file:
    hex_list = [ord(c) for c in f'{file.read()}']
    print(hex_list)`

I used the following code to attempt to look inside the SolidWorks file and received a long list of integers such as:

[123, 23, 34, 5, 23, 0, ... 57, 97, 112, 91, 39]

If I change the code to the following:

filename = "LABL_Double.SLDPRT"

with open(filename, "rb") as file:
    print(file.read())

I then receive a binary string output with hex values as such:

b'\x87>\xd1#\x00\x00\x00\x04k...\xd2\x1d\xafxa8\xbe\xc4\x8c\x9ap['

What can I do with these two different outputs from reading the SLDPRT file. Can either of them be converted to human-readable text that can be parsed and converted into an STL file? I know this is possible to do stand alone within a program because tools like SolidWorks and the provided API above are capable of this. Any help regarding knowledge behind what is going inside SolidWorks files would be greatly appreciated.


问:
Why doesn't .Net use an object's actual type when referenced as a base-class, and what can I do about it?
MRE on .NetFiddle

```<code>using System;

class Base {}
class SubClass1 : Base{}
class SubClass2 : Base{}

public class Program
{
    public static void Main()
    {
        Test(new Base());
        Test(new SubClass1());
        Test(new SubClass2());

        var o = new Base(); Test(o);
        o = new SubClass1(); Test(o);
        o = new SubClass2(); Test(o);
    }

    static void Test(Base o) => Console.WriteLine($"Test Base on {o.GetType()}");
    static void Test(SubClass1 o) => Console.WriteLine($"Test SubClass1 on {o.GetType()}");
    static void Test(SubClass2 o) => Console.WriteLine($"Test SubClass2 on {o.GetType()}");
}
</code>```

Test Base on Base

Test SubClass1 on SubClass1

Test SubClass2 on SubClass2

Test Base on Base

Test Base on SubClass1

Test Base on SubClass2

Why does .Net not match the 'best' method in the second set of calls, and use the referenced type rather than the actual object type? Just "because it does" or because this would lead to many other problems in the language?

Other than having to explicitly check the type (maybe using a switch pattern) is there a workaround?

Body:
MRE on .NetFiddle

using System;

class Base {}
class SubClass1 : Base{}
class SubClass2 : Base{}

public class Program
{
    public static void Main()
    {
        Test(new Base());
        Test(new SubClass1());
        Test(new SubClass2());

        var o = new Base(); Test(o);
        o = new SubClass1(); Test(o);
        o = new SubClass2(); Test(o);
    }

    static void Test(Base o) => Console.WriteLine($"Test Base on {o.GetType()}");
    static void Test(SubClass1 o) => Console.WriteLine($"Test SubClass1 on {o.GetType()}");
    static void Test(SubClass2 o) => Console.WriteLine($"Test SubClass2 on {o.GetType()}");
}

Test Base on Base

Test SubClass1 on SubClass1

Test SubClass2 on SubClass2

Test Base on Base

Test Base on SubClass1

Test Base on SubClass2

Why does .Net not match the 'best' method in the second set of calls, and use the referenced type rather than the actual object type? Just "because it does" or because this would lead to many other problems in the language?

Other than having to explicitly check the type (maybe using a switch pattern) is there a workaround?


问:
How can I manually edit pyflowchart output entered on flowchart.js.org?
I need to create a flowchart for my python code for documentation purposes. I tried using pyflowchart and flowchart.js.org but since my code contains 600+ lines, the flowchart is huge and complex. So I tried to edit the textual representation, but got errors. Can someone please explain the syntax of these textual representations, so that I can edit the flowchart according to my needs.</p>


问:
Posting XML SOAP Envelope on Lazarus
I'm struggling with application "client side" to communicate with service.
Requirement for that type of communication is to use XML Soap Envelope.

I'm trying to use TFPHTTPClient for that. I prepare Form to see response from serwer but something is missing.
When I send a request I receive error "Stream read error"
On Form I put Button and Memo1 for displaing XML code and Memo2 for answear.
Interesting is when I copy code from memo1 and paste into SoapUI everything is OK
My code is:

```<code>    procedure TForm1.Button2Click(Sender: TObject);
        var
          FPHTTPClient: TFPHTTPClient;
          SL: TStringList;
          Str: String;

        begin
          FPHTTPClient := TFPHTTPClient.Create(nil);
          try
            FPHTTPClient.AllowRedirect := True;
            FPHTTPClient.KeepConnection:=True;
            FPHTTPClient.AddHeader('Content-Type','application/soap+xml;charset=utf-8');
            FPHTTPClient.AddHeader('User-Agent','Apache-HttpClient/4.5.5 (Java/16.0.1)');

            SL := TStringList.Create;

            try
              SL.Add('<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:ns="http://CIS/BIR/PUBL/2014/07"> ');
              SL.Add('<soap:Header xmlns:wsa="http://www.w3.org/2005/08/addressing">');
              SL.Add('<wsa:To>https://wyszukiwarkaregontest.stat.gov.pl/wsBIR/UslugaBIRzewnPubl.svc</wsa:To>');
              SL.Add('<wsa:Action>http://CIS/BIR/PUBL/2014/07/IUslugaBIRzewnPubl/Zaloguj</wsa:Action>');
              SL.Add('</soap:Header>');
              SL.Add('<soap:Body>');
              SL.Add('<ns:Zaloguj>');
              SL.Add('<ns:pKluczUzytkownika>abcde12345abcde12345</ns:pKluczUzytkownika>');
              SL.Add('</ns:Zaloguj>');
              SL.Add('</soap:Body>');
              SL.Add('</soap:Envelope>');

        Memo1.Lines.BeginUpdate;
        Memo1.Lines := SL;
        Memo1.Lines.EndUpdate;
              try

                Str:=FPHTTPClient.FormPost('https://wyszukiwarkaregontest.stat.gov.pl/wsBIR/UslugaBIRzewnPubl.svc',SL);
                            //ShowMessage(Str);

        Memo2.text := Str;

              except
                on E: exception do
                  ShowMessage(E.Message);
              end;
            finally
              SL.Free;
            end;
          finally
            FPHTTPClient.Free;
          end;
        end;

</code>```

Title: Posting XML SOAP Envelope on Lazarus

Body:
I'm struggling with application "client side" to communicate with service.
Requirement for that type of communication is to use XML Soap Envelope.

I'm trying to use TFPHTTPClient for that. I prepare Form to see response from serwer but something is missing.
When I send a request I receive error "Stream read error"
On Form I put Button and Memo1 for displaing XML code and Memo2 for answear.
Interesting is when I copy code from memo1 and paste into SoapUI everything is OK
My code is:

    procedure TForm1.Button2Click(Sender: TObject);
        var
          FPHTTPClient: TFPHTTPClient;
          SL: TStringList;
          Str: String;

        begin
          FPHTTPClient := TFPHTTPClient.Create(nil);
          try
            FPHTTPClient.AllowRedirect := True;
            FPHTTPClient.KeepConnection:=True;
            FPHTTPClient.AddHeader('Content-Type','application/soap+xml;charset=utf-8');
            FPHTTPClient.AddHeader('User-Agent','Apache-HttpClient/4.5.5 (Java/16.0.1)');

            SL := TStringList.Create;

            try
              SL.Add('<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:ns="http://CIS/BIR/PUBL/2014/07"> ');
              SL.Add('<soap:Header xmlns:wsa="http://www.w3.org/2005/08/addressing">');
              SL.Add('<wsa:To>https://wyszukiwarkaregontest.stat.gov.pl/wsBIR/UslugaBIRzewnPubl.svc</wsa:To>');
              SL.Add('<wsa:Action>http://CIS/BIR/PUBL/2014/07/IUslugaBIRzewnPubl/Zaloguj</wsa:Action>');
              SL.Add('</soap:Header>');
              SL.Add('<soap:Body>');
              SL.Add('<ns:Zaloguj>');
              SL.Add('<ns:pKluczUzytkownika>abcde12345abcde12345</ns:pKluczUzytkownika>');
              SL.Add('</ns:Zaloguj>');
              SL.Add('</soap:Body>');
              SL.Add('</soap:Envelope>');

        Memo1.Lines.BeginUpdate;
        Memo1.Lines := SL;
        Memo1.Lines.EndUpdate;
              try

                Str:=FPHTTPClient.FormPost('https://wyszukiwarkaregontest.stat.gov.pl/wsBIR/UslugaBIRzewnPubl.svc',SL);
                            //ShowMessage(Str);

        Memo2.text := Str;

              except
                on E: exception do
                  ShowMessage(E.Message);
              end;
            finally
              SL.Free;
            end;
          finally
            FPHTTPClient.Free;
          end;
        end;


问:
How do I Configure paths in Blazor WASM that are on the same host but outside of Blazor
I have some Apps that are MVC in part and Blazor in other parts. Generally once I'm in Blazor, I can't get out. It captures every page request, locally giving not found errors for pages that would be served by controllers.

I had thought that there should be a way to configure this, for example a global setting for paths that Navigation Manager sees as External (even on same host). Maybe configuring /admin/ as a real whole page fetch (leaving the Blazor SPA altogether).

Does anybody have any idea how such a thing could be configured or implemented?

Thanks.


问:
NETSUITE Apply Credit Memo CSV
Im trying to apply a credit memo to invoice using suitecript and using a CSV import.

```<code>var fileObjCSV_notas = file.create({
            name:  context.csv_notas+'_'+context.csvName+'.csv',
            fileType: file.Type.CSV,
            contents: context.csv_notas,
            description: 'CSV RECIBOCOBRO_notas',
            encoding: file.Encoding.UTF8,
            folder: 18763624,
            isOnline: true
            });
            var fileIdcsv_notas = fileObjCSV_notas.save();
            log.error('IDARCHIVO',fileIdcsv_notas);

        var scriptTask_notas = task.create({taskType: task.TaskType.CSV_IMPORT});
        scriptTask_notas.mappingId = 306;
        tas
        var f_notas = file.load({id: fileIdcsv_notas});

        scriptTask_notas.importFile = f_notas;

        var csvImportTaskId = scriptTask_notas.submit();
</code>```

In the  import status page says  "1 of 1 records imported successfully" but de credit memo remains open, but If I use the same user in UI  the import works perfectly.

Title: NETSUITE Apply Credit Memo CSV

Body:
Im trying to apply a credit memo to invoice using suitecript and using a CSV import.

var fileObjCSV_notas = file.create({
            name:  context.csv_notas+'_'+context.csvName+'.csv',
            fileType: file.Type.CSV,
            contents: context.csv_notas,
            description: 'CSV RECIBOCOBRO_notas',
            encoding: file.Encoding.UTF8,
            folder: 18763624,
            isOnline: true
            });
            var fileIdcsv_notas = fileObjCSV_notas.save();
            log.error('IDARCHIVO',fileIdcsv_notas);

        var scriptTask_notas = task.create({taskType: task.TaskType.CSV_IMPORT});
        scriptTask_notas.mappingId = 306;
        tas
        var f_notas = file.load({id: fileIdcsv_notas});

        scriptTask_notas.importFile = f_notas;

        var csvImportTaskId = scriptTask_notas.submit();

In the  import status page says  "1 of 1 records imported successfully" but de credit memo remains open, but If I use the same user in UI  the import works perfectly.


问:
Upgraded Java Project missing JSF Framework in Netbeans 16
I have recently upgraded a java maven project from JDK 8 to JDK 17 as well as changed IDEs from Netbeans 13 to Netbeans 16.

The project builds but when I go to run I get errors about the java server faces.
When I look at the project properties -> Frameworks -> JavaServer Faces the libaries are blank.

Is this an issue with Netbeans 16 or am I missing something?

If I open the same project in Netbeans 13 it has JavaServer Faces library entries.

I have tried to update the JavaServer faces library's in maven, the JDK 17 and the tried to add a differnt version of JSF via maven into the project, but the proejct frameworks remain blank .


问:
404 error when redirect to Angular UI index.html page from Spring Boot
We have a web application (Backend: Spring Boot microservice: Frontend: Angular UI) for reporting.

Few weeks ago several critical vulnerabilities popped up when build the UI using npm 7.24.2 (Angular 11 and node 12). To remediate these vulnerabilities we have to upgrade Angular from v11 to v14 and node v12 to v16.

The http request flow is outlined below:

application url

(redirect) Company's SSO authentication

(redirect) Spring boot Authorization/Role Assignment service

(redirect) Angular UI index.html page

The application was running fine before this Angular upgrade, but now  the response of step 4 (from spring boot microservice to angular ui index.html page) is always a error page with the following message after a successful login (authentication and authorization):

```<code>{"timeStamp":"Wen Jan 11 13:22;23 UTC 2023", "status":"404","error":"Not Found","message":"NotFound","path":"/"}
</code>```

Note:
(1) This happens when the application is deployed to AppEngine, running on local PC is OK
(2) The spring boot microservice and angular UI project are two standalone components/services. If we put the entire compiled angular UI contents from /dist folder into the Spring boot service under the /resource/public(or static) folder, the whole application will run fine. But we have to run them as two standalone components, that is, a UI application and a microservice.

Any help is highly appreciated!

We tried to add an index controller and error registry in the spring boot service, we also tried to add a static index.html page under spring /resources/public to force manually redirect to the Angular Ui index.html page, neither of them worked.

Body:
We have a web application (Backend: Spring Boot microservice: Frontend: Angular UI) for reporting.

Few weeks ago several critical vulnerabilities popped up when build the UI using npm 7.24.2 (Angular 11 and node 12). To remediate these vulnerabilities we have to upgrade Angular from v11 to v14 and node v12 to v16.

The http request flow is outlined below:

application url

(redirect) Company's SSO authentication

(redirect) Spring boot Authorization/Role Assignment service

(redirect) Angular UI index.html page

The application was running fine before this Angular upgrade, but now  the response of step 4 (from spring boot microservice to angular ui index.html page) is always a error page with the following message after a successful login (authentication and authorization):

{"timeStamp":"Wen Jan 11 13:22;23 UTC 2023", "status":"404","error":"Not Found","message":"NotFound","path":"/"}

Note:
(1) This happens when the application is deployed to AppEngine, running on local PC is OK
(2) The spring boot microservice and angular UI project are two standalone components/services. If we put the entire compiled angular UI contents from /dist folder into the Spring boot service under the /resource/public(or static) folder, the whole application will run fine. But we have to run them as two standalone components, that is, a UI application and a microservice.

Any help is highly appreciated!

We tried to add an index controller and error registry in the spring boot service, we also tried to add a static index.html page under spring /resources/public to force manually redirect to the Angular Ui index.html page, neither of them worked.


问:
ggplot: Reorder Facet rows in facet.grid
I am having issues reorganizing my rows using facet.grid. I have four groups that by default are organized alphabetically. Using the factor command I can organize the groups - but they switch to columns (horizontal) and I need rows (vertical).

Example of subset of my data

```<code>Site            Date       Analyte    Result
   SJR@Calaveres    5/26/22    Top TP    0.35
   SJR@Ship Channel 5/26/22    Top TP   0.56
   Turning Basin    5/26/22    Top TP    0.46
   Morelli Boat Ramp 5/26/22    Top TP  0.45
   Public Dock      5/26/22    Top TP     0.55

wi_daily_wq<-read.csv("nutrients_p.csv")
 p <- ggplot(data = wi_daily_wq, aes(x = Date, y = Result))+
   geom_point(aes(color = Site)) +
   theme_bw()
 p

 # Add vertical facets, aka divide the plot up vertically since they share an x axis
 p + facet_grid(Analyte ~ .)

 # Add vertical facets, but scale only the y axes freely
 p + facet_grid(Analyte ~ ., scales = "free_y")
 p + facet_grid(Analyte ~ ., scales = "free_y",
                switch = "y") # flip the facet labels along the y axis from the right side to the left

#Trying to organize rows in order that I want
p + facet_grid(~factor (Analyte,levels=c('Bottom TP','Top TP','Bottom PO4','Top PO4')))
         ylab(NULL) + # remove the word "values"
       theme(strip.background = element_blank(), # remove the background
             strip.placement = "outside")  # put labels to the left of the axis text
</code>```

If I remove the following argument from the above code I get the row plot I like. But, the rows are just in alphabetical order, not the order I need them in.

```<code>p + facet_grid(~factor (Analyte,levels=c('Bottom TP','Top TP','Bottom PO4','Top PO4')))
</code>```

I'm wondering what adjustment I need to make to my code to organize the rows in the order I need them without converting the facets to columns.

Body:
I am having issues reorganizing my rows using facet.grid. I have four groups that by default are organized alphabetically. Using the factor command I can organize the groups - but they switch to columns (horizontal) and I need rows (vertical).

Example of subset of my data

Site            Date       Analyte    Result
   SJR@Calaveres    5/26/22    Top TP    0.35
   SJR@Ship Channel 5/26/22    Top TP   0.56
   Turning Basin    5/26/22    Top TP    0.46
   Morelli Boat Ramp 5/26/22    Top TP  0.45
   Public Dock      5/26/22    Top TP     0.55

wi_daily_wq<-read.csv("nutrients_p.csv")
 p <- ggplot(data = wi_daily_wq, aes(x = Date, y = Result))+
   geom_point(aes(color = Site)) +
   theme_bw()
 p

 # Add vertical facets, aka divide the plot up vertically since they share an x axis
 p + facet_grid(Analyte ~ .)

 # Add vertical facets, but scale only the y axes freely
 p + facet_grid(Analyte ~ ., scales = "free_y")
 p + facet_grid(Analyte ~ ., scales = "free_y",
                switch = "y") # flip the facet labels along the y axis from the right side to the left

#Trying to organize rows in order that I want
p + facet_grid(~factor (Analyte,levels=c('Bottom TP','Top TP','Bottom PO4','Top PO4')))
         ylab(NULL) + # remove the word "values"
       theme(strip.background = element_blank(), # remove the background
             strip.placement = "outside")  # put labels to the left of the axis text

If I remove the following argument from the above code I get the row plot I like. But, the rows are just in alphabetical order, not the order I need them in.

p + facet_grid(~factor (Analyte,levels=c('Bottom TP','Top TP','Bottom PO4','Top PO4')))

I'm wondering what adjustment I need to make to my code to organize the rows in the order I need them without converting the facets to columns.


问:
Conjugate gradient with tensorflow and sparse tensor runs slower than scipy with sparse matrices
I implemented the conjugate gradient method using TensorFlow to invert a sparse matrix.
The matrix I used to test the method is well-conditioned, as it is the sum of a mass matrix and a stiffness matrix obtained with finite elements.

I compared with the same method implemented using scipy and on the same data.
The solutions obtained with either methods are the same, however, TensorFlow is 5 times slower (I tested under colab environment).

Under colab environment, scipy ran in 0.27 s, while TensorFlow required 1.37 s

Why the algorithm is so slow under TensorFlow?

I can not cast to dense matrices, as I want to use the formula with matrices of large size (100k X100k or more).

Thanks,

Cesare

Here is the code I used to test this:

```<code>import tensorflow as tf
import numpy as np
from scipy.sparse import coo_matrix,linalg
import os
import sys
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
from time import time
from scipy.spatial import Delaunay

def create_mesh(Lx=1,Ly=1,Nx=100,Ny=100):
    mesh0=dict()
    dx = Lx/Nx
    dy = Ly/Ny
    XX,YY=np.meshgrid(np.arange(0,Lx+dx,dx),np.arange(0,Ly+dy,dy))
    points=np.vstack((XX.ravel(),YY.ravel())).T
    #np.random.shuffle(points)
    tri = Delaunay(points)
    mesh0['Pts']=np.copy(points).astype(np.float32)
    mesh0['Tria']=np.copy(tri.simplices).astype(int)
    return(mesh0)

def eval_connectivity(mesh0):
    print('computing mesh connectivity')
    npt=mesh0['Pts'].shape[0]
    connectivity = {}
    for jpt in range(npt):
        connectivity[jpt] = []
    for Tria in mesh0['Tria']:
        for ilpt in range(3):
            iglobalPt=Tria[ilpt]
            for jlpt in range(1+ilpt,3):
                jglobalPt=Tria[jlpt]
                connectivity[iglobalPt].append(jglobalPt)
                connectivity[jglobalPt].append(iglobalPt)
    for key,value in connectivity.items():
        connectivity[key]=np.unique(np.array(value,dtype=int))
    return(connectivity)

def eval_local_mass(mesh0,iTri):
    lmass = np.zeros(shape=(3,3),dtype=np.float32)
    Tria=mesh0['Tria'][iTri]
    v10   = mesh0['Pts'][Tria[1],:]-mesh0['Pts'][Tria[0],:]
    v20   = mesh0['Pts'][Tria[2],:]-mesh0['Pts'][Tria[0],:]
    N12   = np.cross(v10,v20)
    Tsurf = 0.5*np.linalg.norm(N12)
    for ipt in range(3):
            lmass[ipt,ipt]=1.0/12.0
            for jpt in range(1+ipt,3):
                lmass[ipt,jpt] = 1.0/24.0
                lmass[jpt,ipt] = lmass[ipt,jpt]
    lmass = 2.0*Tsurf*lmass
    return(lmass)

def eval_local_stiffness(mesh0,iTri):
    Tria  = mesh0['Tria'][iTri]
    v10   = mesh0['Pts'][Tria[1],:]-mesh0['Pts'][Tria[0],:]
    v20   = mesh0['Pts'][Tria[2],:]-mesh0['Pts'][Tria[0],:]
    N12   = np.cross(v10,v20)
    Tsurf = 0.5*np.linalg.norm(N12)
    covbT = np.zeros(shape=(3,3),dtype=np.float32)
    covbT[0,:2] = v10
    covbT[1,:2] = v20
    covbT[2,2]  = N12/(2*Tsurf)
    contrb      = np.linalg.inv(covbT)
    v1          = contrb[:,0]
    v2          = contrb[:,1]
    a     = np.dot(v1,v1)
    b     = np.dot(v1,v2)
    c     = np.dot(v2,v2)
    gij_c = np.array([[a,b],[b,c]],dtype=np.float32)
    lgrad = np.array([[-1.0,1.0,0.0], [-1.0,0.0,1.0] ],dtype=np.float32)
    lstif = Tsurf*np.matmul( np.matmul(lgrad.T,gij_c), lgrad )
    return(lstif)

def compute_vectors_sparse_matrices(mesh0):
    npt     =  mesh0['Pts'].shape[0]
    connect = eval_connectivity(mesh0)
    nzero   = 0
    for key,value in connect.items():
        nzero += (1+value.shape[0])
    I  = np.zeros(shape=(nzero),dtype=int)
    J  = np.zeros(shape=(nzero),dtype=int)
    VM = np.zeros(shape=(nzero),dtype=np.float32)
    VS = np.zeros(shape=(nzero),dtype=np.float32)
    k0 = np.zeros(shape=(npt+1),dtype=int)

    k0[0] = 0
    k     = -1
    for jpt in range(npt):
        loc_con = connect[jpt].tolist()[:]
        loc_con.append(jpt)
        loc_con = np.sort(loc_con)
        k0[jpt+1]=k0[jpt]+loc_con.shape[0]
        for jloc in range(loc_con.shape[0]):
            k=k+1
            I[k]= jpt
            J[k]= loc_con[jloc]

    for iTr, Tria in enumerate(mesh0['Tria']):
        lstiff = eval_local_stiffness(mesh0,iTr)
        lmass  = eval_local_mass(mesh0,iTr)
        for iEntry,irow in enumerate(Tria):
            loc_con = connect[irow].tolist()[:]
            loc_con.append(irow)
            loc_con = np.sort(loc_con)
            for jEntry,jcol in enumerate(Tria):
                indexEntry     = k0[irow]+np.where(loc_con==jcol)[0]
                VM[indexEntry] = VM[indexEntry]+lmass[iEntry,jEntry]
                VS[indexEntry] = VS[indexEntry]+lstiff[iEntry,jEntry]
    return(I,J,VM,VS)

def compute_global_sparse_matrices(mesh0):
    I,J,VM,VS = compute_vectors_sparse_matrices(mesh0)
    npt       =  mesh0['Pts'].shape[0]
    MASS      = coo_matrix((VM,(I,J)),shape=(npt,npt))
    STIFF     = coo_matrix((VS,(I,J)),shape=(npt,npt))
    return(MASS,STIFF)

def compute_global_sparse_tensors(mesh0):
    I,J,VM,VS = compute_vectors_sparse_matrices(mesh0)
    npt       =  mesh0['Pts'].shape[0]
    indices   = np.hstack([I[:,np.newaxis], J[:,np.newaxis]])
    MASS      = tf.sparse.SparseTensor(indices=indices, values=VM.astype(np.float32), dense_shape=[npt, npt])
    STIFF     = tf.sparse.SparseTensor(indices=indices, values=VS.astype(np.float32), dense_shape=[npt, npt])
    return(MASS,STIFF)

def compute_matrices_scipy(mesh0):
    MASS,STIFF = compute_global_sparse_matrices(mesh0)
    return(MASS,STIFF)

def compute_matrices_tensorflow(mesh0):
    MASS,STIFF = compute_global_sparse_tensors(mesh0)
    return(MASS,STIFF)

def conjgrad_scipy(A,b,x0,niter=100,toll=1.e-5):
    x     = np.copy(x0)
    r     = b - A * x
    p     = np.copy(r)
    rsold = np.dot(r,r)

    for it in range(niter):
        Ap    = A * p
        alpha = rsold /np.dot(p,Ap)
        x     += alpha * p
        r     -= alpha * Ap
        rsnew = np.dot(r,r)
        if (np.sqrt(rsnew) < toll):
            break
        p = r + (rsnew / rsold) * p
        rsold = rsnew
    return([x,it,np.sqrt(rsnew)])

def conjgrad_tensorflow(A,b,x0,niter=100,toll=1.e-5):
    x     = x0
    r     = b - tf.sparse.sparse_dense_matmul(A,x)
    p     = r
    rsold = tf.reduce_sum(tf.multiply(r, r))
    for it in range(niter):
        Ap    = tf.sparse.sparse_dense_matmul(A,p)
        alpha = rsold /tf.reduce_sum(tf.multiply(p, Ap))
        x     += alpha * p
        r     -= alpha * Ap
        rsnew = tf.reduce_sum(tf.multiply(r, r))
        if (tf.sqrt(rsnew) < toll):
            break
        p = r + (rsnew / rsold) * p
        rsold = rsnew
    return([x,it,tf.sqrt(rsnew)])

mesh     = create_mesh(Lx=10,Ly=10,Nx=100,Ny=100)
x0       = tf.constant(  (mesh['Pts'][:,0]<5 ).astype(np.float32) )
nit_time = 10
dcoef    = 1.0
maxit    = x0.shape[0]//2
stoll    = 1.e-6
print('nb of nodes:\t{}'.format(mesh['Pts'].shape[0]))
print('nb of trias:\t{}'.format(mesh['Tria'].shape[0]))

t0 = time()
MASS0,STIFF0  = compute_matrices_scipy(mesh)
elapsed_scipy=time()-t0
print('Matrices; elapsed: {:3.5f} s'.format(elapsed_scipy))

A           = MASS0+dcoef*STIFF0
x           = np.copy(np.squeeze(x0.numpy()) )
t0 = time()
for jt in range(nit_time):
    b = MASS0*x
    x1,it,tol=conjgrad_scipy(A,b,x,niter=maxit,toll=stoll)
    x=np.copy(x1)
    print('time {}; iters {}; resid: {:3.2f}'.format(1+jt,it,tol) )
elapsed_scipy=time()-t0
print('elapsed, scipy: {:3.5f} s'.format(elapsed_scipy))

t0 = time()
MASS,STIFF  =compute_matrices_tensorflow(mesh)
elapsed=time()-t0
print('Matrices; elapsed: {:3.5f} s'.format(elapsed))

x = None
x1 = None
A           = tf.sparse.add(MASS,tf.sparse.map_values(tf.multiply, STIFF, dcoef))
x           = tf.expand_dims(tf.identity(x0),axis=1)
t0 = time()
for jt in range(nit_time):
    b = tf.sparse.sparse_dense_matmul(MASS,x)
    x1,it,tol=conjgrad_tensorflow(A,b,x,niter=maxit,toll=stoll)
    x = x1
    print('time {}; iters {}; resid: {:3.2f}'.format(1+jt,it,tol) )
elapsed_tf=time()-t0
print('elapsed, tf: {:3.2f} s'.format(elapsed_tf))

print('elapsed times:')
print('scipy: {:3.2f} s\ttf: {:3.2f} s'.format(elapsed_scipy,elapsed_tf))
</code>```

Body:
I implemented the conjugate gradient method using TensorFlow to invert a sparse matrix.
The matrix I used to test the method is well-conditioned, as it is the sum of a mass matrix and a stiffness matrix obtained with finite elements.

I compared with the same method implemented using scipy and on the same data.
The solutions obtained with either methods are the same, however, TensorFlow is 5 times slower (I tested under colab environment).

Under colab environment, scipy ran in 0.27 s, while TensorFlow required 1.37 s

Why the algorithm is so slow under TensorFlow?

I can not cast to dense matrices, as I want to use the formula with matrices of large size (100k X100k or more).

Thanks,

Cesare

Here is the code I used to test this:

import tensorflow as tf
import numpy as np
from scipy.sparse import coo_matrix,linalg
import os
import sys
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
from time import time
from scipy.spatial import Delaunay

def create_mesh(Lx=1,Ly=1,Nx=100,Ny=100):
    mesh0=dict()
    dx = Lx/Nx
    dy = Ly/Ny
    XX,YY=np.meshgrid(np.arange(0,Lx+dx,dx),np.arange(0,Ly+dy,dy))
    points=np.vstack((XX.ravel(),YY.ravel())).T
    #np.random.shuffle(points)
    tri = Delaunay(points)
    mesh0['Pts']=np.copy(points).astype(np.float32)
    mesh0['Tria']=np.copy(tri.simplices).astype(int)
    return(mesh0)

def eval_connectivity(mesh0):
    print('computing mesh connectivity')
    npt=mesh0['Pts'].shape[0]
    connectivity = {}
    for jpt in range(npt):
        connectivity[jpt] = []
    for Tria in mesh0['Tria']:
        for ilpt in range(3):
            iglobalPt=Tria[ilpt]
            for jlpt in range(1+ilpt,3):
                jglobalPt=Tria[jlpt]
                connectivity[iglobalPt].append(jglobalPt)
                connectivity[jglobalPt].append(iglobalPt)
    for key,value in connectivity.items():
        connectivity[key]=np.unique(np.array(value,dtype=int))
    return(connectivity)

def eval_local_mass(mesh0,iTri):
    lmass = np.zeros(shape=(3,3),dtype=np.float32)
    Tria=mesh0['Tria'][iTri]
    v10   = mesh0['Pts'][Tria[1],:]-mesh0['Pts'][Tria[0],:]
    v20   = mesh0['Pts'][Tria[2],:]-mesh0['Pts'][Tria[0],:]
    N12   = np.cross(v10,v20)
    Tsurf = 0.5*np.linalg.norm(N12)
    for ipt in range(3):
            lmass[ipt,ipt]=1.0/12.0
            for jpt in range(1+ipt,3):
                lmass[ipt,jpt] = 1.0/24.0
                lmass[jpt,ipt] = lmass[ipt,jpt]
    lmass = 2.0*Tsurf*lmass
    return(lmass)

def eval_local_stiffness(mesh0,iTri):
    Tria  = mesh0['Tria'][iTri]
    v10   = mesh0['Pts'][Tria[1],:]-mesh0['Pts'][Tria[0],:]
    v20   = mesh0['Pts'][Tria[2],:]-mesh0['Pts'][Tria[0],:]
    N12   = np.cross(v10,v20)
    Tsurf = 0.5*np.linalg.norm(N12)
    covbT = np.zeros(shape=(3,3),dtype=np.float32)
    covbT[0,:2] = v10
    covbT[1,:2] = v20
    covbT[2,2]  = N12/(2*Tsurf)
    contrb      = np.linalg.inv(covbT)
    v1          = contrb[:,0]
    v2          = contrb[:,1]
    a     = np.dot(v1,v1)
    b     = np.dot(v1,v2)
    c     = np.dot(v2,v2)
    gij_c = np.array([[a,b],[b,c]],dtype=np.float32)
    lgrad = np.array([[-1.0,1.0,0.0], [-1.0,0.0,1.0] ],dtype=np.float32)
    lstif = Tsurf*np.matmul( np.matmul(lgrad.T,gij_c), lgrad )
    return(lstif)

def compute_vectors_sparse_matrices(mesh0):
    npt     =  mesh0['Pts'].shape[0]
    connect = eval_connectivity(mesh0)
    nzero   = 0
    for key,value in connect.items():
        nzero += (1+value.shape[0])
    I  = np.zeros(shape=(nzero),dtype=int)
    J  = np.zeros(shape=(nzero),dtype=int)
    VM = np.zeros(shape=(nzero),dtype=np.float32)
    VS = np.zeros(shape=(nzero),dtype=np.float32)
    k0 = np.zeros(shape=(npt+1),dtype=int)

    k0[0] = 0
    k     = -1
    for jpt in range(npt):
        loc_con = connect[jpt].tolist()[:]
        loc_con.append(jpt)
        loc_con = np.sort(loc_con)
        k0[jpt+1]=k0[jpt]+loc_con.shape[0]
        for jloc in range(loc_con.shape[0]):
            k=k+1
            I[k]= jpt
            J[k]= loc_con[jloc]

    for iTr, Tria in enumerate(mesh0['Tria']):
        lstiff = eval_local_stiffness(mesh0,iTr)
        lmass  = eval_local_mass(mesh0,iTr)
        for iEntry,irow in enumerate(Tria):
            loc_con = connect[irow].tolist()[:]
            loc_con.append(irow)
            loc_con = np.sort(loc_con)
            for jEntry,jcol in enumerate(Tria):
                indexEntry     = k0[irow]+np.where(loc_con==jcol)[0]
                VM[indexEntry] = VM[indexEntry]+lmass[iEntry,jEntry]
                VS[indexEntry] = VS[indexEntry]+lstiff[iEntry,jEntry]
    return(I,J,VM,VS)

def compute_global_sparse_matrices(mesh0):
    I,J,VM,VS = compute_vectors_sparse_matrices(mesh0)
    npt       =  mesh0['Pts'].shape[0]
    MASS      = coo_matrix((VM,(I,J)),shape=(npt,npt))
    STIFF     = coo_matrix((VS,(I,J)),shape=(npt,npt))
    return(MASS,STIFF)

def compute_global_sparse_tensors(mesh0):
    I,J,VM,VS = compute_vectors_sparse_matrices(mesh0)
    npt       =  mesh0['Pts'].shape[0]
    indices   = np.hstack([I[:,np.newaxis], J[:,np.newaxis]])
    MASS      = tf.sparse.SparseTensor(indices=indices, values=VM.astype(np.float32), dense_shape=[npt, npt])
    STIFF     = tf.sparse.SparseTensor(indices=indices, values=VS.astype(np.float32), dense_shape=[npt, npt])
    return(MASS,STIFF)

def compute_matrices_scipy(mesh0):
    MASS,STIFF = compute_global_sparse_matrices(mesh0)
    return(MASS,STIFF)

def compute_matrices_tensorflow(mesh0):
    MASS,STIFF = compute_global_sparse_tensors(mesh0)
    return(MASS,STIFF)

def conjgrad_scipy(A,b,x0,niter=100,toll=1.e-5):
    x     = np.copy(x0)
    r     = b - A * x
    p     = np.copy(r)
    rsold = np.dot(r,r)

    for it in range(niter):
        Ap    = A * p
        alpha = rsold /np.dot(p,Ap)
        x     += alpha * p
        r     -= alpha * Ap
        rsnew = np.dot(r,r)
        if (np.sqrt(rsnew) < toll):
            break
        p = r + (rsnew / rsold) * p
        rsold = rsnew
    return([x,it,np.sqrt(rsnew)])

def conjgrad_tensorflow(A,b,x0,niter=100,toll=1.e-5):
    x     = x0
    r     = b - tf.sparse.sparse_dense_matmul(A,x)
    p     = r
    rsold = tf.reduce_sum(tf.multiply(r, r))
    for it in range(niter):
        Ap    = tf.sparse.sparse_dense_matmul(A,p)
        alpha = rsold /tf.reduce_sum(tf.multiply(p, Ap))
        x     += alpha * p
        r     -= alpha * Ap
        rsnew = tf.reduce_sum(tf.multiply(r, r))
        if (tf.sqrt(rsnew) < toll):
            break
        p = r + (rsnew / rsold) * p
        rsold = rsnew
    return([x,it,tf.sqrt(rsnew)])

mesh     = create_mesh(Lx=10,Ly=10,Nx=100,Ny=100)
x0       = tf.constant(  (mesh['Pts'][:,0]<5 ).astype(np.float32) )
nit_time = 10
dcoef    = 1.0
maxit    = x0.shape[0]//2
stoll    = 1.e-6
print('nb of nodes:\t{}'.format(mesh['Pts'].shape[0]))
print('nb of trias:\t{}'.format(mesh['Tria'].shape[0]))

t0 = time()
MASS0,STIFF0  = compute_matrices_scipy(mesh)
elapsed_scipy=time()-t0
print('Matrices; elapsed: {:3.5f} s'.format(elapsed_scipy))

A           = MASS0+dcoef*STIFF0
x           = np.copy(np.squeeze(x0.numpy()) )
t0 = time()
for jt in range(nit_time):
    b = MASS0*x
    x1,it,tol=conjgrad_scipy(A,b,x,niter=maxit,toll=stoll)
    x=np.copy(x1)
    print('time {}; iters {}; resid: {:3.2f}'.format(1+jt,it,tol) )
elapsed_scipy=time()-t0
print('elapsed, scipy: {:3.5f} s'.format(elapsed_scipy))

t0 = time()
MASS,STIFF  =compute_matrices_tensorflow(mesh)
elapsed=time()-t0
print('Matrices; elapsed: {:3.5f} s'.format(elapsed))

x = None
x1 = None
A           = tf.sparse.add(MASS,tf.sparse.map_values(tf.multiply, STIFF, dcoef))
x           = tf.expand_dims(tf.identity(x0),axis=1)
t0 = time()
for jt in range(nit_time):
    b = tf.sparse.sparse_dense_matmul(MASS,x)
    x1,it,tol=conjgrad_tensorflow(A,b,x,niter=maxit,toll=stoll)
    x = x1
    print('time {}; iters {}; resid: {:3.2f}'.format(1+jt,it,tol) )
elapsed_tf=time()-t0
print('elapsed, tf: {:3.2f} s'.format(elapsed_tf))

print('elapsed times:')
print('scipy: {:3.2f} s\ttf: {:3.2f} s'.format(elapsed_scipy,elapsed_tf))


问:
Python - Getting Feature importance scores from Logistic Regression model in 6 digits
I'm trying to find the feature importance of a Logistic Regression model and the importance score values returned are way too higher than expected. Expected the scores to be in the range of single digits, but obtained 6 digit figures.

Here are the details of my model.

The data is highly imbalanced and hence using Random Oversampling on minority class.

```<code>oversample = RandomOverSampler(sampling_strategy='minority')
Xo_train, yo_train = oversample.fit_resample(X_train, y_train)
</code>```

Normalize Xo_train:

```<code>norm = preprocessing.Normalizer()
Xo_train_norm = norm.fit_transform(Xo_train)
</code>```

Using Logistic Regression with Grid search on hyper parameters:

```<code>params_LogReg = {}
params_LogReg['solver'] = ['lbfgs', 'newton-cg', 'ga']
params_LogReg['penalty'] = ['none', 'l2']
params_LogReg['C'] = [0.05, 0.1, 0.5]

model_LogReg = LogisticRegression()
search = RandomizedSearchCV(model_LogReg, params_LogReg, n_iter = 10, scoring = 'recall_weighted', n_jobs = -1)
tuned_LogReg = search.fit(Xo_train_norm, yo_train)
</code>```

Got below parameters after fitting:

```<code>LogisticRegression(C=0.1, penalty='none', solver='newton-cg')
</code>```

Calculating feature importance as below:

```<code>importance = tuned_LogReg.best_estimator_.coef_[0]
</code>```

The 3 top scores I got for the features are as below and rest in the same pattern:

```<code>| Feature      | Importance Score |
|:-----------  | ----------------:|
|NWK_CNT_bins  |       560178.044 |
|PAID_AMT_bins |       467168.967 |
|Grad_Rate_bins|       443438.490 |
</code>```

'*_bins' are continuous columns grouped into 4 bins.

Never expected the importance scores to be in 6 digits. Is it normal ? Or am I missing something in the calculations ? Any insight is greatly appreciated. Thank you.

Body:
I'm trying to find the feature importance of a Logistic Regression model and the importance score values returned are way too higher than expected. Expected the scores to be in the range of single digits, but obtained 6 digit figures.

Here are the details of my model.

The data is highly imbalanced and hence using Random Oversampling on minority class.

oversample = RandomOverSampler(sampling_strategy='minority')
Xo_train, yo_train = oversample.fit_resample(X_train, y_train)

Normalize Xo_train:

norm = preprocessing.Normalizer()
Xo_train_norm = norm.fit_transform(Xo_train)

Using Logistic Regression with Grid search on hyper parameters:

params_LogReg = {}
params_LogReg['solver'] = ['lbfgs', 'newton-cg', 'ga']
params_LogReg['penalty'] = ['none', 'l2']
params_LogReg['C'] = [0.05, 0.1, 0.5]

model_LogReg = LogisticRegression()
search = RandomizedSearchCV(model_LogReg, params_LogReg, n_iter = 10, scoring = 'recall_weighted', n_jobs = -1)
tuned_LogReg = search.fit(Xo_train_norm, yo_train)

Got below parameters after fitting:

LogisticRegression(C=0.1, penalty='none', solver='newton-cg')

Calculating feature importance as below:

importance = tuned_LogReg.best_estimator_.coef_[0]

The 3 top scores I got for the features are as below and rest in the same pattern:

| Feature      | Importance Score |
|:-----------  | ----------------:|
|NWK_CNT_bins  |       560178.044 |
|PAID_AMT_bins |       467168.967 |
|Grad_Rate_bins|       443438.490 |

'*_bins' are continuous columns grouped into 4 bins.

Never expected the importance scores to be in 6 digits. Is it normal ? Or am I missing something in the calculations ? Any insight is greatly appreciated. Thank you.


问:
Format a string w/ Java MaskFormatter in Databricks/Scala
I create a function based on Java MaskFormatter function in Databricks/Scala.

But when I call it from sparksql, I received error message

Error in SQL statement: AnalysisException: Undefined function:
formatAccount. This function is neither a built-in/temporary function,
nor a persistent function that is qualified as
spark_catalog.default.formataccount.; line 1 pos 32

Here is my function

```<code>import javax.swing.text.MaskFormatter
def formatAccount(account: String, mask:String ) : String =
{
 val formatter = new MaskFormatter(mask.replace("X", "A"))

 formatter.setValueContainsLiteralCharacters(false)

 val formatAccount = formatter.valueToString(account)

  formatAccount
}
</code>```

Here is the query code which received the error message

```<code>sql("""select java_method(emitToKafka ,formatAccount("1222233334", "X-XXXX-XXXX-X"))""")
</code>```

However if I run below code, it works fine.

```<code>formatAccount("1222233334", "X-XXXX-XXXX-X")

res0: String = 1-2222-3333-4
</code>```

what could be missed?

Body:
I create a function based on Java MaskFormatter function in Databricks/Scala.

But when I call it from sparksql, I received error message

Error in SQL statement: AnalysisException: Undefined function:
formatAccount. This function is neither a built-in/temporary function,
nor a persistent function that is qualified as
spark_catalog.default.formataccount.; line 1 pos 32

Here is my function

import javax.swing.text.MaskFormatter
def formatAccount(account: String, mask:String ) : String =
{
 val formatter = new MaskFormatter(mask.replace("X", "A"))

 formatter.setValueContainsLiteralCharacters(false)

 val formatAccount = formatter.valueToString(account)

  formatAccount
}

Here is the query code which received the error message

sql("""select java_method(emitToKafka ,formatAccount("1222233334", "X-XXXX-XXXX-X"))""")

However if I run below code, it works fine.

formatAccount("1222233334", "X-XXXX-XXXX-X")

res0: String = 1-2222-3333-4

what could be missed?


问:
Project vue + vite + quasar inconsistent after build, taking long time to load some fonts
I have a project in Vue3 + Quasar + Vite, I've been developing it and so far so good. But when I did the build and uploaded it to the production environment it has some inconsistencies, usually the first time I access the page in the day, the page loads without some quasar fonts, icons and with a horizontal scroll, after refreshing the page it back to normal operation, the problem is that this behavior keeps repeating itself, print below the operation when it occurs correctly (circled in orange) and when the error occurs (circled in red), just a font that I believe is generated by Quasar, it's taking 158798ms to load. Someone had this issue before?

Error