问:
How to add a separator to the Expander component in UWP app?
I'm looking for a way of implementing this kind of separator to the expander component in UWP app:

Any ideas how to do that?

I've managed to create the similar look of the expander, but I don't know how to implement separators?

Also, I would like to learn how to make expanders kind of "push" other components down when I expand them, so they don't overlap with other components, but simply move them.

Here's the XAML code for this expander:

```<code><muxc:Expander x:Name="FontExpander"
                   x:Uid="FontExpander"
                   Width="1155"
                   IsExpanded="True"
                   Margin="22,323,0,0"
                   VerticalAlignment="Top"
                   Grid.Row="2"
                   Height="380"
                   HorizontalContentAlignment="Left"
                   ExpandDirection="Down">
        <muxc:Expander.Header>

            <Grid HorizontalAlignment="Stretch" VerticalAlignment="Center">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>

                <FontIcon Margin="0,0,12,0"
                                  VerticalAlignment="Center"
                                  Foreground="{ThemeResource TextFillColorPrimaryBrush}"
                                  FontSize="16"
                                  Glyph=""/>

                <StackPanel Grid.Column="1"
                                    Margin="0,12"
                                    Orientation="Vertical">
                    <TextBlock x:Uid="SettingsFontTitle" Style="{StaticResource BodyTextBlockStyle}"/>
                    <TextBlock x:Uid="SettingsFontDescription"
                                       Style="{StaticResource CaptionTextBlockStyle}"
                                       Foreground="{ThemeResource TextFillColorSecondaryBrush}"
                                       TextWrapping="WrapWholeWords"/>
                </StackPanel>
            </Grid>

        </muxc:Expander.Header>
        <muxc:Expander.Content>

            <Grid  Margin="-18,-170,-17,-170">

                <TextBlock x:Name="SettingsFamily" x:Uid="SettingsFamily" Text="Family" Margin="50,51,1000,286"/>
                <ComboBox x:Name="ComboBoxFamily" ItemsSource="{x:Bind Fonts}" Width="200" Margin="950,41,0,0" SelectionChanged="ComboBoxFamily_SelectionChanged" />

                <TextBlock x:Name="SettingsStyle" x:Uid="SettingsStyle" Text="Style" Margin="50,106,995,218" Loaded="SettingsStyle_Loaded"/>
                <ComboBox  x:Name="ComboBoxStyle" Width="200"  Margin="950,101,0,0">
                    <x:String>Regular</x:String>
                </ComboBox>

                <TextBlock x:Name="SettingsSize" x:Uid="SettingsSize" Text="Size" Margin="50,166,1002,158"/>
                <ComboBox x:Name="ComboBoxSize" ItemsSource="{x:Bind FontSizes}" Width="200" Margin="950,161,0,0"/>

                <TextBlock x:Name="Text" x:Uid="SettingsText" Text="Hello World! I am so excited to be here!" Margin="62,224,38,126" TextWrapping="Wrap" FontSize="{x:Bind (x:Double)ComboBoxSize.SelectedValue, Mode=OneWay}" TextAlignment="Center"/>

            </Grid>
        </muxc:Expander.Content>
    </muxc:Expander>
</code>```

Any help would be much appreciated!

答:
A separate can for example be implemented using a Border or a Grid:

```<code><Grid Background="DarkGray" Height="1" />
</code>```

As a side note, you shouldn't use margins to position your elements. Use an appropriate layout Panel. Using a Grid, you should add ColumnDefinitions and RowDefinitions to it as examplified here.

Body:
I'm looking for a way of implementing this kind of separator to the expander component in UWP app:

Any ideas how to do that?

I've managed to create the similar look of the expander, but I don't know how to implement separators?

Also, I would like to learn how to make expanders kind of "push" other components down when I expand them, so they don't overlap with other components, but simply move them.

Here's the XAML code for this expander:

<muxc:Expander x:Name="FontExpander"
                   x:Uid="FontExpander"
                   Width="1155"
                   IsExpanded="True"
                   Margin="22,323,0,0"
                   VerticalAlignment="Top"
                   Grid.Row="2"
                   Height="380"
                   HorizontalContentAlignment="Left"
                   ExpandDirection="Down">
        <muxc:Expander.Header>

            <Grid HorizontalAlignment="Stretch" VerticalAlignment="Center">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>

                <FontIcon Margin="0,0,12,0"
                                  VerticalAlignment="Center"
                                  Foreground="{ThemeResource TextFillColorPrimaryBrush}"
                                  FontSize="16"
                                  Glyph=""/>

                <StackPanel Grid.Column="1"
                                    Margin="0,12"
                                    Orientation="Vertical">
                    <TextBlock x:Uid="SettingsFontTitle" Style="{StaticResource BodyTextBlockStyle}"/>
                    <TextBlock x:Uid="SettingsFontDescription"
                                       Style="{StaticResource CaptionTextBlockStyle}"
                                       Foreground="{ThemeResource TextFillColorSecondaryBrush}"
                                       TextWrapping="WrapWholeWords"/>
                </StackPanel>
            </Grid>

        </muxc:Expander.Header>
        <muxc:Expander.Content>

            <Grid  Margin="-18,-170,-17,-170">

                <TextBlock x:Name="SettingsFamily" x:Uid="SettingsFamily" Text="Family" Margin="50,51,1000,286"/>
                <ComboBox x:Name="ComboBoxFamily" ItemsSource="{x:Bind Fonts}" Width="200" Margin="950,41,0,0" SelectionChanged="ComboBoxFamily_SelectionChanged" />

                <TextBlock x:Name="SettingsStyle" x:Uid="SettingsStyle" Text="Style" Margin="50,106,995,218" Loaded="SettingsStyle_Loaded"/>
                <ComboBox  x:Name="ComboBoxStyle" Width="200"  Margin="950,101,0,0">
                    <x:String>Regular</x:String>
                </ComboBox>

                <TextBlock x:Name="SettingsSize" x:Uid="SettingsSize" Text="Size" Margin="50,166,1002,158"/>
                <ComboBox x:Name="ComboBoxSize" ItemsSource="{x:Bind FontSizes}" Width="200" Margin="950,161,0,0"/>

                <TextBlock x:Name="Text" x:Uid="SettingsText" Text="Hello World! I am so excited to be here!" Margin="62,224,38,126" TextWrapping="Wrap" FontSize="{x:Bind (x:Double)ComboBoxSize.SelectedValue, Mode=OneWay}" TextAlignment="Center"/>

            </Grid>
        </muxc:Expander.Content>
    </muxc:Expander>

Any help would be much appreciated!

Body:
A separate can for example be implemented using a Border or a Grid:

<Grid Background="DarkGray" Height="1" />

As a side note, you shouldn't use margins to position your elements. Use an appropriate layout Panel. Using a Grid, you should add ColumnDefinitions and RowDefinitions to it as examplified here.


来源: stackexchange

问:
Recorded Macro Error: Method 'CreatePivotTable' of object 'PivotCache' failed
I recorded a macro for creating a pivot table on the existing sheet but am getting Error: Method 'CreatePivotTable' of object 'PivotCache' failed. Would really appreciate help with how to get rid of this error! Thanks.</p>

```<code>Sub MakePivot()

ActiveWindow.SmallScroll ToRight:=-45
Columns("A:Y").Select
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=
    "New!R1C1:R1048576C25", Version:=xlPivotTableVersion14).
    CreatePivotTable TableDestination:="", TableName:= _
    "PivotTable1", DefaultVersion:=xlPivotTableVersion14

With ActiveSheet.PivotTables("PivotTable1").PivotFields("____")
    .Orientation = xlRowField
    .Position = 1
End With
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
    "PivotTable1").PivotFields("______"), "Count of ______", xlCount
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
    "PivotTable1").PivotFields("Value "), "Count of Value ", xlCount
ExecuteExcel4Macro _
    "PIVOT.FIELD.PROPERTIES(""PivotTable1"",""Count of ______"",,,2)"
ExecuteExcel4Macro _
    "PIVOT.FIELD.PROPERTIES(""PivotTable1"",""Count of Value "",,,2)"
End Sub
</code>```

答:
It seems like a bug of Excel Application.
I've solved this problem like this.

This example use already existing WorkbookConnection.

```<code> 'Get WorkbookConnection object
 Dim conn As WorkbookConnection
 Set conn =  ActiveWorkbook.Connections("MyConnectionName")

 'Declare temp variables
 Dim connStr As String
 Dim sqlStr As String

 'Store connection string and command text in variables depends on connection type
 If conn.Type = xlConnectionTypeODBC Then
   connStr = conn.ODBCConnection.Connection
   sqlStr = conn.ODBCConnection.CommandText
 End If

 If conn.Type = xlConnectionTypeOLEDB Then
   connStr = conn.OLEDBConnection.Connection
   sqlStr = conn.OLEDBConnection.CommandText
 End If

 'Create PivotCache
 Dim pcache As pivotCache
 Set pcache = ActiveWorkbook.PivotCaches.Create(xlExternal, conn)

 'Then we need to get recordset to create pivot table
 Dim adodb_conn As Object
 Dim rs As Object
 Set adodb_conn = CreateObject("ADODB.Connection")
 Set rs = CreateObject("ADODB.Recordset")
 adodb_conn.Open connStr
 rs.Open sqlStr, adodb_conn

 Set pcache.Recordset = rs
 'When CreatePivotTable method called the linked WorkbookConnection is losing connection string and command text
 Set pvt = pcache.CreatePivotTable(TableDestination:=Sheets("MySheetName").Cells(1, 1), TableName:="MyPivotTableName")

 rs.Close
 adodb_conn.Close

 'Restore CommandText and connection string
 pcache.CommandText = sqlStr
 pcache.Connection = connStr

 ' Now you have PivotTable that linked with yours WorkbookConnection
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I recorded a macro for creating a pivot table on the existing sheet but am getting Error: Method 'CreatePivotTable' of object 'PivotCache' failed. Would really appreciate help with how to get rid of this error! Thanks.

Sub MakePivot()

ActiveWindow.SmallScroll ToRight:=-45
Columns("A:Y").Select
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=
    "New!R1C1:R1048576C25", Version:=xlPivotTableVersion14).
    CreatePivotTable TableDestination:="", TableName:= _
    "PivotTable1", DefaultVersion:=xlPivotTableVersion14

With ActiveSheet.PivotTables("PivotTable1").PivotFields("____")
    .Orientation = xlRowField
    .Position = 1
End With
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
    "PivotTable1").PivotFields("______"), "Count of ______", xlCount
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
    "PivotTable1").PivotFields("Value "), "Count of Value ", xlCount
ExecuteExcel4Macro _
    "PIVOT.FIELD.PROPERTIES(""PivotTable1"",""Count of ______"",,,2)"
ExecuteExcel4Macro _
    "PIVOT.FIELD.PROPERTIES(""PivotTable1"",""Count of Value "",,,2)"
End Sub

Body:
It seems like a bug of Excel Application.
I've solved this problem like this.

This example use already existing WorkbookConnection.

 'Get WorkbookConnection object
 Dim conn As WorkbookConnection
 Set conn =  ActiveWorkbook.Connections("MyConnectionName")

 'Declare temp variables
 Dim connStr As String
 Dim sqlStr As String

 'Store connection string and command text in variables depends on connection type
 If conn.Type = xlConnectionTypeODBC Then
   connStr = conn.ODBCConnection.Connection
   sqlStr = conn.ODBCConnection.CommandText
 End If

 If conn.Type = xlConnectionTypeOLEDB Then
   connStr = conn.OLEDBConnection.Connection
   sqlStr = conn.OLEDBConnection.CommandText
 End If

 'Create PivotCache
 Dim pcache As pivotCache
 Set pcache = ActiveWorkbook.PivotCaches.Create(xlExternal, conn)

 'Then we need to get recordset to create pivot table
 Dim adodb_conn As Object
 Dim rs As Object
 Set adodb_conn = CreateObject("ADODB.Connection")
 Set rs = CreateObject("ADODB.Recordset")
 adodb_conn.Open connStr
 rs.Open sqlStr, adodb_conn

 Set pcache.Recordset = rs
 'When CreatePivotTable method called the linked WorkbookConnection is losing connection string and command text
 Set pvt = pcache.CreatePivotTable(TableDestination:=Sheets("MySheetName").Cells(1, 1), TableName:="MyPivotTableName")

 rs.Close
 adodb_conn.Close

 'Restore CommandText and connection string
 pcache.CommandText = sqlStr
 pcache.Connection = connStr

 ' Now you have PivotTable that linked with yours WorkbookConnection

ContentLicense: CC BY-SA 4.0


问:
Advantage of switching from ASP.NET to bread & butter HTML/jQuery
I have been getting more and more sick of all the quirks about control ids, trying to get your data in serverside (based on client-side events). I seem to spend more time fighting with controls in asp.net, that I think it takes me more time than I gain by using it.

I was thinking about using plain html/javascript with jQuery and a web service that returns json for the data.

The only thing I think I would miss from webforms is the MasterPages, the session management, authentication based on windows login and possibly validators(although they have some quirks too). (In fact, maybe not for sessions and auth, but I have never developped webservices)

Is there something wrong with the way
I am thinking about this, or
something I didn't think about ?

Are there things in asp.net that you
think I will miss ?

Has anyone done this before and wants to share experience ?

Please, also take note, that I only have the Framework 2.0 available for development.

Edit: The kind of things giving me troubles in asp.net that makes me wonder for the switch:

Here is a sample of a page giving me problems.

There is a tree table (master / details)

You can edit fields on each child row.

When you press the save button, the data from the group row must be updated (just data from a select, no modification in database), as
the data from the child row.

I don't want to refresh the whole page because the displayed records are based from search criterias.

The Master / Details are generated using Repeaters

Trying to update a record from code behind is really quirky, and still have no clue about updating the display.

Using jQuery and a web service, my guess would be that i could update directly to the database, request what I want to be displayed and just update that record. This is the kind of things that make me wonder if asp.net is just getting in my way.

```

 ________________________________________________________________________
| -  Some             Details           About            Group           |
|________________________________________________________________________|
    |¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯|
    | ChildRecord Some  Editable  Fields       SaveButton   |
    | ChildRecord Some  Editable  Fields       SaveButton   |
    | ChildRecord Some  Editable  Fields       SaveButton   |
    | ChildRecord Some  Editable  Fields       SaveButton   |
    |_______________________________________________________|
 ________________________________________________________________________
| +  Some             Details           About            Group           |
|________________________________________________________________________|
 ________________________________________________________________________
| +  Some             Details           About            Group           |
|________________________________________________________________________|

```

Edit2:
The problem I have about ASP.NET is not related to ajax. Yes, I use jQuery to make the interfaces more dynamic like showing / hiding the search section when not needed and collapsing details from the tree, but this is all I do with it.

What bothers me is that if I want to check which button has been clicked in this example, I have to use some tricks that feel a bit haky.

If you want to use databound comboboxes in a repeater, you have to use codebehind to set the selected value, it will be a pain to retreive the data selected.

Next, if you want to check what data was modified, you have to save the datatable in the viewstate, read data from all controls in the repeater, then compare with the datatable to make an update. This is this kind of things that bother me with asp.net.

答:
I think the fundamental question to ask yourself is:

```Am I using the controls for what they've been designed to do?```

Having worked solely with ASP.NET in the 2.0 Framework, I've found I have not had to deal with the issues you are describing.  ASP.NET can be quirky yes, but mostly when you use it for something other than it was intended.  In which case custom rolled controls fill the niche easily.

Edit:

Your troubles sound like you're trying to implement AJAX techniques, however in your question you don't mention using the AJAX framework.  Have a look at that as it may be able to fill your niche.

OwnerDisplayName: Martin

ContentLicense: CC BY-SA 2.5

Body:
I have been getting more and more sick of all the quirks about control ids, trying to get your data in serverside (based on client-side events). I seem to spend more time fighting with controls in asp.net, that I think it takes me more time than I gain by using it.

I was thinking about using plain html/javascript with jQuery and a web service that returns json for the data.

The only thing I think I would miss from webforms is the MasterPages, the session management, authentication based on windows login and possibly validators(although they have some quirks too). (In fact, maybe not for sessions and auth, but I have never developped webservices)

Is there something wrong with the way
I am thinking about this, or
something I didn't think about ?

Are there things in asp.net that you
think I will miss ?

Has anyone done this before and wants to share experience ?

Please, also take note, that I only have the Framework 2.0 available for development.

Edit: The kind of things giving me troubles in asp.net that makes me wonder for the switch:

Here is a sample of a page giving me problems.

There is a tree table (master / details)

You can edit fields on each child row.

When you press the save button, the data from the group row must be updated (just data from a select, no modification in database), as
the data from the child row.

I don't want to refresh the whole page because the displayed records are based from search criterias.

The Master / Details are generated using Repeaters

Trying to update a record from code behind is really quirky, and still have no clue about updating the display.

Using jQuery and a web service, my guess would be that i could update directly to the database, request what I want to be displayed and just update that record. This is the kind of things that make me wonder if asp.net is just getting in my way.

 ________________________________________________________________________
| -  Some             Details           About            Group           |
|________________________________________________________________________|
    |¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯|
    | ChildRecord Some  Editable  Fields       SaveButton   |
    | ChildRecord Some  Editable  Fields       SaveButton   |
    | ChildRecord Some  Editable  Fields       SaveButton   |
    | ChildRecord Some  Editable  Fields       SaveButton   |
    |_______________________________________________________|
 ________________________________________________________________________
| +  Some             Details           About            Group           |
|________________________________________________________________________|
 ________________________________________________________________________
| +  Some             Details           About            Group           |
|________________________________________________________________________|

Edit2:
The problem I have about ASP.NET is not related to ajax. Yes, I use jQuery to make the interfaces more dynamic like showing / hiding the search section when not needed and collapsing details from the tree, but this is all I do with it.

What bothers me is that if I want to check which button has been clicked in this example, I have to use some tricks that feel a bit haky.

If you want to use databound comboboxes in a repeater, you have to use codebehind to set the selected value, it will be a pain to retreive the data selected.

Next, if you want to check what data was modified, you have to save the datatable in the viewstate, read data from all controls in the repeater, then compare with the datatable to make an update. This is this kind of things that bother me with asp.net.

LastEditorDisplayName: Martin

Body:
I think the fundamental question to ask yourself is:

Am I using the controls for what they've been designed to do?

Having worked solely with ASP.NET in the 2.0 Framework, I've found I have not had to deal with the issues you are describing.  ASP.NET can be quirky yes, but mostly when you use it for something other than it was intended.  In which case custom rolled controls fill the niche easily.

Edit:

Your troubles sound like you're trying to implement AJAX techniques, however in your question you don't mention using the AJAX framework.  Have a look at that as it may be able to fill your niche.

OwnerDisplayName: LFSR Consulting

LastEditorDisplayName: LFSR Consulting


问:
How to determine the runtime for the two reverse string methods in O() notaion?
I have two queries to reverse a string. Need to compare them:

```<code>public string ReverseD(string text)
{
    return new string(text.ToCharArray().Reverse().ToArray());
}

public string ReverseB(string text)
{
    char[] charArray = text.ToCharArray();
    Array.Reverse(charArray);
    return new string(charArray);
}
</code>```

How can I determine the run time for these two algorithms in O() notation? Need to compare.

答:
While knowing the asymptotic performance of these two approaches to reversing a string is useful, it's probably not what you really need. You're probably not going to be applying the algorithm to strings whose length becomes larger and larger.

In cases like this, it's actualy more helpful to just run both algorithms a bunch of times, and see which one takes less time.

Most likely it will be the straight Array.Reverse() version, since it will intelligently swap items within the array, whereas the Enumerable.Reverse() method will yield return each element in reverse order. Either will be O(n), since they both manipulate each of the n items in the array a constant number of times.

But again, the best way to see which one will perform better is to actually run them and see.

Body:
I have two queries to reverse a string. Need to compare them:

public string ReverseD(string text)
{
    return new string(text.ToCharArray().Reverse().ToArray());
}

public string ReverseB(string text)
{
    char[] charArray = text.ToCharArray();
    Array.Reverse(charArray);
    return new string(charArray);
}

How can I determine the run time for these two algorithms in O() notation? Need to compare.


问:
Best way to convert .ipynb to .py in VSCode
I'm looking for a good way to convert .ipynb to .py files in VSCode. So far I've tried:

the "Export As" Option built into vscode. Not ideal as it produces the following at the start of the script, as well as "Run Cell", "Run Below", etc. buttons/links:

"To add a new cell, type '# %%' To add a new markdown cell, type '# %%
[markdown]' %% from IPython import get_ipython"

nbconvert. I usually insert this as a command in the script itself (https://stackoverflow.com/a/19779226/14198216) so it's automatically converted and saved once run. But this also leaves "Run Cell" etc, as well as execution markings (ex: "In [1]")

jupytext. I also usually insert this as a command. At the start of the .py, it produces:

-- coding: utf-8 --
--- jupyter:    jupytext:
text_representation:

Is there a nice, minimalist solution that doesn't insert a bunch of gunk (which needs to be manually edited out) in the .py version of my notebooks and can be easily/automatically executed from the notebook itself? This could also be setting tweaks that I'm currently unaware of that can make one of the things I mentioned work better.

Thanks in advance.

答:
First, you need to install the Jupyter package:

https://marketplace.visualstudio.com/items?itemName=ms-toolsai.jupyter

Second open "Command Palette" (⇧⌘P) and search for this line:
Jupyter: Export to Python Script


问:
Is it possible to pull out a list of particular field values from a collection of generic objects in C#?
I have the following method in a class I am using for pagination in my app:

```<code>public static PagedList<T> ToPagedList(IEnumerable<T> source, int pageNumber, int pageSize)
        {
            var count = source.Count();
            var items = source
              .Skip((pageNumber - 1) * pageSize)
              .Take(pageSize).ToList();

            return new PagedList<T>(items, count, pageNumber, pageSize);
        }
</code>```

In this method I am passing in a collection of generic objects as IEnumerable<T> source which regardless of type will always have an Id field. What I'd like to do is pull out all of the Ids for these objects and store them in a list to be passed into my PagedList constructor. Is this possible?

答:
An interface would be the best way, but you specifically said "field" and interfaces cannot contain fields.

You could get around this limitation with an abstract base class, but you cannot have multiple base classes on a single class (if applicable).

...All of this assumes that you have the ability to modify those classes.

Another way to do this would be:

```<code>public static PagedList<T> ToPagedList<T>(IEnumerable<T> source, int pageNumber, int pageSize)
{
    var count = source.Count();

    var items = source
        .Skip((pageNumber - 1) * pageSize)
        .Take(pageSize).ToList();

    var ids = items
        .Select(i => ((dynamic)i).Id)   // field is **always** named "Id"
        .Cast<int>()                    // its type is **always** int
        .ToList();

    return new PagedList<T>(items, count, pageNumber, pageSize/*, ids*/); // pass ids
}
</code>```

This assumes the field in question is named "Id", and it is an int.

Adjust accordingly and handle potential errors.

I think I originally misunderstood the question, the comment by @Dusan caused me to reevaluate and update the code.

Body:
I have the following method in a class I am using for pagination in my app:

public static PagedList<T> ToPagedList(IEnumerable<T> source, int pageNumber, int pageSize)
        {
            var count = source.Count();
            var items = source
              .Skip((pageNumber - 1) * pageSize)
              .Take(pageSize).ToList();

            return new PagedList<T>(items, count, pageNumber, pageSize);
        }

In this method I am passing in a collection of generic objects as IEnumerable<T> source which regardless of type will always have an Id field. What I'd like to do is pull out all of the Ids for these objects and store them in a list to be passed into my PagedList constructor. Is this possible?

Body:
An interface would be the best way, but you specifically said "field" and interfaces cannot contain fields.

You could get around this limitation with an abstract base class, but you cannot have multiple base classes on a single class (if applicable).

...All of this assumes that you have the ability to modify those classes.

Another way to do this would be:

public static PagedList<T> ToPagedList<T>(IEnumerable<T> source, int pageNumber, int pageSize)
{
    var count = source.Count();

    var items = source
        .Skip((pageNumber - 1) * pageSize)
        .Take(pageSize).ToList();

    var ids = items
        .Select(i => ((dynamic)i).Id)   // field is **always** named "Id"
        .Cast<int>()                    // its type is **always** int
        .ToList();

    return new PagedList<T>(items, count, pageNumber, pageSize/*, ids*/); // pass ids
}

This assumes the field in question is named "Id", and it is an int.

Adjust accordingly and handle potential errors.

I think I originally misunderstood the question, the comment by @Dusan caused me to reevaluate and update the code.


问:
useState with an argument in it's array is breaking a setInterval and makes it glitchy and erratic
I just asked a question earlier here: react value of a state variable different in a different function

and now I have a new problem.

having a useEffect that looks like this

```<code>  useEffect(() => {
    countDown();
    console.log('Score in useeffect', strokeScore);
  }, [strokeScore]);
</code>```

is breaking a setInterval that looks like this:

```<code>  const countDown = () => {
    // let strokeCountdown = Math.floor(Math.random() * 31) + 100;
    let strokeCountdown = 20
    let strokeCountdownSpeedOptions = [1000, 500, 300, 200];
    let strokeCountDownSpeed = strokeCountdownSpeedOptions[Math.floor(Math.random()*strokeCountdownSpeedOptions.length)];
    let strokeCounter = setInterval(() => {
        strokeCountdown--
        setStrokeCountdown(strokeCountdown)
        if (strokeCountdown === 0) {
            endOfGameRound()
            clearInterval(strokeCounter)
            setTotalStrokeScore(strokeScore);
        }
    }, strokeCountDownSpeed)
  }
</code>```

The full component looks like this:

```<code>import React, { useEffect, useState } from 'react';

function ScoreCard() {

  const [strokeScore, setStrokeScore] = useState(1);

  const [totalStrokeScore, setTotalStrokeScore] = useState(1);

  const [strokeCountdown, setStrokeCountdown] = useState();

  const strokeCountdownDing = new Audio('/sounds/round-complete.mp3');

  // make new variable, maybe?
  let strokeScoreCount = 0;

  const endOfGameRound = () => {
    strokeCountdownDing.play();
    document.getElementById('stroke-counter-button').disabled = true;
  }

  const addToStrokeScore = () => {
    setStrokeScore(prev => prev + 1);
    // prints the correct number
    console.log('Score in function', strokeScore);
    if (strokeCountdown === 0) {
        endOfGameRound()
    }
  }

  const subtractStrokeScore = () => {
    setStrokeScore(strokeScore - 1);
  }

  const countDown = () => {
    // let strokeCountdown = Math.floor(Math.random() * 31) + 100;
    let strokeCountdown = 20
    let strokeCountdownSpeedOptions = [1000, 500, 300, 200];
    let strokeCountDownSpeed = strokeCountdownSpeedOptions[Math.floor(Math.random()*strokeCountdownSpeedOptions.length)];
    let strokeCounter = setInterval(() => {
        strokeCountdown--
        setStrokeCountdown(strokeCountdown)
        if (strokeCountdown === 0) {
            endOfGameRound()
            clearInterval(strokeCounter)
            setTotalStrokeScore(strokeScore);
        }
    }, strokeCountDownSpeed)
  }

  useEffect(() => {
    countDown();
    console.log('Score in useeffect', strokeScore);
  }, [strokeScore]);

  return (
    <div className="game__score-card">
      <div className="game__speed-level">
          Speed: idk
      </div>
      <div className="game__stroke-countdown">
          Countdown: {strokeCountdown}
      </div>
      <p>Score: {strokeScore}</p>
      <button id="stroke-counter-button" onClick={addToStrokeScore}>
          {strokeCountdown === 0 ? 'Game Over' : 'Stroke'}
      </button>
      {/* window.location just temp for now */}
      {strokeCountdown === 0
        ? <button onClick={() => window.location.reload(false)}>Play Again</button>
        : <button disabled>Game in Progress</button>
      }
      <div className="game__total-score">
          Total score: {totalStrokeScore}
      </div>
    </div>
  );
}

export default ScoreCard;
</code>```

When I click on the button, the timer gets erratic and goes all over the place.

All I want to do is make it so that the timer counts down smoothly, gets the clicks the user made and add it to total score.

Why is

```<code>  useEffect(() => {
    countDown();
    console.log('Score in useeffect', strokeScore);
  }, [strokeScore]);
</code>```

Breaking everything?

答:
I was calling countDown() everytime I clicked so I just did

```<code>  useEffect(() => {
    if (strokeScore === 1) {
        countDown();
    }
    console.log('Score in useeffect', strokeScore);
  }, [strokeScore]);
</code>```

Body:
I just asked a question earlier here: react value of a state variable different in a different function

and now I have a new problem.

having a useEffect that looks like this

  useEffect(() => {
    countDown();
    console.log('Score in useeffect', strokeScore);
  }, [strokeScore]);

is breaking a setInterval that looks like this:

  const countDown = () => {
    // let strokeCountdown = Math.floor(Math.random() * 31) + 100;
    let strokeCountdown = 20
    let strokeCountdownSpeedOptions = [1000, 500, 300, 200];
    let strokeCountDownSpeed = strokeCountdownSpeedOptions[Math.floor(Math.random()*strokeCountdownSpeedOptions.length)];
    let strokeCounter = setInterval(() => {
        strokeCountdown--
        setStrokeCountdown(strokeCountdown)
        if (strokeCountdown === 0) {
            endOfGameRound()
            clearInterval(strokeCounter)
            setTotalStrokeScore(strokeScore);
        }
    }, strokeCountDownSpeed)
  }

The full component looks like this:

import React, { useEffect, useState } from 'react';

function ScoreCard() {

  const [strokeScore, setStrokeScore] = useState(1);

  const [totalStrokeScore, setTotalStrokeScore] = useState(1);

  const [strokeCountdown, setStrokeCountdown] = useState();

  const strokeCountdownDing = new Audio('/sounds/round-complete.mp3');

  // make new variable, maybe?
  let strokeScoreCount = 0;

  const endOfGameRound = () => {
    strokeCountdownDing.play();
    document.getElementById('stroke-counter-button').disabled = true;
  }

  const addToStrokeScore = () => {
    setStrokeScore(prev => prev + 1);
    // prints the correct number
    console.log('Score in function', strokeScore);
    if (strokeCountdown === 0) {
        endOfGameRound()
    }
  }

  const subtractStrokeScore = () => {
    setStrokeScore(strokeScore - 1);
  }

  const countDown = () => {
    // let strokeCountdown = Math.floor(Math.random() * 31) + 100;
    let strokeCountdown = 20
    let strokeCountdownSpeedOptions = [1000, 500, 300, 200];
    let strokeCountDownSpeed = strokeCountdownSpeedOptions[Math.floor(Math.random()*strokeCountdownSpeedOptions.length)];
    let strokeCounter = setInterval(() => {
        strokeCountdown--
        setStrokeCountdown(strokeCountdown)
        if (strokeCountdown === 0) {
            endOfGameRound()
            clearInterval(strokeCounter)
            setTotalStrokeScore(strokeScore);
        }
    }, strokeCountDownSpeed)
  }

  useEffect(() => {
    countDown();
    console.log('Score in useeffect', strokeScore);
  }, [strokeScore]);

  return (

          Speed: idk

          Countdown: {strokeCountdown}

Score: {strokeScore}

      <button id="stroke-counter-button" onClick={addToStrokeScore}>
          {strokeCountdown === 0 ? 'Game Over' : 'Stroke'}
      </button>
      {/* window.location just temp for now */}
      {strokeCountdown === 0
        ? <button onClick={() => window.location.reload(false)}>Play Again</button>
        : <button disabled>Game in Progress</button>
      }

          Total score: {totalStrokeScore}

  );
}

export default ScoreCard;

When I click on the button, the timer gets erratic and goes all over the place.

All I want to do is make it so that the timer counts down smoothly, gets the clicks the user made and add it to total score.

Why is

  useEffect(() => {
    countDown();
    console.log('Score in useeffect', strokeScore);
  }, [strokeScore]);

Breaking everything?

Body:
I was calling countDown() everytime I clicked so I just did

  useEffect(() => {
    if (strokeScore === 1) {
        countDown();
    }
    console.log('Score in useeffect', strokeScore);
  }, [strokeScore]);


问:
Dump raw XML to debug Grails REST calls
We need to dump the raw XML for troubleshooting data dependant issues on a Grails 1.2 app. In the UrlMappings we have "parseRequest:true". The following does not get me what I'm looking for, any other options? Note that we need this on a production machine, so fiddler or similar proxy based solutions suitable for development are not an option</p>

```<code>def beforeInterceptor = {
    println "#"*99
    println "Executing action $actionName with params=$params"
    println request.inputStream.dump()
    //println request.inputStream.text // java.io.IOException: Stream closed
    println request.XML
}
</code>```

答:
If I remember correctly, when you do request.XML you should receive an XmlSlurper object.  So this should get what you want.

```<code>def beforeInterceptor = {
   def xml = request.XML
   def xmlString = new XmlNodePrinter(new PrintWriter(new StringWriter())).print(xml)
}
</code>```

Title: Dump raw XML to debug Grails REST calls

Body:
We need to dump the raw XML for troubleshooting data dependant issues on a Grails 1.2 app. In the UrlMappings we have "parseRequest:true". The following does not get me what I'm looking for, any other options? Note that we need this on a production machine, so fiddler or similar proxy based solutions suitable for development are not an option

def beforeInterceptor = {
    println "#"*99
    println "Executing action $actionName with params=$params"
    println request.inputStream.dump()
    //println request.inputStream.text // java.io.IOException: Stream closed
    println request.XML
}

Body:
If I remember correctly, when you do request.XML you should receive an XmlSlurper object.  So this should get what you want.

def beforeInterceptor = {
   def xml = request.XML
   def xmlString = new XmlNodePrinter(new PrintWriter(new StringWriter())).print(xml)
}


问:
How do I display every element from my localStorage item?
i'm trying to create a simple To-do list, and my question is how do i get all elements of a single item in localStorage displayed?

pushing things into localStorage in a form of an array works fine, but only thing I see on my page is the first index of the "tasks" array.

```<code>const inputEl = document.getElementById("inputEl")
const submitBtn = document.getElementById("submit")
const clearBtn = document.getElementById("clearBtn")
const todoListContainer = document.getElementById("todoList")
const taskContainer = document.querySelector(".task")
const cancelBtn = document.querySelector(".cancelBtn")
const doneBtn = document.querySelector(".doneBtn")
const errorMsg = document.querySelector(".error")

let localStorageContent = localStorage.getItem("tasks")
let tasks = []

function createTask(){
    if(inputEl.value.length != 0){

    const newDiv = document.createElement("div")
    newDiv.classList.add("task")
    const newParagraph = document.createElement("p")
    const newCancelBtn = document.createElement("button")
    newCancelBtn.classList.add("cancelBtn")
    newCancelBtn.textContent = "X"
    const newDoneBtn = document.createElement("button")
    newDoneBtn.classList.add("doneBtn")
    newDoneBtn.textContent = "Done"

    todoListContainer.appendChild(newDiv)
    newDiv.appendChild(newParagraph)
    newDiv.appendChild(newCancelBtn)
    newDiv.appendChild(newDoneBtn)
    //^^ Creating a container for a new task, with all its elements and assigning the classes^^

    tasks.push(inputEl.value)
    localStorage.setItem("tasks", JSON.stringify(tasks))
    inputEl.value = ""

    newParagraph.textContent = JSON.parse(localStorageContent)

    errorMsg.textContent = ""

    }else{
        errorMsg.textContent = "You have to type something in!"
        errorMsg.classList.toggle("visibility")

    }

}

submitBtn.addEventListener("click", () =>{
    createTask()

})
</code>```

答:
When you execute JSON.parse(localStorageContent) you convert your string into an array, that's right.

But:

```<code>newParagraph.textContent = JSON.parse(localStorageContent)
</code>```

is the same as:

```<code>newParagraph.textContent = JSON.parse(localStorageContent)[0]
</code>```

So, you have to loop through your JSON.parse(localStorageContent)
array... Therefore, create a new variable:

```<code>let tasksItem = JSON.parse(localStorageContent)
</code>```

and loop on with .forEach method

Body:
i'm trying to create a simple To-do list, and my question is how do i get all elements of a single item in localStorage displayed?

pushing things into localStorage in a form of an array works fine, but only thing I see on my page is the first index of the "tasks" array.

const inputEl = document.getElementById("inputEl")
const submitBtn = document.getElementById("submit")
const clearBtn = document.getElementById("clearBtn")
const todoListContainer = document.getElementById("todoList")
const taskContainer = document.querySelector(".task")
const cancelBtn = document.querySelector(".cancelBtn")
const doneBtn = document.querySelector(".doneBtn")
const errorMsg = document.querySelector(".error")

let localStorageContent = localStorage.getItem("tasks")
let tasks = []

function createTask(){
    if(inputEl.value.length != 0){

    const newDiv = document.createElement("div")
    newDiv.classList.add("task")
    const newParagraph = document.createElement("p")
    const newCancelBtn = document.createElement("button")
    newCancelBtn.classList.add("cancelBtn")
    newCancelBtn.textContent = "X"
    const newDoneBtn = document.createElement("button")
    newDoneBtn.classList.add("doneBtn")
    newDoneBtn.textContent = "Done"

    todoListContainer.appendChild(newDiv)
    newDiv.appendChild(newParagraph)
    newDiv.appendChild(newCancelBtn)
    newDiv.appendChild(newDoneBtn)
    //^^ Creating a container for a new task, with all its elements and assigning the classes^^

    tasks.push(inputEl.value)
    localStorage.setItem("tasks", JSON.stringify(tasks))
    inputEl.value = ""

    newParagraph.textContent = JSON.parse(localStorageContent)

    errorMsg.textContent = ""

    }else{
        errorMsg.textContent = "You have to type something in!"
        errorMsg.classList.toggle("visibility")

    }

}

submitBtn.addEventListener("click", () =>{
    createTask()

})

Body:
When you execute JSON.parse(localStorageContent) you convert your string into an array, that's right.

But:

newParagraph.textContent = JSON.parse(localStorageContent)

is the same as:

newParagraph.textContent = JSON.parse(localStorageContent)[0]

So, you have to loop through your JSON.parse(localStorageContent)
array... Therefore, create a new variable:

let tasksItem = JSON.parse(localStorageContent)

and loop on with .forEach method


问:
Check if number is decimal
I need to check in PHP if user entered a decimal number (US way, with decimal point: X.XXX)

Any reliable way to do this?

答:
I can't comment, but I have this interesting behaviour.
(tested on v. 7.3.19 on a website for php testing online)

If you multiply 50 by 1.1 fmod gives different results than expected.
If you do by 1.2 or 1.3 it's fine, if you do another number (like 60 or 40) is also fine.

```<code>$price = 50;
$price = $price * 1.1;

if(strpos($price,".") !== false){
    echo "decimal";
}else{
    echo "not a decimal";
}

echo '<br />';

if(fmod($price, 1) !== 0.00){
    //echo fmod($price, 1);
    echo "decimal";
} else {
    echo "not a decimal";
}//end if
</code>```

Title: Check if number is decimal

Body:
I can't comment, but I have this interesting behaviour.
(tested on v. 7.3.19 on a website for php testing online)

If you multiply 50 by 1.1 fmod gives different results than expected.
If you do by 1.2 or 1.3 it's fine, if you do another number (like 60 or 40) is also fine.

$price = 50;
$price = $price * 1.1;

if(strpos($price,".") !== false){
    echo "decimal";
}else{
    echo "not a decimal";
}

echo '<br />';

if(fmod($price, 1) !== 0.00){
    //echo fmod($price, 1);
    echo "decimal";
} else {
    echo "not a decimal";
}//end if


问:
'NoneType' object has no attribute 'element'
why in the code below when printing head.element inside the while loop I dont get any error
but the same code print code outside the loop get me an error?</p>
```<code>class node:
  def __init__(self, element):
        self.element = element
        self.next = None

head = None

node1 = node(1)
node2 = node(2)

head = node1
node1.next = node2

while head != None:
    print(head.element)
    head = head.next

print(head.element)
</code>```

答:
The error is raised by your last line of code:

```<code>print(head.element)
</code>```

when/if the flow reaches the line above, the head variable is None, since the while loop ends only when head == None.

```<code>while head != None:
    print(head.element)
    head = head.next # The last time this will return None
</code>```

Body:
why in the code below when printing head.element inside the while loop I dont get any error
but the same code print code outside the loop get me an error?

class node:
  def __init__(self, element):
        self.element = element
        self.next = None

head = None

node1 = node(1)
node2 = node(2)

head = node1
node1.next = node2

while head != None:
    print(head.element)
    head = head.next

print(head.element)

Body:
The error is raised by your last line of code:

print(head.element)

when/if the flow reaches the line above, the head variable is None, since the while loop ends only when head == None.

while head != None:
    print(head.element)
    head = head.next # The last time this will return None


问:
How to switch external css file based on user input in rshiny?
I am looking to build a dark mode in my application. I realize we can achieve that using bs_theme(), but my application has many more settings in an external css file that do not get read when I use bs_theme().

I want to have 2 separate CSS files, one for light theme and one for dark theme. Based on the user input, the relevant theme file should be loaded in my Rshiny app. Any suggestion on how this could be done?

答:
I'd create two different css classes in this case.

Here you'll find how to include css files (as many as you like) into a shiny app.

To switch between the classes we can use addCssClass/ removeCssClass (or toggleCssClass) from library(shinyjs):

```<code>library(shiny)
library(shinyjs)

if(!dir.exists("www")){
  dir.create("www")
}

writeLines(".dark {
  background-color: black;
  color: white; /* text color */
}", con = "www/dark_mode.css")

writeLines(".light {
  background-color: white;
  color: black; /* text color */
}", con = "www/light_mode.css")

ui <- fluidPage(
  useShinyjs(),
  tags$head(
    tags$link(rel = "stylesheet", type = "text/css", href = "dark_mode.css"),
    tags$link(rel = "stylesheet", type = "text/css", href = "light_mode.css")
  ),
  radioButtons("mode", "Select mode", choices = c("dark", "light"), selected  = "light")
)

server <- function(input, output, session) {
  observeEvent(input$mode, {
    if(input$mode == "dark"){
      addCssClass(class = "dark", selector = "body")
      removeCssClass(class = "light", selector = "body")
    } else {
      addCssClass(class = "light", selector = "body")
      removeCssClass(class = "dark", selector = "body")
    }
  })
}

shinyApp(ui, server)
</code>```

The same can be done via Shiny.addCustomMessageHandler and some custom JS using e.g. element.classList.add("myclass"); (see this).

Edit: Apply addCssClass to inputs of different classes:

```<code>library(shiny)
library(shinyjs)

if(!dir.exists("www")){
  dir.create("www")
}

writeLines(".dark {
  background-color: black !important;
  color: white; /* text color */
}", con = "www/dark_mode.css")

writeLines(".light {
  background-color: white !important;
  color: black; /* text color */
}", con = "www/light_mode.css")

ui <- fluidPage(
  useShinyjs(),
  tags$head(
    tags$link(rel = "stylesheet", type = "text/css", href = "dark_mode.css"),
    tags$link(rel = "stylesheet", type = "text/css", href = "light_mode.css")
  ),
  radioButtons("mode", "Select mode", choices = c("dark", "light"), selected  = "light"),
  selectizeInput("Test", "Test Input", choices = 1:10),
  actionButton("testButton", "Test Button")
)

server <- function(input, output, session) {
  observeEvent(input$mode, {
    applyTo <- list(".selectize-input", ".btn-default")
    if(input$mode == "dark"){
      lapply(applyTo, function(x){
        addCssClass(class = "dark", selector = x)
        removeCssClass(class = "light", selector = x)
      })
    } else {
      lapply(applyTo, function(x){
        addCssClass(class = "light", selector = x)
        removeCssClass(class = "dark", selector = x)
      })
    }
  })
}

shinyApp(ui, server)
</code>```

Edit: using forEach:

```<code>library(shiny)
library(shinyjs)

if(!dir.exists("www")){
  dir.create("www")
}

writeLines(".dark {
  background-color: black !important;
  color: white; /* text color */
}", con = "www/dark_mode.css")

writeLines(".light {
  background-color: white !important;
  color: black; /* text color */
}", con = "www/light_mode.css")

ui <- fluidPage(
  useShinyjs(),
  tags$head(
    tags$link(rel = "stylesheet", type = "text/css", href = "dark_mode.css"),
    tags$link(rel = "stylesheet", type = "text/css", href = "light_mode.css")
  ),
  radioButtons("mode", "Select mode", choices = c("dark", "light"), selected  = "light"),
  selectizeInput("Test", "Test Input", choices = 1:10),
  actionButton("testButton", "Test Button")
)

server <- function(input, output, session) {

  dm_classes <- paste(c(".selectize-input", ".btn-default"), collapse = ", ")

  observeEvent(input$mode, {
    if(input$mode == "dark"){
      runjs(sprintf("document.querySelectorAll('%s').forEach(x=>x.classList.add('dark'));
                     document.querySelectorAll('%s').forEach(x=>x.classList.remove('light'));", dm_classes, dm_classes))
    } else {
      runjs(sprintf("document.querySelectorAll('%s').forEach(x=>x.classList.add('light'));
                     document.querySelectorAll('%s').forEach(x=>x.classList.remove('dark'));", dm_classes, dm_classes))
    }
  })
}

shinyApp(ui, server)
</code>```

Body:
I'd create two different css classes in this case.

Here you'll find how to include css files (as many as you like) into a shiny app.

To switch between the classes we can use addCssClass/ removeCssClass (or toggleCssClass) from library(shinyjs):

library(shiny)
library(shinyjs)

if(!dir.exists("www")){
  dir.create("www")
}

writeLines(".dark {
  background-color: black;
  color: white; /* text color */
}", con = "www/dark_mode.css")

writeLines(".light {
  background-color: white;
  color: black; /* text color */
}", con = "www/light_mode.css")

ui <- fluidPage(
  useShinyjs(),
  tags$head(
    tags$link(rel = "stylesheet", type = "text/css", href = "dark_mode.css"),
    tags$link(rel = "stylesheet", type = "text/css", href = "light_mode.css")
  ),
  radioButtons("mode", "Select mode", choices = c("dark", "light"), selected  = "light")
)

server <- function(input, output, session) {
  observeEvent(input$mode, {
    if(input$mode == "dark"){
      addCssClass(class = "dark", selector = "body")
      removeCssClass(class = "light", selector = "body")
    } else {
      addCssClass(class = "light", selector = "body")
      removeCssClass(class = "dark", selector = "body")
    }
  })
}

shinyApp(ui, server)

The same can be done via Shiny.addCustomMessageHandler and some custom JS using e.g. element.classList.add("myclass"); (see this).

Edit: Apply addCssClass to inputs of different classes:

library(shiny)
library(shinyjs)

if(!dir.exists("www")){
  dir.create("www")
}

writeLines(".dark {
  background-color: black !important;
  color: white; /* text color */
}", con = "www/dark_mode.css")

writeLines(".light {
  background-color: white !important;
  color: black; /* text color */
}", con = "www/light_mode.css")

ui <- fluidPage(
  useShinyjs(),
  tags$head(
    tags$link(rel = "stylesheet", type = "text/css", href = "dark_mode.css"),
    tags$link(rel = "stylesheet", type = "text/css", href = "light_mode.css")
  ),
  radioButtons("mode", "Select mode", choices = c("dark", "light"), selected  = "light"),
  selectizeInput("Test", "Test Input", choices = 1:10),
  actionButton("testButton", "Test Button")
)

server <- function(input, output, session) {
  observeEvent(input$mode, {
    applyTo <- list(".selectize-input", ".btn-default")
    if(input$mode == "dark"){
      lapply(applyTo, function(x){
        addCssClass(class = "dark", selector = x)
        removeCssClass(class = "light", selector = x)
      })
    } else {
      lapply(applyTo, function(x){
        addCssClass(class = "light", selector = x)
        removeCssClass(class = "dark", selector = x)
      })
    }
  })
}

shinyApp(ui, server)

Edit: using forEach:

library(shiny)
library(shinyjs)

if(!dir.exists("www")){
  dir.create("www")
}

writeLines(".dark {
  background-color: black !important;
  color: white; /* text color */
}", con = "www/dark_mode.css")

writeLines(".light {
  background-color: white !important;
  color: black; /* text color */
}", con = "www/light_mode.css")

ui <- fluidPage(
  useShinyjs(),
  tags$head(
    tags$link(rel = "stylesheet", type = "text/css", href = "dark_mode.css"),
    tags$link(rel = "stylesheet", type = "text/css", href = "light_mode.css")
  ),
  radioButtons("mode", "Select mode", choices = c("dark", "light"), selected  = "light"),
  selectizeInput("Test", "Test Input", choices = 1:10),
  actionButton("testButton", "Test Button")
)

server <- function(input, output, session) {

  dm_classes <- paste(c(".selectize-input", ".btn-default"), collapse = ", ")

  observeEvent(input$mode, {
    if(input$mode == "dark"){
      runjs(sprintf("document.querySelectorAll('%s').forEach(x=>x.classList.add('dark'));
                     document.querySelectorAll('%s').forEach(x=>x.classList.remove('light'));", dm_classes, dm_classes))
    } else {
      runjs(sprintf("document.querySelectorAll('%s').forEach(x=>x.classList.add('light'));
                     document.querySelectorAll('%s').forEach(x=>x.classList.remove('dark'));", dm_classes, dm_classes))
    }
  })
}

shinyApp(ui, server)


问:
3.16 LAB: Simple statistics Java
Part 1:
Given 4 integers, output their product and their average, using integer arithmetic.

Ex: If the input is:

8, 10, 5, 4
the output is:

```<code>1600 6
</code>```

Note: Integer division discards the fraction. Hence the average of 8, 10, 5, 4 is output as 6, not 6.75.

Note: The test cases include four very large input values whose product results in overflow. You do not need to do anything special, but just observe that the output does not represent the correct product (in fact, four positive numbers yield a negative output; wow).

Submit the above for grading. Your program will fail the last test cases (which is expected), until you complete part 2 below.

Part 2:
Also output the product and average, using floating-point arithmetic.

Output each floating-point value with three digits after the decimal point, which can be achieved as follows:
System.out.printf("%.3f", yourValue);

Ex: If the input is 8, 10, 5, 4, the output is:

```<code>1600. 6

1600.000 6.750
</code>```

Note that fractions aren't discarded, and that overflow does not occur for the test case with large values.

What I have,

```<code>import java.util.Scanner;

public class LabProgram {

  public static void main(String[] args) {

      Scanner scnr = new Scanner(System.in);
      int num1;
      int num2;
      int num3;
      int num4;

        num1 = scnr.nextInt();
        num2 = scnr.nextInt();
        num3 = scnr.nextInt();
        num4 = scnr.nextInt();

        double average_arith = (num1+num2+num3+num4)/4.0;
        double product_arith = num1*num2*num3*num4;

        int result1 = (int) average_arith;
        int result2 = (int) product_arith;

        System.out.printf("%d %d\n",result2,result1);
        System.out.printf("%.3f %.3f\n",product_arith,average_arith);

   }
}
</code>```

So When I input example numbers everything checks out except overflow,

```<code>input: 100000 200000 300000 500000
</code>```

Expected output:

```<code>-1679818752 275000

 3000000000000000000000.000 275000.000
</code>```

My output:

```<code>-1679818752 275000

-1679818752.000 275000.000
</code>```

Any help please?

答:
try using this code</p>
```<code>  int average;
  average = (num1 * num2 * num3 * num4);
  int product;
  product = (num1 + num2 + num3 + num4) / 4;
  double product2;
  double average2;
  average2 = ((double)num1 + num2 + num3 + num4 / 4.0);
  product2 = ((double)num1 * num2 * num3 * num4);

</code>```

Title: 3.16 LAB: Simple statistics Java

Body:
Part 1:
Given 4 integers, output their product and their average, using integer arithmetic.

Ex: If the input is:

8, 10, 5, 4
the output is:

1600 6

Note: Integer division discards the fraction. Hence the average of 8, 10, 5, 4 is output as 6, not 6.75.

Note: The test cases include four very large input values whose product results in overflow. You do not need to do anything special, but just observe that the output does not represent the correct product (in fact, four positive numbers yield a negative output; wow).

Submit the above for grading. Your program will fail the last test cases (which is expected), until you complete part 2 below.

Part 2:
Also output the product and average, using floating-point arithmetic.

Output each floating-point value with three digits after the decimal point, which can be achieved as follows:
System.out.printf("%.3f", yourValue);

Ex: If the input is 8, 10, 5, 4, the output is:

1600. 6

1600.000 6.750

Note that fractions aren't discarded, and that overflow does not occur for the test case with large values.

What I have,

import java.util.Scanner;

public class LabProgram {

  public static void main(String[] args) {

      Scanner scnr = new Scanner(System.in);
      int num1;
      int num2;
      int num3;
      int num4;

        num1 = scnr.nextInt();
        num2 = scnr.nextInt();
        num3 = scnr.nextInt();
        num4 = scnr.nextInt();

        double average_arith = (num1+num2+num3+num4)/4.0;
        double product_arith = num1*num2*num3*num4;

        int result1 = (int) average_arith;
        int result2 = (int) product_arith;

        System.out.printf("%d %d\n",result2,result1);
        System.out.printf("%.3f %.3f\n",product_arith,average_arith);

   }
}

So When I input example numbers everything checks out except overflow,

input: 100000 200000 300000 500000

Expected output:

-1679818752 275000

 3000000000000000000000.000 275000.000

My output:

-1679818752 275000

-1679818752.000 275000.000

Any help please?

Body:
try using this code

  int average;
  average = (num1 * num2 * num3 * num4);
  int product;
  product = (num1 + num2 + num3 + num4) / 4;
  double product2;
  double average2;
  average2 = ((double)num1 + num2 + num3 + num4 / 4.0);
  product2 = ((double)num1 * num2 * num3 * num4);


问:
Autofac contravariance and resolving open generic types
When resolving all implementations of a generic type (with a contravariant T) from autofac I'd like to get all possible contravariant matches. This only works when registering the ContravariantRegistrationSource. But then I get too much instances for open generic implementations because it walks the inheritance tree gives me an instance per subclass.

This might sound a bit abstract, so here's 2 unit tests that demonstrate the problem. They both fail, but I'd like to get at least one of them working:

```<code>using Autofac;
using FluentAssertions;
using System.Collections.Generic;
using Xunit;
using Autofac.Features.Variance;

namespace Aiv.Vbr.QueryService.WebApi.Test.AdresMatchTests
{
    public class TestAutofacGenerics
    {
        public interface IGenericInterface<in T> { }
        public class GenericImplementation<T> : IGenericInterface<T> { }
        public class SpecificImplementation : IGenericInterface<TClass> { }
        public class TInterfaceImplementation : IGenericInterface<TInterface> { }
        public interface TInterface { }
        public class TClass : TInterface { }

        [Fact]
        public void AutofacShouldAlsoResolveContravariantImplementations()
        {
            var builder = new ContainerBuilder();
            builder.RegisterType<SpecificImplementation>().As<IGenericInterface<TClass>>();
            builder.RegisterType<TInterfaceImplementation>().As<IGenericInterface<TInterface>>();
            builder.RegisterGeneric(typeof(GenericImplementation<>)).As(typeof(IGenericInterface<>));

            var instances = builder.Build().Resolve<IEnumerable<IGenericInterface<TClass>>>();

            //This fails: only 2 types get resolved: GenericImplementation<TClass> and SpecificImplementation
            //but also expected TInterfaceImplementation
            instances.Should().HaveCount(3);
        }

        [Fact]
        public void AutofacShouldOnlyResolveOpenGenericsForSpecifiedClass()
        {
            var builder = new ContainerBuilder();
            builder.RegisterSource(new ContravariantRegistrationSource());
            builder.RegisterType<SpecificImplementation>().As<IGenericInterface<TClass>>();
            builder.RegisterType<TInterfaceImplementation>().As<IGenericInterface<TInterface>>();
            builder.RegisterGeneric(typeof(GenericImplementation<>)).As(typeof(IGenericInterface<>));

            var instances = builder.Build().Resolve<IEnumerable<IGenericInterface<TClass>>>();

            //This fails: 5 types get resolved: GenericImplementation<TClass>, GenericImplementation<Object>,
            // GenericImplementation<TInterface>, SpecificImplementation and TInteraceImplementation
            //but did not want GenericImplementation<Object> and GenericImplementation<TInterface>
            instances.Should().HaveCount(3);
        }
    }
}
</code>```

The issue is described here and a possible solution suggested is to use a custom ContravariantRegistrationSource which is scoped, but I fail to see how this can resolve my issue.
What can I do?

答:
The issue is related to how ContravariantRegistrationSource and RegisterGeneric works

When you resolve GenericImplementation<TClass>
ContravariantRegistrationSource will try to resolve

```<code>GenericImplementation<TClass>
GenericImplementation<Object>
GenericImplementation<TInterface>
</code>```

because you have

```<code>builder.RegisterGeneric(typeof(GenericImplementation<>))
       .As(typeof(IGenericInterface<>));
</code>```

Autofac will returns registration for each of them.

It is the expected behavior and unfortunately there is no easy way to fix it.

I had the same issue with MediatR and INotificationHandler, I ended by doing my own IRegistrationSource.

```<code>/// <summary>
/// Returns contravariant registration source without duplicator target.
///
/// <see cref="ContravariantRegistrationSource" /> returns all contravariant implementation of a type.
/// For example when we resolve IEnumerable<INotificationHandler<SpecificCommand>> it will returns a collection with GenericHandler<SpecificCommand>, GenericHandler<BaseCommand>, SpecificCommandHandler
/// this registration source will first look up for the native registrations and then group registration based on activator limit type.
/// </summary>
/// <remarks>See https://stackoverflow.com/questions/46464944/autofac-contravariance-and-resolving-open-generic-types </remarks>
public class ExplicitContravariantRegistrationSource : IRegistrationSource
{
    private readonly IRegistrationSource _source = new ContravariantRegistrationSource();
    private readonly Type _type;

    public ExplicitContravariantRegistrationSource(Type type)
    {
        if (type == null)
        {
            throw new ArgumentNullException(nameof(type));
        }
        if (!type.IsGenericTypeDefinition)
        {
            throw new ArgumentException("Type should be a generic type definition", nameof(type));
        }
        this._type = type;
    }

    public IEnumerable<IComponentRegistration> RegistrationsFor(
        Service service,
        Func<Service, IEnumerable<ServiceRegistration>> registrationAccessor)
    {
        if (service is IServiceWithType st
                && st.ServiceType.IsGenericType
                && this._type == st.ServiceType.GetGenericTypeDefinition())
        {

            // get all non contravariant registration source
            var originalRegistrations = registrationAccessor(service).ToArray();

            var components = _source
                                // retrieve all contravariant registration source
                                .RegistrationsFor(service, registrationAccessor)
                                // Group will ensure having only a single registration of a activator limit type
                                .GroupBy(this.GetTargetTypeDefinitionOrSelf)
                                // exclude groups if autofac already resolved the same activator limit type
                                .Where(o => !originalRegistrations.Select(oo => this.GetTargetTypeDefinitionOrSelf(oo.Registration)).Contains(o.Key))
                                // taking the last is the default behavior for autofac, it can be improved
                                .Select(o => o.Last());
            return components;
        }
        else
        {
            return Enumerable.Empty<IComponentRegistration>();
        }
    }

    private Type GetTargetTypeDefinitionOrSelf(IComponentRegistration componentRegistration)
    {
        return componentRegistration.Target.Activator.LimitType.IsGenericType ?
                    componentRegistration.Target.Activator.LimitType.GetGenericTypeDefinition()
                    : componentRegistration.Target.Activator.LimitType;
    }

    public bool IsAdapterForIndividualComponents => _source.IsAdapterForIndividualComponents;
}
</code>```

and I use it like this :

```<code>builder.RegisterSource(new ExplicitContravariantRegistrationSource(typeof(INotificationHandler<>)));
</code>```

Body:
When resolving all implementations of a generic type (with a contravariant T) from autofac I'd like to get all possible contravariant matches. This only works when registering the ContravariantRegistrationSource. But then I get too much instances for open generic implementations because it walks the inheritance tree gives me an instance per subclass.

This might sound a bit abstract, so here's 2 unit tests that demonstrate the problem. They both fail, but I'd like to get at least one of them working:

using Autofac;
using FluentAssertions;
using System.Collections.Generic;
using Xunit;
using Autofac.Features.Variance;

namespace Aiv.Vbr.QueryService.WebApi.Test.AdresMatchTests
{
    public class TestAutofacGenerics
    {
        public interface IGenericInterface<in T> { }
        public class GenericImplementation<T> : IGenericInterface<T> { }
        public class SpecificImplementation : IGenericInterface<TClass> { }
        public class TInterfaceImplementation : IGenericInterface<TInterface> { }
        public interface TInterface { }
        public class TClass : TInterface { }

        [Fact]
        public void AutofacShouldAlsoResolveContravariantImplementations()
        {
            var builder = new ContainerBuilder();
            builder.RegisterType<SpecificImplementation>().As<IGenericInterface<TClass>>();
            builder.RegisterType<TInterfaceImplementation>().As<IGenericInterface<TInterface>>();
            builder.RegisterGeneric(typeof(GenericImplementation<>)).As(typeof(IGenericInterface<>));

            var instances = builder.Build().Resolve<IEnumerable<IGenericInterface<TClass>>>();

            //This fails: only 2 types get resolved: GenericImplementation<TClass> and SpecificImplementation
            //but also expected TInterfaceImplementation
            instances.Should().HaveCount(3);
        }

        [Fact]
        public void AutofacShouldOnlyResolveOpenGenericsForSpecifiedClass()
        {
            var builder = new ContainerBuilder();
            builder.RegisterSource(new ContravariantRegistrationSource());
            builder.RegisterType<SpecificImplementation>().As<IGenericInterface<TClass>>();
            builder.RegisterType<TInterfaceImplementation>().As<IGenericInterface<TInterface>>();
            builder.RegisterGeneric(typeof(GenericImplementation<>)).As(typeof(IGenericInterface<>));

            var instances = builder.Build().Resolve<IEnumerable<IGenericInterface<TClass>>>();

            //This fails: 5 types get resolved: GenericImplementation<TClass>, GenericImplementation<Object>,
            // GenericImplementation<TInterface>, SpecificImplementation and TInteraceImplementation
            //but did not want GenericImplementation<Object> and GenericImplementation<TInterface>
            instances.Should().HaveCount(3);
        }
    }
}

The issue is described here and a possible solution suggested is to use a custom ContravariantRegistrationSource which is scoped, but I fail to see how this can resolve my issue.
What can I do?

Body:
The issue is related to how ContravariantRegistrationSource and RegisterGeneric works

When you resolve GenericImplementation<TClass>
ContravariantRegistrationSource will try to resolve

GenericImplementation<TClass>
GenericImplementation<Object>
GenericImplementation<TInterface>

because you have

builder.RegisterGeneric(typeof(GenericImplementation<>))
       .As(typeof(IGenericInterface<>));

Autofac will returns registration for each of them.

It is the expected behavior and unfortunately there is no easy way to fix it.

I had the same issue with MediatR and INotificationHandler, I ended by doing my own IRegistrationSource.

/// <summary>
/// Returns contravariant registration source without duplicator target.
///
/// <see cref="ContravariantRegistrationSource" /> returns all contravariant implementation of a type.
/// For example when we resolve IEnumerable&lt;INotificationHandler&lt;SpecificCommand&gt;&gt; it will returns a collection with GenericHandler&lt;SpecificCommand&gt;, GenericHandler&lt;BaseCommand&gt;, SpecificCommandHandler
/// this registration source will first look up for the native registrations and then group registration based on activator limit type.
/// </summary>
/// <remarks>See https://stackoverflow.com/questions/46464944/autofac-contravariance-and-resolving-open-generic-types </remarks>
public class ExplicitContravariantRegistrationSource : IRegistrationSource
{
    private readonly IRegistrationSource _source = new ContravariantRegistrationSource();
    private readonly Type _type;

    public ExplicitContravariantRegistrationSource(Type type)
    {
        if (type == null)
        {
            throw new ArgumentNullException(nameof(type));
        }
        if (!type.IsGenericTypeDefinition)
        {
            throw new ArgumentException("Type should be a generic type definition", nameof(type));
        }
        this._type = type;
    }

    public IEnumerable<IComponentRegistration> RegistrationsFor(
        Service service,
        Func<Service, IEnumerable<ServiceRegistration>> registrationAccessor)
    {
        if (service is IServiceWithType st
                && st.ServiceType.IsGenericType
                && this._type == st.ServiceType.GetGenericTypeDefinition())
        {

            // get all non contravariant registration source
            var originalRegistrations = registrationAccessor(service).ToArray();

            var components = _source
                                // retrieve all contravariant registration source
                                .RegistrationsFor(service, registrationAccessor)
                                // Group will ensure having only a single registration of a activator limit type
                                .GroupBy(this.GetTargetTypeDefinitionOrSelf)
                                // exclude groups if autofac already resolved the same activator limit type
                                .Where(o => !originalRegistrations.Select(oo => this.GetTargetTypeDefinitionOrSelf(oo.Registration)).Contains(o.Key))
                                // taking the last is the default behavior for autofac, it can be improved
                                .Select(o => o.Last());
            return components;
        }
        else
        {
            return Enumerable.Empty<IComponentRegistration>();
        }
    }

    private Type GetTargetTypeDefinitionOrSelf(IComponentRegistration componentRegistration)
    {
        return componentRegistration.Target.Activator.LimitType.IsGenericType ?
                    componentRegistration.Target.Activator.LimitType.GetGenericTypeDefinition()
                    : componentRegistration.Target.Activator.LimitType;
    }

    public bool IsAdapterForIndividualComponents => _source.IsAdapterForIndividualComponents;
}

and I use it like this :

builder.RegisterSource(new ExplicitContravariantRegistrationSource(typeof(INotificationHandler<>)));


答: In last iteration while loop, the head was asing None and you try to print the property element of class None.

Title: 'NoneType' object has no attribute 'element'


问:
How can I add data to a firestore array without overwriting it's previous content?
I'm trying to store book Ids in the books array in firestore. every time I add a new book it overwrites the first one.

```<code>await updateDoc(
  doc(dataBase, "users", user.uid),
  {
    currentlyReading: {
      arrayUnion(bookId)
    }
  },
  { merge: true }
);
</code>```

I'm using updateDoc as stated in the documentation + merge: true, but it only stores one element. is there any way I can keep adding elements without overwriting? Thank you in advance.

this is a screen shot of the Document

答:
The { merge: true } prevents from existing fields from being removed when using setDoc() and doesn't work for array elements. There's no need for that option when using updateDoc(). One way would be to use arrayUnion() add new elements to the array.

```<code>import { doc, updateDoc, arrayUnion } from "firebase/firestore"

await updateDoc(doc(dataBase, "users", (user.uid)), {
  currentlyReading:{
    books: arrayUnion(bookId)
  }
})
</code>```

Body:
I'm trying to store book Ids in the books array in firestore. every time I add a new book it overwrites the first one.

await updateDoc(
  doc(dataBase, "users", user.uid),
  {
    currentlyReading: {
      arrayUnion(bookId)
    }
  },
  { merge: true }
);

I'm using updateDoc as stated in the documentation + merge: true, but it only stores one element. is there any way I can keep adding elements without overwriting? Thank you in advance.

this is a screen shot of the Document

Body:
The { merge: true } prevents from existing fields from being removed when using setDoc() and doesn't work for array elements. There's no need for that option when using updateDoc(). One way would be to use arrayUnion() add new elements to the array.

import { doc, updateDoc, arrayUnion } from "firebase/firestore"

await updateDoc(doc(dataBase, "users", (user.uid)), {
  currentlyReading:{
    books: arrayUnion(bookId)
  }
})


问:
How do I import modules in the Factor interpreter?
I'm following the Sam's decipher tutorial. When he does 8 group, on my computer Factor gripes that it doesn't know the group function.

```<code>( scratchpad ) "01101001001000000110011001110101011000110110101101100101011001000010000001111001011011110111010101110010001000000110110101101111011011010000110100001010011000010110111001100100001000000110111001101111011101110010000001100110011011110111001000100000011110010110111101110101"

--- Data stack:
"0110100100100000011001100111010101100011011010110110010101100..."
( scratchpad ) 8 group
1: 8 group
          ^
No word named “group” found in current vocabulary search path

The following restarts are available:

:1      Use the grouping vocabulary
:2      Use the unix.ffi vocabulary
:3      Use the unix.groups vocabulary
4 :res  Defer word in current vocabulary

Type :help for debugging help.
</code>```

Apparently group is located in the grouping module, but I don't know how to import the module in the interpreter (something like +m module in Haskell's GHCi).

答:
In the interpreter, type USE: grouping ; to add a single vocabulary to the search path, or USING: a b c ; to add a list of vocabularies.

Documentation: USE: USING:.

Body:
I'm following the Sam's decipher tutorial. When he does 8 group, on my computer Factor gripes that it doesn't know the group function.

( scratchpad ) "01101001001000000110011001110101011000110110101101100101011001000010000001111001011011110111010101110010001000000110110101101111011011010000110100001010011000010110111001100100001000000110111001101111011101110010000001100110011011110111001000100000011110010110111101110101"

--- Data stack:
"0110100100100000011001100111010101100011011010110110010101100..."
( scratchpad ) 8 group
1: 8 group
          ^
No word named “group” found in current vocabulary search path

The following restarts are available:

:1      Use the grouping vocabulary
:2      Use the unix.ffi vocabulary
:3      Use the unix.groups vocabulary
4 :res  Defer word in current vocabulary

Type :help for debugging help.

Apparently group is located in the grouping module, but I don't know how to import the module in the interpreter (something like +m module in Haskell's GHCi).


问:
Look up from a dictionary to fill pandas DataFrame with a condition
I have a dictionary that's something like this.

```<code>d = {
     "p1": ["$0.00", nan, "$25.00"],
     "p2": ["$30.25", nan, "$12.25"],
     "p3": ["$0.00"],
     "p4": [nan, "$15.00"]
    }
</code>```

I'd like to look up values from the dictionary and assign them to a column in pandas DataFrame. The DataFrame is something like this:

```<code>df = pd.DataFrame({
                   'name': ["p1","p2","p3","p4"],
                   'val': [np.nan, np.nan, 4, np.nan]
                   })
</code>```

Assignment:

```<code>def fun(name):

    # look up from dict

    # apply condition

    return

df['val'] = df.apply(lambda x: func(x['name']), axis=1)
</code>```

For the assignment, the condition is to find the largest value from the dictionary, if length of the value pair > 0, i.e there is more than 1 element in the list. Note, the elements are stored as strings. So, need the function needs to convert them to float type.

Expected output:

答:
First rework your dictionary to keep the "highest" value with a custom key. Then perform a simple map:

```<code>d2 = {k: max((e for e in v if pd.notna(e)),
             key=lambda x: float(x.strip('$')) if isinstance(x, str) else x)
      for k,v in d.items()}
# {'p1': '$25.00', 'p2': '$30.25', 'p3': '$0.00', 'p4': '$15.00'}

df['val'] = df['name'].map(d2)
</code>```

output:

```<code>  name     val
0   p1  $25.00
1   p2  $30.25
2   p3   $0.00
3   p4  $15.00

</code>```

Body:
I have a dictionary that's something like this.

d = {
     "p1": ["$0.00", nan, "$25.00"],
     "p2": ["$30.25", nan, "$12.25"],
     "p3": ["$0.00"],
     "p4": [nan, "$15.00"]
    }

I'd like to look up values from the dictionary and assign them to a column in pandas DataFrame. The DataFrame is something like this:

df = pd.DataFrame({
                   'name': ["p1","p2","p3","p4"],
                   'val': [np.nan, np.nan, 4, np.nan]
                   })

Assignment:

def fun(name):

    # look up from dict

    # apply condition

    return

df['val'] = df.apply(lambda x: func(x['name']), axis=1)

For the assignment, the condition is to find the largest value from the dictionary, if length of the value pair > 0, i.e there is more than 1 element in the list. Note, the elements are stored as strings. So, need the function needs to convert them to float type.

Expected output:

Body:
First rework your dictionary to keep the "highest" value with a custom key. Then perform a simple map:

d2 = {k: max((e for e in v if pd.notna(e)),
             key=lambda x: float(x.strip('$')) if isinstance(x, str) else x)
      for k,v in d.items()}
# {'p1': '$25.00', 'p2': '$30.25', 'p3': '$0.00', 'p4': '$15.00'}

df['val'] = df['name'].map(d2)

output:

  name     val
0   p1  $25.00
1   p2  $30.25
2   p3   $0.00
3   p4  $15.00


问:
GeoDjango heroku 'DatabaseOperations' object has no attribute 'spatial_aggregate_name'
I'm trying to deploy my app on Heroku, which works locally but is throwing this error when deployed on heroku:

AttributeError : 'DatabaseOperations' object has no attribute 'spatial_aggregate_name'

For context I the api call that is triggering the error is trying to return all addresses from a table that are in a certain boundary.

my DATABASE settings in settings.py:

INSTALLED_APPS = [
    'map.apps.MapConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.postgres',
    'rest_framework',
    'django.contrib.gis',
    'coreapi',
    'listings',
    'drf_yasg',
]

DATABASES = {
    'default': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        'NAME': 'neighborhoods',
        'USER': 'django',
        'PASSWORD': db_pass,
        'HOST':'db_name.xxxxxxx.us-west-1.rds.amazonaws.com',
        'PORT':'5432'
    }
}

# Heroku: Update database configurations from $DATABASE_URL.
import dj_database_url
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)

# Activate Django-Heroku.
django_heroku.settings(locals(), staticfiles=False)
```
<p>I'm using the heroku goe buildpack.</p>
<p>I just can't seem to figure out why it is working locally but not on heroku.</p>
<p>Here is my traceback:</p>
```> Django Version: 4.0.2 Python Version: 3.9.4 Installed Applications:
> ['map.apps.MapConfig',  'django.contrib.admin',
> 'django.contrib.auth',  'django.contrib.contenttypes',
> 'django.contrib.sessions',  'django.contrib.messages',
> 'django.contrib.staticfiles',  'django.contrib.postgres',
> 'rest_framework',  'django.contrib.gis',  'coreapi',  'listings',
> 'drf_yasg'] Installed Middleware:
> ['django.middleware.security.SecurityMiddleware',
> 'whitenoise.middleware.WhiteNoiseMiddleware',
> 'django.contrib.sessions.middleware.SessionMiddleware',
> 'django.middleware.common.CommonMiddleware',
> 'django.middleware.csrf.CsrfViewMiddleware',
> 'django.contrib.auth.middleware.AuthenticationMiddleware',
> 'django.contrib.messages.middleware.MessageMiddleware',
> 'django.middleware.clickjacking.XFrameOptionsMiddleware']
>
>
>
> Traceback (most recent call last):   File
> "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/exception.py",
> line 47, in inner
>     response = get_response(request)   File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py",
> line 181, in _get_response
>     response = wrapped_callback(request, *callback_args, **callback_kwargs)   File "/app/.heroku/python/lib/python3.9/site-packages/django/views/decorators/csrf.py",
> line 54, in wrapped_view
>     return view_func(*args, **kwargs)   File "/app/.heroku/python/lib/python3.9/site-packages/django/views/generic/base.py",
> line 69, in view
>     return self.dispatch(request, *args, **kwargs)   File "/app/.heroku/python/lib/python3.9/site-packages/rest_framework/views.py",
> line 509, in dispatch
>     response = self.handle_exception(exc)   File "/app/.heroku/python/lib/python3.9/site-packages/rest_framework/views.py",
> line 469, in handle_exception
>     self.raise_uncaught_exception(exc)   File "/app/.heroku/python/lib/python3.9/site-packages/rest_framework/views.py",
> line 480, in raise_uncaught_exception
>     raise exc   File "/app/.heroku/python/lib/python3.9/site-packages/rest_framework/views.py",
> line 506, in dispatch
>     response = handler(request, *args, **kwargs)   File "/app/.heroku/python/lib/python3.9/site-packages/rest_framework/decorators.py",
> line 50, in handler
>     return func(*args, **kwargs)   File "/app/listings/views.py", line 62, in GetHomesInHood
>     home_recs = find_homes(   File "/app/listings/HomeFinder.py", line 205, in find_homes
>     filtered_listings = filter_listings_model(hood_ids, beds, baths)   File "/app/listings/HomeFinder.py", line 40, in filter_listings_model
>     hood_boundaries = NeighborhoodBoundaries.objects.filter(pk__in=neighborhood_ids).aggregate(Collect('geometry'))
> File
> "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/query.py",
> line 403, in aggregate
>     return query.get_aggregation(self.db, kwargs)   File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/sql/query.py",
> line 501, in get_aggregation
>     result = compiler.execute_sql(SINGLE)   File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/sql/compiler.py",
> line 1189, in execute_sql
>     sql, params = self.as_sql()   File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/sql/compiler.py",
> line 531, in as_sql
>     extra_select, order_by, group_by = self.pre_sql_setup()   File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/sql/compiler.py",
> line 59, in pre_sql_setup
>     self.setup_query()   File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/sql/compiler.py",
> line 50, in setup_query
>     self.select, self.klass_info, self.annotation_col_map = self.get_select()   File
> "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/sql/compiler.py",
> line 267, in get_select
>     sql, params = self.compile(col)   File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/sql/compiler.py",
> line 463, in compile
>     sql, params = node.as_sql(self, self.connection)   File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/gis/db/models/aggregates.py",
> line 25, in as_sql
>     function=function or connection.ops.spatial_aggregate_name(self.name),
>
> Exception Type: AttributeError at /listings/neighborhood/ Exception
> Value: 'DatabaseOperations' object has no attribute
> 'spatial_aggregate_name'
```

I just can't seem to pinpoint what is changing about the heroku setup and why it is not finding necessary attributes like 'spacial_aggregate_name'.  Any help is greatly appreciated :)

答:
This may be a patch rather than a solution, but I am able to get it to work if I make the following adjustments in settings.py.  Commenting out the following settings:

```<code># Heroku: Update database configurations from $DATABASE_URL.
#import dj_database_url
# db_from_env = dj_database_url.config(conn_max_age=500,
#                                      engine = 'django.contrib.gis.db.backends.postgis',
#                                     )
# DATABASES['default'].update(db_from_env)

# Activate Django-Heroku.
# django_heroku.settings(locals(), staticfiles=False)
</code>```

it seems these lines were changing the settings in heroku to use a different postgresql instance setup via heroku-postgres instead of the database I already had setup properly.

Hopefully there is no need for those lines.

Body:
I'm trying to deploy my app on Heroku, which works locally but is throwing this error when deployed on heroku:

AttributeError : 'DatabaseOperations' object has no attribute 'spatial_aggregate_name'

For context I the api call that is triggering the error is trying to return all addresses from a table that are in a certain boundary.

my DATABASE settings in settings.py:

INSTALLED_APPS = [
    'map.apps.MapConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.postgres',
    'rest_framework',
    'django.contrib.gis',
    'coreapi',
    'listings',
    'drf_yasg',
]

DATABASES = {
    'default': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        'NAME': 'neighborhoods',
        'USER': 'django',
        'PASSWORD': db_pass,
        'HOST':'db_name.xxxxxxx.us-west-1.rds.amazonaws.com',
        'PORT':'5432'
    }
}

# Heroku: Update database configurations from $DATABASE_URL.
import dj_database_url
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)

# Activate Django-Heroku.
django_heroku.settings(locals(), staticfiles=False)

I'm using the heroku goe buildpack.

I just can't seem to figure out why it is working locally but not on heroku.

Here is my traceback:

> Django Version: 4.0.2 Python Version: 3.9.4 Installed Applications:
> ['map.apps.MapConfig',  'django.contrib.admin',
> 'django.contrib.auth',  'django.contrib.contenttypes',
> 'django.contrib.sessions',  'django.contrib.messages',
> 'django.contrib.staticfiles',  'django.contrib.postgres',
> 'rest_framework',  'django.contrib.gis',  'coreapi',  'listings',
> 'drf_yasg'] Installed Middleware:
> ['django.middleware.security.SecurityMiddleware',
> 'whitenoise.middleware.WhiteNoiseMiddleware',
> 'django.contrib.sessions.middleware.SessionMiddleware',
> 'django.middleware.common.CommonMiddleware',
> 'django.middleware.csrf.CsrfViewMiddleware',
> 'django.contrib.auth.middleware.AuthenticationMiddleware',
> 'django.contrib.messages.middleware.MessageMiddleware',
> 'django.middleware.clickjacking.XFrameOptionsMiddleware']
>
>
>
> Traceback (most recent call last):   File
> "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/exception.py",
> line 47, in inner
>     response = get_response(request)   File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py",
> line 181, in _get_response
>     response = wrapped_callback(request, *callback_args, **callback_kwargs)   File "/app/.heroku/python/lib/python3.9/site-packages/django/views/decorators/csrf.py",
> line 54, in wrapped_view
>     return view_func(*args, **kwargs)   File "/app/.heroku/python/lib/python3.9/site-packages/django/views/generic/base.py",
> line 69, in view
>     return self.dispatch(request, *args, **kwargs)   File "/app/.heroku/python/lib/python3.9/site-packages/rest_framework/views.py",
> line 509, in dispatch
>     response = self.handle_exception(exc)   File "/app/.heroku/python/lib/python3.9/site-packages/rest_framework/views.py",
> line 469, in handle_exception
>     self.raise_uncaught_exception(exc)   File "/app/.heroku/python/lib/python3.9/site-packages/rest_framework/views.py",
> line 480, in raise_uncaught_exception
>     raise exc   File "/app/.heroku/python/lib/python3.9/site-packages/rest_framework/views.py",
> line 506, in dispatch
>     response = handler(request, *args, **kwargs)   File "/app/.heroku/python/lib/python3.9/site-packages/rest_framework/decorators.py",
> line 50, in handler
>     return func(*args, **kwargs)   File "/app/listings/views.py", line 62, in GetHomesInHood
>     home_recs = find_homes(   File "/app/listings/HomeFinder.py", line 205, in find_homes
>     filtered_listings = filter_listings_model(hood_ids, beds, baths)   File "/app/listings/HomeFinder.py", line 40, in filter_listings_model
>     hood_boundaries = NeighborhoodBoundaries.objects.filter(pk__in=neighborhood_ids).aggregate(Collect('geometry'))
> File
> "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/query.py",
> line 403, in aggregate
>     return query.get_aggregation(self.db, kwargs)   File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/sql/query.py",
> line 501, in get_aggregation
>     result = compiler.execute_sql(SINGLE)   File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/sql/compiler.py",
> line 1189, in execute_sql
>     sql, params = self.as_sql()   File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/sql/compiler.py",
> line 531, in as_sql
>     extra_select, order_by, group_by = self.pre_sql_setup()   File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/sql/compiler.py",
> line 59, in pre_sql_setup
>     self.setup_query()   File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/sql/compiler.py",
> line 50, in setup_query
>     self.select, self.klass_info, self.annotation_col_map = self.get_select()   File
> "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/sql/compiler.py",
> line 267, in get_select
>     sql, params = self.compile(col)   File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/sql/compiler.py",
> line 463, in compile
>     sql, params = node.as_sql(self, self.connection)   File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/gis/db/models/aggregates.py",
> line 25, in as_sql
>     function=function or connection.ops.spatial_aggregate_name(self.name),
>
> Exception Type: AttributeError at /listings/neighborhood/ Exception
> Value: 'DatabaseOperations' object has no attribute
> 'spatial_aggregate_name'

I just can't seem to pinpoint what is changing about the heroku setup and why it is not finding necessary attributes like 'spacial_aggregate_name'.  Any help is greatly appreciated :)

Body:
This may be a patch rather than a solution, but I am able to get it to work if I make the following adjustments in settings.py.  Commenting out the following settings:

# Heroku: Update database configurations from $DATABASE_URL.
#import dj_database_url
# db_from_env = dj_database_url.config(conn_max_age=500,
#                                      engine = 'django.contrib.gis.db.backends.postgis',
#                                     )
# DATABASES['default'].update(db_from_env)

# Activate Django-Heroku.
# django_heroku.settings(locals(), staticfiles=False)

it seems these lines were changing the settings in heroku to use a different postgresql instance setup via heroku-postgres instead of the database I already had setup properly.

Hopefully there is no need for those lines.