问:
notCompatibleWithConfigurationCache() not working with Gradle task, keeps Reusing configuration cache anyways
The configuration cache is enabled in the Gradle settings for the project, yet for this task it reuses the configuration cache anyways. Before I would always use the --no-configuration-cache flag since it would not edit the baseline file on consecutive runs. I updated Gradle and use notCompatibleWithConfigurationCache() in other tasks, yet only for this one it still reuses the configuration cache. How can I fix this? Is there another way I could read/write the file without having to use --no-configuration-cache?

This was the code I was using:

```<code>tasks.register("fixBaseline", Copy){
    notCompatibleWithConfigurationCache()
    List<String> fileList = []

    // Read in file list
    if (project.hasProperty("directory")) {
        // Read in files from directory
        String directoryPath = project.property(directoryProperty) as String
        def fileNameFinder = new FileNameFinder()
        def pathList = fileNameFinder.getFileNames("$rootDir$File.separator$directoryPath", "**/*.kt")

        for (pathName in pathList) {
            def f = file(pathName)
            fileList.add(f.name)
        }
    }

    // Remove lines from baseline
    def baselineDir = "$rootDir/config/base"
    def baselineFile = file("$rootDir/config/base/baseline.xml")
    def outputFile = File.createTempFile("remove", ".tmp", baselineFile.getParentFile())
    int linesRemoved = 0

    project.logger.lifecycle("Clearing files from baseline...\n")
    outputFile.withPrintWriter { outputWriter ->
        baselineFile.eachLine { line, lineNumber ->
            for (fileName in fileList){
                if (line.contains(fileName)){
                    linesRemoved++
                    return
                }
            }
            outputWriter.println(line)
        }
    }

    // Rename temporary file to baseline.xml
    from baselineDir
    include outputFile.name
    destinationDir file(baselineDir)
    rename outputFile.name, baselineFile.name

    project.logger.lifecycle("\nRemoved $linesRemoved lines")
    project.logger.lifecycle('----------')

    doLast {
        project.delete(outputFile)
    }
}
</code>```

Body:
The configuration cache is enabled in the Gradle settings for the project, yet for this task it reuses the configuration cache anyways. Before I would always use the --no-configuration-cache flag since it would not edit the baseline file on consecutive runs. I updated Gradle and use notCompatibleWithConfigurationCache() in other tasks, yet only for this one it still reuses the configuration cache. How can I fix this? Is there another way I could read/write the file without having to use --no-configuration-cache?

This was the code I was using:

tasks.register("fixBaseline", Copy){
    notCompatibleWithConfigurationCache()
    List<String> fileList = []

    // Read in file list
    if (project.hasProperty("directory")) {
        // Read in files from directory
        String directoryPath = project.property(directoryProperty) as String
        def fileNameFinder = new FileNameFinder()
        def pathList = fileNameFinder.getFileNames("$rootDir$File.separator$directoryPath", "**/*.kt")

        for (pathName in pathList) {
            def f = file(pathName)
            fileList.add(f.name)
        }
    }

    // Remove lines from baseline
    def baselineDir = "$rootDir/config/base"
    def baselineFile = file("$rootDir/config/base/baseline.xml")
    def outputFile = File.createTempFile("remove", ".tmp", baselineFile.getParentFile())
    int linesRemoved = 0

    project.logger.lifecycle("Clearing files from baseline...\n")
    outputFile.withPrintWriter { outputWriter ->
        baselineFile.eachLine { line, lineNumber ->
            for (fileName in fileList){
                if (line.contains(fileName)){
                    linesRemoved++
                    return
                }
            }
            outputWriter.println(line)
        }
    }

    // Rename temporary file to baseline.xml
    from baselineDir
    include outputFile.name
    destinationDir file(baselineDir)
    rename outputFile.name, baselineFile.name

    project.logger.lifecycle("\nRemoved $linesRemoved lines")
    project.logger.lifecycle('----------')

    doLast {
        project.delete(outputFile)
    }
}


来源: stackexchange

问:
promise is not executing for executesql on Ionic-native sqlite object
The promise on executesql on Ionic-native sqlite object is not working in NodeJS 16.

this.getTransactionDbConnection().executeSql(OfflineService.SQL_GET_METADATA, [key])

.then((data)

If I divide above call into 2 parts like below , then I am able to see both console statements

```<code>console.log(transDb); let sqlResponse =
transDb.executeSql(OfflineService.SQL_GET_METADATA, [key]);
console.log(sqlResponse); sqlResponse.then(data)``` --------- This line is not responding.

I do understand, I need to put async await and check.
But Observer will fail. That will be then a bigger change.

Same code works on NodeJS 12.

In package.json dependencies, I am using
Ionic-native/sqlite : ^4.7.0,
cordova-sqlite-storage : ^2.5.0

My complete code -

  getMetadata(key: string): Observable<string> {
        return Observable.create((observer: Observer<string>) => {
            this.getTransactionDbConnection().executeSql(OfflineService.SQL_GET_METADATA, [key])
                .then((data) => {
                    console.log('After executesql',JSON.stringify(data));
                    const metadataValue = data.rows.length > 0 ? data.rows.item(0).VALUE : '';
                    console.log('Get metadata.', key, metadataValue);
                    observer.next(metadataValue);
                    observer.complete();

                }).catch(e => {
                console.error('Error occurred while trying to get metadata.', e.message);
                observer.error(e);
            });
        });
    }
```

ContentLicense: CC BY-SA 4.0

Body:
The promise on executesql on Ionic-native sqlite object is not working in NodeJS 16.

this.getTransactionDbConnection().executeSql(OfflineService.SQL_GET_METADATA, [key])

.then((data)

If I divide above call into 2 parts like below , then I am able to see both console statements

console.log(transDb); let sqlResponse =
transDb.executeSql(OfflineService.SQL_GET_METADATA, [key]);
console.log(sqlResponse); sqlResponse.then(data)``` --------- This line is not responding.

I do understand, I need to put async await and check.
But Observer will fail. That will be then a bigger change.

Same code works on NodeJS 12.

In package.json dependencies, I am using
Ionic-native/sqlite : ^4.7.0,
cordova-sqlite-storage : ^2.5.0

My complete code -

  getMetadata(key: string): Observable<string> {
        return Observable.create((observer: Observer<string>) => {
            this.getTransactionDbConnection().executeSql(OfflineService.SQL_GET_METADATA, [key])
                .then((data) => {
                    console.log('After executesql',JSON.stringify(data));
                    const metadataValue = data.rows.length > 0 ? data.rows.item(0).VALUE : '';
                    console.log('Get metadata.', key, metadataValue);
                    observer.next(metadataValue);
                    observer.complete();

                }).catch(e => {
                console.error('Error occurred while trying to get metadata.', e.message);
                observer.error(e);
            });
        });
    }


问:
How to move section (rectangle) of html?
I need some help. I have created an image of a nav bar. I positioned all the items using CSS individually. I would like to find out if there is a way to configure the CSS code so that I could move the rectangle with everything inside at once. I would appreciate any help. Thank you in advance.

Demo:

.numbersystem1 {
  font-family: tahoma;
  position: absolute;
  top: 85px;
  left: 600px;
}

.rectangle {
  width: 530px;
  height: 60px;
  border: 1px solid #000;
  position: absolute;
  top: 20%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.nvbr {
  font-family: tahoma;
  font-size: 15px;
  position: absolute;
  top: 87px;
  left: 631px;
}

.nvbrleft {
  font-family: tahoma;
  font-size: 15px;
  position: absolute;
  top: 165px;
  left: 640px;
}

.nvbrright1 {
  font-family: tahoma;
  font-size: 15px;
  position: absolute;
  top: 165px;
  left: 940px;
}

.nvbrright2 {
  font-family: tahoma;
  font-size: 15px;
  position: absolute;
  top: 165px;
  left: 1100px;
}

.nvbrright3 {
  font-family: tahoma;
  font-size: 15px;
  position: absolute;
  top: 165px;
  left: 1020px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="articles.css">
</head>

<body>
  <p class="numbersystem1"> 1.</p>
  <p class="nvbr"> Nav Bar</p>
  <div class="rectangle"></div>
  <p class="nvbrleft"> Yourwebsitename</p>
  <p class="nvbrright1"> Home</p>
  <p class="nvbrright2"> idea3</p>
  <p class="nvbrright3"> about</p>
</body>

</html></code>```

Body:
I need some help. I have created an image of a nav bar. I positioned all the items using CSS individually. I would like to find out if there is a way to configure the CSS code so that I could move the rectangle with everything inside at once. I would appreciate any help. Thank you in advance.

Demo:

.numbersystem1 {
  font-family: tahoma;
  position: absolute;
  top: 85px;
  left: 600px;
}

.rectangle {
  width: 530px;
  height: 60px;
  border: 1px solid #000;
  position: absolute;
  top: 20%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.nvbr {
  font-family: tahoma;
  font-size: 15px;
  position: absolute;
  top: 87px;
  left: 631px;
}

.nvbrleft {
  font-family: tahoma;
  font-size: 15px;
  position: absolute;
  top: 165px;
  left: 640px;
}

.nvbrright1 {
  font-family: tahoma;
  font-size: 15px;
  position: absolute;
  top: 165px;
  left: 940px;
}

.nvbrright2 {
  font-family: tahoma;
  font-size: 15px;
  position: absolute;
  top: 165px;
  left: 1100px;
}

.nvbrright3 {
  font-family: tahoma;
  font-size: 15px;
  position: absolute;
  top: 165px;
  left: 1020px;
}

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="articles.css">

 1.

 Nav Bar

 Yourwebsitename

 Home

 idea3

 about


问:
How to select dropdown value in cypress in javascript
Hi I have code which has button which acts as dropdown when the value is selected the dropdown gets disappears and it gets converted to text.

following is dropdown code:

```<code><div data-scope="loadDocuments:edit" data-testid="document-type"
name="requirements.3.type" id="field-969" aria-invalid="true" data-
fieldname="requirements.3.type" class="css-79elbk">
<button aria-expanded="false" data-isempty="true" type="button" class="input css-
1l1jgmx"
data-testid="expand" aria-haspopup="listbox">
  </button>
  <div data-testid="document-type-wrapper" class="css-185bgai" style="width: 142px;"
  data-
  popper-reference-hidden="false" data-popper-escaped="false" data-popper-
  placement="top-
  start">
  <div data-scope="loadDocuments:edit" data-has-settled="true" class="css-9lqswl">
     <div role="combobox" aria-expanded="true" aria-haspopup="listbox" aria-
  owns="downshift-20-menu" aria-labelledby="downshift-20-label" class="css-1vx1dtt">
  <input autocomplete="off" aria-autocomplete="list" aria-activedescendant="downshift-
  20-item-0" aria-controls="downshift-20-menu" aria-labelledby="downshift-20-label"
  id="downshift-20-input" data-testid="document-type-input" class="css-19gvycd"
  value=""></div>
     <ul role="listbox" aria-labelledby="downshift-20-label" id="downshift-20-menu"
  class="css-hr18p6">
        <li data-disabled="false" id="downshift-20-item-0" role="option" aria-
  selected="true" class="css-hhznq2">Bill of Lading</li>
        <li data-disabled="false" id="downshift-20-item-1" role="option" aria-
  selected="false" class="css-bh1437">Carrier Invoice</li>
        <li data-disabled="false" id="downshift-20-item-2" role="option" aria-
  selected="false" class="css-bh1437">Carrier Tender Offer</li>
        <li data-disabled="false" id="downshift-20-item-3" role="option" aria-
  selected="false" class="css-bh1437">Customer Approval</li>
     </ul>
   </div>
  </div>
 </div>
</code>```

once I select the value the the above code gets removed and below code gets added

```<code><div role="cell" data-columnidx="2" data-cellheader="[object Object]" class="css-1wtbph2" title="Bill of Lading"><span title="Bill of Lading" class="css-vrb89d">Bill of Lading</span></div>
</code>```

below is the cypress code, value is getting selected but getting disappeared immediately in a fraction of a second.

```<code> cy.get("[data-testid=requirements-table] [data-testid=document-type]")
.find("button")
.click({ force: true });
 cy.get("[data-testid=requirements-table] [data-testid=document-type]")
.find("li")
.contains(new RegExp("^" + "Bill of Lading" + "$", "g"))
.should('exist')
.click({ force: true });
</code>```

following is the result image

expected output

getting this text in cypress when I manually click on the button Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node.(don't know its related to my issue)

Body:
Hi I have code which has button which acts as dropdown when the value is selected the dropdown gets disappears and it gets converted to text.

following is dropdown code:

<button aria-expanded="false" data-isempty="true" type="button" class="input css-
1l1jgmx"
data-testid="expand" aria-haspopup="listbox">
  </button>

  <input autocomplete="off" aria-autocomplete="list" aria-activedescendant="downshift-
  20-item-0" aria-controls="downshift-20-menu" aria-labelledby="downshift-20-label"
  id="downshift-20-input" data-testid="document-type-input" class="css-19gvycd"
  value="">

Bill of Lading

Carrier Invoice

Carrier Tender Offer

Customer Approval

once I select the value the the above code gets removed and below code gets added

Bill of Lading

below is the cypress code, value is getting selected but getting disappeared immediately in a fraction of a second.

 cy.get("[data-testid=requirements-table] [data-testid=document-type]")
.find("button")
.click({ force: true });
 cy.get("[data-testid=requirements-table] [data-testid=document-type]")
.find("li")
.contains(new RegExp("^" + "Bill of Lading" + "$", "g"))
.should('exist')
.click({ force: true });

following is the result image

expected output

getting this text in cypress when I manually click on the button Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node.(don't know its related to my issue)


问:
How to paste Excel Chart as bitmap in email with Python
Trying to copy and paste an excel chart into the body of an email. My first step was to try to save it as an image, and then copy and paste the image into an email. However i am getting this error when trying to save it: com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', 'That name is already taken. Try a different one.', 'xlmain11.chm', 0, -2146827284), None)

If anybody knew a better solution to copy and paste excel charts into email, let me know! I already have an emailer that works. I am just trying to save the chart.

My Code is:

```<code>def capture_image(workbook,worksheet_name,name_of_image,t=5):

    xlapp = win32com.client.DispatchEx("Excel.Application")
    time.sleep(t)
    wb = xlapp.Workbooks.Open(workbook,None,False)
    xlapp.Visible = False
    xlapp.DisplayAlerts = False
    wb.RefreshAll()
    time.sleep(t*2)

    #To select particular worksheet of the workbook by name.
    xlapp.Sheets(worksheet_name).Select()

    # To create an object for the worksheet.
    xlSheet1 = xlapp.Sheets(worksheet_name)

    i =0
    # "chart" will capture all the charts available in the seleted worksheet.
    for chart in xlSheet1.ChartObjects():
        print (chart.Name)
        chart.CopyPicture()

        #Create new temporary sheet
        xlapp.ActiveWorkbook.Sheets.Add(After=xlapp.ActiveWorkbook.Sheets(3)).Name="temp_sheet" + str(i)

        # To create an object for the worksheet.
        temp_sheet = xlapp.ActiveSheet

        #Add chart object to new sheet.
        cht = xlapp.ActiveSheet.ChartObjects().Add(0,0,800, 600)

        #Paste copied chart into new object
        cht.Chart.Paste()

        #Export image
        #cht.Chart.Export("chart" + str(i) + ".png")

    #Provide a range in which the image need to be copied from the temporary worksheet.
    temp_sheet.Range(temp_sheet.Cells(1,1),temp_sheet.Cells(1,1)).CopyPicture()

    #It will capture copied image from the clipboard and assign that to img variable.
    img = ImageGrab.grabclipboard()
    if img is None:
       print('Error: No image data in clipboard')

    #we will provide address and name to which the immage need to be saved.
    imgFile = os.path.join('G:\\MyFolder\\',name_of_image)
    img.save(imgFile)

    #Delete the temporary worksheet when chart image is capture.
    temp_sheet.Delete()
    wb.Save()
    wb.Close()
    xlapp.Quit()

workbook = 'C:\\Users\\myFolder\\myData.xlsx'
worksheet_name = 'GRAPH'
name_of_image = 'MyImage'
a = capture_image(workbook, worksheet_name, name_of_image)

</code>```

Body:
Trying to copy and paste an excel chart into the body of an email. My first step was to try to save it as an image, and then copy and paste the image into an email. However i am getting this error when trying to save it: com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', 'That name is already taken. Try a different one.', 'xlmain11.chm', 0, -2146827284), None)

If anybody knew a better solution to copy and paste excel charts into email, let me know! I already have an emailer that works. I am just trying to save the chart.

My Code is:

def capture_image(workbook,worksheet_name,name_of_image,t=5):

    xlapp = win32com.client.DispatchEx("Excel.Application")
    time.sleep(t)
    wb = xlapp.Workbooks.Open(workbook,None,False)
    xlapp.Visible = False
    xlapp.DisplayAlerts = False
    wb.RefreshAll()
    time.sleep(t*2)

    #To select particular worksheet of the workbook by name.
    xlapp.Sheets(worksheet_name).Select()

    # To create an object for the worksheet.
    xlSheet1 = xlapp.Sheets(worksheet_name)

    i =0
    # "chart" will capture all the charts available in the seleted worksheet.
    for chart in xlSheet1.ChartObjects():
        print (chart.Name)
        chart.CopyPicture()

        #Create new temporary sheet
        xlapp.ActiveWorkbook.Sheets.Add(After=xlapp.ActiveWorkbook.Sheets(3)).Name="temp_sheet" + str(i)

        # To create an object for the worksheet.
        temp_sheet = xlapp.ActiveSheet

        #Add chart object to new sheet.
        cht = xlapp.ActiveSheet.ChartObjects().Add(0,0,800, 600)

        #Paste copied chart into new object
        cht.Chart.Paste()

        #Export image
        #cht.Chart.Export("chart" + str(i) + ".png")

    #Provide a range in which the image need to be copied from the temporary worksheet.
    temp_sheet.Range(temp_sheet.Cells(1,1),temp_sheet.Cells(1,1)).CopyPicture()

    #It will capture copied image from the clipboard and assign that to img variable.
    img = ImageGrab.grabclipboard()
    if img is None:
       print('Error: No image data in clipboard')

    #we will provide address and name to which the immage need to be saved.
    imgFile = os.path.join('G:\\MyFolder\\',name_of_image)
    img.save(imgFile)

    #Delete the temporary worksheet when chart image is capture.
    temp_sheet.Delete()
    wb.Save()
    wb.Close()
    xlapp.Quit()

workbook = 'C:\\Users\\myFolder\\myData.xlsx'
worksheet_name = 'GRAPH'
name_of_image = 'MyImage'
a = capture_image(workbook, worksheet_name, name_of_image)


问:
How to get contents of multiple related tables with Hibernate Spring?
I've created a new project in Java using Springboot. I've followed a tutorial online to create an Entity called User which I have stored in a PostgreSQL database using Hibernate and a schema file. The User file is shown below. I'm now trying to create a Controller that will allow me to get all the data of a User from the database, but Hibernate creates another table to store the @ElementCollection. This means when I use the default queries, I get the User, but the roles column is not able to be accessed since it has stored in another table. It is stored as a jsonb. How can I get the entire User data?

User class

```<code>@Table(name = "users")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private @Getter long id;
    private @Getter @Setter String email;
    private @Getter @Setter String encryptedPassword;
    private @Getter String accessToken;
    private @Getter float netWorth;

    @ElementCollection
    private @Getter @Setter Set<String> roles;

    ... (Other class functions)

}
</code>```

Repository and Service class

```<code>@Repository
public interface UserRepository extends CrudRepository<User, Long> {}

@Service
public class UserService {

    @Autowired // This means to get the bean called userRepository
    // Which is auto-generated by Spring, we will use it to handle the data
    private UserRepository repository;

    public Optional<User> findOne(long id) {
        return repository.findById(id);
    }

}
</code>```

Controller Class

```<code>@RestController
@RequestMapping(path="/user") // This means URL's start with /user (after Application path)
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping(path="/get/{id}") // Map ONLY GET Requests
    public ResponseEntity<User> getUser(@PathVariable("id") long id) {
        // @ResponseBody means the returned String is the response, not a view name
        // @RequestParam means it is a parameter from the GET or POST request
        try {
            Optional<User> savedUser = userService.findOne(id);
            if (!savedUser.isPresent()) {
                throw new ResponseStatusException(
                    HttpStatus.NOT_FOUND, "User with ID: " + id + " not found.");
            }
            return new ResponseEntity<>(savedUser.get(), HttpStatus.FOUND);
        } catch (Exception e) {
            throw new ResponseStatusException(
                HttpStatus.INTERNAL_SERVER_ERROR, "Error in retrieving user.", e);
        }
    }
}
</code>```

Body:
I've created a new project in Java using Springboot. I've followed a tutorial online to create an Entity called User which I have stored in a PostgreSQL database using Hibernate and a schema file. The User file is shown below. I'm now trying to create a Controller that will allow me to get all the data of a User from the database, but Hibernate creates another table to store the @ElementCollection. This means when I use the default queries, I get the User, but the roles column is not able to be accessed since it has stored in another table. It is stored as a jsonb. How can I get the entire User data?

User class

@Table(name = "users")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private @Getter long id;
    private @Getter @Setter String email;
    private @Getter @Setter String encryptedPassword;
    private @Getter String accessToken;
    private @Getter float netWorth;

    @ElementCollection
    private @Getter @Setter Set<String> roles;

    ... (Other class functions)

}

Repository and Service class

@Repository
public interface UserRepository extends CrudRepository<User, Long> {}

@Service
public class UserService {

    @Autowired // This means to get the bean called userRepository
    // Which is auto-generated by Spring, we will use it to handle the data
    private UserRepository repository;

    public Optional<User> findOne(long id) {
        return repository.findById(id);
    }

}

Controller Class

@RestController
@RequestMapping(path="/user") // This means URL's start with /user (after Application path)
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping(path="/get/{id}") // Map ONLY GET Requests
    public ResponseEntity<User> getUser(@PathVariable("id") long id) {
        // @ResponseBody means the returned String is the response, not a view name
        // @RequestParam means it is a parameter from the GET or POST request
        try {
            Optional<User> savedUser = userService.findOne(id);
            if (!savedUser.isPresent()) {
                throw new ResponseStatusException(
                    HttpStatus.NOT_FOUND, "User with ID: " + id + " not found.");
            }
            return new ResponseEntity<>(savedUser.get(), HttpStatus.FOUND);
        } catch (Exception e) {
            throw new ResponseStatusException(
                HttpStatus.INTERNAL_SERVER_ERROR, "Error in retrieving user.", e);
        }
    }
}


问:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
I'm trying to write a program that prints out the amount of words that have more than 5 characters. I think my code is right, however, I'm running into an index out of bounds error.

I have no clue where I'm going wrong. If anyone can help, that'd be appreciated.

I tried changing the string array size in the main method by removing "Hello" and by removing both "Hello" and "Python".
I've also tried changing the for loop from i < s[i].length() to i < s[i].length()-1.

I still received the error message with these changes.


问:
Typescript: Automated conversion imports of types and interfaces to explicit type-import syntax
I would like to automatically convert all imports (and exports) of types and interfaces to an explicit type syntax:

```<code>/module/types.ts:
export type MyType = { ... }

/module/index.ts:
export type { MyType } from './types'

/core/index.ts:
import type { MyType } from '../module/'

</code>```

Right now in my code base everything is imported/exported without the explicit import/export type syntax, but for performance reasons (in particularly Jest), I want to change this.

However doing this manually is not an option, since I have hundreds of files and thousands of these statements.

Bulk find & replace is not an option either, because Classes, Consts and Enums cannot be exported/imported with the type syntax.

Is there a typescript processor that can do this already (maybe Babel)?

Body:
I would like to automatically convert all imports (and exports) of types and interfaces to an explicit type syntax:

/module/types.ts:
export type MyType = { ... }

/module/index.ts:
export type { MyType } from './types'

/core/index.ts:
import type { MyType } from '../module/'

Right now in my code base everything is imported/exported without the explicit import/export type syntax, but for performance reasons (in particularly Jest), I want to change this.

However doing this manually is not an option, since I have hundreds of files and thousands of these statements.

Bulk find & replace is not an option either, because Classes, Consts and Enums cannot be exported/imported with the type syntax.

Is there a typescript processor that can do this already (maybe Babel)?


问:
How to get the url of attached file in Bot Framework Composer and send it to an API?
I'm currently developing a chatbot in Bot Framework Composer. I should get attachment input from user and send its url as a body of an API request. The attached file is from my computer, its url is something like 'https://localhost'. That's why I can't post its url to an API, I get invalid image url error. I'll send some screenshots about the issue and API response. Is there any solution that I can implement within Bot Framework Composer to handle this process?

images about the issue

I searched about the issue, someone stated that the attached file should be uploaded to blob first, then API request should be posted with blob url. However, I couldn't find how to implement this solution within Bot Framework Component.


问:
How to input a vector of arguments in a function in python?
I have a function, which takes a variable number of inputs. For example, the functions may look like fn(a0,a1,...). Now, I have a vector A=[a0,a1,...], and I want to call fn, but I'm not sure how to dynamically set the number of inputs (if handling outside of the function). I do not want to handle this inside the function.

How can I do this?


问:
Django token authentication error: cURL request without header shows 401 unauthorized, but adding header token auth changes to 404 not found error
Titles lays out the issue I am facing. Working on a boiler plate Django app with an API endpoint. I am able to (semi-successfully) access the endpoint via a simple cURL without header which returns a 401, but when I add the header token, I now get a 404 not found error. What could be going wrong? I've tried multiple different combinations of django settings changes across these forums and cannot get it to change. Examples of some things I have tried:

Changing order of MIDDLEWARE

CORS_ORIGIN_WHITELIST

CORS_ALLOWED_ORIGINS

CORS_ALLOW_CREDENTIALS

CORS_ORIGIN_ALLOW_ALL

Playing with REST_FRAMEWORK settings -- both DEFAULT_AUTHENTICATION_CLASSES & DEFAULT_PERMISSION_CLASSES

Changing ALLOWED_HOSTS from [] to current value below

CORS_ALLOWED_ORIGINS

Attaching snippets of relevant code:

401 cURL: curl -X GET http://127.0.0.1:8000/bettor/create/

404 cURL: curl -X GET http://127.0.0.1:8000/bettor/create/ -H "Authorization: Token <super secret but valid token>"

settings.py:

```<code>from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '<secret hidden key>'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['localhost', '127.0.0.1']

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # helpers
    'rest_framework',
    'rest_framework.authtoken',
    'corsheaders',
    # my apps
    'Bets',
    'Users',
]

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
    "corsheaders.middleware.CorsMiddleware",
    "django.middleware.common.CommonMiddleware"
]

ROOT_URLCONF = 'backend.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'backend.wsgi.application'

# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = [ 'http://localhost:3000', 'http://localhost:19006', 'http://127.0.0.1:19006', 'http://127.0.0.1:3000', 'http://127.0.0.1:8000', 'http://localhost:8000' ]
CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000', 'http://localhost:19006', 'http://127.0.0.1:19006', 'http://127.0.0.1:3000', 'http://127.0.0.1:8000', 'http://localhost:8000' ]
CORS_ALLOW_CREDENTIALS = True

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    )
}

</code>```

model/views.py:

```<code>class BettorViewSet(viewsets.ModelViewSet):
    serializer_class = BettorSerializer
    queryset = Bettor.objects.all()
</code>```

model/serializer.py:

```<code>class BettorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Bettor
        # fields = ('userId', 'bettorId', 'booksConnected', 'isCapper', 'phoneNumber')
        fields = "__all__"
</code>```

model/apps.py:

```<code>class UsersConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'Users'
</code>```

model/admin.py:

```<code>class BettorAdmin(admin.ModelAdmin):
    list_display = ('userId', 'bettorId', 'booksConnected', 'isCapper', 'phoneNumber')

# Register your models here.
admin.site.register(Bettor, BettorAdmin)
</code>```

urls.py:

```<code>router = routers.DefaultRouter()
router.register(r'bettor', views.BettorViewSet)
urlpatterns = [
...
re_path('', include(router.urls)),
...
]
</code>```

There's also some asgi.py and wsgi.py files that I haven't touched.

Body:
Titles lays out the issue I am facing. Working on a boiler plate Django app with an API endpoint. I am able to (semi-successfully) access the endpoint via a simple cURL without header which returns a 401, but when I add the header token, I now get a 404 not found error. What could be going wrong? I've tried multiple different combinations of django settings changes across these forums and cannot get it to change. Examples of some things I have tried:

Changing order of MIDDLEWARE

CORS_ORIGIN_WHITELIST

CORS_ALLOWED_ORIGINS

CORS_ALLOW_CREDENTIALS

CORS_ORIGIN_ALLOW_ALL

Playing with REST_FRAMEWORK settings -- both DEFAULT_AUTHENTICATION_CLASSES & DEFAULT_PERMISSION_CLASSES

Changing ALLOWED_HOSTS from [] to current value below

CORS_ALLOWED_ORIGINS

Attaching snippets of relevant code:

401 cURL: curl -X GET http://127.0.0.1:8000/bettor/create/

404 cURL: curl -X GET http://127.0.0.1:8000/bettor/create/ -H "Authorization: Token <super secret but valid token>"

settings.py:

from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '<secret hidden key>'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['localhost', '127.0.0.1']

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # helpers
    'rest_framework',
    'rest_framework.authtoken',
    'corsheaders',
    # my apps
    'Bets',
    'Users',
]

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
    "corsheaders.middleware.CorsMiddleware",
    "django.middleware.common.CommonMiddleware"
]

ROOT_URLCONF = 'backend.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'backend.wsgi.application'

# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = [ 'http://localhost:3000', 'http://localhost:19006', 'http://127.0.0.1:19006', 'http://127.0.0.1:3000', 'http://127.0.0.1:8000', 'http://localhost:8000' ]
CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000', 'http://localhost:19006', 'http://127.0.0.1:19006', 'http://127.0.0.1:3000', 'http://127.0.0.1:8000', 'http://localhost:8000' ]
CORS_ALLOW_CREDENTIALS = True

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    )
}

model/views.py:

class BettorViewSet(viewsets.ModelViewSet):
    serializer_class = BettorSerializer
    queryset = Bettor.objects.all()

model/serializer.py:

class BettorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Bettor
        # fields = ('userId', 'bettorId', 'booksConnected', 'isCapper', 'phoneNumber')
        fields = "__all__"

model/apps.py:

class UsersConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'Users'

model/admin.py:

class BettorAdmin(admin.ModelAdmin):
    list_display = ('userId', 'bettorId', 'booksConnected', 'isCapper', 'phoneNumber')

# Register your models here.
admin.site.register(Bettor, BettorAdmin)

urls.py:

router = routers.DefaultRouter()
router.register(r'bettor', views.BettorViewSet)
urlpatterns = [
...
re_path('', include(router.urls)),
...
]

There's also some asgi.py and wsgi.py files that I haven't touched.


问:
postgres functions vs spring data query methods
I am using spring data jpa and it is known that I can build queries just by building the name of the method.

I am using postgres as database manager.

```<code>interface PersonRepository extends Repository<Person, Long> {
  List<Person> findByLastname(String lastname);
}

</code>```

You could also build this same query as a function in postgres. My question is in performance issues that it is better to do it from the postgres side or from spring data jpa. And I would like to know what are the pros and cons of each way of doing the queries.

Body:
I am using spring data jpa and it is known that I can build queries just by building the name of the method.

I am using postgres as database manager.

interface PersonRepository extends Repository<Person, Long> {
  List<Person> findByLastname(String lastname);
}

You could also build this same query as a function in postgres. My question is in performance issues that it is better to do it from the postgres side or from spring data jpa. And I would like to know what are the pros and cons of each way of doing the queries.


问:
Selected state on nav item in Next 13
I want to have a selected state on a nav item in next 13, I could find no way of getting any context on a server component so ended up with a client component like this

```<code>'use client';

import Image from 'next/image';
import Styles from '../styles/header.module.css';
import Link from 'next/link';
import { usePathname } from 'next/navigation';

interface MainRoute {
  name: string;
  path: string;
  index: number;
}

const mainRoutes = [
  { name: 'home', path: '/' },
  { name: 'path 2', path: '/path2' },
  { name: 'path 3', path: '/path3' },
] as MainRoute[];

export default function Header({}) {
  const path = usePathname();
  return (
    <header>
      <div className={Styles.header}>
        <h1>
          App title
        </h1>
      </div>
      <div className={Styles.header}>
        <ul id="mainNav">
          {mainRoutes.map((route, index) => (
            <li key={index}>
              <Link
                className={path === route.path ? Styles.selected : ''}
                href={route.path}
              >
                {route.name}
              </Link>{' '}
              {index !== mainRoutes.length - 1 ? <span>|</span> : ''}
            </li>
          ))}
        </ul>
      </div>
    </header>
  );
}
</code>```

Is this the best way to achieve this basic styling?
As far as I am aware, now all of this code has to be shipped over to the client.

Title: Selected state on nav item in Next 13

Body:
I want to have a selected state on a nav item in next 13, I could find no way of getting any context on a server component so ended up with a client component like this

'use client';

import Image from 'next/image';
import Styles from '../styles/header.module.css';
import Link from 'next/link';
import { usePathname } from 'next/navigation';

interface MainRoute {
  name: string;
  path: string;
  index: number;
}

const mainRoutes = [
  { name: 'home', path: '/' },
  { name: 'path 2', path: '/path2' },
  { name: 'path 3', path: '/path3' },
] as MainRoute[];

export default function Header({}) {
  const path = usePathname();
  return (

          App title

          {mainRoutes.map((route, index) => (

              <Link
                className={path === route.path ? Styles.selected : ''}
                href={route.path}
              >
                {route.name}
              </Link>{' '}
              {index !== mainRoutes.length - 1 ? | : ''}

          ))}

  );
}

Is this the best way to achieve this basic styling?
As far as I am aware, now all of this code has to be shipped over to the client.


问:
Error: Unable to resolve module @firebase/app
I want to use firebase database in react-native Project but, i have a problem can you help me about it ?

I deleted all node module and package.json and reinstall with yarn but not solved


问:
Axios post request returns undefined for req.query
I am trying to pass data using axios.post method to the express server backend but it gives undefined.

Here's the frontend code:

```<code>const login = async (codeParam) => {
  if (codeParam.code.length > 1) {
    try {
      console.log("login with", codeParam) //returns the right value {code: 'value'}
      const response = await axios.post(
        "http://localhost:8000/getAccessToken",
        codeParam
      )

      if (response.data) {
        console.log("access token:", response.data.access_token)
        localStorage.setItem("user", JSON.stringify(response.data.access_token))
        localStorage.setItem("isLoggedIn", true)
      }
    } catch (error) {
      console.log(error)
    }
  }
}
</code>```

And here's the backend route:

```<code>app.post("/getAccessToken", (req, res) => {
  console.log("code", req.query.code) //returns undefined
  axios
    .post("https://github.com/login/oauth/access_token", {
      client_id: process.env.REACT_APP_CLIENT_ID,
      client_secret: process.env.REACT_APP_CLIENT_SECRET,
      code: req.query.code,
      redirect_uri: process.env.REACT_APP_REDIRECT_URI,
    })
    .then((result) => {
      console.log("access token backend", result.data)
    })
    .catch((err) => {
      console.log("error:", err)
    })
})
</code>```

I am trying to pass the "codeParam" object to the backend route but it's giving undefined. Here's what I get on the console:

```<code>code undefined
access token backend error=bad_verification_code&error_description=The+code+passed+is+incorrect+or+expired.&error_uri=https%3A%2F%2Fdocs.github.com%2Fapps%2Fmanaging-oauth-apps%2Ftroubleshooting-oauth-app-access-token-request-errors%2F%23bad-verification-code
</code>```

The problem is:

```<code>req.query.code
</code>```

It should return something or maybe I am doing it wrong?

Body:
I am trying to pass data using axios.post method to the express server backend but it gives undefined.

Here's the frontend code:

const login = async (codeParam) => {
  if (codeParam.code.length > 1) {
    try {
      console.log("login with", codeParam) //returns the right value {code: 'value'}
      const response = await axios.post(
        "http://localhost:8000/getAccessToken",
        codeParam
      )

      if (response.data) {
        console.log("access token:", response.data.access_token)
        localStorage.setItem("user", JSON.stringify(response.data.access_token))
        localStorage.setItem("isLoggedIn", true)
      }
    } catch (error) {
      console.log(error)
    }
  }
}

And here's the backend route:

app.post("/getAccessToken", (req, res) => {
  console.log("code", req.query.code) //returns undefined
  axios
    .post("https://github.com/login/oauth/access_token", {
      client_id: process.env.REACT_APP_CLIENT_ID,
      client_secret: process.env.REACT_APP_CLIENT_SECRET,
      code: req.query.code,
      redirect_uri: process.env.REACT_APP_REDIRECT_URI,
    })
    .then((result) => {
      console.log("access token backend", result.data)
    })
    .catch((err) => {
      console.log("error:", err)
    })
})

I am trying to pass the "codeParam" object to the backend route but it's giving undefined. Here's what I get on the console:

code undefined
access token backend error=bad_verification_code&error_description=The+code+passed+is+incorrect+or+expired.&error_uri=https%3A%2F%2Fdocs.github.com%2Fapps%2Fmanaging-oauth-apps%2Ftroubleshooting-oauth-app-access-token-request-errors%2F%23bad-verification-code

The problem is:

req.query.code

It should return something or maybe I am doing it wrong?


问:
"No module named cobra.test"
I have the code

And get the error "ModuleNotFoundError: No module named 'cobra.test'"
Seems to be a common problem on Google but I can't find any solutions. All help is appreciated!

Title: "No module named cobra.test"


问:
Spring generate Flux<Part> from File
I build a utility class to upload a file to AWS S3 using a full WebFlux reactive stack.
The controller class method looks like this:

```<code>     @Override
     @Transactional(propagation = Propagation.REQUIRES_NEW)
     @Timed(value = "timed.upload_customer_media", description = "Time taken to upload customer media")
     public Mono<ServerResponse> uploadCustomerMedia(ServerRequest serverRequest) {

          return serverRequest.body(BodyExtractors.toMultipartData())
                  .flatMap(parts -> {
                               Map<String, Part> partMap = parts.toSingleValueMap();
                               partMap.forEach((partName, value) -> log.info("Name: {}, value: {}", partName, value));

                               FilePart filePart = (FilePart) partMap.get("file");
                               log.info("File name is : [{}]", filePart.filename());

                               FormFieldPart formFieldPart = (FormFieldPart) partMap.get("mediaDTO");

                               log.info("mediaDTO is : [{}]", formFieldPart.value());
                               MediaDTO mediaDTO;
                               try {
                                    mediaDTO = objectMapper.readValue(formFieldPart.value(), MediaDTO.class);
                                    log.info("mediaDTO is : [{}]", mediaDTO);

                                    var customerId = Long.parseLong(serverRequest.pathVariable(CUSTOMER_ID));
                                    log.info("customerId is : [{}]", customerId);

                                    return s3FileHandlerService.multipartUploadHandler(customerId, mediaDTO, Flux.just(filePart))
                                            .elapsed()
                                            .flatMap(tr -> {
                                                 log.info("Duration to upload file to S3 [fileName : {}, duration : {}]", filePart.filename(), tr.getT1());
                                                 log.debug("Now deleting file part from temp folder.");
                                                 return Mono.just(tr.getT2());
                                            })
                                            .flatMap(s -> filePart.delete()
                                                    .then(Mono.just(s)));

                               } catch (Exception ex) {
                                    log.error("Error parsing mediaDTO: {}", ex.getMessage());
                                    return Mono.error(() -> new CustomerProcessingException(HttpStatus.INTERNAL_SERVER_ERROR, "Error processing request.", ex));
                               }
                          }
                  )
                  .flatMap(body -> ServerResponse.status(HttpStatus.CREATED)
                          .contentType(MediaType.APPLICATION_JSON).body(BodyInserters.fromValue(body)))

                  .metrics();

     }
</code>```

The signature for the method looks like this:

```<code>     public Mono<String> multipartUploadHandler(Long customerId, MediaDTO mediaDTO, Flux<Part> parts) {
</code>```

So, my MultipartFile upload controller works like a dream. I can extract the Form payload and the attached file, upload it to S3 and happiness is.

A new requirement is to take an existing file that has been downloaded to the local os using WebClient, and submit it to this method.
For the life of me, I cannot find a way to construct an instance of the Part interface using the file contents to submit.

I am looking the org.springframework.http.codec.multipart.Part and FilePart interface JavaDoc, but all the known implementations are private classes.
Example: DefaultFilePart is private static final in DefaultParts.

So my question: Has anybody ever needed to do something like this or pointers?

Title: Spring generate Flux<Part> from File

Body:
I build a utility class to upload a file to AWS S3 using a full WebFlux reactive stack.
The controller class method looks like this:

     @Override
     @Transactional(propagation = Propagation.REQUIRES_NEW)
     @Timed(value = "timed.upload_customer_media", description = "Time taken to upload customer media")
     public Mono<ServerResponse> uploadCustomerMedia(ServerRequest serverRequest) {

          return serverRequest.body(BodyExtractors.toMultipartData())
                  .flatMap(parts -> {
                               Map<String, Part> partMap = parts.toSingleValueMap();
                               partMap.forEach((partName, value) -> log.info("Name: {}, value: {}", partName, value));

                               FilePart filePart = (FilePart) partMap.get("file");
                               log.info("File name is : [{}]", filePart.filename());

                               FormFieldPart formFieldPart = (FormFieldPart) partMap.get("mediaDTO");

                               log.info("mediaDTO is : [{}]", formFieldPart.value());
                               MediaDTO mediaDTO;
                               try {
                                    mediaDTO = objectMapper.readValue(formFieldPart.value(), MediaDTO.class);
                                    log.info("mediaDTO is : [{}]", mediaDTO);

                                    var customerId = Long.parseLong(serverRequest.pathVariable(CUSTOMER_ID));
                                    log.info("customerId is : [{}]", customerId);

                                    return s3FileHandlerService.multipartUploadHandler(customerId, mediaDTO, Flux.just(filePart))
                                            .elapsed()
                                            .flatMap(tr -> {
                                                 log.info("Duration to upload file to S3 [fileName : {}, duration : {}]", filePart.filename(), tr.getT1());
                                                 log.debug("Now deleting file part from temp folder.");
                                                 return Mono.just(tr.getT2());
                                            })
                                            .flatMap(s -> filePart.delete()
                                                    .then(Mono.just(s)));

                               } catch (Exception ex) {
                                    log.error("Error parsing mediaDTO: {}", ex.getMessage());
                                    return Mono.error(() -> new CustomerProcessingException(HttpStatus.INTERNAL_SERVER_ERROR, "Error processing request.", ex));
                               }
                          }
                  )
                  .flatMap(body -> ServerResponse.status(HttpStatus.CREATED)
                          .contentType(MediaType.APPLICATION_JSON).body(BodyInserters.fromValue(body)))

                  .metrics();

     }

The signature for the method looks like this:

     public Mono<String> multipartUploadHandler(Long customerId, MediaDTO mediaDTO, Flux<Part> parts) {

So, my MultipartFile upload controller works like a dream. I can extract the Form payload and the attached file, upload it to S3 and happiness is.

A new requirement is to take an existing file that has been downloaded to the local os using WebClient, and submit it to this method.
For the life of me, I cannot find a way to construct an instance of the Part interface using the file contents to submit.

I am looking the org.springframework.http.codec.multipart.Part and FilePart interface JavaDoc, but all the known implementations are private classes.
Example: DefaultFilePart is private static final in DefaultParts.

So my question: Has anybody ever needed to do something like this or pointers?


问:
Custom elementor forms extension - Not redirecting after submit
This is an extension for elementor pro forms that sends the form data to an API.

This first API will return a success or failure message.
If successful, the response will also contain an ID number.

That ID number should then be used in a second API request where the number is appended to the URL. This second API will return a login URL.

The plugin should then redirect the user to the returned URL.

Currently I am receiving a response from the first API. the response I've received is as follows:
{"code":201,"data":{"id":133714},"message":"Success"}

The second API Response I get is the following:
{"code": 200,"request_method":"GET","autologin":"https://www.exampleurl.com/login" }

But it is not redirecting the user. Can you help me discover why?

`

```<code><?php
/*
Plugin Name: Elementor Custom form
Plugin URI:
Description:
Version:
Author:
Author URI:
License:
License URI:
*/

/*
This plugin adds a custom form action to Elementor Pro forms.

The new action sends an API Request to a custom endpoint.
After receiving a valid response, the form will send another API Request to a different endpoint.

The response from the second API Request is used to redirect the user to a different page.
*/

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

class Bpd_Custom_Form_Action extends \ElementorPro\Modules\Forms\Classes\Action_Base {

    public function get_name() {
        return 'custom_form_action';
    }

    public function get_label() {
        return __( 'Custom Form Action', 'elementor-pro' );
    }

    public function register_settings_section( $widget ) {
        $widget->start_controls_section(
            'section_custom_form_action',
            [
                'label' => $this->get_label(),
                'condition' => [
                    'submit_actions' => $this->get_name(),
                ],
            ]
        );

        //////////////////////////////////////////////
        //
        // FIRST API - SETTINGS & AUTHORIZATION
        //
        //////////////////////////////////////////////

        $widget->add_control(
            'custom_form_action_api_url',
            [
                'label' => __( 'URL', 'elementor-pro' ),
                'type' => \Elementor\Controls_Manager::TEXT,
                'placeholder' => 'https://example.com/api/',
                'description' => __( 'Enter the URL of the API endpoint you want to send the form data to.', 'elementor-pro' ),
                'label_block' => true,
                'separator' => 'before',
            ]
        );

        $widget->add_control(
            'custom_form_action_application_token',
            [
                'label' => __( 'Application Token', 'elementor-pro' ),
                'type' => \Elementor\Controls_Manager::TEXT,
                'placeholder' => 'https://example.com/api/',
                'label_block' => true,
                'description' => __( 'Enter the application token for your API request.', 'elementor-pro' ),
                'separator' => 'before',
            ]
        );

        //////////////////////////////////////////////
        //
        // FIRST API - Body & Response Options
        //
        //////////////////////////////////////////////

        $widget->add_control(
            'custom_form_action_api_body',
            [
                'label' => __( 'Body', 'elementor-pro' ),
                'type' => \Elementor\Controls_Manager::TEXTAREA,
                'placeholder' => '{ "name": "{{{ name }}}", "email": "{{{ email }}}" "ip": "{{{ USERIP }}}" }',
                'description' => __( 'Enter the body of the API request. You can use the form fields as placeholders. For example: { "name": "{{{ name }}}", "email": "{{{ email }}}" }', 'elementor-pro' ),
                'label_block' => true,
                'separator' => 'before',
            ]
        );

        //////////////////////////////////////////////
        //
        // Second API - SETTINGS & AUTHORIZATION
        //
        //////////////////////////////////////////////

        $widget->add_control(
            'custom_form_action_second_api_url',
            [
                'label' => __( 'Second API URL', 'elementor-pro' ),
                'type' => \Elementor\Controls_Manager::TEXT,
                'placeholder' => 'https://example.com/thank-you/',
                'description' => __( 'Enter the URL of the page you want to redirect the user to after the form is submitted.', 'elementor-pro' ),
                'label_block' => true,
                'separator' => 'before',
            ]
        );

        $widget->add_control(
            'custom_form_action_second_application_token',
            [
                'label' => __( 'Second Application Token', 'elementor-pro' ),
                'type' => \Elementor\Controls_Manager::TEXT,
                'placeholder' => 'https://example.com/api/',
                'label_block' => true,
                'description' => __( 'Enter the application token for your API request.', 'elementor-pro' ),
                'separator' => 'before',
            ]
        );

        $widget->end_controls_section();

    }

    public function register_form_action( $widget ) {

        $widget->add_form_action(
            'custom_form_action',
            [
                'label' => __( 'Custom Form Action', 'elementor-pro' ),
                'event' => \ElementorPro\Modules\Forms\Classes\Form_Record::get_form_settings( 'custom_form_action_event' ),
                'callback' => [ $this, 'custom_form_action' ],
            ]
        );

    }

    public function run( $record, $ajax_handler ) {

        $debugLog = '';

    $settings = $record->get( 'form_settings' );

        // create the first api request
        $first_api_url = $settings['custom_form_action_api_url'];
        $first_api_body = $settings['custom_form_action_api_body'];

        // set up the first header request
        $first_api_header_authorization = 'Bearer ' . $settings['custom_form_action_application_token'];

        // get the form fields
        $fields = $record->get( 'fields' );

        // replace the placeholders with the form field values
        $first_api_body = $this->replace_placeholders( $first_api_body, $fields );

        //////////////////////////////////////////
        //
        // Make the first API request
        //
        //////////////////////////////////////////

        //if the method is post
            // send the post request
        $first_api_response = wp_remote_post( $first_api_url, [
            'method' => 'POST',
            'headers' => array(
                'Authorization' => 'Bearer ' . $settings['custom_form_action_application_token'],
                'content-type' => 'application/json',
                ),
            'body' =>  $first_api_body,
            'timeout' => 20,
            'redirection' => 5,
            'httpversion' => '1.0',
            //SET BLOCKING TO TRUE TO WAIT FOR A RESPONSE - 5 hours wasted for this.
            'blocking' => true,
            'data_format' => 'body',
        ] );

        if ( ! is_wp_error( $first_api_response ) ) {
            $response_data = json_decode( $first_api_response['body'], true );
            if ( isset( $response_data['data']['id'] ) ) {
                $new_lead_id = $response_data['data']['id'];
            }
            else{
                $new_lead_id = '';
            }
        }

        //////////////////////////////////////////
        //
        // Make the second API request
        //
        //////////////////////////////////////////

        // create the second api request
        $second_api_url = $settings['custom_form_action_second_api_url'];

        // set up the second header request
        $second_api_header_authorization = 'Bearer ' . $settings['custom_form_action_second_application_token'];

        if (!empty($first_api_response_body)){
        $new_lead_id =  $first_api_response_body->data->id;
        }

        $new_api_url = $second_api_url . $new_lead_id;
        $new_api_body = '{ "lead_id": ' . $new_lead_id . '}';

        // send the second api request

        $second_api_response = wp_remote_post( $new_api_url, [
            'method' => 'POST',
            'headers' => array(
                'Authorization' => 'Bearer ' . $second_api_header_authorization,
                'content-type' => 'application/json',
                ),
            'body' =>  $new_api_body,
            'timeout' => 20,
            'redirection' => 5,
            'httpversion' => '1.0',
            'blocking' => true,
            'data_format' => 'body',
        ] );

        //Check for errors in the Second api response.

        if ( ! is_wp_error( $second_api_response ) ) {
            $response_data = json_decode( $second_api_response['body'], true );
            if ( isset( $response_data['autologin'] ) ) {
                $autologin = $response_data['autologin'];
            }
            else{
                $autologin = 'https://google.com';
            }
        }

        //redirect the user
        if ( ! empty( $autologin ) ) {
            wp_redirect( $autologin );
            exit;
        }
        else{
            wp_redirect( 'https://www.google.com' );
            exit;
        }

    if ( is_wp_error( $first_api_response ) ) {

            wp_remote_retrieve_response_code( $second_api_response );

            if ( wp_remote_retrieve_response_code( $second_api_response ) == 201 ) {
                //add success message
                $ajax_handler->add_success_message( __( 'First API Response: ' . $second_api_response['body'], 'elementor-pro' ) );

            }
            elseif ( wp_remote_retrieve_response_code( $second_api_response ) == 202 ) {
                //add error message
                $ajax_handler->add_error_message( __( 'First API Response: ' . $second_api_response['body'], 'elementor-pro' ) );
            }
        }

        if ( is_wp_error( $second_api_response ) ) {
            $ajax_handler->add_error_message( __( '<br><br>Data ID From First Response: '. $first_api_response_body->data->id
            . '<br>Second API Body: ' . json_encode($second_api_body)
            . '<br> First API Response Selector: ' . $first_api_body_response_selector
            . '<br>Second API Response: ' . $second_api_response['body']
            . '<br>Redirect URL: ' . $redirect_response_url
            . '<br><br>',
            'elementor-pro'
                )
            );
            return;
        }

         if ( ! empty( $redirect_response_url ) && filter_var( $redirect_response_url, FILTER_VALIDATE_URL ) ) {

            $ajax_handler->add_response_data( 'redirect_url', $redirect_response_url );

        }

    }//end run function

    public function on_export( $element ) {

        unset( $element['custom_form_action_message_redirect_url'] );

        return $element;

    }

    public function replace_placeholders( $string, $fields ) {

        $ip_of_current_user = $this->bpd_get_user_ip();

        foreach ( $fields as $id => $field ) {
            $string = str_replace( '{{{ USERIP }}}', $ip_of_current_user, $string );
            $string = str_replace( '{{{ ' . $id . ' }}}', $field['value'], $string );

        }

        return $string;

    }

    public function bpd_get_user_ip() {

/*
       if ( ! empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {

            $ip = $_SERVER['HTTP_CLIENT_IP'];
            return $ip;

        } elseif ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {

            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
            return $ip;

        } else {

            $ip = $_SERVER['REMOTE_ADDR'];
            return $ip;

        }
        */

            $ip = $_SERVER['REMOTE_ADDR'];
            return $ip;

    }

}
</code>```

`

Body:
This is an extension for elementor pro forms that sends the form data to an API.

This first API will return a success or failure message.
If successful, the response will also contain an ID number.

That ID number should then be used in a second API request where the number is appended to the URL. This second API will return a login URL.

The plugin should then redirect the user to the returned URL.

Currently I am receiving a response from the first API. the response I've received is as follows:
{"code":201,"data":{"id":133714},"message":"Success"}

The second API Response I get is the following:
{"code": 200,"request_method":"GET","autologin":"https://www.exampleurl.com/login" }

But it is not redirecting the user. Can you help me discover why?

`

<?php
/*
Plugin Name: Elementor Custom form
Plugin URI:
Description:
Version:
Author:
Author URI:
License:
License URI:
*/

/*
This plugin adds a custom form action to Elementor Pro forms.

The new action sends an API Request to a custom endpoint.
After receiving a valid response, the form will send another API Request to a different endpoint.

The response from the second API Request is used to redirect the user to a different page.
*/

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

class Bpd_Custom_Form_Action extends \ElementorPro\Modules\Forms\Classes\Action_Base {

    public function get_name() {
        return 'custom_form_action';
    }

    public function get_label() {
        return __( 'Custom Form Action', 'elementor-pro' );
    }

    public function register_settings_section( $widget ) {
        $widget->start_controls_section(
            'section_custom_form_action',
            [
                'label' => $this->get_label(),
                'condition' => [
                    'submit_actions' => $this->get_name(),
                ],
            ]
        );

        //////////////////////////////////////////////
        //
        // FIRST API - SETTINGS & AUTHORIZATION
        //
        //////////////////////////////////////////////

        $widget->add_control(
            'custom_form_action_api_url',
            [
                'label' => __( 'URL', 'elementor-pro' ),
                'type' => \Elementor\Controls_Manager::TEXT,
                'placeholder' => 'https://example.com/api/',
                'description' => __( 'Enter the URL of the API endpoint you want to send the form data to.', 'elementor-pro' ),
                'label_block' => true,
                'separator' => 'before',
            ]
        );

        $widget->add_control(
            'custom_form_action_application_token',
            [
                'label' => __( 'Application Token', 'elementor-pro' ),
                'type' => \Elementor\Controls_Manager::TEXT,
                'placeholder' => 'https://example.com/api/',
                'label_block' => true,
                'description' => __( 'Enter the application token for your API request.', 'elementor-pro' ),
                'separator' => 'before',
            ]
        );

        //////////////////////////////////////////////
        //
        // FIRST API - Body & Response Options
        //
        //////////////////////////////////////////////

        $widget->add_control(
            'custom_form_action_api_body',
            [
                'label' => __( 'Body', 'elementor-pro' ),
                'type' => \Elementor\Controls_Manager::TEXTAREA,
                'placeholder' => '{ "name": "{{{ name }}}", "email": "{{{ email }}}" "ip": "{{{ USERIP }}}" }',
                'description' => __( 'Enter the body of the API request. You can use the form fields as placeholders. For example: { "name": "{{{ name }}}", "email": "{{{ email }}}" }', 'elementor-pro' ),
                'label_block' => true,
                'separator' => 'before',
            ]
        );

        //////////////////////////////////////////////
        //
        // Second API - SETTINGS & AUTHORIZATION
        //
        //////////////////////////////////////////////

        $widget->add_control(
            'custom_form_action_second_api_url',
            [
                'label' => __( 'Second API URL', 'elementor-pro' ),
                'type' => \Elementor\Controls_Manager::TEXT,
                'placeholder' => 'https://example.com/thank-you/',
                'description' => __( 'Enter the URL of the page you want to redirect the user to after the form is submitted.', 'elementor-pro' ),
                'label_block' => true,
                'separator' => 'before',
            ]
        );

        $widget->add_control(
            'custom_form_action_second_application_token',
            [
                'label' => __( 'Second Application Token', 'elementor-pro' ),
                'type' => \Elementor\Controls_Manager::TEXT,
                'placeholder' => 'https://example.com/api/',
                'label_block' => true,
                'description' => __( 'Enter the application token for your API request.', 'elementor-pro' ),
                'separator' => 'before',
            ]
        );

        $widget->end_controls_section();

    }

    public function register_form_action( $widget ) {

        $widget->add_form_action(
            'custom_form_action',
            [
                'label' => __( 'Custom Form Action', 'elementor-pro' ),
                'event' => \ElementorPro\Modules\Forms\Classes\Form_Record::get_form_settings( 'custom_form_action_event' ),
                'callback' => [ $this, 'custom_form_action' ],
            ]
        );

    }

    public function run( $record, $ajax_handler ) {

        $debugLog = '';

    $settings = $record->get( 'form_settings' );

        // create the first api request
        $first_api_url = $settings['custom_form_action_api_url'];
        $first_api_body = $settings['custom_form_action_api_body'];

        // set up the first header request
        $first_api_header_authorization = 'Bearer ' . $settings['custom_form_action_application_token'];

        // get the form fields
        $fields = $record->get( 'fields' );

        // replace the placeholders with the form field values
        $first_api_body = $this->replace_placeholders( $first_api_body, $fields );

        //////////////////////////////////////////
        //
        // Make the first API request
        //
        //////////////////////////////////////////

        //if the method is post
            // send the post request
        $first_api_response = wp_remote_post( $first_api_url, [
            'method' => 'POST',
            'headers' => array(
                'Authorization' => 'Bearer ' . $settings['custom_form_action_application_token'],
                'content-type' => 'application/json',
                ),
            'body' =>  $first_api_body,
            'timeout' => 20,
            'redirection' => 5,
            'httpversion' => '1.0',
            //SET BLOCKING TO TRUE TO WAIT FOR A RESPONSE - 5 hours wasted for this.
            'blocking' => true,
            'data_format' => 'body',
        ] );

        if ( ! is_wp_error( $first_api_response ) ) {
            $response_data = json_decode( $first_api_response['body'], true );
            if ( isset( $response_data['data']['id'] ) ) {
                $new_lead_id = $response_data['data']['id'];
            }
            else{
                $new_lead_id = '';
            }
        }

        //////////////////////////////////////////
        //
        // Make the second API request
        //
        //////////////////////////////////////////

        // create the second api request
        $second_api_url = $settings['custom_form_action_second_api_url'];

        // set up the second header request
        $second_api_header_authorization = 'Bearer ' . $settings['custom_form_action_second_application_token'];

        if (!empty($first_api_response_body)){
        $new_lead_id =  $first_api_response_body->data->id;
        }

        $new_api_url = $second_api_url . $new_lead_id;
        $new_api_body = '{ "lead_id": ' . $new_lead_id . '}';

        // send the second api request

        $second_api_response = wp_remote_post( $new_api_url, [
            'method' => 'POST',
            'headers' => array(
                'Authorization' => 'Bearer ' . $second_api_header_authorization,
                'content-type' => 'application/json',
                ),
            'body' =>  $new_api_body,
            'timeout' => 20,
            'redirection' => 5,
            'httpversion' => '1.0',
            'blocking' => true,
            'data_format' => 'body',
        ] );

        //Check for errors in the Second api response.

        if ( ! is_wp_error( $second_api_response ) ) {
            $response_data = json_decode( $second_api_response['body'], true );
            if ( isset( $response_data['autologin'] ) ) {
                $autologin = $response_data['autologin'];
            }
            else{
                $autologin = 'https://google.com';
            }
        }

        //redirect the user
        if ( ! empty( $autologin ) ) {
            wp_redirect( $autologin );
            exit;
        }
        else{
            wp_redirect( 'https://www.google.com' );
            exit;
        }

    if ( is_wp_error( $first_api_response ) ) {

            wp_remote_retrieve_response_code( $second_api_response );

            if ( wp_remote_retrieve_response_code( $second_api_response ) == 201 ) {
                //add success message
                $ajax_handler->add_success_message( __( 'First API Response: ' . $second_api_response['body'], 'elementor-pro' ) );

            }
            elseif ( wp_remote_retrieve_response_code( $second_api_response ) == 202 ) {
                //add error message
                $ajax_handler->add_error_message( __( 'First API Response: ' . $second_api_response['body'], 'elementor-pro' ) );
            }
        }

        if ( is_wp_error( $second_api_response ) ) {
            $ajax_handler->add_error_message( __( '

Data ID From First Response: '. $first_api_response_body->data->id
            . '
Second API Body: ' . json_encode($second_api_body)
            . '
 First API Response Selector: ' . $first_api_body_response_selector
            . '
Second API Response: ' . $second_api_response['body']
            . '
Redirect URL: ' . $redirect_response_url
            . '

',
            'elementor-pro'
                )
            );
            return;
        }

         if ( ! empty( $redirect_response_url ) && filter_var( $redirect_response_url, FILTER_VALIDATE_URL ) ) {

            $ajax_handler->add_response_data( 'redirect_url', $redirect_response_url );

        }

    }//end run function

    public function on_export( $element ) {

        unset( $element['custom_form_action_message_redirect_url'] );

        return $element;

    }

    public function replace_placeholders( $string, $fields ) {

        $ip_of_current_user = $this->bpd_get_user_ip();

        foreach ( $fields as $id => $field ) {
            $string = str_replace( '{{{ USERIP }}}', $ip_of_current_user, $string );
            $string = str_replace( '{{{ ' . $id . ' }}}', $field['value'], $string );

        }

        return $string;

    }

    public function bpd_get_user_ip() {

/*
       if ( ! empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {

            $ip = $_SERVER['HTTP_CLIENT_IP'];
            return $ip;

        } elseif ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {

            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
            return $ip;

        } else {

            $ip = $_SERVER['REMOTE_ADDR'];
            return $ip;

        }
        */

            $ip = $_SERVER['REMOTE_ADDR'];
            return $ip;

    }

}

`


问:
Regex Search & Replace Dates and .html from internal links in wordpress
I have wordpress website, which has dates and .html in urls in internal links, for example

```<code>https://www.example.com/2022/07/my-first-posts.html
</code>```

i want to remove dates and .html with PHP regex search & replace plugin so urls will look like this

```<code>https://www.example.com/my-first-posts/
</code>```

how to perform search and replace?

This is screenshot of plugin

i tried

```<code>/(\d*)/(\d*)/([A-Za-z0-9-*])(.*?)\.html
</code>```

to perform search and replace but it is not working correctly.

Body:
I have wordpress website, which has dates and .html in urls in internal links, for example

https://www.example.com/2022/07/my-first-posts.html

i want to remove dates and .html with PHP regex search & replace plugin so urls will look like this

https://www.example.com/my-first-posts/

how to perform search and replace?

This is screenshot of plugin

i tried

/(\d*)/(\d*)/([A-Za-z0-9-*])(.*?)\.html

to perform search and replace but it is not working correctly.


问:
No response from postgres server
I'm trying to set up a small postgresql server on my raspberry pi.  So far, I've:

Installed postgres onto my pi

Set a static IP adress for my pi

edited  /etc/postgresql/13/main/postgresql.conf so that listen_addresses = '*'

edited /etc/postgresql/13/main/pg_hba.conf to include

host    all             all             0.0.0.0/0               md5

Running pg_isready on my pi gives me

```<code>root@pibox:~# pg_isready
/run/postgresql:5432 - accepting connections
</code>```

However, running the following results in no response

```<code>root@pibox:~# pg_isready -d <db_name> -h<static_ip> -p 5432 -U postgres
<pi's IP>:5432 - no response
</code>```

Additionally, I'm not able to connect from my laptop

```<code>psql --host=<static IP> --port=5432  --dbname <db name> --username=postgres
psql: error: connection to server at "<the pi's IP>", port 5432 failed: Connection refused
</code>```

What are some of the next steps I can take so that I can connect to my postgres server from my laptop and execute queries against the databases?

EDIT:

My laptop is running macOS 12.4.  I'm connecting to my pi via ssh over my home network.  The pi is running a copy of DietPi.  Here is some more relevant info

```<code>root@pibox:~# cat /etc/os-release
PRETTY_NAME="Debian GNU/Linux 11 (bullseye)"
NAME="Debian GNU/Linux"
VERSION_ID="11"
VERSION="11 (bullseye)"
VERSION_CODENAME=bullseye
ID=debian
HOME_URL="https://www.debian.org/"
SUPPORT_URL="https://www.debian.org/support"
BUG_REPORT_URL="https://bugs.debian.org/"
</code>```

Running the following commands yeilds these outputs

```<code>root@pibox:~# pg_isready
/run/postgresql:5432 - accepting connections

root@pibox:~# pg_isready -d postgres -h <Pi IP> -p 5432 -U postgres
<Pi IP>:5432 - no response

root@pibox:~# pg_isready -d postgres -h 127.0.0.1 -p 5432 -U postgres
127.0.0.1:5432 - no response

root@pibox:~# pg_lsclusters
Ver Cluster Port Status Owner    Data directory              Log file
13  main    5432 online postgres /var/lib/postgresql/13/main /var/log/postgresql/postgresql-13-main.log
</code>```

Title: No response from postgres server

Body:
I'm trying to set up a small postgresql server on my raspberry pi.  So far, I've:

Installed postgres onto my pi

Set a static IP adress for my pi

edited  /etc/postgresql/13/main/postgresql.conf so that listen_addresses = '*'

edited /etc/postgresql/13/main/pg_hba.conf to include

host    all             all             0.0.0.0/0               md5

Running pg_isready on my pi gives me

root@pibox:~# pg_isready
/run/postgresql:5432 - accepting connections

However, running the following results in no response

root@pibox:~# pg_isready -d <db_name> -h<static_ip> -p 5432 -U postgres
<pi's IP>:5432 - no response

Additionally, I'm not able to connect from my laptop

psql --host=<static IP> --port=5432  --dbname <db name> --username=postgres
psql: error: connection to server at "<the pi's IP>", port 5432 failed: Connection refused

What are some of the next steps I can take so that I can connect to my postgres server from my laptop and execute queries against the databases?

EDIT:

My laptop is running macOS 12.4.  I'm connecting to my pi via ssh over my home network.  The pi is running a copy of DietPi.  Here is some more relevant info

root@pibox:~# cat /etc/os-release
PRETTY_NAME="Debian GNU/Linux 11 (bullseye)"
NAME="Debian GNU/Linux"
VERSION_ID="11"
VERSION="11 (bullseye)"
VERSION_CODENAME=bullseye
ID=debian
HOME_URL="https://www.debian.org/"
SUPPORT_URL="https://www.debian.org/support"
BUG_REPORT_URL="https://bugs.debian.org/"

Running the following commands yeilds these outputs

root@pibox:~# pg_isready
/run/postgresql:5432 - accepting connections

root@pibox:~# pg_isready -d postgres -h <Pi IP> -p 5432 -U postgres
<Pi IP>:5432 - no response

root@pibox:~# pg_isready -d postgres -h 127.0.0.1 -p 5432 -U postgres
127.0.0.1:5432 - no response

root@pibox:~# pg_lsclusters
Ver Cluster Port Status Owner    Data directory              Log file
13  main    5432 online postgres /var/lib/postgresql/13/main /var/log/postgresql/postgresql-13-main.log


问:
How to put a button a Element-Plus `el-menu`
I am currently using an el-menu as a bar for my app and in it I want to have various buttons to do things, but not el-menu-items as those are intended to be clicked to take you somewhere and isn't what they're designed to do.

If i use do something like putting an el-button on the el-menu, it doesn't line up with the rest of the bar:

<el-menu mode="horizontal" :ellipsis="false">
   <el-button circle>button</el-button>
</el-menu>
```

like so

Body:
I am currently using an el-menu as a bar for my app and in it I want to have various buttons to do things, but not el-menu-items as those are intended to be clicked to take you somewhere and isn't what they're designed to do.

If i use do something like putting an el-button on the el-menu, it doesn't line up with the rest of the bar:

<el-menu mode="horizontal" :ellipsis="false">
   <el-button circle>button</el-button>
</el-menu>

like so


问:
Informix Server - 5 databases with same name
( Original question changed 12/21/22 - had wrong Informix server name - Should be Informix Dynamic Server )

I have 5 different regional databases running on one machine using Informix SE that I now must move to Informix Dynamic Server (IDS). All 5 databases have the same name, but are stored in completely different directories. It is a business requirement that each database is kept separate.

Some database/code information

Code is over 20 years old, but has been continuously updated to meet changing business needs.

There are over 200 tables.

Each of the 5 databases maintains over 4 million records with retention being 1 year for most tables.

Running on 1 Solaris server, the performance has been great.

The code base contains 45 4ge modules made up of 286 4gl modules.

There are over 200 reports now converted from ace to 4gl as well.

So, renaming the database would require changing almost 500 4gl modules.

Having maintained the SE databases for 20 years, I am now being required to set up the IDS database with no previous experience in it.

The question now: is there some straight forward documentation on how to set up multiple instances of IDS to support the 5 separate regional databases?


问:
script not conforming to the other css rules
So here I have my index.html, everything else excepts the  conforms to the css rules, but I have no idea why  isn't. Could someone explain why this is happening? :O

body {
  background-color: rgb(44, 44, 44);
}

h1 {
  color: black;
  font-size: 300%;
}

h2 {
  color: black;
  font-size: 400%;
}

div.outer {
  background-color: #ffffff9d;
  width: 50%;
  margin: 0 auto;
  word-wrap: break-word;
  border-bottom: 5px solid rgb(153, 144, 144);
}

div.inner {
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="sample"></div>
<div class="outer">
  <div class="inner">
    <h1 class="top">Room Temp</h1>
    <h2>
      <script>
        var socket = io();
        socket.on('data', function(data) {
          console.log(data);
          document.getElementById('sample').innerHTML = data;
        });
      </script>
    </h2>
  </div></code>```

Body:
So here I have my index.html, everything else excepts the  conforms to the css rules, but I have no idea why  isn't. Could someone explain why this is happening? :O

body {
  background-color: rgb(44, 44, 44);
}

h1 {
  color: black;
  font-size: 300%;
}

h2 {
  color: black;
  font-size: 400%;
}

div.outer {
  background-color: #ffffff9d;
  width: 50%;
  margin: 0 auto;
  word-wrap: break-word;
  border-bottom: 5px solid rgb(153, 144, 144);
}

div.inner {
  text-align: center;
}

Room Temp


问:
How to prepare webpack for multi page site properly?
I have a following webpack config:

```<code>const path = require('path');
const CompressionPlugin = require("compression-webpack-plugin");
const HtmlWebpackPlugin = require('html-webpack-plugin');
// npm run build for packing everything

const current   = "main";
const pagesPath = "/frontEnd/pages/";
let optionsObj  = {
    main:{
        entry: `${pagesPath}main/scripts/main.js`,
        htmlPath: `.${pagesPath}main/index.html`,
        output: {
            path: path.resolve(__dirname, 'data/public/pages/main/bundle'),
            filename: 'main.bundle.js',
        }
    },
    settings:{
        entry: `${pagesPath}settings/scripts/settings.js`,
        htmlPath: `.${pagesPath}settings/settings.html`,
        output: {
            path: path.resolve(__dirname, 'data/public/pages/settings/bundle'),
            filename: 'settings.bundle.js',
        }
    },
    login:{
        entry: `${pagesPath}login/scripts/login.js`,
        htmlPath: `.${pagesPath}login/index.html`,
        output: {
            path: path.resolve(__dirname, 'data/public/pages/login/bundle'),
            filename: 'login.bundle.js',
        }
    }
};
const options   = optionsObj[current];

console.log(`[Webpack] - Compiling with ${current} options: `,options);

module.exports = {
    context: path.resolve(__dirname, ''),
    mode: "production",
    entry: options.entry,
    devtool: 'eval-source-map',
    optimization: {
        chunkIds: 'total-size',
        mergeDuplicateChunks: true,
        minimize: true,
    },
    resolve: {
        alias: {
            assets: '/data/public/assets/',
        },
    },
    output: {
        path: options.output.path,
        filename: options.output.filename,
    },
    plugins: [
        new CompressionPlugin(),
        new HtmlWebpackPlugin({
            inject:false,
            template: options.htmlPath,
            filename: 'index.bundle.html',
        }),
    ],
    module: {
        rules: [{
            test: /\.css$/,
            use: [
              'style-loader',
              'css-loader'
            ]
        }]
    }
};
</code>```

The current variable is controlling what config is loaded on build.
This approach works but it does not take into consideration of modules which are used in more than one file so it produces a really large bundle over all.

For example, if main.js includes cookies.js and settings.js also includes cookies.js then both of the bundle file will contain cookies.js. This results in a duplicated cookies.js module. File sizes are critical for me because i have only 16mb of max space available for frontend. I'm also using compression plugin.

How can i prevent that?

( my frontEnd folder is near 385kb but my data/pages folder which webpack uses to store the bundles is 9.50mb )

PS: My goal is to inject the appropirate modules and css files into the HTML and serve only one file.

Body:
I have a following webpack config:

const path = require('path');
const CompressionPlugin = require("compression-webpack-plugin");
const HtmlWebpackPlugin = require('html-webpack-plugin');
// npm run build for packing everything

const current   = "main";
const pagesPath = "/frontEnd/pages/";
let optionsObj  = {
    main:{
        entry: `${pagesPath}main/scripts/main.js`,
        htmlPath: `.${pagesPath}main/index.html`,
        output: {
            path: path.resolve(__dirname, 'data/public/pages/main/bundle'),
            filename: 'main.bundle.js',
        }
    },
    settings:{
        entry: `${pagesPath}settings/scripts/settings.js`,
        htmlPath: `.${pagesPath}settings/settings.html`,
        output: {
            path: path.resolve(__dirname, 'data/public/pages/settings/bundle'),
            filename: 'settings.bundle.js',
        }
    },
    login:{
        entry: `${pagesPath}login/scripts/login.js`,
        htmlPath: `.${pagesPath}login/index.html`,
        output: {
            path: path.resolve(__dirname, 'data/public/pages/login/bundle'),
            filename: 'login.bundle.js',
        }
    }
};
const options   = optionsObj[current];

console.log(`[Webpack] - Compiling with ${current} options: `,options);

module.exports = {
    context: path.resolve(__dirname, ''),
    mode: "production",
    entry: options.entry,
    devtool: 'eval-source-map',
    optimization: {
        chunkIds: 'total-size',
        mergeDuplicateChunks: true,
        minimize: true,
    },
    resolve: {
        alias: {
            assets: '/data/public/assets/',
        },
    },
    output: {
        path: options.output.path,
        filename: options.output.filename,
    },
    plugins: [
        new CompressionPlugin(),
        new HtmlWebpackPlugin({
            inject:false,
            template: options.htmlPath,
            filename: 'index.bundle.html',
        }),
    ],
    module: {
        rules: [{
            test: /\.css$/,
            use: [
              'style-loader',
              'css-loader'
            ]
        }]
    }
};

The current variable is controlling what config is loaded on build.
This approach works but it does not take into consideration of modules which are used in more than one file so it produces a really large bundle over all.

For example, if main.js includes cookies.js and settings.js also includes cookies.js then both of the bundle file will contain cookies.js. This results in a duplicated cookies.js module. File sizes are critical for me because i have only 16mb of max space available for frontend. I'm also using compression plugin.

How can i prevent that?

( my frontEnd folder is near 385kb but my data/pages folder which webpack uses to store the bundles is 9.50mb )

PS: My goal is to inject the appropirate modules and css files into the HTML and serve only one file.


问:
How to write a Pester test to see if script succeeds to change a firewall rule without actually changing my firewall rules?
I have a script that all it does is changing a list of firewall rules/profiles. I'd like to write unit tests for that script without messing my firewall rules.

This script runs on a VM.

I'm using Pester for testing.


问:
Reply to email V3 email (v3) is not working
I'm getting this error

```<code> "error": {
    "code": 400,
    "source": "logic-apis-centralus.azure-apim.net",
    "clientRequestId": "392138e8-1e84-42b0-997c-f08297a077c4",
    "message": "The response is not in a JSON format.",
}
</code>```

I'm also sending the message Id from http request and it was successfully parsed from request and set as a parameter in reply to email v3

It is able to get messageId from the request and then it tries to send reply to that particular email and it gives this error

Body:
I'm getting this error

 "error": {
    "code": 400,
    "source": "logic-apis-centralus.azure-apim.net",
    "clientRequestId": "392138e8-1e84-42b0-997c-f08297a077c4",
    "message": "The response is not in a JSON format.",
}

I'm also sending the message Id from http request and it was successfully parsed from request and set as a parameter in reply to email v3

It is able to get messageId from the request and then it tries to send reply to that particular email and it gives this error


问:
Firestore - recommended way to write to a document and tell its size?
I have a collection of document in Firestore.

I want to write data to a map in a document, but once it exceeds a certain size (number of entries) - I want to create another document and write to it.

What would be a recommended way to do that?
How can I avoid reading a document (to get the map size) after each write?


问:
Lev Distance vs Use fuzzy search in ElasticSearch
I am trying to understand whether writing an in memory algorithm like Lev Dist (or any other) is better or utilizing the already existing fuzzy search query in ES (which uses lev dist underneath) is better?

The most important metric i am looking for is computation time.

Which out of the two options is faster? How can i evaluate which one works better for my use case (Kotlin programming)

Any other pros and cons of using one vs the other? One thing i can think of is if i write my own algorithm i can write customizations to improve speed. But if ES infrastructure is comparable, i do not want to spend time building my own algorithm uneccesarily

Thanks


问:
QNAP ( how to find full path for php81 ) global path for Apache81 php81
QNAP TS-251+
I have a problem, I can't find the php file for the php81 version

where can I find the full path for php81 in apache81 please?

I tried too

find . -type d | grep php81

php -v

PHP 7.4.30 (cli) (built: Dec 15 2022 06:13:30) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies