问:
Can I capture the exception information in python without using try statement?
I wonder if there is a way to capture the exception information when running a Python script, besides using try-except statements?

My Python script is subject to constant change by different people. Errors can occur anywhere inside the file, either a syntax or value error.

I want to be able to interpret the exception information and provide custom error messages to people, for friendly reminding.

I don't want, or couldn't afford, to include all code lines into the try statement. Just wonder if I can have custom error message displayed whenever there is an exception raised.

Thank you for helping out here!

Regards,
Paul

答:
The beauty of a try/catch statement is that it catches any unhandled exceptions raised by any lower scope.  You can put a try/catch at the very top level of your script and it'll catch anything that happens anywhere else.  There's no need to wrap each line individually!

```<code>if __name__ == '__main__':
    try:
        my_main_func()
    except Exception as e:
        # this will catch any exception from anywhere else in the program!
        print(e)
        raise
</code>```

Body:
The beauty of a try/catch statement is that it catches any unhandled exceptions raised by any lower scope.  You can put a try/catch at the very top level of your script and it'll catch anything that happens anywhere else.  There's no need to wrap each line individually!

if __name__ == '__main__':
    try:
        my_main_func()
    except Exception as e:
        # this will catch any exception from anywhere else in the program!
        print(e)
        raise


来源: stackexchange

问:
git - unable to create temporary file: no such file or directory - only for certain files?
I've got a strange issue here with one of my git repositories. I cannot add certain files. Git states:

$ git add Konstruktion/Druckteile/1x_*

  warning: CRLF will be replaced by LF in Konstruktion/Druckteile/1x_Hals.gcode.

  The file will have its original line endings in your working directory.

  error: unable to create temporary file: No such file or directory

  error: Konstruktion/Druckteile/1x_Nickhalter_links.STL: failed to insert into database

  error: unable to index file Konstruktion/Druckteile/1x_Nickhalter_links.STL

  fatal: adding files failed

But only for this single file. All other files in the same directory, even with similar names (e.g. 1x_Nickhalter_rechts.STL) work like a charm. Why only this file? What's special about it?

What can I do to figure out what's wrong?

Ah, just for info: it's git 1.8.5.2.msysgit.0 running on Windows 8.1 (64bit).

Thanks a lot.

Cheers,
Hendrik

答: I had protected folders enabled in windows. You need to add git to apps that can modify certain folders.</p>

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
How to round numeric values from Google Sheet to specific precision?
I have javascript function that let round to precision any numeric values

Usually it works well. But there are some values returns not very correct result.
So what I mean

function roundToPrecision(x, precision) {
  var y = +x + (precision === undefined ? 0.5 : precision / 2);
  return y - (y % (precision === undefined ? 1 : +precision));
}

function test() {
  console.log(roundToPrecision(678.03423424554234, 0.01)) //678.03 OK
  console.log(roundToPrecision(4.12342545544545, 0.01)) //4.12 OK
  console.log(roundToPrecision(34.0516356456356, 0.01)) //34.05 OK
  console.log(roundToPrecision(23.0769230769231, 0.01)) //23.080000000000002 not correct!
  console.log(roundToPrecision(4.06153846153846, 0.01)) //4.0600000000000005 not correct!

}
test()```

I don't understand why it is happening. Source values comes from Google Sheet.
I know I can use toFixed() but this method returns string. I need numeric results.
Where I'm wrong and how to fix it?

答:
function roundToPrecision(x, precision) {
  return Number(x.toFixed(precision));
}

function test() {
  console.log(roundToPrecision(678.03423424554234, 2)) //678.03 OK
  console.log(roundToPrecision(4.12342545544545, 2)) //4.12 OK
  console.log(roundToPrecision(34.0516356456356, 2)) //34.05 OK
  console.log(roundToPrecision(23.0769230769231, 2)) //23.080000000000002 not correct!
  console.log(roundToPrecision(4.06153846153846, 2)) //4.0600000000000005 not correct!

}
test()```

Body:
I have javascript function that let round to precision any numeric values

Usually it works well. But there are some values returns not very correct result.
So what I mean

function roundToPrecision(x, precision) {
  var y = +x + (precision === undefined ? 0.5 : precision / 2);
  return y - (y % (precision === undefined ? 1 : +precision));
}

function test() {
  console.log(roundToPrecision(678.03423424554234, 0.01)) //678.03 OK
  console.log(roundToPrecision(4.12342545544545, 0.01)) //4.12 OK
  console.log(roundToPrecision(34.0516356456356, 0.01)) //34.05 OK
  console.log(roundToPrecision(23.0769230769231, 0.01)) //23.080000000000002 not correct!
  console.log(roundToPrecision(4.06153846153846, 0.01)) //4.0600000000000005 not correct!

}
test()

I don't understand why it is happening. Source values comes from Google Sheet.
I know I can use toFixed() but this method returns string. I need numeric results.
Where I'm wrong and how to fix it?


问:
How to redirect to a different domain using Nginx?
How can I redirect mydomain.example and any subdomain *.mydomain.example to www.adifferentdomain.example using Nginx?

答:
You can simply write a if condition inside server {} block:</p>
```<code>server {

    if ($host = mydomain.example) {
        return 301 http://www.adifferentdomain.example;
    }
}
</code>```

Body:
You can simply write a if condition inside server {} block:

server {

    if ($host = mydomain.example) {
        return 301 http://www.adifferentdomain.example;
    }
}


问:
Server Role to execute SQL Server Agent Jobs in SQL SERVER 2008
The users from other departments ask me to grant them to execute Schedule Jobs / SSIS in SQL Server Agent.  At present, they cannot see SQL Server Agent tree in their ManagmentStudio.  I think, it's because they don't have the rights to execute them.

So, I would like to know which server role should I give to them.  I only want to give them minimum privileges.  When I check the existing roles in my server, I could only see the following server roles

bulkadmin

dbcreator

diskadmin

processadmin

public

securityadmin

serveradmin

setupadmin

sysadmin

Please advise me.

答:
It isn't a server role.

It is one of the "SQL Server Agent Fixed Database Roles" in msdb

See "How to: Configure a User to Create and Manage SQL Server Agent Jobs (SQL Server Management Studio)" on MSDN


问:
After Encode to base64 image rotated by 90 degres
in my app I'm uploading images to server. I encode image from my WP 8.1 and send it to server. Sending and receiving work well but I have problem with image. I don't know why but whem I uploaded the image photographed on portrait after decoding is this image rotated by 90 degrees. Landscapes images are good, but portrait are rotated. Here is my encode and decode code

Encode:

```<code> private async Task<string> StorageFileToBase64(StorageFile file)
        {
            string Base64String = "";

            if (file != null)
            {
                IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read);
                var reader = new DataReader(fileStream.GetInputStreamAt(0));
                await reader.LoadAsync((uint)fileStream.Size);
                byte[] byteArray = new byte[fileStream.Size];
                reader.ReadBytes(byteArray);
                Base64String = Convert.ToBase64String(byteArray);
            }

            return Base64String;
        }
</code>```

Decode image on server

```<code>public void ShowImg(string b64)
            {
                byte[] imageBytes = Convert.FromBase64String(b64);
                // Convert byte[] to Image
                var ms = new MemoryStream(imageBytes, 0, imageBytes.Length);

                Image image = Image.FromStream(ms, true);

                f.pictureBox1.Image = image;

            }
</code>```

答:
```<code>string startExpression = "data:image/png;base64,";
using (var ms = new MemoryStream())
{
   ms.Flush();
   System.Drawing.Image imageIn = System.Drawing.Image.FromFile(fileName);
   ms.Position = 0;
   imageIn.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipX);
   imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
   var bytes= ms.ToArray();
   string fileBase = Convert.ToBase64String(bytes);
   var base64= startExpression + fileBase;
   imageIn.Dispose();
   ms.Dispose();
}
</code>```

Body:
in my app I'm uploading images to server. I encode image from my WP 8.1 and send it to server. Sending and receiving work well but I have problem with image. I don't know why but whem I uploaded the image photographed on portrait after decoding is this image rotated by 90 degrees. Landscapes images are good, but portrait are rotated. Here is my encode and decode code

Encode:

 private async Task<string> StorageFileToBase64(StorageFile file)
        {
            string Base64String = "";

            if (file != null)
            {
                IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read);
                var reader = new DataReader(fileStream.GetInputStreamAt(0));
                await reader.LoadAsync((uint)fileStream.Size);
                byte[] byteArray = new byte[fileStream.Size];
                reader.ReadBytes(byteArray);
                Base64String = Convert.ToBase64String(byteArray);
            }

            return Base64String;
        }

Decode image on server

public void ShowImg(string b64)
            {
                byte[] imageBytes = Convert.FromBase64String(b64);
                // Convert byte[] to Image
                var ms = new MemoryStream(imageBytes, 0, imageBytes.Length);

                Image image = Image.FromStream(ms, true);

                f.pictureBox1.Image = image;

            }


问:
BLE Advertising RawData - How to decode?
I have a E66 Fitness band connected to a gateway and the band does connect to the gateway and I receive data on MQTT.
But I am unsure on how to decode the RawData format, can someone help me with that?
Thanks  </p>

```<code>{
      "TimeStamp":"2020-05-30 16:44:32",
      "DataFormat":"RawData",
      "BLEMac(hex)":"E5F604C2EAAE",
      "RSSI(dBm)":-30,
      "BLEName":"E67 EAAE",
      "RawData(hex)":"02010610FF107803E8000000000000640023290009094536372045414145"
  }

</code>```

答:
BLE data is decoded as follows:-

1st byte = length (n bytes)

2nd byte = Types

n-1 bytes = actual data

And this repeats over the whole raw data. You can find the meaning of raw data here. Going over your example:-

1st Set:

02: Length: 2 Bytes

01: Type: Flags

06: Flag - 02 && 04: LE General Discoverable && BR/EDR Not Supported

2nd Set:

10: Length: 16 bytes

FF: Type: Manufacture Data

107803E80000000000006400232900: Data specific to the manufacturer

3rd Set:

09: Length: 9 bytes

09: Type: Complete Local Name

4536372045414145: E67 EAAE (Name of device in ASCII)

I hope this helps.

Body:
I have a E66 Fitness band connected to a gateway and the band does connect to the gateway and I receive data on MQTT.
But I am unsure on how to decode the RawData format, can someone help me with that?
Thanks

{
      "TimeStamp":"2020-05-30 16:44:32",
      "DataFormat":"RawData",
      "BLEMac(hex)":"E5F604C2EAAE",
      "RSSI(dBm)":-30,
      "BLEName":"E67 EAAE",
      "RawData(hex)":"02010610FF107803E8000000000000640023290009094536372045414145"
  }


问:
PostgreSQL: What is meant by "please specify covering index name"
I wanted to edit the actions in a table. However I get the error message "Please specify covering index name." when I try to edit the FK. How do I fix this?

The table consists of only two columns:

The foreign keys:

category FK:

答: in our case this helped: before saving "new FK", firstly open "edit options" of "previously created FK", and DO NOT CHANGE anything then return to "newly created FK" edit options, save button magically activated


问:
useEffect dependency with Context API. My code works fine with empty array but still gives the warning
So. I get clients from context as initialState and the code below is from my listing component (listClients.js or smth) . I update the context with the data fetched from firebase. Everything works fine actully with using empty array as dependency. I get my final array listed on my list component.. But eslint is still saying me that I should add "clientsRef" and "updateClients" into dependency but this causes an infinite loop. So what should I do with that? Close my eyes to this warning?</p>

```<code>const { clients, removeClient, updateClients } = useContext(ClientsContext);
const collection = 'clients';
const clientsRef = firestore.collection('clients').orderBy('createdAt', 'desc');

useEffect(() => {

    const unsubscribeFromSnapshot = clientsRef.onSnapshot(async snapshot => {
        const clientsMap = convertSnapshotToMap(snapshot);
        updateClients(clientsMap);

    });

    return () => {
        unsubscribeFromSnapshot();
    }
}, []);
</code>```

答:
You can declare the clientsRef within the useEffect and for updateCloients function you can make use of useCallback in the ContextProvider. Once you do that you can add them as a dependency to useEffect

```<code>const { clients, removeClient, updateClients } = useContext(ClientsContext);

useEffect(() => {
    const collection = 'clients';
     const clientsRef = firestore.collection('clients').orderBy('createdAt', 'desc');
    const unsubscribeFromSnapshot = clientsRef.onSnapshot(async snapshot => {
        const clientsMap = convertSnapshotToMap(snapshot);
        updateClients(clientsMap);

    });

    return () => {
        unsubscribeFromSnapshot();
    }
}, []);
</code>```

In ClientContext Provider

```<code>const updateClients = useCallback(() => {
   // logic here
}, []);
</code>```

However if you are sure that you just want the logic within useEffect to run once and not anytime later, you can disable the warning with

```<code>// eslint-disable-next-line react-hooks/exhaustive-deps
</code>```

Ex:

```<code>useEffect(() => {

    const unsubscribeFromSnapshot = clientsRef.onSnapshot(async snapshot => {
        const clientsMap = convertSnapshotToMap(snapshot);
        updateClients(clientsMap);

    });

    return () => {
        unsubscribeFromSnapshot();
    }
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
</code>```

For more details please check this post:

How to fix missing dependency warning when using useEffect React Hook?

Body:
So. I get clients from context as initialState and the code below is from my listing component (listClients.js or smth) . I update the context with the data fetched from firebase. Everything works fine actully with using empty array as dependency. I get my final array listed on my list component.. But eslint is still saying me that I should add "clientsRef" and "updateClients" into dependency but this causes an infinite loop. So what should I do with that? Close my eyes to this warning?

const { clients, removeClient, updateClients } = useContext(ClientsContext);
const collection = 'clients';
const clientsRef = firestore.collection('clients').orderBy('createdAt', 'desc');

useEffect(() => {

    const unsubscribeFromSnapshot = clientsRef.onSnapshot(async snapshot => {
        const clientsMap = convertSnapshotToMap(snapshot);
        updateClients(clientsMap);

    });

    return () => {
        unsubscribeFromSnapshot();
    }
}, []);

Body:
You can declare the clientsRef within the useEffect and for updateCloients function you can make use of useCallback in the ContextProvider. Once you do that you can add them as a dependency to useEffect

const { clients, removeClient, updateClients } = useContext(ClientsContext);

useEffect(() => {
    const collection = 'clients';
     const clientsRef = firestore.collection('clients').orderBy('createdAt', 'desc');
    const unsubscribeFromSnapshot = clientsRef.onSnapshot(async snapshot => {
        const clientsMap = convertSnapshotToMap(snapshot);
        updateClients(clientsMap);

    });

    return () => {
        unsubscribeFromSnapshot();
    }
}, []);

In ClientContext Provider

const updateClients = useCallback(() => {
   // logic here
}, []);

However if you are sure that you just want the logic within useEffect to run once and not anytime later, you can disable the warning with

// eslint-disable-next-line react-hooks/exhaustive-deps

Ex:

useEffect(() => {

    const unsubscribeFromSnapshot = clientsRef.onSnapshot(async snapshot => {
        const clientsMap = convertSnapshotToMap(snapshot);
        updateClients(clientsMap);

    });

    return () => {
        unsubscribeFromSnapshot();
    }
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

For more details please check this post:

How to fix missing dependency warning when using useEffect React Hook?


问:
Invalid Cast Exception in UWP Treeview C#
When using a treeview that is bound to a three tier hierarchical collection (Order - SKU - Location). I am using a DataTemplateSelector to choose the TreeViewItem template to use. I am getting an Invalid exception exactly the same as in this post when I scroll - the exception seems to occur faster if I scroll faster.

I have attempted both suggested solutions in that post (wrapping the treeview in a scroll viewer, and the custom user control). Wrapping the TreeView does not help, and I cannot get the custom user control solution to work correctly for me and I wonder if it is related to the fact I have a three tier collection instead of two tiers. The code for the custom UserControl is exactly the same as in the linked post except modified for my collection. When I try it it only binds one tier of the collection to the treeview. What I am looking for is a solution prevents the framework code from reusing the templates which appears to be what is causing the exception.

Here is my XAML and code for the TreeView that currently produces the exception:

```<code><Page
x:Class="PickSheetManager.Views.PickSheetManagerPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:winui="using:Microsoft.UI.Xaml.Controls"
xmlns:model="using:PickSheetManager.Core.Models"
xmlns:behaviors="using:PickSheetManager.Behaviors"
xmlns:templateSelectors="using:PickSheetManager.TemplateSelectors"
xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
xmlns:controls1="using:PickSheetManager.Controls"
xmlns:ic="using:Microsoft.Xaml.Interactions.Core"
xmlns:i="using:Microsoft.Xaml.Interactivity"
Style="{StaticResource PageStyle}"
behaviors:NavigationViewHeaderBehavior.HeaderMode="Never"
mc:Ignorable="d">

<Page.Resources>
    <DataTemplate x:Key="OrderTemplate" x:DataType="model:Order">
        <winui:TreeViewItem
            AutomationProperties.Name="{x:Bind PoIDx}"
            ItemsSource="{x:Bind SKUs}" IsExpanded="True">
            <StackPanel x:Name="stack" Orientation="Horizontal">
            <i:Interaction.Behaviors>
                <ic:DataTriggerBehavior Binding ="{x:Bind NotEnoughInventory}" Value="True">
                    <ic:ChangePropertyAction TargetObject="{Binding ElementName=stack}" PropertyName="Background" Value="Red" />
                </ic:DataTriggerBehavior>
            </i:Interaction.Behaviors>
            <CheckBox IsChecked="{x:Bind IsSelected, Mode=TwoWay}" Padding="5" MinWidth="0"/>
            <TextBlock Text="PoIDx: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
            <TextBlock Text="{x:Bind PoIDx}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
            <TextBlock Text="Delivery: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
            <TextBlock Text="{x:Bind DeliveryType}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
            <TextBlock Text="Delivery: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
            <TextBlock Text="{x:Bind DeliveryType}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
            <TextBlock Text="Type: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
            <TextBlock Text="{x:Bind OrderType}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
            <TextBlock Text="Total Quantity: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
            <TextBlock Text="{x:Bind TotalQuantity}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
            <TextBlock Text="Printed: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
            <TextBlock Text="{x:Bind IsPrinted}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
            <TextBlock Text="Notes: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
            <TextBox Text="{x:Bind Notes, Mode=TwoWay}" Margin="{StaticResource XXSmallTopRightBottomMargin}" Width="150"/>
        </StackPanel>
        </winui:TreeViewItem>
    </DataTemplate>

    <DataTemplate x:Key="SKUTemplate" x:DataType="model:SKU">
        <winui:TreeViewItem
            AutomationProperties.Name="{x:Bind SKUNum}"
            ItemsSource="{x:Bind Locations}" IsExpanded="True">
            <StackPanel x:Name="stack2" Orientation="Horizontal">
                <i:Interaction.Behaviors>
                    <ic:DataTriggerBehavior Binding ="{x:Bind NotEnoughInventory}" Value="True">
                        <ic:ChangePropertyAction TargetObject="{Binding ElementName=stack2}" PropertyName="Background" Value="Yellow" />
                    </ic:DataTriggerBehavior>
                </i:Interaction.Behaviors>
                <CheckBox IsChecked="{x:Bind IsSelected, Mode=TwoWay}" Padding="5" MinWidth="0" />
                <TextBlock Text="SKU: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="{x:Bind SKUNum}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="Needed: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="{x:Bind NeedQuantity}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="Available: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="{x:Bind AvailableQuantity}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
            </StackPanel>
        </winui:TreeViewItem>
    </DataTemplate>

    <DataTemplate x:Key="LocationTemplate" x:DataType="model:Location">
        <winui:TreeViewItem
            AutomationProperties.Name="{x:Bind LocationName}"
            IsExpanded="True">
            <StackPanel Orientation="Horizontal">
                <CheckBox IsChecked="{x:Bind IsSelected, Mode=TwoWay}" Padding="5" MinWidth="0" />
                <TextBlock Text="{x:Bind LocationName}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="Pick Type: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="{x:Bind PickType}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="Pick Quantity: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="{x:Bind PickQuantity}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="Available Quantity: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="{x:Bind AvailableQuantity}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBox Text="{x:Bind Notes, Mode=TwoWay}" Margin="{StaticResource XXSmallTopRightBottomMargin}" Width="150" />
            </StackPanel>
        </winui:TreeViewItem>
    </DataTemplate>

    <templateSelectors:SampleDataTemplateSelector x:Key="TreeViewTemplateSelector"
        OrderDetailTemplate="{StaticResource OrderTemplate}"
        SKUDetailTemplate="{StaticResource SKUTemplate}"
        LocationDetailTemplate="{StaticResource LocationTemplate}" />
</Page.Resources>

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition x:Name="treeViewColumn" Width="6*" />
        <ColumnDefinition x:Name="detailViewColumn" Width="4*" />
    </Grid.ColumnDefinitions>
    <Grid Grid.Column="0">
        <Grid.RowDefinitions>
            <RowDefinition x:Name="treeViewRow" Height="8*" />
            <RowDefinition x:Name="controlRow" Height="2*" />
        </Grid.RowDefinitions>
        <ScrollViewer x:Name="WrapViewer" Grid.Row="0" Grid.Column="0" Padding="{StaticResource DetailPageMargin}">
        </ScrollViewer>
        <winui:TreeView
            x:Name="treeView"
            Grid.Row="0"
            SelectionMode="Single"
            ItemsSource="{x:Bind ViewModel.openOrders}"
            ItemTemplateSelector="{StaticResource TreeViewTemplateSelector}">
            <i:Interaction.Behaviors>
                <behaviors:TreeViewCollapseBehavior x:Name="collapseBehavior" />
                <ic:EventTriggerBehavior EventName="ItemInvoked">
                    <ic:InvokeCommandAction Command="{x:Bind ViewModel.ItemInvokedCommand}" />
                </ic:EventTriggerBehavior>
            </i:Interaction.Behaviors>
        </winui:TreeView>
    </Grid>
    <Grid Grid.Column="1">
        <Grid.RowDefinitions>
            <RowDefinition x:Name="detailViewRow" Height="4*" />
            <RowDefinition x:Name="iarRow" Height="4*" />
            <RowDefinition x:Name="controlRow2" Height="2*" />
        </Grid.RowDefinitions>
    </Grid>
</Grid>
</code>```

The collection being bound

```<code> public ObservableCollection<Order> openOrders { get; } = new ObservableCollection<Order>();

 public async Task LoadDataAsync()
 {
     var data2 = await OrderDataLoader.GetTreeViewDataAsync();
     foreach (var item in data2)
     {
         openOrders.Add(item);
     }
 }
</code>```

And the DataTemplateSelector code:

```<code>public class SampleDataTemplateSelector : DataTemplateSelector
{
    public DataTemplate OrderDetailTemplate { get; set; }

    public DataTemplate SKUDetailTemplate { get; set; }

    public DataTemplate LocationDetailTemplate { get; set; }

    protected override DataTemplate SelectTemplateCore(object item)
    {
        return GetTemplate(item) ?? base.SelectTemplateCore(item);
    }

    protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
    {
        return GetTemplate(item) ?? base.SelectTemplateCore(item, container);
    }

    private DataTemplate GetTemplate(object item)
    {
        switch (item)
        {
            case Order order:
                return OrderDetailTemplate;
            case SKU sku:
                return SKUDetailTemplate;
            case Location location:
                return LocationDetailTemplate;
        }

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

Update

I have actually tried two different attempts to get the user control to work. Both resulted in only one tier being displayed.

Attempt #1 UserControl XAML:

```<code><UserControl
    x:Class="PickSheetManager.Controls.OrderTreeItemControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:winui="using:Microsoft.UI.Xaml.Controls"
    xmlns:model="using:PickSheetManager.Core.Models"
    xmlns:behaviors="using:PickSheetManager.Behaviors"
    xmlns:templateSelectors="using:PickSheetManager.TemplateSelectors"
    xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
    xmlns:controls1="using:PickSheetManager.Controls"
    xmlns:ic="using:Microsoft.Xaml.Interactions.Core"
    xmlns:i="using:Microsoft.Xaml.Interactivity"
    mc:Ignorable="d">

    <UserControl.Resources>
        <DataTemplate x:Name="OrderTemplate" x:DataType="model:Order">
            <StackPanel x:Name="stack" Orientation="Horizontal">
                <i:Interaction.Behaviors>
                    <ic:DataTriggerBehavior Binding ="{x:Bind NotEnoughInventory}" Value="True">
                        <ic:ChangePropertyAction TargetObject="{Binding ElementName=stack}" PropertyName="Background" Value="Red" />
                    </ic:DataTriggerBehavior>
                </i:Interaction.Behaviors>
                <CheckBox IsChecked="{x:Bind IsSelected, Mode=TwoWay}" Padding="5" MinWidth="0"/>
                <TextBlock Text="PoIDx: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="{x:Bind PoIDx}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="Delivery: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="{x:Bind DeliveryType}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="Delivery: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="{x:Bind DeliveryType}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="Type: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="{x:Bind OrderType}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="Total Quantity: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="{x:Bind TotalQuantity}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="Printed: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="{x:Bind IsPrinted}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="Notes: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBox Text="{x:Bind Notes, Mode=TwoWay}" Margin="{StaticResource XXSmallTopRightBottomMargin}" Width="150"/>
            </StackPanel>
        </DataTemplate>
        <DataTemplate x:Name="SKUTemplate" x:DataType="model:SKU">
            <StackPanel x:Name="stack2" Orientation="Horizontal">
                <i:Interaction.Behaviors>
                    <ic:DataTriggerBehavior Binding ="{x:Bind NotEnoughInventory}" Value="True">
                        <ic:ChangePropertyAction TargetObject="{Binding ElementName=stack2}" PropertyName="Background" Value="Yellow" />
                    </ic:DataTriggerBehavior>
                </i:Interaction.Behaviors>
                <CheckBox IsChecked="{x:Bind IsSelected, Mode=TwoWay}" Padding="5" MinWidth="0" />
                <TextBlock Text="SKU: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="{x:Bind SKUNum}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="Needed: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="{x:Bind NeedQuantity}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="Available: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="{x:Bind AvailableQuantity}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
            </StackPanel>
        </DataTemplate>
        <DataTemplate x:Name="LocationTemplate" x:DataType="model:Location">
            <StackPanel Orientation="Horizontal">
                <CheckBox IsChecked="{x:Bind IsSelected, Mode=TwoWay}" Padding="5" MinWidth="0" />
                <TextBlock Text="{x:Bind LocationName}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="Pick Type: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="{x:Bind PickType}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="Pick Quantity: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="{x:Bind PickQuantity}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="Available Quantity: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="{x:Bind AvailableQuantity}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBox Text="{x:Bind Notes, Mode=TwoWay}" Margin="{StaticResource XXSmallTopRightBottomMargin}" Width="150" />
            </StackPanel>
        </DataTemplate>
    </UserControl.Resources>

    <Grid>
        <ContentControl x:Name="MainContent"/>
    </Grid>
</UserControl>
</code>```

Attempt #1 .cs

```<code>    namespace PickSheetManager.Controls
{
    public sealed partial class OrderTreeItemControl : UserControl
    {
        public OrderTreeItemControl()
        {
            this.InitializeComponent();
        }

        public Order Data
        {
            get { return (OpenOrdersBase)GetValue(DataProperty); }
            set { SetValue(DataProperty, value); }
        }

        public static readonly DependencyProperty DataProperty =
            DependencyProperty.Register("Data", typeof(OpenOrdersBase), typeof(OrderTreeItemControl), new PropertyMetadata(null, new PropertyChangedCallback(Data_Changed)));

        private static void Data_Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (e.NewValue != null)
            {
                var instance = d as OrderTreeItemControl;
                if (e.NewValue is Location)
                {
                    instance.MainContent.ContentTemplate = instance.LocationTemplate;
                }
                else if (e.NewValue is SKU)
                {
                    instance.MainContent.ContentTemplate = instance.SKUTemplate;
                }
                else
                {
                    instance.MainContent.ContentTemplate = instance.OrderTemplate;
                }
            }
        }
    }
}
</code>```

Attempt #1 Model Classes

```<code>public class OpenOrdersBase
{
    public ObservableCollection<Order> Orders { get; } = new ObservableCollection<Order>();
}
public class Order : OpenOrdersBase
{
    public bool IsSelected { get; set; }
    public string OrderNumber { get; set; }
    public string PoIDx { get; set; }
   ...
    public ICollection<SKU> SKUs { get; set; }

}
public class SKU : OpenOrderBase
{
    public bool IsSelected { get; set; }
    public string SKUNum { get; set; }
    ...
    public ICollection<Location> Locations { get; set; }
}
public class Location : OpenOrdersBase
{
    public bool IsSelected { get; set; }
    ...
    public string Notes { get; set; }
}
</code>```

Attempt #1 Page XAML

```<code><DataTemplate x:Key="BaseTemplate" x:DataType="model:Order">
            <winui:TreeViewItem
                IsExpanded="False"
                ItemsSource="{x:Bind SKUs}">
                <controls1:TestControl Data="{Binding}"/>
             </winui:TreeViewItem>
         </DataTemplate>
...
<winui:TreeView
            x:Name="treeView"
            Grid.Row="0"
            SelectionMode="Single"
            Margin="10,10,10,10"
            ItemsSource="{x:Bind ViewModel.openOrders}"
            ItemTemplate="{StaticResource BaseTemplate}">
            <i:Interaction.Behaviors>
                <behaviors:TreeViewCollapseBehavior x:Name="collapseBehavior" />
                <ic:EventTriggerBehavior EventName="ItemInvoked">
                    <ic:InvokeCommandAction Command="{x:Bind ViewModel.ItemInvokedCommand}" />
                </ic:EventTriggerBehavior>
            </i:Interaction.Behaviors>
        </winui:TreeView>
</code>```

Attempt #2 The big difference was in the UserControl XAML and In the Models
UserControl XAML

```<code>    <UserControl
    x:Class="PickSheetManager.Controls.OrderTreeItemControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:winui="using:Microsoft.UI.Xaml.Controls"
    xmlns:model="using:PickSheetManager.Core.Models"
    xmlns:behaviors="using:PickSheetManager.Behaviors"
    xmlns:templateSelectors="using:PickSheetManager.TemplateSelectors"
    xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
    xmlns:controls1="using:PickSheetManager.Controls"
    xmlns:ic="using:Microsoft.Xaml.Interactions.Core"
    xmlns:i="using:Microsoft.Xaml.Interactivity"
    mc:Ignorable="d">

    <UserControl.Resources>

        <DataTemplate x:Name="OrderTemplate" x:DataType="model:Order">
            <winui:TreeViewItem
                AutomationProperties.Name="{x:Bind PoIDx}"
                ItemsSource="{x:Bind SKUs}"
                IsExpanded="True">
                <StackPanel x:Name="stack" Orientation="Horizontal">
                    <i:Interaction.Behaviors>
                        <ic:DataTriggerBehavior Binding ="{x:Bind NotEnoughInventory}" Value="True">
                            <ic:ChangePropertyAction TargetObject="{Binding ElementName=stack}" PropertyName="Background" Value="Red" />
                        </ic:DataTriggerBehavior>
                    </i:Interaction.Behaviors>
                    <CheckBox IsChecked="{x:Bind IsSelected, Mode=TwoWay}" Padding="5" MinWidth="0"/>
                    <TextBlock Text="PoIDx: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="{x:Bind PoIDx}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="Delivery: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="{x:Bind DeliveryType}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="Delivery: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="{x:Bind DeliveryType}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="Type: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="{x:Bind OrderType}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="Total Quantity: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="{x:Bind TotalQuantity}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="Printed: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="{x:Bind IsPrinted}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="Notes: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBox Text="{x:Bind Notes, Mode=TwoWay}" Margin="{StaticResource XXSmallTopRightBottomMargin}" Width="150"/>
                </StackPanel>
            </winui:TreeViewItem>

        </DataTemplate>
        <DataTemplate x:Name="SKUTemplate" x:DataType="model:SKU">
            <winui:TreeViewItem
                AutomationProperties.Name="{x:Bind SKUNum}"
                ItemsSource="{x:Bind Locations}"
                IsExpanded="True">
                <StackPanel x:Name="stack2" Orientation="Horizontal">
                    <i:Interaction.Behaviors>
                        <ic:DataTriggerBehavior Binding ="{x:Bind NotEnoughInventory}" Value="True">
                            <ic:ChangePropertyAction TargetObject="{Binding ElementName=stack2}" PropertyName="Background" Value="Yellow" />
                        </ic:DataTriggerBehavior>
                    </i:Interaction.Behaviors>
                    <CheckBox IsChecked="{x:Bind IsSelected, Mode=TwoWay}" Padding="5" MinWidth="0" />
                    <TextBlock Text="SKU: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="{x:Bind SKUNum}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="Needed: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="{x:Bind NeedQuantity}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="Available: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="{x:Bind AvailableQuantity}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                </StackPanel>
            </winui:TreeViewItem>
        </DataTemplate>
        <DataTemplate x:Name="LocationTemplate" x:DataType="model:Location">
            <winui:TreeViewItem
                AutomationProperties.Name="{x:Bind LocationName}"
                IsExpanded="True">
                <StackPanel Orientation="Horizontal">
                    <CheckBox IsChecked="{x:Bind IsSelected, Mode=TwoWay}" Padding="5" MinWidth="0" />
                    <TextBlock Text="{x:Bind LocationName}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="Pick Type: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="{x:Bind PickType}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="Pick Quantity: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="{x:Bind PickQuantity}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="Available Quantity: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="{x:Bind AvailableQuantity}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBox Text="{x:Bind Notes, Mode=TwoWay}" Margin="{StaticResource XXSmallTopRightBottomMargin}" Width="150" />
                </StackPanel>
            </winui:TreeViewItem>
        </DataTemplate>
    </UserControl.Resources>

    <Grid>
        <ContentControl x:Name="MainContent"/>
    </Grid>
</UserControl>
</code>```

In the code for the user control I simply updated OpenOrdersBase to Order as I removed the inheritance from all the models.

Fianlly the Page XAML changed in this manner

```<code><DataTemplate x:Key="BaseTemplate" x:DataType="model:Order">
    <controls1:TestControl Data="{Binding}"/>
</DataTemplate>
</code>```

答:
In fact, your attempt 1 is very close to success, and only requires some minor modifications.

This problem lies in the definition of the class:

Order, SKU, Location have a common base class OpenOperBase, which is good, but the base class should provide a common property, rather than a special Order collection.

Try this:

public class OpenOrdersBase
{
    public ObservableCollection<OpenOrdersBase> Children { get; set; } = new ObservableCollection<OpenOrdersBase>();
}
```

<p>In your <code>Order</code> and <code>SKU</code> class, there is a sub-collection attribute, extract them as a separate base class collection attribute, which will see the effect in the data binding later.</p>

<p>Now you can delete <code>Order.SKUs</code> and <code>SKU.Locations</code>.</p>

<p>When binding, the content of <code>TestControl</code> does not need to be changed (keep the wording in attempt#1), but the <code>TreeViewItem</code> template needs to change the <strong>DataType</strong></p>

<pre class="lang-xml prettyprint-override"><code><DataTemplate x:DataType="models:OpenOrdersBase" x:Key="BaseTemplate">
    <TreeViewItem ItemsSource="{x:Bind Children}">
        <controls:TestControl Data="{Binding}"/>
    </TreeViewItem>
</DataTemplate>
</code>```

Our general idea is as follows:

Since TreeViewItem only has effect directly as a child of TreeView.Children, the method of attempt #2 is not desirable.

The TreeView.ItemTemplate property affects all internal children, so when binding TreeViewItem.ItemsSource, it is best to bind a base class collection, rather than a specific type of collection (such as SKUs)

If you want to display different templates based on the data type, creating a UserControl and judging the type internally is a feasible way (you have already done it).

Thanks.

Body:
When using a treeview that is bound to a three tier hierarchical collection (Order - SKU - Location). I am using a DataTemplateSelector to choose the TreeViewItem template to use. I am getting an Invalid exception exactly the same as in this post when I scroll - the exception seems to occur faster if I scroll faster.

I have attempted both suggested solutions in that post (wrapping the treeview in a scroll viewer, and the custom user control). Wrapping the TreeView does not help, and I cannot get the custom user control solution to work correctly for me and I wonder if it is related to the fact I have a three tier collection instead of two tiers. The code for the custom UserControl is exactly the same as in the linked post except modified for my collection. When I try it it only binds one tier of the collection to the treeview. What I am looking for is a solution prevents the framework code from reusing the templates which appears to be what is causing the exception.

Here is my XAML and code for the TreeView that currently produces the exception:

<Page
x:Class="PickSheetManager.Views.PickSheetManagerPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:winui="using:Microsoft.UI.Xaml.Controls"
xmlns:model="using:PickSheetManager.Core.Models"
xmlns:behaviors="using:PickSheetManager.Behaviors"
xmlns:templateSelectors="using:PickSheetManager.TemplateSelectors"
xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
xmlns:controls1="using:PickSheetManager.Controls"
xmlns:ic="using:Microsoft.Xaml.Interactions.Core"
xmlns:i="using:Microsoft.Xaml.Interactivity"
Style="{StaticResource PageStyle}"
behaviors:NavigationViewHeaderBehavior.HeaderMode="Never"
mc:Ignorable="d">

<Page.Resources>
    <DataTemplate x:Key="OrderTemplate" x:DataType="model:Order">
        <winui:TreeViewItem
            AutomationProperties.Name="{x:Bind PoIDx}"
            ItemsSource="{x:Bind SKUs}" IsExpanded="True">
            <StackPanel x:Name="stack" Orientation="Horizontal">

                <ic:DataTriggerBehavior Binding ="{x:Bind NotEnoughInventory}" Value="True">
                    <ic:ChangePropertyAction TargetObject="{Binding ElementName=stack}" PropertyName="Background" Value="Red" />
                </ic:DataTriggerBehavior>

            <CheckBox IsChecked="{x:Bind IsSelected, Mode=TwoWay}" Padding="5" MinWidth="0"/>
            <TextBlock Text="PoIDx: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
            <TextBlock Text="{x:Bind PoIDx}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
            <TextBlock Text="Delivery: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
            <TextBlock Text="{x:Bind DeliveryType}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
            <TextBlock Text="Delivery: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
            <TextBlock Text="{x:Bind DeliveryType}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
            <TextBlock Text="Type: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
            <TextBlock Text="{x:Bind OrderType}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
            <TextBlock Text="Total Quantity: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
            <TextBlock Text="{x:Bind TotalQuantity}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
            <TextBlock Text="Printed: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
            <TextBlock Text="{x:Bind IsPrinted}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
            <TextBlock Text="Notes: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
            <TextBox Text="{x:Bind Notes, Mode=TwoWay}" Margin="{StaticResource XXSmallTopRightBottomMargin}" Width="150"/>
        </StackPanel>
        </winui:TreeViewItem>
    </DataTemplate>

    <DataTemplate x:Key="SKUTemplate" x:DataType="model:SKU">
        <winui:TreeViewItem
            AutomationProperties.Name="{x:Bind SKUNum}"
            ItemsSource="{x:Bind Locations}" IsExpanded="True">
            <StackPanel x:Name="stack2" Orientation="Horizontal">

                    <ic:DataTriggerBehavior Binding ="{x:Bind NotEnoughInventory}" Value="True">
                        <ic:ChangePropertyAction TargetObject="{Binding ElementName=stack2}" PropertyName="Background" Value="Yellow" />
                    </ic:DataTriggerBehavior>

                <CheckBox IsChecked="{x:Bind IsSelected, Mode=TwoWay}" Padding="5" MinWidth="0" />
                <TextBlock Text="SKU: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="{x:Bind SKUNum}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="Needed: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="{x:Bind NeedQuantity}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="Available: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="{x:Bind AvailableQuantity}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
            </StackPanel>
        </winui:TreeViewItem>
    </DataTemplate>

    <DataTemplate x:Key="LocationTemplate" x:DataType="model:Location">
        <winui:TreeViewItem
            AutomationProperties.Name="{x:Bind LocationName}"
            IsExpanded="True">
            <StackPanel Orientation="Horizontal">
                <CheckBox IsChecked="{x:Bind IsSelected, Mode=TwoWay}" Padding="5" MinWidth="0" />
                <TextBlock Text="{x:Bind LocationName}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="Pick Type: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="{x:Bind PickType}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="Pick Quantity: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="{x:Bind PickQuantity}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="Available Quantity: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="{x:Bind AvailableQuantity}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBox Text="{x:Bind Notes, Mode=TwoWay}" Margin="{StaticResource XXSmallTopRightBottomMargin}" Width="150" />
            </StackPanel>
        </winui:TreeViewItem>
    </DataTemplate>

    <templateSelectors:SampleDataTemplateSelector x:Key="TreeViewTemplateSelector"
        OrderDetailTemplate="{StaticResource OrderTemplate}"
        SKUDetailTemplate="{StaticResource SKUTemplate}"
        LocationDetailTemplate="{StaticResource LocationTemplate}" />
</Page.Resources>

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition x:Name="treeViewColumn" Width="6*" />
        <ColumnDefinition x:Name="detailViewColumn" Width="4*" />
    </Grid.ColumnDefinitions>
    <Grid Grid.Column="0">
        <Grid.RowDefinitions>
            <RowDefinition x:Name="treeViewRow" Height="8*" />
            <RowDefinition x:Name="controlRow" Height="2*" />
        </Grid.RowDefinitions>
        <ScrollViewer x:Name="WrapViewer" Grid.Row="0" Grid.Column="0" Padding="{StaticResource DetailPageMargin}">
        </ScrollViewer>
        <winui:TreeView
            x:Name="treeView"
            Grid.Row="0"
            SelectionMode="Single"
            ItemsSource="{x:Bind ViewModel.openOrders}"
            ItemTemplateSelector="{StaticResource TreeViewTemplateSelector}">

                <behaviors:TreeViewCollapseBehavior x:Name="collapseBehavior" />
                <ic:EventTriggerBehavior EventName="ItemInvoked">
                    <ic:InvokeCommandAction Command="{x:Bind ViewModel.ItemInvokedCommand}" />
                </ic:EventTriggerBehavior>

        </winui:TreeView>
    </Grid>
    <Grid Grid.Column="1">
        <Grid.RowDefinitions>
            <RowDefinition x:Name="detailViewRow" Height="4*" />
            <RowDefinition x:Name="iarRow" Height="4*" />
            <RowDefinition x:Name="controlRow2" Height="2*" />
        </Grid.RowDefinitions>
    </Grid>
</Grid>

The collection being bound

 public ObservableCollection<Order> openOrders { get; } = new ObservableCollection<Order>();

 public async Task LoadDataAsync()
 {
     var data2 = await OrderDataLoader.GetTreeViewDataAsync();
     foreach (var item in data2)
     {
         openOrders.Add(item);
     }
 }

And the DataTemplateSelector code:

public class SampleDataTemplateSelector : DataTemplateSelector
{
    public DataTemplate OrderDetailTemplate { get; set; }

    public DataTemplate SKUDetailTemplate { get; set; }

    public DataTemplate LocationDetailTemplate { get; set; }

    protected override DataTemplate SelectTemplateCore(object item)
    {
        return GetTemplate(item) ?? base.SelectTemplateCore(item);
    }

    protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
    {
        return GetTemplate(item) ?? base.SelectTemplateCore(item, container);
    }

    private DataTemplate GetTemplate(object item)
    {
        switch (item)
        {
            case Order order:
                return OrderDetailTemplate;
            case SKU sku:
                return SKUDetailTemplate;
            case Location location:
                return LocationDetailTemplate;
        }

        return null;
    }
}

Update

I have actually tried two different attempts to get the user control to work. Both resulted in only one tier being displayed.

Attempt #1 UserControl XAML:

<UserControl
    x:Class="PickSheetManager.Controls.OrderTreeItemControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:winui="using:Microsoft.UI.Xaml.Controls"
    xmlns:model="using:PickSheetManager.Core.Models"
    xmlns:behaviors="using:PickSheetManager.Behaviors"
    xmlns:templateSelectors="using:PickSheetManager.TemplateSelectors"
    xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
    xmlns:controls1="using:PickSheetManager.Controls"
    xmlns:ic="using:Microsoft.Xaml.Interactions.Core"
    xmlns:i="using:Microsoft.Xaml.Interactivity"
    mc:Ignorable="d">

    <UserControl.Resources>
        <DataTemplate x:Name="OrderTemplate" x:DataType="model:Order">
            <StackPanel x:Name="stack" Orientation="Horizontal">

                    <ic:DataTriggerBehavior Binding ="{x:Bind NotEnoughInventory}" Value="True">
                        <ic:ChangePropertyAction TargetObject="{Binding ElementName=stack}" PropertyName="Background" Value="Red" />
                    </ic:DataTriggerBehavior>

                <CheckBox IsChecked="{x:Bind IsSelected, Mode=TwoWay}" Padding="5" MinWidth="0"/>
                <TextBlock Text="PoIDx: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="{x:Bind PoIDx}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="Delivery: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="{x:Bind DeliveryType}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="Delivery: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="{x:Bind DeliveryType}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="Type: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="{x:Bind OrderType}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="Total Quantity: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="{x:Bind TotalQuantity}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="Printed: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="{x:Bind IsPrinted}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="Notes: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBox Text="{x:Bind Notes, Mode=TwoWay}" Margin="{StaticResource XXSmallTopRightBottomMargin}" Width="150"/>
            </StackPanel>
        </DataTemplate>
        <DataTemplate x:Name="SKUTemplate" x:DataType="model:SKU">
            <StackPanel x:Name="stack2" Orientation="Horizontal">

                    <ic:DataTriggerBehavior Binding ="{x:Bind NotEnoughInventory}" Value="True">
                        <ic:ChangePropertyAction TargetObject="{Binding ElementName=stack2}" PropertyName="Background" Value="Yellow" />
                    </ic:DataTriggerBehavior>

                <CheckBox IsChecked="{x:Bind IsSelected, Mode=TwoWay}" Padding="5" MinWidth="0" />
                <TextBlock Text="SKU: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="{x:Bind SKUNum}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="Needed: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="{x:Bind NeedQuantity}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="Available: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="{x:Bind AvailableQuantity}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
            </StackPanel>
        </DataTemplate>
        <DataTemplate x:Name="LocationTemplate" x:DataType="model:Location">
            <StackPanel Orientation="Horizontal">
                <CheckBox IsChecked="{x:Bind IsSelected, Mode=TwoWay}" Padding="5" MinWidth="0" />
                <TextBlock Text="{x:Bind LocationName}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="Pick Type: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="{x:Bind PickType}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="Pick Quantity: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="{x:Bind PickQuantity}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="Available Quantity: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBlock Text="{x:Bind AvailableQuantity}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                <TextBox Text="{x:Bind Notes, Mode=TwoWay}" Margin="{StaticResource XXSmallTopRightBottomMargin}" Width="150" />
            </StackPanel>
        </DataTemplate>
    </UserControl.Resources>

    <Grid>
        <ContentControl x:Name="MainContent"/>
    </Grid>
</UserControl>

Attempt #1 .cs

    namespace PickSheetManager.Controls
{
    public sealed partial class OrderTreeItemControl : UserControl
    {
        public OrderTreeItemControl()
        {
            this.InitializeComponent();
        }

        public Order Data
        {
            get { return (OpenOrdersBase)GetValue(DataProperty); }
            set { SetValue(DataProperty, value); }
        }

        public static readonly DependencyProperty DataProperty =
            DependencyProperty.Register("Data", typeof(OpenOrdersBase), typeof(OrderTreeItemControl), new PropertyMetadata(null, new PropertyChangedCallback(Data_Changed)));

        private static void Data_Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (e.NewValue != null)
            {
                var instance = d as OrderTreeItemControl;
                if (e.NewValue is Location)
                {
                    instance.MainContent.ContentTemplate = instance.LocationTemplate;
                }
                else if (e.NewValue is SKU)
                {
                    instance.MainContent.ContentTemplate = instance.SKUTemplate;
                }
                else
                {
                    instance.MainContent.ContentTemplate = instance.OrderTemplate;
                }
            }
        }
    }
}

Attempt #1 Model Classes

public class OpenOrdersBase
{
    public ObservableCollection<Order> Orders { get; } = new ObservableCollection<Order>();
}
public class Order : OpenOrdersBase
{
    public bool IsSelected { get; set; }
    public string OrderNumber { get; set; }
    public string PoIDx { get; set; }
   ...
    public ICollection<SKU> SKUs { get; set; }

}
public class SKU : OpenOrderBase
{
    public bool IsSelected { get; set; }
    public string SKUNum { get; set; }
    ...
    public ICollection<Location> Locations { get; set; }
}
public class Location : OpenOrdersBase
{
    public bool IsSelected { get; set; }
    ...
    public string Notes { get; set; }
}

Attempt #1 Page XAML

<DataTemplate x:Key="BaseTemplate" x:DataType="model:Order">
            <winui:TreeViewItem
                IsExpanded="False"
                ItemsSource="{x:Bind SKUs}">
                <controls1:TestControl Data="{Binding}"/>
             </winui:TreeViewItem>
         </DataTemplate>
...
<winui:TreeView
            x:Name="treeView"
            Grid.Row="0"
            SelectionMode="Single"
            Margin="10,10,10,10"
            ItemsSource="{x:Bind ViewModel.openOrders}"
            ItemTemplate="{StaticResource BaseTemplate}">

                <behaviors:TreeViewCollapseBehavior x:Name="collapseBehavior" />
                <ic:EventTriggerBehavior EventName="ItemInvoked">
                    <ic:InvokeCommandAction Command="{x:Bind ViewModel.ItemInvokedCommand}" />
                </ic:EventTriggerBehavior>

        </winui:TreeView>

Attempt #2 The big difference was in the UserControl XAML and In the Models
UserControl XAML

    <UserControl
    x:Class="PickSheetManager.Controls.OrderTreeItemControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:winui="using:Microsoft.UI.Xaml.Controls"
    xmlns:model="using:PickSheetManager.Core.Models"
    xmlns:behaviors="using:PickSheetManager.Behaviors"
    xmlns:templateSelectors="using:PickSheetManager.TemplateSelectors"
    xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
    xmlns:controls1="using:PickSheetManager.Controls"
    xmlns:ic="using:Microsoft.Xaml.Interactions.Core"
    xmlns:i="using:Microsoft.Xaml.Interactivity"
    mc:Ignorable="d">

    <UserControl.Resources>

        <DataTemplate x:Name="OrderTemplate" x:DataType="model:Order">
            <winui:TreeViewItem
                AutomationProperties.Name="{x:Bind PoIDx}"
                ItemsSource="{x:Bind SKUs}"
                IsExpanded="True">
                <StackPanel x:Name="stack" Orientation="Horizontal">

                        <ic:DataTriggerBehavior Binding ="{x:Bind NotEnoughInventory}" Value="True">
                            <ic:ChangePropertyAction TargetObject="{Binding ElementName=stack}" PropertyName="Background" Value="Red" />
                        </ic:DataTriggerBehavior>

                    <CheckBox IsChecked="{x:Bind IsSelected, Mode=TwoWay}" Padding="5" MinWidth="0"/>
                    <TextBlock Text="PoIDx: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="{x:Bind PoIDx}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="Delivery: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="{x:Bind DeliveryType}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="Delivery: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="{x:Bind DeliveryType}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="Type: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="{x:Bind OrderType}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="Total Quantity: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="{x:Bind TotalQuantity}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="Printed: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="{x:Bind IsPrinted}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="Notes: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBox Text="{x:Bind Notes, Mode=TwoWay}" Margin="{StaticResource XXSmallTopRightBottomMargin}" Width="150"/>
                </StackPanel>
            </winui:TreeViewItem>

        </DataTemplate>
        <DataTemplate x:Name="SKUTemplate" x:DataType="model:SKU">
            <winui:TreeViewItem
                AutomationProperties.Name="{x:Bind SKUNum}"
                ItemsSource="{x:Bind Locations}"
                IsExpanded="True">
                <StackPanel x:Name="stack2" Orientation="Horizontal">

                        <ic:DataTriggerBehavior Binding ="{x:Bind NotEnoughInventory}" Value="True">
                            <ic:ChangePropertyAction TargetObject="{Binding ElementName=stack2}" PropertyName="Background" Value="Yellow" />
                        </ic:DataTriggerBehavior>

                    <CheckBox IsChecked="{x:Bind IsSelected, Mode=TwoWay}" Padding="5" MinWidth="0" />
                    <TextBlock Text="SKU: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="{x:Bind SKUNum}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="Needed: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="{x:Bind NeedQuantity}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="Available: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="{x:Bind AvailableQuantity}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                </StackPanel>
            </winui:TreeViewItem>
        </DataTemplate>
        <DataTemplate x:Name="LocationTemplate" x:DataType="model:Location">
            <winui:TreeViewItem
                AutomationProperties.Name="{x:Bind LocationName}"
                IsExpanded="True">
                <StackPanel Orientation="Horizontal">
                    <CheckBox IsChecked="{x:Bind IsSelected, Mode=TwoWay}" Padding="5" MinWidth="0" />
                    <TextBlock Text="{x:Bind LocationName}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="Pick Type: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="{x:Bind PickType}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="Pick Quantity: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="{x:Bind PickQuantity}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="Available Quantity: " Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBlock Text="{x:Bind AvailableQuantity}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                    <TextBox Text="{x:Bind Notes, Mode=TwoWay}" Margin="{StaticResource XXSmallTopRightBottomMargin}" Width="150" />
                </StackPanel>
            </winui:TreeViewItem>
        </DataTemplate>
    </UserControl.Resources>

    <Grid>
        <ContentControl x:Name="MainContent"/>
    </Grid>
</UserControl>

In the code for the user control I simply updated OpenOrdersBase to Order as I removed the inheritance from all the models.

Fianlly the Page XAML changed in this manner

<DataTemplate x:Key="BaseTemplate" x:DataType="model:Order">
    <controls1:TestControl Data="{Binding}"/>
</DataTemplate>

Body:
In fact, your attempt 1 is very close to success, and only requires some minor modifications.

This problem lies in the definition of the class:

Order, SKU, Location have a common base class OpenOperBase, which is good, but the base class should provide a common property, rather than a special Order collection.

Try this:

public class OpenOrdersBase
{
    public ObservableCollection<OpenOrdersBase> Children { get; set; } = new ObservableCollection<OpenOrdersBase>();
}

In your Order and SKU class, there is a sub-collection attribute, extract them as a separate base class collection attribute, which will see the effect in the data binding later.

Now you can delete Order.SKUs and SKU.Locations.

When binding, the content of TestControl does not need to be changed (keep the wording in attempt#1), but the TreeViewItem template needs to change the DataType

<DataTemplate x:DataType="models:OpenOrdersBase" x:Key="BaseTemplate">
    <TreeViewItem ItemsSource="{x:Bind Children}">
        <controls:TestControl Data="{Binding}"/>
    </TreeViewItem>
</DataTemplate>

Our general idea is as follows:

Since TreeViewItem only has effect directly as a child of TreeView.Children, the method of attempt #2 is not desirable.

The TreeView.ItemTemplate property affects all internal children, so when binding TreeViewItem.ItemsSource, it is best to bind a base class collection, rather than a specific type of collection (such as SKUs)

If you want to display different templates based on the data type, creating a UserControl and judging the type internally is a feasible way (you have already done it).

Thanks.


问:
Order By before Group By using Eloquent (Laravel)
I have a "messages" table with the following columns

```<code>CREATE TABLE `messages` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `fromId` int(11) NOT NULL,
  `toId` int(11) NOT NULL,
  `message` text NOT NULL,
  `status` int(11) NOT NULL,
  `device` varchar(100) NOT NULL,
  `createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=57 DEFAULT CHARSET=latin1;
</code>```

I'm trying to get all messages where 'toId' = $id and grouping by fromId. The problem is that the "message" shown on the results is the first ones, not the latest ones. I tried ordering by createdAt but it's not working.

How can I order by "createdAt" prior to querying and grouping the results? I want to do this in the laravel way using Eloquent.

My query:

```<code>$chats = Message::with('sender','recipient')
        ->where('toId',$id)
        ->orderBy('createdAt')
        ->groupBy('fromId')
        ->paginate(10)
</code>```

答:
```<code> $data = MCCAddMilkEntry::where('coming_from','=','society')
        ->whereRaw('id = (select max(`id`) from mcc_add_milk_entry)')->get();
</code>```

Body:
I have a "messages" table with the following columns

CREATE TABLE `messages` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `fromId` int(11) NOT NULL,
  `toId` int(11) NOT NULL,
  `message` text NOT NULL,
  `status` int(11) NOT NULL,
  `device` varchar(100) NOT NULL,
  `createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=57 DEFAULT CHARSET=latin1;

I'm trying to get all messages where 'toId' = $id and grouping by fromId. The problem is that the "message" shown on the results is the first ones, not the latest ones. I tried ordering by createdAt but it's not working.

How can I order by "createdAt" prior to querying and grouping the results? I want to do this in the laravel way using Eloquent.

My query:

$chats = Message::with('sender','recipient')
        ->where('toId',$id)
        ->orderBy('createdAt')
        ->groupBy('fromId')
        ->paginate(10)


问:
How can a mersenne_twister_engine be serialized using Boost?
I have a class that implements std::mt19937 and I would like to be able to save and load the state of the random number generator for consistency. I'm aware that the << and >> operators can be used to save/load the engine's state and that I can separate the save and load functions when I archive the file if necessary. My guess at how to do this would be to use the << and >> operators to store the state into/extract the state from an object that can be serialized. My questions are

What object can be used to store the state of the mersenne_twister_engine that can also be serialized using Boost?

Is my approach safe and generally considered to be good practice?

Is there an approach to this that is generally considered to be better?

答:
From this output/input operator reference regarding the output operator:

Serializes the internal state of the pseudo-random number engine e as a sequence of decimal numbers separated by one or more spaces, and inserts it to the stream ost.

The stream could be any kind of output stream, for example an output string stream. You can then use the string that the string-streams created and pass it on to whatever serialization framework you need.

Or if the serialization framework support direct output/input stream operations, you can use it directly with the engine operators.


问:
Behind the scene- If I use Aync but doesn't use await in it, would it be identical with normal function?
due to everyone's help, I got the logic behind async, promise, then, await.

I have one curisosity on top of its basic nature, which is what if
I declare async function but doesn't use await in it.

technically every argument within async function is invisibly capsulated by '.then()'
but how it works would be exactly same as synchronous function execution.
For example,

```<code>async function trackUserHandler() {

  var positiondata= await getPosition();
  var timerdata = await setTimer(2000)

  console.log(positiondata, timerdata);

setTimer(1000).then(() => {
    console.log('Timer done!');
  });
  console.log('one');

}
</code>```

The console below doesn't run till the first two await function is done due to await(s) sitting before this.

```<code> console.log(positiondata, timerdata);
</code>```

What if I don't put any await(s) in the async like below?

```<code>async function trackUserHandler() {

  var positiondata=  getPosition();
  var timerdata =  setTimer(2000)

  console.log(positiondata, timerdata);

setTimer(1000).then(() => {
    console.log('Timer done!');
  });
  console.log('one');

}
</code>```

I test-run this code and behaves seemigly same as regular function without 'async'.
Of course behind the scene, everything in the function is encapsulated into 'then()' though.

Am I understanding right?

Thank you in advance.

答:
Behind the scene- If I use Aync but doesn't use await in it, would it be identical with normal function?

Yes, you are right. An async function without an await expression will run synchronously and would be identical with normal function, but the only difference is that async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise.

For example, the following:

```<code>async function foo() {
   return 1
}
</code>```

...is equivalent to:

```<code>function foo() {
   return Promise.resolve(1)
}
</code>```

If there is an await expression inside the function body, however, the async function will always complete asynchronously.

For example:

```<code>async function foo() {
   await 1
}
</code>```

...is equivalent to:

```<code>function foo() {
   return Promise.resolve(1).then(() => undefined)
}
</code>```

Code after each await expression can be thought of as existing in a .then callback.

Body:
due to everyone's help, I got the logic behind async, promise, then, await.

I have one curisosity on top of its basic nature, which is what if
I declare async function but doesn't use await in it.

technically every argument within async function is invisibly capsulated by '.then()'
but how it works would be exactly same as synchronous function execution.
For example,

async function trackUserHandler() {

  var positiondata= await getPosition();
  var timerdata = await setTimer(2000)

  console.log(positiondata, timerdata);

setTimer(1000).then(() => {
    console.log('Timer done!');
  });
  console.log('one');

}

The console below doesn't run till the first two await function is done due to await(s) sitting before this.

 console.log(positiondata, timerdata);

What if I don't put any await(s) in the async like below?

async function trackUserHandler() {

  var positiondata=  getPosition();
  var timerdata =  setTimer(2000)

  console.log(positiondata, timerdata);

setTimer(1000).then(() => {
    console.log('Timer done!');
  });
  console.log('one');

}

I test-run this code and behaves seemigly same as regular function without 'async'.
Of course behind the scene, everything in the function is encapsulated into 'then()' though.

Am I understanding right?

Thank you in advance.

Body:
Behind the scene- If I use Aync but doesn't use await in it, would it be identical with normal function?

Yes, you are right. An async function without an await expression will run synchronously and would be identical with normal function, but the only difference is that async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise.

For example, the following:

async function foo() {
   return 1
}

...is equivalent to:

function foo() {
   return Promise.resolve(1)
}

If there is an await expression inside the function body, however, the async function will always complete asynchronously.

For example:

async function foo() {
   await 1
}

...is equivalent to:

function foo() {
   return Promise.resolve(1).then(() => undefined)
}

Code after each await expression can be thought of as existing in a .then callback.


问:
Append hidden ID to dynamically created DIV
I'm using plain JavaScript and have created a number of dynamically generated DIVs for which I'm trying to append a unique ID to each with the idea of being able to update the ID of any selected DIV separately depending on an event being triggered. Is there a way to add a hidden (not visible on the page) editable ID or value pair to each DIV on generation?</p>

答: I am suggesting to use a for loop to generate the divs, and the var = document.createElement("DIV"), then var.setAttribute("id", i) that will give unique ids.All in for loops.It should help.


问:
Call a function after previous function is complete reactjs
I want to call function this.onLoggin() after this.props.verifyCode(params); already done, how can i do it.
here is myfunction:

```<code>onSubmit = (e) => {
        e.preventDefault();
        let params = {
            email: this.props.email,
            codeVerify: this.state.code
        }
        this.props.verifyCode(params);
        this.onLoggin();

    }

onLoggin = () =>{
        if(this.props.isVerify === true){
            const body = {
                username: this.props.user.username,
                password: this.props.user.password
            }
            this.props.loggin(body);
        }
    }
</code>```

verifyCode come from redux:

```<code>const AUTHEN_URL = 'http://localhost:8080/client/user-info-client/regist';

const verifyCode = (params) => dispatch => {
    axios.post(AUTHEN_URL, null, {params})
        .then(res => {
            dispatch({
            type: VERIFY_CODE,
            payload: res.data.data,
        })});
}

export default verifyCode;
</code>```

here is my reducer:

```<code>const initialState = {
        isVerify: false
};

const verifyCode = (state = initialState, action) => {
    switch (action.type){
        case VERIFY_CODE:
            return {
                isVerify: true
            }
        default:
            return state;

    }
}

export default verifyCode;
</code>```

答:
Your verifyCode is a redux action. You need to add a reducer to make use of the information received as a response. Also, add the reducer while configuring store.

```<code>export const verification = (state = { isVerify : false, loginInfo : null}, action) => {
  switch (action.type) {
    case ActionTypes.VERIFY_CODE:
      return {...state, isVerify : true, loginInfo: action.payload};

    default:
      return state;
  }
};
</code>```

Then, proceed to matchStateToProps and use

```<code>if(this.props.verification.isVerify === true)
</code>```

to check if the user has successfully verified. You can also add further conditional rendering using this.props.verification.loginInfo

Body:
I want to call function this.onLoggin() after this.props.verifyCode(params); already done, how can i do it.
here is myfunction:

onSubmit = (e) => {
        e.preventDefault();
        let params = {
            email: this.props.email,
            codeVerify: this.state.code
        }
        this.props.verifyCode(params);
        this.onLoggin();

    }

onLoggin = () =>{
        if(this.props.isVerify === true){
            const body = {
                username: this.props.user.username,
                password: this.props.user.password
            }
            this.props.loggin(body);
        }
    }

verifyCode come from redux:

const AUTHEN_URL = 'http://localhost:8080/client/user-info-client/regist';

const verifyCode = (params) => dispatch => {
    axios.post(AUTHEN_URL, null, {params})
        .then(res => {
            dispatch({
            type: VERIFY_CODE,
            payload: res.data.data,
        })});
}

export default verifyCode;

here is my reducer:

const initialState = {
        isVerify: false
};

const verifyCode = (state = initialState, action) => {
    switch (action.type){
        case VERIFY_CODE:
            return {
                isVerify: true
            }
        default:
            return state;

    }
}

export default verifyCode;

Body:
Your verifyCode is a redux action. You need to add a reducer to make use of the information received as a response. Also, add the reducer while configuring store.

export const verification = (state = { isVerify : false, loginInfo : null}, action) => {
  switch (action.type) {
    case ActionTypes.VERIFY_CODE:
      return {...state, isVerify : true, loginInfo: action.payload};

    default:
      return state;
  }
};

Then, proceed to matchStateToProps and use

if(this.props.verification.isVerify === true)

to check if the user has successfully verified. You can also add further conditional rendering using this.props.verification.loginInfo


问:
Row does not contain data for all columns
Im trying to import a text file containing:

http://pastebin.com/qhzrq3M7

Into my database using the command

```<code>Load data local infile 'C:/Users/Gary/Desktop/XML/jobs.txt'
INTO Table jobs
fields terminated by '\t';
</code>```

But I keep getting the error Row 1-13 doesn't contain data for all columns

答:
Make sure there are no "\"s at the end of any field. In the csv viewed as text this would look like "\," which is obviously a no-no, since that comma will be ignored so you won't have enough columns.

(This primarily applies when you don't have field encasings like quotes around each field.)

Body:
Im trying to import a text file containing:

http://pastebin.com/qhzrq3M7

Into my database using the command

Load data local infile 'C:/Users/Gary/Desktop/XML/jobs.txt'
INTO Table jobs
fields terminated by '\t';

But I keep getting the error Row 1-13 doesn't contain data for all columns


问:
Finding two non-subsequent elements in array which sum is maximal - interview question
The question is similar to here, besides:

We are looking for the maximum.

The answer can contain the first or last element of the array (but not both - because we consider them as adjacent).

My attempt:

I think of using the same idea of RomCoo in the link above, but adjust it to this problem:

Find the largest number.

Find the second largest that is not a neighbour of the first. Then build the sum.

Calculate the sum of both neighbours of the first number. Check if its larger then the first sum.
If not: take the first sum, otherwise take the second one.

I believe that the pairs on steps (2) and (3) are the only ones who can make the largest sum, but I can't formally prove it.

If this correct how can you formally prove it?

And if not, how do you solve it?

答: Assume we have two numbers A and B that make up a larger sum. Either A or B (or both) must not be directly adjacent to the largest number, because otherwise they fall into (3). Lets take this to be A, without loss of generality. Since A is not adjacent to our largest number, then B could be safely replaced by our largest number if its not already, resulting in a greater overall sum. Therefore, to be maximal, B must equal our largest number. By the same logic, if there existed a larger value than A not adjacent to our largest number, then this sum would not be maximal either, so A must be the second largest number. This means A and B would fall into (2). So, (2) and (3) are our only valid solutions.


问:
Passing the same chain of parameters multiple times with currying
Given this expression:

```<code>// val fn1 : a:'a -> b:'b -> c:'c -> d:'d -> e:'e -> f:'f -> g:'g -> unit
// val fn2 : a:'a -> b:'b -> c:'c -> d:'d -> e:'e -> f:'f -> g:'g -> unit

type T =
  | A
  | B

// val t : T
// val a : 'a
// val b : 'b
// val c : 'c
// val d : 'd
// val e : 'e
// val f : 'f
// val g : 'g

match t with
| A -> fn1 a b c d e f g
| B -> fn2 a b c d e f g
</code>```

Is there a way to not repeat the same chain of parameters while calling a function that supports currying? so you could write some weird stuff like this

```<code>(a, b, c, d, e, f, g)
|||||||> (match t with A -> fn1 | B -> fn2)
</code>```

Would this be a case for an anonymous record? What are the common practices to achieve this?

答:
Just apply, rather than pipes?

```<code>(match t with
| A -> curried1
| B -> curried2
) 1 2 3 4
</code>```

FSharp closures are implemented as FSharpFunc<T, TResult>, which have an invoke method which let you call the method without multiple partial applications.

I wouldn't recommend going that way, but in extreme cases you can use reflection to invoke a function with an array of parameters.

```<code>let funInvoke fn args =
        let fnType = fn.GetType()
        if not (FSharpType.IsFunction fnType) then
            failwith "Not a function"

        let invoke = Array.head (fnType.GetMethods())
        invoke.Invoke(fn, args)
</code>```

and then

```<code>funInvoke curried1 [|1; 2; 3 ; 4 |]
</code>```

Body:
Given this expression:

// val fn1 : a:'a -> b:'b -> c:'c -> d:'d -> e:'e -> f:'f -> g:'g -> unit
// val fn2 : a:'a -> b:'b -> c:'c -> d:'d -> e:'e -> f:'f -> g:'g -> unit

type T =
  | A
  | B

// val t : T
// val a : 'a
// val b : 'b
// val c : 'c
// val d : 'd
// val e : 'e
// val f : 'f
// val g : 'g

match t with
| A -> fn1 a b c d e f g
| B -> fn2 a b c d e f g

Is there a way to not repeat the same chain of parameters while calling a function that supports currying? so you could write some weird stuff like this

(a, b, c, d, e, f, g)
|||||||> (match t with A -> fn1 | B -> fn2)

Would this be a case for an anonymous record? What are the common practices to achieve this?

Body:
Just apply, rather than pipes?

(match t with
| A -> curried1
| B -> curried2
) 1 2 3 4

FSharp closures are implemented as FSharpFunc<T, TResult>, which have an invoke method which let you call the method without multiple partial applications.

I wouldn't recommend going that way, but in extreme cases you can use reflection to invoke a function with an array of parameters.

let funInvoke fn args =
        let fnType = fn.GetType()
        if not (FSharpType.IsFunction fnType) then
            failwith "Not a function"

        let invoke = Array.head (fnType.GetMethods())
        invoke.Invoke(fn, args)

and then

funInvoke curried1 [|1; 2; 3 ; 4 |]


问:
Background repeat only on one side of the site layout, content centered?
How can I repeat endlessly a background color/image only on one side of my site layout and keep the content centered?

The best method seems to be with tables as it will work even in IE6, however is there a method to do this without tables and javascript and be working in at least IE7+?

The method with divs/display:table does not work in IE at all,

```<code><style type="text/css">

*{
margin:0;
padding:0;
}

/* table method */

.table-container{
margin-top:20px;
border:0;
border-collapse:collapse;
width:100%;
height:100px;
}

.table-container .left{
background:transparent;
}

.table-container .center{
width:960px;
background:#ddd;
vertical-align:top;
}

.table-container .center div{
margin:0 auto;
width:960px;
}

.table-container .right{
width:auto;
background:#ccc;
}

/* div method */

.div-container{
display:table;
margin-top:20px;
border:0;
width:100%;
height:100px;
}

.div-container .left{
display:table-cell;
background:transparent;
}

.div-container .center{
display:table-cell;
width:960px;
margin:0 auto;
background:#ddd;
vertical-align:top;
}

.div-container .right{
display:table-cell;
width:auto;
background:#ccc;
}

</style>

<table class="table-container">
<tr>
<td class="left"> </td>
<td class="center"><div>Table method : This space must be centered</div></td>
<td class="right"> </td>
</tr>
</table>

<div class="div-container">
<div class="left"> </div>
<div class="center">Div method : This space must be centered</div>
<div class="right"> </div>
</div>
</code>```

答:
You can achieve cool effects like half screen background colours by using position absolute. And there are easier ways to center text than using the display: table layout - which I have also shown in my CSS.

Here is a working examnple on JSFiddle and I have done my best to explain the CSS in comments below.

Here is the code:

 CSS

```<code>.content {
    margin: auto;         //use these to center the content
    position: relative:   //position relative, so the absolute div is positioned relative to this div
    text-align: center;   //use these to center the content
    width: 60%;
}

.content p {
    position: relative;   //position relative so we can set a z-index
    z-index: 1;           //z-index is higher than that of the background so it appears above
}

.background {
    background-color: #777;
    height: 100%;
    left:0;               //we want the left of the div to be 0px from the left of its container div
    position: absolute;   //position absolute, so we can put it anywhere we want
    top: 0;               //we want the top of the div to be 0px from the top of the container div
    width: 50%;
    z-index: 0;           //we want the z-index to be lower than the text
}
</code>```

HTML

```<code><div class="content">
    <p>...text...</p>
    <div class="background"></div>
</div>
</code>```

Enjoy

Body:
How can I repeat endlessly a background color/image only on one side of my site layout and keep the content centered?

The best method seems to be with tables as it will work even in IE6, however is there a method to do this without tables and javascript and be working in at least IE7+?

The method with divs/display:table does not work in IE at all,

Table method : This space must be centered

Div method : This space must be centered

Body:
You can achieve cool effects like half screen background colours by using position absolute. And there are easier ways to center text than using the display: table layout - which I have also shown in my CSS.

Here is a working examnple on JSFiddle and I have done my best to explain the CSS in comments below.

Here is the code:

 CSS

.content {
    margin: auto;         //use these to center the content
    position: relative:   //position relative, so the absolute div is positioned relative to this div
    text-align: center;   //use these to center the content
    width: 60%;
}

.content p {
    position: relative;   //position relative so we can set a z-index
    z-index: 1;           //z-index is higher than that of the background so it appears above
}

.background {
    background-color: #777;
    height: 100%;
    left:0;               //we want the left of the div to be 0px from the left of its container div
    position: absolute;   //position absolute, so we can put it anywhere we want
    top: 0;               //we want the top of the div to be 0px from the top of the container div
    width: 50%;
    z-index: 0;           //we want the z-index to be lower than the text
}

HTML

<div class="content">
    <p>...text...</p>
    <div class="background"></div>
</div>

Enjoy


问:
moodle not showing CSS and theme with linux server
I'm experiencing a problem regarding Moodle.

I've made an install into a Linux server, but CSS and themes are not displaying so i have only plain text.

How can this be possible and how to solve it?

Thanks.

答:
It is a late response but I think it may help someone like me.
I too ran into the same situation when I migrated moodle from Google Cloud to Godaddy which resulted in just plain text pages without any css. I tried doing a fresh installation of moodle just to check if there are any missing elements. The installation refused to continue and gave an error message that "PHP iconv extension is missing". Later I went to the terminal and ran the following command (to install the missing iconv extenstion and restart apache):

```<code>yum install ea-php73-php-iconv -y
sudo systemctl restart httpd
</code>```

That's it..everything started working as expected!

Body:
It is a late response but I think it may help someone like me.
I too ran into the same situation when I migrated moodle from Google Cloud to Godaddy which resulted in just plain text pages without any css. I tried doing a fresh installation of moodle just to check if there are any missing elements. The installation refused to continue and gave an error message that "PHP iconv extension is missing". Later I went to the terminal and ran the following command (to install the missing iconv extenstion and restart apache):

yum install ea-php73-php-iconv -y
sudo systemctl restart httpd

That's it..everything started working as expected!


问:
X,Y,Z coordinates of an object in the viewer when you select it from the tree
is it possible to get the X,Y,Z coordinates of an object when you select it from the object tree itself. I know you can do it when you mouse click on a particular object but i want to get the coordinates when using the navigation tree. Is there a way to get them using the viewer ? </p>

答:
If the model browser's selection behavior is set to default (isolation) then simply subscribe to Autodesk.Viewing.ISOLATE_EVENT as you would for selection:

```<code>NOP_VIEWER.addEventListener(Autodesk.Viewing.ISOLATE_EVENT, e=>{
//NOP_VIEWER.utilities.getBoundingBox().center()
})
</code>```

BTW you can customize interaction behavior for the model browser by specifying the click config here:

```<code>NOP_VIEWER.modelstructure.clickConfig = {
  click:{
    onObject: ["toggleMultipleOverlayedSelection"]
  }
//...
}
</code>```

Body:
If the model browser's selection behavior is set to default (isolation) then simply subscribe to Autodesk.Viewing.ISOLATE_EVENT as you would for selection:

NOP_VIEWER.addEventListener(Autodesk.Viewing.ISOLATE_EVENT, e=>{
//NOP_VIEWER.utilities.getBoundingBox().center()
})

BTW you can customize interaction behavior for the model browser by specifying the click config here:

NOP_VIEWER.modelstructure.clickConfig = {
  click:{
    onObject: ["toggleMultipleOverlayedSelection"]
  }
//...
}


答:
In your example, the 2 functions won't behave the same. Without the await keyword, your variables won't capture the results returned by these 2 functions, but instead receive 2 Promises.

var positiondata = getPosition();
var timerdata = setTimer(2000);
```

So your console.log will print out 2 Promises instead of the values you actually expect.

Title: Behind the scene- If I use Aync but doesn't use await in it, would it be identical with normal function?

Body:
In your example, the 2 functions won't behave the same. Without the await keyword, your variables won't capture the results returned by these 2 functions, but instead receive 2 Promises.

var positiondata = getPosition();
var timerdata = setTimer(2000);

So your console.log will print out 2 Promises instead of the values you actually expect.


问:
How to connect to docker host from container on Windows 10 (Docker for Windows)
At which IP address can a docker container connect to its host on Docker for Windows (on Windows 10)? How do you find this IP address?

Example: you have a service running at port 1234 on your Windows 10 machine. A program inside your container must access this service. What IP address should the program use to connect to the host?

答: On Windows 10, after your docker container is started, you can run docker-machine ip in command line (cmd or Docker QuickStart Terminal, etc) to get the ip address of your docker container. This ip address is usually, 192.168.99.100.