问:
Jetpack Compose: Row with all items same height
I'm trying to implement a layout in Compose where the items of a horizontally scrollable Row should all have the same height, so smaller items should adjust to the size of the biggest item in the row. I know about intrinsic size but I just can't get it to work. Also I don't want to assign a fixed height to the Row, as the Row's height should also be the height of its biggest child composable.

This is the simplified layout

@Composable
fun Screen(
    modifier: Modifier = Modifier,
) {
    Row(
        modifier = modifier
            .height(IntrinsicSize.Min)
            .horizontalScroll(state = rememberScrollState()),
        horizontalArrangement = Arrangement.spacedBy(10.dp),
    ) {
        Item(
            text = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy " +
                    "eirmod tempor invidunt ut labore et dolore magna aliquyam"
        )

        Item(
            text = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy " +
                    "eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam " +
                    "voluptua. At"
        )

        Item(
            text = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam"
        )
    }
}

@Composable
private fun Item(
    modifier: Modifier = Modifier,
    text: String,
) {
    Column(
        modifier = modifier.width(200.dp),
        horizontalAlignment = Alignment.End,
        verticalArrangement = Arrangement.SpaceBetween
    ) {
        Column {
            Text("Some static text")

            // Dynamic text
            Text(
                text,
                modifier = Modifier.padding(top = 5.dp)
            )
        }

        // The space between these two composables should be flexible,
        // hence the outer column with Arrangement.SpaceBetween

        Button(
            modifier = Modifier.padding(top = 20.dp),
            onClick = {}
        ) {
            Text("Button")
        }
    }
}
```

This is the result

but what I actually want is

When I apply fillMaxHeight() to Item, the items take up the whole height and all buttons are aligned to the bottom of the screen.

Jetpack Compose version: 1.1.0

Update: This was a bug in Compose which was fixed in compose-foundation version 1.3.0-beta01.

答:
Implenting such a feature to set height of each element is possible with SubComposeLayout which lets you to remeasure your composables based on new metrics such as sibling with max width or height.

You can check description of SubComposeLayout here, or my answer to have Columns with equal widths here.

```<code>@Composable
fun SubcomposeRow(
    modifier: Modifier = Modifier,
    content: @Composable () -> Unit = {},
) {

    SubcomposeLayout(modifier = modifier) { constraints ->

        var recompositionIndex = 0

        var placeables: List<Placeable> = subcompose(recompositionIndex++, content).map {
            it.measure(constraints)
        }

        placeables.forEachIndexed() { index: Int, placeable: Placeable ->
            println("Index: $index, placeable width: ${placeable.width}, height: ${placeable.height}")
        }

        var rowSize =
            placeables.fold(IntSize.Zero) { currentMax: IntSize, placeable: Placeable ->
                IntSize(
                    width = currentMax.width + placeable.width,
                    height = maxOf(currentMax.height, placeable.height)
                )
            }

        // Remeasure every element using height of longest item as minHeight of Constraint
        if (!placeables.isNullOrEmpty() && placeables.size > 1) {
            placeables = subcompose(recompositionIndex, content).map { measurable: Measurable ->
                measurable.measure(
                    Constraints(
                        minHeight = rowSize.height,
                        maxHeight = constraints.maxHeight
                    )
                )
            }

            rowSize =
                placeables.fold(IntSize.Zero) { currentMax: IntSize, placeable: Placeable ->
                    IntSize(
                        width = currentMax.width + placeable.width,
                        height = maxOf(currentMax.height, placeable.height)
                    )
                }
        }

        layout(rowSize.width, rowSize.height) {
            var xPos = 0
            placeables.forEach { placeable: Placeable ->
                placeable.placeRelative(xPos, 0)
                xPos += placeable.width
            }

        }
    }
}
</code>```

Constraints in second measurement is important since we want each composable to have max height

```<code>                Constraints(
                    minHeight = rowSize.height,
                    maxHeight = constraints.maxHeight
                )
</code>```

Usage

```<code>@Composable
fun Screen(
    modifier: Modifier = Modifier,
) {
    SubcomposeRow(
        modifier = modifier
            .background(Color.LightGray)
            .horizontalScroll(state = rememberScrollState()),
    ) {
        Item(
            text = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy " +
                    "eirmod tempor invidunt ut labore et dolore magna aliquyam"
        )

        Item(
            text = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy " +
                    "eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam " +
                    "voluptua. At"
        )

        Item(
            text = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam"
        )
    }
}

@Composable
private fun Item(
    modifier: Modifier = Modifier,
    text: String,
) {
    Column(
        modifier = modifier
            .width(200.dp)
            .background(Color.Red),
        horizontalAlignment = Alignment.End,
        verticalArrangement = Arrangement.SpaceBetween
    ) {
        Column(modifier = Modifier.background(Color.Yellow)) {
            Text("Some static text")

            // Dynamic text
            Text(
                text,
                modifier = Modifier.padding(top = 5.dp)
            )
        }

        // The space between these two composables should be flexible,
        // hence the outer column with Arrangement.SpaceBetween

        Button(
            modifier = Modifier
                .padding(top = 20.dp),
            onClick = {}
        ) {
            Text("Button")
        }
    }
}
</code>```

Result

Body:
I'm trying to implement a layout in Compose where the items of a horizontally scrollable Row should all have the same height, so smaller items should adjust to the size of the biggest item in the row. I know about intrinsic size but I just can't get it to work. Also I don't want to assign a fixed height to the Row, as the Row's height should also be the height of its biggest child composable.

This is the simplified layout

@Composable
fun Screen(
    modifier: Modifier = Modifier,
) {
    Row(
        modifier = modifier
            .height(IntrinsicSize.Min)
            .horizontalScroll(state = rememberScrollState()),
        horizontalArrangement = Arrangement.spacedBy(10.dp),
    ) {
        Item(
            text = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy " +
                    "eirmod tempor invidunt ut labore et dolore magna aliquyam"
        )

        Item(
            text = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy " +
                    "eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam " +
                    "voluptua. At"
        )

        Item(
            text = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam"
        )
    }
}

@Composable
private fun Item(
    modifier: Modifier = Modifier,
    text: String,
) {
    Column(
        modifier = modifier.width(200.dp),
        horizontalAlignment = Alignment.End,
        verticalArrangement = Arrangement.SpaceBetween
    ) {
        Column {
            Text("Some static text")

            // Dynamic text
            Text(
                text,
                modifier = Modifier.padding(top = 5.dp)
            )
        }

        // The space between these two composables should be flexible,
        // hence the outer column with Arrangement.SpaceBetween

        Button(
            modifier = Modifier.padding(top = 20.dp),
            onClick = {}
        ) {
            Text("Button")
        }
    }
}

This is the result

but what I actually want is

When I apply fillMaxHeight() to Item, the items take up the whole height and all buttons are aligned to the bottom of the screen.

Jetpack Compose version: 1.1.0

Update: This was a bug in Compose which was fixed in compose-foundation version 1.3.0-beta01.

Body:
Implenting such a feature to set height of each element is possible with SubComposeLayout which lets you to remeasure your composables based on new metrics such as sibling with max width or height.

You can check description of SubComposeLayout here, or my answer to have Columns with equal widths here.

@Composable
fun SubcomposeRow(
    modifier: Modifier = Modifier,
    content: @Composable () -> Unit = {},
) {

    SubcomposeLayout(modifier = modifier) { constraints ->

        var recompositionIndex = 0

        var placeables: List<Placeable> = subcompose(recompositionIndex++, content).map {
            it.measure(constraints)
        }

        placeables.forEachIndexed() { index: Int, placeable: Placeable ->
            println("Index: $index, placeable width: ${placeable.width}, height: ${placeable.height}")
        }

        var rowSize =
            placeables.fold(IntSize.Zero) { currentMax: IntSize, placeable: Placeable ->
                IntSize(
                    width = currentMax.width + placeable.width,
                    height = maxOf(currentMax.height, placeable.height)
                )
            }

        // Remeasure every element using height of longest item as minHeight of Constraint
        if (!placeables.isNullOrEmpty() && placeables.size > 1) {
            placeables = subcompose(recompositionIndex, content).map { measurable: Measurable ->
                measurable.measure(
                    Constraints(
                        minHeight = rowSize.height,
                        maxHeight = constraints.maxHeight
                    )
                )
            }

            rowSize =
                placeables.fold(IntSize.Zero) { currentMax: IntSize, placeable: Placeable ->
                    IntSize(
                        width = currentMax.width + placeable.width,
                        height = maxOf(currentMax.height, placeable.height)
                    )
                }
        }

        layout(rowSize.width, rowSize.height) {
            var xPos = 0
            placeables.forEach { placeable: Placeable ->
                placeable.placeRelative(xPos, 0)
                xPos += placeable.width
            }

        }
    }
}

Constraints in second measurement is important since we want each composable to have max height

                Constraints(
                    minHeight = rowSize.height,
                    maxHeight = constraints.maxHeight
                )

Usage

@Composable
fun Screen(
    modifier: Modifier = Modifier,
) {
    SubcomposeRow(
        modifier = modifier
            .background(Color.LightGray)
            .horizontalScroll(state = rememberScrollState()),
    ) {
        Item(
            text = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy " +
                    "eirmod tempor invidunt ut labore et dolore magna aliquyam"
        )

        Item(
            text = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy " +
                    "eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam " +
                    "voluptua. At"
        )

        Item(
            text = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam"
        )
    }
}

@Composable
private fun Item(
    modifier: Modifier = Modifier,
    text: String,
) {
    Column(
        modifier = modifier
            .width(200.dp)
            .background(Color.Red),
        horizontalAlignment = Alignment.End,
        verticalArrangement = Arrangement.SpaceBetween
    ) {
        Column(modifier = Modifier.background(Color.Yellow)) {
            Text("Some static text")

            // Dynamic text
            Text(
                text,
                modifier = Modifier.padding(top = 5.dp)
            )
        }

        // The space between these two composables should be flexible,
        // hence the outer column with Arrangement.SpaceBetween

        Button(
            modifier = Modifier
                .padding(top = 20.dp),
            onClick = {}
        ) {
            Text("Button")
        }
    }
}

Result


来源: stackexchange

问:
Which one is more efficient on saving rendering? (React)
I am wondering two cases, which is better for writing?

case 1

```<code>import * as React from 'react';

const TestComponent:React.FC = () => {
    const [count, setCount] = React.useState<number>(0)

    const increment = () => {
        setCount(count + 1)
    }

    console.log("rendering...")

    return <div>
        <div><span>{count}</span></div>
        <button onClick={increment}>click</button>
        </div>
}

export default TestComponent
</code>```

case 2

```<code>import * as React from 'react';

const TestComponent:React.FC = () => {
    const [count, setCount] = React.useState<number>(0)

    const increment = () => {
        setCount(count + 1)
    }

    console.log("rendering...")

    return <div>
        <div><span>{count}</span></div>
        <button onClick={_ => increment()}>click</button>
        </div>
}

export default TestComponent
</code>```

For case 2, I am the following double.
Is the arrow function recreated on each render phase?

```<code> onClick={_ => increment()}
</code>```

答:
In the first case you are re-creating increment on every render.

In the second case you are re-creating both increment and the arrow function, so from this point of view you are creating one more function in the second case.

The difference in performance is negligible.

There is a third way of writing this:

```<code><button onClick={_ => setCount(count+1)}>click</button>
</code>```

Again, you will create an arrow function each time, but you won't pollute the component with the increment functions.

This being said, I think all approaches are valid. Maybe the second one is superfluous as you can just pass the function as param.

My reasoning when deciding if you declare a function that alters a state and use that one is related to how much am I gonna use it. If I'm just updating the state without any further business logic then you can just update the state.

If updating the state implies some more business logic then declare a new function and use it.

ContentLicense: CC BY-SA 4.0

Body:
I am wondering two cases, which is better for writing?

case 1

import * as React from 'react';

const TestComponent:React.FC = () => {
    const [count, setCount] = React.useState<number>(0)

    const increment = () => {
        setCount(count + 1)
    }

    console.log("rendering...")

    return

{count}

        <button onClick={increment}>click</button>

}

export default TestComponent

case 2

import * as React from 'react';

const TestComponent:React.FC = () => {
    const [count, setCount] = React.useState<number>(0)

    const increment = () => {
        setCount(count + 1)
    }

    console.log("rendering...")

    return

{count}

        <button onClick={_ => increment()}>click</button>

}

export default TestComponent

For case 2, I am the following double.
Is the arrow function recreated on each render phase?

 onClick={_ => increment()}

Body:
In the first case you are re-creating increment on every render.

In the second case you are re-creating both increment and the arrow function, so from this point of view you are creating one more function in the second case.

The difference in performance is negligible.

There is a third way of writing this:

<button onClick={_ => setCount(count+1)}>click</button>

Again, you will create an arrow function each time, but you won't pollute the component with the increment functions.

This being said, I think all approaches are valid. Maybe the second one is superfluous as you can just pass the function as param.

My reasoning when deciding if you declare a function that alters a state and use that one is related to how much am I gonna use it. If I'm just updating the state without any further business logic then you can just update the state.

If updating the state implies some more business logic then declare a new function and use it.


问:
Download PDF file from google drive AppScript Google Sheet
I created a button in google sheets and I'm trying to download file from google drive with ID that I store in a cell. I searched stackoverflow and I found some code that might work, but it doesn't. When I assign the script to the button and I click it, it says "We're sorry, a server error occurred. Please wait a bit and try again."

That's the code I'm trying to use:

```<code>function doGet(e) {
  return HtmlService.createHtmlOutput(downloader());
}

function downloader() {
  var mySheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("File Lookup");
  var File_LinkID = mySheet.getRange("J4").getValue();

  var out = "<body onload='dllink.click()'>";
  out +="<a id='dllink' href='https://drive.google.com/uc?export=download&id="+File_LinkID+"'>wait will download automatically<a/>";
  out +="</body>";
  return out;
};
</code>```

Thank you!

答:
In your situation, how about the following modification?

From:

```<code>out +="<a id='dllink' href='https://drive.google.com/uc?export=download&id="+File_LinkID+"'>wait will download automatically<a/>";
</code>```

To:

```<code>out +="<a id='dllink' target='_blank' href='https://drive.google.com/uc?export=download&id="+File_LinkID+"'>wait will download automatically<a/>";
</code>```

In this modification, target='_blank' is added.

Note:

If an error is related to the permission, please publicly share the file and test it again.

In your script, it seems that Web Apps is used. In this case, when you modified the Google Apps Script, please modify the deployment as a new version. By this, the modified script is reflected in Web Apps. Please be careful this.

You can see the detail of this in the report of "Redeploying Web Apps without Changing URL of Web Apps for new IDE".

Body:
I created a button in google sheets and I'm trying to download file from google drive with ID that I store in a cell. I searched stackoverflow and I found some code that might work, but it doesn't. When I assign the script to the button and I click it, it says "We're sorry, a server error occurred. Please wait a bit and try again."

That's the code I'm trying to use:

function doGet(e) {
  return HtmlService.createHtmlOutput(downloader());
}

function downloader() {
  var mySheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("File Lookup");
  var File_LinkID = mySheet.getRange("J4").getValue();

  var out = "";
  out +="wait will download automatically";
  out +="";
  return out;
};

Thank you!

Body:
In your situation, how about the following modification?

From:

out +="<a id='dllink' href='https://drive.google.com/uc?export=download&id="+File_LinkID+"'>wait will download automatically<a/>";

To:

out +="<a id='dllink' target='_blank' href='https://drive.google.com/uc?export=download&id="+File_LinkID+"'>wait will download automatically<a/>";

In this modification, target='_blank' is added.

Note:

If an error is related to the permission, please publicly share the file and test it again.

In your script, it seems that Web Apps is used. In this case, when you modified the Google Apps Script, please modify the deployment as a new version. By this, the modified script is reflected in Web Apps. Please be careful this.

You can see the detail of this in the report of "Redeploying Web Apps without Changing URL of Web Apps for new IDE".


问:
Android. Repository from data layer with global lifecycle
I have a project that currently supports MVP and MVVM. Coroutines, hilt, repository pattern are also used.
I need single resources that I will cache.

For example, activity A executes a network request, the user can go to activity B during the execution of the request. However, I need that, regardless of whether I left activity A or not, the network request continues its execution and cache data.

I have a repository that contains the logic for executing a request and caching it. I also tried to provide the repository with the  @Singleton annotation using the hilt.

However, as soon as I switch from activity A to activity B, the network request stops executing and no data is stored in the cache.

I understand that what I have done is not sufficient to make the network request be executed in the background even if I leave the activity, but unfortunately I do not understand how I can implement this.

I also read that it is possible to use the same repository instance in the view models of activity A and activity B. But what if it is possible to switch from activity A to many other activities, then I should use the repository instance in the view models of all activities? In addition, my problem is that one activity can have a view model, and another presenter, because. still not the whole project migrated to MVVM.

I tried to find some information on the Internet, but I did not find anything like it.

Please help me. Perhaps someone can share interesting sources with a similar implementation.

答:
Use GlobalScope coroutine to make the request last as long as the Application but you can also use workmanager to make the request and cache it.

For GlobalScope refer to: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-global-scope/

For WorkManager refer to:
https://developer.android.com/topic/libraries/architecture/workmanager


问:
How to select last populated cell in table column
I am learning how to use macros/vba and used the record macros function to understand how this works.  For the part "Range("A31").Activate" how do I make it select the last populated cell? Since this column changes everyday- I would like to the code copy the data from this table to another.</p>
```<code>Sub PurshToOutput()
    Range("Inputtable[[#Headers],[UPC]]").Select
    Selection.End(xlDown).Select
    Range(Selection, Selection.End(xlUp)).Select
    Range("Inputtable[UPC]").Select
    Range("A31").Activate
    Selection.Copy
    Sheets("OUTPUT").Select
    Range("Outputtable[UPC]").Select
    ActiveSheet.Paste
End Sub
</code>```

答:
Selecting, activating only consumes Excel resources not bringing any benefit. When record a macro, Excel show selections only because they have been done and they have been recorded, not because they are necessary. Obtaining the last cell on a specific column in a specific ListObject can be done in the next way:

```<code>Sub lastCellInTableColumn()
   Dim lastCellUPC As Range
   Set lastCellUPC = Range("Outputtable[UPC]").cells(Range("Outputtable[UPC]").Rows.count, 1)
   Debug.Print lastCellUPC.Address, lastCellUPC.Value
End Sub
</code>```

If you want copying only the last cell (of UPC column) value, in all UPC column of the second table, you can simple use:

```<code>Range("Inputtable[UPC]").cells(Range("Inputtable[UPC]").Rows.count, 1).Copy _
                                    Sheets("OUTPUT").Range("Outputtable[UPC]")
</code>```

Edited:

In order to copy all the column content you can use the next way(s). Since the table names should be unique, it is not necessare to use the sheet name where they lies:

```<code>   Range("Inputtable[UPC]").Copy Range("Outputtable[UPC]").cells(1) 'copy all column
</code>```

A better way (faster and needing less resources) is using arrays, since the format in tables is rather similar. The clipboard will not be involved, anymore. The above copying way can be replaced by this more efficient way:

```<code>Dim arr: arr = Range("Inputtable[UPC]").Value
    Range("Outputtable[UPC]").cells(1).resize(UBound(arr), 1).Value = arr
</code>```

Now, if the column is not full and you need copying only the existing range, you can use the next way:

```<code>    Dim lastC As Range, arr
    Set lastC = lastUsedTblCell(Range("Inputtable[UPC]"))

    If Not lastC Is Nothing Then
         arr = Range(Range("Inputtable[UPC]").cells(1), lastC).Value
         If IsArray(arr) Then
            Range("Outputtable[UPC]").cells(1).resize(UBound(arr), 1).Value = arr
         Else
            Range("Outputtable[UPC]").cells(1).Value = arr
         End If
    End If

Function lastUsedTblCell(tblRng As Range) As Range
   Dim lastC As Range
   Set lastC = tblRng.Find(what:="*", After:=tblRng.cells(1), LookIn:=xlValues, searchOrder:=xlByRows, SearchDirection:=xlPrevious)
   If Not lastC Is Nothing Then
        Set lastUsedTblCell = lastC
    End If
End Function
</code>```

If you want/need proceeding in a similar way related to the second table column, meaning to paste in its first empty row, you can use the following way (using the function from above, too):

```<code>Dim lastC As Range, arr
    Set lastC = lastUsedTblCell(Range("Inputtable[UPC]"))

    Dim lastCOut As Range
    Set lastCOut = lastUsedTblCell(Range("Outputtable[UPC]"))
    If lastCOut Is Nothing Then Set lastCOut = Range("Outputtable[UPC]").cells(1).Offset(-1)

    If Not lastC Is Nothing Then
         arr = Range(Range("Inputtable[UPC]").cells(1), lastC).Value
         If IsArray(arr) Then
            lastCOut.Offset(1).resize(UBound(arr), 1).Value = arr
         Else
            lastCOut.Offset(1).Value = arr
         End If
    End If
End Sub
</code>```

In this last case, if the number of pasted rows will be bigger than the table rows, the table will be extended with the necessary rows.

If something unclear, please do not hesitate to ask for clarifications.

Body:
I am learning how to use macros/vba and used the record macros function to understand how this works.  For the part "Range("A31").Activate" how do I make it select the last populated cell? Since this column changes everyday- I would like to the code copy the data from this table to another.

Sub PurshToOutput()
    Range("Inputtable[[#Headers],[UPC]]").Select
    Selection.End(xlDown).Select
    Range(Selection, Selection.End(xlUp)).Select
    Range("Inputtable[UPC]").Select
    Range("A31").Activate
    Selection.Copy
    Sheets("OUTPUT").Select
    Range("Outputtable[UPC]").Select
    ActiveSheet.Paste
End Sub

Body:
Selecting, activating only consumes Excel resources not bringing any benefit. When record a macro, Excel show selections only because they have been done and they have been recorded, not because they are necessary. Obtaining the last cell on a specific column in a specific ListObject can be done in the next way:

Sub lastCellInTableColumn()
   Dim lastCellUPC As Range
   Set lastCellUPC = Range("Outputtable[UPC]").cells(Range("Outputtable[UPC]").Rows.count, 1)
   Debug.Print lastCellUPC.Address, lastCellUPC.Value
End Sub

If you want copying only the last cell (of UPC column) value, in all UPC column of the second table, you can simple use:

Range("Inputtable[UPC]").cells(Range("Inputtable[UPC]").Rows.count, 1).Copy _
                                    Sheets("OUTPUT").Range("Outputtable[UPC]")

Edited:

In order to copy all the column content you can use the next way(s). Since the table names should be unique, it is not necessare to use the sheet name where they lies:

   Range("Inputtable[UPC]").Copy Range("Outputtable[UPC]").cells(1) 'copy all column

A better way (faster and needing less resources) is using arrays, since the format in tables is rather similar. The clipboard will not be involved, anymore. The above copying way can be replaced by this more efficient way:

Dim arr: arr = Range("Inputtable[UPC]").Value
    Range("Outputtable[UPC]").cells(1).resize(UBound(arr), 1).Value = arr

Now, if the column is not full and you need copying only the existing range, you can use the next way:

    Dim lastC As Range, arr
    Set lastC = lastUsedTblCell(Range("Inputtable[UPC]"))

    If Not lastC Is Nothing Then
         arr = Range(Range("Inputtable[UPC]").cells(1), lastC).Value
         If IsArray(arr) Then
            Range("Outputtable[UPC]").cells(1).resize(UBound(arr), 1).Value = arr
         Else
            Range("Outputtable[UPC]").cells(1).Value = arr
         End If
    End If

Function lastUsedTblCell(tblRng As Range) As Range
   Dim lastC As Range
   Set lastC = tblRng.Find(what:="*", After:=tblRng.cells(1), LookIn:=xlValues, searchOrder:=xlByRows, SearchDirection:=xlPrevious)
   If Not lastC Is Nothing Then
        Set lastUsedTblCell = lastC
    End If
End Function

If you want/need proceeding in a similar way related to the second table column, meaning to paste in its first empty row, you can use the following way (using the function from above, too):

Dim lastC As Range, arr
    Set lastC = lastUsedTblCell(Range("Inputtable[UPC]"))

    Dim lastCOut As Range
    Set lastCOut = lastUsedTblCell(Range("Outputtable[UPC]"))
    If lastCOut Is Nothing Then Set lastCOut = Range("Outputtable[UPC]").cells(1).Offset(-1)

    If Not lastC Is Nothing Then
         arr = Range(Range("Inputtable[UPC]").cells(1), lastC).Value
         If IsArray(arr) Then
            lastCOut.Offset(1).resize(UBound(arr), 1).Value = arr
         Else
            lastCOut.Offset(1).Value = arr
         End If
    End If
End Sub

In this last case, if the number of pasted rows will be bigger than the table rows, the table will be extended with the necessary rows.

If something unclear, please do not hesitate to ask for clarifications.


问:
Microservices and Joins for Large Lists of Data
Although I have found moving into the Microservice technology to be very compelling and rewarding in many ways, one challenge I came across is when you traditionally would write a query based on JPA that may join a Customer with an Address (this is just an example).

The problem is, we need to return many customer records (say 100 at a time) where each Address is assigned to a Customer (let's assume one to one relationship).

Using a Join and JPA solves this problem very easily, but in Microservices, essentially we would need 2 Microservices, one for Customer, one for Address.  The problem is, we may first fetch the Customer records but how do we return all of the Address records that relate to each Customer since the Address records have a dependency on the Customer being queried?

I don't think we can use a single query in each Microservice that would return every Address unless we use every Customer ID from the first result as that would be horrible in so many ways.

Since the criteria for the query may not pertain to both Microservices (example: if we search by last name), we don't have a single criteria value we can use in both Microservices that would allow us to easily map the data together in the gateway.

So what do we do?

答: Micro Services Architecture encourages duplication, but open doors to scalability at granular level. In traditional monolith, that was not possible, with scaling the complete monolith as whole which was not smart</p>

ContentLicense: CC BY-SA 3.0


问:
Make JavaScript wait until websocket receives a reply
So as the title says, I'm playing around with websockets. So far all good, except for the fact that I can't make the page wait until we get a reponse. Now, I do actually have a good reason to do this; the requests times are about 2-10 ms due it going to 127.0.0.1 , so barely noticable. It is however long enough for the page to progress long enough to get to a part where the response is needed.

As you can tell, that is kind of a problem.

I am using the normal JS socket interface on the client and a golang websocket library on the backend.

Any ideas?

答:
Are you using some Web libraries like ReactJs/VueuJs?

If you are using some library that you can manage the Browser DOM, you can use a Spinner strategy. Wen, you page first rendering you send to the user at the first time a Spinner and before your data cames you remove the spinner and show your page. If you prefer you can use a Skeleton in place of the spinner.

If you are using react you can do something like this.

import { useState } from 'react'

const Page = () => {
 const [loading, setLoading] = useState(true)
 cosnt [data, setData] = useState({})

 useEffect(() => {
   socket.on('message', (data) => {
     setData(data)
     setLoading(false)
   })
 }, [])

 return (<>
    { loading ? <Spinner /> : <Screen data={data} /> }
 </>)
}
```


问:
How to Send this kind of Json Response
How To Send the Kind of api response when i am sending then the first letter become small
I want response key VehicleNumber but i am getting vehicleNumber
the First letter small i ma getting

```<code>    "status": "1",
    "data": [
        {
            "VehicleNumber": "DL1ZD1455",
            "Address": "gurgaon sector 48,sector 48, gurgaon",
            "Latitude": 28.42682,
            "Longitude": 77.03228,
            "Alerttime": "dd/MM/yyyy HH:mm:ss",
            "Speed": "21.000",
        }
    ],
    "message": "Success"
}```

i am getting this kind of response
```

{
"status": "1",
"data": [
{
"address": "Lucknow Airport Terminal,Uttar Pradesh",
"vehicleNumber": "DL1PD3231",
"speed": "0",
"latitude": 26.76383,
"longitude": 80.88558,
"alerttime": "2021-12-19 17:16:41"
}
],
"message": "Success"
}

答:
```<code>List<Map> panicData = new ArrayList<Map>();
    ResultSet rs = stm.executeQuery(query1);
                while (rs.next()) {
                    Map<Object, Object>hsa=new HashMap<Object,Object>();
                    String VehicleNumber=rs.getString(1);
                    String Address=rs.getString(2);
                    Double Latitude=rs.getDouble(3);
                    Double Longitude=rs.getDouble(4);
                    String Alerttime=rs.getString(5);
                    int spd=rs.getInt(6);
                    String Speed=spd+"";
                    hsa.put("VehicleNumber",VehicleNumber);
                    hsa.put("Address", Address);
                    hsa.put("Latitude", Latitude);
                    hsa.put("Longitude", Longitude);
                    hsa.put("Alerttime", Alerttime);
                    hsa.put("Speed",Speed);

                    panicData.add(hsa);
                }
            }
</code>```

Title: How to Send this kind of Json Response

Body:
How To Send the Kind of api response when i am sending then the first letter become small
I want response key VehicleNumber but i am getting vehicleNumber
the First letter small i ma getting

    "status": "1",
    "data": [
        {
            "VehicleNumber": "DL1ZD1455",
            "Address": "gurgaon sector 48,sector 48, gurgaon",
            "Latitude": 28.42682,
            "Longitude": 77.03228,
            "Alerttime": "dd/MM/yyyy HH:mm:ss",
            "Speed": "21.000",
        }
    ],
    "message": "Success"
}```

i am getting this kind of response

{
"status": "1",
"data": [
{
"address": "Lucknow Airport Terminal,Uttar Pradesh",
"vehicleNumber": "DL1PD3231",
"speed": "0",
"latitude": 26.76383,
"longitude": 80.88558,
"alerttime": "2021-12-19 17:16:41"
}
],
"message": "Success"
}


问:
File cannot be downloaded in CentOS
My code is running well on Windows.

```<code>// this is where the code cracks, tmpFile is a 160kb size file.
File image = HttpUtil.downloadFileFromUrl(url, new File(tmpFile));
</code>```

Here is the reproducible example:

```<code>@Test
  public void getFileBytes() {
    String DEST = "/home/files/";
    String fileId = "abc";
    String tmpFile = DEST + fileId + "." + "jpeg";

    if (!(FileUtil.exist(DEST) && FileUtil.isDirectory(DEST))) {
      FileUtil.del(DEST);
      new File(DEST).mkdirs();
    }

    String url = "https://images.pexels.com/photos/189349/pexels-photo-189349.jpeg";

    File image = HttpUtil.downloadFileFromUrl(url, new File(tmpFile));

  }
</code>```

The HttpUtil and FileUtil are comes from :

```<code><!-- https://mvnrepository.com/artifact/cn.hutool/hutool-all -->
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.7.19</version>
</dependency>
</code>```

Once I packaged it to war and deployed on CentOS 7.9, the docker container gave NullPointerException.

```<code>java.lang.NullPointerException: null
        at cn.hutool.core.io.file.FileReader.checkFile(FileReader.java:299)
        at cn.hutool.core.io.file.FileReader.<init>(FileReader.java:57)
        at cn.hutool.core.io.file.FileReader.<init>(FileReader.java:93)
        at cn.hutool.core.io.file.FileReader.create(FileReader.java:46)
        at cn.hutool.core.io.FileUtil.readBytes(FileUtil.java:1878)
        at com.supconit.taishunwenbao.screen.service.impl.ImageServiceImpl.compressImage(ImageServiceImpl.java:87)
        at com.supconit.taishunwenbao.screen.controller.ImageController.compressedImageDownload(ImageController.java:29)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
        at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150)
        at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
        at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
        at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:655)
        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at com.supconit.honeycomb.initAuth.filters.SetUserIdAndUsernameForCloudFilter.doFilterInternal(SetUserIdAndUsernameForCloudFilter.java:39)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1722)
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
        at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
        at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.lang.Thread.run(Thread.java:745)

</code>```

I've gave the folder(where tmpFile stays) below permissions:

```<code>chomd 777 /home/files
</code>```

I've make sure the nginx configuration correct:

```<code>client_max_body_size 500000m;
</code>```

Is there any reason that cause file download failed?

答:
This is anything but a Java question; else it would be the typical NullPointerException.

How about labeling the files with the proper SE Linux security context? https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html-single/selinux_users_and_administrators_guide/index#sect-Managing_Confined_Services-The_Apache_HTTP_Server-The_Apache_HTTP_Server_and_SELinux

For example:

```<code>semanage fcontext -a -t httpd_sys_rw_content_t "/var/www(/.*)?"
restorecon -R /var/www
</code>```

Also access to user home directories (alike /home/files) must be explicitly permitted:

```<code>sesetbool -P httpd_enable_homedirs on
</code>```

Command ls -laZ at least shows the labels. Run sudo sealert -a /var/log/audit/audit.log to see all the alerts in the audit log.

Title: File cannot be downloaded in CentOS

Body:
My code is running well on Windows.

// this is where the code cracks, tmpFile is a 160kb size file.
File image = HttpUtil.downloadFileFromUrl(url, new File(tmpFile));

Here is the reproducible example:

@Test
  public void getFileBytes() {
    String DEST = "/home/files/";
    String fileId = "abc";
    String tmpFile = DEST + fileId + "." + "jpeg";

    if (!(FileUtil.exist(DEST) && FileUtil.isDirectory(DEST))) {
      FileUtil.del(DEST);
      new File(DEST).mkdirs();
    }

    String url = "https://images.pexels.com/photos/189349/pexels-photo-189349.jpeg";

    File image = HttpUtil.downloadFileFromUrl(url, new File(tmpFile));

  }

The HttpUtil and FileUtil are comes from :

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.7.19</version>
</dependency>

Once I packaged it to war and deployed on CentOS 7.9, the docker container gave NullPointerException.

java.lang.NullPointerException: null
        at cn.hutool.core.io.file.FileReader.checkFile(FileReader.java:299)
        at cn.hutool.core.io.file.FileReader.<init>(FileReader.java:57)
        at cn.hutool.core.io.file.FileReader.<init>(FileReader.java:93)
        at cn.hutool.core.io.file.FileReader.create(FileReader.java:46)
        at cn.hutool.core.io.FileUtil.readBytes(FileUtil.java:1878)
        at com.supconit.taishunwenbao.screen.service.impl.ImageServiceImpl.compressImage(ImageServiceImpl.java:87)
        at com.supconit.taishunwenbao.screen.controller.ImageController.compressedImageDownload(ImageController.java:29)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
        at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150)
        at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
        at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
        at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:655)
        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at com.supconit.honeycomb.initAuth.filters.SetUserIdAndUsernameForCloudFilter.doFilterInternal(SetUserIdAndUsernameForCloudFilter.java:39)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1722)
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
        at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
        at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.lang.Thread.run(Thread.java:745)

I've gave the folder(where tmpFile stays) below permissions:

chomd 777 /home/files

I've make sure the nginx configuration correct:

client_max_body_size 500000m;

Is there any reason that cause file download failed?

Body:
This is anything but a Java question; else it would be the typical NullPointerException.

How about labeling the files with the proper SE Linux security context? https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html-single/selinux_users_and_administrators_guide/index#sect-Managing_Confined_Services-The_Apache_HTTP_Server-The_Apache_HTTP_Server_and_SELinux

For example:

semanage fcontext -a -t httpd_sys_rw_content_t "/var/www(/.*)?"
restorecon -R /var/www

Also access to user home directories (alike /home/files) must be explicitly permitted:

sesetbool -P httpd_enable_homedirs on

Command ls -laZ at least shows the labels. Run sudo sealert -a /var/log/audit/audit.log to see all the alerts in the audit log.


问:
How to manage kivy file?
when we use kivy to create interface , the kivy file content of many lines of code,
For example we have button with specific design, if I want use this button 10 times for each time should I write of properties of button ?

there is any way to manage the file? or we can make more than one kivy file to manage  and easy understands code of kivy?

答:
first define the class in the python file like

```<code>from kivymd.uix.behaviors import RoundedRectangularElevationBehavior, RectangularRippleBehavior
from kivy.uix.behaviors import ButtonBehavior
from kivymd.uix.boxlayout import MDBoxLayout

class CustomButon(RoundedRectangularElevationBehavior, RectangularRippleBehavior, ButtonBehaviour, MDBoxLayout):
    text = StringProperty()

    def fxn_to_call_on_release(self):
        pass
</code>```

and your kv file should look somewhat like this when defining the properties of the button

```<code><CustomButton>:
    size_hint: None, None
    width: dp(80)
    height: dp(32)
    elevation: 20
    radius: [dp(15), dp(15), dp(15), dp(15)]
    canvas.before:
        Color:
            rgba: gch("#f3a635")
        RoundedRectangle:
            size: self.size
            pos: self.pos
            radius: [dp(15), dp(15), dp(15), dp(15)]

    MDLabel:
        text: root.text,
        halign: "center",
        font_style: "Button",
        opposite_colors: True,
        bold: True
</code>```

The properties defined are my preferences, you can edit as you see fit.
with these definitions you can call the button in other widgets;

```<code>CustomButton:
    on_release: self.fxn_to_call_on_release()
    text: "Button Text"
</code>```

you can call the button like this as many times as you wish.

Title: How to manage kivy file?

Body:
first define the class in the python file like

from kivymd.uix.behaviors import RoundedRectangularElevationBehavior, RectangularRippleBehavior
from kivy.uix.behaviors import ButtonBehavior
from kivymd.uix.boxlayout import MDBoxLayout

class CustomButon(RoundedRectangularElevationBehavior, RectangularRippleBehavior, ButtonBehaviour, MDBoxLayout):
    text = StringProperty()

    def fxn_to_call_on_release(self):
        pass

and your kv file should look somewhat like this when defining the properties of the button

<CustomButton>:
    size_hint: None, None
    width: dp(80)
    height: dp(32)
    elevation: 20
    radius: [dp(15), dp(15), dp(15), dp(15)]
    canvas.before:
        Color:
            rgba: gch("#f3a635")
        RoundedRectangle:
            size: self.size
            pos: self.pos
            radius: [dp(15), dp(15), dp(15), dp(15)]

    MDLabel:
        text: root.text,
        halign: "center",
        font_style: "Button",
        opposite_colors: True,
        bold: True

The properties defined are my preferences, you can edit as you see fit.
with these definitions you can call the button in other widgets;

CustomButton:
    on_release: self.fxn_to_call_on_release()
    text: "Button Text"

you can call the button like this as many times as you wish.


问:
How to remove duplicate values from an array of objects in react for select components of MUI
I wanted to remove data from my array of objects. There are lots of duplicate values in my data, and this should be in the form of map so this is on my select value for selection.

Array of Objects:

```<code>rawData = [
0: {
  style_no: "BAG-011459",
  Item_description: "Hoplite Top Load Bag Standard 21 x 36 Olive",
  mon: "21310026-4",
  type: "Bags",
  oq: 51,
  force_update: 62,
  c_n: "WHITE DUCK",
  pl_q: 51,
  os: "Open",
},
1: {
  style_no: "BAG-010865",
  Item_description: "Hoplite Top Load Bag Large 25 x 42  Olive",
  mon: "21310030-5",
  type: "Bags",
  oq: 102,
  force_update: 63,
  c_n: "WHITE DUCK",
  pl_q: 102,
  os: "Open",
},
2: {
  style_no: "BAG-011932",
  Item_description: "Hoplite Top Load Bag Large 25x42 Black",
  mon: "21310035-8",
  type: "Bags",
  oq: 464,
  force_update: 64,
  c_n: "WHITE DUCK",
  pl_q: 464,
  os: "Open",
},
3:{
  style_no: "BAG-011932",
  Item_description: "Hoplite Top Load Bag Large 25x42 Black",
  mon: "21310034-8",
  type: "Bags",
  oq: 464,
  force_update: 65,
  c_n: "WHITE DUCK",
  pl_q: 464,
  os: "Open",
},
4:{
  style_no: "BAG-011931",
  Item_description: "Hoplite Top Load Bag Standard 21x36 Black",
  mon: "21310034-7",
  type: "Bags",
  oq: 160,
  force_update: 66,
  c_n: "WHITE DUCK",
  pl_q: 160,
  os: "Open",
},
5: {
  style_no: "BAG-011931",
  Item_description: "Hoplite Top Load Bag Standard 21x36 Black",
  mon: "21310036-7",
  type: "Bags",
  oq: 150,
  force_update: 67,
  c_n: "WHITE DUCK",
  pl_q: 150,
  os: "Open",
},
6: {
  style_no: "BAG-011931",
  Item_description: "Hoplite Top Load Bag Standard 21x36 Black",
  mon: "21310035-7",
  type: "Bags",
  oq: 160,
  force_update: 68,
  c_n: "WHITE DUCK",
  pl_q: 160,
  os: "Open",
},
7: {
  style_no: "BAG-011460",
  Item_description: "Hoplite Top Load Bag Extra Large 30 x 50 Olive",
  mon: "21310034-6",
  type: "Bags",
  oq: 456,
  force_update: 69,
  c_n: "WHITE DUCK",
  pl_q: 456,
  os: "Open",
},
8: {
  style_no: "BAG-011460",
  Item_description: "Hoplite Top Load Bag Extra Large 30 x 50 Olive",
  mon: "21310035-6",
  type: "Bags",
  oq: 456,
  force_update: 70,
  c_n: "WHITE DUCK",
  pl_q: 456,
  os: "Open",
},
]
</code>```

Select Body:

```<code>    {/* Customer */}
    <FormControl sx={{ m: 0.5 }} variant="standard">
      <InputLabel
        style={{ fontSize: "15px" }}
        id="demo-customized-select-label"
      >
        Customer
      </InputLabel>
      <Select
        required
        style={{
          fontSize: "12px",
          width: "125px",
        }}
        labelId="demo-customized-select-label"
        id="demo-customized-select"
        value={plandata.customer}
        onChange={(e) => {
          setPlanData((prev) => ({ ...prev, customer: e.target.value }));
        }}
        input={<BootstrapInput />}
      >
        {rawData
          ?.filter((data) => data.type.includes(plandata.division))
          .map((value) => (
            <MenuItem value={value.c_n.toString()}>
              {value.c_n.toString()}
            </MenuItem>
          ))}
      </Select>
    </FormControl>
</code>```

The snippet of the select box is

Note: I already go through the answers which was related to this question but not find my query.
Edited: If any senior find me out for this problem is great, because yet I am unable to find solution.

答:
Try this way:</p>
```<code>{/* Customer */}
<FormControl sx={{ m: 0.5 }} variant="standard">
  <InputLabel
    style={{ fontSize: "15px" }}
    id="demo-customized-select-label"
  >
    Customer
  </InputLabel>
  <Select
    required
    style={{
      fontSize: "12px",
      width: "125px",
    }}
    labelId="demo-customized-select-label"
    id="demo-customized-select"
    value={plandata.customer}
    onChange={(e) => {
      setPlanData((prev) => ({ ...prev, customer: e.target.value }));
    }}
    input={<BootstrapInput />}
  >
    {rawData
      ?.filter((data) => data.type.includes(plandata.division))
      ?.filter((value, index, self) => self.indexOf(value) === index)
      .map((value) => (
        <MenuItem value={value.c_n.toString()}>
          {value.c_n.toString()}
        </MenuItem>
      ))}
  </Select>
</FormControl>
</code>```

Body:
I wanted to remove data from my array of objects. There are lots of duplicate values in my data, and this should be in the form of map so this is on my select value for selection.

Array of Objects:

rawData = [
0: {
  style_no: "BAG-011459",
  Item_description: "Hoplite Top Load Bag Standard 21 x 36 Olive",
  mon: "21310026-4",
  type: "Bags",
  oq: 51,
  force_update: 62,
  c_n: "WHITE DUCK",
  pl_q: 51,
  os: "Open",
},
1: {
  style_no: "BAG-010865",
  Item_description: "Hoplite Top Load Bag Large 25 x 42  Olive",
  mon: "21310030-5",
  type: "Bags",
  oq: 102,
  force_update: 63,
  c_n: "WHITE DUCK",
  pl_q: 102,
  os: "Open",
},
2: {
  style_no: "BAG-011932",
  Item_description: "Hoplite Top Load Bag Large 25x42 Black",
  mon: "21310035-8",
  type: "Bags",
  oq: 464,
  force_update: 64,
  c_n: "WHITE DUCK",
  pl_q: 464,
  os: "Open",
},
3:{
  style_no: "BAG-011932",
  Item_description: "Hoplite Top Load Bag Large 25x42 Black",
  mon: "21310034-8",
  type: "Bags",
  oq: 464,
  force_update: 65,
  c_n: "WHITE DUCK",
  pl_q: 464,
  os: "Open",
},
4:{
  style_no: "BAG-011931",
  Item_description: "Hoplite Top Load Bag Standard 21x36 Black",
  mon: "21310034-7",
  type: "Bags",
  oq: 160,
  force_update: 66,
  c_n: "WHITE DUCK",
  pl_q: 160,
  os: "Open",
},
5: {
  style_no: "BAG-011931",
  Item_description: "Hoplite Top Load Bag Standard 21x36 Black",
  mon: "21310036-7",
  type: "Bags",
  oq: 150,
  force_update: 67,
  c_n: "WHITE DUCK",
  pl_q: 150,
  os: "Open",
},
6: {
  style_no: "BAG-011931",
  Item_description: "Hoplite Top Load Bag Standard 21x36 Black",
  mon: "21310035-7",
  type: "Bags",
  oq: 160,
  force_update: 68,
  c_n: "WHITE DUCK",
  pl_q: 160,
  os: "Open",
},
7: {
  style_no: "BAG-011460",
  Item_description: "Hoplite Top Load Bag Extra Large 30 x 50 Olive",
  mon: "21310034-6",
  type: "Bags",
  oq: 456,
  force_update: 69,
  c_n: "WHITE DUCK",
  pl_q: 456,
  os: "Open",
},
8: {
  style_no: "BAG-011460",
  Item_description: "Hoplite Top Load Bag Extra Large 30 x 50 Olive",
  mon: "21310035-6",
  type: "Bags",
  oq: 456,
  force_update: 70,
  c_n: "WHITE DUCK",
  pl_q: 456,
  os: "Open",
},
]

Select Body:

    {/* Customer */}
    <FormControl sx={{ m: 0.5 }} variant="standard">
      <InputLabel
        style={{ fontSize: "15px" }}
        id="demo-customized-select-label"
      >
        Customer
      </InputLabel>
      <Select
        required
        style={{
          fontSize: "12px",
          width: "125px",
        }}
        labelId="demo-customized-select-label"
        id="demo-customized-select"
        value={plandata.customer}
        onChange={(e) => {
          setPlanData((prev) => ({ ...prev, customer: e.target.value }));
        }}
        input={<BootstrapInput />}
      >
        {rawData
          ?.filter((data) => data.type.includes(plandata.division))
          .map((value) => (
            <MenuItem value={value.c_n.toString()}>
              {value.c_n.toString()}
            </MenuItem>
          ))}
      </Select>
    </FormControl>

The snippet of the select box is

Note: I already go through the answers which was related to this question but not find my query.
Edited: If any senior find me out for this problem is great, because yet I am unable to find solution.

Body:
Try this way:

{/* Customer */}
<FormControl sx={{ m: 0.5 }} variant="standard">
  <InputLabel
    style={{ fontSize: "15px" }}
    id="demo-customized-select-label"
  >
    Customer
  </InputLabel>
  <Select
    required
    style={{
      fontSize: "12px",
      width: "125px",
    }}
    labelId="demo-customized-select-label"
    id="demo-customized-select"
    value={plandata.customer}
    onChange={(e) => {
      setPlanData((prev) => ({ ...prev, customer: e.target.value }));
    }}
    input={<BootstrapInput />}
  >
    {rawData
      ?.filter((data) => data.type.includes(plandata.division))
      ?.filter((value, index, self) => self.indexOf(value) === index)
      .map((value) => (
        <MenuItem value={value.c_n.toString()}>
          {value.c_n.toString()}
        </MenuItem>
      ))}
  </Select>
</FormControl>


问:
silverlight error - the opreation is not supported for a relative uri
I've just started developing silverlight applications. I've created a webserivce in my asp.net project. Now, when I try to connect to it through my silverlight project I receive the following error:

"the opreation is not supported for a relative uri"

I am using the following url -->

http://192.168.1.2/MyWebsite/SubVersionedHistory.svc

I can find the class and its methods, but I receive this horrific error when I add it.

Thank you for your help and advice,

Vondiplo

答:
Maybe this response can help you

You cannot use AbsolutePath, You need to use AbsoluteURL.  Build your URL this way:
  Uri url = new Uri(App.Current.Host.Source, "../settings.xml");client.DownloadStringAsync(url);

http://silverlight.net/forums/p/28912/95541.aspx

HTH
  Braulio

OwnerDisplayName: Vondiplo

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Braulio


问:
How to set different images alternately in listView's row?
I have a listview, in which I am fetching data from Twitter, I also show it in listView,
but I want to show different images in different rows of listView.

I used convert-view.setBackGroundResource(R.drawable.strip1);, it repeats this image in all rows, but I want to set it alternatively. How is it possible?

答:
use the position in:

```<code>getView(int position, View convertView, ViewGroup parent)
</code>```

and do something like this

```<code>if(position%2 == 0) {
    convert-view.setBackGroundResource(R.drawable.strip1);
} else {
    convert-view.setBackGroundResource(R.drawable.strip2);
}
</code>```

Body:
use the position in:

getView(int position, View convertView, ViewGroup parent)

and do something like this

if(position%2 == 0) {
    convert-view.setBackGroundResource(R.drawable.strip1);
} else {
    convert-view.setBackGroundResource(R.drawable.strip2);
}


问:
WSO2 MI Validate Mediator
I cannot properly configure validation based on JSON schema.
Validate Mediator failed with the following:</p>
```<code>Unsupported Operation org.apache.axiom.om.OMException: Unsupported Operation
    at org.apache.axiom.om.impl.llom.OMTextImpl.getInputStream(OMTextImpl.java:422)
    at org.apache.synapse.mediators.builtin.ValidateMediator.mediate(ValidateMediator.java:231)
    at org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:109)
    at org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:71)
    at org.apache.synapse.mediators.base.SequenceMediator.mediate(SequenceMediator.java:158)
    at org.apache.synapse.api.Resource.process(Resource.java:342)
    at org.apache.synapse.api.API.process(API.java:463)
    at org.apache.synapse.api.AbstractApiHandler.apiProcess(AbstractApiHandler.java:93)
    at org.apache.synapse.api.AbstractApiHandler.dispatchToAPI(AbstractApiHandler.java:71)
    at org.apache.synapse.api.rest.RestRequestHandler.dispatchToAPI(RestRequestHandler.java:84)
    at org.apache.synapse.api.rest.RestRequestHandler.process(RestRequestHandler.java:70)
    at org.apache.synapse.rest.RESTRequestHandler.process(RESTRequestHandler.java:54)
    at org.apache.synapse.core.axis2.Axis2SynapseEnvironment.injectMessage(Axis2SynapseEnvironment.java:344)
    at org.apache.synapse.core.axis2.SynapseMessageReceiver.receive(SynapseMessageReceiver.java:101)
    at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:180)
    at org.apache.synapse.transport.passthru.ServerWorker.processNonEntityEnclosingRESTHandler(ServerWorker.java:375)
    at org.apache.synapse.transport.passthru.ServerWorker.processEntityEnclosingRequest(ServerWorker.java:434)
    at org.apache.synapse.transport.passthru.ServerWorker.run(ServerWorker.java:182)
    at org.apache.axis2.transport.base.threads.NativeWorkerPool$1.run(NativeWorkerPool.java:172)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
</code>```

答:
You have to specify the Media Type of the schema file as application/json[1].After creating the artifacts from the Integration Studio, open the created carbon application and check relevant artifact file of the schema.
Then it should be configured as below.

```<code><?xml version="1.0" encoding="UTF-8"?><resources>
<item>
    <file>ValidationResource.json</file>
    <path>/_system/config/myresources</path>
    <mediaType>application/json</mediaType>
    <properties/>
</item>
</code>```

[1] https://ei.docs.wso2.com/en/latest/micro-integrator/references/mediators/validate-Mediator/#examples_1

Title: WSO2 MI Validate Mediator

Body:
I cannot properly configure validation based on JSON schema.
Validate Mediator failed with the following:

Unsupported Operation org.apache.axiom.om.OMException: Unsupported Operation
    at org.apache.axiom.om.impl.llom.OMTextImpl.getInputStream(OMTextImpl.java:422)
    at org.apache.synapse.mediators.builtin.ValidateMediator.mediate(ValidateMediator.java:231)
    at org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:109)
    at org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:71)
    at org.apache.synapse.mediators.base.SequenceMediator.mediate(SequenceMediator.java:158)
    at org.apache.synapse.api.Resource.process(Resource.java:342)
    at org.apache.synapse.api.API.process(API.java:463)
    at org.apache.synapse.api.AbstractApiHandler.apiProcess(AbstractApiHandler.java:93)
    at org.apache.synapse.api.AbstractApiHandler.dispatchToAPI(AbstractApiHandler.java:71)
    at org.apache.synapse.api.rest.RestRequestHandler.dispatchToAPI(RestRequestHandler.java:84)
    at org.apache.synapse.api.rest.RestRequestHandler.process(RestRequestHandler.java:70)
    at org.apache.synapse.rest.RESTRequestHandler.process(RESTRequestHandler.java:54)
    at org.apache.synapse.core.axis2.Axis2SynapseEnvironment.injectMessage(Axis2SynapseEnvironment.java:344)
    at org.apache.synapse.core.axis2.SynapseMessageReceiver.receive(SynapseMessageReceiver.java:101)
    at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:180)
    at org.apache.synapse.transport.passthru.ServerWorker.processNonEntityEnclosingRESTHandler(ServerWorker.java:375)
    at org.apache.synapse.transport.passthru.ServerWorker.processEntityEnclosingRequest(ServerWorker.java:434)
    at org.apache.synapse.transport.passthru.ServerWorker.run(ServerWorker.java:182)
    at org.apache.axis2.transport.base.threads.NativeWorkerPool$1.run(NativeWorkerPool.java:172)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Body:
You have to specify the Media Type of the schema file as application/json[1].After creating the artifacts from the Integration Studio, open the created carbon application and check relevant artifact file of the schema.
Then it should be configured as below.

<?xml version="1.0" encoding="UTF-8"?><resources>
<item>
    <file>ValidationResource.json</file>
    <path>/_system/config/myresources</path>
    <mediaType>application/json</mediaType>
    <properties/>
</item>

[1] https://ei.docs.wso2.com/en/latest/micro-integrator/references/mediators/validate-Mediator/#examples_1


问:
How to store nested data in MySQL Database?
So I'm making a course table which stores course details, which will be displayed on my website. Now each course will have multiple videos/chapters. Eg: A course named stone age, might have 3 chapters pre historic, mediaeval, modern. I need to store link to these three videos under a single course which is "stone age". How do I do that?

Stone Age

pre historic

mediaeval

modern

course 2
etc...

My course table has coursename, coursesubject, coursedescription, cprice, cid, cimg.
Do I need to make another table to store the media content for this course? Or can it be done using a single table?

答:
I suggest that you create a column for the course, one for the chapter and finally one for the video.

```<code>CREATE TABLE course_videos (
   CourseName VARCHAR(25),
   Chapter VARCHAR(25),
   Video VARCHAR(50)
   );
</code>```

I'm assuming that you're storing a URL for the video and not the video itself.
An entry might be:

```<code>INSERT INTO course_videos VALUES (
  'Stone Age' ,
   'pre historique'
   'name of the video.mp4'
   );
</code>```

One simple table will handle the 2 levels of the heirarchy. For the given application I don't anticipate a large number of entries ( <1000) so storage space and optimization of performance are not concerns.

Body:
I suggest that you create a column for the course, one for the chapter and finally one for the video.

CREATE TABLE course_videos (
   CourseName VARCHAR(25),
   Chapter VARCHAR(25),
   Video VARCHAR(50)
   );

I'm assuming that you're storing a URL for the video and not the video itself.
An entry might be:

INSERT INTO course_videos VALUES (
  'Stone Age' ,
   'pre historique'
   'name of the video.mp4'
   );

One simple table will handle the 2 levels of the heirarchy. For the given application I don't anticipate a large number of entries ( <1000) so storage space and optimization of performance are not concerns.


问:
REST URL structure advice
I'm trying to finalise on a restful url structure for the wishlist section of a site I'm working on. It's a pretty simple model, a user can have many wishlists and each wishlist can contain many products.

Currently I have the obvious CRUD URLs to manipulate the wishlist itself :

```<code>GET account/wishlists.json
GET account/wishlists/{id}.json
POST account/wishlists.json?name=My%20Wishlist
POST account/wishlists/{id}.json?name=My%20New%20Name
DELETE account/wishlists/{id}.json
</code>```

However, I don't think I know how to structure the URLs that would add/remove a product to a wishlist :(

Here are my current choices :

1) Have the product to add as part of the URL and use the HTTP verb to define my action

```<code>POST account/wishlist/{id}/product/{product_id}.json
DELETE account/wishlist/{id}/product/{product_id}.json
</code>```

or

2) Have the action as part of the URL and the product id as part of the payload

```<code>POST account/wishlist/{id}/add.json?product_id={product_id}
POST account/wishlist/{id}/remove.json?product_id={product_id}
</code>```

(1) is clean and, as far as I can tell it's pretty RESTful but doesn't allow things like adding multiple products easily etc.

I'm also a bit concerned about using the DELETE verb - I'm not deleting the product or the wishlist, I'm just removing one from the other.

(2) is more explicit but veers away from REST - I wouldn't be just referring to the resource in the url, I would be referring to an operation on that resource :(

Any advice on which of the above would be more correct would be very helpful! (If there's a third option that's better than mine, feel free to correct me!)

答:
I think your first option is more in line with the REST philosophy. If you want to manipulate multiple products, you could pass the ids as a list in the body, instead of using a query parameter.

As for the delete part, given that you are deleting a subresource of wishlist, I think the intention is clear (i.e. remove the connection from the wishlist to the product). If you wanted to globally remove a product, the URL should be something like

```<code>DELETE /products/{id}
</code>```

Title: REST URL structure advice

Body:
I'm trying to finalise on a restful url structure for the wishlist section of a site I'm working on. It's a pretty simple model, a user can have many wishlists and each wishlist can contain many products.

Currently I have the obvious CRUD URLs to manipulate the wishlist itself :

GET account/wishlists.json
GET account/wishlists/{id}.json
POST account/wishlists.json?name=My%20Wishlist
POST account/wishlists/{id}.json?name=My%20New%20Name
DELETE account/wishlists/{id}.json

However, I don't think I know how to structure the URLs that would add/remove a product to a wishlist :(

Here are my current choices :

1) Have the product to add as part of the URL and use the HTTP verb to define my action

POST account/wishlist/{id}/product/{product_id}.json
DELETE account/wishlist/{id}/product/{product_id}.json

or

2) Have the action as part of the URL and the product id as part of the payload

POST account/wishlist/{id}/add.json?product_id={product_id}
POST account/wishlist/{id}/remove.json?product_id={product_id}

(1) is clean and, as far as I can tell it's pretty RESTful but doesn't allow things like adding multiple products easily etc.

I'm also a bit concerned about using the DELETE verb - I'm not deleting the product or the wishlist, I'm just removing one from the other.

(2) is more explicit but veers away from REST - I wouldn't be just referring to the resource in the url, I would be referring to an operation on that resource :(

Any advice on which of the above would be more correct would be very helpful! (If there's a third option that's better than mine, feel free to correct me!)

Body:
I think your first option is more in line with the REST philosophy. If you want to manipulate multiple products, you could pass the ids as a list in the body, instead of using a query parameter.

As for the delete part, given that you are deleting a subresource of wishlist, I think the intention is clear (i.e. remove the connection from the wishlist to the product). If you wanted to globally remove a product, the URL should be something like

DELETE /products/{id}


问:
Cannot convert value of type 'Published<Bool>.Publisher' to expected argument type 'Binding<Bool>'
When trying to compile the following code:

```<code>class LoginViewModel: ObservableObject, Identifiable {
    @Published var mailAdress: String = ""
    @Published var password: String = ""
    @Published var showRegister = false
    @Published var showPasswordReset = false

    private let applicationStore: ApplicationStore

    init(applicationStore: ApplicationStore) {
        self.applicationStore = applicationStore
    }

    var passwordResetView: some View {
        PasswordResetView(isPresented: $showPasswordReset) // This is where the error happens
    }
}
</code>```

Where PasswordResetView looks like this:

```<code>struct PasswordResetView: View {
    @Binding var isPresented: Bool
    @State var mailAddress: String = ""

    var body: some View {
            EmptyView()
        }
    }
}
</code>```

I get the error compile error

```<code>Cannot convert value of type 'Published<Bool>.Publisher' to expected argument type 'Binding<Bool>'
</code>```

If I use the published variable from outside the LoginViewModel class it just works fine:

```<code>struct LoginView: View {
    @ObservedObject var viewModel: LoginViewModel

    init(viewModel: LoginViewModel) {
      self.viewModel = viewModel
    }

    var body: some View {
            PasswordResetView(isPresented: self.$viewModel.showPasswordReset)
    }
}
</code>```

Any suggestions what I am doing wrong here? Any chance I can pass a published variable as a binding from inside the owning class?

Thanks!

答:
Not sure why the proposed solutions here are so complex, when there is a very direct fix for this.

Found this answer on a similar Reddit question:

The problem is that you are accessing the projected value of an @Published (which is a Publisher) when you should instead be accessing the projected value of an @ObservedObject (which is a Binding), that is: you have globalSettings.$tutorialView where you should have $globalSettings.tutorialView.

Body:
When trying to compile the following code:

class LoginViewModel: ObservableObject, Identifiable {
    @Published var mailAdress: String = ""
    @Published var password: String = ""
    @Published var showRegister = false
    @Published var showPasswordReset = false

    private let applicationStore: ApplicationStore

    init(applicationStore: ApplicationStore) {
        self.applicationStore = applicationStore
    }

    var passwordResetView: some View {
        PasswordResetView(isPresented: $showPasswordReset) // This is where the error happens
    }
}

Where PasswordResetView looks like this:

struct PasswordResetView: View {
    @Binding var isPresented: Bool
    @State var mailAddress: String = ""

    var body: some View {
            EmptyView()
        }
    }
}

I get the error compile error

Cannot convert value of type 'Published<Bool>.Publisher' to expected argument type 'Binding<Bool>'

If I use the published variable from outside the LoginViewModel class it just works fine:

struct LoginView: View {
    @ObservedObject var viewModel: LoginViewModel

    init(viewModel: LoginViewModel) {
      self.viewModel = viewModel
    }

    var body: some View {
            PasswordResetView(isPresented: self.$viewModel.showPasswordReset)
    }
}

Any suggestions what I am doing wrong here? Any chance I can pass a published variable as a binding from inside the owning class?

Thanks!


问:
Can't change python interpreter from VS CODE Status Bar
Status Bar Image when python file is opened

pls help if you can, idk why the current active interpreter is not visible in the status bar anymore when ive python file opened, its a pain to open command pallete and then type python interpreter just to check what venv im in.

答: You can just tap CTRL + Shift + P and typing Python Interpreter, it'll will show in VS Code a way to you select a interpreter.


问:
Spring Security addFilterAfter method removes the registered filter
I have a spring project with only two dependencies web & security (for testing purpose)

I am just creating simple filter like that:

public class TestFilter implements Filter {
    private AuthenticationManager authenticationManager;

    public TestFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        filterChain.doFilter(servletRequest, servletResponse);
    }
}
```
<p>And registering this filter in the configuration:</p>
<pre class="lang-java prettyprint-override"><code>@Configuration
@EnableWebSecurity(debug = true)
public class TestConf extends WebSecurityConfigurerAdapter {

    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterAfter(new TestFilter(authenticationManagerBean()), BasicAuthenticationFilter.class);
    }
}
</code>```

Problem is that,

if I use addFilterAfter method, BasicAuthenticationFilter is removed by the Spring, (I can confirm that with console output, @EnableWebSecurity(debug = true) this annotation prints all security filters)

Here is the log:

```<code>o.s.s.web.DefaultSecurityFilterChain     : Will secure any request with [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@158f4cfe, org.springframework.security.web.context.SecurityContextPersistenceFilter@1174a305, org.springframework.security.web.header.HeaderWriterFilter@2b037cfc, org.springframework.security.web.csrf.CsrfFilter@76db540e, org.springframework.security.web.authentication.logout.LogoutFilter@13741d5a, com.....security.filter.TestFilter@35f639fa, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@1866da85, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@2ec3633f, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@5aaaa446, org.springframework.security.web.session.SessionManagementFilter@19ee1ae6, org.springframework.security.web.access.ExceptionTranslationFilter@4eb1c69]
</code>```

if i don't register my custom filter, then I can see BasicAuthenticationFilter: security.web.authentication.www.BasicAuthenticationFilter

Here is the configuration class:

@Configuration
@EnableWebSecurity(debug = true)
public class ProjectBeanConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
    }
}
```
<p>Here is the log:</p>
``` o.s.s.web.DefaultSecurityFilterChain     : Will secure any request with [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@704641e3, org.springframework.security.web.context.SecurityContextPersistenceFilter@750ff7d3, org.springframework.security.web.header.HeaderWriterFilter@42b6d0cc, org.springframework.security.web.csrf.CsrfFilter@5c7668ba, org.springframework.security.web.authentication.logout.LogoutFilter@459b187a, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@741f8dbe, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter@7fd26ad8, org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter@2f00f851, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@7a8406c2, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@2620e717, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@3d37203b, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@4207609e, org.springframework.security.web.session.SessionManagementFilter@3f4f5330, org.springframework.security.web.access.ExceptionTranslationFilter@e042c99, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@17d32e9b]
```

What can be the reason?

答:
It is because you define your own WebSecurityConfigurerAdapter which causes the default security configuration defined by spring-boot does not take effect. And in your configuration , you never enable BasicAuthenticationFilter. So try the following should fix the problem :

@Override
protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic()
        .and().addFilterAfter(new TestFilter(authenticationManagerBean()), BasicAuthenticationFilter.class);
 }
```
<p>If you want to keep the default configuration provided by spring-boot and add a <code>TestFilter</code> on top of it , you have to configure it manually :</p>
<pre class="lang-java prettyprint-override"><code>@Override
protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated().and().formLogin().and().httpBasic()
        .and().addFilterAfter(new TestFilter(authenticationManagerBean()), BasicAuthenticationFilter.class);
 }
</code>```

You can find the default configuration at here and its javadoc also already mentioned such behaviour :

The default configuration for web security. It relies on Spring
Security's content-negotiation strategy to determine what sort of
authentication to use. If the user specifies their own
WebSecurityConfigurerAdapter or  SecurityFilterChain bean, this
will back-off completely and the users should  specify all the bits
that they want to configure as part of the custom security
configuration.

Body:
I have a spring project with only two dependencies web & security (for testing purpose)

I am just creating simple filter like that:

public class TestFilter implements Filter {
    private AuthenticationManager authenticationManager;

    public TestFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        filterChain.doFilter(servletRequest, servletResponse);
    }
}

And registering this filter in the configuration:

@Configuration
@EnableWebSecurity(debug = true)
public class TestConf extends WebSecurityConfigurerAdapter {

    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterAfter(new TestFilter(authenticationManagerBean()), BasicAuthenticationFilter.class);
    }
}

Problem is that,

if I use addFilterAfter method, BasicAuthenticationFilter is removed by the Spring, (I can confirm that with console output, @EnableWebSecurity(debug = true) this annotation prints all security filters)

Here is the log:

o.s.s.web.DefaultSecurityFilterChain     : Will secure any request with [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@158f4cfe, org.springframework.security.web.context.SecurityContextPersistenceFilter@1174a305, org.springframework.security.web.header.HeaderWriterFilter@2b037cfc, org.springframework.security.web.csrf.CsrfFilter@76db540e, org.springframework.security.web.authentication.logout.LogoutFilter@13741d5a, com.....security.filter.TestFilter@35f639fa, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@1866da85, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@2ec3633f, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@5aaaa446, org.springframework.security.web.session.SessionManagementFilter@19ee1ae6, org.springframework.security.web.access.ExceptionTranslationFilter@4eb1c69]

if i don't register my custom filter, then I can see BasicAuthenticationFilter: security.web.authentication.www.BasicAuthenticationFilter

Here is the configuration class:

@Configuration
@EnableWebSecurity(debug = true)
public class ProjectBeanConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
    }
}

Here is the log:

 o.s.s.web.DefaultSecurityFilterChain     : Will secure any request with [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@704641e3, org.springframework.security.web.context.SecurityContextPersistenceFilter@750ff7d3, org.springframework.security.web.header.HeaderWriterFilter@42b6d0cc, org.springframework.security.web.csrf.CsrfFilter@5c7668ba, org.springframework.security.web.authentication.logout.LogoutFilter@459b187a, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@741f8dbe, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter@7fd26ad8, org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter@2f00f851, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@7a8406c2, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@2620e717, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@3d37203b, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@4207609e, org.springframework.security.web.session.SessionManagementFilter@3f4f5330, org.springframework.security.web.access.ExceptionTranslationFilter@e042c99, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@17d32e9b]

What can be the reason?

Body:
It is because you define your own WebSecurityConfigurerAdapter which causes the default security configuration defined by spring-boot does not take effect. And in your configuration , you never enable BasicAuthenticationFilter. So try the following should fix the problem :

@Override
protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic()
        .and().addFilterAfter(new TestFilter(authenticationManagerBean()), BasicAuthenticationFilter.class);
 }

If you want to keep the default configuration provided by spring-boot and add a TestFilter on top of it , you have to configure it manually :

@Override
protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated().and().formLogin().and().httpBasic()
        .and().addFilterAfter(new TestFilter(authenticationManagerBean()), BasicAuthenticationFilter.class);
 }

You can find the default configuration at here and its javadoc also already mentioned such behaviour :

The default configuration for web security. It relies on Spring
Security's content-negotiation strategy to determine what sort of
authentication to use. If the user specifies their own
WebSecurityConfigurerAdapter or  SecurityFilterChain bean, this
will back-off completely and the users should  specify all the bits
that they want to configure as part of the custom security
configuration.


问:
./arrayScript.sh: 3: NAME[0]=Zara: not found
I am learning how shell scripting in Unix and have written a simple shell script:

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

NAME[0]="Zara"
NAME[1]="Qadir"
NAME[2]="Mahnaz"
NAME[3]="Ayan"
NAME[4]="Daisy"
echo "First Index: ${NAME[0]}"
echo "Second Index: ${NAME[1]}"
</code>```

However, whenever I run this in ubuntu as ./arrayScript.sh I am met with this error:

```<code>./arrayScript.sh: 3: NAME[0]=Zara: not found
./arrayScript.sh: 4: NAME[1]=Qadir: not found
./arrayScript.sh: 5: NAME[2]=Mahnaz: not found
./arrayScript.sh: 6: NAME[3]=Ayan: not found
./arrayScript.sh: 7: NAME[4]=Daisy: not found
./arrayScript.sh: 8: Bad substitution
</code>```

I have come to understand that .sh files do not support arrays and that if I run the file as:

```<code>bash ./arrayScript.sh
</code>```

It works fines, but I thought that running ./arrayScript.sh should have worked because that is what is given in the tutorial example? Can someone inform me whether I am doing something wrong, as I have copied the example letter for letter from here:
https://www.tutorialspoint.com/unix/unix-using-arrays.htm

答:
#!/bin/sh is not bash. When you call it on cli with bash ./arrayScript.sh, the interpretor mentioned in the shebang is ignored and it will be parsed by bash. Your code works. When you simply call it with ./arrayScript.sh it uses that shebang to determine the interpretor. You have sh and not bash, so it picks the wrong interpretor for the code in the file.

Replace #!/bin/sh with #!/bin/bash and you should be fine.

Body:
I am learning how shell scripting in Unix and have written a simple shell script:

#!/bin/sh

NAME[0]="Zara"
NAME[1]="Qadir"
NAME[2]="Mahnaz"
NAME[3]="Ayan"
NAME[4]="Daisy"
echo "First Index: ${NAME[0]}"
echo "Second Index: ${NAME[1]}"

However, whenever I run this in ubuntu as ./arrayScript.sh I am met with this error:

./arrayScript.sh: 3: NAME[0]=Zara: not found
./arrayScript.sh: 4: NAME[1]=Qadir: not found
./arrayScript.sh: 5: NAME[2]=Mahnaz: not found
./arrayScript.sh: 6: NAME[3]=Ayan: not found
./arrayScript.sh: 7: NAME[4]=Daisy: not found
./arrayScript.sh: 8: Bad substitution

I have come to understand that .sh files do not support arrays and that if I run the file as:

bash ./arrayScript.sh

It works fines, but I thought that running ./arrayScript.sh should have worked because that is what is given in the tutorial example? Can someone inform me whether I am doing something wrong, as I have copied the example letter for letter from here:
https://www.tutorialspoint.com/unix/unix-using-arrays.htm


问:
Wrong Azerty keyboard layout for Logitech MX keys Azerty version in Linux
I have a very weird issue. I purchased the Logitech MX Keys Macintosh version. After settings up Pop OS by choosing the French Macinstosh version (which) is the correct one, the Logitech version swaps my @ and < key strokes. When I connect a native Macintosh keyboard it works. Anyone any tip how I can fix this?</p>

答:
I had the same issue but not sure about the cause, pressing fn +p for 3 seconds seems to switch it back correctly.

Also, via the Logitech software:

disable the 'Always keep in mac-layout'.


问:
How could I use mobx in nodejs but not browser?
I try to use mobx in nodejs but the script is not work.

```<code>(async function () {
  const mobx = require('./mobx.umd.min.js')
  // example 2, array of primitives
  // observes computed value, works
  const { observable, computed, autorun } = mobx;

  var numbers = observable([1, 2, 3]);
  autorun(() => {

    console.log(numbers);
  });
  numbers.push(4); //autorun does not trigger
  numbers.push(4); //autorun does not trigger
})();

</code>```

but the script works in broswer:

<!DOCTYPE html>

```

I want to use mobx in nodejs, How could I use mobx in nodejs directly?

答:
You are referencing numbers array inside Node.js autorun, but you have not changed it, so there is not reason to MobX to autorun. Observers (e.g. autorun, computed, observer and etc.) only react when something was changed.

You only changed array content, not the array itself. So if your code was something like that:

```<code>  autorun(() => {
    console.log(numbers.map(x => x);
  });
</code>```

It would work as expected, because here you actually referencing array content. And browser version works because you are using numbers.join and referencing array content with that call.

Next time try to test identical cases in both environments just to be sure that the error in not in your code!

Body:
I try to use mobx in nodejs but the script is not work.

(async function () {
  const mobx = require('./mobx.umd.min.js')
  // example 2, array of primitives
  // observes computed value, works
  const { observable, computed, autorun } = mobx;

  var numbers = observable([1, 2, 3]);
  autorun(() => {

    console.log(numbers);
  });
  numbers.push(4); //autorun does not trigger
  numbers.push(4); //autorun does not trigger
})();

but the script works in broswer:

<!DOCTYPE html>

I want to use mobx in nodejs, How could I use mobx in nodejs directly?

Body:
You are referencing numbers array inside Node.js autorun, but you have not changed it, so there is not reason to MobX to autorun. Observers (e.g. autorun, computed, observer and etc.) only react when something was changed.

You only changed array content, not the array itself. So if your code was something like that:

  autorun(() => {
    console.log(numbers.map(x => x);
  });

It would work as expected, because here you actually referencing array content. And browser version works because you are using numbers.join and referencing array content with that call.

Next time try to test identical cases in both environments just to be sure that the error in not in your code!


问:
on_message() does not allow @bot.commad() to work
i have code:

```<code>bot = commands.Bot(command_prefix='!')
@bot.event
async def on_ready():
    print('Егор выпущен на охоту')

@bot.event
async def on_message(message):
    if message.content.lower().startswith('шутка'):
        await message.channel.send(random.choice(arr2))
        await  bot.process_commands(message)

@bot.command(name="flip")
async def flip(ctx):
    await ctx.send(random.choice(flips))
bot.run('TOKEN')
</code>```

i tried await bot.process_commands(message) but it didn't help. What could be the issue and how to fix it?

答:
The only time bot.process_commands(message) is run in your code is if the user types "шутка", which is not what you want. Instead, take the process outside of the if statement, as seen in the revised code below.

@bot.event
async def on_message(message):
    if message.content.lower().startswith('шутка'):
        await message.channel.send(random.choice(arr2))
    await bot.process_commands(message)
```

Body:
i have code:

bot = commands.Bot(command_prefix='!')
@bot.event
async def on_ready():
    print('Егор выпущен на охоту')

@bot.event
async def on_message(message):
    if message.content.lower().startswith('шутка'):
        await message.channel.send(random.choice(arr2))
        await  bot.process_commands(message)

@bot.command(name="flip")
async def flip(ctx):
    await ctx.send(random.choice(flips))
bot.run('TOKEN')

i tried await bot.process_commands(message) but it didn't help. What could be the issue and how to fix it?