问:
How to paint specific rows in a listbox (WPF app)
I am writing a project that includes a WPF window that contains a listbox. the listbox is uses binding to a list of tasks (a class I've created). I am trying to have some specific rows of the listbox painted and some specific rows to have colored borders based on the fields of the items in the list. how do i add a paint/brush method for specific rows to a listbox and not the whole listbox?
Below is the XAML properties of the listbox:</p>

```<code><ListBox Name="Tasks" HorizontalAlignment="Left" ItemsSource="{Binding Path=Tasks,Mode=TwoWay}" Height="199" Margin="303,97,0,0" VerticalAlignment="Top" Width="439" RenderTransformOrigin="0.5,0.5">
            <ListBox.RenderTransform>
                <TransformGroup>
                    <ScaleTransform/>
                    <SkewTransform/>
                    <RotateTransform Angle="0.294"/>
                    <TranslateTransform/>
                </TransformGroup>
            </ListBox.RenderTransform>
        </ListBox>
</code>```

答:
The ItemsControl has a special feature for selecting templates for items shown in the control. In the following sample I illustrate the use of the DataTemplateSelector

First the XAML. In the Resource  section different data templates are defined for the different types of items you want to show in the ListBox, and there is a reference to the DataTemplateSelector (defined in the C# code later):

```<code><Window x:Class="TestWpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:TestWpfApp"
        mc:Ignorable="d"
        x:Name="DataWindow"
        WindowState="Maximized"
        Title="MainWindow" Height="450" Width="800">
   <Window.Resources>
      <!-- The data template selector -->
      <local:DataItemTemplateSelector x:Key="DataItemTemplateSelector"/>
      <!-- Data template for a normal data item -->
      <DataTemplate x:Key="NormalDatatemplate">
         <Border Width="200"
                 Margin="0"
                 Background="White"
                 BorderThickness="2"
                 Padding="3"
                 BorderBrush="Transparent">
            <TextBlock VerticalAlignment="Center"
                       HorizontalAlignment="Stretch"
                       FontSize="20"
                       Foreground="Black"
                       Background="Transparent"
                       Text="{Binding Path=Header}"/>
         </Border>
      </DataTemplate>
      <!-- Data template for a special data item -->
      <DataTemplate x:Key="SpecialDatatemplate">
         <Border Width="200"
                 Margin="0"
                 Background="Yellow"
                 BorderThickness="2"
                 Padding="3"
                 BorderBrush="Blue">
            <TextBlock VerticalAlignment="Center"
                       HorizontalAlignment="Stretch"
                       FontSize="20"
                       Foreground="Black"
                       Background="Transparent"
                       Text="{Binding Path=Header}"/>
         </Border>
      </DataTemplate>
   </Window.Resources>
   <Grid>
      <ListBox x:Name="DataListBox"
               Margin="50"
               Width="Auto"
               Height="Auto"
               HorizontalAlignment="Center"
               VerticalAlignment="Top"
               ItemsSource="{Binding ElementName=DataWindow, Path=DataList}"
               ItemTemplateSelector="{StaticResource ResourceKey=DataItemTemplateSelector}"/>
   </Grid>
</Window>
</code>```

And then the C# code, there the DataItemTemplateSelector is defined and the DataList with some testdata:

```<code>using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;

namespace TestWpfApp
{
   // Different types of items on the list
   public enum DataItemType
   {
      Normal,
      Special
   }
   // Items on the list
   public class DataItem
   {
      public string Header { set; get; }
      public DataItemType DataType { set; get; }
   }
   // Data template selector for items on the list
   public class DataItemTemplateSelector : DataTemplateSelector
   {
      public override DataTemplate SelectTemplate(object dataItem, DependencyObject container)
      {
         // Check that everyting is OK
         if ((dataItem != null) && (dataItem is DataItem))
         {
            // Switch on the data type
            switch (((DataItem)(dataItem)).DataType)
            {
               case DataItemType.Normal:
                  // Return the data template for a normal data item
                  return Application.Current.MainWindow.FindResource("NormalDatatemplate") as DataTemplate;
               case DataItemType.Special:
                  // Return the data template for a special data item
                  return Application.Current.MainWindow.FindResource("SpecialDatatemplate") as DataTemplate;
               default:
                  return null;
            }
         }
         return null;
      }
   }
   /// <summary>
   /// Interaction logic for MainWindow.xaml
   /// </summary>
   public partial class MainWindow : Window
   {
      // The list of data to show in the list box
      public List<DataItem> DataList { set; get; }
      // The constructor of the main window
      public MainWindow()
      {
         // Some test data
         this.DataList = new List<DataItem>();
         this.DataList.Add(new DataItem() { Header = "Item 1", DataType = DataItemType.Normal });
         this.DataList.Add(new DataItem() { Header = "Item 2", DataType = DataItemType.Normal });
         this.DataList.Add(new DataItem() { Header = "Item 3", DataType = DataItemType.Special });
         this.DataList.Add(new DataItem() { Header = "Item 4", DataType = DataItemType.Normal });
         // Initializing the window
         InitializeComponent();
      }
   }
}
</code>```

I hope you get the idea of using the DataTemplateSelector, and then you can style your ListBox and the different types of items in it

Body:
I am writing a project that includes a WPF window that contains a listbox. the listbox is uses binding to a list of tasks (a class I've created). I am trying to have some specific rows of the listbox painted and some specific rows to have colored borders based on the fields of the items in the list. how do i add a paint/brush method for specific rows to a listbox and not the whole listbox?
Below is the XAML properties of the listbox:

<ListBox Name="Tasks" HorizontalAlignment="Left" ItemsSource="{Binding Path=Tasks,Mode=TwoWay}" Height="199" Margin="303,97,0,0" VerticalAlignment="Top" Width="439" RenderTransformOrigin="0.5,0.5">
            <ListBox.RenderTransform>
                <TransformGroup>
                    <ScaleTransform/>
                    <SkewTransform/>
                    <RotateTransform Angle="0.294"/>
                    <TranslateTransform/>
                </TransformGroup>
            </ListBox.RenderTransform>
        </ListBox>

Body:
The ItemsControl has a special feature for selecting templates for items shown in the control. In the following sample I illustrate the use of the DataTemplateSelector

First the XAML. In the Resource  section different data templates are defined for the different types of items you want to show in the ListBox, and there is a reference to the DataTemplateSelector (defined in the C# code later):

<Window x:Class="TestWpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:TestWpfApp"
        mc:Ignorable="d"
        x:Name="DataWindow"
        WindowState="Maximized"
        Title="MainWindow" Height="450" Width="800">
   <Window.Resources>
      <!-- The data template selector -->
      <local:DataItemTemplateSelector x:Key="DataItemTemplateSelector"/>
      <!-- Data template for a normal data item -->
      <DataTemplate x:Key="NormalDatatemplate">
         <Border Width="200"
                 Margin="0"
                 Background="White"
                 BorderThickness="2"
                 Padding="3"
                 BorderBrush="Transparent">
            <TextBlock VerticalAlignment="Center"
                       HorizontalAlignment="Stretch"
                       FontSize="20"
                       Foreground="Black"
                       Background="Transparent"
                       Text="{Binding Path=Header}"/>
         </Border>
      </DataTemplate>
      <!-- Data template for a special data item -->
      <DataTemplate x:Key="SpecialDatatemplate">
         <Border Width="200"
                 Margin="0"
                 Background="Yellow"
                 BorderThickness="2"
                 Padding="3"
                 BorderBrush="Blue">
            <TextBlock VerticalAlignment="Center"
                       HorizontalAlignment="Stretch"
                       FontSize="20"
                       Foreground="Black"
                       Background="Transparent"
                       Text="{Binding Path=Header}"/>
         </Border>
      </DataTemplate>
   </Window.Resources>
   <Grid>
      <ListBox x:Name="DataListBox"
               Margin="50"
               Width="Auto"
               Height="Auto"
               HorizontalAlignment="Center"
               VerticalAlignment="Top"
               ItemsSource="{Binding ElementName=DataWindow, Path=DataList}"
               ItemTemplateSelector="{StaticResource ResourceKey=DataItemTemplateSelector}"/>
   </Grid>
</Window>

And then the C# code, there the DataItemTemplateSelector is defined and the DataList with some testdata:

using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;

namespace TestWpfApp
{
   // Different types of items on the list
   public enum DataItemType
   {
      Normal,
      Special
   }
   // Items on the list
   public class DataItem
   {
      public string Header { set; get; }
      public DataItemType DataType { set; get; }
   }
   // Data template selector for items on the list
   public class DataItemTemplateSelector : DataTemplateSelector
   {
      public override DataTemplate SelectTemplate(object dataItem, DependencyObject container)
      {
         // Check that everyting is OK
         if ((dataItem != null) && (dataItem is DataItem))
         {
            // Switch on the data type
            switch (((DataItem)(dataItem)).DataType)
            {
               case DataItemType.Normal:
                  // Return the data template for a normal data item
                  return Application.Current.MainWindow.FindResource("NormalDatatemplate") as DataTemplate;
               case DataItemType.Special:
                  // Return the data template for a special data item
                  return Application.Current.MainWindow.FindResource("SpecialDatatemplate") as DataTemplate;
               default:
                  return null;
            }
         }
         return null;
      }
   }
   /// <summary>
   /// Interaction logic for MainWindow.xaml
   /// </summary>
   public partial class MainWindow : Window
   {
      // The list of data to show in the list box
      public List<DataItem> DataList { set; get; }
      // The constructor of the main window
      public MainWindow()
      {
         // Some test data
         this.DataList = new List<DataItem>();
         this.DataList.Add(new DataItem() { Header = "Item 1", DataType = DataItemType.Normal });
         this.DataList.Add(new DataItem() { Header = "Item 2", DataType = DataItemType.Normal });
         this.DataList.Add(new DataItem() { Header = "Item 3", DataType = DataItemType.Special });
         this.DataList.Add(new DataItem() { Header = "Item 4", DataType = DataItemType.Normal });
         // Initializing the window
         InitializeComponent();
      }
   }
}

I hope you get the idea of using the DataTemplateSelector, and then you can style your ListBox and the different types of items in it


来源: stackexchange

问:
Woocommerce Email settings, Content type dropdown not working
Not able to update the Woocommerce content type in email settings.

答: This will sound odd, but if you remove the  emoji from the Additional Content area, your content-type changes should save. I have some more details on the problem here if you're curious. </p>

ContentLicense: CC BY-SA 4.0


问:
Why the nested dictionary cannot append into list correctly?
I try to append a dictionary into a list, but I find the sub-dictionary is always keep the last one I read from CSV file(deviceProfile.csv). Does anyone know why?
Here is my CSV file.

```<code>name,description,primaryTable,startingAddress,boolIndex
test_name_1,1,table_1,1,1
test_name_2,2,table_2,2,2
test_name_3,3,table_3,3,3
</code>```

Here is my python code.

```<code>import csv
import yaml
from pprint import pprint

resource = {
    'name': "",
    'description': "",
    'attributes':
      { 'primaryTable': "", 'startingAddress': "", 'boolIndex': "" },
}

resourceArray = []

with open("deviceProfile.csv") as f:
    myCsvDic = csv.DictReader(f)
    for row in myCsvDic:
        resource['name'] = row['name']
        resource['description'] = row['description']
        resource['attributes']['primaryTable'] = row['primaryTable']
        resource['attributes']['startingAddress'] = row['startingAddress']
        resource['attributes']['boolIndex'] = row['boolIndex']
        test = resource.copy()
        resourceArray.append(test)

pprint (resourceArray)
</code>```

And the result is

```<code>[{'attributes': {'boolIndex': '3',
                 'primaryTable': 'table_3',
                 'startingAddress': '3'},
  'description': '1',
  'name': 'test_name_1'},
 {'attributes': {'boolIndex': '3',
                 'primaryTable': 'table_3',
                 'startingAddress': '3'},
  'description': '2',
  'name': 'test_name_2'},
 {'attributes': {'boolIndex': '3',
                 'primaryTable': 'table_3',
                 'startingAddress': '3'},
  'description': '3',
  'name': 'test_name_3'}]
</code>```

It is strange that name and description are appended into list correctly, but attributes. The attributes is always append the last sub-dictionary.

Any help will be appreciated. Thanks.

答:
Why do you have resource on the top outside the loop ???

```<code>resource = {
    'name': "",
    'description': "",
    'attributes':
      { 'primaryTable': "", 'startingAddress': "", 'boolIndex': "" },
}
</code>```

Remove that and just change the loop to this :

```<code>for row in myCsvDic:
    resource = {}
    resource['name'] = row['name']
    resource['description'] = row['description']
    resource['attributes']['primaryTable'] = row['primaryTable']
    resource['attributes']['startingAddress'] = row['startingAddress']
    resource['attributes']['boolIndex'] = row['boolIndex']
    resourceArray.append(resource)
</code>```

Body:
I try to append a dictionary into a list, but I find the sub-dictionary is always keep the last one I read from CSV file(deviceProfile.csv). Does anyone know why?
Here is my CSV file.

name,description,primaryTable,startingAddress,boolIndex
test_name_1,1,table_1,1,1
test_name_2,2,table_2,2,2
test_name_3,3,table_3,3,3

Here is my python code.

import csv
import yaml
from pprint import pprint

resource = {
    'name': "",
    'description': "",
    'attributes':
      { 'primaryTable': "", 'startingAddress': "", 'boolIndex': "" },
}

resourceArray = []

with open("deviceProfile.csv") as f:
    myCsvDic = csv.DictReader(f)
    for row in myCsvDic:
        resource['name'] = row['name']
        resource['description'] = row['description']
        resource['attributes']['primaryTable'] = row['primaryTable']
        resource['attributes']['startingAddress'] = row['startingAddress']
        resource['attributes']['boolIndex'] = row['boolIndex']
        test = resource.copy()
        resourceArray.append(test)

pprint (resourceArray)

And the result is

[{'attributes': {'boolIndex': '3',
                 'primaryTable': 'table_3',
                 'startingAddress': '3'},
  'description': '1',
  'name': 'test_name_1'},
 {'attributes': {'boolIndex': '3',
                 'primaryTable': 'table_3',
                 'startingAddress': '3'},
  'description': '2',
  'name': 'test_name_2'},
 {'attributes': {'boolIndex': '3',
                 'primaryTable': 'table_3',
                 'startingAddress': '3'},
  'description': '3',
  'name': 'test_name_3'}]

It is strange that name and description are appended into list correctly, but attributes. The attributes is always append the last sub-dictionary.

Any help will be appreciated. Thanks.

Body:
Why do you have resource on the top outside the loop ???

resource = {
    'name': "",
    'description': "",
    'attributes':
      { 'primaryTable': "", 'startingAddress': "", 'boolIndex': "" },
}

Remove that and just change the loop to this :

for row in myCsvDic:
    resource = {}
    resource['name'] = row['name']
    resource['description'] = row['description']
    resource['attributes']['primaryTable'] = row['primaryTable']
    resource['attributes']['startingAddress'] = row['startingAddress']
    resource['attributes']['boolIndex'] = row['boolIndex']
    resourceArray.append(resource)


问:
What does it mean by a "pointer points to another memory location"?
I know that a pointer variable stores the memory address of another variable. But what does it mean by "Pointer points to another memory location"? What does it mean by "pointer points to..."?

答:
It points to another memory location exactly the same way a postal address on the postcard you recently received points to your home. A pointer contains the address of a memory location. A postal address contains the address of a physical location - be it a building, an apartment, a post office box... "Points to" thus means "refers to a location of". That's true of both pointers and postal addresses.

It's not true that a pointer must point to another memory location. It's true that the vast majority of pointers in use in real-world software indeed point somewhere else. That is 99.9...% of pointers in existence in the world at any given time, with an additional 15 nines after the decimal point. At the very, very least.

But a pointer can surely point to itself, too. Sometimes it's handy if all you want is to stick a pointer somewhere, and learn where this "somewhere" is. For example, in most C and C++ implementations, the following short program will print the stack address where the pointer variable resided at runtime (yes, the implementations don't have to store that variable on the stack, but in most real-world cases it will be a stack address indeed):

```<code>#include <stdio.h>

int main() {
  void *pointer = &pointer;
  printf("The variable \"%s\" is stored on stack at address %p\n", "pointer", &pointer);
}
</code>```

For example, I got the following output:

```<code>The variable "pointer" is stored on stack at address 0x7fff2350e9f8
</code>```

A pointer may also point to no memory location. A null pointer would be an example of that:

```<code>// Conformant C and C++
int *nullPointer1 = NULL; // Idiomatic C
int *nullPointer2 = 0;
// Conformant C++
int *nullPointer3 = nullptr; // Idiomatic C++
int *nullPointer4 = {}; // Idiomatic C++
std::unique_ptr<int> nullPointer5; // This is really C++ - raw pointers should be used only when truly needed, in library code etc.
</code>```

Such pointers are OK, but the only valid use for them is to check that they are indeed null. They cannot be dereferenced - I mean, yes, you can dereference them, but it's undefined behavior, and modern compilers treat undefined behavior in your code as a license to delete such code. That is, if you dereference a null pointer, and the compiler can prove that it's always the case, the code that does such dereferencing may be removed. Examples (gcc 10.1 x64, -O3):

```<code>int main() {
  int *pointer = 0;
  int b = *pointer;
}

// produces same assembly output as
int main() { return 0; }
</code>```

It gets better. This code:

```<code>int main() {
   int *pointer = 0;
   *pointer = 5;
}
</code>```

when compiled, the 2nd line is modified as if you wrote *pointer = 0, and right after the assignment follows the ub2 "instruction" that triggers the undefined instruction exception. In other words: if you ran this in a process where 0-th memory page was mapped in, it'd fail, even though loading 5 at address 0 would be a valid operation! Instead, it'd load 0 at address 0, and then fail with an exception.

Body:
It points to another memory location exactly the same way a postal address on the postcard you recently received points to your home. A pointer contains the address of a memory location. A postal address contains the address of a physical location - be it a building, an apartment, a post office box... "Points to" thus means "refers to a location of". That's true of both pointers and postal addresses.

It's not true that a pointer must point to another memory location. It's true that the vast majority of pointers in use in real-world software indeed point somewhere else. That is 99.9...% of pointers in existence in the world at any given time, with an additional 15 nines after the decimal point. At the very, very least.

But a pointer can surely point to itself, too. Sometimes it's handy if all you want is to stick a pointer somewhere, and learn where this "somewhere" is. For example, in most C and C++ implementations, the following short program will print the stack address where the pointer variable resided at runtime (yes, the implementations don't have to store that variable on the stack, but in most real-world cases it will be a stack address indeed):

#include <stdio.h>

int main() {
  void *pointer = &pointer;
  printf("The variable \"%s\" is stored on stack at address %p\n", "pointer", &pointer);
}

For example, I got the following output:

The variable "pointer" is stored on stack at address 0x7fff2350e9f8

A pointer may also point to no memory location. A null pointer would be an example of that:

// Conformant C and C++
int *nullPointer1 = NULL; // Idiomatic C
int *nullPointer2 = 0;
// Conformant C++
int *nullPointer3 = nullptr; // Idiomatic C++
int *nullPointer4 = {}; // Idiomatic C++
std::unique_ptr<int> nullPointer5; // This is really C++ - raw pointers should be used only when truly needed, in library code etc.

Such pointers are OK, but the only valid use for them is to check that they are indeed null. They cannot be dereferenced - I mean, yes, you can dereference them, but it's undefined behavior, and modern compilers treat undefined behavior in your code as a license to delete such code. That is, if you dereference a null pointer, and the compiler can prove that it's always the case, the code that does such dereferencing may be removed. Examples (gcc 10.1 x64, -O3):

int main() {
  int *pointer = 0;
  int b = *pointer;
}

// produces same assembly output as
int main() { return 0; }

It gets better. This code:

int main() {
   int *pointer = 0;
   *pointer = 5;
}

when compiled, the 2nd line is modified as if you wrote *pointer = 0, and right after the assignment follows the ub2 "instruction" that triggers the undefined instruction exception. In other words: if you ran this in a process where 0-th memory page was mapped in, it'd fail, even though loading 5 at address 0 would be a valid operation! Instead, it'd load 0 at address 0, and then fail with an exception.


问:
How to get react app to scroll when overflow isn't detected?
I am new to web dev and have started using the create-react-app to start my own website. I'm running into an issue where the content cannot fit on the screen but I cannot seem to get my site to scroll. I've added the following code to the index.css file and the scroll shows up without a scroll bar. I think it's because the site hasn't detected overflow. However, I do not know how to fix this</p>

```<code>html {
  overflow-y: scroll;
  overflow-x: hidden;
}

body {
position: absolute;
}
</code>```

答: The page will only scroll once the height of the html element has exceeded the window height.</p>

Body:
I am new to web dev and have started using the create-react-app to start my own website. I'm running into an issue where the content cannot fit on the screen but I cannot seem to get my site to scroll. I've added the following code to the index.css file and the scroll shows up without a scroll bar. I think it's because the site hasn't detected overflow. However, I do not know how to fix this

html {
  overflow-y: scroll;
  overflow-x: hidden;
}

body {
position: absolute;
}


问:
Draw a circle with rectangles python turtle
I wanna draw (this shape) polygon with knowing rectangle length and width, and number of rectangles,

And Here's my code:

```<code>from turtle import *

color('black')
begin_fill()
length = 50
width = 20
num_of_rectangles = 8
for i in range(num_of_rectangles):
    forward(length)
    right(90)
    forward(width)
    right(90)
    forward(length)
    right(90)
    forward(width)
    right(90)
    penup()
    circle(50, 180/num_of_rectangles, 4)
    pendown()

done()
</code>```

But this code doesn't display the wanted shape, So how can i draw the shape above?

答:
Your rectangles have the right orientation, but the wrong position.  My solution is to have each loop start and end in the centre of the image.    This ensures the rectangles are all at the centre.

from turtle import *

color('black')
begin_fill()
length = 50
width = 20
num_of_rectangles = 8
for i in range(num_of_rectangles):
    # go to corner:
    penup()
    forward(length/2)
    right(90)
    forward(width/2)
    right(90)
    pendown()
    # draw rectangle:
    forward(length)
    right(90)
    forward(width)
    right(90)
    forward(length)
    right(90)
    forward(width)
    right(90)
    penup()
    # go back to centre:
    penup()
    forward(length/2)
    right(90)
    forward(width/2)
    left(90)
    pendown()
    # turn
    right(180/num_of_rectangles)

done()
```

Body:
I wanna draw (this shape) polygon with knowing rectangle length and width, and number of rectangles,

And Here's my code:

from turtle import *

color('black')
begin_fill()
length = 50
width = 20
num_of_rectangles = 8
for i in range(num_of_rectangles):
    forward(length)
    right(90)
    forward(width)
    right(90)
    forward(length)
    right(90)
    forward(width)
    right(90)
    penup()
    circle(50, 180/num_of_rectangles, 4)
    pendown()

done()

But this code doesn't display the wanted shape, So how can i draw the shape above?


问:
Mapping value from alias column into @Entity Class
Is there any possible way to map value from alias column in query for my @Entity Class? For example, for this case there are new columns : first name and last name which is not exist in Transaction Table. Is there any way to map the value into Transaction @Entity Class?

Example entity and dao

@Entity

```<code>import java.sql.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="Transaction")
public class Transaction {
    @Id
    @Column(name="customer_id")
    private String customerId;

    @Column(name="first_name")
    private String firstName;

    @Column(name="last_name")
    private String lastName;
</code>```

@TransactionDAO

```<code>import org.springframework.data.jpa.repository.Query;
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

@Repository
public interface TransactionDao extends PagingAndSortingRepository<Transaction, Long>,  QuerydslPredicateExecutor<Transaction>{
    @Query(value = "SELECT customer_id, SUBSTR (customer_name, 1, 10) as first_name, SUBSTR (customer_name, 11, 20) as last_name FROM Transaction WHERE customer_id=:#{#customerId}", nativeQuery = true)
    public List<Transaction> selectByTransaction(@Param("customerId") String customerId);

}
</code>```

If i use @Column annotation for first_name and last_name, there will be an error because two of that column is not existing in Transaction Table

答:
Yes it's possible to map output of a Query to different model. Answer here is Projection via Interface. You can create interface with field names you want to receive from Query or Repository method. For exaple if you want to receive only firstName and lastName you create Interface like this one below. Other fields will be omitted. Fields in Interface can be diffrent than fields in your @Entity class.

```<code>interface TransactionProjection {
    String getFirstName();
    String getLastName();
}
</code>```

Helpful links:
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections
https://www.baeldung.com/spring-data-jpa-projections

Body:
Is there any possible way to map value from alias column in query for my @Entity Class? For example, for this case there are new columns : first name and last name which is not exist in Transaction Table. Is there any way to map the value into Transaction @Entity Class?

Example entity and dao

@Entity

import java.sql.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="Transaction")
public class Transaction {
    @Id
    @Column(name="customer_id")
    private String customerId;

    @Column(name="first_name")
    private String firstName;

    @Column(name="last_name")
    private String lastName;

@TransactionDAO

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

@Repository
public interface TransactionDao extends PagingAndSortingRepository<Transaction, Long>,  QuerydslPredicateExecutor<Transaction>{
    @Query(value = "SELECT customer_id, SUBSTR (customer_name, 1, 10) as first_name, SUBSTR (customer_name, 11, 20) as last_name FROM Transaction WHERE customer_id=:#{#customerId}", nativeQuery = true)
    public List<Transaction> selectByTransaction(@Param("customerId") String customerId);

}

If i use @Column annotation for first_name and last_name, there will be an error because two of that column is not existing in Transaction Table

Body:
Yes it's possible to map output of a Query to different model. Answer here is Projection via Interface. You can create interface with field names you want to receive from Query or Repository method. For exaple if you want to receive only firstName and lastName you create Interface like this one below. Other fields will be omitted. Fields in Interface can be diffrent than fields in your @Entity class.

interface TransactionProjection {
    String getFirstName();
    String getLastName();
}

Helpful links:
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections
https://www.baeldung.com/spring-data-jpa-projections


问:
Change default font in vuetify
I can't figure out how to change the default font in vuetify. I've been looking for the right variable within ./node_modules/vuetify, but I can't locate it.

I'd ideally not make any changes in the module, but would rather override such variables from outside the module.

答:
Install your font via CDN/npm. Then just override this variable by adding this line in ./src/styles/variables.scss

```<code>//Change default font to 'Inter'
$body-font-family: "Inter" !important;
</code>```

A short and simple approach.

ContentLicense: CC BY-SA 3.0

Title: Change default font in vuetify

Body:
Install your font via CDN/npm. Then just override this variable by adding this line in ./src/styles/variables.scss

//Change default font to 'Inter'
$body-font-family: "Inter" !important;

A short and simple approach.


问:
How does a Launch4J created EXE work with java programs that require external data such as images or sprites, say, in a game?
I'm delving into Launch4J a bit and was wondering if anyone had any experience with something similar to the title. If, say, a Java program was using the LWJGL and was loading sprites and textures etc. and was loaded them appropriately, and was all compiled successfully and exported to a .jar and then to a .exe with Launch4J, would the .exe also need to be in a directory containing all that game data (the folders and such that contained game resources)?</p>

答: Launch4J does nothing except launching a JAR (and possibly embedding it). Access to files works basically exactly the same as it would if you ran your jar with the javaw command. That means: yes, you just have to put the EXE into the same folder in which you'd usually launch the JAR, and it should access those files just fine.</p>


问:
Docker Hub Update Notifications
Are there any good methods/tools to get notifications on updates to containers on Docker Hub? Just to clarify, I don't want to automatically update, just somehow be notified of updates.

I'm currently running a Kubernetes cluster so if I could just specify a list of containers (as opposed to it using the ones on my system) that would be great.

答:
Have you tried docker-notify?  It runs on Node (perhaps imperfect).. but within it's own container.  You'll need a mailserver or a webhook for it to trigger against.

I'm surprised this isn't supported by docker.exe or Docker-hub.. base image changes (eg Alpine) cause a lot of churn with both hub-dependent (Nginx, Postgres) and local dependent containers possibly needing rebuild.

Title: Docker Hub Update Notifications


问:
SQL Server foreign key partitions for two tables
I'm new to databases and I don't understand how partitions work. I tried to understand some examples but I'm still lost. I just need to make a partition of table Persona basing me of idUbicacion, for each different foreign key I need the partition. I'm thank for you help. :)

```<code>CREATE TABLE Ubicacion
(
    numero int identity(1,1) primary key NOT NULL,
    pais varchar(200) NOT NULL
    provincia varchar(200) NOT NULL,
);

CREATE TABLE Persona
(
    id int identity(1,1) primary key NOT NULL,
    nombre varchar(500),
    cedula int,
    nacionalidad varchar(200),
    idUbicacion int foreign key references Ubicacion(id) NOT NULL
);
</code>```

答:
If you are partitioning a table then you need to define a partitioning key which needs to be included in the primary key. For example (this is not the right syntax just a pseudo code):

```<code>CREATE TABLE Ubicacion(
    numero int identity(1,1) NOT NULL,
    pais varchar(200) NOT NULL,
    provincia varchar(200) NOT NULL,
    primary key (numero, provincia)
) PARTITION BY provincia;
</code>```

Then you need to add this extra field to all your foreign keys if possible:

```<code>CREATE TABLE Persona(
    id int identity(1,1) primary key NOT NULL,
    nombre varchar(500),
    cedula int,
    nacionalidad varchar(200),
    provincia varchar(200) NOT NULL,
    idUbicacion int NOT NULL,
    foreign key (idUbicacion, provincia) references Ubicacion(id, provincia)
);
</code>```

Not easy right? So I have 2 recommendation for you:

Don't partition a primary table (dimension table) only a fact table.

If you use partitioning then don't use foreign keys.

Body:
I'm new to databases and I don't understand how partitions work. I tried to understand some examples but I'm still lost. I just need to make a partition of table Persona basing me of idUbicacion, for each different foreign key I need the partition. I'm thank for you help. :)

CREATE TABLE Ubicacion
(
    numero int identity(1,1) primary key NOT NULL,
    pais varchar(200) NOT NULL
    provincia varchar(200) NOT NULL,
);

CREATE TABLE Persona
(
    id int identity(1,1) primary key NOT NULL,
    nombre varchar(500),
    cedula int,
    nacionalidad varchar(200),
    idUbicacion int foreign key references Ubicacion(id) NOT NULL
);

Body:
If you are partitioning a table then you need to define a partitioning key which needs to be included in the primary key. For example (this is not the right syntax just a pseudo code):

CREATE TABLE Ubicacion(
    numero int identity(1,1) NOT NULL,
    pais varchar(200) NOT NULL,
    provincia varchar(200) NOT NULL,
    primary key (numero, provincia)
) PARTITION BY provincia;

Then you need to add this extra field to all your foreign keys if possible:

CREATE TABLE Persona(
    id int identity(1,1) primary key NOT NULL,
    nombre varchar(500),
    cedula int,
    nacionalidad varchar(200),
    provincia varchar(200) NOT NULL,
    idUbicacion int NOT NULL,
    foreign key (idUbicacion, provincia) references Ubicacion(id, provincia)
);

Not easy right? So I have 2 recommendation for you:

Don't partition a primary table (dimension table) only a fact table.

If you use partitioning then don't use foreign keys.


问:
Rendering pandas DataFrame to html on Flask
Can anyone give me some tips or links to investigate how to remedy a df.describe() in a web browser thru a flask app?

For example if I print(df.describe()) in IPython this comes thru in a nice format:

```<code>     kW
count  28219.000000
mean     134.723654
std       46.849081
min       24.300000
25%       91.300000
50%      135.900000
75%      168.600000
max      313.900000
</code>```

But if I attempt this with a render template pass the data as string::

```<code>maxStatsStr = str(df.describe())

resp = make_response(render_template('table.html',
maxStatsStr=maxStatsStr))

return resp
</code>```

To the front end HTML file with Jinja syntax:

```<code><p>{{maxStatsStr}}</p>
</code>```

This shows up in the browser

```<code>kW count 34880.000000 mean 79.687947 std 42.909287 min 12.200000 25% 38.800000 50% 73.400000 75% 113.200000 max 292.800000
</code>```

Would a better method be creating like a table somehow, and using a for loop with Jinja to display the data? On the backend I just dont know how to prepare a df.describe() to be rendered as a table, like this below:

```<code>{% for table in tables %}
            {{ table|safe }}
{% endfor %}
</code>```

FINAL CODE USED

```<code>statsInfoStr = df.describe().to_html()

resp = make_response(render_template('table.html',
maxDateStr=maxDateStr,

tables=[statsInfoStr], titles=df.describe().T))
return resp
</code>```

table.html jinja to loop over data:

```<code>        <h2>Summary Statistics</h2>
        {% for table in tables %}
                    {{ table|safe }}
        {% endfor %}

    </body>
</html>
</code>```

答:
First, you can utilize the pd.DataFrame.to_html method to get the frame converted to html.

You might even use the Styling Guide to pretty it up before converting to html.

Then, you probably want to use the render_template_string function instead.

e.g.:

```<code>def some_flask_func(...):
    # ... your other codes ... #

    # If you just want to get the vanilla structure:
    df_html = df.describe().to_html()

    # or, if you want to use Styler instead:
    df_html = df.describe().style.apply(some_style_func).render()

    # render directly from string:
    resp = make_response(render_template_string(df_html)
    return resp
</code>```

Body:
Can anyone give me some tips or links to investigate how to remedy a df.describe() in a web browser thru a flask app?

For example if I print(df.describe()) in IPython this comes thru in a nice format:

     kW
count  28219.000000
mean     134.723654
std       46.849081
min       24.300000
25%       91.300000
50%      135.900000
75%      168.600000
max      313.900000

But if I attempt this with a render template pass the data as string::

maxStatsStr = str(df.describe())

resp = make_response(render_template('table.html',
maxStatsStr=maxStatsStr))

return resp

To the front end HTML file with Jinja syntax:

{{maxStatsStr}}

This shows up in the browser

kW count 34880.000000 mean 79.687947 std 42.909287 min 12.200000 25% 38.800000 50% 73.400000 75% 113.200000 max 292.800000

Would a better method be creating like a table somehow, and using a for loop with Jinja to display the data? On the backend I just dont know how to prepare a df.describe() to be rendered as a table, like this below:

{% for table in tables %}
            {{ table|safe }}
{% endfor %}

FINAL CODE USED

statsInfoStr = df.describe().to_html()

resp = make_response(render_template('table.html',
maxDateStr=maxDateStr,

tables=[statsInfoStr], titles=df.describe().T))
return resp

table.html jinja to loop over data:

Summary Statistics

        {% for table in tables %}
                    {{ table|safe }}
        {% endfor %}

Body:
First, you can utilize the pd.DataFrame.to_html method to get the frame converted to html.

You might even use the Styling Guide to pretty it up before converting to html.

Then, you probably want to use the render_template_string function instead.

e.g.:

def some_flask_func(...):
    # ... your other codes ... #

    # If you just want to get the vanilla structure:
    df_html = df.describe().to_html()

    # or, if you want to use Styler instead:
    df_html = df.describe().style.apply(some_style_func).render()

    # render directly from string:
    resp = make_response(render_template_string(df_html)
    return resp


问:
RabbitMQ console returned 431
I start rabbitmq on docker with command:

```<code>docker run -d --hostname my-rabbit --name rabbit-fox -p 5672:5672 -p 8090:15672 rabbitmq:3-management
</code>```

it runs fine and i can log into console, but later on Chrome browser i get this:

and can not use then console in the browser.

答:
Clearing browser's cache & memory did the work in my case.

After facing the same issue these steps performed:
I tried to re-run the docker, even I got to the point I re-installed the RabbitMQ server image without any result.

It simply was solved when I cleared the browser's Cache & Memory

Title: RabbitMQ console returned 431

Body:
I start rabbitmq on docker with command:

docker run -d --hostname my-rabbit --name rabbit-fox -p 5672:5672 -p 8090:15672 rabbitmq:3-management

it runs fine and i can log into console, but later on Chrome browser i get this:

and can not use then console in the browser.


问:
Connect to Topic using Function App's MSI
Is it possible to connect to a Service Bus Topic using App Service Function App's MSI? Any documentations or examples to perform this via ARM Template or .NET SDK (C#) would be helpful.</p>

答:
See example below:

namespaces:

```<code>using Microsoft.Azure.ServiceBus;

using Microsoft.Azure.ServiceBus.Primitives;
</code>```

Adding services to the container:

```<code>services.Configure<ServiceBusConfiguration>(Configuration.GetSection("ServiceBus"));
</code>```

Main implementation:

```<code>public class ServiceBusConfiguration
{
    public string Namespace { get; set; }
    public string Topic { get; set; }
}

public class HomeController : Controller
{
    public ServiceBusConfiguration Config { get; }

    public HomeController(IOptions<ServiceBusConfiguration> serviceBusConfig)
    {
       Config = serviceBusConfig.Value;
    }

    [HttpPost]
    public async Task<ActionResult> Send(ServiceBusMessageData messageInfo)
    {
      if (string.IsNullOrEmpty(messageInfo.MessageToSend))
      {
        return RedirectToAction("Index");
      }

      var tokenProvider = TokenProvider.CreateManagedServiceIdentityTokenProvider();
      var sendClient = new TopicClient($"sb://{Config.Namespace}.servicebus.windows.net/", Config.Topic, tokenProvider);
      await sendClient.SendAsync(new Message(Encoding.UTF8.GetBytes(messageInfo.MessageToSend)));
      await sendClient.CloseAsync();

      return RedirectToAction("Index");
   }
}
</code>```

To get more details please see Use Service Bus from App Service with Managed Service Identity

Body:
See example below:

namespaces:

using Microsoft.Azure.ServiceBus;

using Microsoft.Azure.ServiceBus.Primitives;

Adding services to the container:

services.Configure<ServiceBusConfiguration>(Configuration.GetSection("ServiceBus"));

Main implementation:

public class ServiceBusConfiguration
{
    public string Namespace { get; set; }
    public string Topic { get; set; }
}

public class HomeController : Controller
{
    public ServiceBusConfiguration Config { get; }

    public HomeController(IOptions<ServiceBusConfiguration> serviceBusConfig)
    {
       Config = serviceBusConfig.Value;
    }

    [HttpPost]
    public async Task<ActionResult> Send(ServiceBusMessageData messageInfo)
    {
      if (string.IsNullOrEmpty(messageInfo.MessageToSend))
      {
        return RedirectToAction("Index");
      }

      var tokenProvider = TokenProvider.CreateManagedServiceIdentityTokenProvider();
      var sendClient = new TopicClient($"sb://{Config.Namespace}.servicebus.windows.net/", Config.Topic, tokenProvider);
      await sendClient.SendAsync(new Message(Encoding.UTF8.GetBytes(messageInfo.MessageToSend)));
      await sendClient.CloseAsync();

      return RedirectToAction("Index");
   }
}

To get more details please see Use Service Bus from App Service with Managed Service Identity


问:
print icon obtained from db - laravel
I want to put together a menu and get an icon dynamically.

the result i want is something like this:

Database table:

code:

    Categoryes
    Stores All

      @foreach($tipos as $tipo)

        {{$tipo->icono }}

tipo)}}">{{$tipo->tipo }}

      @endforeach

```

but it prints the label not the icon

What should I do to show my icons?

答:
I dont know the template engine you are using, but it seems to escape the html chars. maybe it just works by removing the double brackets ("{$tipo->icono}" instead of "{{$tipo->icono }}").

But for app-design reasons: i'd suggest to store just the type (or class) in the database. not an html-tag. meaning: the column "icono" should just contain f.e. "glass-martini" - instead of a complete html-tag. put the html-stuff in your template and add the class from your column there.

Title: print icon obtained from db - laravel

Body:
I want to put together a menu and get an icon dynamically.

the result i want is something like this:

Database table:

code:

    Categoryes
    Stores All

      @foreach($tipos as $tipo)

        {{$tipo->icono }}

tipo)}}">{{$tipo->tipo }}

      @endforeach

but it prints the label not the icon

What should I do to show my icons?


问:
WCF - Inspect the messages being sent/received?
I have 2 solutions:
 - Server Solution
 - Client Solution

The server registers itself to my localhost IIS: http://localhost/MyApp/

The client adds WCF Services (Service References) from the localhost application: http://localhost/MyApp/MyService.svc

When I'm running the client I want to be able to see the messages being passed back and forth. I downloaded Fiddler, but it doesn't seem to want to show me any traffic being sent unless I actually use a web browser. Am I using Fiddler wrong or is there another tool I should be using for this?

To clarify, what I'm looking to do is to see the actual messages being passed in. I don't want to do anything with them except see them visually with my own eyes.

I like the WCF Service Log Utility, but I don't think I have the correct setting on there. I can't see the actual soap message, just that a message was received.

And also to clarify further, I don't care what tool I use as long as I can easily see the messages themselves.

答: Is your service SOAP or RESTful? You can use the WCF Service Trace Viewer Tool to view the SOAP message headers and bodies. Instructions for configuring your web service for tracing are here.</p>


问:
How to enable PyCharm autocompletion for imported library (Discord.py)
How do I enable method autocompletion for discord.py in PyCharm? Until now I've been doing it the hard way by looking at the documentation and I didn't even know that autocomplete for a library existed. So how do I enable it?</p>

答:
Code completion (intellisense) can be found from the settings menu:

Ctrl + alt + s to bring up the settings

Click on the dropdown for Editor -> General, and then select Code Completion

And here you're able to enable and customise the settings as you wish.

Try selecting File -> Invalidate caches / Restart... if it doesn't work.

If that still doesn't work, go into your settings, Project Structure, direct yourself to the discord folder and mark it as a source:


问:
How do I loop through columns in R?
I am trying to clean up my code for cleaning missing data. I have a dataset with 6 columns and the code works if I were to do them individually like this:

```<code>mammographic_masses <- mammographic_masses %>%
  mutate(birad = replace(birad, birad== "na", NA)) %>%
  mutate(birad = replace(birad, birad== "N/A", NA))
</code>```

But when I try to do it in a for loop like this:

```<code>for (i in ncol(mammographic_masses)){
  print(class(mammographic_masses[[i]]))
  mammographic_masses <- mammographic_masses %>%
    mutate(mammographic_masses[[,i]] = replace(mammographic_masses[[,i]], mammographic_masses[[,i]] == "na", NA)) %>%
    mutate(mammographic_masses[[,i]] = replace(mammographic_masses[[,i]], mammographic_masses[[,i]] == "N/A", NA))
}
</code>```

I get an error:

```<code>Error: unexpected '=' in:
"  mammographic_masses <- mammographic_masses %>%
    mutate(mammographic_masses[[,i]] ="
>     mutate(mammographic_masses[[,i]] = replace(mammographic_masses[[,i]], mammographic_masses[[,i]] == "N/A", NA))
Error: unexpected '=' in "    mutate(mammographic_masses[[,i]] ="
> }
Error: unexpected '}' in "}"
</code>```

I also was reading up on other ways such as apply etc. but i cant figure a way to loop it per column

答:
We can also use na_if

```<code>library(dplyr)
mammographic_masses %>%
     mutate(across(everything(), ~ na_if(na_if(., "na"), "N/A")))
</code>```

data

```<code>set.seed(2020)
n <- 10
mammographic_masses <- replicate(4, sample(c(letters[1:4], "na", "N/A"), n, TRUE))
mammographic_masses <- as.data.frame(mammographic_masses)
</code>```

Title: How do I loop through columns in R?

Body:
I am trying to clean up my code for cleaning missing data. I have a dataset with 6 columns and the code works if I were to do them individually like this:

mammographic_masses <- mammographic_masses %>%
  mutate(birad = replace(birad, birad== "na", NA)) %>%
  mutate(birad = replace(birad, birad== "N/A", NA))

But when I try to do it in a for loop like this:

for (i in ncol(mammographic_masses)){
  print(class(mammographic_masses[[i]]))
  mammographic_masses <- mammographic_masses %>%
    mutate(mammographic_masses[[,i]] = replace(mammographic_masses[[,i]], mammographic_masses[[,i]] == "na", NA)) %>%
    mutate(mammographic_masses[[,i]] = replace(mammographic_masses[[,i]], mammographic_masses[[,i]] == "N/A", NA))
}

I get an error:

Error: unexpected '=' in:
"  mammographic_masses <- mammographic_masses %>%
    mutate(mammographic_masses[[,i]] ="
>     mutate(mammographic_masses[[,i]] = replace(mammographic_masses[[,i]], mammographic_masses[[,i]] == "N/A", NA))
Error: unexpected '=' in "    mutate(mammographic_masses[[,i]] ="
> }
Error: unexpected '}' in "}"

I also was reading up on other ways such as apply etc. but i cant figure a way to loop it per column

Body:
We can also use na_if

library(dplyr)
mammographic_masses %>%
     mutate(across(everything(), ~ na_if(na_if(., "na"), "N/A")))

data

set.seed(2020)
n <- 10
mammographic_masses <- replicate(4, sample(c(letters[1:4], "na", "N/A"), n, TRUE))
mammographic_masses <- as.data.frame(mammographic_masses)


问:
compiling Promises with babel and core-js causes infinite window reload
I want to run the following piece of code on IE11

```<code>let myPromise = Promise.resolve(123);
myPromise.then((value) => {
console.log(value);
});
</code>```

My recipe is Rollup and babel (& core-js for polyfilling) with the following .babelrc configuration:

```<code>{
    "presets": [
        ["@babel/preset-env", {
            "useBuiltIns": "usage",
            "corejs": 3,
            "targets": {
                "browsers": ["last 2 versions", "ie >= 11"]
            }
        }]
     ]
}
</code>```

When I try to load the code, I get some infinite loop. The browser's tab seems to reload every couple of milliseconds.

答:
I just wanted you to know that your question/issue in core-js (https://github.com/zloirock/core-js/issues/627) was really helpful and solved the problem for me, which was exactly the same as yours there and here.

So I wanted to leave here the solution provided there by Denis Pushkarev - as I did find this topic first and it may help other developers to quick get an answer:

You could change options to format: 'iife' to make it work.

Body:
I want to run the following piece of code on IE11

let myPromise = Promise.resolve(123);
myPromise.then((value) => {
console.log(value);
});

My recipe is Rollup and babel (& core-js for polyfilling) with the following .babelrc configuration:

{
    "presets": [
        ["@babel/preset-env", {
            "useBuiltIns": "usage",
            "corejs": 3,
            "targets": {
                "browsers": ["last 2 versions", "ie >= 11"]
            }
        }]
     ]
}

When I try to load the code, I get some infinite loop. The browser's tab seems to reload every couple of milliseconds.


问:
Android Studio: Group elements together
I am fairly new to android studio and I am trying to make a car rental app for a university project.

I designed an app which has a horizontal slider containing blocks of different cars however I am unsure on how I would do this, I understand how the slider works and how to add elements to it.

I have a linear layout within the horizontal slider which will contain all of the blocks but I am unsure how to make a block of elements. Within the block it should have two buttons, an image and some text. Here is a picture of the design.

As you can see the available blocks are surrounded by a square. this is what I want, a small container which surrounds my data. Sort of like a div box in html.

Is there a way to do this?
Please just point me in the correct direction!
Many thanks!

答:
It seems like cardviews can handle most of the grouping you want to do. I would reccomend looking into them because they incorporate a lot of material design components right out of the box.
https://developer.android.com/guide/topics/ui/layout/cardview</p>

Title: Android Studio: Group elements together


问:
Subtract and Sum Operations On Columns
I have an output like this:

```<code>Volume               c1                     c2
--------------------------------------------------
0                   1000                     0
1-20                 100                    10
20+                   50                    40
</code>```

I get this output by this:

```<code>SELECT
case when volume=0 then '0' when volume <21 then '1-20' when volume>=21 then '21+' as Volume,
sum(ab) as c1,
sum(xy) as c2
FROM
table t
GROUP BY
case when volume=0 then '0' when volume <21 then '1-20' when volume>=21 then '21+'
</code>```

However, I need to get the output just like below. I am trying to subtract sum of c1 column from sum of c2 column and result must be placed at first row under c2 column just like this:

```<code>Volume                c1                  c2
--------------------------------------------------
0                   1000                **1100**
1-20                 100                  10
20+                   50                  40
</code>```

How can I do this?

Thanks in advance.

答:
I would simply do:

```<code>SELECT (case when volume = 0 then '0' when volume < 21 then '1-20' when volume>=21 then '21+' end) as Volume,
       sum(ab) as c1,
       (case when volume = 0
             then sum(sum(ab)) over () - sum(sum(xy))
             else sum(xy)
       end) as c2
FROM  table t
GROUP BY (case when volume=0 then '0' when volume <21 then '1-20' when volume>=21 then '21+' end);
</code>```

Subqueries and CTEs are unnecessary when you can simply use window functions.

Title: Subtract and Sum Operations On Columns

Body:
I have an output like this:

Volume               c1                     c2
--------------------------------------------------
0                   1000                     0
1-20                 100                    10
20+                   50                    40

I get this output by this:

SELECT
case when volume=0 then '0' when volume <21 then '1-20' when volume>=21 then '21+' as Volume,
sum(ab) as c1,
sum(xy) as c2
FROM
table t
GROUP BY
case when volume=0 then '0' when volume <21 then '1-20' when volume>=21 then '21+'

However, I need to get the output just like below. I am trying to subtract sum of c1 column from sum of c2 column and result must be placed at first row under c2 column just like this:

Volume                c1                  c2
--------------------------------------------------
0                   1000                **1100**
1-20                 100                  10
20+                   50                  40

How can I do this?

Thanks in advance.

Body:
I would simply do:

SELECT (case when volume = 0 then '0' when volume < 21 then '1-20' when volume>=21 then '21+' end) as Volume,
       sum(ab) as c1,
       (case when volume = 0
             then sum(sum(ab)) over () - sum(sum(xy))
             else sum(xy)
       end) as c2
FROM  table t
GROUP BY (case when volume=0 then '0' when volume <21 then '1-20' when volume>=21 then '21+' end);

Subqueries and CTEs are unnecessary when you can simply use window functions.


问:
In Azure Logic Apps, How to make a HTTP Get/Post Call with NTLM Authentication?
I am trying to make a HTTP (Get/Post) call in Azure Logic Apps ?
The called service is on-premise (it's in fact a webservice) and it supports NTLM Authentication.

I can reach the service via postman (enabling NTLM Authentication).
Does Azure Logic Apps support it ?
if not, What are the alternatives..

Thanks
Prabath

答: Logic app doesn't support NTLM authentication</p>


问:
C# Multithreading - wait for method to finish before running it again
I have a method that looks like this:

```<code>while(intVariable < 4))
        {
            DoSomeStuff();

            if (intVariable == 3)
            {
                FinalDecide();
            }

            if (rollCounter < 3)
            {
                Decide(args);
            }
            intVariable++;
        }
</code>```

The method Decide() runs 32 Threads and I want to make sure that before loop starts Decide() second time, the first time finishes

Inside Decide I have something like this:

```<code>for (int i = 0; i < 32; i++)
        {
            Thread t = new Thread(new ParameterizedThreadStart(Prepare));
            t.IsBackground = true;
            t.Start(i);
        }

        runner = new System.Threading.Thread(WaitforThreads);
        runner.IsBackground = true;
        runner.Start();
</code>```

Even though I wait for those 32 threads to complete inside this run of Decide method, the code continues and fires Decide method second time before the first one finishes which causes bugs

How do I make sure that method Decide finishes WaitforThreads() method before it starts second time?

答:
One way to achieve this is making the Decide method return Thread[] of the started threads and saving this to a variable accessible from the while loop and then just join all threads before calling Decide next time:

Thread[] decideThreads = null;
while(intVariable < 4))
        {
            DoSomeStuff();

            if (intVariable == 3)
            {
                FinalDecide();
            }

            if (rollCounter < 3)
            {
                if (decideThreads != null)
                {
                    foreach (var t in decideThreads)
                        t.Join();
                }
                decideThreads = Decide(args);
            }
            intVariable++;
        }
```

<p>Even better, you could replace the threads with <code>Task<T></code> as was suggested in comments and then just return a <code>Task.WhenAll</code> instead of <code>Thread[]</code>. You could then use <code>async</code> to make the code more efficient:</p>

<pre class="lang-cs prettyprint-override"><code>Task decideTask = null;
while(intVariable < 4))
        {
            DoSomeStuff();

            if (intVariable == 3)
            {
                FinalDecide();
            }

            if (rollCounter < 3)
            {
                if (decideTask != null)
                    await decideTask;

                decideTask = Decide(args);
            }
            intVariable++;
        }
</code>```

Decide would then do something like:

Task[] workers = new Task[32];
for (int i = 0; i < 32; i++)
        {
            var localI = i; // to be captured in lambda
            workers[i] = new Task(() => Prepare(localI));
        }

return Task.WhenAll(workers);

```

Body:
I have a method that looks like this:

while(intVariable < 4))
        {
            DoSomeStuff();

            if (intVariable == 3)
            {
                FinalDecide();
            }

            if (rollCounter < 3)
            {
                Decide(args);
            }
            intVariable++;
        }

The method Decide() runs 32 Threads and I want to make sure that before loop starts Decide() second time, the first time finishes

Inside Decide I have something like this:

for (int i = 0; i < 32; i++)
        {
            Thread t = new Thread(new ParameterizedThreadStart(Prepare));
            t.IsBackground = true;
            t.Start(i);
        }

        runner = new System.Threading.Thread(WaitforThreads);
        runner.IsBackground = true;
        runner.Start();

Even though I wait for those 32 threads to complete inside this run of Decide method, the code continues and fires Decide method second time before the first one finishes which causes bugs

How do I make sure that method Decide finishes WaitforThreads() method before it starts second time?

Body:
One way to achieve this is making the Decide method return Thread[] of the started threads and saving this to a variable accessible from the while loop and then just join all threads before calling Decide next time:

Thread[] decideThreads = null;
while(intVariable < 4))
        {
            DoSomeStuff();

            if (intVariable == 3)
            {
                FinalDecide();
            }

            if (rollCounter < 3)
            {
                if (decideThreads != null)
                {
                    foreach (var t in decideThreads)
                        t.Join();
                }
                decideThreads = Decide(args);
            }
            intVariable++;
        }

Even better, you could replace the threads with Task<T> as was suggested in comments and then just return a Task.WhenAll instead of Thread[]. You could then use async to make the code more efficient:

Task decideTask = null;
while(intVariable < 4))
        {
            DoSomeStuff();

            if (intVariable == 3)
            {
                FinalDecide();
            }

            if (rollCounter < 3)
            {
                if (decideTask != null)
                    await decideTask;

                decideTask = Decide(args);
            }
            intVariable++;
        }

Decide would then do something like:

Task[] workers = new Task[32];
for (int i = 0; i < 32; i++)
        {
            var localI = i; // to be captured in lambda
            workers[i] = new Task(() => Prepare(localI));
        }

return Task.WhenAll(workers);


问:
How to merge all the content of a branch to another branch?
I'm new to the world of git, and also to Atlassian and SourceTree, so I've very basic about this.
What I want achieve is that:

Suppose that I've a branch called master, which I develop my application with all new features and bugfix, and another branch called release, what I want to do is merge all the content of the master branch, to ther release branch.

What I did so far:

Selected the master branch on the branches view on the left of SourceTree

Clicked on the join button on the header of SourceTree and then on Ok.

Clicked on the Send button on the header of SourceTree.

After the step 3, nothing happen, in my BitBucket repository I doesn't see any Release branch, I've actually created this branch on SourceTree only. Someone could tell me what am I doing wrong?

Thanks.

答:
Follow this step-by-step process:

MERGE ONE BRANCH INTO ANOTHER

```<code>Branch B is new branch and we want want branch A code in B
</code>```

Select A take pull to stay updated.

Select B select merge, merge from log.

select A from first column in pop down select latest commit.

commit merge immediately f no conflicts check box selected, select Ok

Resolved xcproject conflicts in editor. >> <<

You have A changes in B

Body:
Follow this step-by-step process:

MERGE ONE BRANCH INTO ANOTHER

Branch B is new branch and we want want branch A code in B

Select A take pull to stay updated.

Select B select merge, merge from log.

select A from first column in pop down select latest commit.

commit merge immediately f no conflicts check box selected, select Ok

Resolved xcproject conflicts in editor. >> <<

You have A changes in B


问:
Sequelize with koa2 can't limit the record. How can I do?

async function selectCards ({
  status,
  teamId,
  userId,
  GMTTime,
  cardId,
  page,
  pageSize
}) {
  console.log(page, pageSize)
  const teamWhere = {}
  if (teamId) {
    teamWhere.id = teamId
  }
  const cardWhere = {}
  if (GMTTime) {
    cardWhere.startAt = {
      [Op.lt]: GMTTime
    }
  }
  if (cardId) {
    cardWhere.id = cardId
  }
  const userCardWhere = {
    userId
  }
  if (status) {
    userCardWhere.status = status
  }
  const result = await User.findOne({
    where: {
      id: userId
    },
    attributes: [],
    include: {
      model: Card,
      where: cardWhere,
      through: {
        where: userCardWhere
      },
      include: {
        model: Team,
        where: teamWhere,
        include: UserTeam
      }

      limit: pageSize // while it cause an error
    }
  })
  if (result == null) return { rows: [] }
  result.cards.map(card => {
    card.dataValues.status = card.user_card.status
    delete card.dataValues.user_card
    card.dataValues.team.dataValues.isAdmin = card.team.user_teams[0].isAdmin
    delete card.dataValues.team.dataValues.user_teams
    return card
  })
  return result
}
```

<p>When i try to add limit as above
An error has occurred</p>

```Only HasMany associations support include.separate Error: Only HasMany associations support include.separate
```

<p>while one card will have many users and one user may have many cards
it's a 'm:n' association</p>

<p>and when i try to use</p>

<pre class="lang-js prettyprint-override"><code>order: [['startAt', 'desc']]
</code>```

it also doesn't work

so i need to limit it by more code

  result.cards.sort((card1, card2) => (
    card2.startAt - card1.startAt
  ))
  const ret = result.cards.slice((page - 1) * pageSize, page * pageSize)
  return { rows: ret }
```

<p>it's not a good choice to use more code because when data is too huge, it will need O(nlogn) to do
can i have some solution just through sequelize?</p>

<p>by the way, it's the model association below</p>

<pre class="lang-js prettyprint-override"><code>Team.hasMany(Card, {
  onDelete: 'CASCADE'
})
Card.hasOne(User, {
  onDelete: 'CASCADE',
  foreignKey: 'publishId'
})
Card.belongsTo(Team, {
  onDelete: 'CASCADE'
})

Card.belongsToMany(User, { through: UserCard })
User.belongsToMany(Card, { through: UserCard })
User.hasMany(UserCard)
UserCard.belongsTo(User)
Card.hasMany(UserCard)
UserCard.belongsTo(Card)
</code>```

答:
You can't use limit on parent records with many-to-many association included (especially with where in this include). This comes from SQL. If you join a parent and a child tables and then add limit that way you'll get first N mixed parent-child records and not first N parent records with all child records. Yes you can try a plain SQL query and you'll get a desired result but Sequelize cannot build such query for you.
However you can try to get parent records with subqueries for filtering them by existence of some child records with certain conditions using sequelize.literal (and a SQL subquery like (EXISTS (SELECT 1 FROM CHILD_TABLE WHERE PARENT_ID=PARENT_TABLE.ID)). In that case you cannot get this child records in the same query but you can use limit properly. Afterwards you can get all child records separately by using a list of parent records' ids.

Body:
async function selectCards ({
  status,
  teamId,
  userId,
  GMTTime,
  cardId,
  page,
  pageSize
}) {
  console.log(page, pageSize)
  const teamWhere = {}
  if (teamId) {
    teamWhere.id = teamId
  }
  const cardWhere = {}
  if (GMTTime) {
    cardWhere.startAt = {
      [Op.lt]: GMTTime
    }
  }
  if (cardId) {
    cardWhere.id = cardId
  }
  const userCardWhere = {
    userId
  }
  if (status) {
    userCardWhere.status = status
  }
  const result = await User.findOne({
    where: {
      id: userId
    },
    attributes: [],
    include: {
      model: Card,
      where: cardWhere,
      through: {
        where: userCardWhere
      },
      include: {
        model: Team,
        where: teamWhere,
        include: UserTeam
      }

      limit: pageSize // while it cause an error
    }
  })
  if (result == null) return { rows: [] }
  result.cards.map(card => {
    card.dataValues.status = card.user_card.status
    delete card.dataValues.user_card
    card.dataValues.team.dataValues.isAdmin = card.team.user_teams[0].isAdmin
    delete card.dataValues.team.dataValues.user_teams
    return card
  })
  return result
}

When i try to add limit as above
An error has occurred

Only HasMany associations support include.separate Error: Only HasMany associations support include.separate

while one card will have many users and one user may have many cards
it's a 'm:n' association

and when i try to use

order: [['startAt', 'desc']]

it also doesn't work

so i need to limit it by more code

  result.cards.sort((card1, card2) => (
    card2.startAt - card1.startAt
  ))
  const ret = result.cards.slice((page - 1) * pageSize, page * pageSize)
  return { rows: ret }

it's not a good choice to use more code because when data is too huge, it will need O(nlogn) to do
can i have some solution just through sequelize?

by the way, it's the model association below

Team.hasMany(Card, {
  onDelete: 'CASCADE'
})
Card.hasOne(User, {
  onDelete: 'CASCADE',
  foreignKey: 'publishId'
})
Card.belongsTo(Team, {
  onDelete: 'CASCADE'
})

Card.belongsToMany(User, { through: UserCard })
User.belongsToMany(Card, { through: UserCard })
User.hasMany(UserCard)
UserCard.belongsTo(User)
Card.hasMany(UserCard)
UserCard.belongsTo(Card)


问:
How to make a debounce function act independently on different instances of the same component on Vue.js?
I have two Vue components that have a "save to disk" call on every change of data, it is loaded into these components via a mixin and each component save into a different file, so they must function independently (only trigger a debounce reset on its own change of data). To prevent too much writing to the disk. Here's my debound function:

```<code>function debounce(fn, delay) {
  var timeoutID = null;
  return function () {
    console.log("clearing " + timeoutID)
    clearTimeout(timeoutID);
    var args = arguments;
    var that = this;
    timeoutID = setTimeout(() => fn.apply(that, args), delay);
  };
}
</code>```

Here's the methods on my mixin that the components inherit:

```<code>  methods: {
    saveData: debounce(function(){
        console.log('saving widget: ' + this.$parent.widget.id);
        this.saver.store = this.persisted;
    }, 5000),
  },
</code>```

It works well when I'm changing data on one or the other component, but when I change data on one and before debounce ends I change on the other, it cancels my debounce function from the first one, and only saves the second component data.

What am I missing here?

答:
That's because each component instance shares the same debounced function, only the context (this, that) is varying.

A simple workaround would be to change your debounce implementation to

function debounce(fn, delay) {
  var thatUidToTimeoutID = {};
  return function () {
    var args = arguments;
    var that = this;
    clearTimeout(thatUidToTimeoutID[that._uid]);
    thatUidToTimeoutID[that._uid] = setTimeout(() => fn.apply(that, args), delay);
  };
}
```

_uid is holding an unique id of each component, it's more of an internal property (hence it's weird key) but it should be good enough.

Body:
I have two Vue components that have a "save to disk" call on every change of data, it is loaded into these components via a mixin and each component save into a different file, so they must function independently (only trigger a debounce reset on its own change of data). To prevent too much writing to the disk. Here's my debound function:

function debounce(fn, delay) {
  var timeoutID = null;
  return function () {
    console.log("clearing " + timeoutID)
    clearTimeout(timeoutID);
    var args = arguments;
    var that = this;
    timeoutID = setTimeout(() => fn.apply(that, args), delay);
  };
}

Here's the methods on my mixin that the components inherit:

  methods: {
    saveData: debounce(function(){
        console.log('saving widget: ' + this.$parent.widget.id);
        this.saver.store = this.persisted;
    }, 5000),
  },

It works well when I'm changing data on one or the other component, but when I change data on one and before debounce ends I change on the other, it cancels my debounce function from the first one, and only saves the second component data.

What am I missing here?

Body:
That's because each component instance shares the same debounced function, only the context (this, that) is varying.

A simple workaround would be to change your debounce implementation to

function debounce(fn, delay) {
  var thatUidToTimeoutID = {};
  return function () {
    var args = arguments;
    var that = this;
    clearTimeout(thatUidToTimeoutID[that._uid]);
    thatUidToTimeoutID[that._uid] = setTimeout(() => fn.apply(that, args), delay);
  };
}

_uid is holding an unique id of each component, it's more of an internal property (hence it's weird key) but it should be good enough.


问:
function "scale_fill_fermenter" not working
I am trying to run the following example code of function scale_fill_fermenter() from the ggplot2 reference.

```<code>#install.packages("ggplot2")
library(ggplot2)
v <- ggplot(faithfuld) + geom_tile(aes(waiting, eruptions, fill = density))
v + scale_fill_fermenter()
</code>```

But I got an error message: Error in scale_fill_fermenter() could not find function "scale_fill_fermenter()".

It's so strange since this is an example from the manual. Has anyone encountered the same problem? How did you solve it?

edit:

RStudio Version 1.2.5033

R version 3.6.2 (2019-12-12)

packageVersion("ggplot2")
[1] ‘3.3.0.9000’

答:
I solved the same problem by upgrading ggplot2. The latest version as I answer now is 3.3.1.

Simply run install.packages("ggplot2") and restart the R environment.

Body:
I am trying to run the following example code of function scale_fill_fermenter() from the ggplot2 reference.

#install.packages("ggplot2")
library(ggplot2)
v <- ggplot(faithfuld) + geom_tile(aes(waiting, eruptions, fill = density))
v + scale_fill_fermenter()

But I got an error message: Error in scale_fill_fermenter() could not find function "scale_fill_fermenter()".

It's so strange since this is an example from the manual. Has anyone encountered the same problem? How did you solve it?

edit:

RStudio Version 1.2.5033

R version 3.6.2 (2019-12-12)

packageVersion("ggplot2")
[1] ‘3.3.0.9000’


问:
Is there an example of how to create a dotnet core 3 console app that authenticates with IdentityServer4?
Is there a way to create a dotnet core 3/3.1 console application that authenticates with my IdentityServer4 using Open ID Connect? There is an old example in IdentityModel.OidcClient called NetCoreConsoleClient, but it requires ASP.Net Core.

The model that I'm looking for is that a user attempts to use the console app, the console app pops open a browser window and initiates an Open ID Connect session with IdentityServer4, the user enters username/password in the browser window, control returns to the console app which now has the necessary tokens to talk to a protected API server. In Microsoft's azure command line tools, they offload authentication to something that seems like OpenID connect. I'm looking to do something similar.

Is ASP.Net Core somehow required for that flow? I don't see why it would be.

Is this the Authorization Code grant type, and if so, how are the tokens passed back to the console app without using a callback URL? We don't want to have to have an open public IP port necessary just to run a console app.

答:
Here are a couple of examples that use IdentityModel libraries and demonstrate techniques you need. If coding in .Net I would recommend their libraries - they have versions for both .Net Core and the older .Net Framework:

Loopback Web Server Example

Private URI Schemes Example

In both cases you use Authorization Code Flow (PKCE) and tokens are passed back to the app slightly differently. The console app will receive an authorization code when login completes and can then swap the code for tokens.

LOOPBACK

During logins the console app temporarily listens for the login response on an address such as http://localhost:8000, which does not require administrator rights.

PRIVATE URI SCHEMES

During installation your scheme, such as x-mycompany-myconsoleapp, is registered as a per user setting. The app receives the login response via an operating system notification to a scheme based URL.

FURTHER INFO

Out of interest, the OAuth flow options for console apps are the same as for desktop apps. Some blog posts of mine may give you an idea of Open Id connect messages and other related behaviour:

Loopback Code Sample + Blog Posts

Private URI Scheme Code Sample + Blog Posts


问:
jQuery ,Css display none - block vs. hide- show
I am trying to hide #showMyList, #showMyName these divs. On click button need to show divs.
Both div has separate buttons. I want to see one div at a time. I can give different css (style)to them so that they will look different.

Which one will be more useful jQuery hide() and show()
Or display none and block?

```<code>#showMyList, #showMyName{
            height: 100px;
            width: 500px;
            text-align: center;
            border: 1px solid gray;
            background-color: antiquewhite;
            position: absolute;
            top: 200px;
            left:200px;
        }
    </style>
    <script>
        $('document').ready(function(){
           $('showMyList').css("display", "none");
            $('showMyAcc').css("display","none");
            $("myList").click(function(){
                $("showMyList").css("display", "block");
                $("myAcc").click(function(){
                  $("showMyAcc").css("display", "block");
                });
            });
        });
</code>```

答:
Consider the following example.

$(function() {
  $('#showMyList, #showMyAcc').hide();
  $("#myList").click(function() {
    $("#showMyAcc").hide();
    $("#showMyList").show();
  });
  $("#myAcc").click(function() {
    $("#showMyList").hide();
    $("#showMyAcc").show();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#showMyList,
#showMyAcc {
  height: 100px;
  width: 500px;
  text-align: center;
  border: 1px solid gray;
  background-color: antiquewhite;
  position: absolute;
  top: 200px;
  left: 200px;
}</code>```

<button id="myList">Show List</button>
<button id="myAcc">Show Name</button>

List

Name
```

You can Hide both elements and then reveal or show 1 at a time.

Body:
I am trying to hide #showMyList, #showMyName these divs. On click button need to show divs.
Both div has separate buttons. I want to see one div at a time. I can give different css (style)to them so that they will look different.

Which one will be more useful jQuery hide() and show()
Or display none and block?

#showMyList, #showMyName{
            height: 100px;
            width: 500px;
            text-align: center;
            border: 1px solid gray;
            background-color: antiquewhite;
            position: absolute;
            top: 200px;
            left:200px;
        }
    </style>

Body:
Consider the following example.

$(function() {
  $('#showMyList, #showMyAcc').hide();
  $("#myList").click(function() {
    $("#showMyAcc").hide();
    $("#showMyList").show();
  });
  $("#myAcc").click(function() {
    $("#showMyList").hide();
    $("#showMyAcc").show();
  });
});

#showMyList,
#showMyAcc {
  height: 100px;
  width: 500px;
  text-align: center;
  border: 1px solid gray;
  background-color: antiquewhite;
  position: absolute;
  top: 200px;
  left: 200px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="myList">Show List</button>
<button id="myAcc">Show Name</button>
<div id="showMyList">List</div>
<div id="showMyAcc">Name</div>

You can Hide both elements and then reveal or show 1 at a time.


问:
Java 8: Formatting lambda with newlines and indentation
What I would like to achieve with lambda indentation is the following:

Multi-line statement:

```<code>String[] ppl = new String[] { "Karen (F)", "Kevin (M)", "Lee (M)", "Joan (F)", "Des (M)", "Rick (M)" };
List<String> strings = Arrays.stream(ppl)
                         .filter(
                             (x) ->
                             {
                                 return x.contains("(M)");
                             }
                         ).collect(Collectors.toList());
strings.stream().forEach(System.out::println);
</code>```

Single-line statement:

```<code>List<String> strings = Arrays.stream(ppl)
                         .map((x) -> x.toUpperCase())
                         .filter((x) -> x.contains("(M)"))
                         .collect(Collectors.toList());
</code>```

Currently, Eclipse is auto-formatting to the following:

Multi-line statement:

```<code>String[] ppl = new String[] { "Karen (F)", "Kevin (M)", "Lee (M)", "Joan (F)", "Des (M)", "Rick (M)" };
List<String> strings = Arrays.stream(ppl).filter((x) ->
{
    return x.contains("(M)");
}).collect(Collectors.toList());
strings.stream().forEach(System.out::println);
</code>```

Single-line statement:

```<code>String[] ppl = new String[] { "Karen (F)", "Kevin (M)", "Lee (M)", "Joan (F)", "Des(M)", "Rick (M)" };
List<String> strings = Arrays.stream(ppl).map((x) -> x.toUpperCase())
        .filter((x) -> x.contains("(M)")).collect(Collectors.toList());
strings.stream().forEach(System.out::println);
</code>```

And I find this really messy, because of how the collect call is directly underneath the return and there's no space inbetween at all. I would prefer it if I could start the lambda in a new line indented, and so that the .filter( call would be right above the .collect( call. However, the only thing that can be customized with standard Java-8 Eclipse Formatter is the brace at the start of the lambda body, but nothing for the () brackets beforehand, nor the indentation.

And in the case of single-line calls, it just uses the basic line-wrap and makes it be a chained mess. I don't think I need to explain why this is hard to decrypt afterwards.

Is there any way to somehow customize the formatting more and achieve the first formatting type in Eclipse? (Or, optionally, in another IDE like IntelliJ IDEA.)

EDIT: The closest I could get was with IntelliJ IDEA 13 Community Edition (read: free edition :P) which was the following (defined by continuous indentation which in this case is 8):

```<code>public static void main(String[] args)
{
    int[] x = new int[] {1, 2, 3, 4, 5, 6, 7};
    int sum = Arrays.stream(x)
            .map((n) -> n * 5)
            .filter((n) -> {
                System.out.println("Filtering: " + n);
                return n % 3 != 0;
            })
            .reduce(0, Integer::sum);

    List<Integer> list = Arrays.stream(x)
            .filter((n) -> n % 2 == 0)
            .map((n) -> n * 4)
            .boxed()
            .collect(Collectors.toList());
    list.forEach(System.out::println);
    System.out.println(sum);
</code>```

It also allows to "align" the chained method invocation like this:

```<code>    int sum = Arrays.stream(x)
                    .map((n) -> n * 5)
                    .filter((n) -> {
                        System.out.println("Filtering: " + n);
                        return n % 3 != 0;
                    })
                    .reduce(0, Integer::sum);

    List<Integer> list = Arrays.stream(x)
                               .filter((n) -> n % 2 == 0)
                               .map((n) -> n * 4)
                               .boxed()
                               .collect(Collectors.toList());
    list.forEach(System.out::println);
    System.out.println(sum);
}
</code>```

I personally find that while it makes more sense, the second version pushes it far too away, so I prefer the first one.

The setup responsible for the first setup is the following:

```<code><?xml version="1.0" encoding="UTF-8"?>
<code_scheme name="Zhuinden">
  <option name="JD_ALIGN_PARAM_COMMENTS" value="false" />
  <option name="JD_ALIGN_EXCEPTION_COMMENTS" value="false" />
  <option name="JD_ADD_BLANK_AFTER_PARM_COMMENTS" value="true" />
  <option name="JD_ADD_BLANK_AFTER_RETURN" value="true" />
  <option name="JD_P_AT_EMPTY_LINES" value="false" />
  <option name="JD_PARAM_DESCRIPTION_ON_NEW_LINE" value="true" />
  <option name="WRAP_COMMENTS" value="true" />
  <codeStyleSettings language="JAVA">
    <option name="KEEP_FIRST_COLUMN_COMMENT" value="false" />
    <option name="BRACE_STYLE" value="2" />
    <option name="CLASS_BRACE_STYLE" value="2" />
    <option name="METHOD_BRACE_STYLE" value="2" />
    <option name="ELSE_ON_NEW_LINE" value="true" />
    <option name="WHILE_ON_NEW_LINE" value="true" />
    <option name="CATCH_ON_NEW_LINE" value="true" />
    <option name="FINALLY_ON_NEW_LINE" value="true" />
    <option name="ALIGN_MULTILINE_PARAMETERS" value="false" />
    <option name="SPACE_WITHIN_BRACES" value="true" />
    <option name="SPACE_BEFORE_IF_PARENTHESES" value="false" />
    <option name="SPACE_BEFORE_WHILE_PARENTHESES" value="false" />
    <option name="SPACE_BEFORE_FOR_PARENTHESES" value="false" />
    <option name="SPACE_BEFORE_TRY_PARENTHESES" value="false" />
    <option name="SPACE_BEFORE_CATCH_PARENTHESES" value="false" />
    <option name="SPACE_BEFORE_SWITCH_PARENTHESES" value="false" />
    <option name="SPACE_BEFORE_SYNCHRONIZED_PARENTHESES" value="false" />
    <option name="SPACE_BEFORE_ARRAY_INITIALIZER_LBRACE" value="true" />
    <option name="METHOD_PARAMETERS_WRAP" value="1" />
    <option name="EXTENDS_LIST_WRAP" value="1" />
    <option name="THROWS_LIST_WRAP" value="1" />
    <option name="EXTENDS_KEYWORD_WRAP" value="1" />
    <option name="THROWS_KEYWORD_WRAP" value="1" />
    <option name="METHOD_CALL_CHAIN_WRAP" value="2" />
    <option name="BINARY_OPERATION_WRAP" value="1" />
    <option name="BINARY_OPERATION_SIGN_ON_NEXT_LINE" value="true" />
    <option name="ASSIGNMENT_WRAP" value="1" />
    <option name="IF_BRACE_FORCE" value="3" />
    <option name="DOWHILE_BRACE_FORCE" value="3" />
    <option name="WHILE_BRACE_FORCE" value="3" />
    <option name="FOR_BRACE_FORCE" value="3" />
    <option name="PARAMETER_ANNOTATION_WRAP" value="1" />
    <option name="VARIABLE_ANNOTATION_WRAP" value="1" />
    <option name="ENUM_CONSTANTS_WRAP" value="2" />
  </codeStyleSettings>
</code_scheme>
</code>```

I tried to make sure everything is reasonable, but I might have messed something up, so it might need minor adjustments.

If you're Hungarian like me and you're using a Hungarian layout, then this keymap might be of use to you, so that you don't end up not being able to use AltGR+F, AltGR+G, AltGR+B, AltGR+N and AltGR+M (which correspond to Ctrl+Alt).

```<code><?xml version="1.0" encoding="UTF-8"?>
<keymap version="1" name="Default copy" parent="$default">
  <action id="ExtractMethod">
    <keyboard-shortcut first-keystroke="shift control M" />
  </action>
  <action id="GotoImplementation">
    <mouse-shortcut keystroke="control alt button1" />
  </action>
  <action id="GotoLine">
    <keyboard-shortcut first-keystroke="shift control G" />
  </action>
  <action id="Inline">
    <keyboard-shortcut first-keystroke="shift control O" />
  </action>
  <action id="IntroduceField">
    <keyboard-shortcut first-keystroke="shift control D" />
  </action>
  <action id="Mvc.RunTarget">
    <keyboard-shortcut first-keystroke="shift control P" />
  </action>
  <action id="StructuralSearchPlugin.StructuralReplaceAction" />
  <action id="Synchronize">
    <keyboard-shortcut first-keystroke="shift control Y" />
  </action>
</keymap>
</code>```

While IntelliJ doesn't seem to provide a way to put the opening brace of the lambda in a new line, otherwise it's a fairly reasonable way of formatting, so I'll mark this as accepted.

答: The option that worked for me was ticking the Never join already wrapped lines option in the Line Wrapping section of the Formatter in Preferences.

Body:
What I would like to achieve with lambda indentation is the following:

Multi-line statement:

String[] ppl = new String[] { "Karen (F)", "Kevin (M)", "Lee (M)", "Joan (F)", "Des (M)", "Rick (M)" };
List<String> strings = Arrays.stream(ppl)
                         .filter(
                             (x) ->
                             {
                                 return x.contains("(M)");
                             }
                         ).collect(Collectors.toList());
strings.stream().forEach(System.out::println);

Single-line statement:

List<String> strings = Arrays.stream(ppl)
                         .map((x) -> x.toUpperCase())
                         .filter((x) -> x.contains("(M)"))
                         .collect(Collectors.toList());

Currently, Eclipse is auto-formatting to the following:

Multi-line statement:

String[] ppl = new String[] { "Karen (F)", "Kevin (M)", "Lee (M)", "Joan (F)", "Des (M)", "Rick (M)" };
List<String> strings = Arrays.stream(ppl).filter((x) ->
{
    return x.contains("(M)");
}).collect(Collectors.toList());
strings.stream().forEach(System.out::println);

Single-line statement:

String[] ppl = new String[] { "Karen (F)", "Kevin (M)", "Lee (M)", "Joan (F)", "Des(M)", "Rick (M)" };
List<String> strings = Arrays.stream(ppl).map((x) -> x.toUpperCase())
        .filter((x) -> x.contains("(M)")).collect(Collectors.toList());
strings.stream().forEach(System.out::println);

And I find this really messy, because of how the collect call is directly underneath the return and there's no space inbetween at all. I would prefer it if I could start the lambda in a new line indented, and so that the .filter( call would be right above the .collect( call. However, the only thing that can be customized with standard Java-8 Eclipse Formatter is the brace at the start of the lambda body, but nothing for the () brackets beforehand, nor the indentation.

And in the case of single-line calls, it just uses the basic line-wrap and makes it be a chained mess. I don't think I need to explain why this is hard to decrypt afterwards.

Is there any way to somehow customize the formatting more and achieve the first formatting type in Eclipse? (Or, optionally, in another IDE like IntelliJ IDEA.)

EDIT: The closest I could get was with IntelliJ IDEA 13 Community Edition (read: free edition :P) which was the following (defined by continuous indentation which in this case is 8):

public static void main(String[] args)
{
    int[] x = new int[] {1, 2, 3, 4, 5, 6, 7};
    int sum = Arrays.stream(x)
            .map((n) -> n * 5)
            .filter((n) -> {
                System.out.println("Filtering: " + n);
                return n % 3 != 0;
            })
            .reduce(0, Integer::sum);

    List<Integer> list = Arrays.stream(x)
            .filter((n) -> n % 2 == 0)
            .map((n) -> n * 4)
            .boxed()
            .collect(Collectors.toList());
    list.forEach(System.out::println);
    System.out.println(sum);

It also allows to "align" the chained method invocation like this:

    int sum = Arrays.stream(x)
                    .map((n) -> n * 5)
                    .filter((n) -> {
                        System.out.println("Filtering: " + n);
                        return n % 3 != 0;
                    })
                    .reduce(0, Integer::sum);

    List<Integer> list = Arrays.stream(x)
                               .filter((n) -> n % 2 == 0)
                               .map((n) -> n * 4)
                               .boxed()
                               .collect(Collectors.toList());
    list.forEach(System.out::println);
    System.out.println(sum);
}

I personally find that while it makes more sense, the second version pushes it far too away, so I prefer the first one.

The setup responsible for the first setup is the following:

<?xml version="1.0" encoding="UTF-8"?>
<code_scheme name="Zhuinden">
  <option name="JD_ALIGN_PARAM_COMMENTS" value="false" />
  <option name="JD_ALIGN_EXCEPTION_COMMENTS" value="false" />
  <option name="JD_ADD_BLANK_AFTER_PARM_COMMENTS" value="true" />
  <option name="JD_ADD_BLANK_AFTER_RETURN" value="true" />
  <option name="JD_P_AT_EMPTY_LINES" value="false" />
  <option name="JD_PARAM_DESCRIPTION_ON_NEW_LINE" value="true" />
  <option name="WRAP_COMMENTS" value="true" />
  <codeStyleSettings language="JAVA">
    <option name="KEEP_FIRST_COLUMN_COMMENT" value="false" />
    <option name="BRACE_STYLE" value="2" />
    <option name="CLASS_BRACE_STYLE" value="2" />
    <option name="METHOD_BRACE_STYLE" value="2" />
    <option name="ELSE_ON_NEW_LINE" value="true" />
    <option name="WHILE_ON_NEW_LINE" value="true" />
    <option name="CATCH_ON_NEW_LINE" value="true" />
    <option name="FINALLY_ON_NEW_LINE" value="true" />
    <option name="ALIGN_MULTILINE_PARAMETERS" value="false" />
    <option name="SPACE_WITHIN_BRACES" value="true" />
    <option name="SPACE_BEFORE_IF_PARENTHESES" value="false" />
    <option name="SPACE_BEFORE_WHILE_PARENTHESES" value="false" />
    <option name="SPACE_BEFORE_FOR_PARENTHESES" value="false" />
    <option name="SPACE_BEFORE_TRY_PARENTHESES" value="false" />
    <option name="SPACE_BEFORE_CATCH_PARENTHESES" value="false" />
    <option name="SPACE_BEFORE_SWITCH_PARENTHESES" value="false" />
    <option name="SPACE_BEFORE_SYNCHRONIZED_PARENTHESES" value="false" />
    <option name="SPACE_BEFORE_ARRAY_INITIALIZER_LBRACE" value="true" />
    <option name="METHOD_PARAMETERS_WRAP" value="1" />
    <option name="EXTENDS_LIST_WRAP" value="1" />
    <option name="THROWS_LIST_WRAP" value="1" />
    <option name="EXTENDS_KEYWORD_WRAP" value="1" />
    <option name="THROWS_KEYWORD_WRAP" value="1" />
    <option name="METHOD_CALL_CHAIN_WRAP" value="2" />
    <option name="BINARY_OPERATION_WRAP" value="1" />
    <option name="BINARY_OPERATION_SIGN_ON_NEXT_LINE" value="true" />
    <option name="ASSIGNMENT_WRAP" value="1" />
    <option name="IF_BRACE_FORCE" value="3" />
    <option name="DOWHILE_BRACE_FORCE" value="3" />
    <option name="WHILE_BRACE_FORCE" value="3" />
    <option name="FOR_BRACE_FORCE" value="3" />
    <option name="PARAMETER_ANNOTATION_WRAP" value="1" />
    <option name="VARIABLE_ANNOTATION_WRAP" value="1" />
    <option name="ENUM_CONSTANTS_WRAP" value="2" />
  </codeStyleSettings>
</code_scheme>

I tried to make sure everything is reasonable, but I might have messed something up, so it might need minor adjustments.

If you're Hungarian like me and you're using a Hungarian layout, then this keymap might be of use to you, so that you don't end up not being able to use AltGR+F, AltGR+G, AltGR+B, AltGR+N and AltGR+M (which correspond to Ctrl+Alt).

<?xml version="1.0" encoding="UTF-8"?>
<keymap version="1" name="Default copy" parent="$default">
  <action id="ExtractMethod">
    <keyboard-shortcut first-keystroke="shift control M" />
  </action>
  <action id="GotoImplementation">
    <mouse-shortcut keystroke="control alt button1" />
  </action>
  <action id="GotoLine">
    <keyboard-shortcut first-keystroke="shift control G" />
  </action>
  <action id="Inline">
    <keyboard-shortcut first-keystroke="shift control O" />
  </action>
  <action id="IntroduceField">
    <keyboard-shortcut first-keystroke="shift control D" />
  </action>
  <action id="Mvc.RunTarget">
    <keyboard-shortcut first-keystroke="shift control P" />
  </action>
  <action id="StructuralSearchPlugin.StructuralReplaceAction" />
  <action id="Synchronize">
    <keyboard-shortcut first-keystroke="shift control Y" />
  </action>
</keymap>

While IntelliJ doesn't seem to provide a way to put the opening brace of the lambda in a new line, otherwise it's a fairly reasonable way of formatting, so I'll mark this as accepted.


问:
python-pptx: control text outline color and width
In python-pptx, is it possible to set/change the text's outline color and width?

Manually you would select the textbox or highlight the text and select "Text Options" then select "Solid line" and then you can choose your color and change the width. See image below where I have changed the outline color to red and width to 3pt.

答: I don't think you're going to like this answer: It's in the category of "examine the XML and confect it directly".</p>